- Notifications
You must be signed in to change notification settings - Fork122
F/delayed handler#100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
7 commits Select commitHold shift + click to select a range
0f752e7 More comments, allow making posts from a branch
billoneil326ae7a Add a non blocking delayed handler
billoneileb836c6 Cleanup
billoneil29b06b9 comments
billoneil6d6ba71 wip
billoneil8b8da4d WIP
billoneil14da547 Fix
billoneilFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
42 changes: 42 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/Http.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| packagecom.stubbornjava.common; | ||
| importjava.util.concurrent.ExecutorService; | ||
| importjava.util.concurrent.Executors; | ||
| importjava.util.concurrent.TimeUnit; | ||
| importorg.jooq.lambda.Unchecked; | ||
| importorg.slf4j.Logger; | ||
| importorg.slf4j.LoggerFactory; | ||
| importcom.google.common.util.concurrent.MoreExecutors; | ||
| importokhttp3.OkHttpClient; | ||
| importokhttp3.Request; | ||
| importokhttp3.Response; | ||
| publicclassHttp { | ||
| privatestaticfinalLoggerlog =LoggerFactory.getLogger(Http.class); | ||
| // {{start:get}} | ||
| publicstaticResponseget(OkHttpClientclient,Stringurl) { | ||
| Requestrequest =newRequest.Builder() | ||
| .url(url) | ||
| .get() | ||
| .build(); | ||
| returnUnchecked.supplier(() -> { | ||
| Responseresponse =client.newCall(request).execute(); | ||
| returnresponse; | ||
| }).get(); | ||
| } | ||
| // {{end:get}} | ||
| // {{start:getInParallel}} | ||
| publicstaticvoidgetInParallel(OkHttpClientclient,Stringurl,intcount) { | ||
| ExecutorServiceexec =Executors.newFixedThreadPool(count); | ||
| for (inti =0;i <count;i++) { | ||
| exec.submit(() ->Http.get(client,url)); | ||
| } | ||
| MoreExecutors.shutdownAndAwaitTermination(exec,30,TimeUnit.SECONDS); | ||
| } | ||
| // {{end:getInParallel}} | ||
| } |
6 changes: 5 additions & 1 deletionstubbornjava-common/src/main/java/com/stubbornjava/common/HttpClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/Timers.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| packagecom.stubbornjava.common; | ||
| importjava.util.concurrent.TimeUnit; | ||
| importorg.slf4j.Logger; | ||
| importorg.slf4j.LoggerFactory; | ||
| importcom.google.common.base.Stopwatch; | ||
| publicclassTimers { | ||
| privatestaticfinalLoggerlogger =LoggerFactory.getLogger(Timers.class); | ||
| privateTimers() {} | ||
| publicstaticvoidtime(Stringmessage,Runnablerunnable) { | ||
| Stopwatchsw =Stopwatch.createStarted(); | ||
| try { | ||
| logger.info("{}",message); | ||
| runnable.run(); | ||
| }catch (Exceptionex) { | ||
| logger.warn("Exception in runnable",ex); | ||
| throwex; | ||
| }finally { | ||
| logger.info("{} took {}ms",message,sw.elapsed(TimeUnit.MILLISECONDS)); | ||
| } | ||
| } | ||
| } |
2 changes: 2 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/undertow/SimpleServer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/undertow/UndertowUtil.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| packagecom.stubbornjava.common.undertow; | ||
| importjava.net.InetSocketAddress; | ||
| importjava.util.function.Consumer; | ||
| importorg.slf4j.Logger; | ||
| importorg.slf4j.LoggerFactory; | ||
| importio.undertow.Undertow; | ||
| importio.undertow.Undertow.ListenerInfo; | ||
| importio.undertow.server.HttpHandler; | ||
| publicclassUndertowUtil { | ||
| privatestaticfinalLoggerlogger =LoggerFactory.getLogger(UndertowUtil.class); | ||
| /** | ||
| * This is currently intended to be used in unit tests but may | ||
| * be appropriate in other situations as well. It's not worth building | ||
| * out a test module at this time so it lives here. | ||
| * | ||
| * This helper will spin up the http handler on a random available port. | ||
| * The full host and port will be passed to the hostConsumer and the server | ||
| * will be shut down after the consumer completes. | ||
| * | ||
| * @param builder | ||
| * @param handler | ||
| * @param hostConusmer | ||
| */ | ||
| publicstaticvoiduseLocalServer(Undertow.Builderbuilder, | ||
| HttpHandlerhandler, | ||
| Consumer<String>hostConusmer) { | ||
| Undertowundertow =null; | ||
| try { | ||
| // Starts server on a random open port | ||
| undertow =builder.addHttpListener(0,"127.0.0.1",handler).build(); | ||
| undertow.start(); | ||
| ListenerInfolistenerInfo =undertow.getListenerInfo().get(0); | ||
| InetSocketAddressaddr = (InetSocketAddress)listenerInfo.getAddress(); | ||
| Stringhost ="http://localhost:" +addr.getPort(); | ||
| hostConusmer.accept(host); | ||
| }finally { | ||
| if (undertow !=null) { | ||
| undertow.stop(); | ||
| } | ||
| } | ||
| } | ||
| } |
4 changes: 3 additions & 1 deletion...rnjava-common/src/main/java/com/stubbornjava/common/undertow/handlers/CustomHandlers.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions...in/java/com/stubbornjava/common/undertow/handlers/diagnostic/DelayedExecutionHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| packagecom.stubbornjava.common.undertow.handlers.diagnostic; | ||
| importjava.time.Duration; | ||
| importjava.util.concurrent.TimeUnit; | ||
| importjava.util.function.Function; | ||
| importio.undertow.server.Connectors; | ||
| importio.undertow.server.HttpHandler; | ||
| importio.undertow.server.HttpServerExchange; | ||
| importio.undertow.server.handlers.BlockingHandler; | ||
| // {{start:delayedHandler}} | ||
| /** | ||
| * A non blocking handler to add a time delay before the next handler | ||
| * is executed. If the exchange has already been dispatched this will | ||
| * un-dispatch the exchange and re-dispatch it before next is called. | ||
| */ | ||
| publicclassDelayedExecutionHandlerimplementsHttpHandler { | ||
| privatefinalHttpHandlernext; | ||
| privatefinalFunction<HttpServerExchange,Duration>durationFunc; | ||
| DelayedExecutionHandler(HttpHandlernext, | ||
| Function<HttpServerExchange,Duration>durationFunc) { | ||
| this.next =next; | ||
| this.durationFunc =durationFunc; | ||
| } | ||
| @Override | ||
| publicvoidhandleRequest(HttpServerExchangeexchange)throwsException { | ||
| Durationduration =durationFunc.apply(exchange); | ||
| finalHttpHandlerdelegate; | ||
| if (exchange.isBlocking()) { | ||
| // We want to undispatch here so that we are not blocking | ||
| // a worker thread. We will spin on the IO thread using the | ||
| // built in executeAfter. | ||
| exchange.unDispatch(); | ||
| delegate =newBlockingHandler(next); | ||
| }else { | ||
| delegate =next; | ||
| } | ||
| exchange.dispatch(exchange.getIoThread(), () -> { | ||
| exchange.getIoThread().executeAfter(() -> | ||
| Connectors.executeRootHandler(delegate,exchange), | ||
| duration.toMillis(), | ||
| TimeUnit.MILLISECONDS); | ||
| }); | ||
| } | ||
| } | ||
| // {{end:delayedHandler}} |
49 changes: 49 additions & 0 deletions...rc/main/java/com/stubbornjava/common/undertow/handlers/diagnostic/DiagnosticHandlers.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| packagecom.stubbornjava.common.undertow.handlers.diagnostic; | ||
| importjava.time.Duration; | ||
| importjava.util.concurrent.ThreadLocalRandom; | ||
| importjava.util.concurrent.TimeUnit; | ||
| importio.undertow.server.HttpHandler; | ||
| publicclassDiagnosticHandlers { | ||
| // {{start:delayedHandler}} | ||
| /** | ||
| * Add a fixed delay before execution of the next handler | ||
| * @param next | ||
| * @param duration | ||
| * @param unit | ||
| * @return | ||
| */ | ||
| publicstaticDelayedExecutionHandlerfixedDelay(HttpHandlernext, | ||
| longduration, | ||
| TimeUnitunit) { | ||
| returnnewDelayedExecutionHandler( | ||
| next, (exchange) ->Duration.ofMillis(unit.toMillis(duration))); | ||
| } | ||
| /** | ||
| * Add a random delay between minDuration (inclusive) and | ||
| * maxDuration (exclusive) before execution of the next handler. | ||
| * This can be used to add artificial latency for requests. | ||
| * | ||
| * @param next | ||
| * @param minDuration inclusive | ||
| * @param maxDuration exclusive | ||
| * @param unit | ||
| * @return | ||
| */ | ||
| publicstaticDelayedExecutionHandlerrandomDelay(HttpHandlernext, | ||
| longminDuration, | ||
| longmaxDuration, | ||
| TimeUnitunit) { | ||
| returnnewDelayedExecutionHandler( | ||
| next, (exchange) -> { | ||
| longduration =ThreadLocalRandom.current() | ||
| .nextLong(minDuration,maxDuration); | ||
| returnDuration.ofMillis(unit.toMillis(duration)); | ||
| }); | ||
| } | ||
| // {{end:delayedHandler}} | ||
| } |
97 changes: 97 additions & 0 deletions...ava/com/stubbornjava/common/undertow/handlers/diagnostic/DelayedExecutionHandlerTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| packagecom.stubbornjava.common.undertow.handlers.diagnostic; | ||
| importstaticorg.junit.Assert.assertTrue; | ||
| importjava.util.List; | ||
| importjava.util.concurrent.Callable; | ||
| importjava.util.concurrent.ExecutorService; | ||
| importjava.util.concurrent.Executors; | ||
| importjava.util.concurrent.Future; | ||
| importjava.util.concurrent.TimeUnit; | ||
| importjava.util.stream.Collectors; | ||
| importjava.util.stream.IntStream; | ||
| importorg.jooq.lambda.Seq; | ||
| importorg.jooq.lambda.Unchecked; | ||
| importorg.junit.Assert; | ||
| importorg.junit.Test; | ||
| importcom.google.common.base.Stopwatch; | ||
| importcom.google.common.util.concurrent.MoreExecutors; | ||
| importcom.stubbornjava.common.Http; | ||
| importcom.stubbornjava.common.HttpClient; | ||
| importcom.stubbornjava.common.undertow.Exchange; | ||
| importcom.stubbornjava.common.undertow.UndertowUtil; | ||
| importcom.stubbornjava.common.undertow.handlers.CustomHandlers; | ||
| importcom.stubbornjava.undertow.handlers.MiddlewareBuilder; | ||
| importio.undertow.Undertow; | ||
| importio.undertow.server.HttpHandler; | ||
| importio.undertow.server.handlers.BlockingHandler; | ||
| importokhttp3.OkHttpClient; | ||
| importokhttp3.Response; | ||
| publicclassDelayedExecutionHandlerTest { | ||
| // Delay for 500ms then return "ok" | ||
| privatestaticfinalDelayedExecutionHandlerdelayedHandler = | ||
| DiagnosticHandlers.fixedDelay((exchange) -> { | ||
| Exchange.body().sendText(exchange,"ok"); | ||
| }, | ||
| 500,TimeUnit.MILLISECONDS); | ||
| @Test | ||
| publicvoidtestOnXIoThread()throwsInterruptedException { | ||
| intnumThreads =10; | ||
| run(delayedHandler,numThreads); | ||
| } | ||
| @Test | ||
| publicvoidtestOnWorkerThread()throwsInterruptedException { | ||
| intnumThreads =10; | ||
| run(newBlockingHandler(delayedHandler),numThreads); | ||
| } | ||
| /** | ||
| * Spin up a new server with a single IO thread and worker thread. | ||
| * Run N GET requests against it concurrently and make sure they | ||
| * do not take N * 500ms total. This is not the best test but it | ||
| * should show that we are delaying N requests at once using a single | ||
| * thread. | ||
| * | ||
| * @param handler | ||
| * @param numThreads | ||
| * @throws InterruptedException | ||
| */ | ||
| privatevoidrun(HttpHandlerhandler,intnumThreads)throwsInterruptedException { | ||
| HttpHandlerroute =MiddlewareBuilder.begin(CustomHandlers::accessLog) | ||
| .complete(handler); | ||
| Undertow.Builderbuilder =Undertow.builder() | ||
| .setWorkerThreads(1) | ||
| .setIoThreads(1); | ||
| UndertowUtil.useLocalServer(builder,route,host -> { | ||
| ExecutorServiceexec =Executors.newFixedThreadPool(numThreads); | ||
| OkHttpClientclient =newOkHttpClient().newBuilder() | ||
| .addInterceptor(HttpClient.getLoggingInterceptor()) | ||
| .build(); | ||
| // Using time in tests isn't the best approach but this one seems | ||
| // A little difficult to test another way. | ||
| Stopwatchsw =Stopwatch.createStarted(); | ||
| List<Callable<Response>>callables =IntStream.range(0,numThreads) | ||
| .mapToObj(i -> (Callable<Response>) () ->Http.get(client,host)) | ||
| .collect(Collectors.toList()); | ||
| sw.stop(); | ||
| Seq.seq(Unchecked.supplier(() ->exec.invokeAll(callables)).get()) | ||
| .map(Unchecked.function(Future::get)) | ||
| .forEach(DelayedExecutionHandlerTest::assertSuccess); | ||
| assertTrue("Responses took too long",sw.elapsed().toMillis() <1_000); | ||
| MoreExecutors.shutdownAndAwaitTermination(exec,10,TimeUnit.SECONDS); | ||
| }); | ||
| } | ||
| privatestaticvoidassertSuccess(Responseresponse) { | ||
| Assert.assertTrue("Response should be a 200",response.isSuccessful()); | ||
| } | ||
| } |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.