-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
AbstractListenerWriteProcessor.java
495 lines (433 loc) · 14.5 KB
/
AbstractListenerWriteProcessor.java
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server.reactive;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.reactivestreams.Processor;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.springframework.core.log.LogDelegateFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Abstract base class for {@code Processor} implementations that bridge between
* event-listener write APIs and Reactive Streams.
*
* <p>Specifically a base class for writing to the HTTP response body with
* Servlet non-blocking I/O and Undertow XNIO as well for writing WebSocket
* messages through the Jakarta WebSocket API (JSR-356), Jetty, and Undertow.
*
* @author Arjen Poutsma
* @author Violeta Georgieva
* @author Rossen Stoyanchev
* @since 5.0
* @param <T> the type of element signaled to the {@link Subscriber}
*/
public abstract class AbstractListenerWriteProcessor<T> implements Processor<T, Void> {
/**
* Special logger for debugging Reactive Streams signals.
* @see LogDelegateFactory#getHiddenLog(Class)
* @see AbstractListenerReadPublisher#rsReadLogger
* @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger
* @see WriteResultPublisher#rsWriteResultLogger
*/
protected static final Log rsWriteLogger = LogDelegateFactory.getHiddenLog(AbstractListenerWriteProcessor.class);
private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
@Nullable
private Subscription subscription;
@Nullable
private volatile T currentData;
/* Indicates "onComplete" was received during the (last) write. */
private volatile boolean sourceCompleted;
/**
* Indicates we're waiting for one last isReady-onWritePossible cycle
* after "onComplete" because some Servlet containers expect this to take
* place prior to calling AsyncContext.complete().
* See https://github.com/eclipse-ee4j/servlet-api/issues/273
*/
private volatile boolean readyToCompleteAfterLastWrite;
private final WriteResultPublisher resultPublisher;
private final String logPrefix;
public AbstractListenerWriteProcessor() {
this("");
}
/**
* Create an instance with the given log prefix.
* @since 5.1
*/
public AbstractListenerWriteProcessor(String logPrefix) {
// AbstractListenerFlushProcessor calls cancelAndSetCompleted directly, so this cancel task
// won't be used for HTTP responses, but it can be for a WebSocket session.
this.resultPublisher = new WriteResultPublisher(logPrefix + "[WP] ", this::cancelAndSetCompleted);
this.logPrefix = (StringUtils.hasText(logPrefix) ? logPrefix : "");
}
/**
* Get the configured log prefix.
* @since 5.1
*/
public String getLogPrefix() {
return this.logPrefix;
}
// Subscriber methods and async I/O notification methods...
@Override
public final void onSubscribe(Subscription subscription) {
this.state.get().onSubscribe(this, subscription);
}
@Override
public final void onNext(T data) {
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "onNext: " + data.getClass().getSimpleName());
}
this.state.get().onNext(this, data);
}
/**
* Error signal from the upstream, write Publisher. This is also used by
* subclasses to delegate error notifications from the container.
*/
@Override
public final void onError(Throwable ex) {
State state = this.state.get();
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "onError: " + ex + " [" + state + "]");
}
state.onError(this, ex);
}
/**
* Completion signal from the upstream, write Publisher. This is also used
* by subclasses to delegate completion notifications from the container.
*/
@Override
public final void onComplete() {
State state = this.state.get();
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "onComplete [" + state + "]");
}
state.onComplete(this);
}
/**
* Invoked when writing is possible, either in the same thread after a check
* via {@link #isWritePossible()}, or as a callback from the underlying
* container.
*/
public final void onWritePossible() {
State state = this.state.get();
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "onWritePossible [" + state + "]");
}
state.onWritePossible(this);
}
/**
* Cancel the upstream "write" Publisher only, for example due to
* Servlet container error/completion notifications. This should usually
* be followed up with a call to either {@link #onError(Throwable)} or
* {@link #onComplete()} to notify the downstream chain, that is unless
* cancellation came from downstream.
*/
public void cancel() {
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "cancel [" + this.state + "]");
}
if (this.subscription != null) {
this.subscription.cancel();
}
}
/**
* Cancel the "write" Publisher and transition to COMPLETED immediately also
* without notifying the downstream. For use when cancellation came from
* downstream.
*/
void cancelAndSetCompleted() {
cancel();
for (;;) {
State prev = this.state.get();
if (prev == State.COMPLETED) {
break;
}
if (this.state.compareAndSet(prev, State.COMPLETED)) {
if (rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + prev + " -> " + this.state);
}
if (prev != State.WRITING) {
discardCurrentData();
}
break;
}
}
}
// Publisher implementation for result notifications...
@Override
public final void subscribe(Subscriber<? super Void> subscriber) {
this.resultPublisher.subscribe(subscriber);
}
// Write API methods to be implemented or template methods to override...
/**
* Whether the given data item has any content to write.
* If false the item is not written.
*/
protected abstract boolean isDataEmpty(T data);
/**
* Template method invoked after a data item to write is received via
* {@link Subscriber#onNext(Object)}. The default implementation saves the
* data item for writing once that is possible.
*/
protected void dataReceived(T data) {
T prev = this.currentData;
if (prev != null) {
// This shouldn't happen:
// 1. dataReceived can only be called from REQUESTED state
// 2. currentData is cleared before requesting
discardData(data);
cancel();
onError(new IllegalStateException("Received new data while current not processed yet."));
}
this.currentData = data;
}
/**
* Whether writing is possible.
*/
protected abstract boolean isWritePossible();
/**
* Write the given item.
* <p><strong>Note:</strong> Sub-classes are responsible for releasing any
* data buffer associated with the item, once fully written, if pooled
* buffers apply to the underlying container.
* @param data the item to write
* @return {@code true} if the current data item was written completely and
* a new item requested, or {@code false} if it was written partially and
* we'll need more write callbacks before it is fully written
*/
protected abstract boolean write(T data) throws IOException;
/**
* Invoked after the current data has been written and before requesting
* the next item from the upstream, write Publisher.
* <p>The default implementation is a no-op.
* @deprecated originally introduced for Undertow to stop write notifications
* when no data is available, but deprecated as of 5.0.6 since constant
* switching on every requested item causes a significant slowdown.
*/
@Deprecated
protected void writingPaused() {
}
/**
* Invoked after onComplete or onError notification.
* <p>The default implementation is a no-op.
*/
protected void writingComplete() {
}
/**
* Invoked when an I/O error occurs during a write. Subclasses may choose
* to ignore this if they know the underlying API will provide an error
* notification in a container thread.
* <p>Defaults to no-op.
*/
protected void writingFailed(Throwable ex) {
}
/**
* Invoked after any error (either from the upstream write Publisher, or
* from I/O operations to the underlying server) and cancellation
* to discard in-flight data that was in
* the process of being written when the error took place.
* @param data the data to be released
* @since 5.0.11
*/
protected abstract void discardData(T data);
// Private methods for use from State's...
private boolean changeState(State oldState, State newState) {
boolean result = this.state.compareAndSet(oldState, newState);
if (result && rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + oldState + " -> " + newState);
}
return result;
}
private void changeStateToReceived(State oldState) {
if (changeState(oldState, State.RECEIVED)) {
writeIfPossible();
}
}
private void changeStateToComplete(State oldState) {
if (changeState(oldState, State.COMPLETED)) {
discardCurrentData();
writingComplete();
this.resultPublisher.publishComplete();
}
else {
this.state.get().onComplete(this);
}
}
private void writeIfPossible() {
boolean result = isWritePossible();
if (!result && rsWriteLogger.isTraceEnabled()) {
rsWriteLogger.trace(getLogPrefix() + "isWritePossible false");
}
if (result) {
onWritePossible();
}
}
private void discardCurrentData() {
T data = this.currentData;
this.currentData = null;
if (data != null) {
discardData(data);
}
}
/**
* Represents a state for the {@link Processor} to be in.
*
* <p><pre>
* UNSUBSCRIBED
* |
* v
* +--- REQUESTED -------------> RECEIVED ---+
* | ^ ^ |
* | | | |
* | + ------ WRITING <------+ |
* | | |
* | v |
* +--------------> COMPLETED <--------------+
* </pre>
*/
private enum State {
UNSUBSCRIBED {
@Override
public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) {
Assert.notNull(subscription, "Subscription must not be null");
if (processor.changeState(this, REQUESTED)) {
processor.subscription = subscription;
subscription.request(1);
}
else {
super.onSubscribe(processor, subscription);
}
}
@Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
// This can happen on (very early) completion notification from container..
processor.changeStateToComplete(this);
}
},
REQUESTED {
@Override
public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) {
if (processor.isDataEmpty(data)) {
Assert.state(processor.subscription != null, "No subscription");
processor.subscription.request(1);
}
else {
processor.dataReceived(data);
processor.changeStateToReceived(this);
}
}
@Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
processor.readyToCompleteAfterLastWrite = true;
processor.changeStateToReceived(this);
}
},
RECEIVED {
@SuppressWarnings("deprecation")
@Override
public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) {
if (processor.readyToCompleteAfterLastWrite) {
processor.changeStateToComplete(RECEIVED);
}
else if (processor.changeState(this, WRITING)) {
T data = processor.currentData;
Assert.state(data != null, "No data");
try {
if (processor.write(data)) {
if (processor.changeState(WRITING, REQUESTED)) {
processor.currentData = null;
if (processor.sourceCompleted) {
processor.readyToCompleteAfterLastWrite = true;
processor.changeStateToReceived(REQUESTED);
}
else {
processor.writingPaused();
Assert.state(processor.subscription != null, "No subscription");
processor.subscription.request(1);
}
}
}
else {
processor.changeStateToReceived(WRITING);
}
}
catch (IOException ex) {
processor.writingFailed(ex);
}
}
}
@Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
processor.sourceCompleted = true;
// A competing write might have completed very quickly
if (processor.state.get() == State.REQUESTED) {
processor.changeStateToComplete(State.REQUESTED);
}
}
},
WRITING {
@Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
processor.sourceCompleted = true;
// A competing write might have completed very quickly
if (processor.state.get() == State.REQUESTED) {
processor.changeStateToComplete(State.REQUESTED);
}
}
},
COMPLETED {
@Override
public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) {
// ignore
}
@Override
public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) {
// ignore
}
@Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
// ignore
}
};
public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) {
subscription.cancel();
}
public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) {
processor.discardData(data);
processor.cancel();
processor.onError(new IllegalStateException("Illegal onNext without demand"));
}
public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) {
if (processor.changeState(this, COMPLETED)) {
processor.discardCurrentData();
processor.writingComplete();
processor.resultPublisher.publishError(ex);
}
else {
processor.state.get().onError(processor, ex);
}
}
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
throw new IllegalStateException(toString());
}
public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) {
// ignore
}
}
}