feat(scheduler): substitute schedule context attributes in target Input (#5194)

* feat(scheduler): substitute schedule context attributes in target Input

Replace <aws.scheduler.schedule-arn>, <aws.scheduler.scheduled-time>,
<aws.scheduler.execution-id> and <aws.scheduler.attempt-number> in the
target Input for templated and universal targets, using the occurrence's
scheduled time and the retry attempt the dispatcher tracks.

* test(scheduler): share one harness between the scheduler integration tests

SchedulerContextAttributesIntegrationTest copied its schedule creation,
scoped dispatcher, unique names and cleanup from
SchedulerStepFunctionsIntegrationTest. Both now use SchedulerTestHarness,
which also builds the at() expression they each formatted by hand.

* fix(scheduler): keep dead-letter context aligned with the last attempt

Materialize the target request before every invocation so an exhausted
occurrence's dead-letter body carries the same execution id and attempt
number as its last attempted delivery. Preserve that request when the
occurrence expires before another retry.

Share scheduled-time formatting across context attributes, default events
and dead-letter attributes. Cover retry-count and event-age exhaustion
and remove the documented first-attempt body limitation.

* style(scheduler): fix shared harness static import order

Place ROLE_ARN before atExpression to satisfy the ImportOrder rule used
by the PR's merged Checkstyle configuration.
This commit is contained in:
Salil Chincholikar authored and GitHub committed 2026-10-09 12:08:34 -04:00
1 parent 5dfb45d71f
commit 07ebc33d28
8 files changed
+606 -143

No files matched your search

@@ -19,14 +19,12 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -208,9 +206,9 @@ public class ScheduleDispatcher implements Resettable {
// Record the fire before delivering so a failing occurrence never holds back the next one.
recordFire(schedule, now);
String requestBody = invoker.materializeRequest(schedule, nextFire);
String executionId = ScheduleInvoker.newExecutionId();
attempt(schedule, new Occurrence(schedule.getArn(), nextFire),
Delivery.first(kind, schedule, requestBody), now);
Delivery.first(kind, schedule, executionId), now);
}
private Instant computeNextFire(Schedule schedule, Kind kind, Instant now) {
@@ -242,8 +240,11 @@ public class ScheduleDispatcher implements Resettable {
}
private void attempt(Schedule schedule, Occurrence occurrence, Delivery delivery, Instant now) {
String requestBody = invoker.materializeRequest(schedule, occurrence.scheduledAt(),
delivery.executionId(), delivery.attemptNumber());
delivery = delivery.withRequestBody(requestBody);
try {
invoker.invoke(schedule, occurrence.scheduledAt());
invoker.invoke(schedule, occurrence.scheduledAt(), delivery.executionId(), delivery.attemptNumber());
} catch (Exception e) {
LOG.warnv("Schedule {0} invocation failed: {1}", schedule.getArn(), e.getMessage());
Delivery failed = delivery.failedWith(e, now);
@@ -304,7 +305,7 @@ public class ScheduleDispatcher implements Resettable {
attributes.put("IS_PAYLOAD_TRUNCATED", stringAttribute("false"));
attributes.put("RETRY_ATTEMPTS", stringAttribute(String.valueOf(delivery.retryAttempts())));
attributes.put("SCHEDULED_TIME", stringAttribute(
occurrence.scheduledAt().truncatedTo(ChronoUnit.SECONDS).toString()));
ScheduleInvoker.formatScheduledTime(occurrence.scheduledAt())));
attributes.put("SCHEDULE_ARN", stringAttribute(schedule.getArn()));
attributes.put("TARGET_ARN", stringAttribute(target.getArn()));
@@ -377,15 +378,25 @@ public class ScheduleDispatcher implements Resettable {
int retryAttempts, String errorCode, String errorMessage,
String requestBody, Instant nextAttemptAt) {
static Delivery first(Kind kind, Schedule schedule, String requestBody) {
String executionId = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
static Delivery first(Kind kind, Schedule schedule, String executionId) {
return new Delivery(kind, schedule.getLastModificationDate(), executionId, 0, null, null,
requestBody, null);
null, null);
}
Delivery withRequestBody(String body) {
return new Delivery(kind, lastModificationDate, executionId, retryAttempts, errorCode, errorMessage,
body, nextAttemptAt);
}
/** The 1-based number of the attempt this delivery makes: the first attempt plus its retries. */
int attemptNumber() {
return retryAttempts + 1;
}
/** Each attempted invocation gets its own execution id, as AWS documents for the context attribute. */
Delivery nextRetry() {
return new Delivery(kind, lastModificationDate, executionId, retryAttempts + 1, errorCode, errorMessage,
requestBody, null);
return new Delivery(kind, lastModificationDate, ScheduleInvoker.newExecutionId(), retryAttempts + 1,
errorCode, errorMessage, requestBody, null);
}
Delivery failedWith(Exception e, Instant now) {
@@ -48,6 +48,11 @@ public class ScheduleInvoker {
private static final Logger LOG = Logger.getLogger(ScheduleInvoker.class);
static final String CONTEXT_SCHEDULE_ARN = "<aws.scheduler.schedule-arn>";
static final String CONTEXT_SCHEDULED_TIME = "<aws.scheduler.scheduled-time>";
static final String CONTEXT_EXECUTION_ID = "<aws.scheduler.execution-id>";
static final String CONTEXT_ATTEMPT_NUMBER = "<aws.scheduler.attempt-number>";
private final SqsService sqsService;
private final LambdaService lambdaService;
private final SnsService snsService;
@@ -79,24 +84,35 @@ public class ScheduleInvoker {
}
/**
* Delivers one occurrence of {@code schedule}, scheduled at {@code scheduledAt}, to its target
* and returns the JSON request that was sent (see {@link #materializeRequest}).
* Delivers the first attempt of one occurrence of {@code schedule}, under a fresh execution id.
* See {@link #invoke(Schedule, Instant, String, int)}.
*/
public String invoke(Schedule schedule, Instant scheduledAt) {
return invoke(schedule, scheduledAt, newExecutionId(), 1);
}
/**
* Delivers one attempt of the occurrence of {@code schedule} scheduled at {@code scheduledAt}
* to its target and returns the JSON request that was sent (see {@link #materializeRequest}).
* {@code executionId} and the 1-based {@code attemptNumber} fill the context attributes of
* the target's {@code Input}.
*/
public String invoke(Schedule schedule, Instant scheduledAt, String executionId, int attemptNumber) {
Target target = schedule.getTarget();
if (target == null || target.getArn() == null) {
return "{}";
}
String arn = target.getArn();
String region = regionOf(schedule, defaultRegion);
String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber);
if (isUniversalTarget(arn)) {
invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()),
target.getInput(), region);
return universalTargetRequest(target);
input, region);
return universalTargetRequest(input);
}
TargetKind kind = TargetKind.of(target);
String payload = templatedPayload(schedule, scheduledAt);
String payload = templatedPayload(schedule, input, scheduledAt);
String targetRegion = extractRegion(arn, region);
switch (kind) {
case SQS -> {
@@ -141,14 +157,52 @@ public class ScheduleInvoker {
* in the dead-letter queue example of the Scheduler user guide.
*/
public String materializeRequest(Schedule schedule, Instant scheduledAt) {
return materializeRequest(schedule, scheduledAt, newExecutionId(), 1);
}
/** The request {@link #invoke(Schedule, Instant, String, int)} sends for the same attempt. */
public String materializeRequest(Schedule schedule, Instant scheduledAt, String executionId,
int attemptNumber) {
Target target = schedule.getTarget();
if (target == null || target.getArn() == null) {
return "{}";
}
String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber);
if (isUniversalTarget(target.getArn())) {
return universalTargetRequest(target);
return universalTargetRequest(input);
}
return templatedTargetRequest(target, TargetKind.of(target), templatedPayload(schedule, scheduledAt));
return templatedTargetRequest(target, TargetKind.of(target),
templatedPayload(schedule, input, scheduledAt));
}
static String formatScheduledTime(Instant scheduledAt) {
return scheduledAt.truncatedTo(ChronoUnit.SECONDS).toString();
}
/** A Scheduler-style execution id: 16 lowercase hex characters. */
public static String newExecutionId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
}
/**
* The target's {@code Input} with the Scheduler context attributes replaced: the schedule ARN,
* the scheduled time as UTC seconds with a {@code Z} suffix, the execution id and the 1-based
* attempt number. Null when the target has no {@code Input}, so the default event is untouched.
*/
static String contextualInput(Schedule schedule, Instant scheduledAt, String executionId,
int attemptNumber) {
String input = schedule.getTarget().getInput();
if (input == null || input.indexOf('<') < 0) {
return input;
}
String scheduledTime = scheduledAt == null
? ""
: formatScheduledTime(scheduledAt);
return input
.replace(CONTEXT_SCHEDULE_ARN, schedule.getArn() == null ? "" : schedule.getArn())
.replace(CONTEXT_SCHEDULED_TIME, scheduledTime)
.replace(CONTEXT_EXECUTION_ID, executionId == null ? "" : executionId)
.replace(CONTEXT_ATTEMPT_NUMBER, String.valueOf(attemptNumber));
}
/** The templated target types Floci delivers to, in the order their ARNs are recognised. */
@@ -189,8 +243,8 @@ public class ScheduleInvoker {
return arn.contains(":aws-sdk:");
}
private String universalTargetRequest(Target target) {
return validJsonOrString(target.getInput() != null ? target.getInput() : "{}");
private String universalTargetRequest(String input) {
return validJsonOrString(input != null ? input : "{}");
}
private String templatedTargetRequest(Target target, TargetKind kind, String payload) {
@@ -256,8 +310,7 @@ public class ScheduleInvoker {
* The payload a templated target receives: the target's {@code Input}, or Scheduler's default
* notification when no {@code Input} was configured (API reference, {@code Target.Input}).
*/
private String templatedPayload(Schedule schedule, Instant scheduledAt) {
String input = schedule.getTarget().getInput();
private String templatedPayload(Schedule schedule, String input, Instant scheduledAt) {
return input != null ? input : defaultScheduledEvent(schedule, scheduledAt);
}
@@ -275,7 +328,7 @@ public class ScheduleInvoker {
event.put("detail-type", "Scheduled Event");
event.put("source", "aws.scheduler");
event.put("account", scheduleArn.accountId());
event.put("time", scheduledAt.truncatedTo(ChronoUnit.SECONDS).toString());
event.put("time", formatScheduledTime(scheduledAt));
event.put("region", scheduleArn.region());
event.put("resources", List.of(schedule.getArn()));
event.put("detail", "{}");