mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
* fix(eventbridge): validate scheduled rule rate expressions Validate schedule expressions before PutRule creates or mutates a rule. Reject mismatched rate units with the AWS ValidationException while preserving existing rule state and timers. Keep stored-expression parsing tolerant. Add service, SDK and scheduler regression coverage. Closes #7996. * refactor(eventbridge): share rate parsing and cover legacy stack updates Use one matcher and parsed value/unit helper for strict API validation and tolerant stored-expression execution. Keep unit agreement checks at the API boundary. Add a CloudFormation SDK regression proving that unrelated stack updates already skip unchanged legacy rules while direct PutRule calls remain strict. Correct the outdated test comment suggesting every resource is re-provisioned. * refactor(eventbridge): share AWS rate validation with Scheduler Move positive value, supported unit and singular/plural constraints into core.common.AwsRateExpressions. Both API validators call the shared checks while their execution parsers retain support for legacy stored expressions. Parse Scheduler rates once per call and retain its checked interval conversion. Add cross-service tests for matching acceptance and rejection reasons. Addresses review 5876298647 on #8113.
This commit is contained in:
1 parent
f3b61cc368
commit
14f01c80e8
12 files changed
+371
-46
No files matched your search
@@ -396,6 +396,7 @@ refuses it. Across accounts the bus policy and the caller's identity policies bo
|
||||
|
||||
## Current Behavior
|
||||
|
||||
- `PutRule` validates schedule expressions before creating or updating a rule, including disabled rules and rules with an event pattern. Rate values must be positive integers, with singular `minute`, `hour` or `day` for 1 and plural units for larger values. Invalid expressions return `ValidationException` without changing an existing rule or its timer.
|
||||
- `PutEvents` reports success once the source bus accepts an event. Target delivery failures are retried and dead-lettered as described above, and otherwise surface only as a `WARN` in the Floci logs.
|
||||
- A `PutEvents` entry for an event bus that does not exist is answered as AWS answers it: with an event id, not counted in `FailedEntryCount`, and dropped, as no rule matches it. Floci logs the drop at `INFO`. Floci's own deliveries to a bus, for a rule, a pipe or a schedule, are unchanged: an entry for a bus that does not exist fails there.
|
||||
- A `Detail` forwarded to an event bus must be a JSON object, as in AWS; anything else is dropped, including an `InputPath` selecting a scalar such as `$.detail.orderId` or an envelope carrying `"detail": null`.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/** Rate constraints shared by EventBridge rules and EventBridge Scheduler API requests. */
|
||||
public final class AwsRateExpressions {
|
||||
|
||||
private static final Set<String> UNITS = Set.of("minute", "minutes", "hour", "hours", "day", "days");
|
||||
|
||||
private AwsRateExpressions() {
|
||||
}
|
||||
|
||||
/** Validates a parsed rate without restricting the parsers used for previously stored schedules. */
|
||||
public static void validate(long value, String unit) {
|
||||
requirePositiveValue(value);
|
||||
String normalizedUnit = unit == null ? "" : unit.toLowerCase(Locale.ROOT);
|
||||
if (!UNITS.contains(normalizedUnit)) {
|
||||
throw new IllegalArgumentException("Rate unit must be minute(s), hour(s), or day(s)");
|
||||
}
|
||||
boolean plural = normalizedUnit.endsWith("s");
|
||||
if ((value == 1) == plural) {
|
||||
throw new IllegalArgumentException("Rate unit must be singular for 1 and plural for values greater than 1");
|
||||
}
|
||||
}
|
||||
|
||||
/** Positive values are also required when executing previously stored expressions. */
|
||||
public static void requirePositiveValue(long value) {
|
||||
if (value < 1) {
|
||||
throw new IllegalArgumentException("Rate value must be >= 1, got: " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,6 +363,13 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
|
||||
if (eventPattern != null && !eventPattern.isBlank()) {
|
||||
validateEventPattern(eventPattern);
|
||||
}
|
||||
if (scheduleExpression != null && !scheduleExpression.isBlank()) {
|
||||
try {
|
||||
ScheduleExpressionParser.validate(scheduleExpression);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException", "Parameter ScheduleExpression is not valid.", 400);
|
||||
}
|
||||
}
|
||||
String effectiveBus = resolvedBusName(busName);
|
||||
ensureBusExists(effectiveBus, region);
|
||||
|
||||
|
||||
@@ -4,9 +4,12 @@ import com.cronutils.model.Cron;
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import com.cronutils.parser.CronParser;
|
||||
import io.floci.aws.core.common.AwsCronDefinitions;
|
||||
import io.floci.aws.core.common.AwsRateExpressions;
|
||||
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -32,28 +35,25 @@ public final class ScheduleExpressionParser {
|
||||
return expression != null && CRON_PATTERN.matcher(expression.trim()).matches();
|
||||
}
|
||||
|
||||
/** Validates API input without changing parsing of previously stored expressions. */
|
||||
public static void validate(String expression) {
|
||||
if (isCronExpression(expression)) {
|
||||
getNextFireTime(expression, ZonedDateTime.now(ZoneOffset.UTC));
|
||||
return;
|
||||
}
|
||||
Rate rate = parseRate(expression);
|
||||
AwsRateExpressions.validate(rate.value(), rate.unit());
|
||||
}
|
||||
|
||||
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) {
|
||||
Rate rate = parseRate(expression);
|
||||
int value = rate.value();
|
||||
return switch (rate.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);
|
||||
default -> throw new IllegalArgumentException("Unknown rate unit: " + rate.unit());
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,6 +85,20 @@ public final class ScheduleExpressionParser {
|
||||
return Math.max(millis, 1000);
|
||||
}
|
||||
|
||||
private static Rate parseRate(String expression) {
|
||||
if (expression == null || expression.isBlank()) {
|
||||
throw new IllegalArgumentException("Schedule expression cannot be null or blank");
|
||||
}
|
||||
Matcher matcher = RATE_PATTERN.matcher(expression.trim());
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalArgumentException("Not a valid rate expression: " + expression);
|
||||
}
|
||||
int value = Integer.parseInt(matcher.group(1));
|
||||
AwsRateExpressions.requirePositiveValue(value);
|
||||
String unit = matcher.group(2).toLowerCase(Locale.ROOT);
|
||||
return new Rate(value, unit);
|
||||
}
|
||||
|
||||
private static String normalizeCronExpression(String cronExpression) {
|
||||
String[] fields = cronExpression.trim().split("\\s+");
|
||||
if (fields.length != 6) {
|
||||
@@ -93,4 +107,6 @@ public final class ScheduleExpressionParser {
|
||||
}
|
||||
return "0 " + cronExpression;
|
||||
}
|
||||
|
||||
private record Rate(int value, String unit) {}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.cronutils.model.Cron;
|
||||
import com.cronutils.model.time.ExecutionTime;
|
||||
import com.cronutils.parser.CronParser;
|
||||
import io.floci.aws.core.common.AwsCronDefinitions;
|
||||
import io.floci.aws.core.common.AwsRateExpressions;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -12,6 +13,7 @@ import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.ResolverStyle;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -37,10 +39,6 @@ public final class SchedulerExpressionParser {
|
||||
"^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?|weeks?)\\s*\\)$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final Pattern AWS_RATE_PATTERN = Pattern.compile(
|
||||
"^rate\\(\\s*(\\d+)\\s+(minutes?|hours?|days?)\\s*\\)$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final Pattern CRON_PATTERN = Pattern.compile(
|
||||
"^cron\\((.+)\\)$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
@@ -71,17 +69,9 @@ public final class SchedulerExpressionParser {
|
||||
switch (classify(expression)) {
|
||||
case AT -> parseAt(expression, timezone);
|
||||
case RATE -> {
|
||||
Matcher rate = AWS_RATE_PATTERN.matcher(expression.trim());
|
||||
if (!rate.matches()) {
|
||||
throw new IllegalArgumentException("Week-based rates are not supported by Scheduler");
|
||||
}
|
||||
parseRateMillis(expression);
|
||||
long value = Long.parseLong(rate.group(1));
|
||||
String unit = rate.group(2);
|
||||
boolean plural = unit.endsWith("s") || unit.endsWith("S");
|
||||
if ((value == 1) == plural) {
|
||||
throw new IllegalArgumentException("Rate unit must be singular for 1 and plural for values greater than 1");
|
||||
}
|
||||
Rate rate = parseRate(expression);
|
||||
AwsRateExpressions.validate(rate.value(), rate.unit());
|
||||
rate.toMillis();
|
||||
}
|
||||
case CRON -> {
|
||||
parseCron(expression);
|
||||
@@ -108,22 +98,17 @@ public final class SchedulerExpressionParser {
|
||||
* Parses a {@code rate(...)} expression and returns the interval in milliseconds.
|
||||
*/
|
||||
public static long parseRateMillis(String expression) {
|
||||
return parseRate(expression).toMillis();
|
||||
}
|
||||
|
||||
private static Rate parseRate(String expression) {
|
||||
Matcher m = RATE_PATTERN.matcher(expression.trim());
|
||||
if (!m.matches()) {
|
||||
throw new IllegalArgumentException("Not a valid rate() expression: " + expression);
|
||||
}
|
||||
long value = Long.parseLong(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" -> Math.multiplyExact(value, 60_000L);
|
||||
case "hour", "hours" -> Math.multiplyExact(value, 3_600_000L);
|
||||
case "day", "days" -> Math.multiplyExact(value, 86_400_000L);
|
||||
case "week", "weeks" -> Math.multiplyExact(value, 604_800_000L);
|
||||
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
|
||||
};
|
||||
AwsRateExpressions.requirePositiveValue(value);
|
||||
return new Rate(value, m.group(2).toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,4 +150,16 @@ public final class SchedulerExpressionParser {
|
||||
}
|
||||
return ZoneId.of(timezone);
|
||||
}
|
||||
|
||||
private record Rate(long value, String unit) {
|
||||
long toMillis() {
|
||||
return switch (unit) {
|
||||
case "minute", "minutes" -> Math.multiplyExact(value, 60_000L);
|
||||
case "hour", "hours" -> Math.multiplyExact(value, 3_600_000L);
|
||||
case "day", "days" -> Math.multiplyExact(value, 86_400_000L);
|
||||
case "week", "weeks" -> Math.multiplyExact(value, 604_800_000L);
|
||||
default -> throw new IllegalArgumentException("Unknown rate unit: " + unit);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.services.eventbridge.ScheduleExpressionParser;
|
||||
import io.floci.aws.services.scheduler.SchedulerExpressionParser;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class AwsRateExpressionValidationTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minute)", "rate(2 minutes)", "rate(1 hour)",
|
||||
"rate(2 hours)", "rate(1 day)", "rate(2 days)", "RATE(1 HOUR)", "rate( 5 minutes )"})
|
||||
void bothServicesAcceptAwsRates(String expression) {
|
||||
assertDoesNotThrow(() -> ScheduleExpressionParser.validate(expression));
|
||||
assertDoesNotThrow(() -> SchedulerExpressionParser.validate(expression, null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minutes)", "rate(2 minute)", "rate(1 hours)",
|
||||
"rate(2 hour)", "rate(1 days)", "rate(2 day)", "rate(0 minutes)", "rate(0 minute)",
|
||||
"rate(1 week)", "rate(2 weeks)", "RATE(1 HOURS)", "RATE(2 WEEK)"})
|
||||
void bothServicesRejectTheSameInvalidRateWithTheSameReason(String expression) {
|
||||
IllegalArgumentException events = assertThrows(IllegalArgumentException.class,
|
||||
() -> ScheduleExpressionParser.validate(expression));
|
||||
IllegalArgumentException scheduler = assertThrows(IllegalArgumentException.class,
|
||||
() -> SchedulerExpressionParser.validate(expression, null));
|
||||
|
||||
assertEquals(events.getMessage(), scheduler.getMessage());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -22,9 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
/**
|
||||
* UpdateStack must leave an unchanged resource alone, whatever its type.
|
||||
*
|
||||
* <p>{@code provision()} re-runs for every resource on every update, changed or not, so a
|
||||
* provisioner that calls create unconditionally either collides with itself (rolling the stack
|
||||
* back) or quietly mints a new physical id, orphaning everything that referenced the old one.
|
||||
* <p>The update engine skips resources outside the change set. Re-provisioning an unchanged
|
||||
* resource could collide with its existing name (rolling the stack back), or quietly mint a new
|
||||
* physical id, orphaning everything that referenced the old one.
|
||||
* Each case here builds a stack holding one resource plus a throwaway queue, updates only the
|
||||
* queue, and asserts both that the stack reached UPDATE_COMPLETE and that the untouched resource
|
||||
* kept its physical id.
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.services.cloudformation.model.Stack;
|
||||
import io.floci.aws.services.eventbridge.EventBridgeService;
|
||||
import io.floci.aws.services.eventbridge.RuleScheduler;
|
||||
import io.floci.aws.services.eventbridge.model.Rule;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.EventBridgeException;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationLegacyScheduleIntegrationTest {
|
||||
|
||||
private static final String STACK_NAME = "legacy-schedule-stack";
|
||||
private static final String RULE_NAME = "legacy-schedule-rule";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
@Inject
|
||||
EventBridgeService eventBridgeService;
|
||||
|
||||
@Inject
|
||||
RuleScheduler scheduler;
|
||||
|
||||
@Test
|
||||
void anUnrelatedStackUpdateKeepsTheLegacyRuleAndItsTimer() {
|
||||
try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, Region.US_EAST_1);
|
||||
EventBridgeClient events = AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, Region.US_EAST_1);
|
||||
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), ACCOUNT, Region.US_EAST_1)) {
|
||||
cfn.createStack(request -> request.stackName(STACK_NAME).templateBody(template("rate(1 minute)", 10)));
|
||||
CfnStackWaits.awaitStatus(STACK_NAME, "CREATE_COMPLETE");
|
||||
try {
|
||||
// Seed state that an older Floci version accepted, without weakening the API validator.
|
||||
String legacyTemplate = template("rate(1 minutes)", 10);
|
||||
Stack stack = cloudFormationService.describeStacks(STACK_NAME, REGION).getFirst();
|
||||
stack.setTemplateBody(legacyTemplate);
|
||||
stack.setOriginalTemplateBody(legacyTemplate);
|
||||
Rule stored = eventBridgeService.describeRule(RULE_NAME, null, REGION);
|
||||
stored.setScheduleExpression("rate(1 minutes)");
|
||||
String originalArn = stored.getArn();
|
||||
assertTrue(scheduler.isRunning(originalArn));
|
||||
|
||||
cfn.updateStack(request -> request.stackName(STACK_NAME).templateBody(template("rate(1 minutes)", 20)));
|
||||
CfnStackWaits.awaitStatus(STACK_NAME, "UPDATE_COMPLETE");
|
||||
|
||||
assertEquals(originalArn, events.describeRule(request -> request.name(RULE_NAME)).arn());
|
||||
assertEquals("rate(1 minutes)", events.describeRule(request -> request.name(RULE_NAME)).scheduleExpression());
|
||||
assertTrue(scheduler.isRunning(originalArn));
|
||||
String queueUrl = cfn.describeStackResource(request -> request.stackName(STACK_NAME)
|
||||
.logicalResourceId("ChurnQueue")).stackResourceDetail().physicalResourceId();
|
||||
assertEquals("20", sqs.getQueueAttributes(request -> request.queueUrl(queueUrl)
|
||||
.attributeNames(QueueAttributeName.VISIBILITY_TIMEOUT)).attributes()
|
||||
.get(QueueAttributeName.VISIBILITY_TIMEOUT));
|
||||
|
||||
EventBridgeException error = assertThrows(EventBridgeException.class,
|
||||
() -> events.putRule(request -> request.name(RULE_NAME).scheduleExpression("rate(1 minutes)")));
|
||||
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
cfn.deleteStack(request -> request.stackName(STACK_NAME));
|
||||
CfnStackWaits.awaitStackDeleted(STACK_NAME);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String template(String expression, int visibilityTimeout) {
|
||||
return """
|
||||
{"Resources": {
|
||||
"ScheduledRule": {"Type": "AWS::Events::Rule", "Properties": {
|
||||
"Name": "%s", "ScheduleExpression": "%s"
|
||||
}},
|
||||
"ChurnQueue": {"Type": "AWS::SQS::Queue", "Properties": {
|
||||
"VisibilityTimeout": %d
|
||||
}}
|
||||
}}
|
||||
""".formatted(RULE_NAME, expression, visibilityTimeout);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package io.floci.aws.services.eventbridge;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
|
||||
import software.amazon.awssdk.services.eventbridge.model.DescribeRuleResponse;
|
||||
import software.amazon.awssdk.services.eventbridge.model.EventBridgeException;
|
||||
import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.eventbridge.model.RuleState;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
class EventBridgeScheduleValidationIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "799600000001";
|
||||
private static final String PATTERN = "{\"source\":[\"schedule.validation\"]}";
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minutes)", "rate(2 minute)", "rate(1 hours)",
|
||||
"rate(2 hour)", "rate(1 days)", "rate(2 day)", "rate(0 minutes)",
|
||||
"rate(-1 minutes)", "rate(1.5 hours)", "rate(1 week)", "rate(2 weeks)",
|
||||
"rate(1 second)", "rate(5)", "rate(999999999999999999999 minutes)",
|
||||
"cron(invalid)", "at(2026-12-01T00:00:00)", "invalid"})
|
||||
void invalidSchedulesAreRejectedBeforeCreatingEvenADisabledRule(String expression) {
|
||||
try (EventBridgeClient client = client()) {
|
||||
EventBridgeException error = assertThrows(EventBridgeException.class, () -> client.putRule(request -> request
|
||||
.name("invalid-schedule").scheduleExpression(expression).state(RuleState.DISABLED)));
|
||||
|
||||
assertValidationError(error);
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.describeRule(request -> request.name("invalid-schedule")));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minute)", "rate(2 minutes)", "rate(1 hour)",
|
||||
"rate(2 hours)", "rate(1 day)", "rate(2 days)", "RATE(2 HOURS)",
|
||||
"rate( 5 minutes )", "cron(0 12 * * ? *)", "cron(0 12 * * ? 2020)"})
|
||||
void validSchedulesRoundTripUnchanged(String expression) {
|
||||
try (EventBridgeClient client = client()) {
|
||||
String name = "valid-schedule";
|
||||
client.putRule(request -> request.name(name).scheduleExpression(expression));
|
||||
try {
|
||||
DescribeRuleResponse rule = client.describeRule(request -> request.name(name));
|
||||
assertEquals(expression, rule.scheduleExpression());
|
||||
assertEquals(RuleState.ENABLED, rule.state());
|
||||
} finally {
|
||||
client.deleteRule(request -> request.name(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minutes)", "rate(2 minute)", "rate(1 hours)",
|
||||
"rate(2 hour)", "rate(1 days)", "rate(2 day)"})
|
||||
void invalidUpdatePreservesTheExistingRule(String expression) {
|
||||
try (EventBridgeClient client = client()) {
|
||||
String name = "preserved-schedule";
|
||||
client.putRule(request -> request.name(name).scheduleExpression("rate(5 minutes)")
|
||||
.eventPattern(PATTERN).description("original"));
|
||||
try {
|
||||
EventBridgeException error = assertThrows(EventBridgeException.class, () -> client.putRule(request -> request
|
||||
.name(name).scheduleExpression(expression).description("changed").state(RuleState.DISABLED)));
|
||||
|
||||
assertValidationError(error);
|
||||
DescribeRuleResponse rule = client.describeRule(request -> request.name(name));
|
||||
assertEquals("rate(5 minutes)", rule.scheduleExpression());
|
||||
assertEquals(PATTERN, rule.eventPattern());
|
||||
assertEquals("original", rule.description());
|
||||
assertEquals(RuleState.ENABLED, rule.state());
|
||||
} finally {
|
||||
client.deleteRule(request -> request.name(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventPatternDoesNotBypassScheduleValidation() {
|
||||
try (EventBridgeClient client = client()) {
|
||||
EventBridgeException error = assertThrows(EventBridgeException.class, () -> client.putRule(request -> request
|
||||
.name("invalid-combined-rule").eventPattern(PATTERN).scheduleExpression("rate(1 minutes)")));
|
||||
|
||||
assertValidationError(error);
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> client.describeRule(request -> request.name("invalid-combined-rule")));
|
||||
}
|
||||
}
|
||||
|
||||
private static EventBridgeClient client() {
|
||||
return AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private static void assertValidationError(EventBridgeException error) {
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
|
||||
assertEquals("Parameter ScheduleExpression is not valid.", error.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
+16
@@ -2,6 +2,7 @@ package io.floci.aws.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
@@ -76,6 +77,21 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
assertTrue(scheduler.isRunning(rule.getArn()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedRateUpdateLeavesTheOriginalTimerRunning() {
|
||||
Rule rule = eventBridgeService.putRule(
|
||||
"preserved-timer", "default", null, "rate(5 minutes)",
|
||||
RuleState.ENABLED, null, null, null, REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> eventBridgeService.putRule(
|
||||
"preserved-timer", "default", null, "rate(1 minutes)",
|
||||
RuleState.DISABLED, null, null, null, REGION));
|
||||
|
||||
assertTrue(scheduler.isRunning(rule.getArn()));
|
||||
assertEquals("rate(5 minutes)", rule.getScheduleExpression());
|
||||
assertEquals(RuleState.ENABLED, rule.getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRuleStopsScheduler() {
|
||||
eventBridgeService.getOrCreateDefaultBus(REGION);
|
||||
|
||||
@@ -450,6 +450,20 @@ class EventBridgeServiceTest {
|
||||
assertEquals("rate(10 minutes)", rules.getFirst().getScheduleExpression());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minutes)", "rate(2 minute)", "rate(1 hours)",
|
||||
"rate(2 hour)", "rate(1 days)", "rate(2 day)"})
|
||||
void putRuleRejectsMismatchedRateUnits(String expression) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.putRule("invalid-rate", null, null, expression, RuleState.ENABLED,
|
||||
null, null, null, REGION));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Parameter ScheduleExpression is not valid.", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertTrue(service.listRules(null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putRuleForNonExistentBusThrows() {
|
||||
assertThrows(AwsException.class, () ->
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package io.floci.aws.services.eventbridge;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.ZonedDateTime;
|
||||
@@ -65,6 +67,15 @@ class ScheduleExpressionParserTest {
|
||||
assertEquals(120000, ScheduleExpressionParser.parseRateToMillis("rate(2 minutes)"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rate(1 minutes)", "rate(2 minute)", "rate(1 hours)",
|
||||
"rate(2 hour)", "rate(1 days)", "rate(2 day)", "rate(1 week)",
|
||||
"rate(2 weeks)", "RATE(1 HOURS)", "RATE(2 WEEK)"})
|
||||
void apiValidationIsStrictWhileStoredRateParsingRemainsTolerant(String expression) {
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleExpressionParser.validate(expression));
|
||||
assertTrue(ScheduleExpressionParser.parseRateToMillis(expression) > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRateRejectsZeroValue() {
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
|
||||
Reference in new issue
Block a user