Skip to content

Commit 545c210

Browse files
committed
Add example
1 parent 9740704 commit 545c210

1 file changed

Lines changed: 339 additions & 0 deletions

File tree

Lines changed: 339 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,339 @@
1+
/*
2+
* ====================================================================
3+
* Licensed to the Apache Software Foundation (ASF) under one
4+
* or more contributor license agreements. See the NOTICE file
5+
* distributed with this work for additional information
6+
* regarding copyright ownership. The ASF licenses this file
7+
* to you under the Apache License, Version 2.0 (the
8+
* "License"); you may not use this file except in compliance
9+
* with the License. You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing,
14+
* software distributed under the License is distributed on an
15+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
* KIND, either express or implied. See the License for the
17+
* specific language governing permissions and limitations
18+
* under the License.
19+
* ====================================================================
20+
*
21+
* This software consists of voluntary contributions made by many
22+
* individuals on behalf of the Apache Software Foundation. For more
23+
* information on the Apache Software Foundation, please see
24+
* <http://www.apache.org/>.
25+
*
26+
*/
27+
28+
package org.apache.hc.core5.http2.examples;
29+
30+
import java.net.InetSocketAddress;
31+
import java.util.List;
32+
import java.util.concurrent.CountDownLatch;
33+
import java.util.concurrent.Future;
34+
import java.util.concurrent.TimeUnit;
35+
import java.util.concurrent.atomic.AtomicInteger;
36+
37+
import org.apache.hc.core5.concurrent.FutureCallback;
38+
import org.apache.hc.core5.function.Supplier;
39+
import org.apache.hc.core5.http.ContentType;
40+
import org.apache.hc.core5.http.Header;
41+
import org.apache.hc.core5.http.HttpConnection;
42+
import org.apache.hc.core5.http.HttpHost;
43+
import org.apache.hc.core5.http.HttpResponse;
44+
import org.apache.hc.core5.http.HttpStatus;
45+
import org.apache.hc.core5.http.Message;
46+
import org.apache.hc.core5.http.Method;
47+
import org.apache.hc.core5.http.URIScheme;
48+
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
49+
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
50+
import org.apache.hc.core5.http.impl.routing.RequestRouter;
51+
import org.apache.hc.core5.http.message.BasicHttpResponse;
52+
import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
53+
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
54+
import org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer;
55+
import org.apache.hc.core5.http.nio.support.AsyncClientPipeline;
56+
import org.apache.hc.core5.http.nio.support.AsyncServerPipeline;
57+
import org.apache.hc.core5.http.protocol.HttpCoreContext;
58+
import org.apache.hc.core5.http2.HttpVersionPolicy;
59+
import org.apache.hc.core5.http2.config.H2Config;
60+
import org.apache.hc.core5.http2.frame.RawFrame;
61+
import org.apache.hc.core5.http2.impl.nio.H2StreamListener;
62+
import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap;
63+
import org.apache.hc.core5.http2.impl.nio.bootstrap.H2ServerBootstrap;
64+
import org.apache.hc.core5.io.CloseMode;
65+
import org.apache.hc.core5.reactor.IOReactorConfig;
66+
import org.apache.hc.core5.reactor.ListenerEndpoint;
67+
import org.apache.hc.core5.util.TimeValue;
68+
import org.apache.hc.core5.util.Timeout;
69+
70+
/**
71+
* HTTP/2 client demo illustrating the effect of the connection-level receive
72+
* window on a multiplexed multi-stream exchange while keeping the per-stream
73+
* initial window constant.
74+
*
75+
* @since 5.7
76+
*/
77+
public final class H2ConnectionWindowSizeExample {
78+
79+
private static final int STREAM_COUNT = 128;
80+
private static final int RESPONSE_SIZE = 2 * 1024 * 1024;
81+
82+
private static final int STREAM_WINDOW_SIZE = 1024 * 1024;
83+
private static final int SMALL_CONNECTION_WINDOW = 65_535;
84+
private static final int LARGE_CONNECTION_WINDOW = 16 * 1024 * 1024;
85+
86+
private static final Timeout CONNECT_TIMEOUT = Timeout.ofSeconds(30);
87+
private static final long COMPLETION_TIMEOUT_MINUTES = 5;
88+
89+
private H2ConnectionWindowSizeExample() {
90+
}
91+
92+
public static void main(final String[] args) throws Exception {
93+
final String payload = createPayload(RESPONSE_SIZE);
94+
final ServerHandle serverHandle = startServer(payload);
95+
try {
96+
System.out.println("Listening on " + serverHandle.port);
97+
System.out.println("Streams: " + STREAM_COUNT);
98+
System.out.println("Response size per stream: " + RESPONSE_SIZE + " bytes");
99+
System.out.println("Per-stream initial window: " + STREAM_WINDOW_SIZE + " bytes");
100+
System.out.println();
101+
102+
final RunResult small = runScenario(serverHandle.port, SMALL_CONNECTION_WINDOW);
103+
final RunResult large = runScenario(serverHandle.port, LARGE_CONNECTION_WINDOW);
104+
105+
printResult("small connection window", small);
106+
printResult("large connection window", large);
107+
} finally {
108+
serverHandle.server.close(CloseMode.GRACEFUL);
109+
serverHandle.server.awaitShutdown(TimeValue.ofSeconds(5));
110+
}
111+
}
112+
113+
private static ServerHandle startServer(final String payload) throws Exception {
114+
final H2Config serverH2Config = H2Config.custom()
115+
.setPushEnabled(false)
116+
.setMaxConcurrentStreams(STREAM_COUNT)
117+
.build();
118+
119+
final Supplier<AsyncServerExchangeHandler> exchangeHandlerSupplier = AsyncServerPipeline.assemble()
120+
.request(Method.GET)
121+
.<Void>consumeContent(contentType -> DiscardingEntityConsumer::new)
122+
.response()
123+
.asString(ContentType.TEXT_PLAIN)
124+
.handle((request, context) -> Message.of(
125+
new BasicHttpResponse(HttpStatus.SC_OK),
126+
payload))
127+
.supplier();
128+
129+
final HttpAsyncServer server = H2ServerBootstrap.bootstrap()
130+
.setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
131+
.setH2Config(serverH2Config)
132+
.setRequestRouter(RequestRouter.<Supplier<AsyncServerExchangeHandler>>builder()
133+
.addRoute(RequestRouter.LOCAL_AUTHORITY, "*", exchangeHandlerSupplier)
134+
.resolveAuthority(RequestRouter.LOCAL_AUTHORITY_RESOLVER)
135+
.build())
136+
.create();
137+
138+
server.start();
139+
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
140+
final ListenerEndpoint listenerEndpoint = future.get();
141+
final InetSocketAddress address = (InetSocketAddress) listenerEndpoint.getAddress();
142+
return new ServerHandle(server, address.getPort());
143+
}
144+
145+
private static RunResult runScenario(final int port, final int connectionWindowSize) throws Exception {
146+
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
147+
.setSoTimeout(30, TimeUnit.SECONDS)
148+
.setTcpNoDelay(true)
149+
.build();
150+
151+
final H2Config h2Config = H2Config.custom()
152+
.setPushEnabled(false)
153+
.setInitialWindowSize(STREAM_WINDOW_SIZE)
154+
.setConnectionWindowSize(connectionWindowSize)
155+
.setMaxConcurrentStreams(STREAM_COUNT)
156+
.build();
157+
158+
final AtomicInteger inputConnFlowControlEvents = new AtomicInteger();
159+
final AtomicInteger failures = new AtomicInteger();
160+
161+
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
162+
.setIOReactorConfig(ioReactorConfig)
163+
.setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
164+
.setH2Config(h2Config)
165+
.setStreamListener(new H2StreamListener() {
166+
167+
@Override
168+
public void onHeaderInput(
169+
final HttpConnection connection,
170+
final int streamId,
171+
final List<? extends Header> headers) {
172+
}
173+
174+
@Override
175+
public void onHeaderOutput(
176+
final HttpConnection connection,
177+
final int streamId,
178+
final List<? extends Header> headers) {
179+
}
180+
181+
@Override
182+
public void onFrameInput(
183+
final HttpConnection connection,
184+
final int streamId,
185+
final RawFrame frame) {
186+
}
187+
188+
@Override
189+
public void onFrameOutput(
190+
final HttpConnection connection,
191+
final int streamId,
192+
final RawFrame frame) {
193+
}
194+
195+
@Override
196+
public void onInputFlowControl(
197+
final HttpConnection connection,
198+
final int streamId,
199+
final int delta,
200+
final int actualSize) {
201+
if (streamId == 0) {
202+
inputConnFlowControlEvents.incrementAndGet();
203+
}
204+
}
205+
206+
@Override
207+
public void onOutputFlowControl(
208+
final HttpConnection connection,
209+
final int streamId,
210+
final int delta,
211+
final int actualSize) {
212+
}
213+
})
214+
.create();
215+
216+
requester.start();
217+
try {
218+
final HttpHost target = new HttpHost("http", "localhost", port);
219+
final Future<AsyncClientEndpoint> future = requester.connect(target, CONNECT_TIMEOUT);
220+
final AsyncClientEndpoint clientEndpoint = future.get();
221+
222+
try {
223+
final CountDownLatch latch = new CountDownLatch(STREAM_COUNT);
224+
final long started = System.nanoTime();
225+
226+
for (int i = 0; i < STREAM_COUNT; i++) {
227+
final String requestUri = "/bytes/" + i;
228+
clientEndpoint.execute(
229+
AsyncClientPipeline.assemble()
230+
.request()
231+
.get(target, requestUri)
232+
.response()
233+
.<Void>consumeContent(contentType -> DiscardingEntityConsumer::new)
234+
.result(new FutureCallback<Message<HttpResponse, Void>>() {
235+
236+
@Override
237+
public void completed(final Message<HttpResponse, Void> message) {
238+
try {
239+
final HttpResponse response = message.head();
240+
if (response.getCode() != HttpStatus.SC_OK) {
241+
failures.incrementAndGet();
242+
System.out.println(requestUri + " -> unexpected status: " + response.getCode());
243+
}
244+
} finally {
245+
latch.countDown();
246+
}
247+
}
248+
249+
@Override
250+
public void failed(final Exception ex) {
251+
failures.incrementAndGet();
252+
ex.printStackTrace(System.out);
253+
latch.countDown();
254+
}
255+
256+
@Override
257+
public void cancelled() {
258+
failures.incrementAndGet();
259+
System.out.println(requestUri + " cancelled");
260+
latch.countDown();
261+
}
262+
})
263+
.create(),
264+
null,
265+
HttpCoreContext.create());
266+
}
267+
268+
final boolean completed = latch.await(COMPLETION_TIMEOUT_MINUTES, TimeUnit.MINUTES);
269+
final long elapsedNanos = System.nanoTime() - started;
270+
271+
if (!completed) {
272+
throw new IllegalStateException("Timed out waiting for responses");
273+
}
274+
if (failures.get() > 0) {
275+
throw new IllegalStateException("Scenario failed with " + failures.get() + " error(s)");
276+
}
277+
278+
return new RunResult(
279+
connectionWindowSize,
280+
elapsedNanos,
281+
inputConnFlowControlEvents.get());
282+
} finally {
283+
clientEndpoint.releaseAndDiscard();
284+
}
285+
} finally {
286+
requester.close(CloseMode.GRACEFUL);
287+
}
288+
}
289+
290+
private static void printResult(final String label, final RunResult result) {
291+
System.out.println(label + ":");
292+
System.out.println(" connection window size: " + result.connectionWindowSize + " bytes");
293+
System.out.printf(" elapsed: %.3f s%n", nanosToSeconds(result.elapsedNanos));
294+
System.out.println(" stream-0 input flow-control events: " + result.inputConnFlowControlEvents);
295+
System.out.println();
296+
}
297+
298+
private static double nanosToSeconds(final long nanos) {
299+
return nanos / 1_000_000_000.0;
300+
}
301+
302+
private static String createPayload(final int size) {
303+
final StringBuilder buffer = new StringBuilder(size);
304+
while (buffer.length() < size) {
305+
buffer.append("0123456789abcdef");
306+
}
307+
if (buffer.length() > size) {
308+
buffer.setLength(size);
309+
}
310+
return buffer.toString();
311+
}
312+
313+
private static final class ServerHandle {
314+
315+
private final HttpAsyncServer server;
316+
private final int port;
317+
318+
private ServerHandle(final HttpAsyncServer server, final int port) {
319+
this.server = server;
320+
this.port = port;
321+
}
322+
}
323+
324+
private static final class RunResult {
325+
326+
private final int connectionWindowSize;
327+
private final long elapsedNanos;
328+
private final int inputConnFlowControlEvents;
329+
330+
private RunResult(
331+
final int connectionWindowSize,
332+
final long elapsedNanos,
333+
final int inputConnFlowControlEvents) {
334+
this.connectionWindowSize = connectionWindowSize;
335+
this.elapsedNanos = elapsedNanos;
336+
this.inputConnFlowControlEvents = inputConnFlowControlEvents;
337+
}
338+
}
339+
}

0 commit comments

Comments
 (0)