feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets (#1588)

* feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets

* feat(stepfunctions): support Map ItemReader for S3-backed JSON datasets

* fix(stepfunctions): surface non-array ItemReader JSON as ItemReaderFailed

* fix(stepfunctions): align ItemReader runtime failures with emulator support

* refactor(stepfunctions): remove unused state machine parameter from resolveMapItems

* fix(stepfunctions): require DISTRIBUTED mode for ItemReader maps

* fix(stepfunctions): surface unimplemented ItemReader input types as ItemReaderFailed

* fix(stepfunctions): update AslExecutorCatchTest for constructor changes

* fix(stepfunctions): align ItemReader JSON object handling with AWS

* fix(stepfunctions): support ItemReader ItemsPointer for JSON datasets

* fix(stepfunctions): align ItemReader mode and JSONata arguments with AWS

* fix(stepfunctions): preserve array item context for Key/Value-shaped data
This commit is contained in:
shrimptails-f authored and GitHub committed 2026-07-06 22:51:39 -05:00
1 parent a40dc52f4d
commit 36ef98047e
5 files changed
+1441 -33

No files matched your search

@@ -23,6 +23,8 @@ import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
@@ -65,6 +67,15 @@ import java.util.function.BiConsumer;
@ApplicationScoped
public class AslExecutor {
private enum MapItemsSource {
DEFAULT,
ITEM_READER_ARRAY,
ITEM_READER_OBJECT
}
private record ResolvedMapItems(JsonNode items, MapItemsSource source) {
}
private static final Logger LOG = Logger.getLogger(AslExecutor.class);
private static final int MAX_WAIT_SECONDS = 30;
@@ -1362,19 +1373,15 @@ public class AslExecutor {
private StateResult executeMapState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
boolean jsonata, String topLevelQueryLanguage, JsonNode context) throws Exception {
JsonNode items;
if (jsonata && stateDef.has("Items")) {
JsonNode itemsNode = stateDef.get("Items");
if (itemsNode.isTextual() && JsonataEvaluator.isExpression(itemsNode.asText())) {
JsonNode statesVar = buildStatesVar(input, null, context);
items = jsonataEvaluator.evaluate(itemsNode.asText(), statesVar);
} else {
items = itemsNode;
if (stateDef.has("ItemReader")) {
String mode = stateDef.path("ItemProcessor").path("ProcessorConfig").path("Mode").asText("INLINE");
if (!"DISTRIBUTED".equals(mode)) {
throw new FailStateException("States.Runtime",
"The ItemReader, ItemBatcher and ResultWriter fields are not supported for INLINE maps");
}
} else {
JsonNode itemsPath = stateDef.path("ItemsPath");
items = itemsPath.isMissingNode() ? input : resolvePath(itemsPath.asText("$"), input);
}
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, input, jsonata, context);
JsonNode items = resolvedItems.items();
if (!items.isArray()) {
throw new FailStateException("States.Runtime", "Items must reference an array");
@@ -1395,20 +1402,25 @@ public class AslExecutor {
ArrayNode results = objectMapper.createArrayNode();
int index = 0;
for (JsonNode item : items) {
ObjectNode iterContext = ((ObjectNode) context).deepCopy();
ObjectNode mapCtx = objectMapper.createObjectNode();
ObjectNode mapItem = objectMapper.createObjectNode();
mapItem.put("Index", index);
if (resolvedItems.source() == MapItemsSource.ITEM_READER_OBJECT) {
mapItem.put("Key", item.path("Key").asText());
mapItem.set("Value", item.get("Value"));
} else {
mapItem.set("Value", item);
}
mapCtx.set("Item", mapItem);
iterContext.set("Map", mapCtx);
JsonNode iterInput = item;
if (itemTransform != null) {
// Enrich context with Map.Item.Index and Map.Item.Value for $$.Map.* references.
// $ in ItemSelector resolves against the Map state's effective input, not the item.
ObjectNode iterContext = ((ObjectNode) context).deepCopy();
ObjectNode mapCtx = objectMapper.createObjectNode();
ObjectNode mapItem = objectMapper.createObjectNode();
mapItem.put("Index", index);
mapItem.set("Value", item);
mapCtx.set("Item", mapItem);
iterContext.set("Map", mapCtx);
iterInput = resolveParameters(itemTransform, mapInput, iterContext);
}
results.add(executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, context));
results.add(executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, iterContext));
index++;
}
@@ -1426,6 +1438,119 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
private ResolvedMapItems resolveMapItems(JsonNode stateDef, JsonNode input,
boolean jsonata, JsonNode context) throws Exception {
if (jsonata && stateDef.has("Items")) {
JsonNode itemsNode = stateDef.get("Items");
if (itemsNode.isTextual() && JsonataEvaluator.isExpression(itemsNode.asText())) {
JsonNode statesVar = buildStatesVar(input, null, context);
return new ResolvedMapItems(jsonataEvaluator.evaluate(itemsNode.asText(), statesVar),
MapItemsSource.DEFAULT);
}
return new ResolvedMapItems(itemsNode, MapItemsSource.DEFAULT);
}
if (stateDef.has("ItemReader")) {
return resolveItemReaderItems(stateDef.get("ItemReader"), input, context, jsonata);
}
JsonNode itemsPath = stateDef.path("ItemsPath");
return new ResolvedMapItems(itemsPath.isMissingNode() ? input : resolvePath(itemsPath.asText("$"), input),
MapItemsSource.DEFAULT);
}
private ResolvedMapItems resolveItemReaderItems(JsonNode itemReader, JsonNode input,
JsonNode context, boolean jsonata) throws Exception {
String resource = itemReader.path("Resource").asText(null);
if ("arn:aws:states:::s3:listObjectsV2".equals(resource)) {
throw new FailStateException("States.ItemReaderFailed",
"ItemReader resource arn:aws:states:::s3:listObjectsV2 is not yet implemented by the emulator");
}
if (!"arn:aws:states:::s3:getObject".equals(resource)) {
throw new FailStateException("States.Runtime", "Unsupported ItemReader resource: " + resource);
}
String inputType = itemReader.path("ReaderConfig").path("InputType").asText(null);
if (!"JSON".equals(inputType)) {
throw new FailStateException("States.ItemReaderFailed",
"ItemReader InputType " + inputType + " is not yet implemented by the emulator");
}
JsonNode resolvedParameters;
if (jsonata && itemReader.has("Arguments")) {
JsonNode statesVar = buildStatesVar(input, null, context);
resolvedParameters = jsonataEvaluator.resolveTemplate(itemReader.get("Arguments"), statesVar);
} else {
JsonNode parameters = itemReader.path("Parameters");
resolvedParameters = resolveParameters(parameters, input, context);
}
String bucket = resolvedParameters.path("Bucket").asText(null);
String key = resolvedParameters.path("Key").asText(null);
if (bucket == null || key == null) {
throw new FailStateException("States.Runtime", "ItemReader Parameters must include Bucket and Key");
}
try {
S3Object object = s3Service.getObject(bucket, key);
JsonNode items = objectMapper.readTree(object.getData());
items = applyItemsPointer(itemReader, items);
if (items.isObject()) {
return new ResolvedMapItems(applyMaxItems(itemReader, normalizeObjectItems(items)),
MapItemsSource.ITEM_READER_OBJECT);
}
if (!items.isArray()) {
throw new FailStateException("States.ItemReaderFailed",
"Attempting to map over non-iterable node.");
}
return new ResolvedMapItems(applyMaxItems(itemReader, items), MapItemsSource.ITEM_READER_ARRAY);
} catch (AwsException e) {
throw new FailStateException("States.ItemReaderFailed", e.getMessage());
} catch (FailStateException e) {
throw e;
} catch (Exception e) {
throw new FailStateException("States.ItemReaderFailed",
e.getMessage() != null ? e.getMessage() : "Failed to parse ItemReader input");
}
}
private ArrayNode normalizeObjectItems(JsonNode items) {
ArrayNode normalized = objectMapper.createArrayNode();
items.fields().forEachRemaining(entry -> {
ObjectNode objectItem = objectMapper.createObjectNode();
objectItem.put("Key", entry.getKey());
objectItem.set("Value", entry.getValue());
normalized.add(objectItem);
});
return normalized;
}
private JsonNode applyItemsPointer(JsonNode itemReader, JsonNode items) {
String itemsPointer = itemReader.path("ReaderConfig").path("ItemsPointer").asText(null);
if (itemsPointer == null || itemsPointer.isEmpty()) {
return items;
}
JsonNode pointedItems = items.at(itemsPointer);
if (pointedItems.isMissingNode()) {
throw new FailStateException("States.ItemReaderFailed",
"The provided ReaderConfig.ItemsPointer does not match any valid path in the JSON structure.");
}
return pointedItems;
}
private JsonNode applyMaxItems(JsonNode itemReader, JsonNode items) {
int maxItems = itemReader.path("ReaderConfig").path("MaxItems").asInt(0);
if (maxItems <= 0 || !items.isArray() || items.size() <= maxItems) {
return items;
}
ArrayNode limited = objectMapper.createArrayNode();
for (int i = 0; i < maxItems; i++) {
limited.add(items.get(i));
}
return limited;
}
private JsonNode executeBranch(String startAt, JsonNode states, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context) throws Exception {
List<HistoryEvent> ignored = new ArrayList<>();
@@ -49,6 +49,11 @@ public class StepFunctionsService implements Resettable {
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
private static final Set<String> JSONPATH_ONLY_FIELDS = Set.of(
"InputPath", "OutputPath", "ResultPath", "ResultSelector", "Parameters", "Result", "ItemsPath");
private static final Set<String> ITEM_READER_RESOURCES = Set.of(
"arn:aws:states:::s3:getObject",
"arn:aws:states:::s3:listObjectsV2");
private static final Set<String> ITEM_READER_INPUT_TYPES = Set.of(
"MANIFEST", "JSON", "CSV", "JSONL", "PARQUET");
@Inject
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
@@ -417,10 +422,10 @@ public class StepFunctionsService implements Resettable {
private static final int MAX_DEFINITION_LENGTH = 1_048_576;
private static final String PARSE_ERROR_MARKER = "INVALID_JSON_DESCRIPTION:";
// Parse the structured location out of the validator's flat error strings,
// which currently encode it as "...field 'X' is only supported... at /States/Y".
// Parse the structured location out of validator flat error strings,
// which currently encode it as "...field 'X' ... at /States/Y".
// AWS's published Diagnostic.location format is "/States/<StateName>/<FieldName>".
private static final Pattern FIELD_PATTERN = Pattern.compile("field '([^']+)' is only supported");
private static final Pattern FIELD_PATTERN = Pattern.compile("field '([^']+)'");
private static final Pattern LOCATION_SUFFIX_PATTERN = Pattern.compile(" at (/States/\\S+)$");
/**
@@ -492,7 +497,11 @@ public class StepFunctionsService implements Resettable {
if (locM.find() && fieldM.find()) {
// Build the structured location and strip the redundant suffix
// from the message, matching AWS's wire format.
location = locM.group(1) + "/" + fieldM.group(1);
location = locM.group(1);
String field = fieldM.group(1);
if (!location.endsWith("/" + field)) {
location = location + "/" + field;
}
message = message.substring(0, locM.start()).trim();
}
}
@@ -552,5 +561,26 @@ public class StepFunctionsService implements Resettable {
}
}
}
if ("Map".equals(stateDef.path("Type").asText()) && stateDef.has("ItemReader")) {
validateItemReader(stateName, stateDef, errors);
}
}
private void validateItemReader(String stateName, JsonNode stateDef, List<String> errors) {
JsonNode itemReader = stateDef.get("ItemReader");
String resource = itemReader.path("Resource").asText(null);
if (resource != null && !ITEM_READER_RESOURCES.contains(resource)) {
errors.add("The field 'Resource' does not match any of the allowed values. Examples: "
+ "[arn:<partition>:states:::s3:getObject, arn:<partition>:states:::s3:listObjectsV2]"
+ " at /States/" + stateName + "/ItemReader/Resource");
}
String inputType = itemReader.path("ReaderConfig").path("InputType").asText(null);
if (inputType != null && !ITEM_READER_INPUT_TYPES.contains(inputType)) {
errors.add("The field 'InputType' should have one of these values: "
+ "[MANIFEST, JSON, CSV, JSONL, PARQUET]"
+ " at /States/" + stateName + "/ItemReader/ReaderConfig/InputType");
}
}
}