feat(redshift-serverless): execute scheduled actions on cron and at schedules (#6851)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-28 21:05:15 -04:00
1 parent a950c704c7
commit e820414f22
21 files changed
+1597 -83

No files matched your search

@@ -93,7 +93,8 @@ class RedshiftServerlessAdministrationHandlerTest {
new RedshiftServerlessEndpointAccessService(storageFactory, regionResolver, serverlessService),
customDomains,
new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService),
new RedshiftServerlessScheduledActionService(storageFactory, serverlessService)),
new RedshiftServerlessScheduledActionService(storageFactory, serverlessService,
mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)),
customDomains);
}
@@ -524,7 +525,7 @@ class RedshiftServerlessAdministrationHandlerTest {
}
@Test
void scheduledActionIsStoredAndNeverRun() {
void scheduledActionIsStoredWithItsNextCronInvocation() {
namespace("sched-ns");
long future = Instant.now().plusSeconds(3600).getEpochSecond();
String target = "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"sched-ns\","
@@ -541,7 +542,7 @@ class RedshiftServerlessAdministrationHandlerTest {
assertEquals(7, created.get("targetAction").get("createSnapshot").get("retentionPeriod").intValue());
assertEquals("env", created.get("targetAction").get("createSnapshot").get("tags").get(0).get("key").textValue());
assertEquals("nightly", created.get("scheduledActionDescription").textValue());
assertEquals(0, created.get("nextInvocations").size());
assertEquals(1, created.get("nextInvocations").size());
assertTrue(created.get("scheduledActionUuid").textValue().length() > 8);
assertEquals("ConflictException", errorType("CreateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\","
@@ -696,7 +697,7 @@ class RedshiftServerlessAdministrationHandlerTest {
void aNamespaceRecreatedUnderTheSameNameDoesNotInheritActions() {
namespace("recreate-ns");
ok("CreateScheduledAction", "{\"scheduledActionName\":\"old-action\",\"namespaceName\":\"recreate-ns\","
+ "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":"
+ "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"0 3 * * ? *\"},\"targetAction\":{\"createSnapshot\":"
+ "{\"namespaceName\":\"recreate-ns\",\"snapshotNamePrefix\":\"p\"}}}");
ok("DeleteNamespace", "{\"namespaceName\":\"recreate-ns\"}");
@@ -705,7 +706,7 @@ class RedshiftServerlessAdministrationHandlerTest {
assertEquals("ResourceNotFoundException", errorType("GetScheduledAction",
"{\"scheduledActionName\":\"old-action\"}"));
ok("CreateScheduledAction", "{\"scheduledActionName\":\"old-action\",\"namespaceName\":\"recreate-ns\","
+ "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":"
+ "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"0 3 * * ? *\"},\"targetAction\":{\"createSnapshot\":"
+ "{\"namespaceName\":\"recreate-ns\",\"snapshotNamePrefix\":\"p\"}}}");
}
@@ -724,7 +725,7 @@ class RedshiftServerlessAdministrationHandlerTest {
void scheduledActionUpdateRejectsAPartialTargetAndATagWithoutAKey() {
namespace("partial-ns");
String create = "{\"scheduledActionName\":\"partial-action\",\"namespaceName\":\"partial-ns\",\"roleArn\":\"r\","
+ "\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":"
+ "\"schedule\":{\"cron\":\"0 3 * * ? *\"},\"targetAction\":{\"createSnapshot\":"
+ "{\"namespaceName\":\"partial-ns\",\"snapshotNamePrefix\":\"p\"";
ok("CreateScheduledAction", create + "}}}");
@@ -737,12 +738,12 @@ class RedshiftServerlessAdministrationHandlerTest {
"{\"scheduledActionName\":\"partial-action\",\"schedule\":{}}"));
JsonNode unchanged = ok("UpdateScheduledAction",
"{\"scheduledActionName\":\"partial-action\",\"enabled\":false}").get("scheduledAction");
assertEquals("x", unchanged.get("schedule").get("cron").textValue());
assertEquals("0 3 * * ? *", unchanged.get("schedule").get("cron").textValue());
assertEquals("DISABLED", unchanged.get("state").textValue());
assertEquals("ValidationException", errorType("CreateScheduledAction",
"{\"scheduledActionName\":\"empty-target\",\"namespaceName\":\"partial-ns\",\"roleArn\":\"r\","
+ "\"schedule\":{\"cron\":\"x\"},\"targetAction\":{}}"));
+ "\"schedule\":{\"cron\":\"0 3 * * ? *\"},\"targetAction\":{}}"));
assertEquals("ValidationException", errorType("CreateScheduledAction",
create.replace("partial-action", "tag-action") + ",\"tags\":[{\"value\":\"v\"}]}}}"));
assertEquals("ValidationException", errorType("CreateScheduledAction",
@@ -10,6 +10,7 @@ import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -21,6 +22,7 @@ import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -785,6 +787,43 @@ class RedshiftServerlessIntegrationTest {
call("DeleteScheduledAction", "{\"scheduledActionName\":\"admin-sched\"}").statusCode(200);
}
@Inject
RedshiftServerlessScheduledActionService scheduledActions;
@Test
void scheduledActionTakesItsSnapshotOnASweepAndReportsTheNextInvocation() {
String namespace = "sweep-ns";
call("CreateNamespace", "{\"namespaceName\":\"" + namespace + "\",\"adminUsername\":\"admin\"}")
.statusCode(200);
cleanup.register(() -> call("DeleteNamespace", "{\"namespaceName\":\"" + namespace + "\"}"));
call("CreateScheduledAction", "{\"scheduledActionName\":\"sweep-sched\",\"namespaceName\":\"" + namespace + "\","
+ "\"roleArn\":\"arn:aws:iam::000000000000:role/r\",\"schedule\":{\"cron\":\"0 * * * ? *\"},"
+ "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"" + namespace + "\","
+ "\"snapshotNamePrefix\":\"sweep\",\"retentionPeriod\":3,"
+ "\"tags\":[{\"key\":\"env\",\"value\":\"it\"}]}}}")
.statusCode(200)
.body("scheduledAction.nextInvocations", hasSize(1));
cleanup.register(() -> call("DeleteScheduledAction", "{\"scheduledActionName\":\"sweep-sched\"}"));
call("CreateScheduledAction", "{\"scheduledActionName\":\"too-often\",\"namespaceName\":\"" + namespace + "\","
+ "\"roleArn\":\"arn:aws:iam::000000000000:role/r\",\"schedule\":{\"cron\":\"0,30 * * * ? *\"},"
+ "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"" + namespace + "\","
+ "\"snapshotNamePrefix\":\"p\"}}}")
.statusCode(400)
.body("__type", equalTo("ValidationException"));
Instant tick = Instant.now().plusSeconds(3 * 3600);
scheduledActions.runScheduledActions(tick);
String snapshot = RedshiftServerlessScheduledActionService.snapshotName("sweep",
tick.truncatedTo(ChronoUnit.HOURS));
cleanup.register(() -> call("DeleteSnapshot", "{\"snapshotName\":\"" + snapshot + "\"}"));
call("GetSnapshot", "{\"snapshotName\":\"" + snapshot + "\"}")
.statusCode(200)
.body("snapshot.namespaceName", equalTo(namespace))
.body("snapshot.status", equalTo("AVAILABLE"))
.body("snapshot.snapshotRetentionPeriod", equalTo(3));
}
private static ValidatableResponse call(String action, String body) {
return given()
.header("X-Amz-Target", TARGET_PREFIX + action)
@@ -132,7 +132,8 @@ class RedshiftServerlessJsonHandlerTest {
new RedshiftServerlessEndpointAccessService(storageFactory, regionResolver, service),
customDomains,
new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service),
new RedshiftServerlessScheduledActionService(storageFactory, service)),
new RedshiftServerlessScheduledActionService(storageFactory, service,
mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)),
customDomains);
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
@@ -20,6 +21,8 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -107,9 +110,13 @@ class RedshiftServerlessRuntimeIntegrationTest {
}
private String executeAndWait(String sql) {
return executeAndWait(sql, WORKGROUP);
}
private String executeAndWait(String sql, String workgroup) {
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "%s", "WorkgroupName": "%s", "Database": "dev"}
""".formatted(sql, WORKGROUP)).then().statusCode(200)
""".formatted(sql, workgroup)).then().statusCode(200)
.extract().path("Id");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(250)).until(() -> {
@@ -163,6 +170,42 @@ class RedshiftServerlessRuntimeIntegrationTest {
""".formatted(workgroupArn)).then().statusCode(200);
}
@Inject
RedshiftServerlessScheduledActionService scheduledActions;
@Test
void aScheduledSnapshotCapturesRowsAndRestoresThem() {
executeAndWait("CREATE TABLE sl_scheduled (id int)");
executeAndWait("INSERT INTO sl_scheduled VALUES (1), (2), (3)");
ScheduledAction request = new ScheduledAction();
request.setScheduledActionName("rt-it-sched");
request.setNamespaceName(NAMESPACE);
request.setRoleArn("arn:aws:iam::000000000000:role/r");
request.setScheduleCron("0 * * * ? *");
request.setTargetNamespaceName(NAMESPACE);
request.setSnapshotNamePrefix("rt-sched");
scheduledActions.createScheduledAction(request, REGION);
Instant tick = Instant.now().truncatedTo(ChronoUnit.HOURS).plus(Duration.ofHours(3)).plus(Duration.ofMinutes(15));
String snapshot = RedshiftServerlessScheduledActionService.snapshotName("rt-sched",
tick.truncatedTo(ChronoUnit.HOURS));
try {
scheduledActions.runScheduledActions(tick);
executeAndWait("DROP TABLE sl_scheduled");
RestAssuredJsonUtils.awsAction("RedshiftServerless", "RestoreFromSnapshot", """
{"namespaceName":"%s","workgroupName":"%s","snapshotName":"%s"}
""".formatted(NAMESPACE, WORKGROUP, snapshot)).then().statusCode(200);
String id = executeAndWait("SELECT count(*) FROM sl_scheduled", WORKGROUP);
ExtractableResponse<Response> result = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract();
assertEquals(3, ((Number) result.path("Records[0][0].longValue")).intValue());
} finally {
scheduledActions.deleteScheduledAction("rt-it-sched", REGION);
service.deleteSnapshot(snapshot, REGION);
executeAndWait("DROP TABLE IF EXISTS sl_scheduled");
}
}
@Test
void theDataApiRejectsAWrongDatabaseAndBothIdentifiers() {
RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
@@ -0,0 +1,75 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.*;
class RedshiftServerlessScheduleTest {
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
@Test
void cronComputesNextAndLatestInUtc() {
ScheduledAction action = cron("(0 3 ? * MON *)");
RedshiftServerlessSchedule.validate(action);
assertEquals(NOW.plusSeconds(3600), RedshiftServerlessSchedule.next(action, NOW).orElseThrow());
assertEquals(NOW.plusSeconds(3600),
RedshiftServerlessSchedule.latestDue(action, NOW, NOW.plusSeconds(7200)).orElseThrow());
assertTrue(RedshiftServerlessSchedule.latestDue(action, NOW, NOW).isEmpty());
}
@Test
void numericWeekdayUsesAwsNumbering() {
assertEquals(NOW.plusSeconds(3600),
RedshiftServerlessSchedule.next(cron("0 3 ? * 2 *"), NOW).orElseThrow());
}
@Test
void supportsExistingCronWrapper() {
assertEquals(NOW.plusSeconds(3600),
RedshiftServerlessSchedule.next(cron("cron(0 3 ? * MON *)"), NOW).orElseThrow());
}
@Test
void rejectsInvalidAndSubHourlyCron() {
for (String expression : new String[]{"x", "* * *", "0 3 * * * *", "0,30 * * * ? *"}) {
assertThrows(AwsException.class, () -> RedshiftServerlessSchedule.validate(cron(expression)), expression);
}
}
@Test
void activeWindowBoundsNextAndDue() {
ScheduledAction action = cron("0 * * * ? *");
action.setStartTime(NOW.plusSeconds(7200));
action.setEndTime(NOW.plusSeconds(10800));
assertEquals(action.getStartTime(), RedshiftServerlessSchedule.next(action, NOW).orElseThrow());
assertEquals(action.getEndTime(),
RedshiftServerlessSchedule.latestDue(action, NOW, NOW.plusSeconds(14400)).orElseThrow());
assertTrue(RedshiftServerlessSchedule.next(action, action.getEndTime()).isEmpty());
action.setEnabled(false);
assertTrue(RedshiftServerlessSchedule.next(action, NOW).isEmpty());
assertTrue(RedshiftServerlessSchedule.latestDue(action, NOW, NOW.plusSeconds(14400)).isEmpty());
}
@Test
void oneOffIsDueOnlyOnceAndWithinWindow() {
ScheduledAction action = new ScheduledAction();
action.setScheduleAt(NOW.plusSeconds(10));
RedshiftServerlessSchedule.validate(action);
assertEquals(action.getScheduleAt(), RedshiftServerlessSchedule.next(action, NOW).orElseThrow());
assertEquals(action.getScheduleAt(),
RedshiftServerlessSchedule.latestDue(action, NOW, NOW.plusSeconds(10)).orElseThrow());
assertTrue(RedshiftServerlessSchedule.latestDue(action, action.getScheduleAt(), NOW.plusSeconds(20)).isEmpty());
action.setEndTime(NOW.plusSeconds(9));
assertTrue(RedshiftServerlessSchedule.next(action, NOW).isEmpty());
}
private ScheduledAction cron(String expression) {
ScheduledAction action = new ScheduledAction();
action.setScheduleCron(expression);
return action;
}
}
@@ -0,0 +1,177 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftServerlessScheduledActionAuthorizerTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
private static final String TARGET = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":namespace/ns-id";
private static final String TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"scheduler.redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String ALLOW = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"redshift-serverless:CreateSnapshot","Resource":"*"}]}""";
private EmulatorConfig config;
private IamService iamService;
private Instance<ScpProvider> scpProvider;
private ScpProvider scps;
private RedshiftServerlessScheduledActionAuthorizer authorizer;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().iam().enforcementEnabled()).thenReturn(true);
iamService = mock(IamService.class);
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
scpProvider = mock(Instance.class);
scps = mock(ScpProvider.class);
when(scpProvider.isResolvable()).thenReturn(true);
when(scpProvider.get()).thenReturn(scps);
authorizer = new RedshiftServerlessScheduledActionAuthorizer(config, iamService, evaluator,
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
}
private void role(String arn, String trust, String policy) {
IamRole role = new IamRole("id", "scheduler", "/", arn, trust);
when(iamService.findRole(ACCOUNT_ID, "scheduler")).thenReturn(Optional.of(role));
when(iamService.resolvePrincipalContext(arn)).thenReturn(CallerContext.of(List.of(policy)));
}
@Test
void trustedRoleWithThePermissionIsAllowed() {
role(ROLE_ARN, TRUST, ALLOW);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isEmpty());
}
@Test
void roleInAnotherPartitionOfTheSameAccountIsEvaluatedAsItsOwn() {
String chinaRole = "arn:aws-cn:iam::" + ACCOUNT_ID + ":role/scheduler";
role(chinaRole, TRUST, ALLOW);
assertTrue(authorizer.refusal(chinaRole, ACCOUNT_ID,
"arn:aws-cn:redshift-serverless:cn-north-1:" + ACCOUNT_ID + ":namespace/ns-id").isEmpty());
}
@Test
void serviceControlPolicyDenyIsRefused() {
role(ROLE_ARN, TRUST, ALLOW);
when(scps.effectiveScpLevels(ACCOUNT_ID)).thenReturn(List.of(List.of("""
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
"Action":"redshift-serverless:CreateSnapshot","Resource":"*"}]}""")));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void serviceControlPolicyThatAllowsLeavesTheRoleAllowed() {
role(ROLE_ARN, TRUST, ALLOW);
when(scps.effectiveScpLevels(ACCOUNT_ID)).thenReturn(List.of(List.of("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}""")));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isEmpty());
}
@Test
void trustPolicyWithMatchingSourceAccountConditionIsAllowed() {
String conditionalTrust = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"scheduler.redshift.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"aws:SourceAccount":"%s"}}}]}""".formatted(ACCOUNT_ID);
role(ROLE_ARN, conditionalTrust, ALLOW);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isEmpty());
}
@Test
void trustPolicyWithMismatchedSourceAccountConditionIsRefused() {
String conditionalTrust = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"scheduler.redshift.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"aws:SourceAccount":"999999999999"}}}]}""";
role(ROLE_ARN, conditionalTrust, ALLOW);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void regionalConditionMatchingTargetRegionIsAllowed() {
String regionalPolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"redshift-serverless:CreateSnapshot","Resource":"*",
"Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}}]}""";
role(ROLE_ARN, TRUST, regionalPolicy);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isEmpty());
}
@Test
void regionalConditionForDifferentRegionIsRefused() {
String regionalPolicy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"redshift-serverless:CreateSnapshot","Resource":"*",
"Condition":{"StringEquals":{"aws:RequestedRegion":"us-west-2"}}}]}""";
role(ROLE_ARN, TRUST, regionalPolicy);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void missingPermissionIsRefused() {
role(ROLE_ARN, TRUST, ALLOW.replace("CreateSnapshot", "GetSnapshot"));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void explicitDenyIsRefused() {
role(ROLE_ARN, TRUST, ALLOW.replace("\"Allow\"", "\"Deny\""));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void roleThatDoesNotTrustTheSchedulerIsRefused() {
role(ROLE_ARN, TRUST.replace("scheduler.redshift", "lambda"), ALLOW);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void missingRoleIsRefused() {
when(iamService.findRole(ACCOUNT_ID, "scheduler")).thenReturn(Optional.empty());
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, TARGET).isPresent());
}
@Test
void roleOfAnotherAccountIsRefusedWithoutLookingItUp() {
Optional<String> refusal = authorizer.refusal("arn:aws:iam::210987654321:role/scheduler", ACCOUNT_ID, TARGET);
assertTrue(refusal.isPresent());
verify(iamService, never()).findRole(anyString(), anyString());
}
@Test
void nonRoleArnIsRefused() {
assertTrue(authorizer.refusal("arn:aws:iam::" + ACCOUNT_ID + ":user/someone", ACCOUNT_ID, TARGET).isPresent());
assertTrue(authorizer.refusal("not-an-arn", ACCOUNT_ID, TARGET).isPresent());
}
@Test
void enforcementOffAllowsEverything() {
when(config.services().iam().enforcementEnabled()).thenReturn(false);
assertTrue(authorizer.refusal("not-an-arn", ACCOUNT_ID, TARGET).isEmpty());
}
}
@@ -0,0 +1,148 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.HybridStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class RedshiftServerlessScheduledActionRecoveryTest {
private static final String ACCOUNT = "123456789012";
private static final String REGION = "us-east-1";
private static final Instant CREATED = Instant.parse("2026-10-28T12:15:00Z");
private static final Instant DUE = Instant.parse("2026-10-28T13:00:00Z");
private static final String SNAPSHOT_NAME = "nightly-2026-10-28-13-00-00";
@TempDir
Path directory;
private final List<HybridStorage<String, ScheduledAction>> backends = new ArrayList<>();
private StorageFactory factory;
private RegionResolver regions;
private RedshiftServerlessService serverless;
private AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots;
private RedshiftServerlessScheduledActionService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
factory = mock(StorageFactory.class);
when(factory.create(anyString(), anyString(), any(TypeReference.class)))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
AccountAwareStorageBackend<Namespace> namespaces = AccountAwareStorageBackend.inMemory(ACCOUNT);
Namespace namespace = new Namespace();
namespace.setNamespaceName("source-ns");
namespace.setNamespaceId("ns-id");
namespace.setNamespaceArn("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT + ":namespace/ns-id");
namespaces.put(REGION + "::source-ns", namespace);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"), any(TypeReference.class)))
.thenReturn((AccountAwareStorageBackend) namespaces);
snapshots = AccountAwareStorageBackend.inMemory(ACCOUNT);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"), any(TypeReference.class)))
.thenReturn((AccountAwareStorageBackend) snapshots);
regions = mock(RegionResolver.class);
when(regions.getAccountId()).thenReturn(ACCOUNT);
serverless = spy(new RedshiftServerlessService(factory, regions, mock(RedshiftServerlessEndpoints.class),
mock(RedshiftServerlessRuntime.class), mock(EmulatorConfig.class)));
service = reload();
ScheduledAction action = new ScheduledAction();
action.setScheduledActionName("hourly");
action.setNamespaceName("source-ns");
action.setRoleArn("arn:aws:iam::" + ACCOUNT + ":role/scheduler");
action.setScheduleCron("0 * * * ? *");
action.setTargetNamespaceName("source-ns");
action.setSnapshotNamePrefix("nightly");
service.createScheduledAction(action, REGION);
backends.getFirst().flush();
}
@AfterEach
void stopBackends() {
backends.forEach(HybridStorage::shutdown);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private RedshiftServerlessScheduledActionService reload() {
HybridStorage<String, ScheduledAction> backend = new HybridStorage<>(directory.resolve("actions.json"),
new TypeReference<Map<String, ScheduledAction>>() {}, 600_000);
backends.add(backend);
backend.load();
AccountAwareStorageBackend<ScheduledAction> actions = new AccountAwareStorageBackend<>(backend, null, ACCOUNT);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-scheduledactions.json"), any(TypeReference.class)))
.thenReturn((AccountAwareStorageBackend) actions);
return new RedshiftServerlessScheduledActionService(factory, serverless,
mock(RedshiftServerlessScheduledActionAuthorizer.class), regions, Clock.fixed(CREATED, ZoneOffset.UTC));
}
@Test
void crashBeforeSnapshotRetriesAfterHybridReloadEvenIfAFlushRanDuringTheAttempt() {
doAnswer(invocation -> {
backends.getFirst().flush();
throw new AssertionError("simulated process crash before snapshot creation");
}).when(serverless).createSnapshot(anyString(), anyString(), any(), any(), anyString());
assertThrows(AssertionError.class, () -> service.runScheduledActions(DUE));
RedshiftServerlessScheduledActionService restarted = reload();
assertNull(restarted.getScheduledAction("hourly", REGION).getLastClaimedInvocation());
doCallRealMethod().when(serverless).createSnapshot(anyString(), anyString(), any(), any(), anyString());
restarted.runScheduledActions(DUE.plusSeconds(60));
assertEquals(1, snapshots.scan(key -> true).size());
assertEquals(SNAPSHOT_NAME, snapshots.scan(key -> true).getFirst().getSnapshotName());
assertEquals(DUE, restarted.getScheduledAction("hourly", REGION).getLastCompletedInvocation());
}
@Test
void crashAfterSnapshotRetriesTheSameNameWithoutCreatingADuplicate() {
doAnswer(invocation -> {
invocation.callRealMethod();
throw new AssertionError("simulated process crash after snapshot creation");
}).when(serverless).createSnapshot(anyString(), anyString(), any(), any(), anyString());
assertThrows(AssertionError.class, () -> service.runScheduledActions(DUE));
RedshiftServerlessScheduledActionService restarted = reload();
assertNull(restarted.getScheduledAction("hourly", REGION).getLastClaimedInvocation());
doCallRealMethod().when(serverless).createSnapshot(anyString(), anyString(), any(), any(), anyString());
restarted.runScheduledActions(DUE.plusSeconds(60));
restarted.runScheduledActions(DUE.plusSeconds(120));
assertEquals(1, snapshots.scan(key -> true).size());
verify(serverless, times(2)).createSnapshot(eq(SNAPSHOT_NAME), eq("source-ns"), any(), any(), eq(REGION));
assertEquals(DUE, restarted.getScheduledAction("hourly", REGION).getLastClaimedInvocation());
assertTrue(restarted.getScheduledAction("hourly", REGION).getLastFailure().contains("already exists"));
}
@Test
void completedCheckpointSurvivesHybridFlushAndReload() {
service.runScheduledActions(DUE);
backends.getFirst().flush();
RedshiftServerlessScheduledActionService restarted = reload();
restarted.runScheduledActions(DUE.plusSeconds(60));
assertEquals(DUE, restarted.getScheduledAction("hourly", REGION).getLastCompletedInvocation());
verify(serverless).createSnapshot(eq(SNAPSHOT_NAME), eq("source-ns"), any(), any(), eq(REGION));
assertEquals(1, snapshots.scan(key -> true).size());
}
}
@@ -0,0 +1,115 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftServerlessScheduledActionSchedulerTest {
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
private final RedshiftServerlessScheduledActionService service = mock(RedshiftServerlessScheduledActionService.class);
private RedshiftServerlessScheduledActionScheduler scheduler(boolean serviceEnabled, boolean actionsEnabled) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().redshiftServerless().enabled()).thenReturn(serviceEnabled);
when(config.services().redshiftServerless().scheduledActionsEnabled()).thenReturn(actionsEnabled);
when(config.services().redshiftServerless().scheduledActionSweepIntervalSeconds()).thenReturn(60);
return new RedshiftServerlessScheduledActionScheduler(service, config);
}
@Test
void workerExistsOnlyWhenTheServiceAndTheSwitchAreBothOn() {
assertTrue(scheduler(true, true).active());
assertFalse(scheduler(true, false).active());
assertFalse(scheduler(false, true).active());
}
@Test
void tickRunsTheSweepAtTheGivenInstant() {
scheduler(true, false).tick(NOW);
verify(service).runScheduledActions(NOW);
}
@Test
void resetDrainsARunningSweepAndPausesUntilItEnds() throws Exception {
RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false);
CountDownLatch running = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
running.countDown();
release.await(10, TimeUnit.SECONDS);
return null;
}).when(service).runScheduledActions(NOW);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> sweep = executor.submit(() -> scheduler.tick(NOW));
assertTrue(running.await(5, TimeUnit.SECONDS));
Future<?> reset = executor.submit(scheduler::beforeReset);
assertThrows(TimeoutException.class, () -> reset.get(300, TimeUnit.MILLISECONDS));
release.countDown();
reset.get(5, TimeUnit.SECONDS);
sweep.get(5, TimeUnit.SECONDS);
scheduler.tick(NOW.plusSeconds(60));
verify(service, never()).runScheduledActions(NOW.plusSeconds(60));
scheduler.afterReset();
scheduler.tick(NOW.plusSeconds(120));
verify(service).runScheduledActions(NOW.plusSeconds(120));
} finally {
release.countDown();
executor.shutdownNow();
}
}
@Test
void overlappingTicksNeverRunTheSweepConcurrently() throws Exception {
RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false);
AtomicInteger concurrent = new AtomicInteger();
AtomicInteger peak = new AtomicInteger();
doAnswer(invocation -> {
peak.accumulateAndGet(concurrent.incrementAndGet(), Math::max);
Thread.sleep(100);
concurrent.decrementAndGet();
return null;
}).when(service).runScheduledActions(NOW);
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
Future<?> first = executor.submit(() -> scheduler.tick(NOW));
Future<?> second = executor.submit(() -> scheduler.tick(NOW));
Future<?> third = executor.submit(() -> scheduler.tick(NOW));
first.get(5, TimeUnit.SECONDS);
second.get(5, TimeUnit.SECONDS);
third.get(5, TimeUnit.SECONDS);
} finally {
executor.shutdownNow();
}
assertEquals(1, peak.get());
}
@Test
void aFailedSweepReleasesTheLock() {
RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false);
doThrow(new IllegalStateException("boom")).when(service).runScheduledActions(NOW);
assertThrows(IllegalStateException.class, () -> scheduler.tick(NOW));
scheduler.tick(NOW.plusSeconds(60));
verify(service).runScheduledActions(NOW.plusSeconds(60));
}
}
@@ -0,0 +1,354 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftServerlessScheduledActionServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "123456789012";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/scheduler";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":namespace/ns-id";
private static final Instant BASE_TIME = Instant.parse("2026-10-28T12:15:00Z");
private final AtomicBoolean failCheckpointWrites = new AtomicBoolean();
private AccountAwareStorageBackend<ScheduledAction> store;
private StorageFactory storageFactory;
private RedshiftServerlessService serverless;
private RedshiftServerlessScheduledActionAuthorizer authorizer;
private RegionResolver regionResolver;
private String namespaceId;
private Clock clock;
private RedshiftServerlessScheduledActionService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
namespaceId = "ns-id";
clock = Clock.fixed(BASE_TIME, ZoneOffset.UTC);
store = new AccountAwareStorageBackend<>(new InMemoryStorage<String, ScheduledAction>() {
@Override
public synchronized void putAllAtomically(Map<String, ScheduledAction> entries) {
if (failCheckpointWrites.get()) {
throw new UncheckedIOException(new IOException("disk full"));
}
super.putAllAtomically(entries);
}
}, null, ACCOUNT_ID);
storageFactory = mock(StorageFactory.class);
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-scheduledactions.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
serverless = mock(RedshiftServerlessService.class);
when(serverless.namespaceExists(anyString(), eq(REGION))).thenReturn(true);
when(serverless.findNamespace(anyString(), eq(REGION))).thenAnswer(invocation -> Optional.of(namespace()));
authorizer = mock(RedshiftServerlessScheduledActionAuthorizer.class);
regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
service = newService();
}
private RedshiftServerlessScheduledActionService newService() {
return new RedshiftServerlessScheduledActionService(storageFactory, serverless, authorizer, regionResolver, clock);
}
private Namespace namespace() {
Namespace namespace = new Namespace();
namespace.setNamespaceId(namespaceId);
namespace.setNamespaceArn(NAMESPACE_ARN);
return namespace;
}
private ScheduledAction request(String name) {
ScheduledAction request = new ScheduledAction();
request.setScheduledActionName(name);
request.setNamespaceName("source-ns");
request.setRoleArn(ROLE_ARN);
request.setScheduleCron("0 * * * ? *");
request.setTargetNamespaceName("source-ns");
request.setSnapshotNamePrefix("Nightly");
request.setRetentionPeriod(7);
Map<String, String> tags = new LinkedHashMap<>();
tags.put("env", "dev");
request.setSnapshotTags(tags);
return request;
}
private static Instant later() {
return BASE_TIME.plus(Duration.ofHours(3));
}
private static String expectedName(Instant tick) {
return RedshiftServerlessScheduledActionService.snapshotName("nightly", tick.truncatedTo(ChronoUnit.HOURS));
}
@Test
void cronActionTakesTheLatestDueSnapshotOnceWithItsArguments() {
service.createScheduledAction(request("hourly"), REGION);
Instant tick = later();
service.runScheduledActions(tick);
service.runScheduledActions(tick.plusSeconds(60));
Map<String, String> tags = new LinkedHashMap<>();
tags.put("env", "dev");
verify(serverless, times(1)).createSnapshot(expectedName(tick), "source-ns", 7, tags, REGION);
assertEquals(tick.truncatedTo(ChronoUnit.HOURS),
store.getForAccount(ACCOUNT_ID, "us-east-1::hourly").orElseThrow().getLastCompletedInvocation());
}
@Test
void missedInvocationsAreCoalescedIntoTheLatestOne() {
service.createScheduledAction(request("hourly"), REGION);
service.runScheduledActions(BASE_TIME.plus(Duration.ofHours(30)));
verify(serverless, times(1)).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void oneOffActionRunsOnceAtItsTime() {
ScheduledAction oneOff = request("once");
oneOff.setScheduleCron(null);
Instant at = BASE_TIME.plusSeconds(600);
oneOff.setScheduleAt(at);
service.createScheduledAction(oneOff, REGION);
service.runScheduledActions(at.minusSeconds(1));
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
service.runScheduledActions(at.plusSeconds(5));
service.runScheduledActions(at.plusSeconds(3600));
verify(serverless, times(1)).createSnapshot(eq(RedshiftServerlessScheduledActionService.snapshotName("nightly", at)),
eq("source-ns"), eq(7), any(), eq(REGION));
}
@Test
void activeWindowAndDisabledActionsDoNotRun() {
ScheduledAction early = request("windowed");
early.setStartTime(BASE_TIME.plus(Duration.ofHours(10)));
service.createScheduledAction(early, REGION);
ScheduledAction disabled = request("off");
disabled.setEnabled(false);
service.createScheduledAction(disabled, REGION);
service.runScheduledActions(later());
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void enablingDoesNotReplayWhatWasMissedWhileDisabled() {
ScheduledAction disabled = request("off");
disabled.setEnabled(false);
service.createScheduledAction(disabled, REGION);
ScheduledAction enable = new ScheduledAction();
enable.setScheduledActionName("off");
enable.setEnabled(true);
service.updateScheduledAction(enable, REGION);
service.runScheduledActions(BASE_TIME.plusSeconds(60));
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void storedActionWithoutACheckpointStartsCountingWithoutReplay() {
ScheduledAction legacy = new ScheduledAction(request("legacy"));
legacy.setScheduledActionUuid("u-1");
legacy.setOwnerId(namespaceId);
legacy.setEnabled(true);
store.put("us-east-1::legacy", legacy);
Instant tick = later();
service.runScheduledActions(tick);
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
service.runScheduledActions(tick.plus(Duration.ofHours(2)));
verify(serverless, times(1)).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void oneFailingActionDoesNotStopOthersAndIsNotRetried() {
service.createScheduledAction(request("a-failing"), REGION);
ScheduledAction other = request("b-healthy");
other.setSnapshotNamePrefix("healthy");
service.createScheduledAction(other, REGION);
Instant tick = later();
when(serverless.createSnapshot(anyString(), anyString(), any(), any(), anyString())).thenAnswer(invocation -> {
if (invocation.getArgument(0, String.class).startsWith("nightly")) {
throw ServerlessSupport.conflict("exists");
}
return null;
});
service.runScheduledActions(tick);
service.runScheduledActions(tick.plusSeconds(30));
verify(serverless, times(1)).createSnapshot(startsWith("nightly"), anyString(), any(), any(), anyString());
verify(serverless, times(1)).createSnapshot(startsWith("healthy"), anyString(), any(), any(), anyString());
assertNotNull(store.getForAccount(ACCOUNT_ID, "us-east-1::a-failing").orElseThrow().getLastFailure());
}
@Test
void failedCheckpointLeavesTheInvocationEligibleForRetry() {
service.createScheduledAction(request("hourly"), REGION);
failCheckpointWrites.set(true);
service.runScheduledActions(later());
assertNull(store.getForAccount(ACCOUNT_ID, "us-east-1::hourly").orElseThrow().getLastClaimedInvocation());
failCheckpointWrites.set(false);
service.runScheduledActions(later().plusSeconds(60));
verify(serverless, times(2)).createSnapshot(eq(expectedName(later())), anyString(), any(), any(), eq(REGION));
assertEquals(later().truncatedTo(ChronoUnit.HOURS),
store.getForAccount(ACCOUNT_ID, "us-east-1::hourly").orElseThrow().getLastCompletedInvocation());
}
@Test
void claimedInvocationIsNotRepeatedAfterRestart() {
service.createScheduledAction(request("hourly"), REGION);
Instant tick = later();
service.runScheduledActions(tick);
RedshiftServerlessScheduledActionService restarted = newService();
restarted.runScheduledActions(tick.plusSeconds(60));
verify(serverless, times(1)).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void recreatedNamespaceInvalidatesTheOldAction() {
service.createScheduledAction(request("hourly"), REGION);
namespaceId = "ns-id-2";
service.runScheduledActions(later());
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
assertTrue(store.getForAccount(ACCOUNT_ID, "us-east-1::hourly").isEmpty());
}
@Test
void deniedRoleTakesNoSnapshotAndIsNotRetried() {
service.createScheduledAction(request("hourly"), REGION);
when(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, NAMESPACE_ARN)).thenReturn(Optional.of("denied"));
Instant tick = later();
service.runScheduledActions(tick);
service.runScheduledActions(tick.plusSeconds(60));
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
verify(authorizer, times(1)).refusal(ROLE_ARN, ACCOUNT_ID, NAMESPACE_ARN);
assertEquals("denied", store.getForAccount(ACCOUNT_ID, "us-east-1::hourly").orElseThrow().getLastFailure());
}
@Test
void anotherAccountsActionIsAuthorizedAsItsOwnAccount() {
ScheduledAction foreign = new ScheduledAction(request("foreign"));
foreign.setScheduledActionUuid("u-2");
foreign.setOwnerId(namespaceId);
foreign.setEnabled(true);
foreign.setRoleArn("arn:aws:iam::210987654321:role/scheduler");
foreign.setActivatedAt(BASE_TIME);
store.putAllAtomicallyForAccount("210987654321", Map.of("us-east-1::foreign", foreign));
when(authorizer.refusal(anyString(), eq("210987654321"), anyString())).thenReturn(Optional.of("denied"));
service.runScheduledActions(later());
verify(authorizer).refusal(eq("arn:aws:iam::210987654321:role/scheduler"), eq("210987654321"), anyString());
verify(serverless, never()).createSnapshot(anyString(), anyString(), any(), any(), anyString());
}
@Test
void readsAndMutationsOfOtherActionsAreNotBlockedByARunningDump() throws Exception {
service.createScheduledAction(request("hourly"), REGION);
ScheduledAction other = request("other");
other.setScheduleCron("0 0 1 1 ? *");
service.createScheduledAction(other, REGION);
CountDownLatch dumping = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(serverless.createSnapshot(anyString(), anyString(), any(), any(), anyString())).thenAnswer(invocation -> {
dumping.countDown();
release.await(10, TimeUnit.SECONDS);
return null;
});
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> sweep = executor.submit(() -> service.runScheduledActions(later()));
assertTrue(dumping.await(5, TimeUnit.SECONDS));
Future<ScheduledAction> read = executor.submit(() -> service.getScheduledAction("hourly", REGION));
Future<ScheduledAction> mutation = executor.submit(() -> {
ScheduledAction change = new ScheduledAction();
change.setScheduledActionName("other");
change.setDescription("changed");
return service.updateScheduledAction(change, REGION);
});
assertEquals("hourly", read.get(5, TimeUnit.SECONDS).getScheduledActionName());
assertEquals("changed", mutation.get(5, TimeUnit.SECONDS).getDescription());
release.countDown();
sweep.get(5, TimeUnit.SECONDS);
} finally {
release.countDown();
executor.shutdownNow();
}
}
@Test
void snapshotNameStaysWithinTheNamingRules() {
String name = RedshiftServerlessScheduledActionService.snapshotName("Nightly", Instant.parse("2030-01-07T03:00:00Z"));
assertEquals("nightly-2030-01-07-03-00-00", name);
assertTrue(RedshiftServerlessScheduledActionService.snapshotName("a".repeat(400), BASE_TIME).length() <= 255);
}
@Test
void unusableSnapshotNamePrefixIsRejectedOnCreate() {
ScheduledAction invalid = request("invalid-prefix");
invalid.setSnapshotNamePrefix("nightly_backup");
assertThrows(AwsException.class, () -> service.createScheduledAction(invalid, REGION));
}
@Test
void unusableSnapshotNamePrefixIsRejectedOnUpdate() {
service.createScheduledAction(request("valid-prefix"), REGION);
ScheduledAction update = new ScheduledAction();
update.setScheduledActionName("valid-prefix");
update.setSnapshotNamePrefix("nightly_backup");
assertThrows(AwsException.class, () -> service.updateScheduledAction(update, REGION));
}
}