Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): stop getSortKeyNames() from corrupting persisted tables (#2463)
Matheus Oliveira726c9c7446b8
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/GlobalSecondaryIndex.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/GlobalSecondaryIndex.javaindex 40c66a7218..5cd7e1e268 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/GlobalSecondaryIndex.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/GlobalSecondaryIndex.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb.model;+import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.quarkus.runtime.annotations.RegisterForReflection;@@ -82,7 +83,13 @@ public class GlobalSecondaryIndex {/*** Returns all sort key attribute names in key-schema order. For a composite sort key this* contains more than one element; ordering must consider all of them, not just the first.+ *+ * <p>{@code @JsonIgnore}d: it is derived from {@code keySchema} (redundant with+ * {@link #getSortKeyName()}), and without a backing setter Jackson's getter-as-setter+ * fallback tries to append into the immutable list this method returns, throwing+ * {@code UnsupportedOperationException} on deserialization whenever the index has a sort key.*/+ @JsonIgnorepublic List<String> getSortKeyNames() {return keySchema.stream().filter(k -> "RANGE".equals(k.getKeyType()))diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/LocalSecondaryIndex.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/LocalSecondaryIndex.javaindex 3050c6011d..d9d71483ef 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/LocalSecondaryIndex.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/LocalSecondaryIndex.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb.model;+import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.quarkus.runtime.annotations.RegisterForReflection;@@ -81,7 +82,13 @@ public class LocalSecondaryIndex {/*** Returns all sort key attribute names in key-schema order. For a composite sort key this* contains more than one element; ordering must consider all of them, not just the first.+ *+ * <p>{@code @JsonIgnore}d: it is derived from {@code keySchema} (redundant with+ * {@link #getSortKeyName()}), and without a backing setter Jackson's getter-as-setter+ * fallback tries to append into the immutable list this method returns, throwing+ * {@code UnsupportedOperationException} on deserialization whenever the index has a sort key.*/+ @JsonIgnorepublic List<String> getSortKeyNames() {return keySchema.stream().filter(k -> "RANGE".equals(k.getKeyType()))diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.javaindex c1189c559e..c60e0ab4d0 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/model/TableDefinition.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.dynamodb.model;+import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.quarkus.runtime.annotations.RegisterForReflection;@@ -226,7 +227,13 @@ public class TableDefinition {/*** Returns all sort key attribute names in key-schema order. For a composite sort key this* contains more than one element; ordering must consider all of them, not just the first.+ *+ * <p>{@code @JsonIgnore}d: it is derived from {@code keySchema} (redundant with+ * {@link #getSortKeyName()}), and without a backing setter Jackson's getter-as-setter+ * fallback tries to append into the immutable list this method returns, throwing+ * {@code UnsupportedOperationException} on deserialization whenever the table has a sort key.*/+ @JsonIgnorepublic List<String> getSortKeyNames() {return keySchema.stream().filter(k -> "RANGE".equals(k.getKeyType()))diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.javanew file mode 100644index 0000000000..84486b2a33--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbGsiSortKeyRestartTest.java@@ -0,0 +1,99 @@+package io.github.hectorvent.floci.services.dynamodb;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.PersistentStorage;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Wire-protocol reproduction for floci-io/floci#2415: a table whose GSI (or LSI, or own primary+ * key) has a RANGE key must survive a restart. Before the fix, {@code TableDefinition}'s Jackson+ * round-trip threw on any such table; {@code PersistentStorage.load()} swallows that as an IOException,+ * quarantines the file, and comes back up with zero tables in the whole store, not just the+ * offending one.+ *+ * <p>The GSI case here matches the issue's own reproduction (base table HASH-only, GSI with a+ * HASH+RANGE key schema). The LSI and base-table-composite-key cases share the identical root+ * cause (getSortKeyNames() added to all three model classes together in #2114) and are covered at+ * the model level by {@code SortKeyNamesJacksonRoundTripTest}.+ */+class DynamoDbGsiSortKeyRestartTest {++ private static final String TABLE = "con-gsi";+ private static final String REGION = "us-east-1";++ private final ObjectMapper mapper = new ObjectMapper();++ /** A store backed by a real file, so a "restart" is just reading it again. */+ private StorageBackend<String, TableDefinition> diskStore(Path file) {+ PersistentStorage<String, TableDefinition> store =+ new PersistentStorage<>(file, new TypeReference<Map<String, TableDefinition>>() { });+ store.load();+ return store;+ }++ private DynamoDbJsonHandler handlerFor(StorageBackend<String, TableDefinition> store) {+ DynamoDbService service = new DynamoDbService(+ store, null, new RegionResolver(REGION, "000000000000"), null, null);+ return new DynamoDbJsonHandler(service, null, null, mapper);+ }++ private ObjectNode createTableWithGsiSortKeyRequest() {+ ObjectNode req = mapper.createObjectNode();+ req.put("TableName", TABLE);+ req.putArray("KeySchema").addObject().put("AttributeName", "PK").put("KeyType", "HASH");+ var attrDefs = req.putArray("AttributeDefinitions");+ attrDefs.addObject().put("AttributeName", "PK").put("AttributeType", "S");+ attrDefs.addObject().put("AttributeName", "GSI1PK").put("AttributeType", "S");+ attrDefs.addObject().put("AttributeName", "GSI1SK").put("AttributeType", "S");+ req.put("BillingMode", "PAY_PER_REQUEST");+ ObjectNode gsi = req.putArray("GlobalSecondaryIndexes").addObject();+ gsi.put("IndexName", "GSI1");+ var gsiKeySchema = gsi.putArray("KeySchema");+ gsiKeySchema.addObject().put("AttributeName", "GSI1PK").put("KeyType", "HASH");+ gsiKeySchema.addObject().put("AttributeName", "GSI1SK").put("KeyType", "RANGE");+ gsi.putObject("Projection").put("ProjectionType", "ALL");+ return req;+ }++ @Test+ void tableWithGsiRangeKeySurvivesARestart(@TempDir Path tmp) throws Exception {+ Path file = tmp.resolve("dynamodb-tables.json");+ StorageBackend<String, TableDefinition> store = diskStore(file);++ handlerFor(store).handle("CreateTable", createTableWithGsiSortKeyRequest(), REGION);++ StorageBackend<String, TableDefinition> reopened = diskStore(file);+ assertTrue(reopened.get(REGION + "::" + TABLE).isPresent(),+ "a table with a GSI sort key must still be there after a restart");+ }++ @Test+ void otherTablesSurviveEvenWhenOneHasAGsiRangeKey(@TempDir Path tmp) throws Exception {+ Path file = tmp.resolve("dynamodb-tables.json");+ StorageBackend<String, TableDefinition> store = diskStore(file);+ DynamoDbJsonHandler handler = handlerFor(store);++ handler.handle("CreateTable", createTableWithGsiSortKeyRequest(), REGION);+ ObjectNode plainTable = mapper.createObjectNode();+ plainTable.put("TableName", "plain-table");+ plainTable.putArray("KeySchema").addObject().put("AttributeName", "id").put("KeyType", "HASH");+ plainTable.putArray("AttributeDefinitions").addObject()+ .put("AttributeName", "id").put("AttributeType", "S");+ handler.handle("CreateTable", plainTable, REGION);++ StorageBackend<String, TableDefinition> reopened = diskStore(file);+ assertTrue(reopened.get(REGION + "::" + "plain-table").isPresent(),+ "an unrelated table must not be wiped out by a sibling table's GSI sort key");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/model/SortKeyNamesJacksonRoundTripTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/model/SortKeyNamesJacksonRoundTripTest.javanew file mode 100644index 0000000000..e09c410a19--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/model/SortKeyNamesJacksonRoundTripTest.java@@ -0,0 +1,79 @@+package io.github.hectorvent.floci.services.dynamodb.model;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.SerializationFeature;+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;+import org.junit.jupiter.api.Test;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * Regression for floci-io/floci#2415: any {@code List<String>}-returning derived getter with no+ * backing setter (here {@code getSortKeyNames()}) is a Jackson trap. On deserialization Jackson+ * finds no setter, falls back to "getter as setter", calls the getter, and appends into the list+ * it returned. {@code getSortKeyNames()} builds that list with {@code Stream.toList()}, which is+ * immutable, so the append throws {@code UnsupportedOperationException} for every RANGE-keyed+ * schema and is swallowed as {@code []} only when there is no sort key to append.+ *+ * <p>{@code getSortKeyNames()} was added to all three classes in the same commit (#2114), so the+ * trap is identical on {@link GlobalSecondaryIndex}, {@link LocalSecondaryIndex} and+ * {@link TableDefinition} itself (a table with its own composite primary key), even though the+ * issue only reports the GSI case.+ */+class SortKeyNamesJacksonRoundTripTest {++ /** Same configuration {@code PersistentStorage}, {@code HybridStorage} and {@code WalStorage} use. */+ private final ObjectMapper mapper = new ObjectMapper();++ SortKeyNamesJacksonRoundTripTest() {+ mapper.registerModule(new JavaTimeModule());+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);+ mapper.enable(SerializationFeature.INDENT_OUTPUT);+ }++ private List<KeySchemaElement> hashAndRangeSchema(String hashName, String rangeName) {+ return List.of(+ new KeySchemaElement(hashName, "HASH"),+ new KeySchemaElement(rangeName, "RANGE"));+ }++ @Test+ void globalSecondaryIndexWithSortKeySurvivesARoundTrip() {+ GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(+ "GSI1", hashAndRangeSchema("GSI1PK", "GSI1SK"), null, "ALL", null);++ String json = assertDoesNotThrow(() -> mapper.writeValueAsString(gsi));+ GlobalSecondaryIndex reloaded =+ assertDoesNotThrow(() -> mapper.readValue(json, GlobalSecondaryIndex.class));++ assertEquals(List.of("GSI1SK"), reloaded.getSortKeyNames());+ }++ @Test+ void localSecondaryIndexWithSortKeySurvivesARoundTrip() {+ LocalSecondaryIndex lsi = new LocalSecondaryIndex(+ "LSI1", hashAndRangeSchema("PK", "LSI1SK"), null, "ALL");++ String json = assertDoesNotThrow(() -> mapper.writeValueAsString(lsi));+ LocalSecondaryIndex reloaded =+ assertDoesNotThrow(() -> mapper.readValue(json, LocalSecondaryIndex.class));++ assertEquals(List.of("LSI1SK"), reloaded.getSortKeyNames());+ }++ @Test+ void tableWithACompositePrimaryKeySurvivesARoundTrip() {+ TableDefinition table = new TableDefinition();+ table.setTableName("orders");+ table.setKeySchema(hashAndRangeSchema("PK", "SK"));++ String json = assertDoesNotThrow(() -> mapper.writeValueAsString(table));+ TableDefinition reloaded =+ assertDoesNotThrow(() -> mapper.readValue(json, TableDefinition.class));++ assertEquals(List.of("SK"), reloaded.getSortKeyNames());+ }+}