-
Notifications
You must be signed in to change notification settings - Fork 629
/
NettyOutbound.java
394 lines (368 loc) · 14.7 KB
/
NettyOutbound.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
/*
* 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.netty5;
import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import io.netty5.buffer.api.Buffer;
import io.netty5.buffer.api.BufferAllocator;
import io.netty5.channel.Channel;
import io.netty5.channel.DefaultFileRegion;
import io.netty5.handler.stream.ChunkedNioFile;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static reactor.netty5.ReactorNetty.PREDICATE_GROUP_BOUNDARY;
import static reactor.netty5.ReactorNetty.PREDICATE_GROUP_FLUSH;
/**
* An outbound-traffic API delegating to an underlying {@link Channel}.
* <p>Note: With HTTP, chaining multiple send operations is discouraged and will not work as expected
* when send involves scalar or mono publishers. For instance {@code send(flux).send(mono)}
* or {@code send(flux).sendObject(message)} will ignore {@code send(flux)}.
* This is an anticipation of an API simplification moving forward next versions where
* send will not return {@link NettyOutbound} anymore.</p>
*
* @author Stephane Maldini
*/
public interface NettyOutbound extends Publisher<Void> {
/**
* Returns the assigned {@link BufferAllocator}.
*
* @return the {@link BufferAllocator}
*/
BufferAllocator alloc();
/**
* Returns a never completing {@link Mono} after this {@link NettyOutbound#then()} has
* completed.
*
* @return a never completing {@link Mono} after this {@link NettyOutbound#then()} has
* completed.
*/
default Mono<Void> neverComplete() {
return then(Mono.never()).then();
}
/**
* Sends data to the peer, listens for any error on write and closes on terminal signal
* (complete|error). <p>A new {@link NettyOutbound} type (or the same) for typed send
* sequences.</p>
* <p>Note: Nesting any send* method is not supported.</p>
* <p>Note: If you need to transform from {@link io.netty.buffer.ByteBuf} to {@link Buffer}
* you can use {@link io.netty5.buffer.api.adaptor.ByteBufAdaptor#extractOrCopy(BufferAllocator, io.netty.buffer.ByteBuf)}</p>
*
* @param dataStream the dataStream publishing OUT items to write on this channel
*
* @return A new {@link NettyOutbound} to append further send. It will emit a complete
* signal successful sequence write (e.g. after "flush") or any error during write.
*/
default NettyOutbound send(Publisher<? extends Buffer> dataStream) {
return send(dataStream, ReactorNetty.PREDICATE_BUFFER_FLUSH);
}
/**
* Sends data to the peer, listens for any error on write and closes on terminal signal
* (complete|error). <p>A new {@link NettyOutbound} type (or the same) for typed send
* sequences.</p>
* <p>Note: Nesting any send* method is not supported.</p>
* <p>Note: If you need to transform from {@link io.netty.buffer.ByteBuf} to {@link Buffer}
* you can use {@link io.netty5.buffer.api.adaptor.ByteBufAdaptor#extractOrCopy(BufferAllocator, io.netty.buffer.ByteBuf)}</p>
*
* @param dataStream the dataStream publishing OUT items to write on this channel
* @param predicate that returns true if explicit flush operation is needed after that buffer
*
* @return A new {@link NettyOutbound} to append further send. It will emit a complete
* signal successful sequence write (e.g. after "flush") or any error during write.
*/
NettyOutbound send(Publisher<? extends Buffer> dataStream, Predicate<Buffer> predicate);
/**
* Sends bytes to the peer, listens for any error on write and closes on terminal
* signal (complete|error). If more than one publisher is attached (multiple calls to
* send()) completion occurs after all publishers complete.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStream the dataStream publishing Buffer items to write on this channel
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendByteArray(Publisher<? extends byte[]> dataStream) {
return send(ReactorNetty.publisherOrScalarMap(dataStream, bytes -> alloc().copyOf(bytes)));
}
/**
* Sends content from given {@link Path} using
* {@link java.nio.channels.FileChannel#transferTo(long, long, WritableByteChannel)}
* support. If the system supports it and the path resolves to a local file
* system {@link File} then transfer will use zero-byte copy
* to the peer.
* <p>It will
* listen for any error on
* write and close
* on terminal signal (complete|error). If more than one publisher is attached
* (multiple calls to send()) completion occurs after all publishers complete.
* <p>
* Note: this will emit {@link io.netty5.channel.FileRegion} in the outbound
* {@link io.netty5.channel.ChannelPipeline}
* Note: Nesting any send* method is not supported.
*
* @param file the file Path
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendFile(Path file) {
try {
return sendFile(file, 0L, Files.size(file));
}
catch (IOException e) {
return then(Mono.error(e));
}
}
/**
* Sends content from the given {@link Path} using
* {@link java.nio.channels.FileChannel#transferTo(long, long, WritableByteChannel)}
* support, if the system supports it, the path resolves to a local file
* system {@link File}, compression and SSL/TLS is not enabled, then transfer will
* use zero-byte copy to the peer., otherwise chunked read/write will be used.
* <p>It will listens for any error on write and closes
* on terminal signal (complete|error). If more than one publisher is attached
* (multiple calls to send()) completion occurs after all publishers complete.</p>
* <p></p>Note: Nesting any send* method is not supported.</p>
*
* @param file the file Path
* @param position where to start
* @param count how much to transfer
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendFile(Path file, long position, long count) {
Objects.requireNonNull(file, "filepath");
return sendUsing(() -> FileChannel.open(file, StandardOpenOption.READ),
(c, fc) -> {
if (ReactorNetty.mustChunkFileTransfer(c, file)) {
ReactorNetty.addChunkedWriter(c);
try {
return new ChunkedNioFile(fc, position, count, 1024);
}
catch (Exception ioe) {
throw Exceptions.propagate(ioe);
}
}
return new DefaultFileRegion(fc, position, count);
},
ReactorNetty.fileCloser);
}
/**
* Sends content from given {@link Path} using chunked read/write. <p>It will listen
* for any error on write and close on terminal signal (complete|error). If more than
* one publisher is attached (multiple calls to send()) completion occurs after all
* publishers complete.</p>
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param file the file Path
* @param position where to start
* @param count how much to transfer
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendFileChunked(Path file, long position, long count) {
Objects.requireNonNull(file, "filepath");
return sendUsing(() -> FileChannel.open(file, StandardOpenOption.READ),
(c, fc) -> {
ReactorNetty.addChunkedWriter(c);
try {
return new ChunkedNioFile(fc, position, count, 1024);
}
catch (Exception e) {
throw Exceptions.propagate(e);
}
},
ReactorNetty.fileCloser);
}
/**
* Sends data to the peer, listens for any error on write and closes on terminal signal
* (complete|error). Each individual {@link Publisher} completion will flush
* the underlying IO runtime.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStreams the dataStream publishing OUT items to write on this channel
*
* @return A {@link Mono} to signal successful sequence write (e.g. after "flush") or
* any error during write
*/
default NettyOutbound sendGroups(Publisher<? extends Publisher<? extends Buffer>> dataStreams) {
Buffer BOUNDARY = alloc().copyOf(PREDICATE_GROUP_BOUNDARY.getBytes(StandardCharsets.UTF_8)).makeReadOnly();
return send(
Flux.from(dataStreams)
.concatMap(p -> Flux.<Buffer>from(p)
.concatWith(Mono.just(BOUNDARY.copy(0, BOUNDARY.readableBytes(), true))), 32)
.doFinally(sig -> BOUNDARY.close()),
buf -> {
boolean flush = PREDICATE_GROUP_FLUSH.test(buf);
if (flush) {
buf.close();
}
return flush;
});
}
/**
* Sends an object through Netty pipeline. If type of {@link Publisher}, sends all signals,
* flushing on complete by default. Write occur in FIFO sequence.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStream the dataStream publishing items to write on this channel
* or a simple pojo supported by configured Netty handlers
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendObject(Publisher<?> dataStream) {
return sendObject(dataStream, ReactorNetty.PREDICATE_FLUSH);
}
/**
* Sends an object through Netty pipeline. If type of {@link Publisher}, sends all signals,
* flushing on complete by default. Write occur in FIFO sequence.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStream the dataStream publishing items to write on this channel
* or a simple pojo supported by configured Netty handlers
* @param predicate that returns true if explicit flush operation is needed after that object
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
NettyOutbound sendObject(Publisher<?> dataStream, Predicate<Object> predicate);
/**
* Sends data to the peer, listens for any error on write and closes on terminal signal
* (complete|error).
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param message the object to publish
*
* @return A {@link Mono} to signal successful sequence write (e.g. after "flush") or
* any error during write
*/
NettyOutbound sendObject(Object message);
/**
* Sends String to the peer, listens for any error on write and closes on terminal signal
* (complete|error). If more than one publisher is attached (multiple calls to send())
* completion occurs after all publishers complete.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStream the dataStream publishing Buffer items to write on this channel
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendString(Publisher<? extends String> dataStream) {
return sendString(dataStream, Charset.defaultCharset());
}
/**
* Sends String to the peer, listens for any error on write and closes on terminal signal
* (complete|error). If more than one publisher is attached (multiple calls to send())
* completion occurs after all publishers complete.
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param dataStream the dataStream publishing Buffer items to write on this channel
* @param charset the encoding charset
*
* @return A Publisher to signal successful sequence write (e.g. after "flush") or any
* error during write
*/
default NettyOutbound sendString(Publisher<? extends String> dataStream,
Charset charset) {
Objects.requireNonNull(charset, "charset");
return send(ReactorNetty.publisherOrScalarMap(dataStream, s -> alloc().copyOf(s.getBytes(charset))));
}
/**
* Binds a send to a starting/cleanup lifecycle
* <p>Note: Nesting any send* method is not supported.</p>
*
* @param sourceInput state generator
* @param mappedInput input to send
* @param sourceCleanup state cleaner
* @param <S> state type
*
* @return a new {@link NettyOutbound}
*/
<S> NettyOutbound sendUsing(Callable<? extends S> sourceInput,
BiFunction<? super Connection, ? super S, ?> mappedInput,
Consumer<? super S> sourceCleanup);
/**
* Subscribes a {@code Void} subscriber to this outbound and trigger all eventual
* parent outbound send.
*
* @param s the {@link Subscriber} to listen for send sequence completion/failure
*/
@Override
default void subscribe(Subscriber<? super Void> s) {
then().subscribe(s);
}
/**
* Obtains a {@link Mono} of pending outbound(s) write completion.
*
* @return a {@link Mono} of pending outbound(s) write completion
*/
default Mono<Void> then() {
return Mono.empty();
}
/**
* Appends a {@link Publisher} task such as a {@link Mono} and returns a new
* {@link NettyOutbound} to sequence further send.
*
* @param other the {@link Publisher} to subscribe to when this pending outbound
* {@link #then()} is complete;
*
* @return a new {@link NettyOutbound}
*/
default NettyOutbound then(Publisher<Void> other) {
return new ReactorNetty.OutboundThen(this, other);
}
/**
* Append a {@link Publisher} task such as a Mono and return a new
* {@link NettyOutbound} to sequence further send.
*
* @param other the {@link Publisher} to subscribe to when this pending outbound
* {@link #then()} is complete;
* @param onCleanup a cleanup hook when other has terminated or cancelled
*
* @return a new {@link NettyOutbound} that
*/
default NettyOutbound then(Publisher<Void> other, Runnable onCleanup) {
return new ReactorNetty.OutboundThen(this, other, onCleanup);
}
/**
* Call the passed callback with a {@link Connection} to operate on the underlying
* {@link Channel} state.
*
* @param withConnection connection callback
*
* @return the {@link Connection}
*/
NettyOutbound withConnection(Consumer<? super Connection> withConnection);
}