mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): SIGTERM container before closing runtime API socket (#2098)
* fix(lambda): SIGTERM container before closing runtime API socket
Real AWS Lambda tears an execution environment down by sending SIGTERM
to the runtime while the runtime API stays responsive; the runtime
library (awslambdaric, Node.js RIC, ...) sees the signal and exits
cleanly on the OS default handler. Floci closed the runtime API socket
first, causing the parked /invocation/next long-poll to wake with a
network error before SIGTERM could reach the process — the runtime
library treated that as a fault and printed a ~40-line traceback on
every clean invocation.
Split RuntimeApiServer.stop() into quiesce() (settle bookkeeping,
notify extensions, complete pending/in-flight invocations) and close()
(release the httpServer socket). Reorder ContainerLauncher.stop() to
quiesce → docker stop → close, so the runtime process receives SIGTERM
against a still-bound socket and exits cleanly. Parked runtime pollers
now stay parked through quiesce() rather than receiving an
AWS-undocumented 204, matching real Lambda behaviour where a shutting
runtime is expected to exit on SIGTERM without the API side responding.
Docker's stop timeout is now selected from AWS's documented
Shutdown-phase grace tiers: 2s when at least one extension is
registered, 1s (rounding up AWS's 300ms runtime sub-budget) otherwise.
Closes #2091
* fix(lambda): populate inFlight under lock to close teardown race
enqueue() and the /invocation/next handler polled the parked ctx or
pending invocation inside the server lock, then dispatched
sendInvocation() asynchronously on the Vert.x context. inFlight was
populated inside sendInvocation, after the lock had been released — so
a concurrent quiesce() could sweep pendingQueue and inFlight (both
empty at that instant) and miss an invocation that was already in
flight from the caller's perspective. The invocation's future would
then never complete, and the caller would hang until the function's
deadline.
Move inFlight.put(...) into the same synchronized block as the poll,
so quiesce()'s sweep and enqueue's dispatch are ordered by the lock.
sendInvocation still does its inFlight.put — now a same-value overwrite
in the fast path, and the source of truth for the slow path where
inFlight.put runs earlier than the ctx write does.
Add two property tests exercising the race window: one where enqueue()
hands the invocation to a parked poller, one where NEXT_PATH polls
from pendingQueue, both followed by an immediate stop().
* fix(lambda): drop deferred dispatch if quiesce completed the invocation
After enqueue() records an invocation in inFlight and hands it to a
parked poller, the actual sendInvocation() runs on a deferred Vert.x
context. If quiesce() lands between the two, it sweeps inFlight and
completes the caller's future with ContainerStopped — but the deferred
callback would still deliver the invocation to the runtime, which
would execute the handler (side effects) and POST /response into a
future that's already completed. CompletableFuture silently discards
the second complete(), so the caller sees an error even though the
function ran and succeeded.
Re-check `stopped && inFlight.get(requestId) == null` inside the lock
before dispatching, and skip the dispatch if so. Applies to both entry
points: enqueue()'s deferred sendInvocation and NEXT_PATH's
synchronous-but-post-lock-release sendInvocation.
Add a property test that parks a poller, enqueues, immediately stops,
and asserts the poller does NOT receive a 200 with the invocation
payload — only a socket close from close() is acceptable.
* fix(lambda): make quiesce's inFlight sweep atomic under lock
The dispatch guards in enqueue()'s deferred callback and NEXT_PATH read
`stopped` under the server lock. Their correctness relies on the
invariant: once quiesce() releases its lock, stopped=true implies
inFlight is empty. The prior code cleared inFlight *outside* the lock,
which left a window where a dispatch could observe stopped=true while
an inFlight entry it's about to deliver was still present — the guard
would let the delivery through, quiesce would then complete the future
with ContainerStopped, and the runtime's /response would be silently
discarded.
Snapshot inFlight inside the lock (symmetric with pendingQueue two
lines above), complete futures outside. Dispatch guards simplified to
just `stopped` since the atomicity now holds by construction. Drop
sendInvocation's redundant inFlight.put — both entry points pre-insert
under the lock.
Also:
- Narrow ContainerLauncher.stop()'s timeout comment: docker's --time is
a max wait for PID 1, not a grace floor. Extensions run as sibling
`docker exec`s and are killed with the container; the 2s ceiling
doesn't back the deadlineMs advertised to extensions.
- Fix javadoc placement: hasRegisteredExtensions() had accidentally
inherited isFaulted()'s comment. Give each its own doc.
Add quiesceAtomicallyClearsInFlightWithStopped test: multiple in-flight
invocations → quiesce → all futures must complete with ContainerStopped.
* fix(lambda): reconcile with #2156 write-flush + trim comments
#2156 landed the "await parked writes before httpServer.close" pattern
for extension SHUTDOWN dispatches. Reconcile our teardown split with
that: quiesce() schedules extension SHUTDOWN dispatches and records
their aggregate flush completion in a new field extensionWritesFlushed;
close() awaits that field before dropping the httpServer.
Preserves both behaviours: SIGTERM-before-socket-close ordering (this
PR's core value) and the write-flush guarantee (#2156's contribution).
Runtime pollers still stay parked — no 204 — matching real AWS Lambda's
teardown. Trim design-doc-shaped comments to reviewer-friendly length
in the same file.
* test(lambda): add deterministic race tests via test-specific subclass
The three sleep-based race tests (removed here) don't distinguish the
fix from the pre-fix code — they exercise the interleaving with
Thread.sleep and pass either way. Replace them with two latch-gated
tests that reproduce the exact interleaving hampsterx flagged
(enqueue's deferred dispatch, and NEXT_PATH's synchronous dispatch,
each racing against a partially-swept quiesce) and prove the guards
plus atomic inFlight sweep close the silent-discard bug.
The tests use the "test-specific subclass" pattern (Meszaros, xUnit
Test Patterns) rather than a settable-field hook on the production
class: quiesce() and the two dispatch sites call three empty
`protected void` methods that a test subclass overrides to gate on
CountDownLatches. Production has no mutable state, no volatile reads,
and matches Floci's existing `Test-only:` javadoc convention
(ContainerLauncher, LambdaService, LambdaConcurrencyLimiter, ...).
Verified: reverting the atomic-sweep-in-lock fix AND the guard
simplification causes both new tests to fail with the expected
"parked poller received the invocation" assertion. Restoring either
fix alone is enough for the tests to pass, confirming they gate on
the invariant that matters (stopped=true ⇒ inFlight empty).
* fix(lambda): commit enqueue dispatch/requeue decision atomically
Per @abanna's review of #2098. enqueue()'s deferred callback read
waitingCtx.response().ended() twice — once inside `synchronized(lock)`
deciding requeue, once outside deciding send. A client disconnect
between the two reads left neither branch firing and the invocation
stranded in inFlight until the function deadline.
Read ended() exactly once inside the lock and commit dispatch/requeue
before releasing. Adds a deterministic latch-gated race test (two new
Test-only protected seams) that fails on the double-read shape and
passes on the fix. 50/50 tests pass.
* fix(lambda): requeue invocation when sendInvocation's write fails
Per Greptile's P1 review of a1a659b4. Even with the atomic dispatch
decision, a runtime disconnect between the lock-committed decision and
the .end() flush left the invocation stranded in inFlight until the
function deadline — the fluent chain has no failure handler.
Wrap the fluent chain in try/catch (setStatusCode/putHeader throw
synchronously on an already-ended response) and attach .onFailure to
.end() (which returns a failed Future for socket-level failures). Both
paths funnel into one handler that requeues into pendingQueue and drops
the stale inFlight entry — mirror of the ctx-ended branch in enqueue()'s
deferred callback. No-op if quiesce() beat us (stopped=true).
Adds a deterministic test that ends the parked ctx from
beforeSendInvocationWrite and asserts pendingQueueSize=1 + inFlightSize=0.
Fails on the pre-fix write-and-forget shape, passes on the fix. 51/51.
This commit is contained in:
1 parent
a235b76835
commit
b911ccd013
4 files changed
+691
-90
No files matched your search
+374
-6
@@ -20,6 +20,7 @@ import java.net.http.HttpResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -67,6 +68,22 @@ class RuntimeApiServerTest {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls until at least {@code count} runtime pollers have parked in the server's
|
||||
* {@code waitingContexts}. Replaces Thread.sleep-based waits so tests don't guess
|
||||
* how long the client-side TCP connect + server-side park sequence takes.
|
||||
*/
|
||||
private void awaitWaitingContexts(int count) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + 5000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
if (server.waitingContextsSize() >= count) return;
|
||||
Thread.sleep(10);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"expected at least " + count + " parked /next poller(s); got "
|
||||
+ server.waitingContextsSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void nextEndpoint_blocksUntilInvocationArrives() throws Exception {
|
||||
@@ -245,9 +262,325 @@ class RuntimeApiServerTest {
|
||||
assertTrue(payload.contains("ContainerStopped"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the default {@code server} with a subclass whose test-only overrides
|
||||
* gate the four race points on the caller-supplied Runnables. Used only by the
|
||||
* race tests below; other tests keep the plain server. Rebinds the port because
|
||||
* start() binds on construction.
|
||||
*/
|
||||
private void installGatedServer(Runnable beforeEnqueueDispatch,
|
||||
Runnable beforeNextPathGuard,
|
||||
Runnable afterQuiesceStoppedFlag) throws Exception {
|
||||
server.stop().get(5, TimeUnit.SECONDS);
|
||||
port = findFreePort();
|
||||
server = new RuntimeApiServer(vertx, port) {
|
||||
@Override protected void beforeEnqueueDeferredDispatch() { beforeEnqueueDispatch.run(); }
|
||||
@Override protected void beforeNextPathDispatchGuard() { beforeNextPathGuard.run(); }
|
||||
@Override protected void afterQuiesceStoppedFlagSet() { afterQuiesceStoppedFlag.run(); }
|
||||
};
|
||||
server.start().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant of {@link #installGatedServer} for the ctx-ends-during-dispatch race:
|
||||
* inject state after enqueue()'s dispatch lock is released, observe whether
|
||||
* sendInvocation subsequently ran.
|
||||
*/
|
||||
private void installGatedServerWithDispatchObservation(
|
||||
java.util.function.Consumer<io.vertx.ext.web.RoutingContext> afterEnqueueLockReleased,
|
||||
java.util.function.Consumer<String> onSendInvocation) throws Exception {
|
||||
server.stop().get(5, TimeUnit.SECONDS);
|
||||
port = findFreePort();
|
||||
server = new RuntimeApiServer(vertx, port) {
|
||||
@Override protected void afterEnqueueDispatchLockReleased(io.vertx.ext.web.RoutingContext waitingCtx) {
|
||||
afterEnqueueLockReleased.accept(waitingCtx);
|
||||
}
|
||||
@Override protected void beforeSendInvocationWrite(String requestId) {
|
||||
onSendInvocation.accept(requestId);
|
||||
}
|
||||
};
|
||||
server.start().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void stopWakesParkedPollerImmediately() throws Exception {
|
||||
void enqueueDeferredDispatch_racedByQuiesce_doesNotDeliverAfterSweep() throws Exception {
|
||||
// The dispatch guard is only sound if quiesce()'s inFlight sweep is atomic
|
||||
// with stopped=true under the lock. Prove that by driving the exact
|
||||
// interleaving the pre-hampsterx-fix code exposed. Sequence:
|
||||
//
|
||||
// 1. Park a /next poller server-side; enqueue an invocation → puts inv into
|
||||
// inFlight under the lock, schedules a deferred sendInvocation on the
|
||||
// event loop.
|
||||
// 2. The deferred dispatch fires but blocks on `holdDispatch` before it
|
||||
// can reach the guard's stopped-recheck.
|
||||
// 3. Run quiesce() on a background thread. Sets stopped=true, sweeps
|
||||
// inFlight (atomically, under fix) or defers it (pre-fix), releases
|
||||
// lock. Blocks at afterQuiesceStoppedFlagSet.
|
||||
// 4. Release `holdDispatch`. Guard reads `stopped`: under the fix, sees
|
||||
// atomically-cleared state and skips. Under the pre-fix code, sweep
|
||||
// hasn't run outside the lock yet — old guard `stopped && inFlight
|
||||
// .get(id)==null` would be false and dispatch would deliver.
|
||||
// 5. Release quiesce.
|
||||
//
|
||||
// Assertion: parked client MUST NOT have received a 200 with our request-id.
|
||||
CountDownLatch dispatchEntered = new CountDownLatch(1);
|
||||
CountDownLatch holdDispatch = new CountDownLatch(1);
|
||||
CountDownLatch quiesceReachedHook = new CountDownLatch(1);
|
||||
CountDownLatch releaseQuiesce = new CountDownLatch(1);
|
||||
installGatedServer(
|
||||
() -> {
|
||||
dispatchEntered.countDown();
|
||||
try { holdDispatch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
},
|
||||
() -> { /* NEXT_PATH not exercised here */ },
|
||||
() -> {
|
||||
quiesceReachedHook.countDown();
|
||||
try { releaseQuiesce.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
|
||||
HttpRequest parkedRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build();
|
||||
CompletableFuture<HttpResponse<String>> parkedResponse =
|
||||
httpClient.sendAsync(parkedRequest, HttpResponse.BodyHandlers.ofString());
|
||||
awaitWaitingContexts(1);
|
||||
|
||||
PendingInvocation invocation = new PendingInvocation(
|
||||
"req-latch-enqueue", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
server.enqueue(invocation);
|
||||
assertTrue(dispatchEntered.await(5, TimeUnit.SECONDS),
|
||||
"deferred dispatch should have entered the pre-guard hook");
|
||||
|
||||
// Kick off quiesce on a background thread; it will freeze at the post-lock hook.
|
||||
CompletableFuture<Void> quiesceDone = CompletableFuture.runAsync(() -> server.quiesce());
|
||||
assertTrue(quiesceReachedHook.await(5, TimeUnit.SECONDS),
|
||||
"quiesce should have released its lock and reached the post-lock hook");
|
||||
|
||||
// NOW release the dispatch while quiesce is frozen post-lock — the exact window
|
||||
// the pre-fix code was vulnerable in. Guard's `stopped=true` under fix must
|
||||
// atomically imply inFlight empty.
|
||||
holdDispatch.countDown();
|
||||
// Give the guard time to run (blocking on releaseQuiesce first).
|
||||
Thread.sleep(200);
|
||||
releaseQuiesce.countDown();
|
||||
quiesceDone.get(5, TimeUnit.SECONDS);
|
||||
|
||||
try {
|
||||
HttpResponse<String> response = parkedResponse.get(2, TimeUnit.SECONDS);
|
||||
assertFalse(response.statusCode() == 200
|
||||
&& "req-latch-enqueue".equals(response.headers()
|
||||
.firstValue("Lambda-Runtime-Aws-Request-Id").orElse("")),
|
||||
"guard failed: parked poller received the invocation after quiesce; "
|
||||
+ "would cause silent discard of /response. Got "
|
||||
+ response.statusCode());
|
||||
} catch (Exception expected) {
|
||||
// socket close from tearDown — expected shape.
|
||||
}
|
||||
InvokeResult result = invocation.getResultFuture().get(2, TimeUnit.SECONDS);
|
||||
assertEquals("Unhandled", result.getFunctionError());
|
||||
assertTrue(new String(result.getPayload()).contains("ContainerStopped"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void nextPathDispatch_racedByQuiesce_doesNotDeliverAfterSweep() throws Exception {
|
||||
// Symmetric to the enqueue race but on NEXT_PATH: an invocation sits in
|
||||
// pendingQueue. The handler polls it out under the lock, moves to inFlight,
|
||||
// releases lock, then reaches the guard. We hold the guard, run quiesce on
|
||||
// a background thread to freeze it post-lock, release the guard.
|
||||
CountDownLatch dispatchEntered = new CountDownLatch(1);
|
||||
CountDownLatch holdDispatch = new CountDownLatch(1);
|
||||
CountDownLatch quiesceReachedHook = new CountDownLatch(1);
|
||||
CountDownLatch releaseQuiesce = new CountDownLatch(1);
|
||||
installGatedServer(
|
||||
() -> { /* enqueue path not exercised here */ },
|
||||
() -> {
|
||||
dispatchEntered.countDown();
|
||||
try { holdDispatch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
quiesceReachedHook.countDown();
|
||||
try { releaseQuiesce.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
|
||||
PendingInvocation invocation = new PendingInvocation(
|
||||
"req-latch-nextpath", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
server.enqueue(invocation);
|
||||
|
||||
HttpRequest nextRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build();
|
||||
CompletableFuture<HttpResponse<String>> nextResponse =
|
||||
httpClient.sendAsync(nextRequest, HttpResponse.BodyHandlers.ofString());
|
||||
assertTrue(dispatchEntered.await(5, TimeUnit.SECONDS),
|
||||
"NEXT_PATH handler should have entered the pre-guard hook");
|
||||
|
||||
CompletableFuture<Void> quiesceDone = CompletableFuture.runAsync(() -> server.quiesce());
|
||||
assertTrue(quiesceReachedHook.await(5, TimeUnit.SECONDS),
|
||||
"quiesce should have released its lock and reached the post-lock hook");
|
||||
|
||||
holdDispatch.countDown();
|
||||
Thread.sleep(200);
|
||||
releaseQuiesce.countDown();
|
||||
quiesceDone.get(5, TimeUnit.SECONDS);
|
||||
|
||||
try {
|
||||
HttpResponse<String> response = nextResponse.get(2, TimeUnit.SECONDS);
|
||||
assertFalse(response.statusCode() == 200
|
||||
&& "req-latch-nextpath".equals(response.headers()
|
||||
.firstValue("Lambda-Runtime-Aws-Request-Id").orElse("")),
|
||||
"guard failed: /next received the invocation after quiesce; "
|
||||
+ "would cause silent discard of /response. Got "
|
||||
+ response.statusCode());
|
||||
} catch (Exception expected) {
|
||||
// socket close from tearDown — expected shape.
|
||||
}
|
||||
InvokeResult result = invocation.getResultFuture().get(2, TimeUnit.SECONDS);
|
||||
assertEquals("Unhandled", result.getFunctionError());
|
||||
assertTrue(new String(result.getPayload()).contains("ContainerStopped"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void enqueueDeferredDispatch_ctxEndsAfterLockRelease_dispatchesOrRequeuesAtomically() throws Exception {
|
||||
// Pre-fix, enqueue()'s deferred callback read waitingCtx.response().ended()
|
||||
// twice — once inside the lock deciding requeue, once outside deciding send.
|
||||
// A disconnect between the two reads made neither branch fire and stranded
|
||||
// the invocation in inFlight until the function deadline. Force that
|
||||
// interleaving by ending the ctx from afterEnqueueDispatchLockReleased.
|
||||
java.util.concurrent.atomic.AtomicInteger sendInvocationCalls =
|
||||
new java.util.concurrent.atomic.AtomicInteger();
|
||||
installGatedServerWithDispatchObservation(
|
||||
waitingCtx -> {
|
||||
if (!waitingCtx.response().ended()) {
|
||||
waitingCtx.response().setStatusCode(500).end();
|
||||
}
|
||||
},
|
||||
requestId -> sendInvocationCalls.incrementAndGet());
|
||||
|
||||
HttpRequest parkedRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build();
|
||||
httpClient.sendAsync(parkedRequest, HttpResponse.BodyHandlers.ofString());
|
||||
awaitWaitingContexts(1);
|
||||
|
||||
PendingInvocation invocation = new PendingInvocation(
|
||||
"req-ctx-ends", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
server.enqueue(invocation);
|
||||
|
||||
// Wait for the runOnContext-scheduled dispatch to have fired.
|
||||
Thread.sleep(500);
|
||||
|
||||
assertEquals(1, sendInvocationCalls.get(),
|
||||
"sendInvocation must run exactly once — a zero count means the "
|
||||
+ "invocation was stranded (the pre-fix stranded-inFlight bug).");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void sendInvocation_writeFails_requeuesAndClearsInFlight() throws Exception {
|
||||
// Post-atomic-decision race: disconnect between dispatch commitment and
|
||||
// .end() flush strands the invocation in inFlight. Force it by ending the
|
||||
// parked ctx from beforeSendInvocationWrite; assert onFailure requeues +
|
||||
// clears inFlight.
|
||||
java.util.concurrent.atomic.AtomicReference<io.vertx.ext.web.RoutingContext> parkedCtx =
|
||||
new java.util.concurrent.atomic.AtomicReference<>();
|
||||
server.stop().get(5, TimeUnit.SECONDS);
|
||||
port = findFreePort();
|
||||
server = new RuntimeApiServer(vertx, port) {
|
||||
@Override protected void afterEnqueueDispatchLockReleased(io.vertx.ext.web.RoutingContext waitingCtx) {
|
||||
parkedCtx.set(waitingCtx);
|
||||
}
|
||||
@Override protected void beforeSendInvocationWrite(String requestId) {
|
||||
io.vertx.ext.web.RoutingContext ctx = parkedCtx.get();
|
||||
if (ctx != null && !ctx.response().ended()) {
|
||||
ctx.response().setStatusCode(500).end();
|
||||
}
|
||||
}
|
||||
};
|
||||
server.start().get(5, TimeUnit.SECONDS);
|
||||
|
||||
HttpRequest parkedRequest = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build();
|
||||
httpClient.sendAsync(parkedRequest, HttpResponse.BodyHandlers.ofString());
|
||||
awaitWaitingContexts(1);
|
||||
|
||||
PendingInvocation invocation = new PendingInvocation(
|
||||
"req-write-fails", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
server.enqueue(invocation);
|
||||
|
||||
// Wait for the runOnContext-scheduled dispatch (and its failed write) to fire.
|
||||
Thread.sleep(500);
|
||||
|
||||
assertEquals(1, server.pendingQueueSize(),
|
||||
"invocation must be requeued after write failure — zero means stranded.");
|
||||
assertEquals(0, server.inFlightSize(),
|
||||
"inFlight must be cleared alongside the requeue.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void quiesceAtomicallyClearsInFlightWithStopped() throws Exception {
|
||||
// The dispatch guards in enqueue()'s deferred callback and NEXT_PATH read
|
||||
// `stopped` under the server lock and act on it. Their correctness depends on
|
||||
// an invariant: once quiesce() releases its lock, `stopped=true` implies
|
||||
// inFlight is empty. If quiesce() cleared inFlight *outside* the lock, a
|
||||
// dispatch could observe stopped=true while an inFlight entry it's about to
|
||||
// deliver was still present — the guard would let the delivery through,
|
||||
// quiesce would then complete the future with ContainerStopped, and the
|
||||
// runtime's /response would be silently discarded.
|
||||
//
|
||||
// Put entries in inFlight via full enqueue → /next round trips (matches the
|
||||
// real code path), then call quiesce and assert all their futures completed.
|
||||
List<PendingInvocation> invocations = new ArrayList<>();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
PendingInvocation inv = new PendingInvocation(
|
||||
"req-atomic-" + i, "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
server.enqueue(inv);
|
||||
invocations.add(inv);
|
||||
HttpResponse<String> resp = httpClient.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port
|
||||
+ "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, resp.statusCode());
|
||||
}
|
||||
|
||||
server.quiesce();
|
||||
|
||||
// quiesce() sets stopped=true AND clears inFlight in the same synchronized
|
||||
// block, so both observations are atomic. Every invocation must be completed.
|
||||
for (PendingInvocation inv : invocations) {
|
||||
InvokeResult result = inv.getResultFuture().get(2, TimeUnit.SECONDS);
|
||||
assertEquals("Unhandled", result.getFunctionError(),
|
||||
"invocation " + inv.getRequestId() + " must be completed by quiesce");
|
||||
assertTrue(new String(result.getPayload()).contains("ContainerStopped"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void closeTerminatesParkedPollerWithoutResponse() throws Exception {
|
||||
// GET /next on a background thread — parks in waitingContexts (no thread held).
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
@@ -260,14 +593,49 @@ class RuntimeApiServerTest {
|
||||
Thread.sleep(500);
|
||||
assertFalse(asyncResponse.isDone(), "handler should be parked");
|
||||
|
||||
// Quiesce leaves the parked poller alone — real Lambda relies on the container
|
||||
// process exiting on SIGTERM to terminate the poll, and the server can't send a
|
||||
// response that AWS doesn't document. close() then drops the underlying HTTP
|
||||
// server, terminating the parked poller's TCP connection from the server side
|
||||
// (the container-exit path in real usage).
|
||||
long start = System.currentTimeMillis();
|
||||
server.stop();
|
||||
HttpResponse<String> response = asyncResponse.get(2, TimeUnit.SECONDS);
|
||||
server.quiesce();
|
||||
server.close().get(2, TimeUnit.SECONDS);
|
||||
long elapsed = System.currentTimeMillis() - start;
|
||||
|
||||
// 204 is only valid on shutdown — the container is being terminated.
|
||||
assertEquals(204, response.statusCode());
|
||||
assertTrue(elapsed < 1000, "stop() should wake parked poller in <1s, took " + elapsed + "ms");
|
||||
// The client sees the socket close, surfacing as a completion exception on the
|
||||
// async future rather than a normal response. If quiesce() had (wrongly) responded
|
||||
// with a documented status code, the future would complete successfully instead.
|
||||
assertThrows(Exception.class, () -> asyncResponse.get(2, TimeUnit.SECONDS));
|
||||
assertTrue(elapsed < 3000, "close() should terminate parked poller in <3s, took " + elapsed + "ms");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void quiesceLeavesSocketOpenForOrderlyShutdown() throws Exception {
|
||||
// Real teardown is quiesce() → SIGTERM container → close(). The middle step
|
||||
// relies on the runtime API socket still being bound so the runtime process
|
||||
// (mid-poll on /invocation/next) can receive SIGTERM without seeing a
|
||||
// network error first. Verify that the port is still bound after quiesce().
|
||||
server.quiesce();
|
||||
|
||||
// A fresh connection can still reach the server. Handler will park it (server is
|
||||
// stopped, no work available) — we only care that the TCP handshake and HTTP
|
||||
// request-line get through, proving the listener is up.
|
||||
HttpRequest probe = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.timeout(java.time.Duration.ofMillis(500))
|
||||
.GET()
|
||||
.build();
|
||||
CompletableFuture<HttpResponse<String>> probeFuture =
|
||||
httpClient.sendAsync(probe, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
// The request should reach the server (parking there) rather than fail on connect.
|
||||
// Timing out on the client side proves the connection was accepted.
|
||||
assertThrows(Exception.class, () -> probeFuture.get(1, TimeUnit.SECONDS));
|
||||
|
||||
// Now close() should complete cleanly, releasing the port.
|
||||
server.close().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user