use of io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR in project servicetalk by apple.
the class CustomTransportTest method testCustomTransport.
@ParameterizedTest
@EnumSource(ServiceType.class)
void testCustomTransport(final ServiceType serviceType) throws Exception {
// You can re-use the EventLoopGroup used by your Netty application, we create one to demonstrate its use.
EventLoopAwareNettyIoExecutor ioExecutor = createIoExecutor("netty-el");
// This is the Netty channel which is reading the request. See getServiceContext(Channel), depending
// upon what control you want to give users knowing this may not be necessary.
Channel c = new EmbeddedChannel();
try {
ServerTransport serverTransport = new InMemoryServerTransport(DEFAULT_ALLOCATOR, serviceType.grpcService);
// Build the client with the custom transport and bridge to server's transport.
Tester.TesterClient client = new Tester.ClientFactory() {
@Override
public TesterClient newClient(final GrpcClientCallFactory factory) {
return super.newClient(factory);
}
}.newClient(new ClientTransportGrpcCallFactory(// Build the client transport, which just calls the server transport directly.
(method, requestMessages) -> serverTransport.handle(c, "clientId", method, requestMessages), ioExecutor.eventLoopGroup()));
// Test using the client.
assertThat(client.test(newReq("scalar")).toFuture().get(), is(newResp("hello scalar")));
assertThat(client.testRequestStream(newReqStream("req")).toFuture().get(), is(newResp("hello reqstream1, reqstream2, ")));
assertThat(client.testResponseStream(newReq("respStream")).toFuture().get(), contains(newResp("hello respStream1"), newResp("hello respStream2")));
assertThat(client.testBiDiStream(newReqStream("duplex")).toFuture().get(), contains(newResp("hello duplexstream1"), newResp("hello duplexstream2")));
} finally {
c.close();
ioExecutor.closeAsync().toFuture().get();
}
}
use of io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR in project servicetalk by apple.
the class NettyHttpServerConnectionTest method updateFlushStrategy.
@ParameterizedTest(name = "server={0} client={1}")
@MethodSource("executionStrategies")
void updateFlushStrategy(HttpExecutionStrategy serverExecutionStrategy, HttpExecutionStrategy clientExecutionStrategy) throws Exception {
customStrategy = new MockFlushStrategy();
AtomicReference<Cancellable> customCancellableRef = new AtomicReference<>();
AtomicBoolean handledFirstRequest = new AtomicBoolean();
serverContext = HttpServers.forAddress(localAddress(0)).ioExecutor(contextRule.ioExecutor()).appendConnectionAcceptorFilter(original -> original.append(ctx -> {
customCancellableRef.set(((NettyConnectionContext) ctx).updateFlushStrategy((__, ___) -> customStrategy));
return completed();
})).executionStrategy(serverExecutionStrategy).listenStreaming((ctx, request, responseFactory) -> {
if (handledFirstRequest.compareAndSet(false, true)) {
customStrategy.afterFirstWrite(FlushStrategy.FlushSender::flush);
return succeeded(responseFactory.ok().payloadBody(responsePublisher));
}
return succeeded(responseFactory.ok().payloadBody(responsePublisher2));
}).toFuture().get();
client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).executionStrategy(clientExecutionStrategy).buildStreaming();
StreamingHttpResponse response = client.request(client.newRequest(GET, "/1")).toFuture().get();
FlushStrategy.FlushSender customFlushSender = customStrategy.verifyApplied();
Cancellable customCancellable = customCancellableRef.get();
assertNotNull(customCancellable);
// Verify that the custom strategy is applied and used for flushing.
customStrategy.verifyWriteStarted();
customStrategy.verifyItemWritten(1);
customStrategy.verifyNoMoreInteractions();
String payloadBodyString = "foo";
TestSubscription testSubscription1 = new TestSubscription();
responsePublisher.onSubscribe(testSubscription1);
testSubscription1.awaitRequestN(1);
responsePublisher.onNext(DEFAULT_ALLOCATOR.fromAscii(payloadBodyString));
responsePublisher.onComplete();
customFlushSender.flush();
Buffer responsePayload = response.payloadBody().collect(DEFAULT_ALLOCATOR::newBuffer, (results, current) -> {
results.writeBytes(current);
return results;
}).toFuture().get();
assertEquals(payloadBodyString, responsePayload.toString(US_ASCII));
customStrategy.verifyItemWritten(2);
customStrategy.verifyWriteTerminated();
// Restore the default flush strategy, which should flush on each
customCancellable.cancel();
StreamingHttpResponse response2 = client.request(client.newRequest(GET, "/2")).toFuture().get();
TestSubscription testSubscription2 = new TestSubscription();
responsePublisher2.onSubscribe(testSubscription2);
responsePublisher2.onNext(DEFAULT_ALLOCATOR.fromAscii(payloadBodyString));
responsePublisher2.onComplete();
responsePayload = response2.payloadBody().collect(DEFAULT_ALLOCATOR::newBuffer, (results, current) -> {
results.writeBytes(current);
return results;
}).toFuture().get();
assertEquals(payloadBodyString, responsePayload.toString(US_ASCII));
}
use of io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR in project servicetalk by apple.
the class PayloadSizeLimitingHttpServiceFilterTest method moreThanMaxRejected.
@Test
void moreThanMaxRejected() {
ExecutionException e = assertThrows(ExecutionException.class, () -> new PayloadSizeLimitingHttpServiceFilter(100).create((ctx, request, responseFactory) -> succeeded(responseFactory.ok().payloadBody(request.payloadBody()))).handle(mock(HttpServiceContext.class), REQ_RESP_FACTORY.post("/").payloadBody(newBufferPublisher(101, DEFAULT_ALLOCATOR)), REQ_RESP_FACTORY).toFuture().get().payloadBody().toFuture().get());
assertThat(e.getCause(), instanceOf(PayloadTooLargeException.class));
}
use of io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR in project servicetalk by apple.
the class RequestTargetEncoderHttpServiceFilterTest method invokeServiceAssertValue.
private void invokeServiceAssertValue(String requestTarget, String expectedPayload) throws Exception {
StreamingHttpResponse response = new RequestTargetEncoderHttpServiceFilter().create(mockService).handle(mockCtx, reqRespFactory.get(requestTarget), reqRespFactory).toFuture().get();
String payload = response.payloadBody().collect(DEFAULT_ALLOCATOR::newCompositeBuffer, (composite, buf) -> {
composite.addBuffer(buf);
return composite;
}).toFuture().get().toString(US_ASCII);
assertThat(payload, is(expectedPayload));
}
use of io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR in project servicetalk by apple.
the class FlushStrategyOnServerTest method setUp.
private void setUp(final Param param) {
this.interceptor = new OutboundWriteEventsInterceptor();
this.headersFactory = DefaultHttpHeadersFactory.INSTANCE;
final StreamingHttpService service = (ctx, request, responseFactory) -> {
StreamingHttpResponse resp = responseFactory.ok();
if (request.headers().get(USE_EMPTY_RESP_BODY) == null) {
resp.payloadBody(from("Hello", "World"), appSerializerUtf8FixLen());
}
if (request.headers().get(USE_AGGREGATED_RESP) != null) {
return resp.toResponse().map(HttpResponse::toStreamingResponse);
}
return succeeded(resp);
};
final DefaultHttpExecutionContext httpExecutionContext = new DefaultHttpExecutionContext(DEFAULT_ALLOCATOR, globalExecutionContext().ioExecutor(), EXECUTOR_RULE.executor(), param.executionStrategy);
final ReadOnlyHttpServerConfig config = new HttpServerConfig().asReadOnly();
final ReadOnlyTcpServerConfig tcpReadOnly = new TcpServerConfig().asReadOnly();
try {
serverContext = TcpServerBinder.bind(localAddress(0), tcpReadOnly, true, httpExecutionContext, null, (channel, observer) -> {
final ConnectionObserver connectionObserver = config.tcpConfig().transportObserver().onNewConnection(channel.localAddress(), channel.remoteAddress());
return initChannel(channel, httpExecutionContext, config, new TcpServerChannelInitializer(tcpReadOnly, connectionObserver).andThen(channel1 -> channel1.pipeline().addLast(interceptor)), service, true, connectionObserver);
}, connection -> connection.process(true)).map(delegate -> new NettyHttpServerContext(delegate, service, httpExecutionContext)).toFuture().get();
} catch (Exception e) {
fail(e);
}
client = HttpClients.forSingleAddress(serverHostAndPort(serverContext)).protocols(h1Default()).buildBlocking();
}
Aggregations