mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(lambda): give each durable execution an X-Ray trace header (#8161)
This commit is contained in:
1 parent
55b2fb7bd3
commit
f5e581a872
23 files changed
+510
-53
No files matched your search
@@ -252,6 +252,11 @@ and an output over 1 MB fails the operation. A missing function or an unqualifie
|
||||
fails the operation at once, and a target in another account or Region is rejected at checkpoint.
|
||||
Stopping the parent leaves the child running, as on AWS.
|
||||
|
||||
Each durable execution gets an X-Ray trace header. It is built from the `X-Amzn-Trace-Id` header of
|
||||
Invoke when the request carries one. `GetDurableExecution` returns it as `TraceHeader`. Every
|
||||
invocation of the execution gets the same `Root` in `_X_AMZN_TRACE_ID`. A `PassThrough` function
|
||||
gets the `Parent` of the execution. An `Active` function gets a new `Parent` on each invocation.
|
||||
|
||||
`GetDurableExecutionHistory` leaves payloads out unless `IncludeExecutionData=true` is sent. The
|
||||
API reference names `true` as the default, but AWS answers this way.
|
||||
|
||||
@@ -269,8 +274,10 @@ Not emulated yet:
|
||||
- Durable executions started by Step Functions or by an event source mapping. These invoke the
|
||||
function as a plain one.
|
||||
- Payload encryption. `KMSKeyArn` is stored and returned only.
|
||||
- EventBridge status-change events, the X-Ray `TraceHeader`, and a dead-letter queue or
|
||||
destinations for durable executions.
|
||||
- EventBridge status-change events and a dead-letter queue or destinations for durable
|
||||
executions.
|
||||
- The `Lineage` field AWS adds to the trace header, and trace header propagation through chained
|
||||
invokes.
|
||||
- The per-execution limits of 3,000 operations and 100 MB of persisted payload.
|
||||
|
||||
## Code signing configuration pagination
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import java.util.HexFormat;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/** Ids in the formats X-Ray uses in an {@code X-Amzn-Trace-Id} header. */
|
||||
public final class XRayTraceIds {
|
||||
|
||||
private static final int TRACE_RANDOM_BYTES = 12;
|
||||
|
||||
private XRayTraceIds() {
|
||||
}
|
||||
|
||||
/** {@code 1-<8 hex digits of epoch seconds>-<24 random hex digits>}. */
|
||||
public static String traceId(long epochSeconds) {
|
||||
byte[] id = new byte[TRACE_RANDOM_BYTES];
|
||||
ThreadLocalRandom.current().nextBytes(id);
|
||||
return "1-" + String.format("%08x", epochSeconds) + "-" + HexFormat.of().formatHex(id);
|
||||
}
|
||||
|
||||
/** 16 random lowercase hex digits, never all zeros. */
|
||||
public static String segmentId() {
|
||||
ThreadLocalRandom random = ThreadLocalRandom.current();
|
||||
long value;
|
||||
do {
|
||||
value = random.nextLong();
|
||||
} while (value == 0);
|
||||
return HexFormat.of().toHexDigits(value);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
package io.floci.aws.services.elbv2;
|
||||
|
||||
import io.floci.aws.core.common.XRayTraceIds;
|
||||
import io.vertx.core.MultiMap;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* The {@code X-Amzn-Trace-Id} header an Application Load Balancer adds or updates before it sends a
|
||||
@@ -59,8 +58,6 @@ final class ElbV2TraceHeader {
|
||||
}
|
||||
|
||||
private static String traceId() {
|
||||
byte[] id = new byte[12];
|
||||
ThreadLocalRandom.current().nextBytes(id);
|
||||
return "1-" + String.format("%08x", Instant.now().getEpochSecond()) + "-" + HexFormat.of().formatHex(id);
|
||||
return XRayTraceIds.traceId(Instant.now().getEpochSecond());
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ public class LambdaController {
|
||||
String durableExecutionName = headers.getHeaderString("X-Amz-Durable-Execution-Name");
|
||||
|
||||
InvokeResult result = lambdaService.invoke(region, functionName, qualifier, payload, type, clientContext,
|
||||
durableExecutionName);
|
||||
durableExecutionName, headers.getHeaderString("X-Amzn-Trace-Id"));
|
||||
|
||||
if (type != InvocationType.Event
|
||||
&& result.getPayload() != null
|
||||
|
||||
@@ -168,7 +168,12 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
|
||||
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId) {
|
||||
return invoke(fn, payload, type, 0, null, null, requestId, null);
|
||||
return invoke(fn, payload, type, 0, null, null, requestId, null, null);
|
||||
}
|
||||
|
||||
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId,
|
||||
String traceId) {
|
||||
return invoke(fn, payload, type, 0, null, null, requestId, null, traceId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -193,7 +198,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
|
||||
String invokedQualifier, String clientContext) {
|
||||
return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString(),
|
||||
null);
|
||||
null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -203,12 +208,12 @@ public class LambdaExecutorService implements Resettable {
|
||||
public InvokeResult invokeStreaming(LambdaFunction fn, byte[] payload, int chainDepth, String invokedQualifier,
|
||||
ResponseStreamListener listener) {
|
||||
return invoke(fn, payload, InvocationType.RequestResponse, chainDepth, invokedQualifier, null,
|
||||
UUID.randomUUID().toString(), listener);
|
||||
UUID.randomUUID().toString(), listener, null);
|
||||
}
|
||||
|
||||
private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
|
||||
String invokedQualifier, String clientContext, String requestId,
|
||||
ResponseStreamListener listener) {
|
||||
ResponseStreamListener listener, String traceId) {
|
||||
if (type == InvocationType.DryRun) {
|
||||
return new InvokeResult(204, null, new byte[0], null, requestId);
|
||||
}
|
||||
@@ -260,7 +265,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
|
||||
try {
|
||||
return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener);
|
||||
return executeSync(fn, payload, requestId, clientContext, invokedQualifier, listener, traceId);
|
||||
} finally {
|
||||
permit.close();
|
||||
}
|
||||
@@ -316,7 +321,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
}
|
||||
InvokeResult result;
|
||||
try (permit) {
|
||||
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null);
|
||||
result = executeSync(event.fn(), event.payload(), event.requestId(), null, event.invokedQualifier(), null, null);
|
||||
} 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
|
||||
@@ -394,7 +399,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
|
||||
private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId,
|
||||
String clientContext, String invokedQualifier,
|
||||
ResponseStreamListener listener) {
|
||||
ResponseStreamListener listener, String traceId) {
|
||||
ContainerHandle handle;
|
||||
try {
|
||||
handle = warmPool.acquireProvisioned(fn, invokedQualifier);
|
||||
@@ -412,6 +417,7 @@ public class LambdaExecutorService implements Resettable {
|
||||
requestId, payload, deadlineMs, fn.getFunctionArn(),
|
||||
new CompletableFuture<>());
|
||||
invocation.setClientContext(clientContext);
|
||||
invocation.setTraceId(traceId);
|
||||
invocation.setResponseStreamListener(listener);
|
||||
RuntimeApiServer runtimeApiServer = handle.getRuntimeApiServer();
|
||||
boolean initializing = !runtimeApiServer.hasRuntimePolled();
|
||||
|
||||
@@ -1444,6 +1444,12 @@ public class LambdaService implements ResourceProvider {
|
||||
*/
|
||||
public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload,
|
||||
InvocationType type, String clientContext, String durableExecutionName) {
|
||||
return invoke(region, functionName, queryQualifier, payload, type, clientContext, durableExecutionName, null);
|
||||
}
|
||||
|
||||
public InvokeResult invoke(String region, String functionName, String queryQualifier, byte[] payload,
|
||||
InvocationType type, String clientContext, String durableExecutionName,
|
||||
String traceHeader) {
|
||||
validateInvokeQualifier(queryQualifier);
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, queryQualifier);
|
||||
String name = ref.name();
|
||||
@@ -1457,7 +1463,8 @@ public class LambdaService implements ResourceProvider {
|
||||
fn = targetResolver.resolveInvokeTarget(region, name, qualifier);
|
||||
}
|
||||
reportCustomResourceLiveness(payload);
|
||||
InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type);
|
||||
InvokeResult durable = invokeIfDurable(fn, region, qualifier, durableExecutionName, payload, type,
|
||||
traceHeader);
|
||||
if (durable != null) {
|
||||
return durable;
|
||||
}
|
||||
@@ -1469,7 +1476,8 @@ public class LambdaService implements ResourceProvider {
|
||||
|
||||
/** 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 durableExecutionName, byte[] payload, InvocationType type,
|
||||
String traceHeader) {
|
||||
if (!fn.isDurable()) {
|
||||
return null;
|
||||
}
|
||||
@@ -1480,7 +1488,7 @@ public class LambdaService implements ResourceProvider {
|
||||
if (type == InvocationType.DryRun) {
|
||||
return null;
|
||||
}
|
||||
InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type);
|
||||
InvokeResult result = invokeDurable(fn, region, durableExecutionName, payload, type, traceHeader);
|
||||
result.setExecutedVersion(fn.getVersion());
|
||||
return result;
|
||||
}
|
||||
@@ -1490,7 +1498,7 @@ public class LambdaService implements ResourceProvider {
|
||||
* limit. Event answers 202 as soon as the execution exists.
|
||||
*/
|
||||
private InvokeResult invokeDurable(LambdaFunction fn, String region, String executionName, byte[] payload,
|
||||
InvocationType type) {
|
||||
InvocationType type, String traceHeader) {
|
||||
boolean synchronous = type == InvocationType.RequestResponse;
|
||||
if (synchronous && fn.getDurableExecutionTimeout() > MAX_FUNCTION_TIMEOUT_SECONDS) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
@@ -1504,7 +1512,8 @@ public class LambdaService implements ResourceProvider {
|
||||
}
|
||||
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));
|
||||
fn.getAccountId(), region, fn.getFunctionName(), fn.getVersion(), executionName, input, synchronous,
|
||||
traceHeader));
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
InvokeResult result;
|
||||
if (!synchronous) {
|
||||
@@ -1589,7 +1598,7 @@ public class LambdaService implements ResourceProvider {
|
||||
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);
|
||||
InvokeResult durable = invokeIfDurable(fn, arn.region(), ref.qualifier(), null, payload, type, null);
|
||||
if (durable != null) {
|
||||
return durable;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,8 @@ public class DurableExecutionService implements Resettable {
|
||||
}
|
||||
|
||||
public record StartRequest(String accountId, String region, String functionName, String qualifier,
|
||||
String executionName, String inputPayload, boolean synchronous) {
|
||||
String executionName, String inputPayload, boolean synchronous,
|
||||
String traceHeader) {
|
||||
}
|
||||
|
||||
public record ListRequest(String accountId, String region, String functionName, String version,
|
||||
@@ -548,6 +549,7 @@ public class DurableExecutionService implements Resettable {
|
||||
private void runInvocation(String accountId, String key, String invocationId, long launchGeneration) {
|
||||
ResolvedDurableTarget target;
|
||||
byte[] payload;
|
||||
String traceId = null;
|
||||
long startedAt;
|
||||
synchronized (lockFor(accountId, key)) {
|
||||
DurableExecution execution = store.getForAccount(accountId, key).orElse(null);
|
||||
@@ -563,6 +565,7 @@ public class DurableExecutionService implements Resettable {
|
||||
try {
|
||||
target = invoker.resolve(accountId, execution.getRegion(), execution.getFunctionName(),
|
||||
execution.getVersion());
|
||||
traceId = DurableTraceHeader.forInvocation(execution.getTraceHeader(), target.activeTracing());
|
||||
payload = objectMapper.writeValueAsBytes(
|
||||
DurableWire.invocationEvent(execution, token, updatedOperationIds));
|
||||
} catch (AwsException | IOException e) {
|
||||
@@ -578,7 +581,7 @@ public class DurableExecutionService implements Resettable {
|
||||
result = new DurableInvocationResult(null, null, "ResourceNotFoundException");
|
||||
} else {
|
||||
try {
|
||||
result = invoker.invoke(target, payload, invocationId);
|
||||
result = invoker.invoke(target, payload, invocationId, traceId);
|
||||
} catch (AwsException e) {
|
||||
result = new DurableInvocationResult(null, DurableWire.functionErrorPayload(
|
||||
DurableErrorObject.of(e.getMessage(), e.getErrorCode())),
|
||||
@@ -703,6 +706,8 @@ public class DurableExecutionService implements Resettable {
|
||||
execution.setVersion(target.version());
|
||||
execution.setExecutionArn(target.functionArn() + "/durable-execution/" + name + "/" + executionId);
|
||||
execution.setStartTimestamp(now);
|
||||
execution.setTraceHeader(DurableTraceHeader.forExecution(request.traceHeader(), target.activeTracing(),
|
||||
now / 1000));
|
||||
execution.setInputPayload(request.inputPayload());
|
||||
execution.setExecutionTimeoutSeconds(target.executionTimeoutSeconds());
|
||||
execution.setRetentionPeriodInDays(target.retentionPeriodInDays());
|
||||
@@ -850,7 +855,7 @@ public class DurableExecutionService implements Resettable {
|
||||
ResolvedDurableTarget target, String name, String executionId, long now,
|
||||
List<Runnable> effects) {
|
||||
StartRequest request = new StartRequest(target.accountId(), target.region(), target.functionName(),
|
||||
target.version(), name, operation.getInputPayload(), false);
|
||||
target.version(), name, operation.getInputPayload(), false, null);
|
||||
DurableExecution child = newExecution(request, target, name, executionId, now);
|
||||
child.setParentExecutionArn(parent.getExecutionArn());
|
||||
child.setParentOperationId(operation.getId());
|
||||
@@ -878,7 +883,7 @@ public class DurableExecutionService implements Resettable {
|
||||
private ChainedOutcome invokePlainFunction(ResolvedDurableTarget target, byte[] payload) {
|
||||
DurableInvocationResult result;
|
||||
try {
|
||||
result = invoker.invoke(target, payload, UUID.randomUUID().toString());
|
||||
result = invoker.invoke(target, payload, UUID.randomUUID().toString(), null);
|
||||
} catch (AwsException e) {
|
||||
return ChainedOutcome.failed(e);
|
||||
} catch (RuntimeException e) {
|
||||
|
||||
@@ -10,7 +10,7 @@ public interface DurableFunctionInvoker {
|
||||
/** The function a durable execution runs on, or an AwsException when the name does not resolve. */
|
||||
ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier);
|
||||
|
||||
DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId);
|
||||
DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId, String traceId);
|
||||
|
||||
record ResolvedDurableTarget(String accountId,
|
||||
String region,
|
||||
@@ -19,7 +19,8 @@ public interface DurableFunctionInvoker {
|
||||
String version,
|
||||
boolean durable,
|
||||
int executionTimeoutSeconds,
|
||||
int retentionPeriodInDays) {
|
||||
int retentionPeriodInDays,
|
||||
boolean activeTracing) {
|
||||
}
|
||||
|
||||
record DurableInvocationResult(String requestId, byte[] payload, String functionError) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.floci.aws.services.lambda.durable;
|
||||
|
||||
import io.floci.aws.core.common.XRayTraceIds;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** The X-Ray trace header of a durable execution and of each invocation of it. */
|
||||
final class DurableTraceHeader {
|
||||
|
||||
private static final Pattern ROOT = Pattern.compile("1-[0-9a-fA-F]{8}-[0-9a-fA-F]{24}");
|
||||
private static final Pattern PARENT = Pattern.compile("[0-9a-fA-F]{16}");
|
||||
|
||||
private DurableTraceHeader() {
|
||||
}
|
||||
|
||||
private record Fields(String root, String parent, String sampled) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lambda records its own segment for an Active function that samples the request, so the Parent
|
||||
* it was sent is replaced.
|
||||
*/
|
||||
static String forExecution(String received, boolean activeTracing, long epochSeconds) {
|
||||
Fields fields = parse(received);
|
||||
String root = fields.root() != null ? fields.root() : XRayTraceIds.traceId(epochSeconds);
|
||||
String sampled = fields.sampled() != null ? fields.sampled() : activeTracing ? "1" : "0";
|
||||
String parent;
|
||||
if (activeTracing && "1".equals(sampled)) {
|
||||
parent = XRayTraceIds.segmentId();
|
||||
} else if (fields.parent() != null) {
|
||||
parent = fields.parent();
|
||||
} else if (fields.sampled() == null) {
|
||||
parent = XRayTraceIds.segmentId();
|
||||
} else {
|
||||
parent = null;
|
||||
}
|
||||
return format(root, parent, sampled);
|
||||
}
|
||||
|
||||
static String forInvocation(String executionHeader, boolean activeTracing) {
|
||||
if (executionHeader == null) {
|
||||
return null;
|
||||
}
|
||||
Fields fields = parse(executionHeader);
|
||||
if (activeTracing) {
|
||||
return format(fields.root(), XRayTraceIds.segmentId(), fields.sampled());
|
||||
}
|
||||
if (fields.parent() != null) {
|
||||
return executionHeader;
|
||||
}
|
||||
return "Root=" + fields.root();
|
||||
}
|
||||
|
||||
private static Fields parse(String header) {
|
||||
String root = null;
|
||||
String parent = null;
|
||||
String sampled = null;
|
||||
if (header != null) {
|
||||
for (String part : header.split(";")) {
|
||||
String field = part.trim();
|
||||
int equals = field.indexOf('=');
|
||||
if (equals < 0) {
|
||||
continue;
|
||||
}
|
||||
String key = field.substring(0, equals);
|
||||
String value = field.substring(equals + 1);
|
||||
if ("Root".equals(key) && root == null && ROOT.matcher(value).matches()) {
|
||||
root = value;
|
||||
} else if ("Parent".equals(key) && parent == null && PARENT.matcher(value).matches()) {
|
||||
parent = value;
|
||||
} else if ("Sampled".equals(key) && sampled == null
|
||||
&& ("0".equals(value) || "1".equals(value))) {
|
||||
sampled = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Fields(root, parent, sampled);
|
||||
}
|
||||
|
||||
private static String format(String root, String parent, String sampled) {
|
||||
StringBuilder header = new StringBuilder("Root=").append(root);
|
||||
if (parent != null) {
|
||||
header.append(";Parent=").append(parent);
|
||||
}
|
||||
return header.append(";Sampled=").append(sampled).toString();
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,9 @@ public final class DurableWire {
|
||||
node.put("DurableExecutionName", execution.getName());
|
||||
node.put("FunctionArn", execution.getFunctionArn());
|
||||
node.put("Version", execution.getVersion());
|
||||
if (execution.getTraceHeader() != null) {
|
||||
node.putObject("TraceHeader").put("XAmznTraceId", execution.getTraceHeader());
|
||||
}
|
||||
node.put("Status", execution.getStatus().name());
|
||||
putTimestamp(node, "StartTimestamp", execution.getStartTimestamp(), false);
|
||||
if (execution.getEndTimestamp() != null) {
|
||||
|
||||
+5
-3
@@ -30,7 +30,8 @@ public class LambdaDurableFunctionInvoker implements DurableFunctionInvoker {
|
||||
return new ResolvedDurableTarget(accountId, region, fn.getFunctionName(), qualifiedArn, version,
|
||||
fn.isDurable(),
|
||||
fn.getDurableExecutionTimeout() != null ? fn.getDurableExecutionTimeout() : 0,
|
||||
fn.getDurableRetentionPeriodInDays() != null ? fn.getDurableRetentionPeriodInDays() : 0);
|
||||
fn.getDurableRetentionPeriodInDays() != null ? fn.getDurableRetentionPeriodInDays() : 0,
|
||||
"Active".equals(fn.getTracingMode()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,11 +39,12 @@ public class LambdaDurableFunctionInvoker implements DurableFunctionInvoker {
|
||||
* {@code $LATEST} execution resumes on whatever code $LATEST holds now, as on AWS.
|
||||
*/
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId) {
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
|
||||
String traceId) {
|
||||
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));
|
||||
() -> executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId, traceId));
|
||||
return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError());
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ public class DurableExecution {
|
||||
/** Set on an execution a chained invoke started. Its close completes that operation of the parent. */
|
||||
private String parentExecutionArn;
|
||||
private String parentOperationId;
|
||||
private String traceHeader;
|
||||
|
||||
public DurableExecution() {
|
||||
}
|
||||
@@ -136,6 +137,8 @@ public class DurableExecution {
|
||||
|
||||
public String getVersion() { return version; }
|
||||
public void setVersion(String version) { this.version = version; }
|
||||
public String getTraceHeader() { return traceHeader; }
|
||||
public void setTraceHeader(String traceHeader) { this.traceHeader = traceHeader; }
|
||||
|
||||
public DurableExecutionStatus getStatus() { return status; }
|
||||
public void setStatus(DurableExecutionStatus status) { this.status = status; }
|
||||
|
||||
@@ -13,6 +13,7 @@ public class PendingInvocation {
|
||||
private final CompletableFuture<InvokeResult> resultFuture;
|
||||
private final CompletableFuture<Void> dispatchedFuture = new CompletableFuture<>();
|
||||
private volatile String clientContext;
|
||||
private volatile String traceId;
|
||||
private volatile ResponseStreamListener responseStreamListener;
|
||||
|
||||
public PendingInvocation(String requestId, byte[] payload, long deadlineMs,
|
||||
@@ -40,6 +41,8 @@ public class PendingInvocation {
|
||||
public String getFunctionArn() { return functionArn; }
|
||||
public String getClientContext() { return clientContext; }
|
||||
public void setClientContext(String clientContext) { this.clientContext = clientContext; }
|
||||
public String getTraceId() { return traceId; }
|
||||
public void setTraceId(String traceId) { this.traceId = traceId; }
|
||||
public ResponseStreamListener getResponseStreamListener() { return responseStreamListener; }
|
||||
public void setResponseStreamListener(ResponseStreamListener listener) { this.responseStreamListener = listener; }
|
||||
public CompletableFuture<InvokeResult> getResultFuture() { return resultFuture; }
|
||||
|
||||
@@ -1072,6 +1072,9 @@ public class RuntimeApiServer {
|
||||
if (invocation.getClientContext() != null) {
|
||||
response.putHeader("Lambda-Runtime-Client-Context", invocation.getClientContext());
|
||||
}
|
||||
if (invocation.getTraceId() != null) {
|
||||
response.putHeader("Lambda-Runtime-Trace-Id", invocation.getTraceId());
|
||||
}
|
||||
write = response.end(body);
|
||||
} catch (IllegalStateException alreadyEnded) {
|
||||
write = Future.failedFuture(alreadyEnded);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class XRayTraceIdsTest {
|
||||
|
||||
@Test
|
||||
void traceIdHasTheRootShapeAndEmbedsTheEpochSeconds() {
|
||||
String id = XRayTraceIds.traceId(0x6af70000L);
|
||||
|
||||
assertTrue(id.matches("1-6af70000-[0-9a-f]{24}"), id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void traceIdPadsSmallEpochSecondsToEightDigits() {
|
||||
assertTrue(XRayTraceIds.traceId(255).startsWith("1-000000ff-"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void traceIdsDiffer() {
|
||||
assertNotEquals(XRayTraceIds.traceId(1), XRayTraceIds.traceId(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void segmentIdIsSixteenLowercaseHexDigitsAndNeverAllZeros() {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
String id = XRayTraceIds.segmentId();
|
||||
assertEquals(16, id.length());
|
||||
assertTrue(id.matches("[0-9a-f]{16}"), id);
|
||||
assertNotEquals("0000000000000000", id);
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -31,7 +31,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
}
|
||||
|
||||
private void stubInvoke() {
|
||||
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any()))
|
||||
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(new InvokeResult(200, null, "{}".getBytes(), null, "req"));
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn"), any(), any(),
|
||||
eq(InvocationType.RequestResponse), eq(CONTEXT_JSON), isNull());
|
||||
eq(InvocationType.RequestResponse), eq(CONTEXT_JSON), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,7 +63,7 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn-event"), any(), any(),
|
||||
eq(InvocationType.Event), isNull(), isNull());
|
||||
eq(InvocationType.Event), isNull(), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,6 +80,6 @@ class LambdaInvokeClientContextIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
|
||||
verify(lambdaService).invoke(any(), eq("ctx-fn-utf"), any(), any(),
|
||||
eq(InvocationType.RequestResponse), eq("{\"custom\":{\"name\":\"caf\\u00E9\"}}"), isNull());
|
||||
eq(InvocationType.RequestResponse), eq("{\"custom\":{\"name\":\"caf\\u00E9\"}}"), isNull(), isNull());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -82,7 +82,7 @@ class LambdaSynchronousInvokeDispatchIntegrationTest {
|
||||
// Each answer only records what it saw and waits for its own release; the checks run on the
|
||||
// test thread, so a mismatch fails there with its own message instead of a 500 to the client.
|
||||
doAnswer(call -> hold(call.getArgument(1), call.getArgument(4), held, invoking, releases))
|
||||
.when(lambdaService).invoke(anyString(), anyString(), any(), any(), any(), any(), any());
|
||||
.when(lambdaService).invoke(anyString(), anyString(), any(), any(), any(), any(), any(), any());
|
||||
doAnswer(call -> hold(call.getArgument(0), call.getArgument(2), held, invoking, releases))
|
||||
.when(lambdaService).invokeArn(anyString(), any(), any());
|
||||
|
||||
|
||||
+10
-9
@@ -63,7 +63,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{\"a\":1}",
|
||||
false)).getExecutionArn();
|
||||
false, null)).getExecutionArn();
|
||||
String oldToken = token(before.events.get(0));
|
||||
firstStorage.flushAll();
|
||||
|
||||
@@ -105,7 +105,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
false, null)).getExecutionArn();
|
||||
String callbackId = first.get(executionArn).getOperations().get("approve").getCallbackId();
|
||||
firstStorage.flushAll();
|
||||
|
||||
@@ -149,7 +149,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
false, null)).getExecutionArn();
|
||||
assertEquals("STARTED", first.get(executionArn).getOperations().get("i1").getStatus().name());
|
||||
firstStorage.flushAll();
|
||||
|
||||
@@ -184,7 +184,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
false, null)).getExecutionArn();
|
||||
String childArn = first.get(executionArn).getOperations().get("i1").getChildExecutionArn();
|
||||
firstStorage.flushAll();
|
||||
|
||||
@@ -226,7 +226,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
return "{\"Status\":\"PENDING\"}";
|
||||
});
|
||||
String parentArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
|
||||
false)).getExecutionArn();
|
||||
false, null)).getExecutionArn();
|
||||
String childArn = first.get(parentArn).getOperations().get("i1").getChildExecutionArn();
|
||||
executions(firstStorage).deleteForAccount(ACCOUNT,
|
||||
"us-east-1/" + DurableExecutionService.parseArn(childArn).executionId());
|
||||
@@ -267,7 +267,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
null)));
|
||||
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\"}";
|
||||
});
|
||||
first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}", false));
|
||||
first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}", false, null));
|
||||
firstStorage.flushAll();
|
||||
|
||||
ScriptedInvoker second = new ScriptedInvoker();
|
||||
@@ -361,7 +361,7 @@ class DurableExecutionServicePersistenceTest {
|
||||
public ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier) {
|
||||
if ("plain-fn".equals(functionName)) {
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:plain-fn", "$LATEST", false, 0, 0);
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:plain-fn", "$LATEST", false, 0, 0, false);
|
||||
}
|
||||
String version = "live".equals(qualifier) ? liveVersion : "1";
|
||||
if (qualifier != null && !"live".equals(qualifier)) {
|
||||
@@ -369,11 +369,12 @@ class DurableExecutionServicePersistenceTest {
|
||||
}
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName + ":" + version, version, true,
|
||||
3600, 7);
|
||||
3600, 7, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId) {
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
|
||||
String traceId) {
|
||||
if (!target.durable()) {
|
||||
plainPayloads.add(new String(payload, StandardCharsets.UTF_8));
|
||||
return new DurableInvocationResult("req", plainOutput.getBytes(StandardCharsets.UTF_8), null);
|
||||
|
||||
+62
-6
@@ -34,9 +34,12 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
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.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -139,6 +142,51 @@ class DurableExecutionServiceTest {
|
||||
assertTrue(eventTypes(service.get(arn)).containsAll(List.of("WaitStarted", "WaitSucceeded")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReceivedTraceHeaderIsStoredAndPassedUnchangedToAPassThroughInvocation() {
|
||||
String header = "Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1";
|
||||
invoker.script(event -> succeeded("\"done\""));
|
||||
|
||||
DurableExecution execution = startWithTraceHeader("traced", header);
|
||||
|
||||
assertEquals(header, service.get(execution.getExecutionArn()).getTraceHeader());
|
||||
assertEquals(List.of(header), invoker.traceIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveFunctionKeepsRootAndSampledAndGetsANewParentOnEachInvocation() {
|
||||
invoker.activeTracing = true;
|
||||
invoker.script(event -> {
|
||||
checkpoint(event, token(event), List.of(waitStart("w1", 5)));
|
||||
return pending();
|
||||
});
|
||||
invoker.script(event -> succeeded("\"done\""));
|
||||
String header = "Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1";
|
||||
|
||||
startWithTraceHeader("active", header);
|
||||
clock.advance(Duration.ofSeconds(5));
|
||||
service.sweep();
|
||||
|
||||
assertEquals(2, invoker.traceIds.size());
|
||||
Pattern shape = Pattern.compile("Root=1-6af70000-0000000000000000000000aa;Parent=([0-9a-f]{16});Sampled=1");
|
||||
Matcher first = shape.matcher(invoker.traceIds.get(0));
|
||||
Matcher second = shape.matcher(invoker.traceIds.get(1));
|
||||
assertTrue(first.matches());
|
||||
assertTrue(second.matches());
|
||||
assertNotEquals(first.group(1), second.group(1));
|
||||
assertNotEquals("00000000000000a1", first.group(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStartWithoutATraceHeaderStoresANewOneForAPassThroughFunction() {
|
||||
invoker.script(event -> succeeded("\"done\""));
|
||||
|
||||
DurableExecution execution = start("untraced", "{}", true);
|
||||
|
||||
assertTrue(service.get(execution.getExecutionArn()).getTraceHeader()
|
||||
.matches("Root=1-[0-9a-f]{8}-[0-9a-f]{24};Parent=[0-9a-f]{16};Sampled=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepRetryBecomesReadyAfterItsDelay() {
|
||||
invoker.script(event -> {
|
||||
@@ -281,7 +329,7 @@ class DurableExecutionServiceTest {
|
||||
assertEquals(409, conflict.getHttpStatus());
|
||||
|
||||
AwsException otherVersion = assertThrows(AwsException.class, () -> service.start(
|
||||
new StartRequest(ACCOUNT, REGION, FUNCTION, "2", "same", "{\"a\":1}", true)));
|
||||
new StartRequest(ACCOUNT, REGION, FUNCTION, "2", "same", "{\"a\":1}", true, null)));
|
||||
assertEquals("Execution already started: " + first.getExecutionArn(), otherVersion.getMessage());
|
||||
}
|
||||
|
||||
@@ -489,7 +537,7 @@ class DurableExecutionServiceTest {
|
||||
|
||||
invoker.functionName = "other-fn";
|
||||
DurableExecution second = service.start(new StartRequest(ACCOUNT, REGION, "other-fn", "1", "shared", "{\"x\":1}",
|
||||
true));
|
||||
true, null));
|
||||
|
||||
assertFalse(first.getExecutionArn().equals(second.getExecutionArn()));
|
||||
assertEquals("\"b\"", service.get(second.getExecutionArn()).getResult());
|
||||
@@ -893,7 +941,11 @@ class DurableExecutionServiceTest {
|
||||
}
|
||||
|
||||
private DurableExecution start(String name, String payload, boolean synchronous) {
|
||||
return service.start(new StartRequest(ACCOUNT, REGION, FUNCTION, "1", name, payload, synchronous));
|
||||
return service.start(new StartRequest(ACCOUNT, REGION, FUNCTION, "1", name, payload, synchronous, null));
|
||||
}
|
||||
|
||||
private DurableExecution startWithTraceHeader(String name, String traceHeader) {
|
||||
return service.start(new StartRequest(ACCOUNT, REGION, FUNCTION, "1", name, "{}", false, traceHeader));
|
||||
}
|
||||
|
||||
private CheckpointResult checkpoint(JsonNode event, String token, List<DurableOperationUpdate> updates) {
|
||||
@@ -979,6 +1031,8 @@ class DurableExecutionServiceTest {
|
||||
int childExecutionTimeoutSeconds = 3600;
|
||||
String functionName = FUNCTION;
|
||||
int retentionPeriodInDays = 7;
|
||||
boolean activeTracing;
|
||||
final List<String> traceIds = new ArrayList<>();
|
||||
|
||||
void script(Function<JsonNode, DurableInvocationResult> script) {
|
||||
scripts.add(script);
|
||||
@@ -993,7 +1047,7 @@ class DurableExecutionServiceTest {
|
||||
String version = qualifier == null ? "$LATEST" : qualifier;
|
||||
if (plainFunctions.containsKey(functionName)) {
|
||||
return new ResolvedDurableTarget(accountId, region, functionName,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName, version, false, 0, 0);
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName, version, false, 0, 0, false);
|
||||
}
|
||||
String name = FUNCTION.equals(functionName) ? this.functionName : functionName;
|
||||
if (!name.equals(this.functionName) && !childScripts.containsKey(name)) {
|
||||
@@ -1003,11 +1057,12 @@ class DurableExecutionServiceTest {
|
||||
return new ResolvedDurableTarget(accountId, region, name,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:" + name + ":" + durableVersion, durableVersion,
|
||||
true, name.equals(this.functionName) ? executionTimeoutSeconds : childExecutionTimeoutSeconds,
|
||||
retentionPeriodInDays);
|
||||
retentionPeriodInDays, activeTracing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId) {
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
|
||||
String traceId) {
|
||||
JsonNode event;
|
||||
try {
|
||||
event = MAPPER.readTree(payload);
|
||||
@@ -1024,6 +1079,7 @@ class DurableExecutionServiceTest {
|
||||
}
|
||||
events.add(event);
|
||||
requestIds.add(requestId);
|
||||
traceIds.add(traceId);
|
||||
Function<JsonNode, DurableInvocationResult> script = scripts.poll();
|
||||
if (script == null) {
|
||||
return handlerResponse("{\"Status\":\"FAILED\",\"Error\":{\"ErrorMessage\":\"no script for "
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package io.floci.aws.services.lambda.durable;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DurableTraceHeaderTest {
|
||||
|
||||
private static final String ROOT = "1-6af70000-0000000000000000000000aa";
|
||||
private static final String PARENT = "00000000000000a1";
|
||||
private static final long NOW = 0x6af80000L;
|
||||
private static final String NEW_ROOT = "1-6af80000-[0-9a-f]{24}";
|
||||
private static final String NEW_ID = "[0-9a-f]{16}";
|
||||
|
||||
private static String execution(String received, boolean active) {
|
||||
return DurableTraceHeader.forExecution(received, active, NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noHeaderOnPassThroughGetsNewRootAndParentUnsampled() {
|
||||
assertTrue(execution(null, false).matches("Root=" + NEW_ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noHeaderOnActiveGetsNewRootAndParentSampled() {
|
||||
assertTrue(execution(null, true).matches("Root=" + NEW_ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullSampledHeaderOnPassThroughIsKept() {
|
||||
String header = "Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1";
|
||||
assertEquals(header, execution(header, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullUnsampledHeaderOnActiveIsKept() {
|
||||
String header = "Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=0";
|
||||
assertEquals(header, execution(header, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullSampledHeaderOnActiveGetsANewParent() {
|
||||
String stored = execution("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1", true);
|
||||
|
||||
assertTrue(stored.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
assertNotEquals("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1", stored);
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerWithoutSampledOnActiveGetsANewParentAndSampled() {
|
||||
String stored = execution("Root=" + ROOT + ";Parent=" + PARENT, true);
|
||||
|
||||
assertTrue(stored.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
assertNotEquals("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1", stored);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootOnlyOnActiveGetsANewParentAndSampled() {
|
||||
assertTrue(execution("Root=" + ROOT, true).matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootOnlyOnPassThroughGetsANewParentAndSampledZero() {
|
||||
assertTrue(execution("Root=" + ROOT, false).matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentWithoutSampledOnPassThroughKeepsTheParentAndIsUnsampled() {
|
||||
assertEquals("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=0",
|
||||
execution("Root=" + ROOT + ";Parent=" + PARENT, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsampledHeaderWithoutParentOnActiveStaysWithoutParent() {
|
||||
assertEquals("Root=" + ROOT + ";Sampled=0", execution("Root=" + ROOT + ";Sampled=0", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sampledHeaderWithoutParentOnPassThroughStaysWithoutParent() {
|
||||
assertEquals("Root=" + ROOT + ";Sampled=1", execution("Root=" + ROOT + ";Sampled=1", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidSampledCountsAsAbsent() {
|
||||
assertEquals("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=0",
|
||||
execution("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=?", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentAndSampledWithoutRootGetANewRoot() {
|
||||
assertTrue(execution("Parent=" + PARENT + ";Sampled=1", false)
|
||||
.matches("Root=" + NEW_ROOT + ";Parent=" + PARENT + ";Sampled=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageOnPassThroughIsReplacedByANewHeader() {
|
||||
assertTrue(execution("garbage", false).matches("Root=" + NEW_ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageOnActiveIsReplacedByANewHeader() {
|
||||
assertTrue(execution("garbage", true).matches("Root=" + NEW_ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvalidRootIsReplacedAndOnlyTheFirstOfAKeyCounts() {
|
||||
String stored = execution("Root=bad;Parent=" + PARENT + ";Parent=" + "1".repeat(16) + ";Sampled=1", false);
|
||||
|
||||
assertTrue(stored.matches("Root=" + NEW_ROOT + ";Parent=" + PARENT + ";Sampled=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fieldsAreTrimmedAndOtherKeysAreIgnored() {
|
||||
assertEquals("Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1",
|
||||
execution(" Self=1-x ; Root=" + ROOT + " ; Parent=" + PARENT + " ;Sampled=1", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeInvocationsShareRootAndSampledAndDifferInParent() {
|
||||
String stored = "Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1";
|
||||
|
||||
String first = DurableTraceHeader.forInvocation(stored, true);
|
||||
String second = DurableTraceHeader.forInvocation(stored, true);
|
||||
|
||||
assertTrue(first.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
assertTrue(second.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=1"));
|
||||
assertNotEquals(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeInvocationKeepsAnUnsampledHeaderWithAParent() {
|
||||
String header = DurableTraceHeader.forInvocation("Root=" + ROOT + ";Sampled=0", true);
|
||||
|
||||
assertTrue(header.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passThroughInvocationReturnsTheStoredHeader() {
|
||||
String stored = "Root=" + ROOT + ";Parent=" + PARENT + ";Sampled=1";
|
||||
assertEquals(stored, DurableTraceHeader.forInvocation(stored, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passThroughInvocationWithoutAParentGetsTheRootOnly() {
|
||||
assertEquals("Root=" + ROOT, DurableTraceHeader.forInvocation("Root=" + ROOT + ";Sampled=0", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invocationWithoutAStoredHeaderGetsNone() {
|
||||
assertNull(DurableTraceHeader.forInvocation(null, true));
|
||||
assertNull(DurableTraceHeader.forInvocation(null, false));
|
||||
}
|
||||
}
|
||||
+25
@@ -65,6 +65,31 @@ class LambdaDurableProtocolIntegrationTest {
|
||||
invoker.drain();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInvokeTraceHeaderReachesTheInvocationAndTheExecution() throws Exception {
|
||||
String traceHeader = "Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1";
|
||||
CompletableFuture<Response> invoke = CompletableFuture.supplyAsync(() -> given()
|
||||
.header("X-Amz-Durable-Execution-Name", "traced-1")
|
||||
.header("X-Amzn-Trace-Id", traceHeader)
|
||||
.body("{}")
|
||||
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations"));
|
||||
|
||||
Invocation invocation = invoker.awaitInvocation(Duration.ofSeconds(30));
|
||||
String arn = MAPPER.readTree(invocation.payload()).get("DurableExecutionArn").asText();
|
||||
assertEquals(traceHeader, invocation.traceId());
|
||||
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get(DURABLE + "/durable-executions/" + arn)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("TraceHeader.XAmznTraceId", equalTo(traceHeader));
|
||||
|
||||
invocation.response().complete(handlerResponse("{\"Status\": \"SUCCEEDED\", \"Result\": \"{}\"}"));
|
||||
assertEquals(200, invoke.get(30, TimeUnit.SECONDS).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSynchronousInvokeReturnsTheResultOfACheckpointedExecution() throws Exception {
|
||||
CompletableFuture<Response> invoke = CompletableFuture.supplyAsync(() -> given()
|
||||
|
||||
+4
-3
@@ -21,7 +21,7 @@ import java.util.concurrent.TimeoutException;
|
||||
@ApplicationScoped
|
||||
public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker {
|
||||
|
||||
public record Invocation(ResolvedDurableTarget target, byte[] payload,
|
||||
public record Invocation(ResolvedDurableTarget target, byte[] payload, String traceId,
|
||||
CompletableFuture<DurableInvocationResult> response) {
|
||||
}
|
||||
|
||||
@@ -39,8 +39,9 @@ public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId) {
|
||||
Invocation invocation = new Invocation(target, payload, new CompletableFuture<>());
|
||||
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
|
||||
String traceId) {
|
||||
Invocation invocation = new Invocation(target, payload, traceId, new CompletableFuture<>());
|
||||
invocations.add(invocation);
|
||||
try {
|
||||
return invocation.response().get(30, TimeUnit.SECONDS);
|
||||
|
||||
@@ -161,6 +161,31 @@ class RuntimeApiServerTest {
|
||||
assertTrue(second.headers().firstValue("Lambda-Runtime-Client-Context").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void nextEndpoint_emitsTraceIdHeaderOnlyWhenPresent() throws Exception {
|
||||
String traceId = "Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1";
|
||||
PendingInvocation withTrace = new PendingInvocation(
|
||||
"req-trace", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>());
|
||||
withTrace.setTraceId(traceId);
|
||||
server.enqueue(withTrace);
|
||||
|
||||
HttpRequest next = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/2018-06-01/runtime/invocation/next"))
|
||||
.GET().build();
|
||||
HttpResponse<String> first = httpClient.send(next, HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(traceId, first.headers().firstValue("Lambda-Runtime-Trace-Id").orElse(null));
|
||||
|
||||
server.enqueue(new PendingInvocation(
|
||||
"req-notrace", "{}".getBytes(), System.currentTimeMillis() + 60_000,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:test",
|
||||
new CompletableFuture<>()));
|
||||
HttpResponse<String> second = httpClient.send(next, HttpResponse.BodyHandlers.ofString());
|
||||
assertTrue(second.headers().firstValue("Lambda-Runtime-Trace-Id").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(10)
|
||||
void nextEndpoint_startsDeadlineWhenInvocationIsDispatched() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user