feat(sfn): support ItemReader InputType CSV (#3603)

* feat(sfn): support ItemReader InputType CSV

A Distributed Map can read a CSV dataset through ItemReader. Field names come
from the first row, or from ReaderConfig.CSVHeaders when CSVHeaderLocation is
GIVEN, and each data row becomes an object of string values.

Every value is a string, a row shorter than the headers pads with empty
strings, and a longer one drops the surplus, as AWS documents.

Drops the assertion that CSV is not implemented, which this replaces.

* feat(sfn): honour CSVDelimiter and quoted newlines in ItemReader CSV

ReaderConfig.CSVDelimiter selects COMMA, PIPE, SEMICOLON, SPACE or TAB. An
unsupported value fails the state with States.ItemReaderFailed.

CsvParser.parseAll gained a delimiter overload and now tracks quotes across
line breaks, so a quoted field may carry the delimiter or a newline without
ending the record. The single argument overload keeps comma behaviour for the
existing callers.

* fix(sfn): apply the documented CSV quote and backslash escaping

AWS preserves a doubled quote as a single quote whether or not the field is
quoted, so the reference dataset's {""MyKey"":""MyValue""} has to reach
States.StringToJson as {"MyKey":"MyValue"}. The reader dropped both quotes
instead: only a quote opening a field starts a quoted run, and the unquoted
case fell through to the toggle that consumed the pair.

Backslash escaping was missing as well. A backslash escapes another backslash,
a quote or the configured delimiter, and a backslash before anything else is
dropped.

parseLine and parseAll now share one scanner so the rules live in one place.
The backslash rules stay off for parseLine, which S3 Select and Athena use,
where a lone backslash is ordinary data.
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-09-17 10:14:45 -04:00
1 parent 6b389c33eb
commit d348686744
5 files changed
+643 -84

No files matched your search

@@ -0,0 +1,99 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CsvParserTest {
/**
* The file from the Step Functions "how Step Functions parses input CSV files" reference,
* whose third field carries a doubled quote and a line break and whose fourth field is an
* unquoted object relying on doubled quotes to survive States.StringToJson.
*/
@Test
void parsesTheAwsReferenceRecord() {
String csv = "abc,123,\"This string contains commas, a double quotation marks (\"\"), "
+ "and a newline (\n)\",{\"\"MyKey\"\":\"\"MyValue\"\"},\"[1,2,3]\"";
List<List<String>> rows = CsvParser.parseAll(csv, ',');
assertEquals(1, rows.size(), "the quoted newline must not split the record");
assertEquals(List.of(
"abc",
"123",
"This string contains commas, a double quotation marks (\"), and a newline (\n)",
"{\"MyKey\":\"MyValue\"}",
"[1,2,3]"), rows.get(0));
}
@Test
void doubledQuotesSurviveInAnUnquotedField() {
assertEquals(List.of("{\"MyKey\":\"MyValue\"}"),
CsvParser.parseAll("{\"\"MyKey\"\":\"\"MyValue\"\"}", ',').get(0));
}
@Test
void doubledQuotesSurviveInAQuotedField() {
assertEquals(List.of("a\"b"), CsvParser.parseAll("\"a\"\"b\"", ',').get(0));
}
/** A field that opens with a quote still follows CSV rules, so "" stays an empty field. */
@Test
void aQuotedEmptyFieldStaysEmpty() {
assertEquals(List.of("", "x"), CsvParser.parseAll("\"\",x", ',').get(0));
}
@Test
void backslashEscapesABackslash() {
String csv = "path,size\nC:\\\\Program Files\\\\MyApp.exe,6534512\n";
List<List<String>> rows = CsvParser.parseAll(csv, ',');
assertEquals(List.of("C:\\Program Files\\MyApp.exe", "6534512"), rows.get(1));
}
@Test
void backslashEscapesAQuoteAndTheDelimiter() {
assertEquals(List.of("a\"b"), CsvParser.parseAll("a\\\"b", ',').get(0));
assertEquals(List.of("a,b"), CsvParser.parseAll("a\\,b", ',').get(0));
assertEquals(List.of("a|b"), CsvParser.parseAll("a\\|b", '|').get(0));
}
/** AWS drops a backslash that precedes anything else and keeps the character. */
@Test
void backslashBeforeAnyOtherCharacterIsDropped() {
assertEquals(List.of("azb"), CsvParser.parseAll("a\\zb", ',').get(0));
}
@Test
void honoursANonCommaDelimiter() {
assertEquals(List.of("a", "b,c"), CsvParser.parseAll("a|\"b,c\"", '|').get(0));
}
@Test
void skipsABlankTrailingLine() {
assertEquals(1, CsvParser.parseAll("a,b\n", ',').size());
}
/**
* S3 Select and Athena read line by line and expect a backslash to stay put, so the backslash
* rules above must not reach parseLine.
*/
@Test
void parseLineKeepsBackslashesLiteral() {
assertEquals(List.of("C:\\Users\\x"), CsvParser.parseLine("C:\\Users\\x"));
}
@Test
void parseLineKeepsQuotedCommasTogether() {
assertEquals(List.of("a", "b,c"), CsvParser.parseLine("a,\"b,c\""));
}
@Test
void parseLineReturnsOneEmptyFieldForAnEmptyLine() {
assertEquals(List.of(""), CsvParser.parseLine(""));
}
}
@@ -1098,6 +1098,382 @@ class StepFunctionsJsonataIntegrationTest {
assertEquals("States.ItemReaderFailed", failure.jsonPath().getString("error"));
}
@Test
void distributedMapWithS3CsvItemReader_firstRowSuppliesHeaders() throws Exception {
createBucket("map-inputs-csv");
putObject("map-inputs-csv", "workers.csv", "workerId,team\nw1,\"alpha,beta\"\nw2,gamma\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV"
},
"Parameters": {
"Bucket": "map-inputs-csv",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
assertTrue(output.contains("\"workerId\":\"w1\"") || output.contains("\"workerId\": \"w1\""));
assertTrue(output.contains("\"team\":\"alpha,beta\"") || output.contains("\"team\": \"alpha,beta\""));
assertTrue(output.contains("\"workerId\":\"w2\"") || output.contains("\"workerId\": \"w2\""));
}
@Test
void distributedMapWithS3CsvItemReader_givenHeadersReadEveryRow() throws Exception {
createBucket("map-inputs-csv-given");
putObject("map-inputs-csv-given", "workers.csv", "w1,alpha\nw2,gamma\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV",
"CSVHeaderLocation": "GIVEN",
"CSVHeaders": ["workerId", "team"]
},
"Parameters": {
"Bucket": "map-inputs-csv-given",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-given-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
assertTrue(output.contains("\"workerId\":\"w1\"") || output.contains("\"workerId\": \"w1\""));
assertTrue(output.contains("\"workerId\":\"w2\"") || output.contains("\"workerId\": \"w2\""));
}
@Test
void distributedMapWithS3CsvItemReader_shortRowPadsWithEmptyValues() throws Exception {
createBucket("map-inputs-csv-ragged");
putObject("map-inputs-csv-ragged", "workers.csv", "workerId,team\nw1\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV"
},
"Parameters": {
"Bucket": "map-inputs-csv-ragged",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-ragged-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
assertTrue(output.contains("\"team\":\"\"") || output.contains("\"team\": \"\""));
}
@Test
void distributedMapWithS3CsvItemReader_honoursCsvDelimiter() throws Exception {
createBucket("map-inputs-csv-pipe");
putObject("map-inputs-csv-pipe", "workers.csv", "workerId|team\nw1|alpha\nw2|gamma\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV",
"CSVDelimiter": "PIPE"
},
"Parameters": {
"Bucket": "map-inputs-csv-pipe",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-pipe-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
assertTrue(output.contains("\"workerId\":\"w1\"") || output.contains("\"workerId\": \"w1\""));
assertTrue(output.contains("\"team\":\"alpha\"") || output.contains("\"team\": \"alpha\""));
assertTrue(output.contains("\"workerId\":\"w2\"") || output.contains("\"workerId\": \"w2\""));
}
@Test
void distributedMapWithS3CsvItemReader_keepsNewlinesInsideAQuotedField() throws Exception {
createBucket("map-inputs-csv-multiline");
putObject("map-inputs-csv-multiline", "workers.csv",
"workerId,note\nw1,\"first line\nsecond line\"\nw2,plain\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV"
},
"Parameters": {
"Bucket": "map-inputs-csv-multiline",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-multiline-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode items = new ObjectMapper().readTree(output);
assertEquals(2, items.size(), "the quoted line break must not split the record: " + output);
assertEquals("first line\nsecond line", items.get(0).path("note").asText());
assertEquals("plain", items.get(1).path("note").asText());
}
/**
* The file and the state machine from the AWS "how Step Functions parses input CSV files"
* reference. The unquoted MyObject field only survives States.StringToJson if the doubled
* quotes around its keys are preserved, so this pins the documented output.
*/
@Test
void distributedMapWithS3CsvItemReader_parsesTheAwsReferenceFile() throws Exception {
createBucket("map-inputs-csv-reference");
putObject("map-inputs-csv-reference", "myCSVInput.csv",
"abc,123,\"This string contains commas, a double quotation marks (\"\"), "
+ "and a newline (\n)\",{\"\"MyKey\"\":\"\"MyValue\"\"},\"[1,2,3]\"");
String definition = """
{
"StartAt": "Map",
"States": {
"Map": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV",
"CSVHeaderLocation": "GIVEN",
"CSVHeaders": ["MyLetters", "MyNumbers", "MyString",
"MyObject", "MyArray"]
},
"Parameters": {
"Bucket": "map-inputs-csv-reference",
"Key": "myCSVInput.csv"
}
},
"ItemSelector": {
"MyLetters.$": "$$.Map.Item.Value.MyLetters",
"MyNumbers.$": "States.StringToJson($$.Map.Item.Value.MyNumbers)",
"MyString.$": "$$.Map.Item.Value.MyString",
"MyObject.$": "States.StringToJson($$.Map.Item.Value.MyObject)",
"MyArray.$": "States.StringToJson($$.Map.Item.Value.MyArray)"
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-reference-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode items = new ObjectMapper().readTree(output);
assertEquals(1, items.size(), "the quoted newline must not split the record: " + output);
JsonNode item = items.get(0);
assertEquals("abc", item.path("MyLetters").asText());
assertEquals(123, item.path("MyNumbers").asInt());
assertEquals("This string contains commas, a double quotation marks (\"), "
+ "and a newline (\n)", item.path("MyString").asText());
assertEquals("MyValue", item.path("MyObject").path("MyKey").asText(),
"doubled quotes in an unquoted field must survive: " + output);
assertEquals(3, item.path("MyArray").size());
assertEquals(1, item.path("MyArray").get(0).asInt());
}
@Test
void distributedMapWithS3CsvItemReader_honoursBackslashEscapes() throws Exception {
createBucket("map-inputs-csv-backslash");
putObject("map-inputs-csv-backslash", "paths.csv",
"path,note\nC:\\\\Program Files\\\\MyApp.exe,a\\\"quoted\\\" word\n"
+ "second\\,field,dropped\\zslash\n");
String definition = """
{
"StartAt": "ProcessPaths",
"States": {
"ProcessPaths": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV"
},
"Parameters": {
"Bucket": "map-inputs-csv-backslash",
"Key": "paths.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-backslash-test", definition);
String execArn = startExecution(smArn, "{}");
String output = waitForExecution(execArn);
JsonNode items = new ObjectMapper().readTree(output);
assertEquals(2, items.size(), output);
assertEquals("C:\\Program Files\\MyApp.exe", items.get(0).path("path").asText());
assertEquals("a\"quoted\" word", items.get(0).path("note").asText());
assertEquals("second,field", items.get(1).path("path").asText(),
"an escaped delimiter must not split the field: " + output);
assertEquals("dropped" + "zslash", items.get(1).path("note").asText());
}
@Test
void distributedMapWithItemBatcher_groupsItemsIntoBatchesOfMaxItemsPerBatch() throws Exception {
String definition = """
@@ -3274,55 +3650,6 @@ class StepFunctionsJsonataIntegrationTest {
""", itemReaderFields);
}
@Test
void distributedMapWithCsvItemReader_failsWithNotImplementedItemReaderError() throws Exception {
createBucket("map-inputs-csv");
putObject("map-inputs-csv", "workers.csv", "workerId\nw1\n");
String definition = """
{
"StartAt": "ProcessWorkers",
"States": {
"ProcessWorkers": {
"Type": "Map",
"ItemReader": {
"Resource": "arn:aws:states:::s3:getObject",
"ReaderConfig": {
"InputType": "CSV"
},
"Parameters": {
"Bucket": "map-inputs-csv",
"Key": "workers.csv"
}
},
"ItemProcessor": {
"ProcessorConfig": {
"Mode": "DISTRIBUTED",
"ExecutionType": "STANDARD"
},
"StartAt": "PassItem",
"States": {
"PassItem": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("map-itemreader-s3-csv-test", definition);
String execArn = startExecution(smArn, "{}");
Response failure = waitForExecutionFailure(execArn);
assertEquals("FAILED", failure.jsonPath().getString("status"));
assertEquals("States.ItemReaderFailed", failure.jsonPath().getString("error"));
assertTrue(failure.jsonPath().getString("cause").contains("InputType CSV is not yet implemented by the emulator"));
}
@Test
void distributedMapWithUnsupportedItemReaderInputType_rejectedAtCreateStateMachine() {
String definition = """