/
HttpOperations.java
504 lines (437 loc) · 13.5 KB
/
HttpOperations.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
496
497
498
499
500
501
502
503
/*
* Copyright (c) 2011-2022 VMware, Inc. or its affiliates, All Rights Reserved.
*
* 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 reactor.netty.http;
import java.net.URI;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufHolder;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.CombinedChannelDuplexHandler;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import reactor.netty.Connection;
import reactor.netty.ConnectionObserver;
import reactor.netty.FutureMono;
import reactor.netty.NettyInbound;
import reactor.netty.NettyOutbound;
import reactor.netty.NettyPipeline;
import reactor.netty.ReactorNetty;
import reactor.netty.channel.AbortedException;
import reactor.netty.channel.ChannelOperations;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import static reactor.netty.ReactorNetty.format;
import static reactor.netty.ReactorNetty.toPrettyHexDump;
/**
* An HTTP ready {@link ChannelOperations} with state management for status and headers
* (first HTTP response packet).
*
* @author Stephane Maldini
*/
public abstract class HttpOperations<INBOUND extends NettyInbound, OUTBOUND extends NettyOutbound>
extends ChannelOperations<INBOUND, OUTBOUND> implements HttpInfos {
volatile int statusAndHeadersSent;
static final int READY = 0;
static final int HEADERS_SENT = 1;
static final int BODY_SENT = 2;
protected HttpOperations(HttpOperations<INBOUND, OUTBOUND> replaced) {
super(replaced);
this.statusAndHeadersSent = replaced.statusAndHeadersSent;
}
protected HttpOperations(Connection connection, ConnectionObserver listener) {
super(connection, listener);
}
/**
* Has headers been sent
*
* @return true if headers have been sent
*/
public final boolean hasSentHeaders() {
return statusAndHeadersSent != READY;
}
@Override
public boolean isWebsocket() {
return false;
}
@Override
public String requestId() {
return asShortText();
}
@Override
@SuppressWarnings("unchecked")
public NettyOutbound send(Publisher<? extends ByteBuf> source) {
if (!channel().isActive()) {
return then(Mono.error(AbortedException.beforeSend()));
}
if (source instanceof Mono) {
return new PostHeadersNettyOutbound(((Mono<ByteBuf>) source)
.flatMap(msg -> {
if (markSentHeaderAndBody(msg)) {
try {
afterMarkSentHeaders();
}
catch (RuntimeException e) {
ReferenceCountUtil.release(msg);
return Mono.error(e);
}
if (HttpUtil.getContentLength(outboundHttpMessage(), -1) == 0) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Dropped HTTP content, " +
"since response has Content-Length: 0 {}"), toPrettyHexDump(msg));
}
msg.release();
return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER)));
}
return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(msg)));
}
return FutureMono.from(channel().writeAndFlush(msg));
})
.doOnDiscard(ByteBuf.class, ByteBuf::release), this, null);
}
return super.send(source);
}
@Override
public NettyOutbound sendObject(Object message) {
if (!channel().isActive()) {
ReactorNetty.safeRelease(message);
return then(Mono.error(AbortedException.beforeSend()));
}
if (!(message instanceof ByteBuf)) {
return super.sendObject(message);
}
ByteBuf b = (ByteBuf) message;
return new PostHeadersNettyOutbound(FutureMono.deferFuture(() -> {
if (markSentHeaderAndBody(b)) {
try {
afterMarkSentHeaders();
}
catch (RuntimeException e) {
b.release();
throw e;
}
if (HttpUtil.getContentLength(outboundHttpMessage(), -1) == 0) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Dropped HTTP content, " +
"since response has Content-Length: 0 {}"), toPrettyHexDump(b));
}
b.release();
return channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER));
}
return channel().writeAndFlush(newFullBodyMessage(b));
}
return channel().writeAndFlush(b);
}), this, b);
}
@Override
public Mono<Void> then() {
if (!channel().isActive()) {
return Mono.error(AbortedException.beforeSend());
}
if (hasSentHeaders()) {
return Mono.empty();
}
return FutureMono.deferFuture(() -> {
if (markSentHeaders(outboundHttpMessage())) {
HttpMessage msg;
if (HttpUtil.isContentLengthSet(outboundHttpMessage())) {
outboundHttpMessage().headers()
.remove(HttpHeaderNames.TRANSFER_ENCODING);
if (HttpUtil.getContentLength(outboundHttpMessage(), 0) == 0) {
markSentBody();
msg = newFullBodyMessage(Unpooled.EMPTY_BUFFER);
}
else {
msg = outboundHttpMessage();
}
}
else {
msg = outboundHttpMessage();
}
try {
afterMarkSentHeaders();
}
catch (RuntimeException e) {
ReferenceCountUtil.release(msg);
throw e;
}
return channel().writeAndFlush(msg)
.addListener(f -> onHeadersSent());
}
else {
return channel().newSucceededFuture();
}
});
}
protected abstract void beforeMarkSentHeaders();
protected abstract void afterMarkSentHeaders();
protected abstract void onHeadersSent();
protected abstract HttpMessage newFullBodyMessage(ByteBuf body);
@Override
public final NettyOutbound sendFile(Path file, long position, long count) {
Objects.requireNonNull(file);
if (hasSentHeaders()) {
return super.sendFile(file, position, count);
}
if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage()) && !HttpUtil.isContentLengthSet(
outboundHttpMessage()) && count < Integer.MAX_VALUE) {
outboundHttpMessage().headers()
.setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count);
}
else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) {
outboundHttpMessage().headers()
.remove(HttpHeaderNames.CONTENT_LENGTH)
.remove(HttpHeaderNames.TRANSFER_ENCODING);
HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
}
return super.sendFile(file, position, count);
}
@Override
public String toString() {
if (isWebsocket()) {
return "ws{uri=" + uri() + ", connection=" + connection() + "}";
}
return method().name() + "{uri=" + uri() + ", connection=" + connection() + "}";
}
@Override
@SuppressWarnings("deprecation")
public HttpOperations<INBOUND, OUTBOUND> addHandler(String name, ChannelHandler handler) {
super.addHandler(name, handler);
if (channel().pipeline().context(handler) == null) {
return this;
}
autoAddHttpExtractor(this, name, handler);
return this;
}
static void autoAddHttpExtractor(Connection c, String name, ChannelHandler handler) {
if (handler instanceof ByteToMessageDecoder
|| handler instanceof ByteToMessageCodec
|| handler instanceof CombinedChannelDuplexHandler) {
String extractorName = name + "$extractor";
if (c.channel().pipeline().context(extractorName) != null) {
return;
}
c.channel().pipeline().addBefore(name, extractorName, HTTP_EXTRACTOR);
if (c.isPersistent()) {
c.onTerminate().subscribe(null, null, () -> c.removeHandler(extractorName));
}
}
}
/**
* Mark the headers sent
*
* @return true if marked for the first time
*/
protected final boolean markSentHeaders(Object... objectsToRelease) {
try {
if (!hasSentHeaders()) {
beforeMarkSentHeaders();
}
}
catch (RuntimeException e) {
for (Object o : objectsToRelease) {
try {
ReferenceCountUtil.release(o);
}
catch (Throwable e2) {
// keep going
}
}
throw e;
}
return HTTP_STATE.compareAndSet(this, READY, HEADERS_SENT);
}
/**
* Mark the body sent
*
* @return true if marked for the first time
*/
protected final boolean markSentBody() {
return HTTP_STATE.compareAndSet(this, HEADERS_SENT, BODY_SENT);
}
/**
* Mark the headers and body sent
*
* @return true if marked for the first time
*/
protected final boolean markSentHeaderAndBody(Object... objectsToRelease) {
try {
if (!hasSentHeaders()) {
beforeMarkSentHeaders();
}
}
catch (RuntimeException e) {
for (Object o : objectsToRelease) {
try {
ReferenceCountUtil.release(o);
}
catch (Throwable e2) {
// keep going
}
}
throw e;
}
return HTTP_STATE.compareAndSet(this, READY, BODY_SENT);
}
@Override
protected final String initShortId() {
if (connection() instanceof AtomicLong) {
return channel().id().asShortText() + '-' + ((AtomicLong) connection()).incrementAndGet();
}
return super.initShortId();
}
/**
* Returns the decoded path portion from the provided {@code uri}
*
* @param uri an HTTP URL that may contain a path with query/fragment
* @return the decoded path portion from the provided {@code uri}
*/
public static String resolvePath(String uri) {
Objects.requireNonNull(uri, "uri");
String tempUri = uri;
int index = tempUri.indexOf('?');
if (index > -1) {
tempUri = tempUri.substring(0, index);
}
index = tempUri.indexOf('#');
if (index > -1) {
tempUri = tempUri.substring(0, index);
}
if (tempUri.isEmpty()) {
return tempUri;
}
if (tempUri.charAt(0) == '/') {
if (tempUri.length() == 1) {
return tempUri;
}
tempUri = "http://localhost:8080" + tempUri;
}
else if (!SCHEME_PATTERN.matcher(tempUri).matches()) {
tempUri = "http://" + tempUri;
}
return URI.create(tempUri)
.getPath();
}
/**
* Outbound Netty HttpMessage
*
* @return Outbound Netty HttpMessage
*/
protected abstract HttpMessage outboundHttpMessage();
@SuppressWarnings("rawtypes")
final static AtomicIntegerFieldUpdater<HttpOperations> HTTP_STATE =
AtomicIntegerFieldUpdater.newUpdater(HttpOperations.class,
"statusAndHeadersSent");
final static ChannelInboundHandler HTTP_EXTRACTOR = NettyPipeline.inboundHandler(
(ctx, msg) -> {
if (msg instanceof ByteBufHolder) {
if (msg instanceof FullHttpMessage) {
// TODO convert into 2 messages if FullHttpMessage
ctx.fireChannelRead(msg);
}
else {
ByteBuf bb = ((ByteBufHolder) msg).content();
ctx.fireChannelRead(bb);
if (msg instanceof LastHttpContent) {
ctx.fireChannelRead(LastHttpContent.EMPTY_LAST_CONTENT);
}
}
}
else {
ctx.fireChannelRead(msg);
}
}
);
static final Logger log = Loggers.getLogger(HttpOperations.class);
static final Pattern SCHEME_PATTERN = Pattern.compile("^(https?|wss?)://.*$");
protected static final class PostHeadersNettyOutbound implements NettyOutbound, Consumer<Throwable>, Runnable {
final Mono<Void> source;
final HttpOperations<?, ?> parent;
final ByteBuf msg;
public PostHeadersNettyOutbound(Mono<Void> source, HttpOperations<?, ?> parent, @Nullable ByteBuf msg) {
this.msg = msg;
if (msg != null) {
this.source = source.doOnError(this)
.doOnCancel(this);
}
else {
this.source = source;
}
this.parent = parent;
}
@Override
public void run() {
if (msg != null && msg.refCnt() > 0) {
msg.release();
}
}
@Override
public void accept(Throwable throwable) {
if (msg != null && msg.refCnt() > 0) {
msg.release();
}
}
@Override
public Mono<Void> then() {
return source;
}
@Override
public ByteBufAllocator alloc() {
return parent.alloc();
}
@Override
public NettyOutbound send(Publisher<? extends ByteBuf> dataStream, Predicate<ByteBuf> predicate) {
return parent.send(dataStream, predicate);
}
@Override
public NettyOutbound sendObject(Publisher<?> dataStream, Predicate<Object> predicate) {
return parent.sendObject(dataStream, predicate);
}
@Override
public NettyOutbound sendObject(Object message) {
return parent.sendObject(message);
}
@Override
public <S> NettyOutbound sendUsing(Callable<? extends S> sourceInput,
BiFunction<? super Connection, ? super S, ?> mappedInput,
Consumer<? super S> sourceCleanup) {
return parent.sendUsing(sourceInput, mappedInput, sourceCleanup);
}
@Override
public NettyOutbound withConnection(Consumer<? super Connection> withConnection) {
return parent.withConnection(withConnection);
}
}
}