feat(dynamodb): add point-in-time recovery restores (#6110)

* feat(dynamodb): add point-in-time recovery restores

* feat(dynamodb): record a point-in-time change before the write

* feat(dynamodb): authorize RestoreTableToPointInTime on its source table

* perf(dynamodb): store each point-in-time change on its own

* feat(dynamodb): delete system backups that have expired

* chore(dynamodb): take point-in-time times from a clock in tests

* chore(dynamodb): share the duplicated test helpers and table name pattern
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-21 01:09:06 -04:00
1 parent bf82846971
commit 1dce18e766
19 files changed
+1391 -70

No files matched your search

@@ -1461,6 +1461,14 @@ public interface EmulatorConfig {
@WithDefault("10")
int vectorIndexBackfillSeconds();
/**
* Seconds LatestRestorableDateTime of point-in-time recovery trails the current time. AWS
* keeps it about five minutes behind.
* Env: FLOCI_SERVICES_DYNAMODB_LATEST_RESTORABLE_LAG_SECONDS
*/
@WithDefault("300")
int latestRestorableLagSeconds();
/** The engine behind the DynamoDB API: {@code native} or {@code local}. Env: FLOCI_SERVICES_DYNAMODB_BACKEND. */
@WithDefault("native")
String backend();
@@ -54,6 +54,11 @@ final class DynamoDbBackupArns {
+ "-" + UUID.randomUUID().toString().substring(0, 8);
}
/** AWS ends the id of a system backup with zeros instead of random hex digits. */
static String mintSystem(String tableArn, Instant creationDateTime) {
return tableArn + "/backup/" + String.format("%014d", creationDateTime.toEpochMilli()) + "-00000000";
}
private static AwsException invalidBackupArn() {
return new AwsException("ValidationException", "Invalid Backup ARN", 400);
}
@@ -0,0 +1,171 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.dynamodb.model.PointInTimeChange;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* The change history behind point-in-time recovery. A change keeps what it replaced, so a table at
* a time is the live table with every later change undone. Each change is stored on its own, under
* {@code <storage key>#<sequence>}.
*/
final class DynamoDbPointInTimeRecovery {
record RestoreWindow(Instant earliest, Instant latest) {}
/** The changes of one table, oldest first. */
private static final class Changes {
private final List<PointInTimeChange> list = new ArrayList<>();
private long nextSequence;
private boolean dropped;
}
private final StorageBackend<String, PointInTimeChange> store;
private final Duration latestLag;
private final Clock clock;
// Keyed like DynamoDbService.itemsByTable: "<account>/<region>::<table>".
private final ConcurrentHashMap<String, Changes> changesByTable = new ConcurrentHashMap<>();
DynamoDbPointInTimeRecovery(StorageBackend<String, PointInTimeChange> store, String defaultAccountId,
Duration latestLag, Clock clock) {
this.store = store;
this.latestLag = latestLag;
this.clock = clock;
Map<String, PointInTimeChange> stored = new HashMap<>();
if (store instanceof AccountAwareStorageBackend<PointInTimeChange> aware) {
stored.putAll(aware.scanAllAccountsRaw());
} else {
for (String key : store.keys()) {
store.get(key).ifPresent(change -> stored.put(defaultAccountId + "/" + key, change));
}
}
stored.forEach((key, change) -> changesByTable
.computeIfAbsent(key.substring(0, key.lastIndexOf('#')), ignored -> new Changes())
.list.add(change));
for (Changes changes : changesByTable.values()) {
changes.list.sort(Comparator.comparingLong(PointInTimeChange::getSequence));
changes.nextSequence = changes.list.getLast().getSequence() + 1;
}
}
void clear() {
changesByTable.clear();
}
/** Call after point-in-time recovery of the table is turned off, so no writer records again. */
void drop(String accountId, String storageKey) {
Changes changes = changesByTable.remove(key(accountId, storageKey));
if (changes == null) {
return;
}
synchronized (changes) {
changes.dropped = true;
for (PointInTimeChange change : changes.list) {
delete(accountId, storageKey, change);
}
}
}
/** Call before the item is written. */
void recordItem(String accountId, String storageKey, TableDefinition table, String itemKey, JsonNode oldItem) {
if (!table.isPointInTimeRecoveryEnabled()) {
return;
}
Changes changes = changesByTable.computeIfAbsent(key(accountId, storageKey), ignored -> new Changes());
synchronized (changes) {
if (changes.dropped || !table.isPointInTimeRecoveryEnabled()) {
return;
}
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
PointInTimeChange change = new PointInTimeChange(changes.nextSequence++, now, itemKey,
oldItem != null ? oldItem.deepCopy() : null);
changes.list.add(change);
put(accountId, storageKey, change);
Instant cutoff = now.minus(recoveryPeriod(table));
int expired = 0;
while (expired < changes.list.size() && changes.list.get(expired).getTime().isBefore(cutoff)) {
delete(accountId, storageKey, changes.list.get(expired));
expired++;
}
changes.list.subList(0, expired).clear();
}
}
/** AWS words an InvalidRestoreTimeException with the latest time to the nanosecond. */
RestoreWindow window(TableDefinition table) {
Instant now = clock.instant();
Instant earliest = later(table.getPointInTimeRecoveryStartDateTime(), now.minus(recoveryPeriod(table)));
return new RestoreWindow(earliest, later(earliest, now.minus(latestLag)));
}
/**
* An item changed after {@code time} takes the value that its first change after it replaced.
* Writers record a change before they write the item, so the live items are copied first.
*/
List<JsonNode> itemsAt(String accountId, String storageKey, Map<String, JsonNode> liveItems, Instant time) {
Map<String, JsonNode> items = new HashMap<>(liveItems);
Changes changes = changesByTable.get(key(accountId, storageKey));
if (changes != null) {
Set<String> undone = new HashSet<>();
synchronized (changes) {
for (PointInTimeChange change : changes.list) {
String itemKey = change.getItemKey();
if (!change.getTime().isAfter(time) || !undone.add(itemKey)) {
continue;
}
if (change.getOldItem() == null) {
items.remove(itemKey);
} else {
items.put(itemKey, change.getOldItem());
}
}
}
}
return new ArrayList<>(items.values());
}
private void put(String accountId, String storageKey, PointInTimeChange change) {
String key = storageKey + "#" + change.getSequence();
if (store instanceof AccountAwareStorageBackend<PointInTimeChange> aware) {
aware.putForAccount(accountId, key, change);
} else {
store.put(key, change);
}
}
private void delete(String accountId, String storageKey, PointInTimeChange change) {
String key = storageKey + "#" + change.getSequence();
if (store instanceof AccountAwareStorageBackend<PointInTimeChange> aware) {
aware.deleteForAccount(accountId, key);
} else {
store.delete(key);
}
}
private static Duration recoveryPeriod(TableDefinition table) {
return Duration.ofDays(table.getPointInTimeRecoveryRecoveryPeriodInDays());
}
private static Instant later(Instant a, Instant b) {
return a.isAfter(b) ? a : b;
}
private static String key(String accountId, String storageKey) {
return accountId + "/" + storageKey;
}
}
@@ -29,6 +29,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.ImportSummary;
import io.github.hectorvent.floci.services.dynamodb.model.ImportTableDescription;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.PointInTimeChange;
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
import io.github.hectorvent.floci.services.dynamodb.model.TableBackup;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
@@ -47,6 +48,7 @@ import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@@ -103,6 +105,8 @@ public class DynamoDbService {
private final StorageBackend<String, ExportDescription> exportStore;
private final StorageBackend<String, ImportTableDescription> importStore;
private final StorageBackend<String, TableBackup> backupStore;
private final DynamoDbPointInTimeRecovery pointInTimeRecovery;
private final Clock clock;
// Items stored per table: storageKey -> Map<itemKey, item>
// itemKey is "pk" or "pk#sk" depending on table schema
private final ConcurrentHashMap<String, ConcurrentSkipListMap<String, JsonNode>> itemsByTable = new ConcurrentHashMap<>();
@@ -170,9 +174,12 @@ public class DynamoDbService {
new TypeReference<Map<String, ImportTableDescription>>() {}),
storageFactory.create("dynamodb", "dynamodb-backups.json",
new TypeReference<Map<String, TableBackup>>() {}),
storageFactory.create("dynamodb", "dynamodb-point-in-time.json",
new TypeReference<Map<String, PointInTimeChange>>() {}),
regionResolver, streamService, kinesisForwarder, s3Service, objectMapper,
config.services().dynamodb().vectorIndexAllocationSeconds(),
config.services().dynamodb().vectorIndexBackfillSeconds());
config.services().dynamodb().vectorIndexBackfillSeconds(),
config.services().dynamodb().latestRestorableLagSeconds(), Clock.systemUTC());
}
/** Package-private constructor for testing. */
@@ -239,11 +246,34 @@ public class DynamoDbService {
ObjectMapper objectMapper,
int vectorIndexAllocationSeconds,
int vectorIndexBackfillSeconds) {
this(tableStore, itemStore, exportStore, importStore, backupStore, new InMemoryStorage<>(), regionResolver,
streamService, kinesisForwarder, s3Service, objectMapper,
vectorIndexAllocationSeconds, vectorIndexBackfillSeconds, 0, Clock.systemUTC());
}
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
StorageBackend<String, Map<String, JsonNode>> itemStore,
StorageBackend<String, ExportDescription> exportStore,
StorageBackend<String, ImportTableDescription> importStore,
StorageBackend<String, TableBackup> backupStore,
StorageBackend<String, PointInTimeChange> pointInTimeStore,
RegionResolver regionResolver,
DynamoDbStreamService streamService,
KinesisStreamingForwarder kinesisForwarder,
S3Service s3Service,
ObjectMapper objectMapper,
int vectorIndexAllocationSeconds,
int vectorIndexBackfillSeconds,
int latestRestorableLagSeconds,
Clock clock) {
this.tableStore = tableStore;
this.itemStore = itemStore;
this.exportStore = exportStore;
this.importStore = importStore;
this.backupStore = backupStore;
this.pointInTimeRecovery = new DynamoDbPointInTimeRecovery(pointInTimeStore, regionResolver.getAccountId(),
Duration.ofSeconds(latestRestorableLagSeconds), clock);
this.clock = clock;
this.regionResolver = regionResolver;
this.streamService = streamService;
this.kinesisForwarder = kinesisForwarder;
@@ -260,6 +290,7 @@ public class DynamoDbService {
itemsByTable.clear();
itemLocks.clear();
txIdempotency.clear();
pointInTimeRecovery.clear();
if (streamService != null) {
streamService.clear();
}
@@ -859,6 +890,12 @@ public class DynamoDbService {
"Attempt to change a resource which is still in use: Cannot delete table while "
+ "indexes are being created, updated, or deleted.", 400);
}
if (table.isPointInTimeRecoveryEnabled()) {
createSystemBackup(storageKey, table, region);
}
// A write still in flight on this table object stops recording once the flag is off.
table.setPointInTimeRecoveryEnabled(false);
pointInTimeRecovery.drop(regionResolver.getAccountId(), storageKey);
tableStore.delete(storageKey);
itemsByTable.remove(scopedItemsKey(storageKey));
itemLocks.remove(scopedItemsKey(storageKey));
@@ -980,6 +1017,9 @@ public class DynamoDbService {
}
requireItemNestingWithinLimit(normalizedItem);
if (stagedItems == null) {
pointInTimeRecovery.recordItem(regionResolver.getAccountId(), storageKey, table, itemKey, existing);
}
tableItems.put(itemKey, normalizedItem);
if (shouldPersist) {
persistItems(storageKey);
@@ -1078,6 +1118,10 @@ public class DynamoDbService {
evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure);
}
JsonNode current = items.get(itemKey);
if (stagedItems == null && current != null) {
pointInTimeRecovery.recordItem(regionResolver.getAccountId(), storageKey, table, itemKey, current);
}
JsonNode removed = items.remove(itemKey);
if (shouldPersist) {
persistItems(storageKey);
@@ -1291,6 +1335,9 @@ public class DynamoDbService {
requireUpdatedItemWithinSizeLimit(item);
}
if (stagedItems == null) {
pointInTimeRecovery.recordItem(regionResolver.getAccountId(), storageKey, table, itemKey, existing);
}
items.put(itemKey, item);
if (shouldPersist) {
persistItems(storageKey);
@@ -1881,6 +1928,12 @@ public class DynamoDbService {
scopedItemsKey(participant.storageKey()), ignored -> new ConcurrentSkipListMap<>());
ConcurrentSkipListMap<String, JsonNode> stagedTable = staged.get(participant.storageKey());
JsonNode value = stagedTable.get(participant.itemKey());
JsonNode before = live.get(participant.itemKey());
if (value != before) {
tableStore.get(participant.storageKey()).ifPresent(participantTable -> pointInTimeRecovery.recordItem(
regionResolver.getAccountId(), participant.storageKey(), participantTable,
participant.itemKey(), before));
}
if (value == null) {
live.remove(participant.itemKey());
} else {
@@ -2683,21 +2736,149 @@ public class DynamoDbService {
LOG.infov("Updated TTL for table {0}: enabled={1}, attr={2}", canonicalTableName, enabled, ttlAttributeName);
}
public TableDefinition updateContinuousBackups(String tableName, boolean enabled,
Integer recoveryPeriodInDays, String region) {
/** The restore window is null while point-in-time recovery is disabled. */
public record ContinuousBackups(TableDefinition table, DynamoDbPointInTimeRecovery.RestoreWindow window) {}
/** The items of a source table as they were at {@code restoreDateTime}, with its current settings, as on AWS. */
public record PointInTimeState(TableDefinition table, List<JsonNode> items, Instant restoreDateTime) {}
public ContinuousBackups describeContinuousBackups(String tableName, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
return continuousBackups(storageKey, requireBackupSource(storageKey, canonicalTableName));
}
/** Enabling a disabled table starts the restore window over, as on AWS. */
public ContinuousBackups updateContinuousBackups(String tableName, boolean enabled,
Integer recoveryPeriodInDays, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = requireBackupSource(storageKey, canonicalTableName);
if (enabled && !table.isPointInTimeRecoveryEnabled()) {
pointInTimeRecovery.drop(regionResolver.getAccountId(), storageKey);
table.setPointInTimeRecoveryStartDateTime(clock.instant().truncatedTo(ChronoUnit.SECONDS));
table.setPointInTimeRecoveryRecoveryPeriodInDays(DEFAULT_RECOVERY_PERIOD_DAYS);
} else if (enabled && recoveryPeriodInDays != null) {
// AWS keeps the earliest time when the period grows, until the longer period has passed.
table.setPointInTimeRecoveryStartDateTime(
pointInTimeRecovery.window(withPointInTimeStart(storageKey, table)).earliest());
}
table.setPointInTimeRecoveryEnabled(enabled);
table.setPointInTimeRecoveryRecoveryPeriodInDays(
recoveryPeriodInDays != null ? recoveryPeriodInDays : table.getPointInTimeRecoveryRecoveryPeriodInDays());
if (!enabled) {
table.setPointInTimeRecoveryStartDateTime(null);
pointInTimeRecovery.drop(regionResolver.getAccountId(), storageKey);
}
if (recoveryPeriodInDays != null) {
table.setPointInTimeRecoveryRecoveryPeriodInDays(recoveryPeriodInDays);
}
tableStore.put(storageKey, table);
LOG.infov("Updated PITR for table {0}: enabled={1}, recoveryPeriodInDays={2}",
canonicalTableName, enabled, table.getPointInTimeRecoveryRecoveryPeriodInDays());
return continuousBackups(storageKey, table);
}
/**
* The checks run in the AWS order: the source table, the presence of a restore time, point-in-time
* recovery on the source, then the restore time. AWS restores any time up to now, although it
* reports a LatestRestorableDateTime minutes earlier and names only that one in the error.
*/
public PointInTimeState pointInTimeState(String sourceTableName, String sourceRegion, String region,
boolean useLatestRestorableTime, Instant restoreDateTime) {
String canonicalTableName = canonicalTableName(sourceRegion, sourceTableName);
String storageKey = regionKey(sourceRegion, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> new AwsException("TableNotFoundException", sourceRegion.equals(region)
? "Table not found: " + canonicalTableName : "Table not found", 400));
if ("CREATING".equals(table.getTableStatus())) {
throw new AwsException("TableNotFoundException", "Table not found", 400);
}
if (!useLatestRestorableTime && restoreDateTime == null) {
throw new AwsException("ValidationException", "Invalid Request: Either one of RestoreDateTime or "
+ "UseLatestRestorableTime must be specified, but not both", 400);
}
if (!table.isPointInTimeRecoveryEnabled()) {
throw new AwsException("PointInTimeRecoveryUnavailableException",
"Point in time recovery is not enabled for table '" + canonicalTableName + "'", 400);
}
String accountId = regionResolver.getAccountId();
DynamoDbPointInTimeRecovery.RestoreWindow window =
pointInTimeRecovery.window(withPointInTimeStart(storageKey, table));
Instant time = useLatestRestorableTime ? window.latest() : restoreDateTime;
if (time.isBefore(window.earliest()) || clock.instant().isBefore(time)) {
throw new AwsException("InvalidRestoreTimeException", "RestoreDateTime '" + time
+ "' must be within EarliestRestorableDateTime '" + window.earliest()
+ "' and LatestRestorableDateTime '" + window.latest() + "' for table '"
+ canonicalTableName + "'", 400);
}
ConcurrentSkipListMap<String, JsonNode> liveItems = itemsByTable.get(scopedItemsKey(storageKey));
List<JsonNode> items = pointInTimeRecovery.itemsAt(accountId, storageKey,
liveItems != null ? liveItems : Map.of(), time);
return new PointInTimeState(snapshotOf(table), items, time);
}
/**
* The table a SourceTableArn names. AWS restores across regions only with an
* SSESpecificationOverride, and treats an unknown region as another region.
*/
public DynamoDbTableNames.ResolvedTableRef pointInTimeSourceArn(String sourceTableArn, String region,
boolean sseOverride) {
if (!sourceTableArn.startsWith("arn:")) {
throw invalidParameter("ARNs must start with 'arn:': " + sourceTableArn);
}
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(sourceTableArn);
} catch (IllegalArgumentException e) {
throw invalidParameter("sourceTableArn is not a valid ARN");
}
if (!"dynamodb".equals(arn.service())) {
throw invalidParameter("Invalid resource Arn: " + sourceTableArn);
}
if (!arn.resource().startsWith("table/")) {
throw invalidParameter("sourceTableArn is not a valid ARN");
}
String tableName = arn.resource().substring("table/".length());
if (tableName.length() < 3 || 255 < tableName.length()
|| !DynamoDbTableNames.TABLE_NAME_CHARS.matcher(tableName).matches()) {
throw new AwsException("ValidationException", "Invalid Request: Invalid TableArn: Invalid Table ARN", 400);
}
if (!arn.accountId().equals(regionResolver.getAccountId())) {
throw new AwsException("ValidationException",
"This action is only supported by accounts that match the resource owner’s account.", 400);
}
if (!arn.region().equals(region) && !sseOverride) {
throw new AwsException("ValidationException",
"Invalid Request: sseSpecificationOverride must be provided for cross-region restores", 400);
}
return new DynamoDbTableNames.ResolvedTableRef(tableName, arn.region());
}
private static AwsException invalidParameter(String message) {
return new AwsException("ValidationException", "One or more parameter values were invalid: " + message, 400);
}
private ContinuousBackups continuousBackups(String storageKey, TableDefinition table) {
return new ContinuousBackups(table, table.isPointInTimeRecoveryEnabled()
? pointInTimeRecovery.window(withPointInTimeStart(storageKey, table))
: null);
}
/** A table that had point-in-time recovery enabled before Floci kept a history starts one now. */
private TableDefinition withPointInTimeStart(String storageKey, TableDefinition table) {
if (table.getPointInTimeRecoveryStartDateTime() == null) {
table.setPointInTimeRecoveryStartDateTime(clock.instant().truncatedTo(ChronoUnit.SECONDS));
tableStore.put(storageKey, table);
}
return table;
}
/** The backup operations do not see a table that a restore is still creating. */
private TableDefinition requireBackupSource(String storageKey, String tableName) {
return tableStore.get(storageKey)
.filter(t -> !"CREATING".equals(t.getTableStatus()))
.orElseThrow(() -> new AwsException("TableNotFoundException", "Table not found: " + tableName, 400));
}
static boolean isExpired(JsonNode item, TableDefinition table) {
if (!table.isTtlEnabled() || table.getTtlAttributeName() == null) return false;
JsonNode attr = item.get(table.getTtlAttributeName());
@@ -2713,8 +2894,10 @@ public class DynamoDbService {
TableDefinition table, List<String> itemKeys,
ConcurrentSkipListMap<String, JsonNode> items) {}
/** The TTL sweep also removes the system backups past their expiry. */
void deleteExpiredItems() {
deleteScannedItems(scanExpiredItems());
deleteExpiredBackups();
}
List<ExpiredTableScan> scanExpiredItems() {
@@ -2771,6 +2954,7 @@ public class DynamoDbService {
if (current == null || !isExpired(current, scan.table())) {
return null;
}
pointInTimeRecovery.recordItem(scan.accountId(), scan.storageKey(), scan.table(), itemKey, current);
return items.remove(itemKey);
});
if (removed == null) {
@@ -4811,6 +4995,9 @@ public class DynamoDbService {
// The live table object is shared and later mutated in place, so a backup keeps its own copy.
private static final ObjectMapper SNAPSHOT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());
private static final int DEFAULT_RECOVERY_PERIOD_DAYS = 35;
private static final int SYSTEM_BACKUP_RETENTION_DAYS = 35;
private static final Comparator<TableBackup> BACKUP_ORDER = Comparator
.comparing(TableBackup::getCreationDateTime)
.thenComparing(TableBackup::getBackupArn);
@@ -4824,6 +5011,29 @@ public class DynamoDbService {
.filter(t -> !"CREATING".equals(t.getTableStatus()))
.orElseThrow(() -> new AwsException("TableNotFoundException",
"Table not found: " + canonicalTableName, 400));
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
TableBackup backup = backupOf(storageKey, table, DynamoDbBackupArns.mint(table.getTableArn(), now), now);
backup.setBackupName(backupName);
backup.setBackupType("USER");
backup.setRegion(region);
backupStore.put(backup.getBackupArn(), backup);
LOG.infov("Created backup {0} of table {1}", backup.getBackupArn(), canonicalTableName);
return backup;
}
/** AWS keeps the backup it takes of a deleted table with point-in-time recovery for 35 days. */
private void createSystemBackup(String storageKey, TableDefinition table, String region) {
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
TableBackup backup = backupOf(storageKey, table, DynamoDbBackupArns.mintSystem(table.getTableArn(), now), now);
backup.setBackupName(table.getTableName() + "$DeletedTableBackup");
backup.setBackupType("SYSTEM");
backup.setExpiryDateTime(now.plus(Duration.ofDays(SYSTEM_BACKUP_RETENTION_DAYS)));
backup.setRegion(region);
backupStore.put(backup.getBackupArn(), backup);
LOG.infov("Created system backup {0} of deleted table {1}", backup.getBackupArn(), table.getTableName());
}
private TableBackup backupOf(String storageKey, TableDefinition table, String backupArn, Instant now) {
ConcurrentSkipListMap<String, JsonNode> items = itemsByTable.get(scopedItemsKey(storageKey));
List<JsonNode> snapshot = new ArrayList<>();
if (items != null) {
@@ -4832,18 +5042,12 @@ public class DynamoDbService {
TableDefinition source = snapshotOf(table);
source.setItemCount(snapshot.size());
Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
TableBackup backup = new TableBackup();
backup.setBackupArn(DynamoDbBackupArns.mint(table.getTableArn(), now));
backup.setBackupName(backupName);
backup.setBackupType("USER");
backup.setBackupArn(backupArn);
backup.setCreationDateTime(now);
backup.setSizeBytes(source.getTableSizeBytes());
backup.setRegion(region);
backup.setTable(source);
backup.setItems(snapshot);
backupStore.put(backup.getBackupArn(), backup);
LOG.infov("Created backup {0} of table {1}", backup.getBackupArn(), canonicalTableName);
return backup;
}
@@ -4854,12 +5058,18 @@ public class DynamoDbService {
}
return backupStore.get(backupArn)
.filter(backup -> backup.getRegion().equals(region))
.filter(this::isUnexpired)
.orElseThrow(() -> new AwsException("BackupNotFoundException",
"Backup not found: " + backupArn, 400));
}
public TableBackup deleteBackup(String backupArn, String region) {
TableBackup backup = describeBackup(backupArn, region);
if ("SYSTEM".equals(backup.getBackupType())) {
throw new AwsException("ValidationException", "Invalid Request: User is not allowed to delete the "
+ "system backup with arn " + backupArn + ". It will automatically expire on "
+ backup.getExpiryDateTime(), 400);
}
backupStore.delete(backupArn);
LOG.infov("Deleted backup {0}", backupArn);
return backup;
@@ -4876,6 +5086,7 @@ public class DynamoDbService {
Set<String> types = "ALL".equals(backupType) ? Set.of("USER", "SYSTEM") : Set.of(backupType);
List<TableBackup> matching = backupStore.scan(key -> true).stream()
.filter(backup -> backup.getRegion().equals(region))
.filter(this::isUnexpired)
.filter(backup -> tableName == null || tableName.equals(backup.getTable().getTableName()))
.filter(backup -> types.contains(backup.getBackupType()))
.filter(backup -> lowerBound == null || !backup.getCreationDateTime().isBefore(lowerBound))
@@ -4919,6 +5130,21 @@ public class DynamoDbService {
LOG.infov("Restored {0} items into table {1}", items.size(), tableName);
}
private void deleteExpiredBackups() {
if (backupStore instanceof AccountAwareStorageBackend<TableBackup> aware) {
aware.deleteAllAccountsMatching(backup -> !isUnexpired(backup));
return;
}
for (String backupArn : new ArrayList<>(backupStore.keys())) {
backupStore.get(backupArn).filter(backup -> !isUnexpired(backup))
.ifPresent(backup -> backupStore.delete(backupArn));
}
}
private boolean isUnexpired(TableBackup backup) {
return backup.getExpiryDateTime() == null || clock.instant().isBefore(backup.getExpiryDateTime());
}
private static boolean isAfter(TableBackup backup, DynamoDbBackupArns.BackupArn start) {
int byTime = Long.compare(backup.getCreationDateTime().toEpochMilli(), start.creationMillis());
return 0 < byTime || (byTime == 0 && 0 < backup.getBackupArn().compareTo(start.arn()));
@@ -12,7 +12,7 @@ import java.util.regex.Pattern;
*/
public final class DynamoDbTableNames {
private static final Pattern TABLE_NAME_CHARS = Pattern.compile("[a-zA-Z0-9_.\\-]+");
static final Pattern TABLE_NAME_CHARS = Pattern.compile("[a-zA-Z0-9_.\\-]+");
private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
private DynamoDbTableNames() {}
@@ -60,6 +60,7 @@ public class NativeDynamoDbJsonHandler {
// The order AWS prints the enum constraint in.
private static final List<String> BACKUP_TYPE_FILTERS = List.of("ALL", "AWS_BACKUP", "USER", "SYSTEM");
private static final int MAX_LIST_BACKUPS_LIMIT = 100;
private static final int MAX_RECOVERY_PERIOD_DAYS = 35;
private final DynamoDbService dynamoDbService;
private final NativeDynamoDbTableService tableService;
@@ -108,6 +109,7 @@ public class NativeDynamoDbJsonHandler {
case "ListBackups" -> handleListBackups(request, region);
case "DeleteBackup" -> handleDeleteBackup(request, region);
case "RestoreTableFromBackup" -> handleRestoreTableFromBackup(request, region);
case "RestoreTableToPointInTime" -> handleRestoreTableToPointInTime(request, region);
case "TransactWriteItems" -> handleTransactWriteItems(request, region);
case "TransactGetItems" -> handleTransactGetItems(request, region);
case "TagResource" -> handleTagResource(request, region);
@@ -1864,31 +1866,50 @@ public class NativeDynamoDbJsonHandler {
}
private Response handleDescribeContinuousBackups(JsonNode request, String region) {
String tableName = request.path("TableName").asText();
TableDefinition table = dynamoDbService.describeTable(tableName, region);
String tableName = requireTableNameParameter(request, "TableName");
DynamoDbTableNames.resolveWithRegion(tableName, region);
DynamoDbService.ContinuousBackups backups = dynamoDbService.describeContinuousBackups(tableName, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table));
response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(backups));
return Response.ok(response).build();
}
private Response handleUpdateContinuousBackups(JsonNode request, String region) {
String tableName = request.path("TableName").asText();
String tableName = requireTableNameParameter(request, "TableName");
DynamoDbTableNames.resolveWithRegion(tableName, region);
JsonNode spec = request.path("PointInTimeRecoverySpecification");
boolean enabled = spec.path("PointInTimeRecoveryEnabled").asBoolean(false);
Integer recoveryPeriodInDays = spec.has("RecoveryPeriodInDays")
? spec.path("RecoveryPeriodInDays").asInt()
: null;
if (recoveryPeriodInDays != null && (recoveryPeriodInDays < 1 || recoveryPeriodInDays > 35)) {
if (spec.isMissingNode() || spec.isNull()) {
throwValidationErrors(List.of("Value null at 'pointInTimeRecoverySpecification' failed to satisfy "
+ "constraint: Member must not be null"));
}
List<String> violations = new ArrayList<>();
JsonNode period = spec.path("RecoveryPeriodInDays");
String periodConstraint = "Value '" + period.asText() + "' at 'pointInTimeRecoverySpecification."
+ "recoveryPeriodInDays' failed to satisfy constraint: ";
if (period.isNumber() && period.asLong() < 1) {
violations.add(periodConstraint + "Member must have value greater than or equal to 1");
}
if (period.isNumber() && MAX_RECOVERY_PERIOD_DAYS < period.asLong()) {
violations.add(periodConstraint + "Member must have value less than or equal to " + MAX_RECOVERY_PERIOD_DAYS);
}
JsonNode enabled = spec.path("PointInTimeRecoveryEnabled");
if (enabled.isMissingNode() || enabled.isNull()) {
violations.add("Value null at 'pointInTimeRecoverySpecification.pointInTimeRecoveryEnabled' failed to "
+ "satisfy constraint: Member must not be null");
}
throwValidationErrors(violations);
Integer recoveryPeriodInDays = period.isNumber() ? period.asInt() : null;
if (!enabled.asBoolean() && recoveryPeriodInDays != null) {
throw new AwsException("ValidationException",
"RecoveryPeriodInDays must be between 1 and 35", 400);
"Invalid Request: Cannot specify RecoveryPeriodInDays when disabling point-in-time recovery.", 400);
}
TableDefinition table = dynamoDbService.updateContinuousBackups(
tableName, enabled, recoveryPeriodInDays, region);
DynamoDbService.ContinuousBackups backups = dynamoDbService.updateContinuousBackups(
tableName, enabled.asBoolean(), recoveryPeriodInDays, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(table));
response.set("ContinuousBackupsDescription", continuousBackupsDescriptionNode(backups));
return Response.ok(response).build();
}
@@ -1975,6 +1996,76 @@ public class NativeDynamoDbJsonHandler {
String backupArn = textOrNull(request, "BackupArn");
DynamoDbBackupArns.parse(backupArn);
String targetTableName = requireTableNameParameter(request, "TargetTableName");
throwValidationErrors(restoreViolations(request, targetTableName));
TableBackup backup = dynamoDbService.describeBackup(backupArn, region);
TableDefinition table = tableService.restoreTable(DynamoDbService.snapshotOf(backup.getTable()),
targetTableName, parseRestoreOverrides(request), region);
ObjectNode description = tableToNode(table);
description.set("RestoreSummary", restoreSummaryNode(backup.getBackupArn(),
backup.getTable().getTableArn(), backup.getCreationDateTime()));
dynamoDbService.finishRestore(targetTableName, backup.getItems(), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("TableDescription", description);
return Response.ok(response).build();
}
/**
* Restores synchronously, like {@link #handleRestoreTableFromBackup}. AWS checks a source table
* name for its length before the validation list, and a source table ARN before both.
*/
private Response handleRestoreTableToPointInTime(JsonNode request, String region) {
String targetTableName = requireTableNameParameter(request, "TargetTableName");
String sourceTableName = textOrNull(request, "SourceTableName");
String sourceTableArn = textOrNull(request, "SourceTableArn");
if (sourceTableName == null && sourceTableArn == null) {
requireTableNameParameter(request, "SourceTableName");
}
DynamoDbTableNames.ResolvedTableRef source;
if (sourceTableArn != null) {
source = dynamoDbService.pointInTimeSourceArn(sourceTableArn, region,
request.path("SSESpecificationOverride").isObject());
} else if (sourceTableName.length() < 3 || 255 < sourceTableName.length()) {
throw new AwsException("ValidationException",
"TableName must be at least 3 characters long and at most 255 characters long", 400);
} else {
source = new DynamoDbTableNames.ResolvedTableRef(sourceTableName, region);
}
List<String> violations = new ArrayList<>();
if (sourceTableName != null) {
violations.addAll(nameViolations(sourceTableName, "sourceTableName"));
}
violations.addAll(restoreViolations(request, targetTableName));
throwValidationErrors(violations);
if (sourceTableName != null && sourceTableArn != null) {
throw new AwsException("ValidationException",
"Invalid Request: Must provide exactly one of: sourceTableArn, sourceTableName", 400);
}
boolean useLatestRestorableTime = request.path("UseLatestRestorableTime").asBoolean(false);
Instant restoreDateTime = timestampOrNull(request, "RestoreDateTime");
if (useLatestRestorableTime && restoreDateTime != null) {
throw new AwsException("ValidationException", "Invalid Request: Both RestoreDateTime and "
+ "UseLatestRestorableTime cannot be set for point-in-time restore request. Please specify "
+ "either RestoreDateTime time or UseLatestRestorableTime", 400);
}
DynamoDbService.PointInTimeState state = dynamoDbService.pointInTimeState(source.name(), source.region(),
region, useLatestRestorableTime, restoreDateTime);
TableDefinition table = tableService.restoreTable(state.table(), targetTableName,
parseRestoreOverrides(request), region);
ObjectNode description = tableToNode(table);
description.set("RestoreSummary", restoreSummaryNode(null, state.table().getTableArn(),
state.restoreDateTime()));
dynamoDbService.finishRestore(targetTableName, state.items(), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("TableDescription", description);
return Response.ok(response).build();
}
/** The validation list both restores share, in the AWS order. */
private static List<String> restoreViolations(JsonNode request, String targetTableName) {
List<String> violations = new ArrayList<>(throughputViolations(request.path("ProvisionedThroughputOverride"),
"provisionedThroughputOverride"));
JsonNode billingModeOverride = request.path("BillingModeOverride");
@@ -1995,19 +2086,7 @@ public class NativeDynamoDbJsonHandler {
member + ".provisionedThroughput"));
}
}
throwValidationErrors(violations);
TableBackup backup = dynamoDbService.describeBackup(backupArn, region);
TableDefinition table = tableService.restoreTable(DynamoDbService.snapshotOf(backup.getTable()),
targetTableName, parseRestoreOverrides(request), region);
ObjectNode description = tableToNode(table);
description.set("RestoreSummary", restoreSummaryNode(backup.getBackupArn(),
backup.getTable().getTableArn(), backup.getCreationDateTime()));
dynamoDbService.finishRestore(targetTableName, backup.getItems(), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("TableDescription", description);
return Response.ok(response).build();
return violations;
}
private static RestoreOverrides parseRestoreOverrides(JsonNode request) {
@@ -3280,15 +3359,20 @@ public class NativeDynamoDbJsonHandler {
return vectorIndexNode;
}
private ObjectNode continuousBackupsDescriptionNode(TableDefinition table) {
/** AWS also answers PointInTimeRecoveryWindowDays, a member its API model does not list. */
private ObjectNode continuousBackupsDescriptionNode(DynamoDbService.ContinuousBackups backups) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ContinuousBackupsStatus", "ENABLED");
ObjectNode pitrNode = objectMapper.createObjectNode();
TableDefinition table = backups.table();
pitrNode.put("PointInTimeRecoveryStatus",
table.isPointInTimeRecoveryEnabled() ? "ENABLED" : "DISABLED");
if (table.isPointInTimeRecoveryEnabled()) {
if (backups.window() != null) {
pitrNode.put("EarliestRestorableDateTime", epochSeconds(backups.window().earliest()));
pitrNode.put("LatestRestorableDateTime", epochSeconds(backups.window().latest()));
pitrNode.put("RecoveryPeriodInDays", table.getPointInTimeRecoveryRecoveryPeriodInDays());
pitrNode.put("PointInTimeRecoveryWindowDays", table.getPointInTimeRecoveryRecoveryPeriodInDays());
}
node.set("PointInTimeRecoveryDescription", pitrNode);
return node;
@@ -181,10 +181,10 @@ public class NativeDynamoDbTableService {
}
/**
* Creates the target of a restore in CREATING from {@code source}, a copy of the table the
* backup holds, with the request's overrides applied. Like AWS, the new table gets the keys,
* indexes, capacity and encryption, and none of the stream, TTL, point-in-time recovery, tags,
* deletion protection or table class.
* Creates the target of a restore in CREATING from {@code source}, a copy of the table a backup
* holds or of the source of a point-in-time restore, with the request's overrides applied. Like
* AWS, the new table gets the keys, indexes, capacity and encryption, and none of the stream,
* TTL, point-in-time recovery, tags, deletion protection or table class.
*/
TableDefinition restoreTable(TableDefinition source, String targetTableName, RestoreOverrides overrides,
String region) {
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.dynamodb.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* One item change to a table with point-in-time recovery enabled. {@code oldItem} is what the change
* replaced, null when it created the item.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class PointInTimeChange {
private long sequence;
private Instant time;
private String itemKey;
private JsonNode oldItem;
public PointInTimeChange() {
}
public PointInTimeChange(long sequence, Instant time, String itemKey, JsonNode oldItem) {
this.sequence = sequence;
this.time = time;
this.itemKey = itemKey;
this.oldItem = oldItem;
}
public long getSequence() { return sequence; }
public void setSequence(long sequence) { this.sequence = sequence; }
public Instant getTime() { return time; }
public void setTime(Instant time) { this.time = time; }
public String getItemKey() { return itemKey; }
public void setItemKey(String itemKey) { this.itemKey = itemKey; }
public JsonNode getOldItem() { return oldItem; }
// Jackson reads a stored null into a JsonNode as NullNode.
public void setOldItem(JsonNode oldItem) { this.oldItem = oldItem != null && oldItem.isNull() ? null : oldItem; }
}
@@ -37,6 +37,7 @@ public class TableDefinition {
private boolean ttlEnabled;
private boolean pointInTimeRecoveryEnabled;
private int pointInTimeRecoveryRecoveryPeriodInDays;
private Instant pointInTimeRecoveryStartDateTime;
private boolean deletionProtectionEnabled;
private boolean streamEnabled;
private String streamArn;
@@ -169,6 +170,11 @@ public class TableDefinition {
this.pointInTimeRecoveryRecoveryPeriodInDays = pointInTimeRecoveryRecoveryPeriodInDays;
}
public Instant getPointInTimeRecoveryStartDateTime() { return pointInTimeRecoveryStartDateTime; }
public void setPointInTimeRecoveryStartDateTime(Instant pointInTimeRecoveryStartDateTime) {
this.pointInTimeRecoveryStartDateTime = pointInTimeRecoveryStartDateTime;
}
public boolean isDeletionProtectionEnabled() { return deletionProtectionEnabled; }
public void setDeletionProtectionEnabled(boolean deletionProtectionEnabled) { this.deletionProtectionEnabled = deletionProtectionEnabled; }
@@ -977,6 +977,19 @@ public class ResourceArnBuilder {
return List.of(importArn);
}
}
// AWS authorizes RestoreTableToPointInTime on its source table.
if (json.hasNonNull("SourceTableArn")) {
String sourceTableArn = json.get("SourceTableArn").asText().trim();
if (!sourceTableArn.isEmpty()) {
return List.of(sourceTableArn);
}
}
if (json.hasNonNull("SourceTableName")) {
String sourceTableName = json.get("SourceTableName").asText().trim();
if (!sourceTableName.isEmpty()) {
return List.of(toDynamoDbTableArn(sourceTableName, region, accountId));
}
}
if (json.hasNonNull("RequestItems") && json.get("RequestItems").isObject()) {
Set<String> arns = new LinkedHashSet<>();
Iterator<String> fieldNames = json.get("RequestItems").fieldNames();