Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): merge shared-prefix projection paths and compact list indices (#3072)
TATSUNO “Taz” Yasuhiro5c8cff61b887
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.javaindex e5d890dab9..ac40f16829 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java@@ -7,8 +7,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;import java.util.ArrayList;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Map;import java.util.Set;+import java.util.TreeMap;/*** Applies a DynamoDB ProjectionExpression to a result item, returning a new@@ -18,24 +21,32 @@ final class ProjectionEvaluator {private static final ObjectMapper MAPPER = new ObjectMapper();+ // The highest list index real DynamoDB accepts in a document path.+ private static final long MAX_LIST_INDEX = 4_294_967_294L;+private ProjectionEvaluator() {}/*** Returns a new ObjectNode containing only the paths named in the expression.* Resolves #alias references via exprAttrNames. Handles dot-path and [n] list index segments.+ * Paths sharing a prefix merge into one reconstructed structure; projected list indices+ * compact to ascending source order, the way DynamoDB reconstructs projected items.*/static ObjectNode project(JsonNode item, String projectionExpression, JsonNode exprAttrNames) {if (item == null || projectionExpression == null || projectionExpression.isBlank()) {return (ObjectNode) item;}validateExpression(projectionExpression);- ObjectNode result = MAPPER.createObjectNode();+ PathTrie root = new PathTrie();for (String rawPath : splitProjectionPaths(projectionExpression)) {List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);- if (segments.isEmpty()) continue;- copyPath(item, result, segments, 0);+ if (segments.isEmpty()) {+ continue;+ }+ root.insert(segments);}- return result;+ ObjectNode projected = projectMapEntries(item, root);+ return projected != null ? projected : MAPPER.createObjectNode();}/**@@ -67,13 +78,16 @@ final class ProjectionEvaluator {if (expression == null || expression.isBlank()) return;char first = expression.charAt(0);if (!Character.isLetterOrDigit(first) && first != '#' && first != '_') {- String token = String.valueOf(first);String near = expression.length() > 2 ? expression.substring(1, 3) : expression.substring(1);- throw new AwsException("ValidationException",- "Invalid " + expressionType + ": Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);+ throw syntaxError(expressionType, String.valueOf(first), near);}}+ private static AwsException syntaxError(String expressionType, String token, String near) {+ return new AwsException("ValidationException",+ "Invalid " + expressionType + ": Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);+ }+static void validateExpression(String expression) {validateSyntax(expression, "ProjectionExpression");DynamoDbReservedWords.check(expression, "ProjectionExpression");@@ -120,6 +134,7 @@ final class ProjectionEvaluator {while (i < rest.length() && rest.charAt(i) == '[') {int close = rest.indexOf(']', i);if (close < 0) break;+ validateListIndex(rest.substring(i + 1, close));segments.add(rest.substring(i, close + 1)); // e.g. "[0]"i = close + 1;}@@ -130,6 +145,33 @@ final class ProjectionEvaluator {return segments;}+ // DynamoDB rejects a non-numeric bracket segment and a leading zero as syntax+ // errors, and a numeric index above 4294967294 as out of the allowable range,+ // all at expression level. Verified on real DynamoDB (us-east-1, 2026-09-05).+ private static void validateListIndex(String content) {+ if (content.isEmpty()) {+ throw syntaxError("ProjectionExpression", "]", "[]");+ }+ final var contentLength = content.length();+ for (var i = 0; i < contentLength; i++) {+ var c = content.charAt(i);+ if (c < '0' || '9' < c) {+ var near = "[" + content + "]";+ throw syntaxError("ProjectionExpression", String.valueOf(c),+ near.substring(0, Math.min(3, near.length())));+ }+ }+ if (contentLength > 1 && content.charAt(0) == '0') {+ throw syntaxError("ProjectionExpression", "0",+ content.substring(0, Math.min(3, contentLength)));+ }+ if (contentLength > 10 || Long.parseLong(content) > MAX_LIST_INDEX) {+ throw new AwsException("ValidationException",+ "Invalid ProjectionExpression: List index is not within the allowable range; "+ + "index: [" + content + "]", 400);+ }+ }+private static String resolveSegment(String seg, JsonNode exprAttrNames) {if (seg.startsWith("#") && exprAttrNames != null) {JsonNode resolved = exprAttrNames.get(seg);@@ -140,61 +182,88 @@ final class ProjectionEvaluator {// ── Tree walking ──- private static void copyPath(JsonNode src, ObjectNode dest, List<String> segments, int idx) {- if (idx >= segments.size()) return;- String seg = segments.get(idx);-- if (seg.matches("\\[\\d+\\]")) {- // List index at root level — handled by the caller- return;- }-- JsonNode child = src.get(seg);- if (child == null) return;-- if (idx == segments.size() - 1) {- // Leaf: deep-copy to avoid placing a live source reference into the- // destination, which could be mutated by a subsequent sibling path.- dest.set(seg, child.deepCopy());- } else {- String nextSeg = segments.get(idx + 1);- if (nextSeg.matches("\\[\\d+\\]")) {- // Next is a list index — extract just that element.- // Reuse existing wrapper if already projected (same fix as the M branch).- int listIdx = Integer.parseInt(nextSeg.substring(1, nextSeg.length() - 1));- JsonNode listNode = child.has("L") ? child.get("L") : child;- if (listNode.isArray() && listIdx < listNode.size() && !dest.has(seg)) {- JsonNode element = listNode.get(listIdx);- // Build {"L": [element]} wrapper- ObjectNode wrapper = MAPPER.createObjectNode();- ArrayNode newList = MAPPER.createArrayNode();- newList.add(element);- wrapper.set("L", newList);- dest.set(seg, wrapper);+ /**+ * Merged view of every projected path. Map-name children and list-index children are+ * kept separately; index children stay sorted so a projected list compacts to+ * ascending source order. A node marked terminal ends a path and copies the whole+ * subtree it points at.+ */+ private static final class PathTrie {+ private boolean terminal;+ private final Map<String, PathTrie> names = new LinkedHashMap<>();+ // Long keys: the allowable index range (up to 4294967294) exceeds Integer.MAX_VALUE.+ private final TreeMap<Long, PathTrie> indices = new TreeMap<>();++ void insert(List<String> segments) {+ PathTrie node = this;+ for (String seg : segments) {+ if (seg.startsWith("[")) {+ long idx = Long.parseLong(seg.substring(1, seg.length() - 1));+ node = node.indices.computeIfAbsent(idx, k -> new PathTrie());+ } else {+ node = node.names.computeIfAbsent(seg, k -> new PathTrie());}- } else if (child.has("M")) {- // Nested map — reuse existing projected map if present- ObjectNode existing = dest.has(seg) && dest.get(seg).has("M")- ? (ObjectNode) dest.get(seg).get("M") : null;- ObjectNode nestedDest = existing != null ? existing : MAPPER.createObjectNode();- copyPath(child.get("M"), nestedDest, segments, idx + 1);- if (existing == null) {- ObjectNode wrapper = MAPPER.createObjectNode();- wrapper.set("M", nestedDest);- dest.set(seg, wrapper);+ }+ node.terminal = true;+ }+ }++ /**+ * Projects a typed attribute value through a trie node. Returns null when nothing+ * under this value matches, so the caller can drop the branch entirely.+ */+ private static JsonNode projectValue(JsonNode src, PathTrie node) {+ if (node.terminal) {+ return src.deepCopy();+ }+ if (!node.indices.isEmpty() && src.has("L")) {+ JsonNode list = src.get("L");+ ArrayNode projectedList = MAPPER.createArrayNode();+ for (Map.Entry<Long, PathTrie> entry : node.indices.entrySet()) {+ long idx = entry.getKey();+ if (idx >= list.size()) {+ continue;}- } else if (child.isObject()) {- // Reuse existing nested object if present- ObjectNode existing = dest.has(seg) && dest.get(seg).isObject()- ? (ObjectNode) dest.get(seg) : null;- ObjectNode nestedDest = existing != null ? existing : MAPPER.createObjectNode();- copyPath(child, nestedDest, segments, idx + 1);- if (existing == null) {- dest.set(seg, nestedDest);+ JsonNode projected = projectValue(list.get((int) idx), entry.getValue());+ if (projected != null) {+ projectedList.add(projected);}- } else {- dest.set(seg, child);+ }+ if (projectedList.isEmpty()) {+ return null;+ }+ ObjectNode wrapper = MAPPER.createObjectNode();+ wrapper.set("L", projectedList);+ return wrapper;+ }+ if (!node.names.isEmpty()) {+ if (src.has("M")) {+ JsonNode projectedMap = projectMapEntries(src.get("M"), node);+ if (projectedMap == null) {+ return null;+ }+ ObjectNode wrapper = MAPPER.createObjectNode();+ wrapper.set("M", projectedMap);+ return wrapper;+ }+ // Defensive fallback for plain (non-DynamoDB-typed) nested objects.+ return projectMapEntries(src, node);+ }+ return null;+ }++ private static ObjectNode projectMapEntries(JsonNode map, PathTrie node) {+ ObjectNode projectedMap = MAPPER.createObjectNode();+ for (Map.Entry<String, PathTrie> entry : node.names.entrySet()) {+ JsonNode child = map.get(entry.getKey());+ if (child == null) {+ continue;+ }+ JsonNode projected = projectValue(child, entry.getValue());+ if (projected != null) {+ projectedMap.set(entry.getKey(), projected);}}+ return projectedMap.isEmpty() ? null : projectedMap;}}diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluatorTest.javanew file mode 100644index 0000000000..be32ed6c58--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluatorTest.java@@ -0,0 +1,193 @@+package io.github.hectorvent.floci.services.dynamodb;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.*;++/**+ * Unit tests for ProjectionExpression evaluation over list indices. Paths sharing a+ * prefix must merge into one reconstructed structure, and projected list indices must+ * compact to ascending source order, matching real DynamoDB. Mirrors the paritysuite+ * dynamodb-conformance tier1 projection cases.+ */+class ProjectionEvaluatorTest {++ private static final ObjectMapper mapper = new ObjectMapper();++ private static ObjectNode listItem() {+ return readValue("""+ {+ "pk": {"S": "p"},+ "l": {"L": [+ {"M": {+ "a": {"S": "a0"},+ "b": {"S": "b0"},+ "m": {"M": {"x": {"S": "x0"}, "y": {"S": "y0"}}},+ "n": {"L": [+ {"M": {"p": {"S": "p00"}, "q": {"S": "q00"}}},+ {"M": {"p": {"S": "p01"}, "q": {"S": "q01"}}}+ ]}+ }},+ {"M": {"a": {"S": "a1"}, "b": {"S": "b1"}}},+ {"M": {"a": {"S": "a2"}, "b": {"S": "b2"}, "c": {"S": "c2"}}}+ ]}+ }+ """);+ }++ @Test+ void projectsMultipleListIndicesCompactedAndIndexOrdered() {+ var item = readValue("""+ {"mylist": {"L": [{"S": "zero"}, {"S": "one"}, {"S": "two"}]}}+ """);++ var result = ProjectionEvaluator.project(item, "#l[2], #l[0]",+ readValue("""+ {"#l": "mylist"}+ """));++ var list = result.get("mylist").get("L");+ assertEquals(2, list.size(), "both requested elements must survive");+ assertEquals("zero", list.get(0).get("S").asText());+ assertEquals("two", list.get(1).get("S").asText());+ }++ @Test+ void mergesTwoScalarPathsUnderOneListIndex() {+ var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b", null);++ var list = result.get("l").get("L");+ assertEquals(1, list.size());+ var element = list.get(0).get("M");+ assertEquals("a0", element.get("a").get("S").asText());+ assertEquals("b0", element.get("b").get("S").asText());+ assertNull(element.get("m"), "unprojected sibling must be dropped");+ }++ @Test+ void mergesScalarSiblingAndNestedMapSiblingUnderOneListIndex() {+ var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].m.x", null);++ var element = result.get("l").get("L").get(0).get("M");+ assertEquals("a0", element.get("a").get("S").asText());+ assertEquals("x0", element.get("m").get("M").get("x").get("S").asText());+ assertNull(element.get("m").get("M").get("y"), "only x was projected inside m");+ assertNull(element.get("b"), "unprojected sibling must be dropped");+ }++ @Test+ void mergesTwoPathsSharingAnElementOfANestedList() {+ var result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[0].q", null);++ var outer = result.get("l").get("L");+ assertEquals(1, outer.size());+ var inner = outer.get(0).get("M").get("n").get("L");+ assertEquals(1, inner.size(), "both paths share inner index 0");+ assertEquals("p00", inner.get(0).get("M").get("p").get("S").asText());+ assertEquals("q00", inner.get(0).get("M").get("q").get("S").asText());+ }++ @Test+ void keepsDistinctInnerListIndicesSeparateUnderOneSharedOuterIndex() {+ var result = ProjectionEvaluator.project(listItem(), "l[0].n[0].p, l[0].n[1].q", null);++ var inner = result.get("l").get("L").get(0).get("M").get("n").get("L");+ assertEquals(2, inner.size());+ assertEquals("p00", inner.get(0).get("M").get("p").get("S").asText());+ assertNull(inner.get(0).get("M").get("q"));+ assertEquals("q01", inner.get(1).get("M").get("q").get("S").asText());+ assertNull(inner.get(1).get("M").get("p"));+ }++ @Test+ void mergesSharedIndexAndKeepsDistinctIndexSeparateCompacted() {+ var result = ProjectionEvaluator.project(listItem(), "l[0].a, l[0].b, l[2].c", null);++ var list = result.get("l").get("L");+ assertEquals(2, list.size(), "index 0 (merged) and index 2 compact to two elements");+ assertEquals("a0", list.get(0).get("M").get("a").get("S").asText());+ assertEquals("b0", list.get(0).get("M").get("b").get("S").asText());+ assertEquals("c2", list.get(1).get("M").get("c").get("S").asText());+ assertNull(list.get(1).get("M").get("a"));+ }++ @Test+ void rejectsNonNumericListIndexAsSyntaxError() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[a]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: Syntax error; token: \"a\", near: \"[a]\"",+ ex.getMessage());+ }++ @Test+ void rejectsEmptyListIndexAsSyntaxError() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: Syntax error; token: \"]\", near: \"[]\"",+ ex.getMessage());+ }++ @Test+ void rejectsListIndexAboveTheAllowableRange() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[999999999999999999999]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: List index is not within the allowable range; "+ + "index: [999999999999999999999]", ex.getMessage());+ }++ @Test+ void rejectsFirstListIndexPastTheAllowableRange() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[4294967295]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: List index is not within the allowable range; "+ + "index: [4294967295]", ex.getMessage());+ }++ @Test+ void rejectsUnicodeDigitListIndexAsSyntaxError() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[123]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: Syntax error; token: \"1\", near: \"[12\"",+ ex.getMessage());+ }++ @Test+ void rejectsLeadingZeroListIndexAsSyntaxError() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[001]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: Syntax error; token: \"0\", near: \"001\"",+ ex.getMessage());+ }++ @Test+ void rejectsLongZeroPaddedListIndexAsSyntaxError() {+ var ex = assertThrows(AwsException.class,+ () -> ProjectionEvaluator.project(mapper.createObjectNode(), "l[0000000000001]", null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Invalid ProjectionExpression: Syntax error; token: \"0\", near: \"000\"",+ ex.getMessage());+ }++ @Test+ void allowableIndexBeyondTheListJustDropsTheAttribute() {+ var result = ProjectionEvaluator.project(listItem(), "l[4294967294]", null);+ assertNull(result.get("l"), "an in-range index past the list end matches nothing");+ }++ private static ObjectNode readValue(String json) {+ try {+ return (ObjectNode) mapper.readTree(json);+ } catch (Exception e) {+ throw new IllegalStateException(e);+ }+ }+}