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

@@ -1908,6 +1908,12 @@ public interface EmulatorConfig {
interface RedshiftServerlessServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("true")
boolean scheduledActionsEnabled();
@WithDefault("60")
int scheduledActionSweepIntervalSeconds();
}
interface NeptuneServiceConfig {
@@ -344,7 +344,7 @@ public class RedshiftServerlessAdminJsonHandler {
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. */
/** Reports the next invocation inside the active window of an enabled action, for both schedule types. */
private ObjectNode scheduledActionNode(ScheduledAction action) {
ObjectNode node = objectMapper.createObjectNode();
if (action.getEndTime() != null) {
@@ -352,13 +352,7 @@ public class RedshiftServerlessAdminJsonHandler {
}
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()));
}
RedshiftServerlessSchedule.next(action, Instant.now()).ifPresent(time -> invocations.add(epoch(time)));
node.put("roleArn", action.getRoleArn());
ObjectNode schedule = node.putObject("schedule");
if (action.getScheduleAt() != null) {
@@ -0,0 +1,111 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.cronutils.model.Cron;
import com.cronutils.model.time.ExecutionTime;
import io.github.hectorvent.floci.core.common.AwsCronDefinitions;
import io.github.hectorvent.floci.services.redshiftserverless.model.ScheduledAction;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
/** UTC schedule rules of a Serverless scheduled action: one-off {@code at} or six-field AWS {@code cron}. */
final class RedshiftServerlessSchedule {
private static final Duration MINIMUM_INTERVAL = Duration.ofHours(1);
private static final Duration SPACING_HORIZON = Duration.ofDays(400);
private static final int MAX_SPACING_CHECKS = 1000;
private RedshiftServerlessSchedule() { }
/** Rejects a cron that does not parse or fires more often than hourly; an {@code at} schedule always passes. */
static void validate(ScheduledAction action) {
if (action.getScheduleCron() == null || action.getScheduleCron().isBlank()) {
return;
}
ExecutionTime cron = parse(action.getScheduleCron());
Optional<Instant> first = nextCron(cron, Instant.EPOCH);
if (first.isEmpty()) {
return;
}
Instant cursor = first.get().minusSeconds(1);
Instant limit = cursor.plus(SPACING_HORIZON);
Instant previous = null;
for (int i = 0; i < MAX_SPACING_CHECKS; i++) {
Optional<Instant> next = nextCron(cron, cursor);
if (next.isEmpty() || next.get().isAfter(limit)) {
return;
}
if (previous != null && Duration.between(previous, next.get()).compareTo(MINIMUM_INTERVAL) < 0) {
throw ServerlessSupport.validation("The cron schedule must be at least one hour apart.");
}
previous = next.get();
cursor = next.get();
}
}
/** The first invocation strictly after {@code after} that is enabled and inside the active window. */
static Optional<Instant> next(ScheduledAction action, Instant after) {
if (Boolean.FALSE.equals(action.getEnabled())) {
return Optional.empty();
}
Instant candidate;
if (action.getScheduleAt() != null) {
candidate = action.getScheduleAt().isAfter(after) ? action.getScheduleAt() : null;
} else {
Instant from = action.getStartTime() != null && action.getStartTime().isAfter(after)
? action.getStartTime().minusNanos(1) : after;
candidate = nextCron(parse(action.getScheduleCron()), from).orElse(null);
}
return Optional.ofNullable(candidate).filter(time -> inWindow(action, time));
}
/** The latest invocation in {@code (anchor, now]} that is inside the window; older ones are coalesced away. */
static Optional<Instant> latestDue(ScheduledAction action, Instant anchor, Instant now) {
if (Boolean.FALSE.equals(action.getEnabled())) {
return Optional.empty();
}
Instant upper = action.getEndTime() != null && action.getEndTime().isBefore(now) ? action.getEndTime() : now;
Optional<Instant> latest;
if (action.getScheduleAt() != null) {
latest = Optional.of(action.getScheduleAt()).filter(time -> !time.isAfter(upper));
} else {
latest = parse(action.getScheduleCron()).lastExecution(upper.atZone(ZoneOffset.UTC).plusNanos(1))
.map(value -> value.toInstant());
}
return latest.filter(time -> time.isAfter(anchor) && inWindow(action, time));
}
private static boolean inWindow(ScheduledAction action, Instant time) {
return (action.getStartTime() == null || !time.isBefore(action.getStartTime()))
&& (action.getEndTime() == null || !time.isAfter(action.getEndTime()));
}
private static Optional<Instant> nextCron(ExecutionTime cron, Instant after) {
return cron.nextExecution(after.atZone(ZoneOffset.UTC)).map(value -> value.toInstant());
}
private static ExecutionTime parse(String expression) {
String body = expression.trim();
if (body.startsWith("cron")) {
body = body.substring(4).trim();
}
if (body.startsWith("(") && body.endsWith(")")) {
body = body.substring(1, body.length() - 1).trim();
}
String[] fields = body.split("\\s+");
if (fields.length != 6) {
throw ServerlessSupport.validation("The cron schedule needs six fields.");
}
if ("?".equals(fields[2]) == "?".equals(fields[4])) {
throw ServerlessSupport.validation("Use ? in exactly one of day-of-month and day-of-week.");
}
try {
Cron cron = AwsCronDefinitions.newParser().parse("0 " + String.join(" ", fields));
cron.validate();
return ExecutionTime.forCron(cron);
} catch (IllegalArgumentException e) {
throw ServerlessSupport.validation("The cron schedule is invalid: " + e.getMessage());
}
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
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.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Decides whether the execution role of a scheduled action may take its snapshot. The role has to
* trust the Redshift scheduler principal and its identity policies, boundary and SCPs have to allow
* {@code redshift-serverless:CreateSnapshot} on the target. Only active with IAM enforcement on, as
* for every other API call. A role of another account is refused, because the snapshot would
* otherwise be taken on the strength of a role the action's account does not own.
*/
@ApplicationScoped
public class RedshiftServerlessScheduledActionAuthorizer {
static final String CREATE_SNAPSHOT = "redshift-serverless:CreateSnapshot";
private static final String SCHEDULER_PRINCIPAL = ServicePrincipals.of("scheduler.redshift");
private final EmulatorConfig config;
private final IamService iamService;
private final IamPolicyEvaluator evaluator;
private final AssumeRolePolicyEvaluator trustEvaluator;
private final Instance<ScpProvider> scpProvider;
@Inject
public RedshiftServerlessScheduledActionAuthorizer(EmulatorConfig config, IamService iamService,
IamPolicyEvaluator evaluator,
AssumeRolePolicyEvaluator trustEvaluator,
Instance<ScpProvider> scpProvider) {
this.config = config;
this.iamService = iamService;
this.evaluator = evaluator;
this.trustEvaluator = trustEvaluator;
this.scpProvider = scpProvider;
}
/**
* Returns why {@code roleArn} may not create a snapshot of {@code targetArn}, or nothing when it may.
*
* @param accountId the account that owns the action
*/
public Optional<String> refusal(String roleArn, String accountId, String targetArn) {
if (!config.services().iam().enforcementEnabled()) {
return Optional.empty();
}
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(roleArn);
} catch (IllegalArgumentException e) {
return Optional.of("The execution role " + roleArn + " is not a valid ARN.");
}
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
return Optional.of("The execution role " + roleArn + " is not an IAM role.");
}
if (!accountId.equals(parsed.accountId())) {
return Optional.of("The execution role " + roleArn + " belongs to another account.");
}
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
Optional<IamRole> role = iamService.findRole(accountId, roleName)
.filter(found -> IamService.roleArnMatches(roleArn, found));
if (role.isEmpty()) {
return Optional.of("The execution role " + roleArn + " does not exist.");
}
if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(), SCHEDULER_PRINCIPAL,
null, accountId)) {
return Optional.of("The execution role " + roleArn + " does not trust " + SCHEDULER_PRINCIPAL + ".");
}
CallerContext caller = iamService.resolvePrincipalContext(role.get().getArn());
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
AwsArnUtils.Arn target = AwsArnUtils.isArn(targetArn) ? AwsArnUtils.parse(targetArn) : null;
String targetRegion = target != null ? target.region() : null;
String targetAccount = target != null ? target.accountId() : accountId;
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
Map.of("aws:PrincipalArn", List.of(role.get().getArn())),
targetArn, targetRegion, accountId, targetAccount);
Decision decision = evaluator.evaluate(caller, List.of(), CREATE_SNAPSHOT, targetArn, context);
if (decision != Decision.ALLOW) {
return Optional.of("The execution role " + roleArn + " is not authorized to perform "
+ CREATE_SNAPSHOT + " on " + targetArn + ".");
}
return Optional.empty();
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/** Drives Serverless scheduled actions outside AWS request threads, one sweep at a time. */
@ApplicationScoped
public class RedshiftServerlessScheduledActionScheduler implements Resettable {
private static final Logger LOG = Logger.getLogger(RedshiftServerlessScheduledActionScheduler.class);
private final RedshiftServerlessScheduledActionService service;
private final ScheduledExecutorService executor;
private final long intervalSeconds;
private final ReentrantLock sweepLock = new ReentrantLock();
private volatile boolean paused;
@Inject
public RedshiftServerlessScheduledActionScheduler(RedshiftServerlessScheduledActionService service,
EmulatorConfig config) {
EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless();
this.service = service;
this.intervalSeconds = Math.max(1, serverless.scheduledActionSweepIntervalSeconds());
this.executor = serverless.enabled() && serverless.scheduledActionsEnabled()
? Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "redshift-serverless-scheduled-actions");
thread.setDaemon(true);
return thread;
}) : null;
}
void onStart(@Observes StartupEvent ignored) {
if (executor != null) {
executor.scheduleWithFixedDelay(this::tickSafely, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
}
void onStop(@Observes ShutdownEvent ignored) {
if (executor != null) {
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warn("The Redshift Serverless scheduled action worker is still finishing a snapshot during shutdown");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.debugv(e, "Interrupted while stopping the Redshift Serverless scheduled action worker");
}
}
}
/** Whether a background worker exists, which the two configuration switches decide. */
boolean active() {
return executor != null;
}
public void tick(Instant now) {
sweepLock.lock();
try {
if (!paused) {
service.runScheduledActions(now);
}
} finally {
sweepLock.unlock();
}
}
/** Drains a running sweep so it cannot write a claim back into storage that reset is about to clear. */
@Override
public void beforeReset() {
paused = true;
sweepLock.lock();
sweepLock.unlock();
}
@Override
public void clear() {
// Claims live with the actions in RedshiftServerlessScheduledActionService storage, which reset wipes.
}
@Override
public void afterReset() {
paused = false;
}
private void tickSafely() {
try {
tick(Instant.now());
} catch (RuntimeException e) {
LOG.warnv(e, "The Redshift Serverless scheduled action sweep failed");
}
}
}
@@ -3,23 +3,36 @@ 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.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend.AccountEntry;
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 org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* 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.
* Redshift Serverless scheduled actions. A sweep ({@link #runScheduledActions}) takes the snapshot of
* every action whose schedule came due since it last looked.
*
* <p>Required members, name patterns and lengths come from the AWS model through
* {@link RedshiftServerlessRequestShapes}; what the model cannot express (the schedule union, the time
@@ -27,44 +40,78 @@ import java.util.UUID;
*
* <p>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.
*
* <p>The sweep records its checkpoint with a normal atomic write after attempting the snapshot.
* A crash before that write, or before a hybrid flush, can cause the time to be retried. Snapshot names
* derive from the scheduled time, so an existing snapshot prevents a duplicate on retry. After downtime
* only the latest due time is attempted, and nothing before an action was created, scheduled again or
* enabled again is replayed. Memory storage forgets actions on restart.
*
* <p>Lock order: the action's lock, then this service's monitor, then the Serverless service's. A
* mutation and a sweep of the same action hold its lock, so neither sees the other half done; the
* monitor is never held while a snapshot is dumped, so reads stay available during one.
*/
@ApplicationScoped
public class RedshiftServerlessScheduledActionService implements Resettable {
private static final Logger LOG = Logger.getLogger(RedshiftServerlessScheduledActionService.class);
private static final int MAX_RETENTION_DAYS = 3653;
private static final int MAX_SNAPSHOT_NAME_LENGTH = 255;
private static final DateTimeFormatter INVOCATION_SUFFIX =
DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss", Locale.ROOT).withZone(ZoneOffset.UTC);
private final AccountAwareStorageBackend<ScheduledAction> actions;
private final RedshiftServerlessService serverless;
private final RedshiftServerlessScheduledActionAuthorizer authorizer;
private final RegionResolver regionResolver;
private final Clock clock;
private final ConcurrentHashMap<String, ReentrantLock> actionLocks = new ConcurrentHashMap<>();
@Inject
public RedshiftServerlessScheduledActionService(StorageFactory storageFactory,
RedshiftServerlessService serverless) {
RedshiftServerlessService serverless,
RedshiftServerlessScheduledActionAuthorizer authorizer,
RegionResolver regionResolver,
Clock clock) {
this.actions = storageFactory.create("redshiftserverless", "redshiftserverless-scheduledactions.json",
new TypeReference<Map<String, ScheduledAction>>() {});
this.serverless = serverless;
this.authorizer = authorizer;
this.regionResolver = regionResolver;
this.clock = clock;
}
RedshiftServerlessScheduledActionService(StorageFactory storageFactory,
RedshiftServerlessService serverless,
RedshiftServerlessScheduledActionAuthorizer authorizer,
RegionResolver regionResolver) {
this(storageFactory, serverless, authorizer, regionResolver, Clock.systemUTC());
}
/**
* 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.");
}
public ScheduledAction createScheduledAction(ScheduledAction request, String region) {
return mutate(region, request.getScheduledActionName(), () -> {
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);
ScheduledAction action = new ScheduledAction(request);
action.setOwnerId(namespaceIdOf(request.getNamespaceName(), region));
action.setScheduledActionUuid(UUID.randomUUID().toString());
action.setEnabled(request.getEnabled() == null || request.getEnabled());
action.setActivatedAt(clock.instant());
actions.put(storageKey(region, action.getScheduledActionName()), action);
return new ScheduledAction(action);
});
}
public synchronized ScheduledAction getScheduledAction(String scheduledActionName, String region) {
@@ -86,55 +133,191 @@ public class RedshiftServerlessScheduledActionService implements Resettable {
/**
* 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.
* ones as a whole, because each is a union of which exactly one member may be set. A new schedule,
* or enabling a disabled action, restarts the count from now so nothing earlier is replayed.
*/
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 ScheduledAction updateScheduledAction(ScheduledAction changes, String region) {
return mutate(region, changes.getScheduledActionName(), () -> {
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) {
if (changes.getEnabled() && Boolean.FALSE.equals(current.getEnabled())) {
updated.setActivatedAt(clock.instant());
}
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());
updated.setActivatedAt(clock.instant());
updated.setLastClaimedInvocation(null);
}
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;
public ScheduledAction deleteScheduledAction(String scheduledActionName, String region) {
return mutate(region, scheduledActionName, () -> {
ScheduledAction existing = new ScheduledAction(require(scheduledActionName, region));
actions.delete(storageKey(region, scheduledActionName));
return existing;
});
}
/**
* Takes the snapshot of every action whose latest due time falls in {@code (checkpoint, now]}. One
* action's failure never stops the others. A deterministic entry point: the lifecycle scheduler
* supplies the clock and tests supply a fixed instant.
*/
public void runScheduledActions(Instant now) {
for (AccountEntry<ScheduledAction> entry : actions.scanAllAccountEntries(key -> true)) {
if (Thread.currentThread().isInterrupted()) {
return;
}
String region = regionOf(entry.key());
if (region == null) {
continue;
}
ReentrantLock lock = lockOf(entry.accountId(), entry.key());
lock.lock();
try {
RequestScopes.runAs(entry.accountId(), region, () -> runScheduledAction(entry, region, now));
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} in account {1} could not be processed",
entry.key(), entry.accountId());
} finally {
lock.unlock();
}
}
}
/** Runs under the action's lock, with the action's account and Region as the request scope. */
private void runScheduledAction(AccountEntry<ScheduledAction> listed, String region, Instant now) {
String accountId = listed.accountId();
String key = listed.key();
ScheduledAction action = actions.getForAccount(accountId, key).orElse(null);
if (action == null) {
return;
}
if (!isOnSameNamespace(action, region)) {
actions.deleteForAccount(accountId, key);
return;
}
if (action.getActivatedAt() == null) {
// A stored action from before scheduling existed starts counting now, without replaying history.
ScheduledAction activated = new ScheduledAction(action);
activated.setActivatedAt(now);
actions.putAllAtomicallyForAccount(accountId, Map.of(key, activated));
return;
}
Instant checkpoint = action.getLastClaimedInvocation() != null
&& action.getLastClaimedInvocation().isAfter(action.getActivatedAt())
? action.getLastClaimedInvocation() : action.getActivatedAt();
Optional<Instant> due = RedshiftServerlessSchedule.latestDue(action, checkpoint, now);
if (due.isEmpty()) {
return;
}
Instant scheduled = due.get();
ScheduledAction outcome = new ScheduledAction(action);
outcome.setLastClaimedInvocation(scheduled);
outcome.setLastFailure(null);
try {
takeSnapshot(action, accountId, region, scheduled);
outcome.setLastCompletedInvocation(scheduled);
} catch (RuntimeException e) {
LOG.warnv(e, "Scheduled action {0} in account {1} failed at {2}",
action.getScheduledActionName(), accountId, scheduled);
outcome.setLastFailure(String.valueOf(e.getMessage()));
}
recordOutcome(accountId, key, action.getScheduledActionUuid(), outcome);
}
private void takeSnapshot(ScheduledAction action, String accountId, String region, Instant scheduled) {
Namespace target = serverless.findNamespace(action.getTargetNamespaceName(), region).orElseThrow(() ->
ServerlessSupport.notFound("The namespace " + action.getTargetNamespaceName() + " was not found."));
Optional<String> refusal = authorizer.refusal(action.getRoleArn(), accountId, target.getNamespaceArn());
if (refusal.isPresent()) {
throw ServerlessSupport.validation(refusal.get());
}
serverless.createSnapshot(snapshotName(action.getSnapshotNamePrefix(), scheduled),
action.getTargetNamespaceName(), action.getRetentionPeriod(), action.getSnapshotTags(), region);
}
/** Stores the checkpoint and outcome only for the action that was run, not for a recreated one. */
private void recordOutcome(String accountId, String key, String uuid, ScheduledAction outcome) {
try {
ScheduledAction current = actions.getForAccount(accountId, key).orElse(null);
if (current != null && Objects.equals(current.getScheduledActionUuid(), uuid)) {
ScheduledAction recorded = new ScheduledAction(current);
recorded.setLastClaimedInvocation(outcome.getLastClaimedInvocation());
recorded.setLastCompletedInvocation(outcome.getLastCompletedInvocation());
recorded.setLastFailure(outcome.getLastFailure());
actions.putAllAtomicallyForAccount(accountId, Map.of(key, recorded));
}
} catch (RuntimeException e) {
LOG.warnv(e, "The outcome of scheduled action {0} in account {1} could not be stored", key, accountId);
}
}
static String snapshotName(String prefix, Instant scheduled) {
String suffix = "-" + INVOCATION_SUFFIX.format(scheduled);
String base = prefix == null ? "" : prefix.toLowerCase(Locale.ROOT);
if (base.length() + suffix.length() > MAX_SNAPSHOT_NAME_LENGTH) {
base = base.substring(0, MAX_SNAPSHOT_NAME_LENGTH - suffix.length());
}
return base + suffix;
}
@Override
public void clear() {
actions.clear();
actionLocks.clear();
}
private <T> T mutate(String region, String name, Supplier<T> body) {
ReentrantLock lock = lockOf(regionResolver.getAccountId(), storageKey(region, name));
lock.lock();
try {
synchronized (this) {
return body.get();
}
} finally {
lock.unlock();
}
}
private ReentrantLock lockOf(String accountId, String key) {
return actionLocks.computeIfAbsent(accountId + "|" + key, ignored -> new ReentrantLock());
}
private static String regionOf(String key) {
int separator = key.indexOf("::");
return separator < 0 ? null : key.substring(0, separator);
}
private ScheduledAction require(String scheduledActionName, String region) {
@@ -180,6 +363,7 @@ public class RedshiftServerlessScheduledActionService implements Resettable {
if (hasAt == hasCron) {
throw ServerlessSupport.validation("schedule must set exactly one of at and cron.");
}
RedshiftServerlessSchedule.validate(action);
}
private void validateTarget(ScheduledAction action, String region) {
@@ -187,6 +371,9 @@ public class RedshiftServerlessScheduledActionService implements Resettable {
throw ServerlessSupport.validation("targetAction must set createSnapshot.");
}
requireNamespace(action.getTargetNamespaceName(), region);
if (action.getSnapshotNamePrefix() != null) {
RedshiftServerlessService.validateSnapshotName(snapshotName(action.getSnapshotNamePrefix(), Instant.EPOCH));
}
Integer retention = action.getRetentionPeriod();
if (retention != null && retention != -1 && (retention < 1 || retention > MAX_RETENTION_DAYS)) {
throw ServerlessSupport.validation("targetAction.createSnapshot.retentionPeriod must be -1 "
@@ -1166,7 +1166,7 @@ public class RedshiftServerlessService implements Resettable {
}
}
private static void validateSnapshotName(String snapshotName) {
static void validateSnapshotName(String snapshotName) {
requireSnapshotName(snapshotName);
if (snapshotName.length() < 3 || snapshotName.length() > 255 || !SNAPSHOT_NAME.matcher(snapshotName).matches()) {
throw ServerlessSupport.validation("snapshotName must be 3-255 characters of lowercase letters, numbers, and hyphens.");
@@ -8,8 +8,8 @@ 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
* A Redshift Serverless scheduled action. The activation and invocation members are internal: the
* scheduler keeps them, and no AWS response shows them. The same type carries an update request, in which a null member
* means the caller left it out.
*/
@RegisterForReflection
@@ -33,12 +33,20 @@ public class ScheduledAction {
private String ownerId;
private boolean scheduleSpecified;
private boolean targetSpecified;
private Instant activatedAt;
private Instant lastClaimedInvocation;
private Instant lastCompletedInvocation;
private String lastFailure;
public ScheduledAction() {
}
public ScheduledAction(ScheduledAction other) {
this.ownerId = other.ownerId;
this.activatedAt = other.activatedAt;
this.lastClaimedInvocation = other.lastClaimedInvocation;
this.lastCompletedInvocation = other.lastCompletedInvocation;
this.lastFailure = other.lastFailure;
this.scheduleSpecified = other.scheduleSpecified;
this.targetSpecified = other.targetSpecified;
this.scheduledActionName = other.scheduledActionName;
@@ -192,4 +200,38 @@ public class ScheduledAction {
public void setTargetSpecified(boolean targetSpecified) {
this.targetSpecified = targetSpecified;
}
/** When the current schedule began counting, so no invocation before it is replayed. */
public Instant getActivatedAt() {
return activatedAt;
}
public void setActivatedAt(Instant activatedAt) {
this.activatedAt = activatedAt;
}
/** The latest scheduled time whose snapshot was started; it is never attempted twice. */
public Instant getLastClaimedInvocation() {
return lastClaimedInvocation;
}
public void setLastClaimedInvocation(Instant lastClaimedInvocation) {
this.lastClaimedInvocation = lastClaimedInvocation;
}
public Instant getLastCompletedInvocation() {
return lastCompletedInvocation;
}
public void setLastCompletedInvocation(Instant lastCompletedInvocation) {
this.lastCompletedInvocation = lastCompletedInvocation;
}
public String getLastFailure() {
return lastFailure;
}
public void setLastFailure(String lastFailure) {
this.lastFailure = lastFailure;
}
}