diff --git a/docs/services/scheduler.md b/docs/services/scheduler.md index 2dbf4c7cef..6e221b20a4 100644 --- a/docs/services/scheduler.md +++ b/docs/services/scheduler.md @@ -37,10 +37,23 @@ window are skipped. The dispatcher ticks every `floci.services.scheduler.tick-interval-seconds` (default `10`). Supported target types: SQS, Lambda, SNS, ECS `RunTask`, EventBridge -`PutEvents`, and unqualified Step Functions state machine ARNs. A Step Functions -target starts an asynchronous execution with the schedule target's `Input`, or -`{}` when `Input` is absent. Scheduler delivery succeeds when `StartExecution` -is accepted; a later workflow failure does not trigger Scheduler retries. +`PutEvents`, and unqualified Step Functions state machine ARNs. Templated +targets receive the schedule target's `Input`. When `Input` is absent, Floci +delivers the default notification AWS sends: an EventBridge-style event with +`detail-type` `Scheduled Event`, `source` `aws.scheduler`, the schedule's +account, region, and ARN (in `resources`), the occurrence time, and `detail` +set to the string `"{}"`. The event `id` is stable per occurrence, so retries +and the dead-letter body carry the same event. A Step Functions target starts +an asynchronous execution with that payload as its input. Scheduler delivery +succeeds when `StartExecution` is accepted; a later workflow failure does not +trigger Scheduler retries. + +`CreateSchedule` and `UpdateSchedule` reject a non-JSON `Input` for Lambda, +Step Functions, and EventBridge targets with a `ValidationException`, as AWS +does. A blank `Input`, or one with text after the JSON value such as +`{} garbage`, is rejected the same way. SQS and SNS targets accept any text, +and the `Input` of a universal (`aws-sdk`) target is only checked when the +schedule is invoked. ### Retries and dead-letter queues @@ -62,8 +75,13 @@ queue with the message attributes `IS_PAYLOAD_TRUNCATED`, `RETRY_ATTEMPTS`, `SCHEDULED_TIME`, `SCHEDULE_ARN`, and `TARGET_ARN`. FIFO queues and non-SQS ARNs are logged and skipped. An `at` schedule with `ActionAfterCompletion=DELETE` is deleted once its occurrence is -delivered or exhausted. For an SQS target, the body contains `MessageBody` and -`QueueUrl`. Non-JSON target input is encoded as a JSON string field. +delivered or exhausted. The body uses the request fields of the target +service's API: SQS `MessageBody` and `QueueUrl` (plus `MessageGroupId` for FIFO +queues), Lambda `FunctionName`, `InvocationType`, and `Payload`, SNS `TopicArn` +and `Message`, Step Functions `stateMachineArn` and `input`, EventBridge +`Entries`, and ECS `cluster`, `taskDefinition`, and `count` with the configured +launch type, group, and network configuration. Non-JSON input of a universal +target is encoded as a JSON string field. ## Configuration diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java index f9c2f54a07..53864e8957 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java @@ -206,7 +206,7 @@ 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.getTarget(), regionOf(schedule)); + String requestBody = invoker.materializeRequest(schedule, nextFire); attempt(schedule, new Occurrence(schedule.getArn(), nextFire), Delivery.first(kind, schedule, requestBody), now); } @@ -241,7 +241,7 @@ public class ScheduleDispatcher implements Resettable { private void attempt(Schedule schedule, Occurrence occurrence, Delivery delivery, Instant now) { try { - invoker.invoke(schedule.getTarget(), regionOf(schedule)); + invoker.invoke(schedule, occurrence.scheduledAt()); } catch (Exception e) { LOG.warnv("Schedule {0} invocation failed: {1}", schedule.getArn(), e.getMessage()); Delivery failed = delivery.failedWith(e, now); @@ -365,7 +365,7 @@ public class ScheduleDispatcher implements Resettable { } private static String regionOf(Schedule schedule) { - return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1"); + return ScheduleInvoker.regionOf(schedule); } private record Occurrence(String scheduleArn, Instant scheduledAt) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java index f2b96296d9..e54ac5fb2f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java @@ -11,8 +11,10 @@ import io.github.hectorvent.floci.services.ecs.model.LaunchType; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.scheduler.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.scheduler.model.EventBridgeParameters; import io.github.hectorvent.floci.services.scheduler.model.EcsParameters; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; import io.github.hectorvent.floci.services.scheduler.model.Target; import io.github.hectorvent.floci.services.sns.SnsMessageAttributes; import io.github.hectorvent.floci.services.sns.SnsService; @@ -23,11 +25,15 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.UUID; /** * Delivers an EventBridge Scheduler target invocation to the underlying service. @@ -70,76 +76,208 @@ public class ScheduleInvoker { this.baseUrl = config.baseUrl(); } - public String invoke(Target target, String region) { + /** + * Delivers one occurrence of {@code schedule}, scheduled at {@code scheduledAt}, to its target + * and returns the JSON request that was sent (see {@link #materializeRequest}). + */ + public String invoke(Schedule schedule, Instant scheduledAt) { + Target target = schedule.getTarget(); if (target == null || target.getArn() == null) { return "{}"; } String arn = target.getArn(); - String payload = target.getInput() != null ? target.getInput() : "{}"; - String requestBody = materializeRequest(target, region); - - // Universal targets (arn:aws:scheduler:::aws-sdk::) carry the - // real resource identifiers inside Input, not in the target ARN. Detect and - // dispatch them before the ARN-substring routing below, which would otherwise - // mis-match (e.g. "aws-sdk:sns:publish" contains ":sns:"). - int sdkIdx = arn.indexOf(":aws-sdk:"); - if (sdkIdx >= 0) { - invokeUniversalTarget(arn.substring(sdkIdx + ":aws-sdk:".length()), payload, region); - return requestBody; + String region = regionOf(schedule); + if (isUniversalTarget(arn)) { + invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()), + target.getInput(), region); + return universalTargetRequest(target); } + TargetKind kind = TargetKind.of(target); + String payload = templatedPayload(schedule, scheduledAt); String targetRegion = extractRegion(arn, region); - if (arn.contains(":sqs:")) { - String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl); - String messageGroupId = target.getSqsParameters() != null - ? target.getSqsParameters().getMessageGroupId() : null; - sqsService.sendMessage(queueUrl, payload, 0, messageGroupId, null, targetRegion); - LOG.debugv("Scheduler delivered to SQS: {0}", arn); - } else if (arn.contains(":lambda:") || arn.contains(":function:")) { - lambdaService.invokeArn(arn, payload.getBytes(), InvocationType.Event); - LOG.debugv("Scheduler delivered to Lambda: {0}", arn); - } else if (arn.contains(":sns:")) { - snsService.publish(arn, null, payload, "Scheduler", targetRegion); - LOG.debugv("Scheduler delivered to SNS: {0}", arn); - } else if (arn.contains(":ecs:") && target.getEcsParameters() != null) { - deliverToEcsRunTask(target, targetRegion); - LOG.debugv("Scheduler delivered to ECS RunTask: {0}", arn); - } else if (isStateMachineArn(arn)) { - String targetAccount = AwsArnUtils.parse(arn).accountId(); - RequestScopes.runAs(targetAccount, - () -> stepFunctionsService.startExecution(arn, null, payload, targetRegion)); - LOG.debugv("Scheduler started Step Functions execution: {0}", arn); - } else if (isEventBridgePutEventsArn(arn)) { - deliverToEventBridge(target, payload, targetRegion); - LOG.debugv("Scheduler delivered to EventBridge: {0}", arn); - } else { - throw new UnsupportedOperationException("Scheduler: unsupported target ARN type: " + arn); + switch (kind) { + case SQS -> { + String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl); + String messageGroupId = target.getSqsParameters() != null + ? target.getSqsParameters().getMessageGroupId() : null; + sqsService.sendMessage(queueUrl, payload, 0, messageGroupId, null, targetRegion); + LOG.debugv("Scheduler delivered to SQS: {0}", arn); + } + case LAMBDA -> { + lambdaService.invokeArn(arn, payload.getBytes(), InvocationType.Event); + LOG.debugv("Scheduler delivered to Lambda: {0}", arn); + } + case SNS -> { + snsService.publish(arn, null, payload, "Scheduler", targetRegion); + LOG.debugv("Scheduler delivered to SNS: {0}", arn); + } + case ECS_RUN_TASK -> { + deliverToEcsRunTask(target, targetRegion); + LOG.debugv("Scheduler delivered to ECS RunTask: {0}", arn); + } + case STEP_FUNCTIONS -> { + String targetAccount = AwsArnUtils.parse(arn).accountId(); + RequestScopes.runAs(targetAccount, + () -> stepFunctionsService.startExecution(arn, null, payload, targetRegion)); + LOG.debugv("Scheduler started Step Functions execution: {0}", arn); + } + case EVENT_BRIDGE -> { + deliverToEventBridge(target, payload, targetRegion); + LOG.debugv("Scheduler delivered to EventBridge: {0}", arn); + } + case UNSUPPORTED -> + throw new UnsupportedOperationException("Scheduler: unsupported target ARN type: " + arn); } - return requestBody; + return templatedTargetRequest(target, kind, payload); } - /** Returns the JSON request sent to the target service, for invocation diagnostics and DLQs. */ - public String materializeRequest(Target target, String region) { + /** + * Returns the JSON request sent to the target service, for invocation diagnostics and DLQs. + * Templated targets use the field names of the target service's API (SQS SendMessage, Lambda + * Invoke, SNS Publish, ECS RunTask, Step Functions StartExecution, EventBridge PutEvents), as + * in the dead-letter queue example of the Scheduler user guide. + */ + public String materializeRequest(Schedule schedule, Instant scheduledAt) { + Target target = schedule.getTarget(); if (target == null || target.getArn() == null) { return "{}"; } - String arn = target.getArn(); - String payload = target.getInput() != null ? target.getInput() : "{}"; - int sdkIdx = arn.indexOf(":aws-sdk:"); - if (sdkIdx >= 0) { - return validJsonOrString(payload); + if (isUniversalTarget(target.getArn())) { + return universalTargetRequest(target); } - if (arn.contains(":sqs:")) { - Map request = new LinkedHashMap<>(); - request.put("MessageBody", payload); - request.put("QueueUrl", AwsArnUtils.arnToQueueUrl(arn, baseUrl)); - if (target.getSqsParameters() != null - && target.getSqsParameters().getMessageGroupId() != null) { - request.put("MessageGroupId", target.getSqsParameters().getMessageGroupId()); + return templatedTargetRequest(target, TargetKind.of(target), templatedPayload(schedule, scheduledAt)); + } + + /** The templated target types Floci delivers to, in the order their ARNs are recognised. */ + private enum TargetKind { + SQS, LAMBDA, SNS, ECS_RUN_TASK, STEP_FUNCTIONS, EVENT_BRIDGE, UNSUPPORTED; + + static TargetKind of(Target target) { + String arn = target.getArn(); + if (arn.contains(":sqs:")) { + return SQS; } - return writeJson(request); + if (arn.contains(":lambda:") || arn.contains(":function:")) { + return LAMBDA; + } + if (arn.contains(":sns:")) { + return SNS; + } + if (arn.contains(":ecs:") && target.getEcsParameters() != null) { + return ECS_RUN_TASK; + } + if (isStateMachineArn(arn)) { + return STEP_FUNCTIONS; + } + if (isEventBridgePutEventsArn(arn)) { + return EVENT_BRIDGE; + } + return UNSUPPORTED; } - return validJsonOrString(payload); + } + + /** + * Universal targets (arn:aws:scheduler:::aws-sdk:<service>:<action>) carry the real + * resource identifiers inside Input, not in the target ARN. They are detected before the + * ARN-substring routing of {@link TargetKind}, which would otherwise mis-match (e.g. + * "aws-sdk:sns:publish" contains ":sns:"). + */ + private static boolean isUniversalTarget(String arn) { + return arn.contains(":aws-sdk:"); + } + + private String universalTargetRequest(Target target) { + return validJsonOrString(target.getInput() != null ? target.getInput() : "{}"); + } + + private String templatedTargetRequest(Target target, TargetKind kind, String payload) { + String arn = target.getArn(); + Map request = new LinkedHashMap<>(); + switch (kind) { + case SQS -> { + request.put("MessageBody", payload); + request.put("QueueUrl", AwsArnUtils.arnToQueueUrl(arn, baseUrl)); + if (target.getSqsParameters() != null + && target.getSqsParameters().getMessageGroupId() != null) { + request.put("MessageGroupId", target.getSqsParameters().getMessageGroupId()); + } + } + case LAMBDA -> { + request.put("FunctionName", arn); + request.put("InvocationType", InvocationType.Event.name()); + request.put("Payload", payload); + } + case SNS -> { + request.put("TopicArn", arn); + request.put("Message", payload); + } + case ECS_RUN_TASK -> request.putAll(ecsRunTaskRequest(target)); + case STEP_FUNCTIONS -> { + request.put("stateMachineArn", arn); + request.put("input", payload); + } + case EVENT_BRIDGE -> request.put("Entries", List.of(eventBridgeEntry(target, payload))); + case UNSUPPORTED -> { + return validJsonOrString(payload); + } + } + return writeJson(request); + } + + private static Map ecsRunTaskRequest(Target target) { + EcsParameters ecs = target.getEcsParameters(); + Map request = new LinkedHashMap<>(); + request.put("cluster", target.getArn()); + request.put("taskDefinition", ecs.getTaskDefinitionArn()); + request.put("count", ecs.getTaskCount() != null ? ecs.getTaskCount() : 1); + putIfPresent(request, "launchType", ecs.getLaunchType()); + putIfPresent(request, "group", ecs.getGroup()); + if (ecs.getNetworkConfiguration() != null && ecs.getNetworkConfiguration().getAwsvpcConfiguration() != null) { + AwsVpcConfiguration vpc = ecs.getNetworkConfiguration().getAwsvpcConfiguration(); + Map awsvpc = new LinkedHashMap<>(); + putIfPresent(awsvpc, "subnets", vpc.getSubnets()); + putIfPresent(awsvpc, "securityGroups", vpc.getSecurityGroups()); + putIfPresent(awsvpc, "assignPublicIp", vpc.getAssignPublicIp()); + request.put("networkConfiguration", Map.of("awsvpcConfiguration", awsvpc)); + } + return request; + } + + private static void putIfPresent(Map map, String key, Object value) { + if (value != null) { + map.put(key, value); + } + } + + /** + * 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(); + return input != null ? input : defaultScheduledEvent(schedule, scheduledAt); + } + + /** + * Scheduler's default notification: an EventBridge-style {@code Scheduled Event} whose + * {@code resources} names the schedule and whose {@code detail} is the string "{}". The event + * id is stable per occurrence so retries and the dead-letter body carry the same event. + */ + private String defaultScheduledEvent(Schedule schedule, Instant scheduledAt) { + AwsArnUtils.Arn scheduleArn = AwsArnUtils.parse(schedule.getArn()); + Map event = new LinkedHashMap<>(); + event.put("version", "0"); + event.put("id", UUID.nameUUIDFromBytes( + (schedule.getArn() + "@" + scheduledAt).getBytes(StandardCharsets.UTF_8)).toString()); + 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("region", scheduleArn.region()); + event.put("resources", List.of(schedule.getArn())); + event.put("detail", "{}"); + return writeJson(event); } private String validJsonOrString(String payload) { @@ -190,7 +328,8 @@ public class ScheduleInvoker { if (source == null || source.getAwsvpcConfiguration() == null) { return null; } - io.github.hectorvent.floci.services.scheduler.model.AwsVpcConfiguration sourceVpc = source.getAwsvpcConfiguration(); + AwsVpcConfiguration sourceVpc = source.getAwsvpcConfiguration(); + // The ECS model's AwsVpcConfiguration clashes with the scheduler model's, which is imported. io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration targetVpc = new io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration(); targetVpc.setSubnets(sourceVpc.getSubnets()); @@ -283,7 +422,7 @@ public class ScheduleInvoker { return value != null && !value.isNull() ? value.asText() : null; } - private boolean isEventBridgePutEventsArn(String arn) { + private static boolean isEventBridgePutEventsArn(String arn) { return arn.contains(":events:") && arn.contains(":event-bus/"); } @@ -297,6 +436,11 @@ public class ScheduleInvoker { } private void deliverToEventBridge(Target target, String payload, String region) { + eventBridgeService.putEvents(List.of(eventBridgeEntry(target, payload)), region); + } + + /** One PutEvents entry for an event-bus target, as delivered and as reported in diagnostics. */ + private Map eventBridgeEntry(Target target, String payload) { String busArn = target.getArn(); String busName = busArn.substring(busArn.indexOf(":event-bus/") + ":event-bus/".length()); @@ -309,12 +453,12 @@ public class ScheduleInvoker { String detailType = ebp != null && ebp.getDetailType() != null && !ebp.getDetailType().isBlank() ? ebp.getDetailType() : "Scheduled Event"; - Map entry = new HashMap<>(); + Map entry = new LinkedHashMap<>(); entry.put("EventBusName", busName); entry.put("Source", source); entry.put("DetailType", detailType); entry.put("Detail", asDetail(payload)); - eventBridgeService.putEvents(List.of(entry), region); + return entry; } private String asDetail(String payload) { @@ -333,4 +477,9 @@ public class ScheduleInvoker { private static String extractRegion(String arn, String defaultRegion) { return AwsArnUtils.regionOrDefault(arn, defaultRegion); } + + /** The region a schedule lives in, taken from its ARN. */ + static String regionOf(Schedule schedule) { + return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1"); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java index 0176996e09..3f59486a78 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.scheduler; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -8,7 +9,12 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.scheduler.model.Schedule; import io.github.hectorvent.floci.services.scheduler.model.ScheduleGroup; import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -26,6 +32,11 @@ public class SchedulerService { // AWS EventBridge Scheduler name constraints: [0-9a-zA-Z-_.]+, 1-64 chars. private static final Pattern NAME_PATTERN = Pattern.compile("[0-9a-zA-Z\\-_.]{1,64}"); private static final String DEFAULT_GROUP = "default"; + // FAIL_ON_TRAILING_TOKENS matters here: without it an Input of "{} garbage" parses as the + // leading object and the rest is silently dropped, so a value AWS rejects would be stored. + private static final ObjectReader JSON = new ObjectMapper() + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readerFor(JsonNode.class); private final StorageBackend groupStore; private final StorageBackend scheduleStore; @@ -374,6 +385,38 @@ public class SchedulerService { throw new AwsException("ValidationException", "1 validation error detected: Value null at 'target.deadLetterConfig.arn' failed to satisfy constraint: Member must not be null", 400); } + String input = req.getTarget().getInput(); + if (input != null && requiresJsonInput(req.getTarget().getArn()) && !isWellFormedJson(input)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at 'target.input' failed to satisfy constraint: Member must be well-formed JSON for Lambda, Step Functions, and EventBridge targets", 400); + } + } + + /** + * Templated Lambda, Step Functions and EventBridge targets require well-formed JSON + * {@code Input} (API reference, {@code Target.Input}); other templated targets accept any + * text, and universal ({@code aws-sdk}) targets are only checked when invoked. + */ + private static boolean requiresJsonInput(String targetArn) { + return AwsArnUtils.isArnFor(targetArn, "lambda") + || AwsArnUtils.isArnFor(targetArn, "states") + || AwsArnUtils.isArnFor(targetArn, "events"); + } + + /** + * A blank value is rejected up front: {@code Input} has a minimum length of 1, and + * {@code readTree} returns a missing node for it instead of failing. + */ + private static boolean isWellFormedJson(String value) { + if (value.isBlank()) { + return false; + } + try { + JSON.readTree(value); + return true; + } catch (JsonProcessingException e) { + return false; + } } private String buildGroupArn(String region, String name) { diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java index b7e22bc30e..120a43db3e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java @@ -75,8 +75,8 @@ class ScheduleDispatcherTest { s.getTarget().setDeadLetterConfig(new DeadLetterConfig(DLQ_TARGET_ARN)); when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); doThrow(new RuntimeException("target unavailable")).when(invoker) - .invoke(eq(s.getTarget()), anyString()); - when(invoker.materializeRequest(eq(s.getTarget()), anyString())).thenReturn(TARGET_REQUEST); + .invoke(eq(s), any()); + when(invoker.materializeRequest(eq(s), any())).thenReturn(TARGET_REQUEST); return s; } @@ -108,7 +108,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, times(1)).invoke(s.getTarget(), "eu-central-1"); + verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z"))); } @Test @@ -118,7 +118,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:17:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -130,7 +130,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:20:00Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); } @Test @@ -163,7 +163,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -174,7 +174,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -185,7 +185,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -195,13 +195,13 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T09:04:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); dispatcher.tick(Instant.parse("2026-04-21T09:06:00Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:11:01Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); } @Test @@ -210,7 +210,7 @@ class ScheduleDispatcherTest { when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); assertDoesNotThrow(() -> dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"))); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -221,7 +221,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); } @Test @@ -232,7 +232,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, times(1)).invoke(s.getTarget(), "eu-central-1"); + verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T09:17:54Z"))); verifyNoInteractions(sqsService); } @@ -243,7 +243,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, never()).invoke(any(), anyString()); + verify(invoker, never()).invoke(any(), any()); verifyNoInteractions(sqsService); } @@ -253,13 +253,13 @@ class ScheduleDispatcherTest { s.getTarget().setRetryPolicy(new RetryPolicy(3600, 1)); when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); doThrow(new RuntimeException("target unavailable")).when(invoker) - .invoke(eq(s.getTarget()), anyString()); + .invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); } @Test @@ -268,15 +268,15 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:18:59Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:20:59Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(3)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(3)).invoke(eq(s), any()); } @Test @@ -286,7 +286,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); verifyNoInteractions(sqsService); } @@ -297,7 +297,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T11:18:00Z")); - verify(invoker, times(2)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(2)).invoke(eq(s), any()); Map attributes = deadLetters(1).get(0); assertEquals("MaximumRetryAttempts", attribute(attributes, "EXHAUSTED_RETRY_CONDITION")); assertEquals("1", attribute(attributes, "RETRY_ATTEMPTS")); @@ -311,7 +311,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); Map attributes = deadLetters(1).get(0); assertEquals("MaximumEventAgeInSeconds", attribute(attributes, "EXHAUSTED_RETRY_CONDITION")); assertEquals("0", attribute(attributes, "RETRY_ATTEMPTS")); @@ -321,13 +321,13 @@ class ScheduleDispatcherTest { void sendsExhaustedOccurrenceToDeadLetterQueueWithSchedulerAttributes() { Schedule s = failingSchedule("dead-letter", "at(2026-04-21T09:17:54)", new RetryPolicy(3600, 2)); doThrow(new AwsException("AWS.SimpleQueueService.NonExistentQueue", - "The specified queue does not exist.", 400)).when(invoker).invoke(eq(s.getTarget()), anyString()); + "The specified queue does not exist.", 400)).when(invoker).invoke(eq(s), any()); dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:19:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:21:00Z")); - verify(invoker, times(3)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(3)).invoke(eq(s), any()); Map attributes = deadLetters(1).get(0); assertEquals(9, attributes.size()); assertEquals("AWS.SimpleQueueService.NonExistentQueue", attribute(attributes, "ERROR_CODE")); @@ -339,7 +339,7 @@ class ScheduleDispatcherTest { assertEquals("2026-04-21T09:17:54Z", attribute(attributes, "SCHEDULED_TIME")); assertEquals(s.getArn(), attribute(attributes, "SCHEDULE_ARN")); assertEquals(SQS_TARGET_ARN, attribute(attributes, "TARGET_ARN")); - verify(invoker, never()).invoke(argThat(target -> DLQ_TARGET_ARN.equals(target.getArn())), anyString()); + verify(invoker, never()).invoke(argThat(schedule -> DLQ_TARGET_ARN.equals(schedule.getTarget().getArn())), any()); } @Test @@ -351,11 +351,11 @@ class ScheduleDispatcherTest { topic.getTarget().setRetryPolicy(new RetryPolicy(3600, 0)); topic.getTarget().setDeadLetterConfig(new DeadLetterConfig("arn:aws:sns:eu-central-1:000000000000:dead-letter")); when(schedulerService.listAllSchedules()).thenReturn(List.of(fifo, topic)); - doThrow(new RuntimeException("target unavailable")).when(invoker).invoke(any(), anyString()); + doThrow(new RuntimeException("target unavailable")).when(invoker).invoke(any(), any()); tickEveryTenSeconds("2026-04-21T09:18:00Z", 2); - verify(invoker, times(2)).invoke(any(), anyString()); + verify(invoker, times(2)).invoke(any(), any()); verifyNoInteractions(sqsService); } @@ -367,7 +367,7 @@ class ScheduleDispatcherTest { dispatcher.tick(Instant.parse("2026-04-21T09:10:00Z")); dispatcher.tick(Instant.parse("2026-04-21T09:12:00Z")); - verify(invoker, times(4)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(4)).invoke(eq(s), any()); List> deadLetters = deadLetters(2); assertEquals("2026-04-21T09:05:00Z", attribute(deadLetters.get(0), "SCHEDULED_TIME")); assertEquals("2026-04-21T09:10:00Z", attribute(deadLetters.get(1), "SCHEDULED_TIME")); @@ -379,7 +379,7 @@ class ScheduleDispatcherTest { Schedule s = failingSchedule("at-delete", "at(2026-04-21T09:17:54)", new RetryPolicy(3600, 1)); s.setActionAfterCompletion("DELETE"); s.setAccountId("000000000000"); - when(invoker.invoke(eq(s.getTarget()), anyString())) + when(invoker.invoke(eq(s), any())) .thenThrow(new RuntimeException("target unavailable")) .thenReturn(TARGET_REQUEST); @@ -415,7 +415,7 @@ class ScheduleDispatcherTest { s.setState("ENABLED"); dispatcher.tick(Instant.parse("2026-04-21T09:18:20Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); verifyNoInteractions(sqsService); } @@ -426,7 +426,7 @@ class ScheduleDispatcherTest { tickEveryTenSeconds("2026-04-21T09:18:00Z", 3); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); verifyNoInteractions(sqsService); } @@ -439,7 +439,7 @@ class ScheduleDispatcherTest { s.setLastModificationDate(Instant.parse("2026-04-21T09:18:05Z")); dispatcher.tick(Instant.parse("2026-04-21T09:18:10Z")); - verify(invoker, times(1)).invoke(eq(s.getTarget()), anyString()); + verify(invoker, times(1)).invoke(eq(s), any()); verifyNoInteractions(sqsService); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java index 00e1ef6869..dff3ba2f0e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.scheduler.model.EventBridgeParameters import io.github.hectorvent.floci.services.scheduler.model.AwsVpcConfiguration; import io.github.hectorvent.floci.services.scheduler.model.EcsParameters; import io.github.hectorvent.floci.services.scheduler.model.NetworkConfiguration; +import io.github.hectorvent.floci.services.scheduler.model.Schedule; import io.github.hectorvent.floci.services.scheduler.model.SqsParameters; import io.github.hectorvent.floci.services.scheduler.model.Target; import io.github.hectorvent.floci.services.sns.SnsService; @@ -23,8 +24,10 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -45,6 +48,7 @@ import static org.mockito.Mockito.when; class ScheduleInvokerTest { private static final String TOPIC_ARN = "arn:aws:sns:us-east-1:000000000000:repro-topic"; + private static final Instant SCHEDULED_AT = Instant.parse("2026-04-21T09:17:54Z"); private SqsService sqsService; private LambdaService lambdaService; @@ -68,6 +72,24 @@ class ScheduleInvokerTest { eventBridgeService, ecsService, stepFunctionsService, new ObjectMapper(), config); } + /** Delivers one occurrence of a schedule in {@code region} whose target is {@code target}. */ + private String invoke(Target target, String region) { + return invoker.invoke(scheduleIn(region, target), SCHEDULED_AT); + } + + private String materializeRequest(Target target, String region) { + return invoker.materializeRequest(scheduleIn(region, target), SCHEDULED_AT); + } + + private static Schedule scheduleIn(String region, Target target) { + Schedule schedule = new Schedule(); + schedule.setName("test-schedule"); + schedule.setGroupName("default"); + schedule.setArn("arn:aws:scheduler:" + region + ":000000000000:schedule/default/test-schedule"); + schedule.setTarget(target); + return schedule; + } + @Test void universalSnsPublishForwardsMessageAttributes() { Target target = new Target(); @@ -80,7 +102,7 @@ class ScheduleInvokerTest { + "\"EventName\":{\"DataType\":\"String\",\"StringValue\":\"my-subject\"}" + "}}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(snsService).publish( eq(TOPIC_ARN), isNull(), isNull(), @@ -93,6 +115,39 @@ class ScheduleInvokerTest { isNull(), isNull(), eq("us-east-1")); } + @Test + void templatedTargetWithoutInputDeliversTheDefaultScheduledEvent() throws Exception { + // Repro from floci-io/floci#3951: a templated target created without Input must receive + // Scheduler's default notification, not "{}". + Target target = new Target(); + target.setArn("arn:aws:sqs:eu-central-1:000000000000:no-input"); + target.setRoleArn("arn:aws:iam::000000000000:role/scheduler-role"); + + invoker.invoke(scheduleIn("eu-central-1", target), Instant.parse("2024-11-07T22:05:00Z")); + + ArgumentCaptor body = ArgumentCaptor.forClass(String.class); + verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/no-input"), body.capture(), + eq(0), isNull(), isNull(), eq("eu-central-1")); + assertDefaultScheduledEvent(body.getValue(), "eu-central-1", "2024-11-07T22:05:00Z"); + } + + /** + * Asserts that {@code delivered} is the default notification Scheduler sends when a templated + * target has no Input. The expected shape is the event captured from a real invocation in + * aws/aws-lambda-dotnet#1864 (note {@code detail} is the string "{}"); only the id varies. + */ + private static void assertDefaultScheduledEvent(String delivered, String region, String time) throws Exception { + String exampleId = "49672d39-8c3a-4cc6-8de5-c57b0acf718f"; + String id = new ObjectMapper().readTree(delivered).path("id").asText(); + assertEquals("{\"version\":\"0\",\"id\":\"" + exampleId + "\"," + + "\"detail-type\":\"Scheduled Event\",\"source\":\"aws.scheduler\"," + + "\"account\":\"000000000000\",\"time\":\"" + time + "\",\"region\":\"" + region + "\"," + + "\"resources\":[\"arn:aws:scheduler:" + region + ":000000000000:schedule/default/test-schedule\"]," + + "\"detail\":\"{}\"}", + id.isEmpty() ? delivered : delivered.replace(id, exampleId)); + assertEquals(id, UUID.fromString(id).toString(), "event id is a UUID"); + } + @Test void materializesSqsRequestForDeadLetterBody() { Target target = new Target(); @@ -100,7 +155,81 @@ class ScheduleInvokerTest { target.setInput("payload"); assertEquals("{\"MessageBody\":\"payload\",\"QueueUrl\":\"http://localhost:4566/000000000000/queue\"}", - invoker.materializeRequest(target, "us-east-1")); + materializeRequest(target, "us-east-1")); + } + + // The expected bodies below use the request field names of each target service's API + // (Lambda Invoke, SNS Publish, Step Functions StartExecution, EventBridge PutEvents, ECS RunTask), + // matching the SQS SendMessage example in the Scheduler dead-letter queue guide. + + @Test + void materializesLambdaInvokeRequestForDeadLetterBody() { + Target target = new Target(); + target.setArn("arn:aws:lambda:us-east-1:000000000000:function:my-func"); + target.setInput("{\"hello\":\"world\"}"); + + assertEquals("{\"FunctionName\":\"arn:aws:lambda:us-east-1:000000000000:function:my-func\"," + + "\"InvocationType\":\"Event\",\"Payload\":\"{\\\"hello\\\":\\\"world\\\"}\"}", + materializeRequest(target, "us-east-1")); + } + + @Test + void materializesSnsPublishRequestForDeadLetterBody() { + Target target = new Target(); + target.setArn(TOPIC_ARN); + target.setInput("plain text"); + + assertEquals("{\"TopicArn\":\"" + TOPIC_ARN + "\",\"Message\":\"plain text\"}", + materializeRequest(target, "us-east-1")); + } + + @Test + void materializesStepFunctionsStartExecutionRequestForDeadLetterBody() { + Target target = new Target(); + target.setArn("arn:aws:states:eu-west-1:000000000000:stateMachine:scheduled-workflow"); + target.setInput("{\"order\":{\"id\":42}}"); + + assertEquals("{\"stateMachineArn\":\"arn:aws:states:eu-west-1:000000000000:stateMachine:scheduled-workflow\"," + + "\"input\":\"{\\\"order\\\":{\\\"id\\\":42}}\"}", + materializeRequest(target, "us-east-1")); + } + + @Test + void materializesEventBridgePutEventsRequestForDeadLetterBody() { + Target target = new Target(); + target.setArn("arn:aws:events:us-east-1:000000000000:event-bus/my-bus"); + target.setInput("{\"hello\":\"world\"}"); + target.setEventBridgeParameters(new EventBridgeParameters("Order Placed", "my.app")); + + assertEquals("{\"Entries\":[{\"EventBusName\":\"my-bus\",\"Source\":\"my.app\"," + + "\"DetailType\":\"Order Placed\",\"Detail\":\"{\\\"hello\\\":\\\"world\\\"}\"}]}", + materializeRequest(target, "us-east-1")); + } + + @Test + void materializesEcsRunTaskRequestForDeadLetterBody() { + Target target = new Target(); + target.setArn("arn:aws:ecs:us-east-1:000000000000:cluster/proof"); + EcsParameters ecsParameters = new EcsParameters(); + ecsParameters.setTaskDefinitionArn("arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1"); + ecsParameters.setLaunchType("FARGATE"); + ecsParameters.setGroup("batch-group"); + ecsParameters.setTaskCount(2); + AwsVpcConfiguration vpc = new AwsVpcConfiguration(); + vpc.setSubnets(List.of("subnet-a", "subnet-b")); + vpc.setSecurityGroups(List.of("sg-a")); + vpc.setAssignPublicIp("DISABLED"); + NetworkConfiguration network = new NetworkConfiguration(); + network.setAwsvpcConfiguration(vpc); + ecsParameters.setNetworkConfiguration(network); + target.setEcsParameters(ecsParameters); + + assertEquals("{\"cluster\":\"arn:aws:ecs:us-east-1:000000000000:cluster/proof\"," + + "\"taskDefinition\":\"arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1\"," + + "\"count\":2,\"launchType\":\"FARGATE\",\"group\":\"batch-group\"," + + "\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":[\"subnet-a\",\"subnet-b\"]," + + "\"securityGroups\":[\"sg-a\"],\"assignPublicIp\":\"DISABLED\"}}}", + materializeRequest(target, "us-east-1")); } @Test @@ -115,7 +244,7 @@ class ScheduleInvokerTest { + "\"BinAttr\":{\"DataType\":\"Binary\",\"BinaryValue\":\"aGVsbG8=\"}" + "}}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(snsService).publish( eq(TOPIC_ARN), isNull(), isNull(), @@ -135,7 +264,7 @@ class ScheduleInvokerTest { target.setRoleArn("arn:aws:iam::000000000000:role/x"); target.setInput("{\"TopicArn\":\"" + TOPIC_ARN + "\",\"Message\":\"hello\"}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(snsService).publish(eq(TOPIC_ARN), isNull(), isNull(), eq("hello"), isNull(), @@ -150,7 +279,7 @@ class ScheduleInvokerTest { target.setRoleArn("arn:aws:iam::000000000000:role/x"); target.setInput("{\"TopicArn\":\"" + TOPIC_ARN + "\",\"Message\":\"scheduled-universal-target\"}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); // The real TopicArn from Input must be used, NOT the universal-target ARN. verify(snsService).publish(eq(TOPIC_ARN), isNull(), isNull(), @@ -170,7 +299,7 @@ class ScheduleInvokerTest { + "\"MessageBody\":\"hi\",\"MessageGroupId\":\"g1\"," + "\"MessageDeduplicationId\":\"dedup-1\"}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(sqsService).sendMessage(eq("http://localhost:4566/000000000000/q.fifo"), eq("hi"), eq(0), eq("g1"), eq("dedup-1"), @@ -193,7 +322,7 @@ class ScheduleInvokerTest { + "\"BinaryAttr\":{\"DataType\":\"Binary.Custom\",\"BinaryValue\":\"" + binaryValueBase64 + "\"}}}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); ArgumentCaptor> attributesCaptor = ArgumentCaptor.captor(); verify(sqsService).sendMessage(eq(queueUrl), eq("hi"), eq(0), eq("g1"), eq("dedup-1"), @@ -230,7 +359,7 @@ class ScheduleInvokerTest { + "\"Valid\":{\"DataType\":\"String\",\"StringValue\":\"value\"}" + "}}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); ArgumentCaptor> attributesCaptor = ArgumentCaptor.captor(); verify(sqsService).sendMessage(eq(queueUrl), eq("hi"), eq(0), eq("g1"), eq("dedup-1"), @@ -248,7 +377,7 @@ class ScheduleInvokerTest { target.setInput("{\"hello\":\"world\"}"); target.setSqsParameters(new SqsParameters("group-7")); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(sqsService).sendMessage(anyString(), eq("{\"hello\":\"world\"}"), eq(0), eq("group-7"), isNull(), eq("us-east-1")); @@ -261,7 +390,7 @@ class ScheduleInvokerTest { target.setArn(arn); target.setInput("{\"detail\":{\"job\":\"workflow-recovery\"}}"); - invoker.invoke(target, "ap-south-1"); + invoke(target, "ap-south-1"); verify(lambdaService).invokeArn( eq(arn), @@ -276,7 +405,7 @@ class ScheduleInvokerTest { target.setArn(TOPIC_ARN); target.setInput("{\"hello\":\"world\"}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(snsService).publish(eq(TOPIC_ARN), isNull(), eq("{\"hello\":\"world\"}"), eq("Scheduler"), eq("us-east-1")); @@ -291,20 +420,22 @@ class ScheduleInvokerTest { target.setRoleArn("arn:aws:iam::000000000000:role/scheduler-role"); target.setInput(input); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(stepFunctionsService).startExecution(stateMachineArn, null, input, "eu-west-1"); } @Test - void stateMachineTargetWithoutInputUsesEmptyObject() { + void stateMachineTargetWithoutInputStartsExecutionWithTheDefaultScheduledEvent() throws Exception { String stateMachineArn = "arn:aws:states:us-east-1:000000000000:stateMachine:scheduled-workflow"; Target target = new Target(); target.setArn(stateMachineArn); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); - verify(stepFunctionsService).startExecution(stateMachineArn, null, "{}", "us-east-1"); + ArgumentCaptor input = ArgumentCaptor.forClass(String.class); + verify(stepFunctionsService).startExecution(eq(stateMachineArn), isNull(), input.capture(), eq("us-east-1")); + assertDefaultScheduledEvent(input.getValue(), "us-east-1", "2026-04-21T09:17:54Z"); } @Test @@ -312,11 +443,12 @@ class ScheduleInvokerTest { String stateMachineArn = "arn:aws:states:us-east-1:000000000000:stateMachine:missing"; Target target = new Target(); target.setArn(stateMachineArn); + target.setInput("{}"); when(stepFunctionsService.startExecution(stateMachineArn, null, "{}", "us-east-1")) .thenThrow(new AwsException("StateMachineDoesNotExist", "State machine does not exist", 400)); AwsException error = assertThrows(AwsException.class, - () -> invoker.invoke(target, "us-east-1")); + () -> invoke(target, "us-east-1")); assertEquals("StateMachineDoesNotExist", error.getErrorCode()); } @@ -327,7 +459,7 @@ class ScheduleInvokerTest { target.setArn("arn:aws:states:us-east-1:000000000000:stateMachine:scheduled-workflow:PROD"); assertThrows(UnsupportedOperationException.class, - () -> invoker.invoke(target, "us-east-1")); + () -> invoke(target, "us-east-1")); verifyNoInteractions(stepFunctionsService); } @@ -339,7 +471,7 @@ class ScheduleInvokerTest { target.setInput("{\"hello\":\"world\"}"); target.setEventBridgeParameters(new EventBridgeParameters("Order Placed", "my.app")); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); ArgumentCaptor>> captor = ArgumentCaptor.forClass(List.class); verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1")); @@ -357,7 +489,7 @@ class ScheduleInvokerTest { target.setArn("arn:aws:events:us-east-1:000000000000:event-bus/my-bus"); target.setInput("{\"hello\":\"world\"}"); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); ArgumentCaptor>> captor = ArgumentCaptor.forClass(List.class); verify(eventBridgeService).putEvents(captor.capture(), eq("us-east-1")); @@ -384,7 +516,7 @@ class ScheduleInvokerTest { ecsParameters.setNetworkConfiguration(network); target.setEcsParameters(ecsParameters); - invoker.invoke(target, "us-west-2"); + invoke(target, "us-west-2"); ArgumentCaptor networkCaptor = ArgumentCaptor.forClass(io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration.class); @@ -414,7 +546,7 @@ class ScheduleInvokerTest { ecsParameters.setLaunchType("UNKNOWN"); target.setEcsParameters(ecsParameters); - invoker.invoke(target, "us-east-1"); + invoke(target, "us-east-1"); verify(ecsService).runTask( eq("arn:aws:ecs:us-east-1:000000000000:cluster/proof"), @@ -434,7 +566,7 @@ class ScheduleInvokerTest { target.setArn("arn:aws:scheduler:::aws-sdk:dynamodb:putItem"); target.setInput("{}"); - assertThrows(UnsupportedOperationException.class, () -> invoker.invoke(target, "us-east-1")); + assertThrows(UnsupportedOperationException.class, () -> invoke(target, "us-east-1")); verifyNoInteractions(sqsService, lambdaService, snsService, eventBridgeService, ecsService); } @@ -445,7 +577,7 @@ class ScheduleInvokerTest { target.setArn("arn:aws:scheduler:::aws-sdk:sqs:sendMessage"); target.setInput("{not-json"); - assertThrows(AwsException.class, () -> invoker.invoke(target, "us-east-1")); + assertThrows(AwsException.class, () -> invoke(target, "us-east-1")); verifyNoInteractions(sqsService, lambdaService, snsService, eventBridgeService, ecsService); } @@ -456,7 +588,7 @@ class ScheduleInvokerTest { target.setArn("arn:aws:dynamodb:us-east-1:000000000000:table/orders"); target.setInput("{}"); - assertThrows(UnsupportedOperationException.class, () -> invoker.invoke(target, "us-east-1")); + assertThrows(UnsupportedOperationException.class, () -> invoke(target, "us-east-1")); verifyNoInteractions(sqsService, lambdaService, snsService, eventBridgeService, ecsService); } diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java index 5017452659..e1fffaba6e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerIntegrationTest.java @@ -546,6 +546,31 @@ class SchedulerIntegrationTest { .statusCode(400); } + @Test + @Order(43) + void createScheduleWithNonJsonInputForLambdaTargetReturns400() { + // Target.Input in the Scheduler API reference: templated Lambda, Step Functions and + // EventBridge targets require well-formed JSON. + given() + .contentType("application/json") + .body(""" + { + "ScheduleExpression": "rate(1 hour)", + "FlexibleTimeWindow": {"Mode": "OFF"}, + "Target": { + "Arn": "arn:aws:lambda:us-east-1:000000000000:function:my-func", + "RoleArn": "arn:aws:iam::000000000000:role/scheduler-role", + "Input": "not json" + } + } + """) + .when() + .post("/schedules/lambda-text-input") + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")); + } + @Test @Order(21) void createScheduleWithEcsParametersRoundTrips() { diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerServiceTest.java index 15f9e6c0e2..482f0dde43 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerServiceTest.java @@ -331,6 +331,104 @@ class SchedulerServiceTest { assertEquals("ValidationException", e.getErrorCode()); } + // Target.Input in the Scheduler API reference: templated Lambda, Step Functions and EventBridge + // targets require well-formed JSON; other target types accept any text, and universal + // (aws-sdk) target input is only checked when the schedule is invoked. + + @Test + void createScheduleRejectsNonJsonInputForLambdaTarget() { + AwsException e = assertThrows(AwsException.class, () -> + service.createSchedule( + newRequest("s", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:lambda:us-east-1:000000000000:function:my-func", + "arn:aws:iam::000000000000:role/my-role", "not json", null)), + REGION)); + assertEquals("ValidationException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + } + + @Test + void createScheduleRejectsNonJsonInputForEventBridgeTarget() { + AwsException e = assertThrows(AwsException.class, () -> + service.createSchedule( + newRequest("s", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:events:us-east-1:000000000000:event-bus/my-bus", + "arn:aws:iam::000000000000:role/my-role", "{\"unterminated\":", null)), + REGION)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void updateScheduleRejectsNonJsonInputForStepFunctionsTarget() { + String stateMachineArn = "arn:aws:states:us-east-1:000000000000:stateMachine:my-workflow"; + service.createSchedule( + newRequest("sfn-upd", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target(stateMachineArn, "arn:aws:iam::000000000000:role/my-role", "{}", null)), + REGION); + AwsException e = assertThrows(AwsException.class, () -> + service.updateSchedule( + newRequest("sfn-upd", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target(stateMachineArn, "arn:aws:iam::000000000000:role/my-role", "not json", null)), + REGION)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void createScheduleRejectsInputWithTrailingTokensForLambdaTarget() { + // Without FAIL_ON_TRAILING_TOKENS, "{} garbage" parses as the leading object and the + // rest is silently dropped. + AwsException e = assertThrows(AwsException.class, () -> + service.createSchedule( + newRequest("s", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:lambda:us-east-1:000000000000:function:my-func", + "arn:aws:iam::000000000000:role/my-role", "{} garbage", null)), + REGION)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void createScheduleRejectsBlankInputForStepFunctionsTarget() { + // Target.Input has a minimum length of 1, and readTree returns a missing node for a + // blank value rather than failing. + for (String blank : List.of("", " ")) { + AwsException e = assertThrows(AwsException.class, () -> + service.createSchedule( + newRequest("s", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:states:us-east-1:000000000000:stateMachine:my-workflow", + "arn:aws:iam::000000000000:role/my-role", blank, null)), + REGION)); + assertEquals("ValidationException", e.getErrorCode()); + } + } + + @Test + void createScheduleAcceptsTextInputForSqsTarget() { + Schedule s = service.createSchedule( + newRequest("sqs-text", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:sqs:us-east-1:000000000000:my-queue", + "arn:aws:iam::000000000000:role/my-role", "plain text", null)), + REGION); + assertEquals("plain text", s.getTarget().getInput()); + } + + @Test + void createScheduleAcceptsAnyInputForUniversalTarget() { + Schedule s = service.createSchedule( + newRequest("universal", null, "rate(1 hour)", + new FlexibleTimeWindow("OFF", null), + new Target("arn:aws:scheduler:::aws-sdk:lambda:invoke", + "arn:aws:iam::000000000000:role/my-role", "not json", null)), + REGION); + assertEquals("not json", s.getTarget().getInput()); + } + @Test void updateScheduleMissingRequiredFieldsThrows() { service.createSchedule(