feat(scheduler): invoke targets when schedules fire (#551)

Adds a background dispatcher that reads persisted schedules and invokes their
targets on time, closing the CRUD-only gap called out in PR #260 and
documented under "Not Yet Supported".

- SchedulerExpressionParser parses at(), rate(), and 6-field cron() with
  optional ScheduleExpressionTimezone (default UTC).
- ScheduleInvoker delivers to SQS, Lambda, SNS, and EventBridge PutEvents,
  mirroring the EventBridgeInvoker pattern but adapted to Scheduler's Target
  model (raw Input string, no JSONPath/template).
- ScheduleDispatcher is a single-threaded ticker that scans every schedule,
  gates on State/StartDate/EndDate, fires due schedules, and honours
  ActionAfterCompletion=DELETE for one-time at() schedules.
- FlexibleTimeWindow, RetryPolicy and DeadLetterConfig are stored but not
  yet honoured; those can be layered on incrementally.

Config (floci.services.scheduler):
  - invocation-enabled (default true)
  - tick-interval-seconds (default 10)

Unit tests cover the parser (at/rate/cron, timezone, validation) and the
dispatcher (firing, once-semantics, delete-after-completion, state gating,
start/end windows, unsupported expression handling).

Closes #550
This commit is contained in:
Victor Sanchez Velasco authored and GitHub committed 2026-04-21 19:42:01 -05:00
1 parent 9ea28ee629
commit b9957dfdbe
8 files changed
+775 -1

No files matched your search

@@ -352,6 +352,21 @@ public interface EmulatorConfig {
interface SchedulerServiceConfig {
@WithDefault("true")
boolean enabled();
/**
* Run the background dispatcher that fires schedule targets. Setting this
* to {@code false} keeps the scheduler API CRUD-only (the pre-invocation
* behavior). Invocation is only attempted when the service itself is enabled.
*/
@WithDefault("true")
boolean invocationEnabled();
/**
* How often the dispatcher scans for due schedules. Must be >= 1s;
* default 10s is a reasonable trade-off between latency and load for local use.
*/
@WithDefault("10")
long tickIntervalSeconds();
}
interface CloudWatchLogsServiceConfig {
@@ -0,0 +1,197 @@
package io.github.hectorvent.floci.services.scheduler;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.scheduler.SchedulerExpressionParser.Kind;
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Fires EventBridge Scheduler targets when schedules are due.
*
* A single background thread ticks on a fixed interval, scans all persisted
* schedules, and invokes the target of any schedule whose next fire time has
* passed. Per-schedule "last fire" state is kept in memory (by schedule ARN);
* restarts reset it, matching the emulator's loose durability expectations.
*
* Scope of the initial implementation:
* <ul>
* <li>Expression kinds: {@code at(...)}, {@code rate(...)}, {@code cron(...)}
* with optional {@code ScheduleExpressionTimezone}.</li>
* <li>Gating: {@code State=DISABLED}, {@code StartDate}/{@code EndDate}.</li>
* <li>Completion: {@code ActionAfterCompletion=DELETE} removes one-time
* {@code at(...)} schedules once fired.</li>
* <li>Targets: whatever {@link ScheduleInvoker} can deliver to (SQS, Lambda,
* SNS, EventBridge).</li>
* <li>Failures: logged; {@code RetryPolicy} / {@code DeadLetterConfig} are
* stored but not yet honored.</li>
* </ul>
*/
@ApplicationScoped
public class ScheduleDispatcher {
private static final Logger LOG = Logger.getLogger(ScheduleDispatcher.class);
private final SchedulerService schedulerService;
private final ScheduleInvoker invoker;
private final long tickIntervalSeconds;
private final boolean enabled;
private final ScheduledExecutorService executor;
private final ConcurrentHashMap<String, Instant> lastFireByArn = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> firedOnceByArn = new ConcurrentHashMap<>();
@Inject
public ScheduleDispatcher(SchedulerService schedulerService,
ScheduleInvoker invoker,
EmulatorConfig config) {
this.schedulerService = schedulerService;
this.invoker = invoker;
this.tickIntervalSeconds = config.services().scheduler().tickIntervalSeconds();
this.enabled = config.services().scheduler().enabled()
&& config.services().scheduler().invocationEnabled();
this.executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "scheduler-dispatcher");
t.setDaemon(true);
return t;
});
}
void onStart(@Observes StartupEvent ignored) {
if (!enabled) {
LOG.info("Scheduler dispatcher disabled by configuration");
return;
}
executor.scheduleAtFixedRate(this::tickSafely, tickIntervalSeconds, tickIntervalSeconds, TimeUnit.SECONDS);
LOG.infov("Scheduler dispatcher started (tick every {0}s)", tickIntervalSeconds);
}
void onStop(@Observes ShutdownEvent ignored) {
executor.shutdownNow();
}
void tickSafely() {
try {
tick(Instant.now());
} catch (Throwable t) {
LOG.warnv("Scheduler dispatcher tick failed: {0}", t.getMessage());
}
}
void tick(Instant now) {
List<Schedule> schedules = schedulerService.listAllSchedules();
for (Schedule schedule : schedules) {
try {
evaluate(schedule, now);
} catch (Exception e) {
LOG.warnv("Failed to evaluate schedule {0}: {1}", schedule.getArn(), e.getMessage());
}
}
}
private void evaluate(Schedule schedule, Instant now) {
if (!"ENABLED".equalsIgnoreCase(schedule.getState())) {
return;
}
if (schedule.getStartDate() != null && now.isBefore(schedule.getStartDate())) {
return;
}
if (schedule.getEndDate() != null && now.isAfter(schedule.getEndDate())) {
return;
}
if (schedule.getScheduleExpression() == null || schedule.getTarget() == null) {
return;
}
Kind kind;
try {
kind = SchedulerExpressionParser.classify(schedule.getScheduleExpression());
} catch (IllegalArgumentException e) {
LOG.warnv("Unsupported expression on schedule {0}: {1}",
schedule.getArn(), schedule.getScheduleExpression());
return;
}
Instant nextFire = computeNextFire(schedule, kind, now);
if (nextFire == null || now.isBefore(nextFire)) {
return;
}
fire(schedule);
recordFire(schedule, now);
if (kind == Kind.AT && isDeleteAfterCompletion(schedule)) {
try {
schedulerService.deleteSchedule(schedule.getName(), schedule.getGroupName(), regionOf(schedule));
lastFireByArn.remove(schedule.getArn());
firedOnceByArn.remove(schedule.getArn());
} catch (Exception e) {
LOG.warnv("Post-completion delete failed for {0}: {1}", schedule.getArn(), e.getMessage());
}
}
}
private Instant computeNextFire(Schedule schedule, Kind kind, Instant now) {
String expr = schedule.getScheduleExpression();
String tz = schedule.getScheduleExpressionTimezone();
String arn = schedule.getArn();
return switch (kind) {
case AT -> {
if (firedOnceByArn.containsKey(arn)) {
yield null;
}
yield SchedulerExpressionParser.parseAt(expr, tz);
}
case RATE -> {
long intervalMs = SchedulerExpressionParser.parseRateMillis(expr);
Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null
? schedule.getCreationDate()
: now);
yield base.plusMillis(intervalMs);
}
case CRON -> {
Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null
? schedule.getCreationDate()
: now.minusSeconds(1));
yield SchedulerExpressionParser.nextCronFire(expr, base, tz);
}
};
}
private void fire(Schedule schedule) {
String region = regionOf(schedule);
try {
invoker.invoke(schedule.getTarget(), region);
LOG.infov("Fired schedule {0} in group {1}", schedule.getName(), schedule.getGroupName());
} catch (Exception e) {
LOG.warnv("Schedule {0} invocation failed: {1}", schedule.getArn(), e.getMessage());
}
}
private void recordFire(Schedule schedule, Instant now) {
lastFireByArn.put(schedule.getArn(), now);
firedOnceByArn.put(schedule.getArn(), Boolean.TRUE);
}
private static boolean isDeleteAfterCompletion(Schedule schedule) {
return "DELETE".equalsIgnoreCase(schedule.getActionAfterCompletion());
}
private static String regionOf(Schedule schedule) {
String arn = schedule.getArn();
if (arn == null) return "us-east-1";
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : "us-east-1";
}
}
@@ -0,0 +1,111 @@
package io.github.hectorvent.floci.services.scheduler;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
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.Target;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Delivers an EventBridge Scheduler target invocation to the underlying service.
* Supports SQS, Lambda, SNS, and EventBridge PutEvents targets — mirrors the
* subset handled by {@code EventBridgeInvoker} but using Scheduler's
* {@link Target} model (raw {@code input} string, no JSONPath/template).
*/
@ApplicationScoped
public class ScheduleInvoker {
private static final Logger LOG = Logger.getLogger(ScheduleInvoker.class);
private final SqsService sqsService;
private final LambdaService lambdaService;
private final SnsService snsService;
private final EventBridgeService eventBridgeService;
private final ObjectMapper objectMapper;
private final String baseUrl;
@Inject
public ScheduleInvoker(SqsService sqsService,
LambdaService lambdaService,
SnsService snsService,
EventBridgeService eventBridgeService,
ObjectMapper objectMapper,
EmulatorConfig config) {
this.sqsService = sqsService;
this.lambdaService = lambdaService;
this.snsService = snsService;
this.eventBridgeService = eventBridgeService;
this.objectMapper = objectMapper;
this.baseUrl = config.baseUrl();
}
public void invoke(Target target, String region) {
if (target == null || target.getArn() == null) {
return;
}
String arn = target.getArn();
String payload = target.getInput() != null ? target.getInput() : "{}";
String targetRegion = extractRegion(arn, region);
if (arn.contains(":sqs:")) {
String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0);
LOG.debugv("Scheduler delivered to SQS: {0}", arn);
} else if (arn.contains(":lambda:") || arn.contains(":function:")) {
String fnName = arn.substring(arn.lastIndexOf(':') + 1);
lambdaService.invoke(targetRegion, fnName, 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 (isEventBridgePutEventsArn(arn)) {
deliverToEventBridge(arn, payload, targetRegion);
LOG.debugv("Scheduler delivered to EventBridge: {0}", arn);
} else {
LOG.warnv("Scheduler: unsupported target ARN type: {0}", arn);
}
}
private boolean isEventBridgePutEventsArn(String arn) {
return arn.contains(":events:") && arn.contains(":event-bus/");
}
private void deliverToEventBridge(String busArn, String payload, String region) {
String busName = busArn.substring(busArn.indexOf(":event-bus/") + ":event-bus/".length());
Map<String, Object> entry = new HashMap<>();
entry.put("EventBusName", busName);
entry.put("Source", "aws.scheduler");
entry.put("DetailType", "Scheduled Event");
entry.put("Detail", asDetail(payload));
eventBridgeService.putEvents(List.of(entry), region);
}
private String asDetail(String payload) {
try {
objectMapper.readTree(payload);
return payload;
} catch (Exception e) {
try {
return objectMapper.writeValueAsString(Map.of("payload", payload));
} catch (Exception inner) {
return "{}";
}
}
}
private static String extractRegion(String arn, String defaultRegion) {
String[] parts = arn.split(":");
return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
}
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.scheduler;
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses AWS EventBridge Scheduler schedule expressions and computes next fire times.
*
* Supported forms (matches the AWS API):
* <ul>
* <li>{@code at(YYYY-MM-DDTHH:mm:ss)} — one-time fire at the given instant
* (interpreted in {@code scheduleExpressionTimezone}, default UTC).</li>
* <li>{@code rate(N unit)} — repeating fire every N minutes/hours/days/weeks.</li>
* <li>{@code cron(fields)} — six-field AWS EventBridge cron (minute hour DOM month DOW year).</li>
* </ul>
*/
public final class SchedulerExpressionParser {
private static final Pattern AT_PATTERN = Pattern.compile(
"^at\\(\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})\\s*\\)$",
Pattern.CASE_INSENSITIVE);
private static final Pattern RATE_PATTERN = Pattern.compile(
"^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?|weeks?)\\s*\\)$",
Pattern.CASE_INSENSITIVE);
private static final Pattern CRON_PATTERN = Pattern.compile(
"^cron\\((.+)\\)$",
Pattern.CASE_INSENSITIVE);
private static final DateTimeFormatter AT_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
private static final CronParser CRON_PARSER;
static {
CronDefinition definition = CronDefinitionBuilder.defineCron()
.withSeconds().and()
.withMinutes().and()
.withHours().and()
.withDayOfMonth().supportsHash().supportsL().supportsW().supportsQuestionMark().and()
.withMonth().and()
.withDayOfWeek().supportsHash().supportsL().supportsW().supportsQuestionMark().and()
.withYear().optional().and()
.instance();
CRON_PARSER = new CronParser(definition);
}
public enum Kind { AT, RATE, CRON }
private SchedulerExpressionParser() {}
public static Kind classify(String expression) {
if (expression == null) {
throw new IllegalArgumentException("Schedule expression is null");
}
String trimmed = expression.trim();
if (AT_PATTERN.matcher(trimmed).matches()) return Kind.AT;
if (RATE_PATTERN.matcher(trimmed).matches()) return Kind.RATE;
if (CRON_PATTERN.matcher(trimmed).matches()) return Kind.CRON;
throw new IllegalArgumentException("Unsupported schedule expression: " + expression);
}
/**
* Parses an {@code at(...)} expression and returns the fire instant.
* The timestamp is interpreted in {@code timezone} (default UTC).
*/
public static Instant parseAt(String expression, String timezone) {
Matcher m = AT_PATTERN.matcher(expression.trim());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid at() expression: " + expression);
}
LocalDateTime local = LocalDateTime.parse(m.group(1), AT_FORMATTER);
ZoneId zone = resolveZone(timezone);
return local.atZone(zone).toInstant();
}
/**
* Parses a {@code rate(...)} expression and returns the interval in milliseconds.
*/
public static long parseRateMillis(String expression) {
Matcher m = RATE_PATTERN.matcher(expression.trim());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid rate() expression: " + expression);
}
int value = Integer.parseInt(m.group(1));
if (value < 1) {
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
}
String unit = m.group(2).toLowerCase();
return switch (unit) {
case "minute", "minutes" -> value * 60_000L;
case "hour", "hours" -> value * 3_600_000L;
case "day", "days" -> value * 86_400_000L;
case "week", "weeks" -> value * 604_800_000L;
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
};
}
/**
* Returns the next fire instant at or after {@code from} for a cron expression
* evaluated in {@code timezone} (default UTC).
*/
public static Instant nextCronFire(String expression, Instant from, String timezone) {
Matcher m = CRON_PATTERN.matcher(expression.trim());
if (!m.matches()) {
throw new IllegalArgumentException("Not a valid cron() expression: " + expression);
}
String cronFields = m.group(1).trim();
String[] fields = cronFields.split("\\s+");
if (fields.length != 6) {
throw new IllegalArgumentException(
"AWS EventBridge cron expressions require 6 fields (minute hour day-of-month month day-of-week year), got "
+ fields.length + ": " + cronFields);
}
Cron cron = CRON_PARSER.parse("0 " + cronFields);
cron.validate();
ExecutionTime exec = ExecutionTime.forCron(cron);
ZoneId zone = resolveZone(timezone);
ZonedDateTime zdt = from.atZone(zone);
return exec.nextExecution(zdt)
.map(ZonedDateTime::toInstant)
.orElseThrow(() -> new IllegalStateException(
"No next fire time for cron expression: " + expression));
}
private static ZoneId resolveZone(String timezone) {
if (timezone == null || timezone.isBlank()) {
return ZoneOffset.UTC;
}
return ZoneId.of(timezone);
}
}
@@ -231,6 +231,15 @@ public class SchedulerService {
LOG.infov("Deleted schedule: {0} in group {1}", name, effectiveGroup);
}
/**
* Return every persisted schedule across all regions and groups. Used by
* {@link ScheduleDispatcher} to evaluate due schedules; other callers should
* prefer {@link #listSchedules}.
*/
public List<Schedule> listAllSchedules() {
return scheduleStore.scan(k -> k.startsWith("schedule:"));
}
public List<Schedule> listSchedules(String groupName, String namePrefix, String state, String region) {
String storagePrefix;
if (groupName != null && !groupName.isBlank()) {