mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambda): durable function callbacks (#5100)
* feat(lambda): durable function callbacks
A CALLBACK operation started at checkpoint gets a callback id that
SendDurableExecutionCallbackSuccess, Failure and Heartbeat complete or
keep alive, after which the function is invoked again to see it.
TimeoutSeconds and HeartbeatTimeoutSeconds time it out with
Callback.Timeout or Callback.Heartbeat. A completed, timed out or
stopped callback answers CallbackTimeoutException, an unreadable id
"Invalid callback id". The callback id carries the execution ARN, which
IAM authorizes the callback actions against.
Option range errors now name the update, as AWS does
("updates.1.member.waitOptions.waitSeconds").
* fix(lambda): name a repeated durable update as AWS does
AWS rejects two updates of one operation in a batch, other than a START
closed by its STEP or CONTEXT action, with "Cannot update the same
operation twice in a single request."
* fix(lambda): leave a durable execution waiting after a body-less callback failure
AWS marks a callback failed with an empty request body as FAILED but does
not invoke the function again, so the execution keeps waiting. The SDKs
send {} when Error is omitted, which does invoke it.
* fix(lambda): bound a durable callback failure's error at 1 MB
AWS rejects an Error over 1048576 bytes, measured as compact JSON, with
InvalidParameterValueException "Error object size must be less than or
equal to 1048576 bytes."
* test(lambda): keep a pending durable callback across a restart
* fix(lambda): reject a durable callback failure body that is not a JSON object
AWS treats only an empty body as a failure with no Error. Whitespace,
null or broken JSON get 400 SerializationException and leave the
callback open.
* docs(lambda): note the durable callback result limit AWS enforces
This commit is contained in:
1 parent
a6df1dbb12
commit
a1ed65c51d
20 files changed
+809
-50
No files matched your search
@@ -68,6 +68,11 @@ public class IamActionRegistry {
|
||||
rule("lambda", "GET", ".*/durable-executions/.+/history$", "lambda:GetDurableExecutionHistory"),
|
||||
rule("lambda", "POST", ".*/durable-executions/.+/stop$", "lambda:StopDurableExecution"),
|
||||
rule("lambda", "GET", ".*/durable-executions/.+$", "lambda:GetDurableExecution"),
|
||||
rule("lambda", "POST", ".*/durable-execution-callbacks/.+/succeed$",
|
||||
"lambda:SendDurableExecutionCallbackSuccess"),
|
||||
rule("lambda", "POST", ".*/durable-execution-callbacks/.+/fail$", "lambda:SendDurableExecutionCallbackFailure"),
|
||||
rule("lambda", "POST", ".*/durable-execution-callbacks/.+/heartbeat$",
|
||||
"lambda:SendDurableExecutionCallbackHeartbeat"),
|
||||
|
||||
// ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──
|
||||
// Handled via Query-style action extraction in the filter
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -224,6 +225,9 @@ public class ResourceArnBuilder {
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────────
|
||||
private String buildLambdaArn(String path, String region, String accountId) {
|
||||
String executionArn = durableExecutionArn(path);
|
||||
if (executionArn == null) {
|
||||
executionArn = durableCallbackExecutionArn(path);
|
||||
}
|
||||
if (executionArn != null) {
|
||||
return executionArn;
|
||||
}
|
||||
@@ -247,6 +251,19 @@ public class ResourceArnBuilder {
|
||||
return matcher.lookingAt() ? matcher.group() : null;
|
||||
}
|
||||
|
||||
/** A callback id carries its execution ARN, so the callback actions are authorized against that execution. */
|
||||
private static String durableCallbackExecutionArn(String path) {
|
||||
String prefix = "/durable-execution-callbacks/";
|
||||
int callbacks = path.indexOf(prefix);
|
||||
int action = path.lastIndexOf('/');
|
||||
if (callbacks < 0 || action <= callbacks + prefix.length()) {
|
||||
return null;
|
||||
}
|
||||
return DurableTokens.callbackExecutionArn(path.substring(callbacks + prefix.length(), action))
|
||||
.filter(arn -> LambdaArnUtils.DURABLE_EXECUTION_ARN.matcher(arn).matches())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
// ── SQS ─────────────────────────────────────────────────────────────────────
|
||||
private String buildSqsArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
String queueUrl = ctx.getUriInfo().getQueryParameters().getFirst("QueueUrl");
|
||||
|
||||
+57
-3
@@ -48,7 +48,7 @@ final class DurableCheckpointApplier {
|
||||
return new Outcome(draft.closingStatus != null);
|
||||
}
|
||||
|
||||
/** Completes waits and step retries whose time has come. The sweeper and every checkpoint call it. */
|
||||
/** Completes waits, step retries and callback timeouts whose time has come. The sweeper and every checkpoint call it. */
|
||||
static boolean fireDueTimers(DurableExecution execution, long now) {
|
||||
boolean changed = false;
|
||||
for (DurableOperation operation : execution.getOperations().values()) {
|
||||
@@ -71,11 +71,38 @@ final class DurableCheckpointApplier {
|
||||
operation.setNextAttemptTimestamp(null);
|
||||
operation.setChangeSequence(execution.nextChangeSequence());
|
||||
changed = true;
|
||||
} else if (operation.getType() == DurableOperationType.CALLBACK
|
||||
&& operation.getStatus() == DurableOperationStatus.STARTED) {
|
||||
changed |= timeOutCallback(execution, operation, now);
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static boolean timeOutCallback(DurableExecution execution, DurableOperation operation, long now) {
|
||||
boolean timedOut = operation.getCallbackDeadline() != null && operation.getCallbackDeadline() <= now;
|
||||
boolean heartbeatMissed = operation.getHeartbeatDeadline() != null && operation.getHeartbeatDeadline() <= now;
|
||||
if (!timedOut && !heartbeatMissed) {
|
||||
return false;
|
||||
}
|
||||
boolean heartbeatFirst = heartbeatMissed
|
||||
&& (!timedOut || operation.getHeartbeatDeadline() < operation.getCallbackDeadline());
|
||||
DurableErrorObject error = heartbeatFirst
|
||||
? DurableErrorObject.of("Callback timed out on heartbeat", "Callback.Heartbeat")
|
||||
: DurableErrorObject.of("Callback timed out", "Callback.Timeout");
|
||||
operation.setStatus(DurableOperationStatus.TIMED_OUT);
|
||||
operation.setError(error);
|
||||
operation.setEndTimestamp(now);
|
||||
operation.setCallbackDeadline(null);
|
||||
operation.setHeartbeatDeadline(null);
|
||||
operation.setChangeSequence(execution.nextChangeSequence());
|
||||
// The history event names only the error type.
|
||||
Map<String, Object> details = new LinkedHashMap<>();
|
||||
details.put("Error", DurableHistory.errorWrapper(DurableErrorObject.of(null, error.getErrorType())));
|
||||
DurableHistory.operationEvent(execution, operation, "CallbackTimedOut", now, details);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void validateBatch(List<DurableOperationUpdate> updates) {
|
||||
long executionUpdates = updates.stream().filter(update -> update.type() == DurableOperationType.EXECUTION).count();
|
||||
if (executionUpdates > 1) {
|
||||
@@ -93,7 +120,7 @@ final class DurableCheckpointApplier {
|
||||
DurableOperationUpdate previous = seen.put(update.id(), update);
|
||||
if (previous != null && !(previous.action() == DurableOperationAction.START
|
||||
&& previous.type() == update.type() && closesInSameBatch(update))) {
|
||||
throw invalid("Cannot checkpoint multiple operations with the same ID.");
|
||||
throw invalid("Cannot update the same operation twice in a single request.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,7 +197,8 @@ final class DurableCheckpointApplier {
|
||||
case CONTEXT -> applyContext(update, existing);
|
||||
case STEP -> applyStep(update, existing);
|
||||
case WAIT -> applyWait(update, existing);
|
||||
case CALLBACK, CHAINED_INVOKE -> throw invalid(update.type() + " operations are not supported yet");
|
||||
case CALLBACK -> applyCallback(update, existing);
|
||||
case CHAINED_INVOKE -> throw invalid(update.type() + " operations are not supported yet");
|
||||
default -> throw invalid("Unknown operation type.");
|
||||
}
|
||||
}
|
||||
@@ -340,6 +368,32 @@ final class DurableCheckpointApplier {
|
||||
}
|
||||
}
|
||||
|
||||
/** Only the function starts a callback. SendDurableExecutionCallback* completes it. */
|
||||
private void applyCallback(DurableOperationUpdate update, DurableOperation existing) {
|
||||
if (update.action() != DurableOperationAction.START) {
|
||||
throw invalid("Invalid action for the given operation type.");
|
||||
}
|
||||
if (existing != null) {
|
||||
throw invalid("Cannot start a CALLBACK that already exist.");
|
||||
}
|
||||
DurableOperation operation = create(update);
|
||||
operation.setCallbackId(DurableTokens.callbackId(execution.getExecutionArn(), update.id()));
|
||||
Map<String, Object> details = new LinkedHashMap<>();
|
||||
details.put("CallbackId", operation.getCallbackId());
|
||||
Integer timeout = update.callbackTimeoutSeconds();
|
||||
if (timeout != null && timeout > 0) {
|
||||
operation.setCallbackDeadline(now + timeout * 1000L);
|
||||
details.put("Timeout", timeout);
|
||||
}
|
||||
Integer heartbeat = update.callbackHeartbeatTimeoutSeconds();
|
||||
if (heartbeat != null && heartbeat > 0) {
|
||||
operation.setHeartbeatTimeoutSeconds(heartbeat);
|
||||
operation.setHeartbeatDeadline(now + heartbeat * 1000L);
|
||||
details.put("HeartbeatTimeout", heartbeat);
|
||||
}
|
||||
event(operation, "CallbackStarted", details);
|
||||
}
|
||||
|
||||
private static void requireMatchingResult(DurableOperationUpdate update) {
|
||||
if (update.action() == DurableOperationAction.SUCCEED && update.error() != null) {
|
||||
throw invalid("Cannot provide an Error for SUCCEED action.");
|
||||
|
||||
+58
@@ -28,6 +28,7 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -53,6 +54,7 @@ public class DurableExecutionController {
|
||||
|
||||
/** Valid Statuses filters for a state Floci never puts an execution in. */
|
||||
private static final Set<String> UNMODELLED_STATUSES = Set.of("PAUSED", "PAUSING", "DELETING");
|
||||
private static final int MAX_CALLBACK_PAYLOAD_BYTES = 1024 * 1024;
|
||||
|
||||
private final DurableExecutionService service;
|
||||
private final LambdaService lambdaService;
|
||||
@@ -179,6 +181,48 @@ public class DurableExecutionController {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/durable-execution-callbacks/{callbackId: .+}/succeed")
|
||||
public Response callbackSucceed(@Context HttpHeaders headers, @PathParam("callbackId") String callbackId,
|
||||
byte[] body) {
|
||||
if (body != null && MAX_CALLBACK_PAYLOAD_BYTES < body.length) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value at 'result' failed to "
|
||||
+ "satisfy constraint: Member must have length less than or equal to " + MAX_CALLBACK_PAYLOAD_BYTES,
|
||||
400);
|
||||
}
|
||||
String result = body == null || body.length == 0 ? null : new String(body, StandardCharsets.UTF_8);
|
||||
service.completeCallback(callbackId, regionResolver.getAccountId(), regionResolver.resolveRegion(headers), true,
|
||||
result, null);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Without a body the callback fails with no Error, and AWS does not invoke the function for it.
|
||||
* Any other body must be a JSON object.
|
||||
*/
|
||||
@POST
|
||||
@Path("/durable-execution-callbacks/{callbackId: .+}/fail")
|
||||
public Response callbackFail(@Context HttpHeaders headers, @PathParam("callbackId") String callbackId,
|
||||
String body) {
|
||||
DurableErrorObject error = body == null || body.isEmpty() ? null : parseCallbackError(body);
|
||||
// AWS measures the error as compact JSON, whatever spacing the request used.
|
||||
if (error != null
|
||||
&& MAX_CALLBACK_PAYLOAD_BYTES < DurableCheckpointApplier.utf8Length(DurableWire.error(error).toString())) {
|
||||
throw new AwsException("InvalidParameterValueException", "Error object size must be less than or equal to "
|
||||
+ MAX_CALLBACK_PAYLOAD_BYTES + " bytes.", 400);
|
||||
}
|
||||
service.completeCallback(callbackId, regionResolver.getAccountId(), regionResolver.resolveRegion(headers), false,
|
||||
null, error);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/durable-execution-callbacks/{callbackId: .+}/heartbeat")
|
||||
public Response callbackHeartbeat(@Context HttpHeaders headers, @PathParam("callbackId") String callbackId) {
|
||||
service.heartbeatCallback(callbackId, regionResolver.getAccountId(), regionResolver.resolveRegion(headers));
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* An execution of another account is not found. One of another region reads as "Function not found",
|
||||
* as AWS answers for an execution ARN of another region.
|
||||
@@ -194,6 +238,20 @@ public class DurableExecutionController {
|
||||
return arn;
|
||||
}
|
||||
|
||||
/** AWS answers whitespace, null or broken JSON with a SerializationException that has no message. */
|
||||
private DurableErrorObject parseCallbackError(String body) {
|
||||
Map<String, Object> error;
|
||||
try {
|
||||
error = objectMapper.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||
} catch (IOException e) {
|
||||
error = null;
|
||||
}
|
||||
if (error == null) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
return DurableWire.parseError(error);
|
||||
}
|
||||
|
||||
private Map<String, Object> readObject(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return Map.of();
|
||||
|
||||
+98
@@ -34,6 +34,7 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -75,6 +76,8 @@ public class DurableExecutionService implements Resettable {
|
||||
static final String INVALID_TOKEN = "Invalid checkpoint token";
|
||||
static final String TOKEN_FOR_OTHER_EXECUTION = "Checkpoint token is not valid for the durable execution ARN";
|
||||
static final String NOT_FOUND = "Durable Execution does not exist";
|
||||
static final String INVALID_CALLBACK_ID = "Invalid callback id";
|
||||
static final String CALLBACK_CLOSED = "The callback is either timed out or already completed";
|
||||
|
||||
private final AccountAwareStorageBackend<DurableExecution> store;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -300,6 +303,101 @@ public class DurableExecutionService implements Resettable {
|
||||
return execution;
|
||||
}
|
||||
|
||||
/**
|
||||
* SendDurableExecutionCallbackSuccess when {@code succeeded}, else SendDurableExecutionCallbackFailure.
|
||||
* The callback's operation completes and the function is invoked again to see it, except for a
|
||||
* failure sent with no body: AWS records it but does not invoke the function.
|
||||
*/
|
||||
public void completeCallback(String callbackId, String accountId, String region, boolean succeeded, String result,
|
||||
DurableErrorObject error) {
|
||||
DurableTokens.CallbackId id = parseCallbackId(callbackId);
|
||||
ArnParts arn = callbackArn(id, accountId, region);
|
||||
List<Runnable> effects = new ArrayList<>();
|
||||
synchronized (lockFor(arn)) {
|
||||
long now = clock.millis();
|
||||
DurableExecution execution = loadPendingCallbackExecution(arn, id, callbackId, now);
|
||||
DurableOperation operation = execution.getOperations().get(id.operationId());
|
||||
operation.setStatus(succeeded ? DurableOperationStatus.SUCCEEDED : DurableOperationStatus.FAILED);
|
||||
operation.setResult(succeeded ? result : null);
|
||||
operation.setError(succeeded ? null : error);
|
||||
operation.setEndTimestamp(now);
|
||||
operation.setCallbackDeadline(null);
|
||||
operation.setHeartbeatDeadline(null);
|
||||
operation.setChangeSequence(execution.nextChangeSequence());
|
||||
Map<String, Object> details = new LinkedHashMap<>();
|
||||
if (succeeded) {
|
||||
details.put("Result", DurableHistory.payloadWrapper(result));
|
||||
} else {
|
||||
details.put("Error", DurableHistory.errorWrapper(error));
|
||||
}
|
||||
DurableHistory.operationEvent(execution, operation, succeeded ? "CallbackSucceeded" : "CallbackFailed",
|
||||
now, details);
|
||||
if (succeeded || error != null) {
|
||||
trigger(execution, effects);
|
||||
}
|
||||
save(execution);
|
||||
}
|
||||
runEffects(effects);
|
||||
}
|
||||
|
||||
/** SendDurableExecutionCallbackHeartbeat. It moves the heartbeat deadline when the callback has one. */
|
||||
public void heartbeatCallback(String callbackId, String accountId, String region) {
|
||||
DurableTokens.CallbackId id = parseCallbackId(callbackId);
|
||||
ArnParts arn = callbackArn(id, accountId, region);
|
||||
synchronized (lockFor(arn)) {
|
||||
long now = clock.millis();
|
||||
DurableExecution execution = loadPendingCallbackExecution(arn, id, callbackId, now);
|
||||
DurableOperation operation = execution.getOperations().get(id.operationId());
|
||||
if (operation.getHeartbeatTimeoutSeconds() != null) {
|
||||
operation.setHeartbeatDeadline(now + operation.getHeartbeatTimeoutSeconds() * 1000L);
|
||||
save(execution);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static DurableTokens.CallbackId parseCallbackId(String callbackId) {
|
||||
return DurableTokens.parseCallbackId(callbackId)
|
||||
.orElseThrow(() -> new AwsException("InvalidParameterValueException", INVALID_CALLBACK_ID, 400));
|
||||
}
|
||||
|
||||
/** A callback of another account or region is one this caller cannot complete. */
|
||||
private static ArnParts callbackArn(DurableTokens.CallbackId id, String accountId, String region) {
|
||||
ArnParts arn;
|
||||
try {
|
||||
arn = parseArn(id.executionArn());
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("InvalidParameterValueException", INVALID_CALLBACK_ID, 400);
|
||||
}
|
||||
if (!arn.accountId().equals(accountId) || !arn.region().equals(region)) {
|
||||
throw callbackClosed();
|
||||
}
|
||||
return arn;
|
||||
}
|
||||
|
||||
/** A callback past its deadline is closed even before the sweeper records the timeout. */
|
||||
private DurableExecution loadPendingCallbackExecution(ArnParts arn, DurableTokens.CallbackId id, String callbackId,
|
||||
long now) {
|
||||
DurableExecution execution = store.getForAccount(arn.accountId(), arn.storeKey())
|
||||
.filter(candidate -> candidate.getExecutionArn().equals(arn.arn()))
|
||||
.orElseThrow(DurableExecutionService::callbackClosed);
|
||||
DurableOperation operation = execution.getOperations().get(id.operationId());
|
||||
if (execution.isClosed() || operation == null || operation.getType() != DurableOperationType.CALLBACK
|
||||
|| operation.getStatus() != DurableOperationStatus.STARTED
|
||||
|| !callbackId.equals(operation.getCallbackId())
|
||||
|| isPast(operation.getCallbackDeadline(), now) || isPast(operation.getHeartbeatDeadline(), now)) {
|
||||
throw callbackClosed();
|
||||
}
|
||||
return execution;
|
||||
}
|
||||
|
||||
private static boolean isPast(Long deadline, long now) {
|
||||
return deadline != null && deadline <= now;
|
||||
}
|
||||
|
||||
private static AwsException callbackClosed() {
|
||||
return new AwsException("CallbackTimeoutException", CALLBACK_CLOSED, 400);
|
||||
}
|
||||
|
||||
/** One tick of {@link DurableExecutionSweeper}. It fires due timers, times out and expires executions. */
|
||||
public void sweep() {
|
||||
long now = clock.millis();
|
||||
|
||||
+32
-2
@@ -3,13 +3,18 @@ package io.github.hectorvent.floci.services.lambda.durable;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The opaque CheckpointToken of the durable execution protocol, standard base64 as AWS documents it.
|
||||
* The opaque CheckpointToken and CallbackId of the durable execution protocol, standard base64 as
|
||||
* AWS documents them. A CallbackId carries its execution ARN, which IAM authorizes against.
|
||||
*/
|
||||
final class DurableTokens {
|
||||
public final class DurableTokens {
|
||||
|
||||
private static final String SEPARATOR = "|";
|
||||
private static final Pattern CALLBACK_ID_PATTERN = Pattern.compile("[A-Za-z0-9+/]+={0,2}");
|
||||
private static final int MAX_CALLBACK_ID_LENGTH = 1024;
|
||||
|
||||
private DurableTokens() {
|
||||
}
|
||||
@@ -17,6 +22,9 @@ final class DurableTokens {
|
||||
record CheckpointToken(String executionArn, String invocationId, long sequence) {
|
||||
}
|
||||
|
||||
record CallbackId(String executionArn, String operationId) {
|
||||
}
|
||||
|
||||
static String checkpointToken(String executionArn, String invocationId, long sequence) {
|
||||
return encode(executionArn + SEPARATOR + invocationId + SEPARATOR + sequence);
|
||||
}
|
||||
@@ -41,6 +49,28 @@ final class DurableTokens {
|
||||
}
|
||||
}
|
||||
|
||||
/** The nonce keeps an id from matching a later callback that reuses the operation id. */
|
||||
static String callbackId(String executionArn, String operationId) {
|
||||
return encode(executionArn + SEPARATOR + operationId + SEPARATOR + UUID.randomUUID());
|
||||
}
|
||||
|
||||
static Optional<CallbackId> parseCallbackId(String callbackId) {
|
||||
if (callbackId == null || callbackId.length() > MAX_CALLBACK_ID_LENGTH
|
||||
|| !CALLBACK_ID_PATTERN.matcher(callbackId).matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String decoded = decode(callbackId);
|
||||
String[] parts = decoded == null ? new String[0] : decoded.split("\\" + SEPARATOR, -1);
|
||||
if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new CallbackId(parts[0], parts[1]));
|
||||
}
|
||||
|
||||
public static Optional<String> callbackExecutionArn(String callbackId) {
|
||||
return parseCallbackId(callbackId).map(CallbackId::executionArn);
|
||||
}
|
||||
|
||||
private static String encode(String value) {
|
||||
return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ public final class DurableWire {
|
||||
|
||||
private static final JsonNodeFactory NODES = JsonNodeFactory.instance;
|
||||
private static final long MAX_DELAY_SECONDS = 31_622_400L;
|
||||
private static final long MAX_CALLBACK_TIMEOUT_SECONDS = 99_999_999L;
|
||||
|
||||
private DurableWire() {
|
||||
}
|
||||
@@ -118,6 +119,11 @@ public final class DurableWire {
|
||||
putTimestamp(details, "ScheduledEndTimestamp", operation.getScheduledEndTimestamp(), millis);
|
||||
}
|
||||
}
|
||||
case CALLBACK -> {
|
||||
ObjectNode details = node.putObject("CallbackDetails");
|
||||
putIfPresent(details, "CallbackId", operation.getCallbackId());
|
||||
putResultAndError(details, operation);
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
@@ -203,7 +209,7 @@ public final class DurableWire {
|
||||
if (!(item instanceof Map<?, ?> map)) {
|
||||
throw new AwsException("SerializationException", "Updates members must be JSON objects", 400);
|
||||
}
|
||||
updates.add(parseUpdate(map));
|
||||
updates.add(parseUpdate(map, "updates." + (updates.size() + 1) + ".member."));
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
@@ -250,12 +256,14 @@ public final class DurableWire {
|
||||
result != null && result.isTextual() ? result.asText() : null, error);
|
||||
}
|
||||
|
||||
private static DurableOperationUpdate parseUpdate(Map<?, ?> map) {
|
||||
/** {@code path} prefixes the member in a ValidationException, as in "updates.1.member.waitOptions.waitSeconds". */
|
||||
private static DurableOperationUpdate parseUpdate(Map<?, ?> map, String path) {
|
||||
DurableOperationType type = enumMember(map, "Type", DurableOperationType.class);
|
||||
DurableOperationAction action = enumMember(map, "Action", DurableOperationAction.class);
|
||||
Map<?, ?> stepOptions = structure(map, "StepOptions");
|
||||
Map<?, ?> waitOptions = structure(map, "WaitOptions");
|
||||
Map<?, ?> contextOptions = structure(map, "ContextOptions");
|
||||
Map<?, ?> callbackOptions = structure(map, "CallbackOptions");
|
||||
return new DurableOperationUpdate(
|
||||
string(map, "Id"),
|
||||
string(map, "ParentId"),
|
||||
@@ -265,9 +273,12 @@ public final class DurableWire {
|
||||
action,
|
||||
string(map, "Payload"),
|
||||
parseError(map.get("Error")),
|
||||
stepOptions == null ? null : integer(stepOptions, "NextAttemptDelaySeconds", "StepOptions"),
|
||||
waitOptions == null ? null : integer(waitOptions, "WaitSeconds", "WaitOptions"),
|
||||
contextOptions == null ? null : bool(contextOptions, "ReplayChildren"));
|
||||
integer(stepOptions, "NextAttemptDelaySeconds", path + "stepOptions", 1, MAX_DELAY_SECONDS),
|
||||
integer(waitOptions, "WaitSeconds", path + "waitOptions", 1, MAX_DELAY_SECONDS),
|
||||
contextOptions == null ? null : bool(contextOptions, "ReplayChildren"),
|
||||
integer(callbackOptions, "TimeoutSeconds", path + "callbackOptions", 0, MAX_CALLBACK_TIMEOUT_SECONDS),
|
||||
integer(callbackOptions, "HeartbeatTimeoutSeconds", path + "callbackOptions", 0,
|
||||
MAX_CALLBACK_TIMEOUT_SECONDS));
|
||||
}
|
||||
|
||||
private static <E extends Enum<E>> E enumMember(Map<?, ?> map, String member, Class<E> type) {
|
||||
@@ -305,20 +316,19 @@ public final class DurableWire {
|
||||
throw new AwsException("SerializationException", member + " must be a string", 400);
|
||||
}
|
||||
|
||||
private static Integer integer(Map<?, ?> map, String member, String structure) {
|
||||
Object value = map.get(member);
|
||||
private static Integer integer(Map<?, ?> structure, String member, String structurePath, long min, long max) {
|
||||
Object value = structure == null ? null : structure.get(member);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String field = structurePath + "." + Character.toLowerCase(member.charAt(0)) + member.substring(1);
|
||||
if (!(value instanceof Number number && (number instanceof Byte || number instanceof Short
|
||||
|| number instanceof Integer || number instanceof Long))) {
|
||||
throw new AwsException("SerializationException", structure + "." + member + " must be an integer", 400);
|
||||
throw new AwsException("SerializationException", field + " must be an integer", 400);
|
||||
}
|
||||
long seconds = number.longValue();
|
||||
if (seconds < 1 || MAX_DELAY_SECONDS < seconds) {
|
||||
String field = Character.toLowerCase(structure.charAt(0)) + structure.substring(1) + "."
|
||||
+ Character.toLowerCase(member.charAt(0)) + member.substring(1);
|
||||
String bound = seconds < 1 ? "greater than or equal to 1" : "less than or equal to " + MAX_DELAY_SECONDS;
|
||||
if (seconds < min || max < seconds) {
|
||||
String bound = seconds < min ? "greater than or equal to " + min : "less than or equal to " + max;
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + seconds
|
||||
+ "' at '" + field + "' failed to satisfy constraint: Member must have value " + bound, 400);
|
||||
}
|
||||
|
||||
+6
-1
@@ -66,7 +66,7 @@ public class DurableExecution {
|
||||
return changeSequence > seenSequence;
|
||||
}
|
||||
|
||||
/** True while a wait or a step retry is still pending. */
|
||||
/** True while a wait, a step retry or a callback is still pending. */
|
||||
@JsonIgnore
|
||||
public boolean hasPendingOperations() {
|
||||
for (DurableOperation operation : operations.values()) {
|
||||
@@ -83,6 +83,11 @@ public class DurableExecution {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
case CALLBACK -> {
|
||||
if (operationStatus == DurableOperationStatus.STARTED) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
|
||||
+23
@@ -29,6 +29,11 @@ public class DurableOperation {
|
||||
private Integer attempt;
|
||||
private Long nextAttemptTimestamp;
|
||||
private Long scheduledEndTimestamp;
|
||||
private String callbackId;
|
||||
private Integer heartbeatTimeoutSeconds;
|
||||
private Long callbackDeadline;
|
||||
/** Moves forward on every SendDurableExecutionCallbackHeartbeat. */
|
||||
private Long heartbeatDeadline;
|
||||
/** Position in the execution's change log. The handler is only shown operations newer than it has seen. */
|
||||
private long changeSequence;
|
||||
|
||||
@@ -52,6 +57,10 @@ public class DurableOperation {
|
||||
copy.attempt = attempt;
|
||||
copy.nextAttemptTimestamp = nextAttemptTimestamp;
|
||||
copy.scheduledEndTimestamp = scheduledEndTimestamp;
|
||||
copy.callbackId = callbackId;
|
||||
copy.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds;
|
||||
copy.callbackDeadline = callbackDeadline;
|
||||
copy.heartbeatDeadline = heartbeatDeadline;
|
||||
copy.changeSequence = changeSequence;
|
||||
return copy;
|
||||
}
|
||||
@@ -101,6 +110,20 @@ public class DurableOperation {
|
||||
public Long getScheduledEndTimestamp() { return scheduledEndTimestamp; }
|
||||
public void setScheduledEndTimestamp(Long scheduledEndTimestamp) { this.scheduledEndTimestamp = scheduledEndTimestamp; }
|
||||
|
||||
public String getCallbackId() { return callbackId; }
|
||||
public void setCallbackId(String callbackId) { this.callbackId = callbackId; }
|
||||
|
||||
public Integer getHeartbeatTimeoutSeconds() { return heartbeatTimeoutSeconds; }
|
||||
public void setHeartbeatTimeoutSeconds(Integer heartbeatTimeoutSeconds) {
|
||||
this.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds;
|
||||
}
|
||||
|
||||
public Long getCallbackDeadline() { return callbackDeadline; }
|
||||
public void setCallbackDeadline(Long callbackDeadline) { this.callbackDeadline = callbackDeadline; }
|
||||
|
||||
public Long getHeartbeatDeadline() { return heartbeatDeadline; }
|
||||
public void setHeartbeatDeadline(Long heartbeatDeadline) { this.heartbeatDeadline = heartbeatDeadline; }
|
||||
|
||||
public long getChangeSequence() { return changeSequence; }
|
||||
public void setChangeSequence(long changeSequence) { this.changeSequence = changeSequence; }
|
||||
}
|
||||
+3
-1
@@ -14,5 +14,7 @@ public record DurableOperationUpdate(String id,
|
||||
DurableErrorObject error,
|
||||
Integer nextAttemptDelaySeconds,
|
||||
Integer waitSeconds,
|
||||
Boolean replayChildren) {
|
||||
Boolean replayChildren,
|
||||
Integer callbackTimeoutSeconds,
|
||||
Integer callbackHeartbeatTimeoutSeconds) {
|
||||
}
|
||||
Reference in new issue
Block a user