summaryrefslogtreecommitdiffstats
path: root/jdisc_http_service/src/main/java/com/yahoo/jdisc/http/server/jetty/ServletOutputStreamWriter.java
blob: 271805765c284893e4c43ea43fd5b94a7063a310 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.server.jetty;

import com.yahoo.jdisc.handler.CompletionHandler;

import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author tonytv
 */
public class ServletOutputStreamWriter {
    /** Rules:
     * 1) Don't modify the output stream without isReady returning true (write/flush/close).
     *    Multiple modification calls without interleaving isReady calls are not allowed.
     * 2) If isReady returned false, no other calls should be made until the write listener is invoked.
     * 3) If the write listener sees isReady == false, it must not do any modifications before its next invocation.
     */


    private enum State {
        NOT_STARTED,
        WAITING_FOR_WRITE_POSSIBLE_CALLBACK,
        WAITING_FOR_BUFFER,
        WRITING_BUFFERS,
        FINISHED_OR_ERROR
    }

    private static final Logger log = Logger.getLogger(ServletOutputStreamWriter.class.getName());

    private static final ByteBuffer CLOSE_STREAM_BUFFER = ByteBuffer.allocate(0);

    private final Object monitor = new Object();

    @GuardedBy("monitor")
    private State state = State.NOT_STARTED;

    @GuardedBy("state")
    private final ServletOutputStream outputStream;
    private final Executor executor;

    @GuardedBy("monitor")
    private final Deque<ResponseContentPart> responseContentQueue = new ArrayDeque<>();

    private final MetricReporter metricReporter;

    /**
     * When this future completes there will be no more calls against the servlet output stream or servlet response.
     * The framework is still allowed to invoke us though.
     *
     * The future might complete in the servlet framework thread, user thread or executor thread.
     */
    final CompletableFuture<Void> finishedFuture = new CompletableFuture<>();


    public ServletOutputStreamWriter(ServletOutputStream outputStream, Executor executor, MetricReporter metricReporter) {
        this.outputStream = outputStream;
        this.executor = executor;
        this.metricReporter = metricReporter;
    }

    public void setSendingError() {
        synchronized (monitor) {
            assertStateIs(state, State.NOT_STARTED);
            state = State.FINISHED_OR_ERROR;
        }
    }

    public void writeBuffer(ByteBuffer buf, CompletionHandler handler) {
        boolean thisThreadShouldWrite = false;

        synchronized (monitor) {
            if (state == State.FINISHED_OR_ERROR) {
                if (handler != null) {
                    executor.execute(() ->  handler.failed(new IllegalStateException("ContentChannel already closed.")));
                }
                return;
            }

            responseContentQueue.addLast(new ResponseContentPart(buf, handler));
            switch (state) {
                case NOT_STARTED:
                    state = State.WAITING_FOR_WRITE_POSSIBLE_CALLBACK;
                    outputStream.setWriteListener(writeListener);
                    break;
                case WAITING_FOR_WRITE_POSSIBLE_CALLBACK:
                case WRITING_BUFFERS:
                    break;
                case WAITING_FOR_BUFFER:
                    thisThreadShouldWrite = true;
                    state = State.WRITING_BUFFERS;
                    break;
                default:
                    throw new IllegalStateException("Invalid state " + state);
            }
        }

        if (thisThreadShouldWrite) {
            writeBuffersInQueueToOutputStream();
        }
    }

    public void close(CompletionHandler handler) {
        writeBuffer(CLOSE_STREAM_BUFFER, handler);
    }

    private void writeBuffersInQueueToOutputStream() {
        boolean lastOperationWasFlush = false;

        while (true) {
            ResponseContentPart contentPart;

            synchronized (monitor) {
                if (state == State.FINISHED_OR_ERROR) {
                    return;
                }

                assertStateIs(state, State.WRITING_BUFFERS);

                if (!outputStream.isReady()) {
                    state = State.WAITING_FOR_WRITE_POSSIBLE_CALLBACK;
                    return;
                }

                contentPart = responseContentQueue.pollFirst();

                if (contentPart == null && lastOperationWasFlush) {
                    state = State.WAITING_FOR_BUFFER;
                    return;
                }
            }

            try {
                boolean isFlush = contentPart == null;
                if (isFlush) {
                    outputStream.flush();
                    lastOperationWasFlush = true;
                    continue;
                }
                lastOperationWasFlush = false;

                if (contentPart.buf == CLOSE_STREAM_BUFFER) {
                    closeOutputStream(contentPart.handler);
                    setFinished(Optional.empty());
                } else {
                    writeBufferToOutputStream(contentPart);
                }
            } catch (Throwable e) {
                setFinished(Optional.of(e));
            }
        }
    }

    private void setFinished(Optional<Throwable> e) {
        synchronized (monitor) {
            state = State.FINISHED_OR_ERROR;
            if (!responseContentQueue.isEmpty()) {
                failAllParts_holdingLock(e.orElse(new IllegalStateException("ContentChannel closed.")));
            }
        }

        assert !Thread.holdsLock(monitor);
        if (e.isPresent()) {
            finishedFuture.completeExceptionally(e.get());
        } else {
            finishedFuture.complete(null);
        }
    }

    private void failAllParts_holdingLock(Throwable e) {
        assert Thread.holdsLock(monitor);

        ArrayList<ResponseContentPart> failedParts = new ArrayList<>(responseContentQueue);
        responseContentQueue.clear();

        @SuppressWarnings("ThrowableInstanceNeverThrown")
        RuntimeException failReason = new RuntimeException("Failing due to earlier ServletOutputStream write failure", e);

        Consumer<ResponseContentPart> failCompletionHandler = responseContentPart ->
                runCompletionHandler_logOnExceptions(
                        () -> responseContentPart.handler.failed(failReason));

        executor.execute(
                () -> failedParts.forEach(failCompletionHandler));
    }

    private void closeOutputStream(CompletionHandler handler) throws Exception {
        callCompletionHandlerWhenDone(handler, () -> {
            outputStream.close();
            return null;
        });
    }

    private void writeBufferToOutputStream(ResponseContentPart contentPart) throws Throwable {
        callCompletionHandlerWhenDone(contentPart.handler, () -> {
            ByteBuffer buffer = contentPart.buf;
            final int bytesToSend = buffer.remaining();
            try {
                if (buffer.hasArray()) {
                    outputStream.write(buffer.array(), buffer.arrayOffset(), buffer.remaining());
                } else {
                    final byte[] array = new byte[buffer.remaining()];
                    buffer.get(array);
                    outputStream.write(array);
                }
                metricReporter.successfulWrite(bytesToSend);
            } catch (Throwable throwable) {
                metricReporter.failedWrite();
                throw throwable;
            }

            return null;
        });
    }

    //Using Callable<Void> instead of Runnable since Callable supports throwing exceptions.
    private void callCompletionHandlerWhenDone(CompletionHandler handler, Callable<Void> callable) throws Exception {
        try {
            callable.call();
        } catch (Throwable e) {
            assert !Thread.holdsLock(monitor);
            runCompletionHandler_logOnExceptions(
                    () -> handler.failed(e));
            throw e;
        }

        assert !Thread.holdsLock(monitor);
        handler.completed(); //Might throw an exception, handling in the enclosing scope.
    }

    private void runCompletionHandler_logOnExceptions(Runnable runnable) {
        assert !Thread.holdsLock(monitor);
        try {
            runnable.run();
        } catch (Throwable e) {
            log.log(Level.WARNING, "Unexpected exception from CompletionHandler.", e);
        }
    }

    private void assertStateIs(State currentState, State expectedState) {
        if (currentState != expectedState) {
            AssertionError error = new AssertionError("Expected state " + expectedState + ", got state " + currentState);
            log.log(Level.WARNING, "Assertion failed.", error);
            throw error;
        }
    }

    public void fail(Throwable t) {
        setFinished(Optional.of(t));
    }

    private final WriteListener writeListener = new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
            synchronized (monitor) {
                if (state == State.FINISHED_OR_ERROR) {
                    return;
                }

                assertStateIs(state, State.WAITING_FOR_WRITE_POSSIBLE_CALLBACK);
                state = State.WRITING_BUFFERS;
            }

            writeBuffersInQueueToOutputStream();
        }

        @Override
        public void onError(Throwable t) {
            setFinished(Optional.of(t));
        }
    };

}