Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat: add scheduled rules support for EventBridge Rules (#217)

Mahamed-Belkheire8c64404899f
diff --git a/.gitignore b/.gitignore
index 2880bbd1c8..bcbad74da3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@ data/
.zed/settings.json
.DS_Store
.zed/settings.json
+.kiro/
CLAUDE.md
GEMINI.md
diff --git a/pom.xml b/pom.xml
index 9a30270d43..b6ca60806f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -61,6 +61,20 @@
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
+ <!-- Vert.x for per-container Lambda Runtime API servers -->
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-vertx</artifactId>
+ </dependency>
+
+ <!-- cron-utils for EventBridge schedule expression parsing -->
+ <dependency>
+ <groupId>com.cronutils</groupId>
+ <artifactId>cron-utils</artifactId>
+ <version>9.2.1</version>
+ </dependency>
+
+
<!-- Docker client for Lambda container lifecycle management -->
<dependency>
<groupId>com.github.docker-java</groupId>
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
new file mode 100644
index 0000000000..acba6654e9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
@@ -0,0 +1,65 @@
+package io.github.hectorvent.floci.services.eventbridge;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.services.eventbridge.model.Target;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+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;
+
+@ApplicationScoped
+public class EventBridgeInvoker {
+
+ private static final Logger LOG = Logger.getLogger(EventBridgeInvoker.class);
+
+ private final LambdaService lambdaService;
+ private final SqsService sqsService;
+ private final SnsService snsService;
+ private final String baseUrl;
+
+ @Inject
+ public EventBridgeInvoker(LambdaService lambdaService,
+ SqsService sqsService,
+ SnsService snsService,
+ EmulatorConfig config) {
+ this.lambdaService = lambdaService;
+ this.sqsService = sqsService;
+ this.snsService = snsService;
+ this.baseUrl = config.baseUrl();
+ }
+
+ public void invokeTarget(Target target, String eventJson, String region) {
+ String arn = target.getArn();
+ String payload = target.getInput() != null ? target.getInput() : eventJson;
+
+ try {
+ if (arn.contains(":lambda:") || arn.contains(":function:")) {
+ String fnName = arn.substring(arn.lastIndexOf(':') + 1);
+ String fnRegion = extractRegionFromArn(arn, region);
+ lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.Event);
+ LOG.debugv("EventBridge delivered to Lambda: {0}", arn);
+ } else if (arn.contains(":sqs:")) {
+ String queueUrl = AwsArnUtils.arnToQueueUrl(arn, baseUrl);
+ sqsService.sendMessage(queueUrl, payload, 0);
+ LOG.debugv("EventBridge delivered to SQS: {0}", arn);
+ } else if (arn.contains(":sns:")) {
+ String topicRegion = extractRegionFromArn(arn, region);
+ snsService.publish(arn, null, payload, "EventBridge", topicRegion);
+ LOG.debugv("EventBridge delivered to SNS: {0}", arn);
+ } else {
+ LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
+ }
+ } catch (Exception e) {
+ LOG.warnv("EventBridge failed to deliver to target {0}: {1}", arn, e.getMessage());
+ }
+ }
+
+ private static String extractRegionFromArn(String arn, String defaultRegion) {
+ String[] parts = arn.split(":");
+ return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
index a57a18a01e..ecf23b283d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java
@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
-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.StorageBackend;
@@ -11,14 +10,11 @@ import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
-import io.github.hectorvent.floci.services.lambda.LambdaService;
-import io.github.hectorvent.floci.services.lambda.model.InvocationType;
-import io.github.hectorvent.floci.services.sns.SnsService;
-import io.github.hectorvent.floci.services.sqs.SqsService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -39,20 +35,17 @@ public class EventBridgeService {
private final StorageBackend<String, Rule> ruleStore;
private final StorageBackend<String, List<Target>> targetStore;
private final RegionResolver regionResolver;
- private final LambdaService lambdaService;
- private final SqsService sqsService;
- private final SnsService snsService;
private final ObjectMapper objectMapper;
- private final String baseUrl;
+ private final RuleScheduler ruleScheduler;
+ private final EventBridgeInvoker invoker;
@Inject
public EventBridgeService(StorageFactory storageFactory,
EmulatorConfig config,
RegionResolver regionResolver,
- LambdaService lambdaService,
- SqsService sqsService,
- SnsService snsService,
- ObjectMapper objectMapper) {
+ ObjectMapper objectMapper,
+ RuleScheduler ruleScheduler,
+ EventBridgeInvoker invoker) {
this(
storageFactory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {}),
@@ -60,7 +53,7 @@ public class EventBridgeService {
new TypeReference<Map<String, Rule>>() {}),
storageFactory.create("eventbridge", "eventbridge-targets.json",
new TypeReference<Map<String, List<Target>>>() {}),
- regionResolver, lambdaService, sqsService, snsService, objectMapper, config.effectiveBaseUrl()
+ regionResolver, objectMapper, ruleScheduler, invoker
);
}
@@ -68,31 +61,26 @@ public class EventBridgeService {
StorageBackend<String, Rule> ruleStore,
StorageBackend<String, List<Target>> targetStore,
RegionResolver regionResolver,
- LambdaService lambdaService,
- SqsService sqsService,
- SnsService snsService,
- ObjectMapper objectMapper) {
- this(busStore, ruleStore, targetStore, regionResolver, lambdaService, sqsService, snsService, objectMapper, "http://localhost:4566");
- }
-
- EventBridgeService(StorageBackend<String, EventBus> busStore,
- StorageBackend<String, Rule> ruleStore,
- StorageBackend<String, List<Target>> targetStore,
- RegionResolver regionResolver,
- LambdaService lambdaService,
- SqsService sqsService,
- SnsService snsService,
ObjectMapper objectMapper,
- String baseUrl) {
+ RuleScheduler ruleScheduler,
+ EventBridgeInvoker invoker) {
this.busStore = busStore;
this.ruleStore = ruleStore;
this.targetStore = targetStore;
this.regionResolver = regionResolver;
- this.lambdaService = lambdaService;
- this.sqsService = sqsService;
- this.snsService = snsService;
this.objectMapper = objectMapper;
- this.baseUrl = baseUrl;
+ this.ruleScheduler = ruleScheduler;
+ this.invoker = invoker;
+ }
+
+ @PostConstruct
+ void init() {
+ if (ruleScheduler != null) {
+ ruleStore.keys().forEach(key -> {
+ ruleStore.get(key).ifPresent(this::startSchedulerIfNeeded);
+ });
+ LOG.infov("EventBridge initialized, {0} scheduler(s) restored", ruleScheduler.getActiveSchedulerCount());
+ }
}
// ──────────────────────────── Event Buses ────────────────────────────
@@ -186,7 +174,7 @@ public class EventBridgeService {
String key = ruleKey(region, effectiveBus, name);
Rule rule = ruleStore.get(key).orElse(new Rule());
rule.setName(name);
- rule.setArn(regionResolver.buildArn("events", region, "rule/" + effectiveBus + "/" + name));
+ rule.setArn(buildRuleArn(region, effectiveBus, name));
rule.setEventBusName(effectiveBus);
rule.setEventPattern(eventPattern);
rule.setScheduleExpression(scheduleExpression);
@@ -200,6 +188,12 @@ public class EventBridgeService {
rule.setCreatedAt(Instant.now());
}
ruleStore.put(key, rule);
+
+ if (ruleScheduler != null) {
+ ruleScheduler.stopScheduler(rule.getArn());
+ startSchedulerIfNeeded(rule);
+ }
+
LOG.infov("Put rule: {0} on bus {1}", name, effectiveBus);
return rule;
}
@@ -207,7 +201,7 @@ public class EventBridgeService {
public void deleteRule(String name, String busName, String region) {
String effectiveBus = resolvedBusName(busName);
String key = ruleKey(region, effectiveBus, name);
- ruleStore.get(key)
+ Rule rule = ruleStore.get(key)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Rule not found: " + name, 404));
List<Target> targets = targetStore.get(key).orElse(List.of());
@@ -215,6 +209,11 @@ public class EventBridgeService {
throw new AwsException("ValidationException",
"Rule still has targets. Remove targets before deleting the rule.", 400);
}
+
+ if (ruleScheduler != null) {
+ ruleScheduler.stopScheduler(rule.getArn());
+ }
+
ruleStore.delete(key);
LOG.infov("Deleted rule: {0}", name);
}
@@ -245,6 +244,7 @@ public class EventBridgeService {
"Rule not found: " + name, 404));
rule.setState(RuleState.ENABLED);
ruleStore.put(key, rule);
+ startSchedulerIfNeeded(rule);
}
public void disableRule(String name, String busName, String region) {
@@ -255,6 +255,10 @@ public class EventBridgeService {
"Rule not found: " + name, 404));
rule.setState(RuleState.DISABLED);
ruleStore.put(key, rule);
+
+ if (ruleScheduler != null) {
+ ruleScheduler.stopScheduler(rule.getArn());
+ }
}
// ──────────────────────────── Targets ────────────────────────────
@@ -336,7 +340,7 @@ public class EventBridgeService {
List<Target> targets = targetStore.get(ruleKey).orElse(List.of());
String eventJson = buildEventEnvelope(entry, effectiveBus, eventId);
for (Target target : targets) {
- invokeTarget(target, eventJson, region);
+ invoker.invokeTarget(target, eventJson, region);
}
}
}
@@ -420,31 +424,6 @@ public class EventBridgeService {
// ──────────────────────────── Target Routing ────────────────────────────
- private void invokeTarget(Target target, String eventJson, String region) {
- String arn = target.getArn();
- String payload = target.getInput() != null ? target.getInput() : eventJson;
- try {
- if (arn.contains(":lambda:") || arn.contains(":function:")) {
- String fnName = arn.substring(arn.lastIndexOf(':') + 1);
- String fnRegion = extractRegionFromArn(arn, region);
- lambdaService.invoke(fnRegion, fnName, payload.getBytes(), InvocationType.Event);
- LOG.debugv("EventBridge delivered to Lambda: {0}", arn);
- } else if (arn.contains(":sqs:")) {
- String queueUrl = sqsArnToUrl(arn);
- sqsService.sendMessage(queueUrl, payload, 0);
- LOG.debugv("EventBridge delivered to SQS: {0}", arn);
- } else if (arn.contains(":sns:")) {
- String topicRegion = extractRegionFromArn(arn, region);
- snsService.publish(arn, null, payload, "EventBridge", topicRegion);
- LOG.debugv("EventBridge delivered to SNS: {0}", arn);
- } else {
- LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
- }
- } catch (Exception e) {
- LOG.warnv("EventBridge failed to deliver to target {0}: {1}", arn, e.getMessage());
- }
- }
-
private String buildEventEnvelope(Map<String, Object> entry, String busName, String eventId) {
try {
String source = (String) entry.getOrDefault("Source", "");
@@ -502,17 +481,30 @@ public class EventBridgeService {
return ruleKeyPrefix(region, busName) + ruleName;
}
- private static String extractRegionFromArn(String arn, String defaultRegion) {
- String[] parts = arn.split(":");
- return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : defaultRegion;
+ private String buildRuleArn(String region, String busName, String ruleName) {
+ if ("default".equals(busName)) {
+ return regionResolver.buildArn("events", region, "rule/" + ruleName);
+ }
+ return regionResolver.buildArn("events", region, "rule/" + busName + "/" + ruleName);
}
- private String sqsArnToUrl(String arn) {
- String[] parts = arn.split(":");
- if (parts.length < 6) {
- throw new IllegalArgumentException("Invalid SQS ARN: " + arn);
+ private void startSchedulerIfNeeded(Rule rule) {
+ if (ruleScheduler != null
+ && rule.getState() == RuleState.ENABLED
+ && rule.getScheduleExpression() != null
+ && !rule.getScheduleExpression().isBlank()) {
+ String region = rule.getRegion() != null ? rule.getRegion() : "us-east-1";
+ String key = ruleKey(region, rule.getEventBusName(), rule.getName());
+ ruleScheduler.startScheduler(
+ rule.getArn(),
+ rule.getScheduleExpression(),
+ () -> {
+ Rule r = ruleStore.get(key).orElse(null);
+ List<Target> t = targetStore.get(key).orElse(List.of());
+ return new RuleScheduler.ScheduleData(r, t);
+ }
+ );
}
- return AwsArnUtils.arnToQueueUrl(arn, baseUrl);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java
new file mode 100644
index 0000000000..89b29882f2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java
@@ -0,0 +1,176 @@
+package io.github.hectorvent.floci.services.eventbridge;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.eventbridge.model.Rule;
+import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
+import io.github.hectorvent.floci.services.eventbridge.model.Target;
+import io.vertx.core.Vertx;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+@ApplicationScoped
+public class RuleScheduler {
+
+ private static final Logger LOG = Logger.getLogger(RuleScheduler.class);
+
+ private final Vertx vertx;
+ private final ObjectMapper objectMapper;
+ private final String accountId;
+ private final EventBridgeInvoker invoker;
+ private final ConcurrentHashMap<String, ScheduleContext> scheduleContexts = new ConcurrentHashMap<>();
+
+ @Inject
+ public RuleScheduler(Vertx vertx,
+ EmulatorConfig config,
+ ObjectMapper objectMapper,
+ EventBridgeInvoker invoker) {
+ this.vertx = vertx;
+ this.objectMapper = objectMapper;
+ this.accountId = config.defaultAccountId();
+ this.invoker = invoker;
+ }
+
+ @PreDestroy
+ void shutdown() {
+ scheduleContexts.values().forEach(ctx -> vertx.cancelTimer(ctx.timerId));
+ scheduleContexts.clear();
+ LOG.info("RuleScheduler shut down, all timers cancelled");
+ }
+
+ public void startScheduler(String ruleArn, String scheduleExpr,
+ Supplier<ScheduleData> dataSupplier) {
+ if (scheduleContexts.containsKey(ruleArn)) {
+ return;
+ }
+
+ if (scheduleExpr == null || scheduleExpr.isBlank()) {
+ LOG.warnv("Cannot start scheduler for rule {0}: no schedule expression", ruleArn);
+ return;
+ }
+
+ try {
+ if (ScheduleExpressionParser.isRateExpression(scheduleExpr)) {
+ startRateScheduler(ruleArn, scheduleExpr, dataSupplier);
+ } else if (ScheduleExpressionParser.isCronExpression(scheduleExpr)) {
+ scheduleCronFire(ruleArn, scheduleExpr, dataSupplier);
+ } else {
+ LOG.warnv("Unknown schedule expression format for rule {0}: {1}", ruleArn, scheduleExpr);
+ }
+ } catch (Exception e) {
+ LOG.warnv("Failed to parse schedule expression for rule {0}: {1}", ruleArn, e.getMessage());
+ }
+ }
+
+ private void startRateScheduler(String ruleArn, String scheduleExpr,
+ Supplier<ScheduleData> dataSupplier) {
+ long intervalMs = ScheduleExpressionParser.parseRateToMillis(scheduleExpr);
+
+ tick(dataSupplier);
+ long timerId = vertx.setPeriodic(intervalMs, id -> tick(dataSupplier));
+ scheduleContexts.put(ruleArn, new ScheduleContext(timerId, scheduleExpr));
+ LOG.debugv("Started rate scheduler for rule {0} with interval {1}ms", ruleArn, intervalMs);
+ }
+
+ private void scheduleCronFire(String ruleArn, String scheduleExpr,
+ Supplier<ScheduleData> dataSupplier) {
+ long delayMs;
+ try {
+ delayMs = ScheduleExpressionParser.millisUntilNextFire(scheduleExpr, ZonedDateTime.now());
+ } catch (Exception e) {
+ LOG.warnv("Failed to compute next fire time for rule {0}: {1}", ruleArn, e.getMessage());
+ return;
+ }
+
+ long timerId = vertx.setTimer(delayMs, id -> {
+ tick(dataSupplier);
+ scheduleContexts.remove(ruleArn);
+ scheduleCronFire(ruleArn, scheduleExpr, dataSupplier);
+ });
+ scheduleContexts.put(ruleArn, new ScheduleContext(timerId, scheduleExpr));
+ LOG.debugv("Scheduled cron fire for rule {0} in {1}ms", ruleArn, delayMs);
+ }
+
+ public void stopScheduler(String ruleArn) {
+ ScheduleContext ctx = scheduleContexts.remove(ruleArn);
+ if (ctx != null) {
+ vertx.cancelTimer(ctx.timerId);
+ LOG.debugv("Stopped scheduler for rule {0}", ruleArn);
+ }
+ }
+
+ private void tick(Supplier<ScheduleData> dataSupplier) {
+ ScheduleData data = dataSupplier.get();
+
+ if (data == null || data.rule == null) {
+ LOG.debugv("Rule no longer exists, stopping scheduler");
+ stopScheduler(data != null && data.rule != null ? data.rule.getArn() : null);
+ return;
+ }
+
+ if (data.rule.getState() != RuleState.ENABLED) {
+ LOG.debugv("Rule {0} is disabled, skipping tick", data.rule.getName());
+ return;
+ }
+
+ if (data.targets.isEmpty()) {
+ LOG.debugv("Rule {0} has no targets, skipping tick", data.rule.getName());
+ return;
+ }
+
+ String region = data.rule.getRegion() != null ? data.rule.getRegion() : "us-east-1";
+ String eventJson = buildScheduledEvent(data.rule, region);
+ LOG.debugv("Rule {0} firing scheduled event", data.rule.getName());
+
+ for (Target target : data.targets) {
+ try {
+ invoker.invokeTarget(target, eventJson, region);
+ } catch (Exception e) {
+ LOG.warnv("Failed to invoke target {0} for rule {1}: {2}",
+ target.getId(), data.rule.getName(), e.getMessage());
+ }
+ }
+ }
+
+ private String buildScheduledEvent(Rule rule, String region) {
+ try {
+ ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("version", "0");
+ node.put("id", UUID.randomUUID().toString());
+ node.put("source", "aws.events");
+ node.put("detail-type", "Scheduled Event");
+ node.put("account", accountId);
+ node.put("time", now.toInstant().toString());
+ node.put("region", region);
+ node.putArray("resources").add(rule.getArn());
+ node.putObject("detail");
+ return objectMapper.writeValueAsString(node);
+ } catch (Exception e) {
+ LOG.warnv("Failed to build scheduled event: {0}", e.getMessage());
+ return "{\"version\":\"0\",\"source\":\"aws.events\",\"detail-type\":\"Scheduled Event\",\"detail\":{}}";
+ }
+ }
+
+ public boolean isRunning(String ruleArn) {
+ return scheduleContexts.containsKey(ruleArn);
+ }
+
+ public int getActiveSchedulerCount() {
+ return scheduleContexts.size();
+ }
+
+ public record ScheduleData(Rule rule, List<Target> targets) {}
+
+ private record ScheduleContext(long timerId, String scheduleExpr) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParser.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParser.java
new file mode 100644
index 0000000000..02606055b9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParser.java
@@ -0,0 +1,109 @@
+package io.github.hectorvent.floci.services.eventbridge;
+
+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.ZonedDateTime;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class ScheduleExpressionParser {
+
+ 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 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);
+ }
+
+ private ScheduleExpressionParser() {}
+
+ public static boolean isRateExpression(String expression) {
+ return expression != null && RATE_PATTERN.matcher(expression.trim()).matches();
+ }
+
+ public static boolean isCronExpression(String expression) {
+ return expression != null && CRON_PATTERN.matcher(expression.trim()).matches();
+ }
+
+ public static long parseRateToMillis(String expression) {
+ if (expression == null || expression.isBlank()) {
+ throw new IllegalArgumentException("Schedule expression cannot be null or blank");
+ }
+
+ Matcher rateMatcher = RATE_PATTERN.matcher(expression.trim());
+ if (!rateMatcher.matches()) {
+ throw new IllegalArgumentException("Not a valid rate expression: " + expression);
+ }
+
+ int value = Integer.parseInt(rateMatcher.group(1));
+ if (value < 1) {
+ throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
+ }
+ String unit = rateMatcher.group(2).toLowerCase();
+
+ return switch (unit) {
+ case "minute", "minutes" -> value * 60 * 1000L;
+ case "hour", "hours" -> value * 60 * 60 * 1000L;
+ case "day", "days" -> value * 24 * 60 * 60 * 1000L;
+ case "week", "weeks" -> value * 7 * 24 * 60 * 60 * 1000L;
+ default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
+ };
+ }
+
+ public static ZonedDateTime getNextFireTime(String expression, ZonedDateTime from) {
+ if (expression == null || expression.isBlank()) {
+ throw new IllegalArgumentException("Schedule expression cannot be null or blank");
+ }
+
+ Matcher cronMatcher = CRON_PATTERN.matcher(expression.trim());
+ if (!cronMatcher.matches()) {
+ throw new IllegalArgumentException("Expected cron expression but got: " + expression);
+ }
+
+ String cronExpression = cronMatcher.group(1);
+ String normalized = normalizeCronExpression(cronExpression);
+ Cron cron = CRON_PARSER.parse(normalized);
+ cron.validate();
+
+ ExecutionTime executionTime = ExecutionTime.forCron(cron);
+ return executionTime.nextExecution(from).orElse(null);
+ }
+
+ public static long millisUntilNextFire(String expression, ZonedDateTime from) {
+ ZonedDateTime next = getNextFireTime(expression, from);
+ if (next == null) {
+ throw new IllegalStateException("No next fire time found for cron expression: " + expression);
+ }
+ long millis = java.time.temporal.ChronoUnit.MILLIS.between(from, next);
+ return Math.max(millis, 1000);
+ }
+
+ private static String normalizeCronExpression(String cronExpression) {
+ String[] fields = cronExpression.trim().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 + ": " + cronExpression);
+ }
+ return "0 " + cronExpression;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java
index fe832b71a4..7b3ff5d235 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java
@@ -51,4 +51,10 @@ public class Rule {
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
+
+ public String getRegion() {
+ if (arn == null) return null;
+ String[] parts = arn.split(":");
+ return parts.length >= 4 && !parts[3].isEmpty() ? parts[3] : null;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
new file mode 100644
index 0000000000..a8a20c4aaf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -0,0 +1,291 @@
+package io.github.hectorvent.floci.services.eventbridge;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
+import io.github.hectorvent.floci.services.eventbridge.model.Rule;
+import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
+import io.github.hectorvent.floci.services.eventbridge.model.Target;
+import io.vertx.core.Vertx;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class EventBridgeSchedulerIntegrationTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+
+ private Vertx vertx;
+ private EventBridgeService eventBridgeService;
+ private RuleScheduler scheduler;
+
+ @BeforeEach
+ void setUp() {
+ vertx = Vertx.vertx();
+ StorageBackend<String, EventBus> busStore = new InMemoryStorage<>();
+ StorageBackend<String, Rule> ruleStore = new InMemoryStorage<>();
+ StorageBackend<String, List<Target>> targetStore = new InMemoryStorage<>();
+
+ EventBridgeInvoker invoker = new EventBridgeInvoker(null, null, null, createConfig());
+ scheduler = new RuleScheduler(vertx, createConfig(), new ObjectMapper(), invoker);
+
+ eventBridgeService = new EventBridgeService(
+ busStore, ruleStore, targetStore,
+ new RegionResolver(REGION, ACCOUNT),
+ new ObjectMapper(), scheduler, invoker);
+ }
+
+ @AfterEach
+ void tearDown() {
+ vertx.close();
+ }
+
+ @Nested
+ @DisplayName("Rate expression lifecycle")
+ class RateLifecycle {
+
+ @Test
+ void putRuleWithScheduleStartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertTrue(scheduler.isRunning(rule.getArn()));
+ }
+
+ @Test
+ void deleteRuleStopsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.deleteRule("test-rule", "default", REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void disableRuleStopsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.disableRule("test-rule", "default", REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void enableRuleStartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.DISABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertFalse(scheduler.isRunning(arn));
+
+ eventBridgeService.enableRule("test-rule", "default", REGION);
+
+ assertTrue(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void putRuleDisablingScheduleStopsTimer() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.DISABLED, null, null, null, REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void putRuleRemovingScheduleStopsTimer() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-rule", "default", null, null,
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void changingCronToRateRestartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertTrue(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void changingRateToCronRestartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-rule", "default", null, "rate(1 minute)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertTrue(scheduler.isRunning(arn));
+ }
+ }
+
+ @Nested
+ @DisplayName("Cron expression lifecycle")
+ class CronLifecycle {
+
+ @Test
+ void putRuleWithScheduleStartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertTrue(scheduler.isRunning(rule.getArn()));
+ }
+
+ @Test
+ void deleteRuleStopsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.deleteRule("test-cron-rule", "default", REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void disableRuleStopsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.disableRule("test-cron-rule", "default", REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void enableRuleStartsScheduler() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.DISABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertFalse(scheduler.isRunning(arn));
+
+ eventBridgeService.enableRule("test-cron-rule", "default", REGION);
+
+ assertTrue(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void putRuleDisablingScheduleStopsTimer() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.DISABLED, null, null, null, REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+
+ @Test
+ void putRuleRemovingScheduleStopsTimer() {
+ eventBridgeService.getOrCreateDefaultBus(REGION);
+ Rule rule = eventBridgeService.putRule(
+ "test-cron-rule", "default", null, "cron(0/1 * * * ? *)",
+ RuleState.ENABLED, null, null, null, REGION);
+ String arn = rule.getArn();
+
+ assertTrue(scheduler.isRunning(arn));
+
+ eventBridgeService.putRule(
+ "test-cron-rule", "default", null, null,
+ RuleState.ENABLED, null, null, null, REGION);
+
+ assertFalse(scheduler.isRunning(arn));
+ }
+ }
+
+ private EmulatorConfig createConfig() {
+ return new EmulatorConfig() {
+ @Override
+ public String baseUrl() { return "http://localhost:4566"; }
+ @Override
+ public String defaultRegion() { return REGION; }
+ @Override
+ public String defaultAccountId() { return ACCOUNT; }
+ @Override
+ public StorageConfig storage() { return null; }
+ @Override
+ public AuthConfig auth() { return null; }
+ @Override
+ public ServicesConfig services() { return null; }
+ };
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
index 6823b5e866..bb6b79c8bd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java
@@ -9,10 +9,6 @@ import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
-import io.github.hectorvent.floci.services.lambda.LambdaService;
-import io.github.hectorvent.floci.services.lambda.model.InvocationType;
-import io.github.hectorvent.floci.services.sns.SnsService;
-import io.github.hectorvent.floci.services.sqs.SqsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -31,22 +27,19 @@ class EventBridgeServiceTest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private EventBridgeService service;
- private LambdaService lambdaServiceMock;
- private SqsService sqsServiceMock;
- private SnsService snsServiceMock;
+ private EventBridgeInvoker invokerMock;
@BeforeEach
void setUp() {
- snsServiceMock = mock(SnsService.class);
- sqsServiceMock = mock(SqsService.class);
- lambdaServiceMock = mock(LambdaService.class);
+ invokerMock = mock(EventBridgeInvoker.class);
service = new EventBridgeService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"),
- lambdaServiceMock, sqsServiceMock, snsServiceMock,
- new ObjectMapper()
+ new ObjectMapper(),
+ null,
+ invokerMock
);
}
@@ -364,11 +357,7 @@ class EventBridgeServiceTest {
assertEquals(0, result.failedCount());
assertEquals(1, result.entries().size());
assertNotNull(result.entries().getFirst().get("EventId"));
- String expectedMessage = "\\{\"version\":\"0\",\"id\":\"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\",\"source\":\"my.app\"," +
- "\"detail-type\":\"Test\",\"account\":\"000000000000\",\"time\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}Z\"," +
- "\"region\":\"us-east-1\",\"resources\":\\[\"resource1\"],\"detail\":\\{},\"event-bus-name\":\"default\"}";
- verify(lambdaServiceMock).invoke(eq(REGION), eq("my-function"),
- argThat(bytes -> new String(bytes).matches(expectedMessage)), eq(InvocationType.Event));
+ verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
}
@Test
@@ -389,10 +378,7 @@ class EventBridgeServiceTest {
assertEquals(0, result.failedCount());
assertEquals(1, result.entries().size());
assertNotNull(result.entries().getFirst().get("EventId"));
- String expectedMessage = "\\{\"version\":\"0\",\"id\":\"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\",\"source\":\"my.app\"," +
- "\"detail-type\":\"Test\",\"account\":\"000000000000\",\"time\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}Z\"," +
- "\"region\":\"us-east-1\",\"resources\":\\[\"resource1\"],\"detail\":\\{},\"event-bus-name\":\"default\"}";
- verify(sqsServiceMock).sendMessage(eq("http://localhost:4566/000000000000/my-queue"), matches(expectedMessage), eq(0));
+ verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
}
@Test
@@ -413,10 +399,6 @@ class EventBridgeServiceTest {
assertEquals(0, result.failedCount());
assertEquals(1, result.entries().size());
assertNotNull(result.entries().getFirst().get("EventId"));
-
- String expectedMessage = "\\{\"version\":\"0\",\"id\":\"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\",\"source\":\"my.app\"," +
- "\"detail-type\":\"Test\",\"account\":\"000000000000\",\"time\":\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}Z\"," +
- "\"region\":\"us-east-1\",\"resources\":\\[\"resource1\"],\"detail\":\\{},\"event-bus-name\":\"default\"}";
- verify(snsServiceMock).publish(eq("arn:aws:sns:us-east-1:000000000000:my-topic"), isNull(), matches(expectedMessage), eq("EventBridge"), eq(REGION));
+ verify(invokerMock).invokeTarget(eq(target), any(String.class), eq(REGION));
}
}
\ No newline at end of file
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParserTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParserTest.java
new file mode 100644
index 0000000000..ce685f8d0b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/ScheduleExpressionParserTest.java
@@ -0,0 +1,180 @@
+package io.github.hectorvent.floci.services.eventbridge;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.ZonedDateTime;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class ScheduleExpressionParserTest {
+
+ // ──────────────────────────── Expression Type Detection ────────────────────────────
+
+ @Test
+ void isRateExpression() {
+ assertTrue(ScheduleExpressionParser.isRateExpression("rate(5 minutes)"));
+ assertTrue(ScheduleExpressionParser.isRateExpression("rate(1 hour)"));
+ assertTrue(ScheduleExpressionParser.isRateExpression("RATE(5 MINUTES)"));
+ assertFalse(ScheduleExpressionParser.isRateExpression("cron(0 10 * * ? *)"));
+ assertFalse(ScheduleExpressionParser.isRateExpression("invalid"));
+ assertFalse(ScheduleExpressionParser.isRateExpression(null));
+ }
+
+ @Test
+ void isCronExpression() {
+ assertTrue(ScheduleExpressionParser.isCronExpression("cron(0 10 * * ? *)"));
+ assertTrue(ScheduleExpressionParser.isCronExpression("CRON(0 10 * * ? *)"));
+ assertFalse(ScheduleExpressionParser.isCronExpression("rate(5 minutes)"));
+ assertFalse(ScheduleExpressionParser.isCronExpression("invalid"));
+ assertFalse(ScheduleExpressionParser.isCronExpression(null));
+ }
+
+ // ──────────────────────────── Rate Expressions ────────────────────────────
+
+ @Test
+ void parseRateMinutes() {
+ assertEquals(300000, ScheduleExpressionParser.parseRateToMillis("rate(5 minutes)"));
+ assertEquals(60000, ScheduleExpressionParser.parseRateToMillis("rate(1 minute)"));
+ assertEquals(120000, ScheduleExpressionParser.parseRateToMillis("rate(2 minutes)"));
+ }
+
+ @Test
+ void parseRateHours() {
+ assertEquals(3600000, ScheduleExpressionParser.parseRateToMillis("rate(1 hour)"));
+ assertEquals(7200000, ScheduleExpressionParser.parseRateToMillis("rate(2 hours)"));
+ }
+
+ @Test
+ void parseRateDays() {
+ assertEquals(86400000, ScheduleExpressionParser.parseRateToMillis("rate(1 day)"));
+ assertEquals(172800000, ScheduleExpressionParser.parseRateToMillis("rate(2 days)"));
+ }
+
+ @Test
+ void parseRateWeeks() {
+ assertEquals(604800000, ScheduleExpressionParser.parseRateToMillis("rate(1 week)"));
+ assertEquals(1209600000, ScheduleExpressionParser.parseRateToMillis("rate(2 weeks)"));
+ }
+
+ @Test
+ void parseRateAcceptsSingularAndPluralUnits() {
+ assertEquals(60000, ScheduleExpressionParser.parseRateToMillis("rate(1 minute)"));
+ assertEquals(60000, ScheduleExpressionParser.parseRateToMillis("rate(1 minutes)"));
+ assertEquals(120000, ScheduleExpressionParser.parseRateToMillis("rate(2 minute)"));
+ assertEquals(120000, ScheduleExpressionParser.parseRateToMillis("rate(2 minutes)"));
+ }
+
+ @Test
+ void parseRateRejectsZeroValue() {
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis("rate(0 minutes)"));
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis("rate(0 minute)"));
+ }
+
+ @Test
+ void parseRateCaseInsensitive() {
+ assertEquals(300000, ScheduleExpressionParser.parseRateToMillis("RATE(5 MINUTES)"));
+ assertEquals(300000, ScheduleExpressionParser.parseRateToMillis("Rate(5 Minutes)"));
+ }
+
+ @Test
+ void parseRateWithSpaces() {
+ assertEquals(300000, ScheduleExpressionParser.parseRateToMillis("rate( 5 minutes )"));
+ }
+
+ @Test
+ void parseRateInvalidFormatThrows() {
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis("rate(5)"));
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis("rate(minutes)"));
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis("cron(0 10 * * ? *)"));
+ }
+
+ @Test
+ void parseRateNullThrows() {
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.parseRateToMillis(null));
+ }
+
+ // ──────────────────────────── Cron Expressions ────────────────────────────
+
+ @Test
+ void getNextFireTimeDailyCron() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-22T08:00:00Z");
+ ZonedDateTime next = ScheduleExpressionParser.getNextFireTime("cron(0 10 * * ? *)", from);
+
+ assertNotNull(next);
+ assertEquals(10, next.getHour());
+ assertEquals(0, next.getMinute());
+ }
+
+ @Test
+ void getNextFireTimeEvery15Minutes() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-22T10:00:00Z");
+ ZonedDateTime next = ScheduleExpressionParser.getNextFireTime("cron(0/15 * * * ? *)", from);
+
+ assertNotNull(next);
+ assertEquals(10, next.getHour());
+ assertEquals(15, next.getMinute());
+ }
+
+ @Test
+ void getNextFireTimeWeekdays() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-23T08:00:00Z");
+ ZonedDateTime next = ScheduleExpressionParser.getNextFireTime("cron(0 9-17 * * 1-5 *)", from);
+
+ assertNotNull(next);
+ assertTrue(next.getHour() >= 9 && next.getHour() <= 17);
+ }
+
+ @Test
+ void getNextFireTimeFirstMondayOfMonth() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-01T02:00:00Z");
+ ZonedDateTime next = ScheduleExpressionParser.getNextFireTime("cron(30 2 ? * 2#1 *)", from);
+
+ assertNotNull(next);
+ assertEquals(2, next.getHour());
+ assertEquals(30, next.getMinute());
+ assertEquals(2, next.getDayOfWeek().getValue());
+ }
+
+ @Test
+ void getNextFireTimeInvalidCronThrows() {
+ assertThrows(Exception.class, () ->
+ ScheduleExpressionParser.getNextFireTime("cron(invalid)", ZonedDateTime.now()));
+ }
+
+ @Test
+ void getNextFireTimeNotCronExpressionThrows() {
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.getNextFireTime("rate(5 minutes)", ZonedDateTime.now()));
+ }
+
+ @Test
+ void getNextFireTimeRejects5FieldCron() {
+ assertThrows(IllegalArgumentException.class, () ->
+ ScheduleExpressionParser.getNextFireTime("cron(0 10 * * *)", ZonedDateTime.now()));
+ }
+
+ // ──────────────────────────── millisUntilNextFire ────────────────────────────
+
+ @Test
+ void millisUntilNextFireCron() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-22T10:00:00Z");
+ long delay = ScheduleExpressionParser.millisUntilNextFire("cron(0/15 * * * ? *)", from);
+
+ assertTrue(delay > 0);
+ assertTrue(delay <= 15 * 60 * 1000);
+ }
+
+ @Test
+ void millisUntilNextFireCronEveryMinute() {
+ ZonedDateTime from = ZonedDateTime.parse("2026-03-22T10:00:30Z");
+ long delay = ScheduleExpressionParser.millisUntilNextFire("cron(0 * * * ? *)", from);
+
+ assertTrue(delay >= 1000);
+ }
+}