mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(dynamodb): improve conformance across validation, expressions, and queries (#826)
* fix(dynamodb): improve conformance across validation, expressions, and queries - Rename InvalidParameterValue → ValidationException for table-name errors - Enforce min-length 3 on table names for all operations, not just CreateTable - ListTables: alphabetical order, Limit validation (1–100), pagination - Enum validation (ReturnValues, ReturnConsumedCapacity) fires before table lookup - ProjectionExpression support on GetItem, Query, Scan, BatchGetItem - Select=COUNT returns Count/ScannedCount and omits Items - Parallel scan: Segment/TotalSegments validation and hash-based sharding - Reserved words rejected in FilterExpression, ConditionExpression, UpdateExpression - Legacy API: AttributesToGet, AttributeUpdates, QueryFilter, ScanFilter, KeyConditions - TransactWriteItems idempotency token with payload-hash conflict detection - ReturnValuesOnConditionCheckFailure on PutItem, UpdateItem, DeleteItem - Item size limit (400 KB) and number normalization on write - Tags API: TagResource, UntagResource, ListTagsOfResource with ARN validation - New Java and Node SDK conformance tests covering all changes above * fix(dynamodb): fix unit testing
This commit is contained in:
1 parent
e0224e93e6
commit
5ab178e10d
21 files changed
+3897
-301
No files matched your search
@@ -0,0 +1,94 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Calculates DynamoDB item size and enforces the 400KB limit.
|
||||
*/
|
||||
final class DynamoDbItemSize {
|
||||
|
||||
static final int MAX_ITEM_SIZE = 400 * 1024; // 400 KB = 409,600 bytes
|
||||
|
||||
private DynamoDbItemSize() {}
|
||||
|
||||
/**
|
||||
* Validates the item fits within 400KB. Throws ValidationException if not.
|
||||
*/
|
||||
static void validateSize(JsonNode item) {
|
||||
int size = calculateItemSize(item);
|
||||
if (size > MAX_ITEM_SIZE) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Item size has exceeded the maximum allowed size", 400);
|
||||
}
|
||||
}
|
||||
|
||||
static int calculateItemSize(JsonNode item) {
|
||||
if (item == null || !item.isObject()) return 0;
|
||||
int total = 0;
|
||||
var fields = item.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
total += utf8Length(entry.getKey());
|
||||
total += attributeValueSize(entry.getValue());
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static int attributeValueSize(JsonNode attr) {
|
||||
if (attr == null) return 0;
|
||||
if (attr.has("S")) return utf8Length(attr.get("S").asText());
|
||||
if (attr.has("N")) return attr.get("N").asText().length();
|
||||
if (attr.has("B")) return binarySize(attr.get("B").asText());
|
||||
if (attr.has("BOOL")) return 1;
|
||||
if (attr.has("NULL")) return 1;
|
||||
if (attr.has("SS")) {
|
||||
int size = 0;
|
||||
for (JsonNode e : attr.get("SS")) size += utf8Length(e.asText()) + 1;
|
||||
return size;
|
||||
}
|
||||
if (attr.has("NS")) {
|
||||
int size = 0;
|
||||
for (JsonNode e : attr.get("NS")) size += e.asText().length() + 1;
|
||||
return size;
|
||||
}
|
||||
if (attr.has("BS")) {
|
||||
int size = 0;
|
||||
for (JsonNode e : attr.get("BS")) size += binarySize(e.asText()) + 1;
|
||||
return size;
|
||||
}
|
||||
if (attr.has("L")) {
|
||||
int size = 0;
|
||||
for (JsonNode e : attr.get("L")) size += attributeValueSize(e) + 3;
|
||||
return size;
|
||||
}
|
||||
if (attr.has("M")) {
|
||||
int size = 0;
|
||||
var fields = attr.get("M").fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
size += utf8Length(entry.getKey()) + 1 + attributeValueSize(entry.getValue()) + 3;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int utf8Length(String s) {
|
||||
if (s == null) return 0;
|
||||
return s.getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
|
||||
private static int binarySize(String base64) {
|
||||
if (base64 == null || base64.isEmpty()) return 0;
|
||||
try {
|
||||
return Base64.getDecoder().decode(base64).length;
|
||||
} catch (Exception e) {
|
||||
// Fallback: estimate from base64 length
|
||||
return (int) (base64.length() * 3L / 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
+859
-40
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DynamoDB number validation and normalization.
|
||||
* Numbers must have <= 38 significant digits, be within range, and are stored
|
||||
* in normalized form (no leading zeros, no trailing decimal zeros, -0 -> 0).
|
||||
*/
|
||||
final class DynamoDbNumberUtils {
|
||||
|
||||
private static final BigDecimal MAX_ABS = new BigDecimal("1E+126");
|
||||
private static final BigDecimal MIN_ABS_NONZERO = new BigDecimal("1E-130");
|
||||
|
||||
private DynamoDbNumberUtils() {}
|
||||
|
||||
/**
|
||||
* Validates and normalizes a DynamoDB number string.
|
||||
* Throws ValidationException if the number is out of range or has too many significant digits.
|
||||
* Returns the normalized string (no leading zeros, no trailing decimal zeros).
|
||||
*/
|
||||
static String validateAndNormalize(String numStr) {
|
||||
if (numStr == null || numStr.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The parameter cannot be converted to a numeric value", 400);
|
||||
}
|
||||
BigDecimal bd;
|
||||
try {
|
||||
bd = new BigDecimal(numStr);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The parameter cannot be converted to a numeric value: " + numStr, 400);
|
||||
}
|
||||
|
||||
BigDecimal stripped = bd.stripTrailingZeros();
|
||||
|
||||
// Check significant digits after normalization
|
||||
if (stripped.precision() > 38) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Number too many significant digits; first supported is 1E-130 last supported is 1E+126", 400);
|
||||
}
|
||||
|
||||
// Check range (only for nonzero values)
|
||||
BigDecimal abs = stripped.abs();
|
||||
if (abs.compareTo(BigDecimal.ZERO) > 0) {
|
||||
if (abs.compareTo(MAX_ABS) >= 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Number overflow. Attempting to store a value that is too large. "
|
||||
+ "The maximum allowed positive value is 9.9999999999999999999999999999999999999E+125", 400);
|
||||
}
|
||||
if (abs.compareTo(MIN_ABS_NONZERO) < 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Number underflow. Attempting to store a value that is too small. "
|
||||
+ "The minimum allowed positive value is 1E-130", 400);
|
||||
}
|
||||
}
|
||||
|
||||
return toNormalizedString(stripped);
|
||||
}
|
||||
|
||||
private static String toNormalizedString(BigDecimal bd) {
|
||||
// -0 -> 0
|
||||
if (bd.compareTo(BigDecimal.ZERO) == 0) {
|
||||
return "0";
|
||||
}
|
||||
// Use plain string to expand scientific notation to decimal form when reasonable
|
||||
return bd.toPlainString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively normalizes all N-type number attribute values in the given item.
|
||||
* Returns a new ObjectNode with normalized values. Input must be a DynamoDB item
|
||||
* where attribute values are DynamoDB typed values (e.g. {S: "x"}, {N: "42"}).
|
||||
*/
|
||||
static ObjectNode normalizeNumbersInItem(JsonNode item) {
|
||||
if (item == null || !item.isObject()) return (ObjectNode) item;
|
||||
ObjectNode result = JsonNodeFactory.instance.objectNode();
|
||||
item.fields().forEachRemaining(entry -> {
|
||||
result.set(entry.getKey(), normalizeAttrValue(entry.getValue()));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private static JsonNode normalizeAttrValue(JsonNode attr) {
|
||||
if (attr == null) return null;
|
||||
|
||||
if (attr.has("N")) {
|
||||
String raw = attr.get("N").asText();
|
||||
String normalized = validateAndNormalize(raw);
|
||||
ObjectNode result = JsonNodeFactory.instance.objectNode();
|
||||
result.put("N", normalized);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (attr.has("NS")) {
|
||||
// Normalize and validate each element
|
||||
ObjectNode result = JsonNodeFactory.instance.objectNode();
|
||||
ArrayNode ns = JsonNodeFactory.instance.arrayNode();
|
||||
for (JsonNode elem : attr.get("NS")) {
|
||||
ns.add(validateAndNormalize(elem.asText()));
|
||||
}
|
||||
result.set("NS", ns);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (attr.has("M")) {
|
||||
ObjectNode result = JsonNodeFactory.instance.objectNode();
|
||||
result.set("M", normalizeNumbersInItem(attr.get("M")));
|
||||
return result;
|
||||
}
|
||||
|
||||
if (attr.has("L")) {
|
||||
ObjectNode result = JsonNodeFactory.instance.objectNode();
|
||||
ArrayNode list = JsonNodeFactory.instance.arrayNode();
|
||||
for (JsonNode elem : attr.get("L")) {
|
||||
list.add(normalizeAttrValue(elem));
|
||||
}
|
||||
result.set("L", list);
|
||||
return result;
|
||||
}
|
||||
|
||||
return attr;
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Validates that DynamoDB expressions do not use reserved words as bare attribute names.
|
||||
*/
|
||||
final class DynamoDbReservedWords {
|
||||
|
||||
private DynamoDbReservedWords() {}
|
||||
|
||||
// Expression clause/operator keywords that are syntactically valid as operators
|
||||
// and should not be treated as attribute name tokens.
|
||||
private static final Set<String> CLAUSE_KEYWORDS = Set.of(
|
||||
"SET", "REMOVE", "ADD", "DELETE",
|
||||
"AND", "OR", "NOT", "BETWEEN", "IN",
|
||||
"TRUE", "FALSE"
|
||||
);
|
||||
|
||||
// Full DynamoDB reserved words list (uppercase)
|
||||
private static final Set<String> RESERVED = Set.of(
|
||||
"ABORT", "ABSOLUTE", "ACTION", "ADD", "AFTER", "AGENT", "ALL", "ALLOCATE",
|
||||
"ALTER", "ANALYZE", "AND", "ANY", "ARCHIVE", "ARE", "ARRAY", "AS", "ASC",
|
||||
"ASCII", "ASENSITIVE", "ASSERTION", "ASYMMETRIC", "AT", "ATOMIC", "ATTACH",
|
||||
"ATTRIBUTE", "AUTH", "AUTHORIZATION", "AUTHORIZE", "AUTO",
|
||||
"BETWEEN", "BIGINT", "BINARY", "BIT", "BLOB", "BLOCK", "BOOLEAN", "BOTH",
|
||||
"BREADTH", "BUCKET", "BULK", "BY",
|
||||
"CALL", "CALLED", "CANCEL", "CASCADE", "CASE", "CAST", "CATALOG", "CHAR",
|
||||
"CHARACTER", "CHECK", "CLASS", "CLOB", "CLOSE", "CLUSTER", "CLUSTERED",
|
||||
"CLUSTERING", "CLUSTERS", "COALESCE", "COLLATE", "COLLATION", "COLUMN",
|
||||
"COLUMNS", "COMBINE", "COMMENT", "COMMIT", "COMPACT", "COMPILE", "COMPRESS",
|
||||
"CONDITION", "CONFLICT", "CONNECT", "CONNECTION", "CONSISTENCY", "CONSISTENT",
|
||||
"CONSTRAINT", "CONSTRAINTS", "CONSTRUCTOR", "CONSUMED", "CONTINUE", "CONVERT",
|
||||
"COPY", "CORRESPONDING", "COUNT", "COUNTER", "CREATE", "CROSS", "CUBE",
|
||||
"CURRENT", "CURSOR", "CYCLE",
|
||||
"DATA", "DATABASE", "DATE", "DATETIME", "DAY", "DEALLOCATE", "DEC", "DECIMAL",
|
||||
"DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DEFINE", "DEFINED",
|
||||
"DEFINITION", "DELETE", "DELIMITED", "DEPTH", "DEREF", "DESC", "DESCRIBE",
|
||||
"DESCRIPTOR", "DETACH", "DETERMINISTIC", "DIAGNOSTICS", "DIRECTORIES",
|
||||
"DISABLE", "DISCONNECT", "DISTINCT", "DISTRIBUTE", "DO", "DOMAIN", "DOUBLE",
|
||||
"DROP", "DUMP", "DURATION", "DYNAMIC",
|
||||
"EACH", "ELEMENT", "ELSE", "ELSEIF", "EMPTY", "ENABLE", "END", "EQUALS",
|
||||
"ERROR", "ESCAPE", "EVALUATED", "EXCEPT", "EXCEPTION", "EXCEPTIONS",
|
||||
"EXCLUSIVE", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXPLAIN", "EXPLODE",
|
||||
"EXPORT", "EXTENDED", "EXTERNAL",
|
||||
"FALSE", "FETCH", "FILTER", "FIRST", "FIXED", "FLATTERN", "FLOAT", "FOR",
|
||||
"FORCE", "FOREIGN", "FORMAT", "FORWARD", "FOUND", "FREE", "FROM", "FULL",
|
||||
"FUNCTION", "FUNCTIONS",
|
||||
"GENERAL", "GENERATE", "GET", "GLOB", "GO", "GOTO", "GRANT", "GREATER",
|
||||
"GROUP", "GROUPING",
|
||||
"HANDLER", "HASH", "HAVE", "HAVING", "HEAP", "HIDDEN", "HOLD", "HOW",
|
||||
"IDENTIFIED", "IDENTITY", "IF", "IGNORE", "IMMEDIATE", "IN", "INCLUDING",
|
||||
"INCLUSIVE", "INCREMENT", "INCREMENTAL", "INDEX", "INDEXES", "INDICATOR",
|
||||
"INFINITE", "INITIALLY", "INLINE", "INNER", "INNTER", "INOUT", "INSERT",
|
||||
"INSTEAD", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "INVALIDATE",
|
||||
"IS", "ISOLATION", "ITEM", "ITEMS", "ITERATE",
|
||||
"JOIN",
|
||||
"KEY", "KEYS",
|
||||
"LAG", "LANGUAGE", "LARGE", "LAST", "LATERAL", "LEAD", "LEADING", "LEAVE",
|
||||
"LEFT", "LENGTH", "LESS", "LEVEL", "LIKE", "LIMIT", "LIMITED", "LINES",
|
||||
"LIST", "LOAD", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCATION", "LOCATOR",
|
||||
"LOCK", "LOCKS", "LOG", "LOGED", "LONG", "LOOP", "LOWER",
|
||||
"MAP", "MATCH", "MATERIALIZED", "MAX", "MAXLEN", "MERGE", "METADATA", "MIN",
|
||||
"MINUS", "MODIFIES", "MODIFY", "MODULE", "MONTH", "MULTI", "MULTISET",
|
||||
"NAME", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NCLOB", "NEW", "NEXT",
|
||||
"NO", "NONE", "NOT", "NULL", "NULLIF", "NUMBER", "NUMERIC",
|
||||
"OBJECT", "OF", "OFFLINE", "OFFSET", "OLD", "ON", "ONLINE", "ONLY",
|
||||
"OPAQUE", "OPEN", "OPERATOR", "OPTION", "OR", "ORDER", "ORDINALITY",
|
||||
"OTHER", "OTHERS", "OUT", "OUTER", "OVER", "OVERLAPS", "OVERRIDE", "OWNER",
|
||||
"PAD", "PARALLEL", "PARAMETER", "PARAMETERS", "PARTIAL", "PARTITION",
|
||||
"PASSWORD", "PATH", "PERCENT", "PERCENTILE", "PERMISSION", "PERMISSIONS",
|
||||
"PIPE", "PIPELINED", "PLAN", "POOL", "POSITION", "PRECISION", "PREPARE",
|
||||
"PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PROCESSED", "PROJECT",
|
||||
"PROJECTION", "PROJECTIONS", "PROTO", "PULL", "PUT",
|
||||
"QUERY", "QUIT", "QUORUM",
|
||||
"RAISE", "RANDOM", "RANGE", "RANK", "RAW", "READ", "READS", "REAL",
|
||||
"REBUILD", "RECORD", "RECURSIVE", "REDUCE", "REF", "REFERENCE", "REFERENCES",
|
||||
"REFERENCING", "REGEXP", "REGION", "REINDEX", "RELATIVE", "RELEASE",
|
||||
"REMAINDER", "RENAME", "REPEAT", "REPLACE", "REQUEST", "RESET", "RESIGNAL",
|
||||
"RESOURCE", "RESPONSE", "RESTORE", "RESTRICT", "RESULT", "RETURN",
|
||||
"RETURNING", "RETURNS", "REVERSE", "REVOKE", "RIGHT", "ROLE", "ROLES",
|
||||
"ROLLBACK", "ROLLUP", "ROUTINE", "ROW", "ROWS", "RULE",
|
||||
"SAVEPOINT", "SCAN", "SCHEMA", "SCOPE", "SCROLL", "SEARCH", "SECOND",
|
||||
"SECTION", "SEGMENT", "SEGMENTS", "SELECT", "SELF", "SEMI", "SENSITIVE",
|
||||
"SEQUENCE", "SERIALIZABLE", "SESSION", "SET", "SETS", "SIGNAL", "SIMILAR",
|
||||
"SIZE", "SKEWED", "SMALLINT", "SNAPSHOT", "SOME", "SOURCE", "SPACE",
|
||||
"SPACES", "SPARSE", "SPECIFIC", "SPECIFICTYPE", "SPLIT", "SQL", "SQLCODE",
|
||||
"SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "START", "STATE",
|
||||
"STATIC", "STATUS", "STORAGE", "STORE", "STORED", "STREAM", "STRING",
|
||||
"STRUCT", "STYLE", "SUB", "SUBMULTISET", "SUBPAGES", "SUBSTRING", "SUM",
|
||||
"SYMMETRIC", "SYSTEM",
|
||||
"TABLE", "TABLESAMPLE", "TEMP", "TEMPORARY", "TERMINATED", "TEXT", "THAN",
|
||||
"THEN", "THROUGHPUT", "TINYINT", "TO", "TOKEN", "TOTAL", "TOUCH",
|
||||
"TRAILING", "TRANSACTION", "TRANSFORM", "TRANSLATE", "TRANSLATION", "TREAT",
|
||||
"TRIGGER", "TRIM", "TRUE", "TRUNCATE", "TTL", "TUPLE", "TYPE",
|
||||
"UNDER", "UNDO", "UNION", "UNIQUE", "UNIT", "UNKNOWN", "UNLOGGED",
|
||||
"UNNEST", "UNPROCESSED", "UNSIGNED", "UNTIL", "UPDATE", "UPPER", "URL",
|
||||
"USAGE", "USE", "USER", "UUID",
|
||||
"VACUUM", "VALUE", "VALUED", "VALUES", "VARCHAR", "VARIABLE", "VARIANCE",
|
||||
"VARYING", "VIEW", "VIEWS", "VIRTUAL", "VOID",
|
||||
"WAIT", "WHEN", "WHERE", "WHILE", "WINDOW", "WITH", "WITHIN", "WITHOUT",
|
||||
"WRITE",
|
||||
"YEAR",
|
||||
"ZONE"
|
||||
);
|
||||
|
||||
/**
|
||||
* Validates that the expression does not use any reserved words as bare attribute names.
|
||||
* Throws ValidationException if a reserved word is found without a # alias.
|
||||
*/
|
||||
static void check(String expression, String expressionType) {
|
||||
if (expression == null || expression.isBlank()) return;
|
||||
List<String> bareIdents = extractBareIdentifiers(expression);
|
||||
for (String ident : bareIdents) {
|
||||
String upper = ident.toUpperCase();
|
||||
if (CLAUSE_KEYWORDS.contains(upper)) continue;
|
||||
if (RESERVED.contains(upper)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid " + expressionType + ": Attribute name is a reserved keyword; "
|
||||
+ "reserved word: " + ident, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> extractBareIdentifiers(String expr) {
|
||||
List<String> result = new ArrayList<>();
|
||||
int i = 0;
|
||||
int len = expr.length();
|
||||
while (i < len) {
|
||||
char c = expr.charAt(i);
|
||||
if (c == '#' || c == ':') {
|
||||
// Skip alias or value ref
|
||||
i++;
|
||||
while (i < len && isIdentChar(expr.charAt(i))) i++;
|
||||
} else if (Character.isLetter(c) || c == '_') {
|
||||
int start = i;
|
||||
while (i < len && isIdentChar(expr.charAt(i))) i++;
|
||||
String word = expr.substring(start, i);
|
||||
// Skip whitespace to check if followed by '('
|
||||
int j = i;
|
||||
while (j < len && expr.charAt(j) == ' ') j++;
|
||||
if (j < len && expr.charAt(j) == '(') {
|
||||
// Function call — skip
|
||||
} else {
|
||||
result.add(word);
|
||||
}
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static boolean isIdentChar(char c) {
|
||||
return Character.isLetterOrDigit(c) || c == '_';
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+57
-15
@@ -11,7 +11,7 @@ import java.util.regex.Pattern;
|
||||
*/
|
||||
public final class DynamoDbTableNames {
|
||||
|
||||
private static final Pattern TABLE_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9_.-]{3,255}");
|
||||
private static final Pattern TABLE_NAME_CHARS = Pattern.compile("[a-zA-Z0-9_.\\-]+");
|
||||
private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
|
||||
|
||||
private DynamoDbTableNames() {}
|
||||
@@ -23,18 +23,23 @@ public final class DynamoDbTableNames {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a short table name. Rejects ARN-form input: callers (e.g. CreateTable)
|
||||
* must persist a canonical short name, not an ARN that would produce ARN-on-ARN
|
||||
* values when derived into {@code TableArn}.
|
||||
* Validates a short table name for use with CreateTable.
|
||||
* CreateTable requires min length 3 and missing TableName is a distinct error.
|
||||
*/
|
||||
public static String requireShortName(String input) {
|
||||
if (input == null || input.isBlank()) {
|
||||
throw invalid("TableName must not be blank");
|
||||
if (input == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The parameter 'TableName' is required but was not present in the request", 400);
|
||||
}
|
||||
if (input.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + input
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3", 400);
|
||||
}
|
||||
if (input.startsWith("arn:")) {
|
||||
throw invalid("TableName must be a short name, not an ARN: " + input);
|
||||
}
|
||||
validateTableName(input);
|
||||
validateTableNameForCreate(input);
|
||||
return input;
|
||||
}
|
||||
|
||||
@@ -47,13 +52,18 @@ public final class DynamoDbTableNames {
|
||||
}
|
||||
|
||||
private static ResolvedTableRef resolveInternal(String input) {
|
||||
if (input == null || input.isBlank()) {
|
||||
throw invalid("TableName must not be blank");
|
||||
if (input == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value null at 'tableName' failed to satisfy constraint: Member must not be null", 400);
|
||||
}
|
||||
if (input.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 1", 400);
|
||||
}
|
||||
if (input.startsWith("arn:")) {
|
||||
return parseArn(input);
|
||||
}
|
||||
validateTableName(input);
|
||||
validateTableNameForOps(input);
|
||||
return new ResolvedTableRef(input, null);
|
||||
}
|
||||
|
||||
@@ -94,17 +104,49 @@ public final class DynamoDbTableNames {
|
||||
throw invalid("Invalid table ARN: " + input);
|
||||
}
|
||||
|
||||
validateTableName(tableName);
|
||||
validateTableNameForOps(tableName);
|
||||
return new ResolvedTableRef(tableName, region);
|
||||
}
|
||||
|
||||
private static void validateTableName(String tableName) {
|
||||
if (!TABLE_NAME_PATTERN.matcher(tableName).matches()) {
|
||||
throw invalid("Invalid TableName: " + tableName);
|
||||
// Validation for CreateTable: min length 3, max 255, pattern
|
||||
private static void validateTableNameForCreate(String tableName) {
|
||||
if (tableName.length() < 3) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3", 400);
|
||||
}
|
||||
if (tableName.length() > 255) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must have length less than or equal to 255", 400);
|
||||
}
|
||||
if (!TABLE_NAME_CHARS.matcher(tableName).matches()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Validation for other operations (PutItem, GetItem, etc.): min length 3, max 255, pattern
|
||||
private static void validateTableNameForOps(String tableName) {
|
||||
if (tableName.length() < 3) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3", 400);
|
||||
}
|
||||
if (tableName.length() > 255) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must have length less than or equal to 255", 400);
|
||||
}
|
||||
if (!TABLE_NAME_CHARS.matcher(tableName).matches()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + tableName
|
||||
+ "' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterValue", message, 400);
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
+203
-31
@@ -1,9 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -33,6 +36,7 @@ final class ExpressionEvaluator {
|
||||
GE, // >=
|
||||
// Punctuation
|
||||
LPAREN, RPAREN, COMMA, DOT,
|
||||
LIST_INDEX, // [n] — list element access
|
||||
// Functions
|
||||
FUNCTION, // attribute_exists, attribute_not_exists, begins_with, contains, size
|
||||
// End
|
||||
@@ -63,6 +67,21 @@ final class ExpressionEvaluator {
|
||||
if (c == ',') { tokens.add(new Token(TokenType.COMMA, ",", i)); i++; continue; }
|
||||
if (c == '.') { tokens.add(new Token(TokenType.DOT, ".", i)); i++; continue; }
|
||||
|
||||
// List index [n]
|
||||
if (c == '[') {
|
||||
int start = i;
|
||||
i++; // skip '['
|
||||
while (i < len && Character.isDigit(expression.charAt(i))) i++;
|
||||
if (i < len && expression.charAt(i) == ']') {
|
||||
i++; // skip ']'
|
||||
tokens.add(new Token(TokenType.LIST_INDEX, expression.substring(start, i), start));
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Expected ']' after list index at position " + i + " in: " + expression);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Comparators (must check <> and <= before <, >= before >)
|
||||
if (c == '<') {
|
||||
if (i + 1 < len && expression.charAt(i + 1) == '>') {
|
||||
@@ -120,7 +139,8 @@ final class ExpressionEvaluator {
|
||||
case "not" -> tokens.add(new Token(TokenType.NOT, word, start));
|
||||
case "in" -> tokens.add(new Token(TokenType.IN, word, start));
|
||||
case "between" -> tokens.add(new Token(TokenType.BETWEEN, word, start));
|
||||
case "attribute_exists", "attribute_not_exists", "begins_with", "contains", "size" ->
|
||||
case "attribute_exists", "attribute_not_exists", "begins_with", "contains", "size",
|
||||
"attribute_type" ->
|
||||
tokens.add(new Token(TokenType.FUNCTION, word, start));
|
||||
default -> tokens.add(new Token(TokenType.IDENTIFIER, word, start));
|
||||
}
|
||||
@@ -291,15 +311,23 @@ final class ExpressionEvaluator {
|
||||
return new PlaceholderOperand(advance().value());
|
||||
}
|
||||
|
||||
// Path: identifier or #name, possibly dotted
|
||||
// Path: identifier or #name, possibly dotted with nested [n] list indices
|
||||
if (current.type() == TokenType.IDENTIFIER || current.type() == TokenType.NAME_REF) {
|
||||
var segments = new ArrayList<String>();
|
||||
segments.add(advance().value());
|
||||
// Consume any immediately-following list indices (no dot needed before [n])
|
||||
while (peek().type() == TokenType.LIST_INDEX) {
|
||||
segments.add(advance().value());
|
||||
}
|
||||
// Consume .name and .name[n] sequences
|
||||
while (peek().type() == TokenType.DOT) {
|
||||
advance(); // consume dot
|
||||
Token seg = peek();
|
||||
if (seg.type() == TokenType.IDENTIFIER || seg.type() == TokenType.NAME_REF) {
|
||||
segments.add(advance().value());
|
||||
while (peek().type() == TokenType.LIST_INDEX) {
|
||||
segments.add(advance().value());
|
||||
}
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"Expected identifier after '.' at position %d".formatted(seg.pos()));
|
||||
@@ -355,6 +383,24 @@ final class ExpressionEvaluator {
|
||||
static String[] splitKeyCondition(String expression) {
|
||||
if (expression == null || expression.isBlank()) return new String[]{expression, null};
|
||||
|
||||
// Strip a single layer of outer parens when they wrap the entire expression,
|
||||
// e.g. "(pk = :pk AND sk = :sk)" → "pk = :pk AND sk = :sk"
|
||||
String stripped = expression.strip();
|
||||
if (stripped.startsWith("(") && stripped.endsWith(")")) {
|
||||
int depth = 0;
|
||||
boolean wrapsAll = true;
|
||||
for (int i = 0; i < stripped.length() - 1; i++) {
|
||||
if (stripped.charAt(i) == '(') depth++;
|
||||
else if (stripped.charAt(i) == ')') {
|
||||
depth--;
|
||||
if (depth == 0) { wrapsAll = false; break; }
|
||||
}
|
||||
}
|
||||
if (wrapsAll) {
|
||||
expression = stripped.substring(1, stripped.length() - 1).strip();
|
||||
}
|
||||
}
|
||||
|
||||
var tokens = tokenize(expression.trim());
|
||||
// Find the top-level AND that separates PK from SK.
|
||||
// We need to skip AND tokens that are part of BETWEEN...AND.
|
||||
@@ -446,32 +492,37 @@ final class ExpressionEvaluator {
|
||||
|
||||
private static boolean evaluateComparison(CompareExpr cmp, JsonNode item,
|
||||
JsonNode exprAttrNames, JsonNode exprAttrValues) {
|
||||
String leftVal = resolveScalar(cmp.left(), item, exprAttrNames, exprAttrValues);
|
||||
String rightVal = resolveScalar(cmp.right(), item, exprAttrNames, exprAttrValues);
|
||||
|
||||
// DynamoDB: comparing a missing attribute with <> returns true
|
||||
if (leftVal == null && cmp.op() == TokenType.NE) return true;
|
||||
if (rightVal == null && cmp.op() == TokenType.NE) return true;
|
||||
if (leftVal == null || rightVal == null) return false;
|
||||
// For EQ/NE, resolve full attribute values to support set comparison
|
||||
if (cmp.op() == TokenType.EQ || cmp.op() == TokenType.NE) {
|
||||
JsonNode leftNode = resolveAttributeValue(cmp.left(), item, exprAttrNames, exprAttrValues);
|
||||
JsonNode rightNode = resolveAttributeValue(cmp.right(), item, exprAttrNames, exprAttrValues);
|
||||
if (leftNode == null && cmp.op() == TokenType.NE) return true;
|
||||
if (rightNode == null && cmp.op() == TokenType.NE) return true;
|
||||
if (leftNode == null || rightNode == null) return false;
|
||||
boolean equal = attributeValuesEqual(leftNode, rightNode);
|
||||
return cmp.op() == TokenType.EQ ? equal : !equal;
|
||||
}
|
||||
|
||||
JsonNode leftNode = resolveAttributeValue(cmp.left(), item, exprAttrNames, exprAttrValues);
|
||||
JsonNode rightNode = resolveAttributeValue(cmp.right(), item, exprAttrNames, exprAttrValues);
|
||||
if (leftNode == null || rightNode == null) return false;
|
||||
int cmpResult = compareAttributeValues(leftNode, rightNode);
|
||||
return switch (cmp.op()) {
|
||||
case EQ -> leftVal.equals(rightVal);
|
||||
case NE -> !leftVal.equals(rightVal);
|
||||
case LT -> compareValues(leftVal, rightVal) < 0;
|
||||
case LE -> compareValues(leftVal, rightVal) <= 0;
|
||||
case GT -> compareValues(leftVal, rightVal) > 0;
|
||||
case GE -> compareValues(leftVal, rightVal) >= 0;
|
||||
case LT -> cmpResult < 0;
|
||||
case LE -> cmpResult <= 0;
|
||||
case GT -> cmpResult > 0;
|
||||
case GE -> cmpResult >= 0;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean evaluateBetween(BetweenExpr bet, JsonNode item,
|
||||
JsonNode exprAttrNames, JsonNode exprAttrValues) {
|
||||
String val = resolveScalar(bet.value(), item, exprAttrNames, exprAttrValues);
|
||||
String low = resolveScalar(bet.low(), item, exprAttrNames, exprAttrValues);
|
||||
String high = resolveScalar(bet.high(), item, exprAttrNames, exprAttrValues);
|
||||
JsonNode val = resolveAttributeValue(bet.value(), item, exprAttrNames, exprAttrValues);
|
||||
JsonNode low = resolveAttributeValue(bet.low(), item, exprAttrNames, exprAttrValues);
|
||||
JsonNode high = resolveAttributeValue(bet.high(), item, exprAttrNames, exprAttrValues);
|
||||
if (val == null || low == null || high == null) return false;
|
||||
return compareValues(val, low) >= 0 && compareValues(val, high) <= 0;
|
||||
return compareAttributeValues(val, low) >= 0 && compareAttributeValues(val, high) <= 0;
|
||||
}
|
||||
|
||||
private static boolean evaluateIn(InExpr in, JsonNode item,
|
||||
@@ -507,8 +558,19 @@ final class ExpressionEvaluator {
|
||||
if (func.args().size() < 2) yield false;
|
||||
String path = resolveAttributePath(func.args().get(0), exprAttrNames);
|
||||
JsonNode attrNode = item != null ? resolveNestedAttribute(item, path) : null;
|
||||
JsonNode prefixNode = resolveAttributeValue(func.args().get(1), item, exprAttrNames, exprAttrValues);
|
||||
if (attrNode == null || prefixNode == null) yield false;
|
||||
if (attrNode.has("B") && prefixNode.has("B")) {
|
||||
byte[] attrBytes = java.util.Base64.getDecoder().decode(attrNode.get("B").asText());
|
||||
byte[] prefixBytes = java.util.Base64.getDecoder().decode(prefixNode.get("B").asText());
|
||||
if (prefixBytes.length > attrBytes.length) yield false;
|
||||
for (int bi = 0; bi < prefixBytes.length; bi++) {
|
||||
if (attrBytes[bi] != prefixBytes[bi]) yield false;
|
||||
}
|
||||
yield true;
|
||||
}
|
||||
String actual = extractScalarValue(attrNode);
|
||||
String prefix = resolveScalar(func.args().get(1), item, exprAttrNames, exprAttrValues);
|
||||
String prefix = extractScalarValue(prefixNode);
|
||||
yield actual != null && prefix != null && actual.startsWith(prefix);
|
||||
}
|
||||
case "contains" -> {
|
||||
@@ -516,6 +578,15 @@ final class ExpressionEvaluator {
|
||||
yield evaluateContains(func.args().get(0), func.args().get(1),
|
||||
item, exprAttrNames, exprAttrValues);
|
||||
}
|
||||
case "attribute_type" -> {
|
||||
if (func.args().size() < 2) yield false;
|
||||
String attrPath = resolveAttributePath(func.args().get(0), exprAttrNames);
|
||||
JsonNode attrVal = item != null ? resolveNestedAttribute(item, attrPath) : null;
|
||||
JsonNode typeNode = resolveAttributeValue(func.args().get(1), item, exprAttrNames, exprAttrValues);
|
||||
if (attrVal == null || typeNode == null) yield false;
|
||||
String typeCode = typeNode.has("S") ? typeNode.get("S").asText() : typeNode.asText();
|
||||
yield attrVal.has(typeCode);
|
||||
}
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
@@ -615,7 +686,18 @@ final class ExpressionEvaluator {
|
||||
String resolvedPath = resolvePathString(path, exprAttrNames);
|
||||
yield item != null ? resolveNestedAttribute(item, resolvedPath) : null;
|
||||
}
|
||||
case FunctionOperand _ -> null;
|
||||
case FunctionOperand func -> {
|
||||
if ("size".equalsIgnoreCase(func.functionName()) && !func.args().isEmpty()) {
|
||||
String path = resolveAttributePath(func.args().getFirst(), exprAttrNames);
|
||||
JsonNode attrNode = item != null ? resolveNestedAttribute(item, path) : null;
|
||||
if (attrNode != null) {
|
||||
ObjectNode numNode = JsonNodeFactory.instance.objectNode();
|
||||
numNode.put("N", String.valueOf(computeSize(attrNode)));
|
||||
yield numNode;
|
||||
}
|
||||
}
|
||||
yield null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -631,14 +713,18 @@ final class ExpressionEvaluator {
|
||||
private static String resolvePathString(PathOperand path, JsonNode exprAttrNames) {
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < path.segments().size(); i++) {
|
||||
if (i > 0) sb.append(".");
|
||||
String segment = path.segments().get(i);
|
||||
String resolved = resolveAttributeName(segment, exprAttrNames);
|
||||
// If the resolved name contains dots, escape them so resolveNestedAttribute treats it as one key
|
||||
if (segment.startsWith("#") && resolved != null) {
|
||||
resolved = resolved.replace(".", DOT_ESCAPE);
|
||||
if (segment.startsWith("[")) {
|
||||
// List index: append directly without preceding dot
|
||||
sb.append(segment);
|
||||
} else {
|
||||
if (i > 0) sb.append(".");
|
||||
String resolved = resolveAttributeName(segment, exprAttrNames);
|
||||
if (segment.startsWith("#") && resolved != null) {
|
||||
resolved = resolved.replace(".", DOT_ESCAPE);
|
||||
}
|
||||
sb.append(resolved);
|
||||
}
|
||||
sb.append(resolved);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -664,13 +750,43 @@ final class ExpressionEvaluator {
|
||||
return attrValue.asText();
|
||||
}
|
||||
|
||||
// Tokenizes a resolved path string (e.g. "a.b[0].c") into segments.
|
||||
// Each segment is either a plain attribute name or a "[n]" list index string.
|
||||
private static List<String> parsePathSegments(String path) {
|
||||
var segs = new ArrayList<String>();
|
||||
for (String dotPart : path.split("\\.")) {
|
||||
dotPart = dotPart.replace(DOT_ESCAPE, ".");
|
||||
int brk = dotPart.indexOf('[');
|
||||
if (brk < 0) {
|
||||
if (!dotPart.isEmpty()) segs.add(dotPart);
|
||||
} else {
|
||||
if (brk > 0) segs.add(dotPart.substring(0, brk));
|
||||
String rest = dotPart.substring(brk);
|
||||
int p = 0;
|
||||
while (p < rest.length() && rest.charAt(p) == '[') {
|
||||
int close = rest.indexOf(']', p);
|
||||
if (close < 0) break;
|
||||
segs.add(rest.substring(p, close + 1)); // "[n]"
|
||||
p = close + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return segs;
|
||||
}
|
||||
|
||||
private static JsonNode resolveNestedAttribute(JsonNode item, String path) {
|
||||
String[] segments = path.split("\\.");
|
||||
List<String> segments = parsePathSegments(path);
|
||||
JsonNode current = item;
|
||||
for (int i = 0; i < segments.length; i++) {
|
||||
for (int i = 0; i < segments.size(); i++) {
|
||||
if (current == null) return null;
|
||||
String segment = segments[i].replace(DOT_ESCAPE, ".");
|
||||
if (i == 0) {
|
||||
String segment = segments.get(i);
|
||||
if (segment.matches("\\[\\d+\\]")) {
|
||||
// List index navigation
|
||||
int idx = Integer.parseInt(segment.substring(1, segment.length() - 1));
|
||||
JsonNode listNode = current.has("L") ? current.get("L") : (current.isArray() ? current : null);
|
||||
if (listNode == null || !listNode.isArray() || idx >= listNode.size()) return null;
|
||||
current = listNode.get(idx);
|
||||
} else if (i == 0) {
|
||||
current = current.get(segment);
|
||||
} else {
|
||||
if (current.has("M")) {
|
||||
@@ -721,6 +837,36 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Set types: SS, NS, BS — order-independent comparison
|
||||
if (a.has("SS") && b.has("SS")) {
|
||||
JsonNode aArr = a.get("SS"), bArr = b.get("SS");
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
var aSet = new java.util.HashSet<String>();
|
||||
aArr.forEach(e -> aSet.add(e.asText()));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(e.asText())) return false; }
|
||||
return true;
|
||||
}
|
||||
if (a.has("SS") || b.has("SS")) return false;
|
||||
if (a.has("BS") && b.has("BS")) {
|
||||
JsonNode aArr = a.get("BS"), bArr = b.get("BS");
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
var aSet = new java.util.HashSet<String>();
|
||||
aArr.forEach(e -> aSet.add(e.asText()));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(e.asText())) return false; }
|
||||
return true;
|
||||
}
|
||||
if (a.has("BS") || b.has("BS")) return false;
|
||||
if (a.has("NS") && b.has("NS")) {
|
||||
JsonNode aArr = a.get("NS"), bArr = b.get("NS");
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
var aSet = new java.util.HashSet<BigDecimal>();
|
||||
try {
|
||||
aArr.forEach(e -> aSet.add(new BigDecimal(e.asText())));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(new BigDecimal(e.asText()))) return false; }
|
||||
} catch (NumberFormatException ex) { return false; }
|
||||
return true;
|
||||
}
|
||||
if (a.has("NS") || b.has("NS")) return false;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -732,6 +878,32 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
static int compareAttributeValues(JsonNode a, JsonNode b) {
|
||||
if (a.has("N") && b.has("N")) {
|
||||
try {
|
||||
return new BigDecimal(a.get("N").asText())
|
||||
.compareTo(new BigDecimal(b.get("N").asText()));
|
||||
} catch (NumberFormatException e) {
|
||||
return a.get("N").asText().compareTo(b.get("N").asText());
|
||||
}
|
||||
}
|
||||
if (a.has("B") && b.has("B")) {
|
||||
byte[] aBytes = Base64.getDecoder().decode(a.get("B").asText());
|
||||
byte[] bBytes = Base64.getDecoder().decode(b.get("B").asText());
|
||||
int minLen = Math.min(aBytes.length, bBytes.length);
|
||||
for (int i = 0; i < minLen; i++) {
|
||||
int diff = (aBytes[i] & 0xFF) - (bBytes[i] & 0xFF);
|
||||
if (diff != 0) return diff;
|
||||
}
|
||||
return Integer.compare(aBytes.length, bBytes.length);
|
||||
}
|
||||
String aStr = a.has("S") ? a.get("S").asText() : extractScalarValue(a);
|
||||
String bStr = b.has("S") ? b.get("S").asText() : extractScalarValue(b);
|
||||
if (aStr == null) aStr = "";
|
||||
if (bStr == null) bStr = "";
|
||||
return aStr.compareTo(bStr);
|
||||
}
|
||||
|
||||
private static int computeSize(JsonNode attrNode) {
|
||||
if (attrNode.has("S")) return attrNode.get("S").asText().length();
|
||||
if (attrNode.has("B")) return attrNode.get("B").asText().length(); // base64 length
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Applies a DynamoDB ProjectionExpression to a result item, returning a new
|
||||
* ObjectNode containing only the projected attributes.
|
||||
*/
|
||||
final class ProjectionEvaluator {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
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.
|
||||
*/
|
||||
static ObjectNode project(JsonNode item, String projectionExpression, JsonNode exprAttrNames) {
|
||||
if (item == null || projectionExpression == null || projectionExpression.isBlank()) {
|
||||
return (ObjectNode) item;
|
||||
}
|
||||
validateProjectionExpression(projectionExpression);
|
||||
DynamoDbReservedWords.check(projectionExpression, "ProjectionExpression");
|
||||
ObjectNode result = MAPPER.createObjectNode();
|
||||
for (String rawPath : splitProjectionPaths(projectionExpression)) {
|
||||
List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);
|
||||
if (segments.isEmpty()) continue;
|
||||
copyPath(item, result, segments, 0);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new ObjectNode containing only the named top-level attributes.
|
||||
* Used by AttributesToGet (no alias resolution, no nested paths).
|
||||
*/
|
||||
static ObjectNode trimToAttributes(ObjectNode item, Set<String> keep) {
|
||||
ObjectNode result = MAPPER.createObjectNode();
|
||||
item.fields().forEachRemaining(entry -> {
|
||||
if (keep.contains(entry.getKey())) {
|
||||
result.set(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
static void validateSyntax(String expression, String expressionType) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateProjectionExpression(String expression) {
|
||||
validateSyntax(expression, "ProjectionExpression");
|
||||
}
|
||||
|
||||
// ── Path splitting ──
|
||||
|
||||
private static List<String> splitProjectionPaths(String expression) {
|
||||
List<String> paths = new ArrayList<>();
|
||||
int depth = 0;
|
||||
int start = 0;
|
||||
for (int i = 0; i < expression.length(); i++) {
|
||||
char c = expression.charAt(i);
|
||||
if (c == '(') depth++;
|
||||
else if (c == ')') depth--;
|
||||
else if (c == ',' && depth == 0) {
|
||||
paths.add(expression.substring(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
if (start < expression.length()) {
|
||||
paths.add(expression.substring(start).trim());
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
// ── Path resolution ──
|
||||
|
||||
private static List<String> resolvePath(String path, JsonNode exprAttrNames) {
|
||||
List<String> segments = new ArrayList<>();
|
||||
// Tokenize on dots, preserving [n] bracket indices
|
||||
String[] parts = path.split("\\.");
|
||||
for (String part : parts) {
|
||||
// A part may end with [n] index(es) like "list[0]" or "[0]"
|
||||
int bracketIdx = part.indexOf('[');
|
||||
if (bracketIdx >= 0) {
|
||||
String name = part.substring(0, bracketIdx);
|
||||
if (!name.isEmpty()) {
|
||||
segments.add(resolveSegment(name, exprAttrNames));
|
||||
}
|
||||
// Parse each [n] suffix
|
||||
String rest = part.substring(bracketIdx);
|
||||
int i = 0;
|
||||
while (i < rest.length() && rest.charAt(i) == '[') {
|
||||
int close = rest.indexOf(']', i);
|
||||
if (close < 0) break;
|
||||
segments.add(rest.substring(i, close + 1)); // e.g. "[0]"
|
||||
i = close + 1;
|
||||
}
|
||||
} else {
|
||||
segments.add(resolveSegment(part, exprAttrNames));
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
private static String resolveSegment(String seg, JsonNode exprAttrNames) {
|
||||
if (seg.startsWith("#") && exprAttrNames != null) {
|
||||
JsonNode resolved = exprAttrNames.get(seg);
|
||||
return resolved != null ? resolved.asText() : seg;
|
||||
}
|
||||
return seg;
|
||||
}
|
||||
|
||||
// ── 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: copy the whole attribute node
|
||||
dest.set(seg, child);
|
||||
} else {
|
||||
String nextSeg = segments.get(idx + 1);
|
||||
if (nextSeg.matches("\\[\\d+\\]")) {
|
||||
// Next is a list index — extract just that element
|
||||
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()) {
|
||||
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);
|
||||
}
|
||||
} else if (child.has("M")) {
|
||||
// Nested map — recurse
|
||||
ObjectNode nestedDest = MAPPER.createObjectNode();
|
||||
copyPath(child.get("M"), nestedDest, segments, idx + 1);
|
||||
ObjectNode wrapper = MAPPER.createObjectNode();
|
||||
wrapper.set("M", nestedDest);
|
||||
dest.set(seg, wrapper);
|
||||
} else if (child.isObject()) {
|
||||
ObjectNode nestedDest = MAPPER.createObjectNode();
|
||||
copyPath(child, nestedDest, segments, idx + 1);
|
||||
dest.set(seg, nestedDest);
|
||||
} else {
|
||||
dest.set(seg, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-8
@@ -1,26 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Thrown when a TransactWriteItems condition check fails.
|
||||
* Carries per-item cancellation reasons for the AWS response.
|
||||
*/
|
||||
public class TransactionCanceledException extends AwsException {
|
||||
|
||||
private final List<String> cancellationReasons;
|
||||
public record CancellationReason(String code, JsonNode item) {}
|
||||
|
||||
public TransactionCanceledException(List<String> cancellationReasons) {
|
||||
private final List<CancellationReason> cancellationReasons;
|
||||
|
||||
public TransactionCanceledException(List<CancellationReason> cancellationReasons) {
|
||||
super("TransactionCanceledException",
|
||||
"Transaction cancelled, please refer cancellation reasons for specific reasons [" +
|
||||
String.join(", ", cancellationReasons) + "]",
|
||||
cancellationReasons.stream()
|
||||
.map(r -> r.code().isEmpty() ? "None" : r.code())
|
||||
.reduce((a, b) -> a + ", " + b).orElse("") + "]",
|
||||
400);
|
||||
this.cancellationReasons = cancellationReasons;
|
||||
}
|
||||
|
||||
public List<String> getCancellationReasons() {
|
||||
public List<CancellationReason> getCancellationReasons() {
|
||||
return cancellationReasons;
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -18,17 +18,27 @@ public class LocalSecondaryIndex {
|
||||
private List<KeySchemaElement> keySchema;
|
||||
private String indexArn;
|
||||
private String projectionType;
|
||||
private List<String> nonKeyAttributes;
|
||||
private long indexSizeBytes;
|
||||
private long itemCount;
|
||||
|
||||
public LocalSecondaryIndex() {}
|
||||
public LocalSecondaryIndex() {
|
||||
this.nonKeyAttributes = new java.util.ArrayList<>();
|
||||
}
|
||||
|
||||
public LocalSecondaryIndex(String indexName, List<KeySchemaElement> keySchema,
|
||||
String indexArn, String projectionType) {
|
||||
this(indexName, keySchema, indexArn, projectionType, null);
|
||||
}
|
||||
|
||||
public LocalSecondaryIndex(String indexName, List<KeySchemaElement> keySchema,
|
||||
String indexArn, String projectionType, List<String> nonKeyAttributes) {
|
||||
this.indexName = indexName;
|
||||
this.keySchema = keySchema;
|
||||
this.indexArn = indexArn;
|
||||
this.projectionType = projectionType != null ? projectionType : "ALL";
|
||||
this.nonKeyAttributes = "INCLUDE".equals(this.projectionType) && nonKeyAttributes != null
|
||||
? nonKeyAttributes : new java.util.ArrayList<>();
|
||||
}
|
||||
|
||||
public String getIndexName() { return indexName; }
|
||||
@@ -43,6 +53,9 @@ public class LocalSecondaryIndex {
|
||||
public String getProjectionType() { return projectionType; }
|
||||
public void setProjectionType(String projectionType) { this.projectionType = projectionType; }
|
||||
|
||||
public List<String> getNonKeyAttributes() { return nonKeyAttributes; }
|
||||
public void setNonKeyAttributes(List<String> nonKeyAttributes) { this.nonKeyAttributes = nonKeyAttributes; }
|
||||
|
||||
public long getIndexSizeBytes() { return indexSizeBytes; }
|
||||
public void setIndexSizeBytes(long indexSizeBytes) { this.indexSizeBytes = indexSizeBytes; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user