- Notifications
You must be signed in to change notification settings - Fork123
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 @@ | ||
package com.stubbornjava.common; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.TimeUnit; | ||
import org.jooq.lambda.Unchecked; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import com.google.common.util.concurrent.MoreExecutors; | ||
import okhttp3.OkHttpClient; | ||
import okhttp3.Request; | ||
import okhttp3.Response; | ||
public class Http { | ||
private static final Logger log = LoggerFactory.getLogger(Http.class); | ||
// {{start:get}} | ||
public static Response get(OkHttpClient client, String url) { | ||
Request request = new Request.Builder() | ||
.url(url) | ||
.get() | ||
.build(); | ||
return Unchecked.supplier(() -> { | ||
Response response = client.newCall(request).execute(); | ||
return response; | ||
}).get(); | ||
} | ||
// {{end:get}} | ||
// {{start:getInParallel}} | ||
public static void getInParallel(OkHttpClient client, String url, int count) { | ||
ExecutorService exec = Executors.newFixedThreadPool(count); | ||
for (int i = 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 @@ | ||
package com.stubbornjava.common; | ||
import java.util.concurrent.TimeUnit; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import com.google.common.base.Stopwatch; | ||
public class Timers { | ||
private static final Logger logger = LoggerFactory.getLogger(Timers.class); | ||
private Timers() {} | ||
public static void time(String message, Runnable runnable) { | ||
Stopwatch sw = Stopwatch.createStarted(); | ||
try { | ||
logger.info("{}", message); | ||
runnable.run(); | ||
} catch (Exception ex) { | ||
logger.warn("Exception in runnable", ex); | ||
throw ex; | ||
} 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 @@ | ||
package com.stubbornjava.common.undertow; | ||
import java.net.InetSocketAddress; | ||
import java.util.function.Consumer; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import io.undertow.Undertow; | ||
import io.undertow.Undertow.ListenerInfo; | ||
import io.undertow.server.HttpHandler; | ||
public class UndertowUtil { | ||
private static final Logger logger = 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 | ||
*/ | ||
public static void useLocalServer(Undertow.Builder builder, | ||
HttpHandler handler, | ||
Consumer<String> hostConusmer) { | ||
Undertow undertow = null; | ||
try { | ||
// Starts server on a random open port | ||
undertow = builder.addHttpListener(0, "127.0.0.1", handler).build(); | ||
undertow.start(); | ||
ListenerInfo listenerInfo = undertow.getListenerInfo().get(0); | ||
InetSocketAddress addr = (InetSocketAddress) listenerInfo.getAddress(); | ||
String host = "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 @@ | ||
package com.stubbornjava.common.undertow.handlers.diagnostic; | ||
import java.time.Duration; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.function.Function; | ||
import io.undertow.server.Connectors; | ||
import io.undertow.server.HttpHandler; | ||
import io.undertow.server.HttpServerExchange; | ||
import io.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. | ||
*/ | ||
public class DelayedExecutionHandler implements HttpHandler { | ||
private final HttpHandler next; | ||
private final Function<HttpServerExchange, Duration> durationFunc; | ||
DelayedExecutionHandler(HttpHandler next, | ||
Function<HttpServerExchange, Duration> durationFunc) { | ||
this.next = next; | ||
this.durationFunc = durationFunc; | ||
} | ||
@Override | ||
public void handleRequest(HttpServerExchange exchange) throws Exception { | ||
Duration duration = durationFunc.apply(exchange); | ||
final HttpHandler delegate; | ||
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 = new BlockingHandler(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 @@ | ||
package com.stubbornjava.common.undertow.handlers.diagnostic; | ||
import java.time.Duration; | ||
import java.util.concurrent.ThreadLocalRandom; | ||
import java.util.concurrent.TimeUnit; | ||
import io.undertow.server.HttpHandler; | ||
public class DiagnosticHandlers { | ||
// {{start:delayedHandler}} | ||
/** | ||
* Add a fixed delay before execution of the next handler | ||
* @param next | ||
* @param duration | ||
* @param unit | ||
* @return | ||
*/ | ||
public static DelayedExecutionHandler fixedDelay(HttpHandler next, | ||
long duration, | ||
TimeUnit unit) { | ||
return new DelayedExecutionHandler( | ||
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 | ||
*/ | ||
public static DelayedExecutionHandler randomDelay(HttpHandler next, | ||
long minDuration, | ||
long maxDuration, | ||
TimeUnit unit) { | ||
return new DelayedExecutionHandler( | ||
next, (exchange) -> { | ||
long duration = ThreadLocalRandom.current() | ||
.nextLong(minDuration, maxDuration); | ||
return Duration.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 @@ | ||
package com.stubbornjava.common.undertow.handlers.diagnostic; | ||
import static org.junit.Assert.assertTrue; | ||
import java.util.List; | ||
import java.util.concurrent.Callable; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.Future; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.IntStream; | ||
import org.jooq.lambda.Seq; | ||
import org.jooq.lambda.Unchecked; | ||
import org.junit.Assert; | ||
import org.junit.Test; | ||
import com.google.common.base.Stopwatch; | ||
import com.google.common.util.concurrent.MoreExecutors; | ||
import com.stubbornjava.common.Http; | ||
import com.stubbornjava.common.HttpClient; | ||
import com.stubbornjava.common.undertow.Exchange; | ||
import com.stubbornjava.common.undertow.UndertowUtil; | ||
import com.stubbornjava.common.undertow.handlers.CustomHandlers; | ||
import com.stubbornjava.undertow.handlers.MiddlewareBuilder; | ||
import io.undertow.Undertow; | ||
import io.undertow.server.HttpHandler; | ||
import io.undertow.server.handlers.BlockingHandler; | ||
import okhttp3.OkHttpClient; | ||
import okhttp3.Response; | ||
public class DelayedExecutionHandlerTest { | ||
// Delay for 500ms then return "ok" | ||
private static final DelayedExecutionHandler delayedHandler = | ||
DiagnosticHandlers.fixedDelay((exchange) -> { | ||
Exchange.body().sendText(exchange, "ok"); | ||
}, | ||
500, TimeUnit.MILLISECONDS); | ||
@Test | ||
public void testOnXIoThread() throws InterruptedException { | ||
int numThreads = 10; | ||
run(delayedHandler, numThreads); | ||
} | ||
@Test | ||
public void testOnWorkerThread() throws InterruptedException { | ||
int numThreads = 10; | ||
run(new BlockingHandler(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 | ||
*/ | ||
private void run(HttpHandler handler, int numThreads) throws InterruptedException { | ||
HttpHandler route = MiddlewareBuilder.begin(CustomHandlers::accessLog) | ||
.complete(handler); | ||
Undertow.Builder builder = Undertow.builder() | ||
.setWorkerThreads(1) | ||
.setIoThreads(1); | ||
UndertowUtil.useLocalServer(builder, route, host -> { | ||
ExecutorService exec = Executors.newFixedThreadPool(numThreads); | ||
OkHttpClient client = new OkHttpClient().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. | ||
Stopwatch sw = 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); | ||
}); | ||
} | ||
private static void assertSuccess(Response response) { | ||
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.