diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 03f7065528..4bca2ec14b 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -1076,6 +1076,19 @@ exist, and `AWS_LAMBDA_LOG_GROUP_NAME` names that group. Once a group is named, functions can share, each stream's name carries the function's name, as on AWS: `2026/10/16/my-fn[$LATEST]` rather than the default group's `2026/10/16/[$LATEST]`. +For a synchronous `Invoke`, `LogType=Tail` returns the last 4,096 bytes of that invocation's +standard output and standard error, base64-encoded in `X-Amz-Log-Result` (`LogResult` in +the SDK and CLI). The first invocation also includes initialization output. A warm +invocation's tail excludes earlier invocations in the same environment. `LogType=None`, +an omitted log type, `Event` and `DryRun` omit the header. CloudWatch log forwarding +continues independently. + +Warm invocation boundaries come from the Docker daemon's or kubelet's log timestamps, +so differences between Floci's clock and the log source's clock do not affect filtering. +Kubernetes snapshots also filter timestamps locally at nanosecond precision. Synchronous +durable invocations return a bounded tail across their handler invocations, including +logs produced after a checkpoint completes the execution and before the handler returns. + The execution environment gets `AWS_LAMBDA_LOG_FORMAT` from `LogFormat` and, under `LogFormat=JSON`, `AWS_LAMBDA_LOG_LEVEL` from `ApplicationLogLevel` (`INFO` when unset, the level the API reports). The runtime interface clients read both: a Python function writes each record as a JSON object, diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaController.java b/src/main/java/io/floci/aws/services/lambda/LambdaController.java index a604dec5ce..98cd8d4c76 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaController.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaController.java @@ -271,8 +271,13 @@ public class LambdaController { ? decodeClientContext(headers.getHeaderString("X-Amz-Client-Context")) : null; String durableExecutionName = headers.getHeaderString("X-Amz-Durable-Execution-Name"); - InvokeResult result = lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext, - durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id")); + boolean logTail = type == InvocationType.RequestResponse + && "Tail".equals(headers.getHeaderString("X-Amz-Log-Type")); + InvokeResult result = logTail + ? lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext, + durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id"), true) + : lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext, + durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id")); if (type != InvocationType.Event && result.getPayload() != null @@ -288,7 +293,7 @@ public class LambdaController { if (result.getFunctionError() != null) { builder.header("X-Amz-Function-Error", result.getFunctionError()); } - if (result.getLogResult() != null) { + if (logTail && result.getLogResult() != null) { builder.header("X-Amz-Log-Result", result.getLogResult()); } builder.header("X-Amz-Executed-Version", result.getExecutedVersion()); diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java index efc086aa2f..a5fd8e49df 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java @@ -21,6 +21,7 @@ import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.UncheckedIOException; import java.net.SocketException; import java.net.UnknownHostException; import java.time.Clock; @@ -37,6 +38,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; /** * Orchestrates Lambda function invocations. @@ -176,6 +178,11 @@ public class LambdaExecutorService implements Resettable { return invoke(fn, payload, type, 0, null, null, requestId, null, traceId); } + public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId, + String traceId, boolean logTail) { + return invoke(fn, payload, type, 0, null, null, requestId, null, traceId, logTail); + } + /** * Invokes {@code fn}, carrying the number of invocations that the same originating event has * already caused. A direct invoke starts at zero; each destination delivery adds one, whether @@ -201,6 +208,12 @@ public class LambdaExecutorService implements Resettable { null, null); } + InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, + String invokedQualifier, String clientContext, boolean logTail) { + return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString(), + null, null, logTail); + } + /** * A synchronous invocation whose response, if the runtime streams it, goes to {@code listener} * as it arrives rather than into the returned result. @@ -214,6 +227,12 @@ public class LambdaExecutorService implements Resettable { private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, String invokedQualifier, String clientContext, String requestId, ResponseStreamListener listener, String traceId) { + return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, requestId, listener, traceId, false); + } + + private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth, + String invokedQualifier, String clientContext, String requestId, + ResponseStreamListener listener, String traceId, boolean logTail) { if (type == InvocationType.DryRun) { return new InvokeResult(204, null, new byte[0], null, requestId); } @@ -265,7 +284,7 @@ public class LambdaExecutorService implements Resettable { } try { - return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId); + return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId, logTail); } finally { permit.close(); } @@ -321,7 +340,7 @@ public class LambdaExecutorService implements Resettable { } InvokeResult result; try (permit) { - result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null); + result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null, false); } catch (RuntimeException e) { LOG.warnv("Error in async Lambda execution for {0}: {1}", event.fn().getFunctionName(), e.getMessage()); // Stops retrying, as upstream did: routes the previous attempt's result, or UnknownError when @@ -399,7 +418,7 @@ public class LambdaExecutorService implements Resettable { private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId, String clientContext, String invokedQualifier, - ResponseStreamListener listener, String traceId) { + ResponseStreamListener listener, String traceId, boolean logTail) { ContainerHandle handle; try { handle = warmPool.acquireProvisioned(fn, invokedQualifier); @@ -423,7 +442,9 @@ public class LambdaExecutorService implements Resettable { boolean initializing = !runtimeApiServer.hasRuntimePolled(); long dispatchWaitMs = dispatchWaitMs(fn.getTimeout(), initializing, runtimeApiServer.getContainerStartedAtMs(), System.currentTimeMillis()); + Supplier logs = null; try { + logs = beginLogTail(handle, logTail); runtimeApiServer.enqueue(invocation); CompletableFuture.anyOf( @@ -431,6 +452,7 @@ public class LambdaExecutorService implements Resettable { .get(dispatchWaitMs, TimeUnit.MILLISECONDS); InvokeResult result = invocation.getResultFuture().get(); + includeLogTail(result, handle, logs); warmPool.release(handle); return result; @@ -447,10 +469,12 @@ public class LambdaExecutorService implements Resettable { } else { LOG.warnv("Function {0} timed out after {1}s", fn.getFunctionName(), fn.getTimeout()); } - warmPool.destroyHandle(handle); - return new InvokeResult(200, "Unhandled", + InvokeResult result = new InvokeResult(200, "Unhandled", buildErrorPayload("Task timed out after " + fn.getTimeout() + " seconds", "Function.TimedOut"), null, requestId); + includeLogTail(result, handle, logs); + warmPool.destroyHandle(handle); + return result; } LOG.warnv("Invocation error for function {0}: {1}", fn.getFunctionName(), cause.getMessage()); warmPool.destroyHandle(handle); @@ -459,6 +483,25 @@ public class LambdaExecutorService implements Resettable { } } + private Supplier beginLogTail(ContainerHandle handle, boolean requested) { + try { + return handle.beginInvocation(requested); + } catch (IllegalStateException | UncheckedIOException e) { + LOG.warnv(e, "Could not begin invocation log capture for function {0}", handle.getFunctionName()); + return null; + } + } + + private void includeLogTail(InvokeResult result, ContainerHandle handle, Supplier logs) { + if (logs != null) { + try { + result.setLogResult(logs.get()); + } catch (IllegalStateException | UncheckedIOException e) { + LOG.warnv(e, "Could not read invocation logs for function {0}", handle.getFunctionName()); + } + } + } + /** * How long an invocation waits for its runtime to take it. A runtime that has never polled /next * is still in its Init phase, which runs from its container's start for the Init budget; once the diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaService.java b/src/main/java/io/floci/aws/services/lambda/LambdaService.java index 5b386df5ea..eaef498b45 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -80,6 +80,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; @@ -1457,6 +1458,13 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload, InvocationType type, String clientContext, String durableExecutionName, String traceHeader) { + return invoke(region, functionName, queryQualifier, payload, type, clientContext, durableExecutionName, + traceHeader, false); + } + + public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload, + InvocationType type, String clientContext, String durableExecutionName, + String traceHeader, boolean logTail) { validateInvokeQualifier(queryQualifier); LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, queryQualifier); String name = ref.name(); @@ -1471,12 +1479,15 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { } reportCustomResourceLiveness(payload); InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type, - traceHeader); + traceHeader, logTail); if (durable != null) { return durable; } - InvokeResult result = executorService.invoke(fn, payload, type, - LambdaInvocationChain.currentDepth(), qualifier, clientContext); + InvokeResult result = logTail + ? executorService.invoke(fn, payload, type, + LambdaInvocationChain.currentDepth(), qualifier, clientContext, true) + : executorService.invoke(fn, payload, type, + LambdaInvocationChain.currentDepth(), qualifier, clientContext); result.setExecutedVersion(fn.getVersion()); return result; } @@ -1484,7 +1495,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { /** Null for a plain function, and for a DryRun, which only checks the qualifier. */ private InvokeResult invokeIfDurable(LambdaFunction fn, String region, String qualifier, String durableExecutionName, byte[] payload, InvocationType type, - String traceHeader) { + String traceHeader, boolean logTail) { if (!fn.isDurable()) { return null; } @@ -1495,7 +1506,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { if (type == InvocationType.DryRun) { return null; } - InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type, traceHeader); + InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type, traceHeader, logTail); result.setExecutedVersion(fn.getVersion()); return result; } @@ -1505,7 +1516,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { * limit. Event answers 202 as soon as the execution exists. */ private InvokeResult invokeDurable(LambdaFunction fn, String region, String executionName, byte[] payload, - InvocationType type, String traceHeader) { + InvocationType type, String traceHeader, boolean logTail) { boolean synchronous = type == InvocationType.RequestResponse; if (synchronous && fn.getDurableExecutionTimeout() > MAX_FUNCTION_TIMEOUT_SECONDS) { throw new AwsException("InvalidParameterValueException", @@ -1520,23 +1531,35 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { String input = payload == null || payload.length == 0 ? "{}" : new String(payload, StandardCharsets.UTF_8); DurableExecution execution = durableExecutionService.start(new DurableExecutionService.StartRequest( fn.getAccountId(), region, fn.getFunctionName(), fn.getVersion(), executionName, input, synchronous, - traceHeader)); + traceHeader, logTail)); String requestId = UUID.randomUUID().toString(); InvokeResult result; if (!synchronous) { result = new InvokeResult(202, null, new byte[0], null, requestId); } else { - result = awaitDurableResult(execution.getExecutionArn(), requestId); + try { + result = awaitDurableResult(execution.getExecutionArn(), requestId, logTail); + } finally { + if (logTail) { + durableExecutionService.releaseInvocationLogs(execution.getExecutionArn()); + } + } } result.setDurableExecutionArn(execution.getExecutionArn()); return result; } - private InvokeResult awaitDurableResult(String executionArn, String requestId) { - DurableExecution finished; + private InvokeResult awaitDurableResult(String executionArn, String requestId, boolean logTail) { try { // A little past the limit, so an execution that times out at 900 s reports its own error. - finished = durableExecutionService.awaitCompletion(executionArn) + return durableExecutionService.awaitCompletion(executionArn) + .thenCompose(finished -> { + InvokeResult result = durableResult(finished, requestId); + return logTail ? durableExecutionService.invocationLogs(executionArn).thenApply(logs -> { + result.setLogResult(logs); + return result; + }) : CompletableFuture.completedFuture(result); + }) .get(MAX_FUNCTION_TIMEOUT_SECONDS + SYNC_DURABLE_GRACE_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { return unhandledDurableResult(DurableErrorObject.of( @@ -1549,6 +1572,9 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { return unhandledDurableResult(DurableErrorObject.of( e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), "InvocationError"), requestId); } + } + + private InvokeResult durableResult(DurableExecution finished, String requestId) { if (finished.getStatus() == DurableExecutionStatus.SUCCEEDED) { byte[] body = finished.getResult() == null ? new byte[0] : finished.getResult().getBytes(StandardCharsets.UTF_8); @@ -1605,7 +1631,7 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn); LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount( arn.accountId(), arn.region(), ref.name(), ref.qualifier()); - InvokeResult durable = invokeIfDurable(fn, arn.region(), ref.qualifier(), null, payload, type, null); + InvokeResult durable = invokeIfDurable(fn, arn.region(), ref.qualifier(), null, payload, type, null, false); if (durable != null) { return durable; } diff --git a/src/main/java/io/floci/aws/services/lambda/durable/DurableExecutionService.java b/src/main/java/io/floci/aws/services/lambda/durable/DurableExecutionService.java index c869bbaa90..7b8eaae801 100644 --- a/src/main/java/io/floci/aws/services/lambda/durable/DurableExecutionService.java +++ b/src/main/java/io/floci/aws/services/lambda/durable/DurableExecutionService.java @@ -91,6 +91,7 @@ public class DurableExecutionService implements Resettable { private final Object[] executionLocks = newLocks(LOCK_STRIPES); private final ConcurrentHashMap startLocks = new ConcurrentHashMap<>(); private final ConcurrentHashMap> completions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap logCaptures = new ConcurrentHashMap<>(); /** Moves on reset and shutdown so an invocation result from before cannot be written afterwards. */ private final AtomicLong generation = new AtomicLong(); @@ -116,7 +117,11 @@ public class DurableExecutionService implements Resettable { public record StartRequest(String accountId, String region, String functionName, String qualifier, String executionName, String inputPayload, boolean synchronous, - String traceHeader) { + String traceHeader, boolean logTail) { + public StartRequest(String accountId, String region, String functionName, String qualifier, + String executionName, String inputPayload, boolean synchronous, String traceHeader) { + this(accountId, region, functionName, qualifier, executionName, inputPayload, synchronous, traceHeader, false); + } } public record ListRequest(String accountId, String region, String functionName, String version, @@ -158,17 +163,41 @@ public class DurableExecutionService implements Resettable { throw new AwsException("DurableExecutionAlreadyStartedException", "Execution already started: " + existing.get().getExecutionArn(), 409); } + captureLogs(request, existing.get()); return existing.get(); } long now = clock.millis(); execution = newExecution(request, target, name, now); trigger(execution, effects); store.putForAccount(request.accountId(), storeKey(execution), execution); + captureLogs(request, execution); } runEffects(effects); return execution; } + private void captureLogs(StartRequest request, DurableExecution execution) { + if (request.synchronous() && request.logTail()) { + logCaptures.compute(execution.getExecutionArn(), (arn, existing) -> { + DurableInvocationLogs logs = existing != null ? existing : new DurableInvocationLogs(); + logs.acquire(); + return logs; + }); + } + } + + public CompletableFuture invocationLogs(String executionArn) { + DurableInvocationLogs logs = logCaptures.get(executionArn); + return logs == null ? CompletableFuture.completedFuture("") : logs.snapshot(); + } + + public void releaseInvocationLogs(String executionArn) { + logCaptures.computeIfPresent(executionArn, (arn, logs) -> { + logs.release(); + return logs.unused() ? null : logs; + }); + } + public CompletableFuture awaitCompletion(String executionArn) { ArnParts arn = parseArn(executionArn); synchronized (lockFor(arn)) { @@ -523,11 +552,15 @@ public class DurableExecutionService implements Resettable { waiter.completeExceptionally(new AwsException("ResourceNotFoundException", NOT_FOUND, 404)); } completions.clear(); + logCaptures.values().forEach(DurableInvocationLogs::cancel); + logCaptures.clear(); } @PreDestroy void shutdown() { generation.incrementAndGet(); + logCaptures.values().forEach(DurableInvocationLogs::cancel); + logCaptures.clear(); } // ──────────────────────────── invocation lane ──────────────────────────── @@ -551,6 +584,8 @@ public class DurableExecutionService implements Resettable { byte[] payload; String traceId = null; long startedAt; + DurableInvocationLogs logs; + String logArn; synchronized (lockFor(accountId, key)) { DurableExecution execution = store.getForAccount(accountId, key).orElse(null); if (execution == null || execution.isClosed() || launchGeneration != generation.get() @@ -575,13 +610,20 @@ public class DurableExecutionService implements Resettable { } // The event carries every operation, so the handler has now seen everything up to here. execution.setSeenSequence(execution.getChangeSequence()); + logArn = execution.getExecutionArn(); + logs = logCaptures.get(logArn); + if (logs != null) { + logs.beginInvocation(); + } } DurableInvocationResult result; if (target == null) { result = new DurableInvocationResult(null, null, "ResourceNotFoundException"); } else { try { - result = invoker.invoke(target, payload, invocationId, traceId); + result = logs != null + ? invoker.invoke(target, payload, invocationId, traceId, true) + : invoker.invoke(target, payload, invocationId, traceId); } catch (AwsException e) { result = new DurableInvocationResult(null, DurableWire.functionErrorPayload( DurableErrorObject.of(e.getMessage(), e.getErrorCode())), @@ -593,6 +635,11 @@ public class DurableExecutionService implements Resettable { "InvocationError"); } } + if (logs != null) { + logs.complete(result.logResult()); + logCaptures.computeIfPresent(logArn, (arn, current) -> + current == logs && logs.unused() ? null : current); + } List effects = new ArrayList<>(); synchronized (lockFor(accountId, key)) { DurableExecution execution = store.getForAccount(accountId, key).orElse(null); diff --git a/src/main/java/io/floci/aws/services/lambda/durable/DurableFunctionInvoker.java b/src/main/java/io/floci/aws/services/lambda/durable/DurableFunctionInvoker.java index 0830ff4f06..b8fbac8ecd 100644 --- a/src/main/java/io/floci/aws/services/lambda/durable/DurableFunctionInvoker.java +++ b/src/main/java/io/floci/aws/services/lambda/durable/DurableFunctionInvoker.java @@ -12,6 +12,11 @@ public interface DurableFunctionInvoker { DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, String traceId); + default DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, + String traceId, boolean logTail) { + return invoke(target, payload, requestId, traceId); + } + record ResolvedDurableTarget(String accountId, String region, String functionName, @@ -23,6 +28,9 @@ public interface DurableFunctionInvoker { boolean activeTracing) { } - record DurableInvocationResult(String requestId, byte[] payload, String functionError) { + record DurableInvocationResult(String requestId, byte[] payload, String functionError, String logResult) { + public DurableInvocationResult(String requestId, byte[] payload, String functionError) { + this(requestId, payload, functionError, null); + } } } diff --git a/src/main/java/io/floci/aws/services/lambda/durable/DurableInvocationLogs.java b/src/main/java/io/floci/aws/services/lambda/durable/DurableInvocationLogs.java new file mode 100644 index 0000000000..f168a275c9 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/durable/DurableInvocationLogs.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.lambda.durable; + +import io.floci.aws.services.lambda.launcher.InvocationLogTail; + +import java.util.concurrent.CompletableFuture; + +/** Transient log capture shared by synchronous Tail callers attached to one durable execution. */ +final class DurableInvocationLogs { + + private final InvocationLogTail tail = new InvocationLogTail(); + private CompletableFuture pending = CompletableFuture.completedFuture(null); + private int callers; + + synchronized void acquire() { + callers++; + } + + synchronized void release() { + callers--; + } + + synchronized boolean unused() { + return callers == 0 && pending.isDone(); + } + + synchronized void beginInvocation() { + pending = new CompletableFuture<>(); + } + + void complete(String encodedLogs) { + CompletableFuture finished; + synchronized (this) { + tail.appendEncoded(encodedLogs); + finished = pending; + } + finished.complete(null); + } + + synchronized CompletableFuture snapshot() { + return pending.thenApply(ignored -> encoded()); + } + + private synchronized String encoded() { + return tail.encoded(); + } + + synchronized void cancel() { + pending.cancel(false); + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionInvoker.java b/src/main/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionInvoker.java index c54a69249e..d06a0a8d00 100644 --- a/src/main/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionInvoker.java +++ b/src/main/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionInvoker.java @@ -41,10 +41,19 @@ public class LambdaDurableFunctionInvoker implements DurableFunctionInvoker { @Override public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, String traceId) { + return invoke(target, payload, requestId, traceId, false); + } + + @Override + public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, + String traceId, boolean logTail) { LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount(target.accountId(), target.region(), target.functionName(), target.version()); InvokeResult result = RequestScopes.callAs(target.accountId(), - () -> executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId)); - return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError()); + () -> logTail + ? executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId, true) + : executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId)); + return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError(), + result.getLogResult()); } } diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerHandle.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerHandle.java index 0f4da26d0d..4d4f588745 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerHandle.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerHandle.java @@ -4,6 +4,9 @@ import io.floci.aws.services.lambda.model.ContainerState; import io.floci.aws.services.lambda.runtime.RuntimeApiServer; import java.io.Closeable; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Supplier; /** * Wraps a running Lambda Docker container and its associated Runtime API server. @@ -20,6 +23,8 @@ public class ContainerHandle { private volatile ContainerState state; private volatile long lastUsedMs; private Closeable logStream; + private Function> logTailReader = initialization -> () -> ""; + private final AtomicBoolean invoked = new AtomicBoolean(); public ContainerHandle(String containerId, String functionName, RuntimeApiServer runtimeApiServer, ContainerState state) { @@ -60,6 +65,14 @@ public class ContainerHandle { public Closeable getLogStream() { return logStream; } public void setLogStream(Closeable logStream) { this.logStream = logStream; } + public void setLogTailReader(Function> reader) { this.logTailReader = reader; } + + /** The first invocation also owns the environment's initialization logs. */ + public Supplier beginInvocation(boolean captureLogs) { + boolean initialization = !invoked.getAndSet(true); + return captureLogs ? logTailReader.apply(initialization) : null; + } + /** * True once an extension in this container reported an init or exit error. Real AWS treats * both as fatal to the execution environment, so {@code WarmPool} must retire the container diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java index ef2162de31..af31e83fd2 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java @@ -516,6 +516,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { lambdaAccountId, containerId, cwLogGroup, cwLogStream, lambdaRegion, "lambda:" + fn.getFunctionName()); handle.setLogStream(logHandle); + handle.setLogTailReader(initialization -> InvocationLogTail.captureDocker(dockerClient, handle.getContainerId(), initialization)); return handle; } catch (RuntimeException e) { diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/InvocationLogTail.java b/src/main/java/io/floci/aws/services/lambda/launcher/InvocationLogTail.java new file mode 100644 index 0000000000..17fb0789f0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/launcher/InvocationLogTail.java @@ -0,0 +1,179 @@ +package io.floci.aws.services.lambda.launcher; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.exception.DockerException; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Base64; +import java.util.EnumMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** A byte-bounded invocation log snapshot, independent of asynchronous CloudWatch forwarding. */ +public final class InvocationLogTail { + + static final int LIMIT = 4096; + private final byte[] tail = new byte[LIMIT]; + private int position; + private int size; + private final TimestampedParser parser = new TimestampedParser(); + private Instant lastTimestamp = Instant.EPOCH; + + public static Supplier captureDocker(DockerClient docker, String containerId, boolean initialization) { + Instant since = initialization ? Instant.EPOCH + : dockerSnapshot(docker, containerId, Instant.EPOCH, 1).lastTimestamp().plusNanos(1); + return () -> readDocker(docker, containerId, since); + } + + public static String readDocker(DockerClient docker, String containerId, Instant since) { + return dockerSnapshot(docker, containerId, since, LIMIT).encoded(); + } + + private static InvocationLogTail dockerSnapshot(DockerClient docker, String containerId, Instant since, int lines) { + InvocationLogTail tail = new InvocationLogTail(); + Map parsers = new EnumMap<>(StreamType.class); + try (LogContainerCmd command = docker.logContainerCmd(containerId) + .withStdOut(true).withStdErr(true).withFollowStream(false).withTimestamps(true) + .withSince((int) Math.min(Integer.MAX_VALUE, since.getEpochSecond())).withTail(lines); + ResultCallback.Adapter callback = new ResultCallback.Adapter<>() { + @Override + public void onNext(Frame frame) { + parsers.computeIfAbsent(frame.getStreamType(), ignored -> tail.new TimestampedParser()) + .acceptFrame(frame.getPayload(), since); + } + }) { + if (!command.exec(callback).awaitCompletion(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out reading Lambda invocation logs"); + } + parsers.values().forEach(TimestampedParser::finish); + return tail; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted reading Lambda invocation logs", e); + } catch (IOException | DockerException e) { + throw new IllegalStateException("Could not read Lambda invocation logs", e); + } + } + + public static String read(InputStream logs) throws IOException { + InvocationLogTail tail = new InvocationLogTail(); + byte[] chunk = new byte[LIMIT]; + int count; + while ((count = logs.read(chunk)) != -1) { + tail.append(chunk, 0, count); + } + return tail.encoded(); + } + + public static InvocationLogTail readTimestamped(InputStream logs, Instant since) throws IOException { + InvocationLogTail tail = new InvocationLogTail(); + byte[] chunk = new byte[LIMIT]; + int count; + while ((count = logs.read(chunk)) != -1) { + tail.parser.accept(chunk, 0, count, since); + } + tail.parser.finish(); + return tail; + } + + public Instant lastTimestamp() { + return lastTimestamp; + } + + void appendTimestamped(byte[] bytes, Instant since) { + parser.accept(bytes, 0, bytes.length, since); + } + + public void appendEncoded(String logs) { + if (logs != null) { + byte[] bytes = Base64.getDecoder().decode(logs); + append(bytes, 0, bytes.length); + } + } + + void append(byte[] bytes, int offset, int length) { + int count = Math.min(length, LIMIT); + int start = offset + length - count; + int first = Math.min(count, LIMIT - position); + System.arraycopy(bytes, start, tail, position, first); + System.arraycopy(bytes, start + first, tail, 0, count - first); + position = (position + count) % LIMIT; + size = Math.min(LIMIT, size + count); + } + + public String encoded() { + parser.finish(); + byte[] bytes = new byte[size]; + int start = (position - size + LIMIT) % LIMIT; + int first = Math.min(size, LIMIT - start); + System.arraycopy(tail, start, bytes, 0, first); + System.arraycopy(tail, 0, bytes, first, size - first); + return Base64.getEncoder().encodeToString(bytes); + } + + private final class TimestampedParser { + private final byte[] prefix = new byte[40]; + private int prefixSize; + private boolean readingPrefix = true; + private boolean include; + + void acceptFrame(byte[] bytes, Instant since) { + // Docker timestamps each record, including records that continue an unterminated line. + // A prefix already in progress belongs to a transport-split record and must be retained. + readingPrefix = true; + accept(bytes, 0, bytes.length, since); + } + + void accept(byte[] bytes, int offset, int length, Instant since) { + int end = offset + length; + while (offset < end) { + if (readingPrefix) { + byte next = bytes[offset++]; + prefix[prefixSize++] = next; + if (next == ' ' || next == '\n' || prefixSize == prefix.length) { + try { + Instant timestamp = Instant.parse(new String(prefix, 0, prefixSize - 1, StandardCharsets.US_ASCII)); + include = !timestamp.isBefore(since); + if (timestamp.isAfter(lastTimestamp)) { + lastTimestamp = timestamp; + } + } catch (DateTimeParseException expected) { + // A log record can continue without a timestamp prefix. + if (include) { + append(prefix, 0, prefixSize); + } + } + prefixSize = 0; + readingPrefix = next == '\n'; + } + } else { + int next = offset; + while (next < end && bytes[next++] != '\n') { + // Append payload bytes in bulk, including any terminating newline. + } + if (include) { + append(bytes, offset, next - offset); + } + readingPrefix = bytes[next - 1] == '\n'; + offset = next; + } + } + } + + void finish() { + if (prefixSize > 0 && include) { + append(prefix, 0, prefixSize); + } + prefixSize = 0; + } + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesApiClient.java b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesApiClient.java index ff1faaec83..ac844214e5 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesApiClient.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesApiClient.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.floci.aws.services.lambda.launcher.InvocationLogTail; import jakarta.enterprise.context.ApplicationScoped; import javax.net.ssl.KeyManager; @@ -36,6 +37,8 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; @@ -199,9 +202,35 @@ public class KubernetesApiClient { * underlying connection and the kubelet stops the follow. */ public InputStream openPodLogStream(String namespace, String podName, String containerName) { + return openPodLogs(namespace, podName, containerName, "&follow=true"); + } + + public String readPodLogTail(String namespace, String podName, Instant since) { + return podLogSnapshot(namespace, podName, since, 4096).encoded(); + } + + public Supplier capturePodLogTail(String namespace, String podName, boolean initialization) { + Instant since = initialization ? Instant.EPOCH + : podLogSnapshot(namespace, podName, Instant.EPOCH, 1).lastTimestamp().plusNanos(1); + return () -> readPodLogTail(namespace, podName, since); + } + + private InvocationLogTail podLogSnapshot(String namespace, String podName, Instant since, int lines) { + String options = "&follow=false×tamps=true&tailLines=" + lines + "&sinceTime=" + + URLEncoder.encode(since.truncatedTo(ChronoUnit.SECONDS).toString(), StandardCharsets.UTF_8); + try (InputStream logs = openPodLogs(namespace, podName, "runtime", options)) { + return InvocationLogTail.readTimestamped(logs, since); + } catch (IOException e) { + throw new UncheckedIOException("Could not read invocation logs for pod " + podName, e); + } catch (KubernetesApiException e) { + throw new IllegalStateException("Could not read invocation logs for pod " + podName, e); + } + } + + private InputStream openPodLogs(String namespace, String podName, String containerName, String options) { ensureInitialized(); String path = podPath(namespace, podName) + "/log?container=" - + URLEncoder.encode(containerName, StandardCharsets.UTF_8) + "&follow=true"; + + URLEncoder.encode(containerName, StandardCharsets.UTF_8) + options; try { HttpResponse response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofInputStream()); if (response.statusCode() != 200) { diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java index 2fe5688b16..6ad6f6b453 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java @@ -226,6 +226,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { ContainerHandle handle = new ContainerHandle(podName, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, false); + handle.setLogTailReader(initialization -> client.capturePodLogTail(namespace, handle.getContainerId(), initialization)); // Log streaming is non-essential and runs after the pod is already Running, // so a failure here (e.g. a missing pods/log RBAC verb) must not tear down a // healthy execution environment. diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java index 83c490f417..3e35acb13b 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaExecutorServiceTest.java @@ -222,6 +222,64 @@ class LambdaExecutorServiceTest { assertNull(result.getFunctionError()); } + @Test + void requestedLogTailIsReadBeforeTheEnvironmentIsReleased() { + RuntimeApiServer runtime = mock(RuntimeApiServer.class); + ContainerHandle handle = new ContainerHandle("logs", "test-fn", runtime, ContainerState.WARM); + handle.setLogTailReader(initialization -> () -> { + verify(warmPool, never()).release(handle); + return "aGVsbG8K"; + }); + stubInvocationResult(handle, new InvokeResult(200, "Unhandled", "{}".getBytes(), null, "logs")); + + InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, 0, null, null, true); + + assertEquals("aGVsbG8K", result.getLogResult()); + assertEquals("Unhandled", result.getFunctionError()); + verify(warmPool).release(handle); + } + + @Test + void anInvocationWithoutTailDoesNotReadTheEnvironmentLogs() { + RuntimeApiServer runtime = mock(RuntimeApiServer.class); + ContainerHandle handle = new ContainerHandle("no-logs", "test-fn", runtime, ContainerState.WARM); + handle.setLogTailReader(initialization -> () -> { + throw new AssertionError("Logs were not requested"); + }); + stubInvocationResult(handle, new InvokeResult(200, null, "{}".getBytes(), null, "no-logs")); + + InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse); + + assertNull(result.getLogResult()); + verify(warmPool).release(handle); + } + + @Test + void aLogReadFailurePreservesTheFunctionResultAndReleasesItsEnvironment() { + RuntimeApiServer runtime = mock(RuntimeApiServer.class); + ContainerHandle handle = new ContainerHandle("bad-logs", "test-fn", runtime, ContainerState.WARM); + handle.setLogTailReader(initialization -> () -> { + throw new IllegalStateException("log driver unavailable"); + }); + stubInvocationResult(handle, new InvokeResult(200, null, "{}".getBytes(), null, "bad-logs")); + + InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, 0, null, null, true); + + assertEquals(200, result.getStatusCode()); + assertNull(result.getFunctionError()); + verify(warmPool).release(handle); + verify(warmPool, never()).destroyHandle(handle); + } + + private void stubInvocationResult(ContainerHandle handle, InvokeResult result) { + when(warmPool.acquire(fn)).thenReturn(handle); + doAnswer(call -> { + PendingInvocation invocation = call.getArgument(0); + invocation.getResultFuture().complete(result); + return invocation.getResultFuture(); + }).when(handle.getRuntimeApiServer()).enqueue(any()); + } + @Test void dispatchWait_coldRuntimeGetsTheInitBudget() { LambdaExecutorService withBudget = diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailDockerIntegrationTest.java new file mode 100644 index 0000000000..c1b2de4335 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailDockerIntegrationTest.java @@ -0,0 +1,112 @@ +package io.floci.aws.services.lambda; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.LambdaCodeFixtures; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.FunctionCode; +import software.amazon.awssdk.services.lambda.model.InvocationType; +import software.amazon.awssdk.services.lambda.model.InvokeResponse; +import software.amazon.awssdk.services.lambda.model.LogType; +import software.amazon.awssdk.services.lambda.model.Runtime; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class LambdaInvokeLogTailDockerIntegrationTest { + + @Inject + DockerClient dockerClient; + + @Test + void synchronousInvokeReturnsItsOwnLogsThroughTheSdk() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker is required for Lambda invocation log tails"); + + String name = "invoke-log-tail-" + UUID.randomUUID().toString().substring(0, 8); + try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), "000000000000", Region.US_EAST_1)) { + client.createFunction(request -> request.functionName(name) + .runtime(Runtime.NODEJS22_X).handler("index.handler") + .role("arn:aws:iam::000000000000:role/lambda-role").timeout(10) + .code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(LambdaCodeFixtures.nodeJsZip(""" + console.log('initialization output'); + exports.handler = async (event) => { + console.log('hello from log tail probe ' + event.marker); + console.error('stderr ' + event.marker); + if (event.large) process.stdout.write('é'.repeat(9000) + ' END ' + event.marker + '\\n'); + if (event.fail) throw new Error('failure ' + event.marker); + return {ok: true}; + }; + """))).build())); + try { + InvokeResponse response = client.invoke(request -> request.functionName(name) + .logType(LogType.TAIL).payload(SdkBytes.fromUtf8String("{\"marker\":\"first\"}"))); + + assertEquals(200, response.statusCode()); + assertEquals("{\"ok\":true}", response.payload().asUtf8String()); + assertNotNull(response.logResult(), "LogType=Tail must return X-Amz-Log-Result"); + String logs = new String(Base64.getDecoder().decode(response.logResult()), StandardCharsets.UTF_8); + assertTrue(logs.contains("hello from log tail probe first"), logs); + assertTrue(logs.contains("initialization output"), logs); + assertTrue(logs.contains("stderr first"), logs); + + InvokeResponse warm = client.invoke(request -> request.functionName(name) + .invocationType(InvocationType.REQUEST_RESPONSE).logType(LogType.TAIL) + .payload(SdkBytes.fromUtf8String("{\"marker\":\"second 世界\"}"))); + String warmLogs = decoded(warm); + assertTrue(warmLogs.contains("second 世界"), warmLogs); + assertFalse(warmLogs.contains("first"), warmLogs); + assertFalse(warmLogs.contains("initialization output"), warmLogs); + + InvokeResponse failed = client.invoke(request -> request.functionName(name).logType(LogType.TAIL) + .payload(SdkBytes.fromUtf8String("{\"marker\":\"failed\",\"fail\":true}"))); + assertEquals("Unhandled", failed.functionError()); + assertTrue(decoded(failed).contains("failure failed"), decoded(failed)); + assertFalse(decoded(failed).contains("second"), decoded(failed)); + + InvokeResponse large = client.invoke(request -> request.functionName(name).logType(LogType.TAIL) + .payload(SdkBytes.fromUtf8String("{\"marker\":\"large\",\"large\":true}"))); + byte[] largeOutput = ("é".repeat(9000) + " END large\n").getBytes(StandardCharsets.UTF_8); + byte[] actualTail = Base64.getDecoder().decode(large.logResult()); + assertArrayEquals(Arrays.copyOfRange(largeOutput, largeOutput.length - 4096, largeOutput.length), + actualTail, () -> "Unexpected tail metadata: " + + new String(actualTail, StandardCharsets.UTF_8).replace("é", "")); + + InvokeResponse noTail = client.invoke(request -> request.functionName(name) + .logType(LogType.NONE).payload(SdkBytes.fromUtf8String("{}"))); + assertNull(noTail.logResult()); + InvokeResponse defaultLogs = client.invoke(request -> request.functionName(name) + .payload(SdkBytes.fromUtf8String("{}"))); + assertNull(defaultLogs.logResult()); + InvokeResponse dryRun = client.invoke(request -> request.functionName(name) + .invocationType(InvocationType.DRY_RUN).logType(LogType.TAIL)); + assertEquals(204, dryRun.statusCode()); + assertNull(dryRun.logResult()); + } finally { + client.deleteFunction(request -> request.functionName(name)); + } + } + } + + private static String decoded(InvokeResponse response) { + assertNotNull(response.logResult()); + return new String(Base64.getDecoder().decode(response.logResult()), StandardCharsets.UTF_8); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailIntegrationTest.java new file mode 100644 index 0000000000..efcea8d858 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/LambdaInvokeLogTailIntegrationTest.java @@ -0,0 +1,67 @@ +package io.floci.aws.services.lambda; + +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@QuarkusTest +class LambdaInvokeLogTailIntegrationTest { + + @InjectMock + LambdaService lambdaService; + + @ParameterizedTest + @ValueSource(strings = {"RequestResponse", "default"}) + void aSynchronousTailRequestReturnsTheEncodedHeader(String invocationType) { + when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any(), any(), eq(true))) + .thenReturn(result(200, "aGVsbG8K")); + + given() + .header("X-Amz-Invocation-Type", "default".equals(invocationType) ? "" : invocationType) + .header("X-Amz-Log-Type", "Tail") + .body("{}") + .when() + .post("/2015-03-31/functions/log-tail/invocations") + .then() + .statusCode(200) + .header("X-Amz-Log-Result", equalTo("aGVsbG8K")); + + verify(lambdaService).invoke(any(), eq("log-tail"), any(), any(), + eq(InvocationType.RequestResponse), any(), any(), any(), eq(true)); + } + + @ParameterizedTest + @ValueSource(strings = {"Event", "DryRun"}) + void nonSynchronousInvocationsIgnoreTail(String invocationType) { + int status = "Event".equals(invocationType) ? 202 : 204; + when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(result(status, "should-not-be-exposed")); + + given() + .header("X-Amz-Invocation-Type", invocationType) + .header("X-Amz-Log-Type", "Tail") + .body("{}") + .when() + .post("/2015-03-31/functions/log-tail/invocations") + .then() + .statusCode(status) + .header("X-Amz-Log-Result", nullValue()); + } + + private static InvokeResult result(int status, String logs) { + return new InvokeResult(status, null, "{}".getBytes(StandardCharsets.UTF_8), logs, "request-id"); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/durable/DurableInvocationLogsTest.java b/src/test/java/io/floci/aws/services/lambda/durable/DurableInvocationLogsTest.java new file mode 100644 index 0000000000..6b4f789c17 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/durable/DurableInvocationLogsTest.java @@ -0,0 +1,63 @@ +package io.floci.aws.services.lambda.durable; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.concurrent.CompletableFuture; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DurableInvocationLogsTest { + + @Test + void resumingAnExecutionKeepsOnlyTheLastFourKilobytesAcrossHandlers() { + DurableInvocationLogs logs = new DurableInvocationLogs(); + logs.acquire(); + byte[] first = "first handler\n".getBytes(StandardCharsets.UTF_8); + logs.beginInvocation(); + logs.complete(Base64.getEncoder().encodeToString(first)); + byte[] second = ("界".repeat(3000) + " second handler\n").getBytes(StandardCharsets.UTF_8); + logs.beginInvocation(); + logs.complete(Base64.getEncoder().encodeToString(second)); + + assertArrayEquals(Arrays.copyOfRange(second, second.length - 4096, second.length), + Base64.getDecoder().decode(logs.snapshot().join())); + logs.release(); + assertTrue(logs.unused()); + } + + @Test + void attachedCallersShareTheCaptureUntilTheLastHandlerAndCallerFinish() { + DurableInvocationLogs logs = new DurableInvocationLogs(); + logs.acquire(); + logs.acquire(); + logs.beginInvocation(); + CompletableFuture snapshot = logs.snapshot(); + logs.release(); + assertFalse(logs.unused()); + logs.release(); + assertFalse(logs.unused(), "an in-flight handler still owns the capture"); + assertFalse(snapshot.isDone()); + + logs.complete("aGFuZGxlcgo="); + + assertArrayEquals("handler\n".getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(snapshot.join())); + assertTrue(logs.unused()); + } + + @Test + void resetCancelsPendingLogWaiters() { + DurableInvocationLogs logs = new DurableInvocationLogs(); + logs.beginInvocation(); + CompletableFuture snapshot = logs.snapshot(); + + logs.cancel(); + + assertTrue(snapshot.isCompletedExceptionally()); + assertTrue(logs.unused()); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionsDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionsDockerIntegrationTest.java index a55f3cb983..8ddd0ff98d 100644 --- a/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableFunctionsDockerIntegrationTest.java @@ -20,6 +20,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Runs a real Python function in a container. Its FAILED envelope closes the execution and the @@ -81,9 +83,25 @@ class LambdaDurableFunctionsDockerIntegrationTest { .body("DurableExecutions[0].Status", equalTo("FAILED")); } + @Test + void aSynchronousDurableTailRequestIncludesTheHandlerLogs() { + Response response = given() + .header("X-Amz-Durable-Execution-Name", "docker-fail-tail") + .header("X-Amz-Log-Type", "Tail") + .body("{\"fail\": true}") + .post(LAMBDA + "/functions/" + FUNCTION + ":1/invocations"); + + assertEquals(200, response.statusCode(), response.asString()); + assertEquals("Unhandled", response.getHeader("X-Amz-Function-Error")); + assertNotNull(response.getHeader("X-Amz-Log-Result"), "Durable Invoke must return requested handler logs"); + String logs = new String(Base64.getDecoder().decode(response.getHeader("X-Amz-Log-Result")), StandardCharsets.UTF_8); + assertTrue(logs.contains("durable handler log"), logs); + } + static String handlerSource() { return """ def handler(event, context): + print("durable handler log", flush=True) return {"Status": "FAILED", "Error": {"ErrorMessage": "asked to fail", "ErrorType": "TestFailure"}} """; diff --git a/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableProtocolIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableProtocolIntegrationTest.java index bebdb87852..266539c4a1 100644 --- a/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableProtocolIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/lambda/durable/LambdaDurableProtocolIntegrationTest.java @@ -27,6 +27,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -46,6 +47,9 @@ class LambdaDurableProtocolIntegrationTest { @Inject ScriptedDurableFunctionInvoker invoker; + @Inject + DurableExecutionService executions; + @BeforeEach void createFunctionAndDrainInvocations() { given() @@ -91,6 +95,33 @@ class LambdaDurableProtocolIntegrationTest { assertEquals(200, invoke.get(30, TimeUnit.SECONDS).statusCode()); } + @Test + void aTailRequestWaitsForHandlerLogsAfterACheckpointClosesTheExecution() throws Exception { + CompletableFuture invoke = CompletableFuture.supplyAsync(() -> given() + .header("X-Amz-Durable-Execution-Name", "checkpoint-log-tail") + .header("X-Amz-Log-Type", "Tail") + .body("{}") + .post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations")); + Invocation invocation = invoker.awaitInvocation(Duration.ofSeconds(30)); + assertTrue(invocation.logTail()); + JsonNode event = MAPPER.readTree(invocation.payload()); + String arn = event.get("DurableExecutionArn").asText(); + checkpoint(arn, event.get("CheckpointToken").asText(), """ + {"Id": "x", "Type": "EXECUTION", "Action": "SUCCEED", "Payload": "\\"done\\""} + """); + assertTrue(executions.awaitCompletion(arn).isDone()); + assertFalse(executions.invocationLogs(arn).isDone(), "the handler still owns its final log tail"); + + invocation.response().complete(new DurableInvocationResult("tail-request", + "{\"Status\":\"SUCCEEDED\"}".getBytes(StandardCharsets.UTF_8), null, "aGFuZGxlciBsb2dzCg==")); + + Response response = invoke.get(30, TimeUnit.SECONDS); + assertEquals(200, response.statusCode()); + assertEquals("\"done\"", response.asString()); + assertEquals("aGFuZGxlciBsb2dzCg==", response.getHeader("X-Amz-Log-Result")); + assertEquals("", executions.invocationLogs(arn).join(), "request log capture is released after the response"); + } + @Test void aChainedInvokeTraceHeaderReachesTheChildInvocationAndExecution() throws Exception { String traceHeader = "Root=1-6af70000-0000000000000000000000e1;Parent=00000000000000e1;Sampled=1"; diff --git a/src/test/java/io/floci/aws/services/lambda/durable/ScriptedDurableFunctionInvoker.java b/src/test/java/io/floci/aws/services/lambda/durable/ScriptedDurableFunctionInvoker.java index 4937785780..e5ca30b52a 100644 --- a/src/test/java/io/floci/aws/services/lambda/durable/ScriptedDurableFunctionInvoker.java +++ b/src/test/java/io/floci/aws/services/lambda/durable/ScriptedDurableFunctionInvoker.java @@ -21,7 +21,7 @@ import java.util.concurrent.TimeoutException; @ApplicationScoped public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker { - public record Invocation(ResolvedDurableTarget target, byte[] payload, String traceId, + public record Invocation(ResolvedDurableTarget target, byte[] payload, String traceId, boolean logTail, CompletableFuture response) { } @@ -41,7 +41,13 @@ public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker { @Override public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, String traceId) { - Invocation invocation = new Invocation(target, payload, traceId, new CompletableFuture<>()); + return invoke(target, payload, requestId, traceId, false); + } + + @Override + public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, + String traceId, boolean logTail) { + Invocation invocation = new Invocation(target, payload, traceId, logTail, new CompletableFuture<>()); invocations.add(invocation); try { return invocation.response().get(30, TimeUnit.SECONDS); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailClockSkewTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailClockSkewTest.java new file mode 100644 index 0000000000..5acd8e7d80 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailClockSkewTest.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.lambda.launcher; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.LogContainerCmd; +import com.github.dockerjava.api.model.Frame; +import com.github.dockerjava.api.model.StreamType; +import io.floci.aws.services.lambda.model.ContainerState; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class InvocationLogTailClockSkewTest { + + @ParameterizedTest + @ValueSource(strings = {"2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"}) + void warmInvocationUsesTheDaemonsBoundaryEvenWhenItsClockDrifts(String sourceTime) { + Instant previous = Instant.parse(sourceTime); + String earlier = previous + " previous invocation\n"; + String current = previous.plusNanos(1) + " current invocation\n"; + DockerClient docker = mock(DockerClient.class); + when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand(earlier, current)); + ContainerHandle handle = new ContainerHandle("worker", "function", null, ContainerState.WARM); + handle.setLogTailReader(initialization -> InvocationLogTail.captureDocker(docker, "worker", initialization)); + handle.beginInvocation(false); + + String logs = handle.beginInvocation(true).get(); + + assertEquals("current invocation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8)); + } + + private static LogContainerCmd snapshotCommand(String earlier, String current) { + LogContainerCmd command = mock(LogContainerCmd.class, RETURNS_SELF); + AtomicInteger lines = new AtomicInteger(); + doAnswer(call -> { + lines.set(call.getArgument(0)); + return command; + }).when(command).withTail(anyInt()); + doAnswer(call -> { + ResultCallback callback = call.getArgument(0); + callback.onNext(new Frame(StreamType.STDOUT, earlier.getBytes(StandardCharsets.UTF_8))); + if (lines.get() != 1) { + callback.onNext(new Frame(StreamType.STDOUT, current.getBytes(StandardCharsets.UTF_8))); + } + callback.onComplete(); + return callback; + }).when(command).exec(any()); + return command; + } + + @Test + void eachDockerRecordDropsItsPrefixEvenWhenThePreviousRecordHasNoNewline() { + DockerClient docker = mock(DockerClient.class); + when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand( + "2026-11-16T19:00:00.001Z partial ", "2026-11-16T19:00:00.002Z continuation\n")); + + String logs = InvocationLogTail.readDocker(docker, "worker", Instant.EPOCH); + + assertEquals("partial continuation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8)); + } + + @Test + void aDockerTimestampSplitAcrossCallbacksIsReassembled() { + DockerClient docker = mock(DockerClient.class); + when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand( + "2026-11-16T19:", "00:00.001Z handler output\n")); + + String logs = InvocationLogTail.readDocker(docker, "worker", Instant.EPOCH); + + assertEquals("handler output\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8)); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailTest.java new file mode 100644 index 0000000000..24594c08fc --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/InvocationLogTailTest.java @@ -0,0 +1,99 @@ +package io.floci.aws.services.lambda.launcher; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InvocationLogTailTest { + + @Test + void emptyLogsHaveAnEmptyBase64Result() throws Exception { + assertEquals("", InvocationLogTail.read(new ByteArrayInputStream(new byte[0]))); + } + + @Test + void truncationCountsUtf8BytesRatherThanCharacters() throws Exception { + byte[] logs = ("earlier output\n" + "界".repeat(3000) + "\nlast line\n").getBytes(StandardCharsets.UTF_8); + + byte[] actual = Base64.getDecoder().decode(InvocationLogTail.read(new ByteArrayInputStream(logs))); + + assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), actual); + } + + @Test + void repeatedSmallWritesWrapWithoutLosingTheTail() { + InvocationLogTail tail = new InvocationLogTail(); + byte[] logs = ("hello\n".repeat(2000) + "last\n").getBytes(StandardCharsets.UTF_8); + for (int offset = 0; offset < logs.length; offset += 17) { + tail.append(logs, offset, Math.min(17, logs.length - offset)); + } + + assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), + Base64.getDecoder().decode(tail.encoded())); + } + + @Test + void aSingleOversizedWriteKeepsTheLastFourKilobytes() { + InvocationLogTail tail = new InvocationLogTail(); + byte[] prefix = "old".getBytes(StandardCharsets.UTF_8); + tail.append(prefix, 0, prefix.length); + byte[] logs = ("x".repeat(8000) + "end\n").getBytes(StandardCharsets.UTF_8); + tail.append(logs, 0, logs.length); + + assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), + Base64.getDecoder().decode(tail.encoded())); + } + + @Test + void timestampFilteringExcludesAnEarlierInvocationInTheSameSecond() { + InvocationLogTail tail = new InvocationLogTail(); + Instant start = Instant.parse("2026-11-16T19:00:00.500Z"); + tail.appendTimestamped(("2026-11-16T19:00:00.499999999Z previous invocation\n" + + "2026-11-16T19:00:00.500000000Z current stdout\n" + + "2026-11-16T19:00:00.501000000Z current stderr\n").getBytes(StandardCharsets.UTF_8), start); + + assertEquals("current stdout\ncurrent stderr\n", decoded(tail)); + } + + @Test + void aLogRecordSplitAcrossFramesKeepsItsContinuationAndUnterminatedTail() { + InvocationLogTail tail = new InvocationLogTail(); + Instant start = Instant.parse("2026-11-16T19:00:00Z"); + tail.appendTimestamped("2026-11-16T19:00:00.001Z hello ".getBytes(StandardCharsets.UTF_8), start); + tail.appendTimestamped("world\n2026-11-16T19:00:00.002Z last".getBytes(StandardCharsets.UTF_8), start); + + assertEquals("hello world\nlast", decoded(tail)); + } + + private static String decoded(InvocationLogTail tail) { + return new String(Base64.getDecoder().decode(tail.encoded()), StandardCharsets.UTF_8); + } + + @Test + void aTimestampPrefixSplitAcrossFramesIsRemovedWithoutLosingOutput() { + InvocationLogTail tail = new InvocationLogTail(); + Instant start = Instant.parse("2026-11-16T19:00:00Z"); + tail.appendTimestamped("2026-11-16T19:".getBytes(StandardCharsets.UTF_8), start); + tail.appendTimestamped("00:00.001Z hello\n".getBytes(StandardCharsets.UTF_8), start); + + assertEquals("hello\n", decoded(tail)); + } + + @Test + void everySplitPointPreservesTheSameTimestampedUtf8Output() { + byte[] record = "2026-11-16T19:00:00.001Z hello 世界\n".getBytes(StandardCharsets.UTF_8); + for (int split = 1; split < record.length; split++) { + InvocationLogTail tail = new InvocationLogTail(); + tail.appendTimestamped(Arrays.copyOfRange(record, 0, split), Instant.EPOCH); + tail.appendTimestamped(Arrays.copyOfRange(record, split, record.length), Instant.EPOCH); + assertEquals("hello 世界\n", decoded(tail), "split at byte " + split); + } + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesInvocationLogTailTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesInvocationLogTailTest.java new file mode 100644 index 0000000000..cbc87715f0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesInvocationLogTailTest.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.lambda.launcher.kubernetes; + +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class KubernetesInvocationLogTailTest { + + @Test + void invocationLogsUseABoundedNonFollowingSnapshotAndLeaveStreamingAvailable() throws Exception { + AtomicReference requested = new AtomicReference<>(); + byte[] logs = ("界".repeat(3000) + "\nlast line\n").getBytes(StandardCharsets.UTF_8); + byte[] timestamped = ("2026-11-16T19:00:00.123456790Z " + "界".repeat(3000) + + "\n2026-11-16T19:00:00.123456791Z last line\n").getBytes(StandardCharsets.UTF_8); + HttpServer server = serveLogs(uri -> uri.getRawQuery().contains("timestamps=true") ? timestamped : logs, requested); + try (HttpClient http = HttpClient.newHttpClient()) { + KubernetesApiClient client = new KubernetesApiClient( + URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token"); + Instant since = Instant.parse("2026-11-16T19:00:00.123456789Z"); + + byte[] tail = Base64.getDecoder().decode(client.readPodLogTail("functions", "worker", since)); + + assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), tail); + assertEquals("/api/v1/namespaces/functions/pods/worker/log", requested.get().getPath()); + String query = URLDecoder.decode(requested.get().getRawQuery(), StandardCharsets.UTF_8); + assertTrue(query.contains("container=runtime"), query); + assertTrue(query.contains("follow=false"), query); + assertTrue(query.contains("tailLines=4096"), query); + assertTrue(query.contains("timestamps=true"), query); + assertTrue(query.contains("sinceTime=2026-11-16T19:00:00Z"), query); + + try (InputStream stream = client.openPodLogStream("functions", "worker", "runtime")) { + assertArrayEquals(logs, stream.readAllBytes()); + } + assertEquals("container=runtime&follow=true", requested.get().getRawQuery()); + } finally { + server.stop(0); + } + } + + @Test + void clientFilteringRemovesEarlierRecordsWithinTheSameSecond() throws Exception { + byte[] logs = ("2026-11-16T19:00:00.123456788Z previous invocation\n" + + "2026-11-16T19:00:00.123456789Z current invocation\n").getBytes(StandardCharsets.UTF_8); + HttpServer server = serveLogs(uri -> logs, new AtomicReference<>()); + try (HttpClient http = HttpClient.newHttpClient()) { + KubernetesApiClient client = new KubernetesApiClient( + URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token"); + + String tail = client.readPodLogTail("functions", "worker", Instant.parse("2026-11-16T19:00:00.123456789Z")); + + assertEquals("current invocation\n", new String(Base64.getDecoder().decode(tail), StandardCharsets.UTF_8)); + } finally { + server.stop(0); + } + } + + @ParameterizedTest + @ValueSource(strings = {"2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"}) + void warmInvocationUsesTheKubeletsClock(String sourceTime) throws Exception { + Instant previous = Instant.parse(sourceTime); + String earlier = previous + " previous invocation\n"; + String current = previous.plusNanos(1) + " current invocation\n"; + HttpServer server = serveLogs(uri -> (uri.getRawQuery().contains("tailLines=1&") + ? earlier : earlier + current).getBytes(StandardCharsets.UTF_8), new AtomicReference<>()); + try (HttpClient http = HttpClient.newHttpClient()) { + KubernetesApiClient client = new KubernetesApiClient( + URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token"); + + String logs = client.capturePodLogTail("functions", "worker", false).get(); + + assertEquals("current invocation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8)); + } finally { + server.stop(0); + } + } + + private static HttpServer serveLogs(Function response, AtomicReference requested) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + requested.set(exchange.getRequestURI()); + byte[] logs = response.apply(exchange.getRequestURI()); + exchange.sendResponseHeaders(200, logs.length); + try (exchange) { + exchange.getResponseBody().write(logs); + } + }); + server.start(); + return server; + } +}