diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java index dfad634789..0df0d3df14 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java @@ -9,15 +9,19 @@ import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementRespon import software.amazon.awssdk.services.redshiftdata.model.StatusString; import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient; import software.amazon.awssdk.services.redshiftserverless.model.ConflictException; +import software.amazon.awssdk.services.redshiftserverless.model.CreateSnapshotScheduleActionParameters; import software.amazon.awssdk.services.redshiftserverless.model.EndpointAccess; import software.amazon.awssdk.services.redshiftserverless.model.GetCredentialsResponse; import software.amazon.awssdk.services.redshiftserverless.model.InvalidPaginationException; import software.amazon.awssdk.services.redshiftserverless.model.Namespace; import software.amazon.awssdk.services.redshiftserverless.model.NamespaceStatus; import software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException; +import software.amazon.awssdk.services.redshiftserverless.model.Schedule; +import software.amazon.awssdk.services.redshiftserverless.model.ScheduledActionResponse; import software.amazon.awssdk.services.redshiftserverless.model.ServerlessTrack; import software.amazon.awssdk.services.redshiftserverless.model.Snapshot; import software.amazon.awssdk.services.redshiftserverless.model.Tag; +import software.amazon.awssdk.services.redshiftserverless.model.TargetAction; import software.amazon.awssdk.services.redshiftserverless.model.UsageLimit; import software.amazon.awssdk.services.redshiftserverless.model.UsageLimitBreachAction; import software.amazon.awssdk.services.redshiftserverless.model.UsageLimitPeriod; @@ -424,6 +428,31 @@ class RedshiftServerlessTest { } } + @Test + void scheduledActionUsesAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Creates resources and asserts emulator-local behavior"); + + try (RedshiftServerlessClient client = TestFixtures.redshiftServerlessClient()) { + String namespaceName = "floci-compat-sched-ns"; + try { + client.createNamespace(request -> request.namespaceName(namespaceName).adminUsername("admin") + .adminUserPassword("Secret123!")); + + ScheduledActionResponse action = client.createScheduledAction(request -> request + .scheduledActionName("floci-compat-sched").namespaceName(namespaceName) + .roleArn("arn:aws:iam::000000000000:role/r") + .schedule(Schedule.builder().cron("cron(0 3 * * ? *)").build()) + .targetAction(TargetAction.builder().createSnapshot(CreateSnapshotScheduleActionParameters + .builder().namespaceName(namespaceName).snapshotNamePrefix("nightly").build()) + .build())).scheduledAction(); + assertThat(action.state().toString()).isEqualTo("ACTIVE"); + assertThat(action.schedule().cron()).isEqualTo("cron(0 3 * * ? *)"); + client.deleteScheduledAction(request -> request.scheduledActionName("floci-compat-sched")); + } finally { + deleteBestEffort(client, namespaceName); + } + } + } private static void deleteSnapshotBestEffort(RedshiftServerlessClient client, String snapshotName) { try { client.deleteSnapshot(request -> request.snapshotName(snapshotName)); diff --git a/docs/services/index.md b/docs/services/index.md index fcfd62ebd6..54343587f5 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -77,7 +77,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | | [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 43 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 | -| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 50 | +| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 37 | | [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 10 | | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.md index 59716ba24a..794dd83a81 100644 --- a/docs/services/redshift-serverless.md +++ b/docs/services/redshift-serverless.md @@ -62,6 +62,11 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h | `ListSnapshotCopyConfigurations` | Page through the snapshot copy configurations, filtered by `namespaceName` | | `UpdateSnapshotCopyConfiguration` | Change the `snapshotRetentionPeriod` of a snapshot copy configuration | | `DeleteSnapshotCopyConfiguration` | Remove a snapshot copy configuration and return it | +| `CreateScheduledAction` | Record a scheduled `createSnapshot` action; it is stored, never run | +| `GetScheduledAction` | Return a scheduled action by name | +| `ListScheduledActions` | Page through the scheduled actions, filtered by `namespaceName` | +| `UpdateScheduledAction` | Apply the supplied members to a scheduled action; `schedule` and `targetAction` replace the stored ones | +| `DeleteScheduledAction` | Remove a scheduled action and return it | Namespace and workgroup state is account and Region scoped and persisted through `StorageFactory`. @@ -140,3 +145,4 @@ aws redshift-serverless delete-namespace --namespace-name analytics - **Endpoint access is recorded, not acted on.** An endpoint is stored per account and Region, echoed in the shape of the API model, and dropped on read once its workgroup is gone; a workgroup recreated under the same name is a different workgroup and does not inherit it. `CreateEndpointAccess` creates no VPC endpoint. `address` and `port` are the workgroup's own, so a client can connect; `vpcEndpoint` carries a generated id and one network interface per subnet, without a `vpcId`, and `ListEndpointAccess` with a `vpcId` returns nothing. `vpcSecurityGroupIds` is optional. Endpoint names are 1 to 30 letters, digits or hyphens, start with a letter, and contain no consecutive or trailing hyphens. Security groups are the only member `UpdateEndpointAccess` changes. - **Custom domain associations are recorded, not acted on.** An association is stored per account and Region and dropped on read once its workgroup is gone; a workgroup recreated under the same name does not inherit it. A workgroup has at most one custom domain association. The certificate expiry time comes from ACM when the certificate exists in the emulator. - **Snapshot copy configurations are recorded, not acted on.** `CreateSnapshotCopyConfiguration` copies no snapshot. A configuration is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The destination Region must differ from the namespace's, and a namespace has only one configuration at a time (`ConflictException`). Delete the existing configuration before choosing another destination Region. +- **Scheduled actions are recorded, never run.** An action is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The owning `namespaceName` and the `targetAction.createSnapshot.namespaceName` must each exist but are not required to match, as the API reference does not say they must. `schedule` holds exactly one of `at` and `cron`; a one-off `at` in the future is the only `nextInvocations` reported, because cron expressions are not evaluated. `startTime`, `endTime` and `at` are epoch seconds. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdminJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdminJsonHandler.java index cbb02542d4..6fa73fdb8c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdminJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdminJsonHandler.java @@ -9,12 +9,16 @@ import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.services.redshiftserverless.model.CustomDomainAssociation; import io.github.hectorvent.floci.services.redshiftserverless.model.EndpointAccess; import io.github.hectorvent.floci.services.redshiftserverless.model.ResourcePolicy; +import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction; import io.github.hectorvent.floci.services.redshiftserverless.model.SnapshotCopyConfiguration; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; +import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.function.Supplier; /** @@ -33,18 +37,21 @@ public class RedshiftServerlessAdminJsonHandler { private final RedshiftServerlessEndpointAccessService endpointAccess; private final RedshiftServerlessResourcePolicyService resourcePolicies; private final RedshiftServerlessSnapshotCopyService snapshotCopies; + private final RedshiftServerlessScheduledActionService scheduledActions; @Inject public RedshiftServerlessAdminJsonHandler(ObjectMapper objectMapper, RedshiftServerlessResourcePolicyService resourcePolicies, RedshiftServerlessEndpointAccessService endpointAccess, RedshiftServerlessCustomDomainService customDomains, - RedshiftServerlessSnapshotCopyService snapshotCopies) { + RedshiftServerlessSnapshotCopyService snapshotCopies, + RedshiftServerlessScheduledActionService scheduledActions) { this.objectMapper = objectMapper; this.resourcePolicies = resourcePolicies; this.endpointAccess = endpointAccess; this.customDomains = customDomains; this.snapshotCopies = snapshotCopies; + this.scheduledActions = scheduledActions; } Supplier operation(String action, JsonNode request, String region) { @@ -112,6 +119,15 @@ public class RedshiftServerlessAdminJsonHandler { case "DeleteSnapshotCopyConfiguration" -> () -> snapshotCopyResponse( snapshotCopies.deleteSnapshotCopyConfiguration( ServerlessSupport.text(request, "snapshotCopyConfigurationId"), region)); + case "CreateScheduledAction" -> () -> scheduledActionResponse( + scheduledActions.createScheduledAction(parseScheduledAction(request), region)); + case "GetScheduledAction" -> () -> scheduledActionResponse( + scheduledActions.getScheduledAction(ServerlessSupport.text(request, "scheduledActionName"), region)); + case "ListScheduledActions" -> () -> listScheduledActions(request, region); + case "UpdateScheduledAction" -> () -> scheduledActionResponse( + scheduledActions.updateScheduledAction(parseScheduledAction(request), region)); + case "DeleteScheduledAction" -> () -> scheduledActionResponse( + scheduledActions.deleteScheduledAction(ServerlessSupport.text(request, "scheduledActionName"), region)); default -> null; }; } @@ -253,6 +269,131 @@ public class RedshiftServerlessAdminJsonHandler { } return node; } + + // ── Scheduled action ─────────────────────────────────────────────────── + + private ScheduledAction parseScheduledAction(JsonNode request) { + ScheduledAction action = new ScheduledAction(); + action.setScheduledActionName(ServerlessSupport.text(request, "scheduledActionName")); + action.setNamespaceName(ServerlessSupport.text(request, "namespaceName")); + action.setRoleArn(ServerlessSupport.text(request, "roleArn")); + action.setDescription(ServerlessSupport.text(request, "scheduledActionDescription")); + action.setEnabled(ServerlessSupport.bool(request, "enabled")); + action.setStartTime(ServerlessSupport.epochSeconds(request, "startTime")); + action.setEndTime(ServerlessSupport.epochSeconds(request, "endTime")); + JsonNode schedule = ServerlessSupport.object(request, "schedule"); + if (schedule != null) { + action.setScheduleSpecified(true); + action.setScheduleAt(ServerlessSupport.epochSeconds(schedule, "at")); + action.setScheduleCron(ServerlessSupport.text(schedule, "cron")); + } + JsonNode target = ServerlessSupport.object(request, "targetAction"); + if (target != null) { + JsonNode snapshot = ServerlessSupport.object(target, "createSnapshot"); + if (snapshot == null) { + throw ServerlessSupport.validation("targetAction must set createSnapshot."); + } + action.setTargetSpecified(true); + action.setTargetNamespaceName(ServerlessSupport.text(snapshot, "namespaceName")); + action.setSnapshotNamePrefix(ServerlessSupport.text(snapshot, "snapshotNamePrefix")); + action.setRetentionPeriod(ServerlessSupport.integer(snapshot, "retentionPeriod")); + action.setSnapshotTags(parseTags(snapshot.path("tags"))); + } + return action; + } + + private static Map parseTags(JsonNode tags) { + if (tags.isMissingNode() || tags.isNull()) { + return null; + } + if (!tags.isArray()) { + throw ServerlessSupport.validation("tags must be an array of tags."); + } + Map parsed = new LinkedHashMap<>(); + for (JsonNode tag : tags) { + if (!tag.isObject()) { + throw ServerlessSupport.validation("tags must contain only tag objects."); + } + if (!tag.path("key").isTextual() || !tag.path("value").isTextual()) { + throw ServerlessSupport.validation("every tag needs a string key and a string value."); + } + parsed.put(tag.path("key").textValue(), tag.path("value").textValue()); + } + return parsed; + } + + private Response listScheduledActions(JsonNode request, String region) { + PaginatedResult page = scheduledActions.listScheduledActions( + ServerlessSupport.text(request, "namespaceName"), region, ServerlessSupport.maxResults(request), + ServerlessSupport.text(request, "nextToken")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode items = response.putArray("scheduledActions"); + for (ScheduledAction action : page.items()) { + ObjectNode item = items.addObject(); + item.put("namespaceName", action.getNamespaceName()); + item.put("scheduledActionName", action.getScheduledActionName()); + } + putNextToken(response, page); + return Response.ok(response).build(); + } + + private Response scheduledActionResponse(ScheduledAction action) { + ObjectNode response = objectMapper.createObjectNode(); + response.set("scheduledAction", scheduledActionNode(action)); + return Response.ok(response).build(); + } + + /** A one-off schedule reports its own time while it is ahead and within its active window on an enabled action; a cron schedule reports none, as Floci never computes them. */ + private ObjectNode scheduledActionNode(ScheduledAction action) { + ObjectNode node = objectMapper.createObjectNode(); + if (action.getEndTime() != null) { + node.put("endTime", epoch(action.getEndTime())); + } + node.put("namespaceName", action.getNamespaceName()); + ArrayNode invocations = node.putArray("nextInvocations"); + if (action.getScheduleAt() != null + && !Boolean.FALSE.equals(action.getEnabled()) + && action.getScheduleAt().isAfter(Instant.now()) + && (action.getStartTime() == null || !action.getScheduleAt().isBefore(action.getStartTime())) + && (action.getEndTime() == null || !action.getScheduleAt().isAfter(action.getEndTime()))) { + invocations.add(epoch(action.getScheduleAt())); + } + node.put("roleArn", action.getRoleArn()); + ObjectNode schedule = node.putObject("schedule"); + if (action.getScheduleAt() != null) { + schedule.put("at", epoch(action.getScheduleAt())); + } else { + schedule.put("cron", action.getScheduleCron()); + } + if (action.getDescription() != null) { + node.put("scheduledActionDescription", action.getDescription()); + } + node.put("scheduledActionName", action.getScheduledActionName()); + node.put("scheduledActionUuid", action.getScheduledActionUuid()); + if (action.getStartTime() != null) { + node.put("startTime", epoch(action.getStartTime())); + } + node.put("state", Boolean.FALSE.equals(action.getEnabled()) ? "DISABLED" : "ACTIVE"); + ObjectNode createSnapshot = node.putObject("targetAction").putObject("createSnapshot"); + createSnapshot.put("namespaceName", action.getTargetNamespaceName()); + if (action.getRetentionPeriod() != null) { + createSnapshot.put("retentionPeriod", action.getRetentionPeriod()); + } + createSnapshot.put("snapshotNamePrefix", action.getSnapshotNamePrefix()); + if (action.getSnapshotTags() != null) { + ArrayNode tags = createSnapshot.putArray("tags"); + action.getSnapshotTags().forEach((key, value) -> { + ObjectNode tag = tags.addObject(); + tag.put("key", key); + tag.put("value", value); + }); + } + return node; + } + + private static double epoch(Instant instant) { + return instant.toEpochMilli() / 1000.0; + } // ── Tracks, managed workgroups and reservations ──────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionService.java new file mode 100644 index 0000000000..bf96877a2b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionService.java @@ -0,0 +1,207 @@ +package io.github.hectorvent.floci.services.redshiftserverless; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +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 jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** + * Redshift Serverless scheduled actions. They are stored and echoed, not run: Floci never takes + * the snapshot on the schedule, and a cron schedule reports no upcoming invocations. + * + *

Required members, name patterns and lengths come from the AWS model through + * {@link RedshiftServerlessRequestShapes}; what the model cannot express (the schedule union, the time + * window, the retention range and the namespaces that must exist) is checked here. + * + *

An action belongs to a namespace but lives in its own store, so deleting the namespace needs + * no hook here. Each read checks that the namespace is still there and drops the action otherwise. + */ +@ApplicationScoped +public class RedshiftServerlessScheduledActionService implements Resettable { + + private static final int MAX_RETENTION_DAYS = 3653; + + private final AccountAwareStorageBackend actions; + private final RedshiftServerlessService serverless; + + @Inject + public RedshiftServerlessScheduledActionService(StorageFactory storageFactory, + RedshiftServerlessService serverless) { + this.actions = storageFactory.create("redshiftserverless", "redshiftserverless-scheduledactions.json", + new TypeReference>() {}); + this.serverless = serverless; + } + + /** + * Creates the action described by {@code request}. {@code enabled} defaults to true. The target + * namespace of the snapshot and the owning namespace must both exist. + */ + public synchronized ScheduledAction createScheduledAction(ScheduledAction request, String region) { + requireNamespace(request.getNamespaceName(), region); + validateSchedule(request); + validateTarget(request, region); + validateWindow(request); + if (live(region).stream().anyMatch(existing -> + existing.getScheduledActionName().equals(request.getScheduledActionName()))) { + throw ServerlessSupport.conflict("The scheduled action " + request.getScheduledActionName() + + " already exists."); + } + + ScheduledAction action = new ScheduledAction(request); + action.setOwnerId(namespaceIdOf(request.getNamespaceName(), region)); + action.setScheduledActionUuid(UUID.randomUUID().toString()); + action.setEnabled(request.getEnabled() == null || request.getEnabled()); + actions.put(storageKey(region, action.getScheduledActionName()), action); + return new ScheduledAction(action); + } + + public synchronized ScheduledAction getScheduledAction(String scheduledActionName, String region) { + return new ScheduledAction(require(scheduledActionName, region)); + } + + public synchronized PaginatedResult listScheduledActions(String namespaceName, String region, + Integer maxResults, String nextToken) { + int limit = ServerlessSupport.pageSize(maxResults); + List matching = live(region).stream() + .filter(action -> namespaceName == null || namespaceName.equals(action.getNamespaceName())) + .sorted(Comparator.comparing(ScheduledAction::getScheduledActionName)) + .map(ScheduledAction::new) + .toList(); + return Pagination.paginate(matching, ScheduledAction::getScheduledActionName, + limit, nextToken, "scheduled-action", + token -> ServerlessSupport.invalidPagination("Invalid nextToken.")); + } + + /** + * Applies the members {@code changes} carries. The schedule and the target replace the stored + * ones as a whole, because each is a union of which exactly one member may be set. + */ + public synchronized ScheduledAction updateScheduledAction(ScheduledAction changes, String region) { + ScheduledAction current = require(changes.getScheduledActionName(), region); + ScheduledAction updated = new ScheduledAction(current); + if (changes.getRoleArn() != null) { + updated.setRoleArn(changes.getRoleArn()); + } + if (changes.getDescription() != null) { + updated.setDescription(changes.getDescription()); + } + if (changes.getEnabled() != null) { + updated.setEnabled(changes.getEnabled()); + } + if (changes.getStartTime() != null) { + updated.setStartTime(changes.getStartTime()); + } + if (changes.getEndTime() != null) { + updated.setEndTime(changes.getEndTime()); + } + if (changes.isScheduleSpecified()) { + validateSchedule(changes); + updated.setScheduleAt(changes.getScheduleAt()); + updated.setScheduleCron(changes.getScheduleCron()); + } + boolean changesTarget = changes.isTargetSpecified() + || changes.getTargetNamespaceName() != null || changes.getSnapshotNamePrefix() != null + || changes.getRetentionPeriod() != null || changes.getSnapshotTags() != null; + if (changesTarget) { + validateTarget(changes, region); + updated.setTargetNamespaceName(changes.getTargetNamespaceName()); + updated.setSnapshotNamePrefix(changes.getSnapshotNamePrefix()); + updated.setRetentionPeriod(changes.getRetentionPeriod()); + updated.setSnapshotTags(changes.getSnapshotTags()); + } + validateWindow(updated); + actions.put(storageKey(region, updated.getScheduledActionName()), updated); + return new ScheduledAction(updated); + } + + public synchronized ScheduledAction deleteScheduledAction(String scheduledActionName, String region) { + ScheduledAction existing = new ScheduledAction(require(scheduledActionName, region)); + actions.delete(storageKey(region, scheduledActionName)); + return existing; + } + + @Override + public void clear() { + actions.clear(); + } + + private ScheduledAction require(String scheduledActionName, String region) { + ScheduledAction action = actions.get(storageKey(region, scheduledActionName)).orElse(null); + if (action != null && !isOnSameNamespace(action, region)) { + actions.delete(storageKey(region, scheduledActionName)); + action = null; + } + if (action == null) { + throw ServerlessSupport.notFound("The scheduled action " + scheduledActionName + " was not found."); + } + return action; + } + + /** The region's actions whose namespace is still there; any other is deleted as it is found. */ + private List live(String region) { + return ServerlessSupport.live(actions, region, + action -> isOnSameNamespace(action, region), + action -> storageKey(region, action.getScheduledActionName())); + } + + /** A namespace recreated under the same name has a new id, so it never inherits its predecessor's actions. */ + private boolean isOnSameNamespace(ScheduledAction action, String region) { + return serverless.findNamespace(action.getNamespaceName(), region) + .map(namespace -> Objects.equals(namespace.getNamespaceId(), action.getOwnerId())) + .orElse(false); + } + + private String namespaceIdOf(String namespaceName, String region) { + return serverless.findNamespace(namespaceName, region).map(Namespace::getNamespaceId).orElse(null); + } + + private void requireNamespace(String namespaceName, String region) { + if (!serverless.namespaceExists(namespaceName, region)) { + throw ServerlessSupport.notFound("The namespace " + namespaceName + " was not found."); + } + } + + /** Exactly one of {@code at} and {@code cron} must be set: the schedule is a union. */ + private static void validateSchedule(ScheduledAction action) { + boolean hasAt = action.getScheduleAt() != null; + boolean hasCron = action.getScheduleCron() != null && !action.getScheduleCron().isBlank(); + if (hasAt == hasCron) { + throw ServerlessSupport.validation("schedule must set exactly one of at and cron."); + } + } + + private void validateTarget(ScheduledAction action, String region) { + if (action.getTargetNamespaceName() == null) { + throw ServerlessSupport.validation("targetAction must set createSnapshot."); + } + requireNamespace(action.getTargetNamespaceName(), region); + Integer retention = action.getRetentionPeriod(); + if (retention != null && retention != -1 && (retention < 1 || retention > MAX_RETENTION_DAYS)) { + throw ServerlessSupport.validation("targetAction.createSnapshot.retentionPeriod must be -1 " + + "(indefinite) or between 1 and " + MAX_RETENTION_DAYS + "."); + } + } + + private static void validateWindow(ScheduledAction action) { + if (action.getStartTime() != null && action.getEndTime() != null + && !action.getEndTime().isAfter(action.getStartTime())) { + throw ServerlessSupport.validation("endTime must be after startTime."); + } + } + + private static String storageKey(String region, String name) { + return region + "::" + name; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java index 4103907b9c..d28e3f6a37 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java @@ -475,6 +475,11 @@ public class RedshiftServerlessService implements Resettable { return snapshotArn.substring(prefix.length()); } + /** Whether {@code namespaceName} names a namespace in {@code region}; never throws for an unknown name. */ + public boolean namespaceExists(String namespaceName, String region) { + return namespaceName != null && namespaces.get(storageKey(region, namespaceName)).isPresent(); + } + /** The workgroup called {@code workgroupName} in {@code region}, empty when there is none. */ public Optional findWorkgroup(String workgroupName, String region) { return workgroupName == null ? Optional.empty() : workgroups.get(storageKey(region, workgroupName)); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/ScheduledAction.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/ScheduledAction.java new file mode 100644 index 0000000000..ae9d69eb1d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/ScheduledAction.java @@ -0,0 +1,195 @@ +package io.github.hectorvent.floci.services.redshiftserverless.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A Redshift Serverless scheduled action. Floci stores and echoes it but never runs it, so no + * snapshot is taken on the schedule. The same type carries an update request, in which a null member + * means the caller left it out. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ScheduledAction { + + private String scheduledActionName; + private String scheduledActionUuid; + private String namespaceName; + private String roleArn; + private String description; + private Boolean enabled; + private Instant startTime; + private Instant endTime; + private Instant scheduleAt; + private String scheduleCron; + private String targetNamespaceName; + private String snapshotNamePrefix; + private Integer retentionPeriod; + private Map snapshotTags; + private String ownerId; + private boolean scheduleSpecified; + private boolean targetSpecified; + + public ScheduledAction() { + } + + public ScheduledAction(ScheduledAction other) { + this.ownerId = other.ownerId; + this.scheduleSpecified = other.scheduleSpecified; + this.targetSpecified = other.targetSpecified; + this.scheduledActionName = other.scheduledActionName; + this.scheduledActionUuid = other.scheduledActionUuid; + this.namespaceName = other.namespaceName; + this.roleArn = other.roleArn; + this.description = other.description; + this.enabled = other.enabled; + this.startTime = other.startTime; + this.endTime = other.endTime; + this.scheduleAt = other.scheduleAt; + this.scheduleCron = other.scheduleCron; + this.targetNamespaceName = other.targetNamespaceName; + this.snapshotNamePrefix = other.snapshotNamePrefix; + this.retentionPeriod = other.retentionPeriod; + this.snapshotTags = other.snapshotTags == null ? null : new LinkedHashMap<>(other.snapshotTags); + } + + public String getScheduledActionName() { + return scheduledActionName; + } + + public void setScheduledActionName(String scheduledActionName) { + this.scheduledActionName = scheduledActionName; + } + + public String getScheduledActionUuid() { + return scheduledActionUuid; + } + + public void setScheduledActionUuid(String scheduledActionUuid) { + this.scheduledActionUuid = scheduledActionUuid; + } + + public String getNamespaceName() { + return namespaceName; + } + + public void setNamespaceName(String namespaceName) { + this.namespaceName = namespaceName; + } + + public String getRoleArn() { + return roleArn; + } + + public void setRoleArn(String roleArn) { + this.roleArn = roleArn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Instant getStartTime() { + return startTime; + } + + public void setStartTime(Instant startTime) { + this.startTime = startTime; + } + + public Instant getEndTime() { + return endTime; + } + + public void setEndTime(Instant endTime) { + this.endTime = endTime; + } + + public Instant getScheduleAt() { + return scheduleAt; + } + + public void setScheduleAt(Instant scheduleAt) { + this.scheduleAt = scheduleAt; + } + + public String getScheduleCron() { + return scheduleCron; + } + + public void setScheduleCron(String scheduleCron) { + this.scheduleCron = scheduleCron; + } + + public String getTargetNamespaceName() { + return targetNamespaceName; + } + + public void setTargetNamespaceName(String targetNamespaceName) { + this.targetNamespaceName = targetNamespaceName; + } + + public String getSnapshotNamePrefix() { + return snapshotNamePrefix; + } + + public void setSnapshotNamePrefix(String snapshotNamePrefix) { + this.snapshotNamePrefix = snapshotNamePrefix; + } + + public Integer getRetentionPeriod() { + return retentionPeriod; + } + + public void setRetentionPeriod(Integer retentionPeriod) { + this.retentionPeriod = retentionPeriod; + } + + public Map getSnapshotTags() { + return snapshotTags; + } + + public void setSnapshotTags(Map snapshotTags) { + this.snapshotTags = snapshotTags; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public boolean isScheduleSpecified() { + return scheduleSpecified; + } + + public void setScheduleSpecified(boolean scheduleSpecified) { + this.scheduleSpecified = scheduleSpecified; + } + + public boolean isTargetSpecified() { + return targetSpecified; + } + + public void setTargetSpecified(boolean targetSpecified) { + this.targetSpecified = targetSpecified; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java index e5b4061fda..f55934d9a0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java @@ -51,7 +51,7 @@ class RedshiftServerlessAdministrationHandlerTest { void setUp() { StorageFactory storageFactory = mock(StorageFactory.class); for (String file : List.of("namespaces", "workgroups", "snapshots", "usagelimits", "resourcepolicies", - "endpointaccess", "customdomains", "snapshotcopyconfigurations")) { + "endpointaccess", "customdomains", "snapshotcopyconfigurations", "scheduledactions")) { when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-" + file + ".json"), any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); @@ -92,7 +92,8 @@ class RedshiftServerlessAdministrationHandlerTest { new RedshiftServerlessResourcePolicyService(storageFactory, serverlessService, mapper), new RedshiftServerlessEndpointAccessService(storageFactory, regionResolver, serverlessService), customDomains, - new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService)), + new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService), + new RedshiftServerlessScheduledActionService(storageFactory, serverlessService)), customDomains); } @@ -522,6 +523,79 @@ class RedshiftServerlessAdministrationHandlerTest { errorType("ListSnapshotCopyConfigurations", "{\"nextToken\":\"bad-token\"}")); } + @Test + void scheduledActionIsStoredAndNeverRun() { + namespace("sched-ns"); + long future = Instant.now().plusSeconds(3600).getEpochSecond(); + String target = "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"sched-ns\"," + + "\"snapshotNamePrefix\":\"nightly\",\"retentionPeriod\":7," + + "\"tags\":[{\"key\":\"env\",\"value\":\"dev\"}]}}"; + + JsonNode created = ok("CreateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"namespaceName\":\"sched-ns\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT_ID + ":role/r\"," + + "\"schedule\":{\"cron\":\"cron(0 3 * * ? *)\"}," + target + "," + + "\"scheduledActionDescription\":\"nightly\"}").get("scheduledAction"); + assertEquals("ACTIVE", created.get("state").textValue()); + assertEquals("cron(0 3 * * ? *)", created.get("schedule").get("cron").textValue()); + assertEquals("nightly", created.get("targetAction").get("createSnapshot").get("snapshotNamePrefix").textValue()); + 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()); + assertTrue(created.get("scheduledActionUuid").textValue().length() > 8); + + assertEquals("ConflictException", errorType("CreateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"namespaceName\":\"sched-ns\",\"roleArn\":\"r\",\"schedule\":{\"cron\":\"cron(0 3 * * ? *)\"}," + + target + "}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", "{\"scheduledActionName\":\"both-sched\"," + + "\"namespaceName\":\"sched-ns\",\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\",\"at\":" + future + + "}," + target + "}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", "{\"scheduledActionName\":\"Bad_Name\"," + + "\"namespaceName\":\"sched-ns\",\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\"}," + target + "}")); + assertEquals("ResourceNotFoundException", errorType("CreateScheduledAction", + "{\"scheduledActionName\":\"no-ns-sched\",\"namespaceName\":\"nope-ns\",\"roleArn\":\"r\"," + + "\"schedule\":{\"cron\":\"x\"}," + target + "}")); + + JsonNode oneOff = ok("UpdateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"enabled\":false,\"schedule\":{\"at\":" + future + "}}").get("scheduledAction"); + assertEquals("DISABLED", oneOff.get("state").textValue()); + assertEquals(0, oneOff.get("nextInvocations").size()); + assertEquals(future, oneOff.get("schedule").get("at").longValue()); + assertEquals("sched-ns", oneOff.get("namespaceName").textValue()); + + JsonNode activeOneOff = ok("UpdateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"enabled\":true}").get("scheduledAction"); + assertEquals("ACTIVE", activeOneOff.get("state").textValue()); + assertEquals(1, activeOneOff.get("nextInvocations").size()); + + JsonNode afterEnd = ok("UpdateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"endTime\":" + (future - 100) + "}").get("scheduledAction"); + assertEquals(0, afterEnd.get("nextInvocations").size()); + + JsonNode beforeStart = ok("UpdateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"endTime\":" + (future + 1000) + ",\"startTime\":" + (future + 100) + "}").get("scheduledAction"); + assertEquals(0, beforeStart.get("nextInvocations").size()); + + JsonNode inWindow = ok("UpdateScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"," + + "\"startTime\":" + (future - 100) + "}").get("scheduledAction"); + assertEquals(1, inWindow.get("nextInvocations").size()); + + assertEquals("ValidationException", + errorType("ListScheduledActions", "{\"maxResults\":0}")); + assertEquals("ValidationException", + errorType("ListScheduledActions", "{\"maxResults\":101}")); + assertEquals("InvalidPaginationException", + errorType("ListScheduledActions", "{\"nextToken\":\"bad-token\"}")); + + JsonNode listed = ok("ListScheduledActions", "{\"namespaceName\":\"sched-ns\"}").get("scheduledActions"); + assertEquals(1, listed.size()); + assertEquals("nightly-snap", listed.get(0).get("scheduledActionName").textValue()); + assertEquals("nightly-snap", ok("DeleteScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"}") + .get("scheduledAction").get("scheduledActionName").textValue()); + assertEquals("ResourceNotFoundException", + errorType("GetScheduledAction", "{\"scheduledActionName\":\"nightly-snap\"}")); + } + @Test void tracksAreTheTwoAwsReleaseTracks() { JsonNode track = ok("GetTrack", "{\"trackName\":\"trailing\"}").get("track"); @@ -618,6 +692,23 @@ class RedshiftServerlessAdministrationHandlerTest { ok("CreateSnapshotCopyConfiguration", "{\"namespaceName\":\"recreate-ns\",\"destinationRegion\":\"us-west-2\"}"); } + @Test + void aNamespaceRecreatedUnderTheSameNameDoesNotInheritActions() { + namespace("recreate-ns"); + ok("CreateScheduledAction", "{\"scheduledActionName\":\"old-action\",\"namespaceName\":\"recreate-ns\"," + + "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":" + + "{\"namespaceName\":\"recreate-ns\",\"snapshotNamePrefix\":\"p\"}}}"); + + ok("DeleteNamespace", "{\"namespaceName\":\"recreate-ns\"}"); + namespace("recreate-ns"); + + assertEquals("ResourceNotFoundException", errorType("GetScheduledAction", + "{\"scheduledActionName\":\"old-action\"}")); + ok("CreateScheduledAction", "{\"scheduledActionName\":\"old-action\",\"namespaceName\":\"recreate-ns\"," + + "\"roleArn\":\"r\",\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":" + + "{\"namespaceName\":\"recreate-ns\",\"snapshotNamePrefix\":\"p\"}}}"); + } + @Test void aSnapshotRecreatedUnderTheSameNameDoesNotInheritItsPolicy() { String arn = snapshot("recreate-snap-ns", "recreate-snap"); @@ -629,6 +720,45 @@ class RedshiftServerlessAdministrationHandlerTest { assertEquals("ResourceNotFoundException", errorType("GetResourcePolicy", "{\"resourceArn\":\"" + arn + "\"}")); } + @Test + void scheduledActionUpdateRejectsAPartialTargetAndATagWithoutAKey() { + namespace("partial-ns"); + String create = "{\"scheduledActionName\":\"partial-action\",\"namespaceName\":\"partial-ns\",\"roleArn\":\"r\"," + + "\"schedule\":{\"cron\":\"x\"},\"targetAction\":{\"createSnapshot\":" + + "{\"namespaceName\":\"partial-ns\",\"snapshotNamePrefix\":\"p\""; + ok("CreateScheduledAction", create + "}}}"); + + assertEquals("ValidationException", errorType("UpdateScheduledAction", + "{\"scheduledActionName\":\"partial-action\",\"targetAction\":{\"createSnapshot\":" + + "{\"retentionPeriod\":5}}}")); + assertEquals("ValidationException", errorType("UpdateScheduledAction", + "{\"scheduledActionName\":\"partial-action\",\"targetAction\":{}}")); + assertEquals("ValidationException", errorType("UpdateScheduledAction", + "{\"scheduledActionName\":\"partial-action\",\"schedule\":{}}")); + JsonNode unchanged = ok("UpdateScheduledAction", + "{\"scheduledActionName\":\"partial-action\",\"enabled\":false}").get("scheduledAction"); + assertEquals("x", 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\":{}}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", + create.replace("partial-action", "tag-action") + ",\"tags\":[{\"value\":\"v\"}]}}}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", + create.replace("partial-action", "tag-noval") + ",\"tags\":[{\"key\":\"k\"}]}}}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", + create.replace("partial-action", "tag-numval") + ",\"tags\":[{\"key\":\"k\",\"value\":123}]}}}")); + assertEquals("ValidationException", errorType("CreateScheduledAction", + create.replace("partial-action", "tag-boolval") + ",\"tags\":[{\"key\":\"k\",\"value\":true}]}}}")); + assertEquals("ResourceNotFoundException", errorType("GetScheduledAction", + "{\"scheduledActionName\":\"tag-noval\"}")); + assertEquals("ResourceNotFoundException", errorType("GetScheduledAction", + "{\"scheduledActionName\":\"tag-numval\"}")); + assertEquals("ResourceNotFoundException", errorType("GetScheduledAction", + "{\"scheduledActionName\":\"tag-boolval\"}")); + } + @Test void anUnknownActionIsStillRejected() { assertEquals("UnknownOperationException", errorType("NoSuchOperation", "{}")); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java index 30d9529c4e..c7ef603250 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java @@ -752,6 +752,24 @@ class RedshiftServerlessIntegrationTest { .statusCode(200); } + @Test + void scheduledActionRoundTripsOverTheWire() { + call("CreateNamespace", "{\"namespaceName\":\"sched-ns\",\"adminUsername\":\"admin\"}").statusCode(200); + + call("CreateScheduledAction", "{\"scheduledActionName\":\"admin-sched\",\"namespaceName\":\"sched-ns\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/r\",\"schedule\":{\"cron\":\"cron(0 3 * * ? *)\"}," + + "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"sched-ns\",\"snapshotNamePrefix\":\"p\"}}}") + .statusCode(200) + .body("scheduledAction.state", equalTo("ACTIVE")) + .body("scheduledAction.schedule.cron", equalTo("cron(0 3 * * ? *)")); + call("CreateScheduledAction", "{\"scheduledActionName\":\"BAD_NAME\",\"namespaceName\":\"sched-ns\"," + + "\"roleArn\":\"arn:aws:iam::000000000000:role/r\",\"schedule\":{\"cron\":\"x\"}," + + "\"targetAction\":{\"createSnapshot\":{\"namespaceName\":\"sched-ns\",\"snapshotNamePrefix\":\"p\"}}}") + .statusCode(400) + .body("__type", equalTo("ValidationException")); + call("DeleteScheduledAction", "{\"scheduledActionName\":\"admin-sched\"}").statusCode(200); + } + private static io.restassured.response.ValidatableResponse call(String action, String body) { return given() .header("X-Amz-Target", TARGET_PREFIX + action) diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java index 6cf515ff60..51def2c375 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java @@ -96,13 +96,14 @@ class RedshiftServerlessJsonHandlerTest { new RedshiftServerlessResourcePolicyService(storageFactory, service, mapper), new RedshiftServerlessEndpointAccessService(storageFactory, regionResolver, service), customDomains, - new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service)), + new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service), + new RedshiftServerlessScheduledActionService(storageFactory, service)), customDomains); } @SuppressWarnings({"unchecked", "rawtypes"}) private static void stubAdministrationStores(StorageFactory storageFactory) { - for (String file : List.of("resourcepolicies", "endpointaccess", "customdomains", "snapshotcopyconfigurations")) { + for (String file : List.of("resourcepolicies", "endpointaccess", "customdomains", "snapshotcopyconfigurations", "scheduledactions")) { when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-" + file + ".json"), any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) AccountAwareStorageBackend.inMemory(ACCOUNT_ID)); @@ -443,7 +444,7 @@ class RedshiftServerlessJsonHandlerTest { @Test void aModeledActionWithoutAnImplementationIsStillAnUnknownOperation() { - Response response = handler.handle("CreateScheduledAction", mapper.createObjectNode(), REGION); + Response response = handler.handle("ConvertRecoveryPointToSnapshot", mapper.createObjectNode(), REGION); assertEquals(400, response.getStatus()); assertEquals("UnknownOperationException", errorType(response));