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

@@ -7,45 +7,116 @@ public class CsvParser {
private CsvParser() {}
/**
* Parses one comma separated line. A field that opens with a quote may hold commas, and a
* doubled quote inside it stands for a single quote. Backslashes stay literal, which is what
* S3 Select and Athena expect of their input.
*/
public static List<String> parseLine(String line) {
List<String> fields = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (inQuotes) {
if (c == '"') {
if (i + 1 < line.length() && line.charAt(i + 1) == '"') {
current.append('"');
i++;
} else {
inQuotes = false;
}
} else {
current.append(c);
}
} else {
if (c == '"') {
inQuotes = true;
} else if (c == ',') {
fields.add(current.toString());
current.setLength(0);
} else {
current.append(c);
}
}
}
fields.add(current.toString());
return fields;
return scan(line, ',', false).get(0).fields();
}
public static List<List<String>> parseAll(String content) {
return parseAll(content, ',');
}
/**
* Parses a whole text delimited document the way Step Functions reads an ItemReader dataset.
* On top of the quoting above, a quoted field may hold line breaks, a doubled quote in an
* unquoted field stands for a single quote, and a backslash escapes another backslash, a
* quote or the delimiter. A backslash before anything else is dropped, as AWS documents. A
* line carrying no fields at all is skipped, as a trailing newline is normal.
*/
public static List<List<String>> parseAll(String content, char delimiter) {
List<List<String>> rows = new ArrayList<>();
for (String line : content.split("\\r?\\n")) {
if (!line.trim().isEmpty()) {
rows.add(parseLine(line));
for (Record record : scan(content, delimiter, true)) {
if (!record.blank()) {
rows.add(record.fields());
}
}
return rows;
}
private record Record(List<String> fields, boolean quoted) {
boolean blank() {
return !quoted && fields.size() == 1 && fields.get(0).isBlank();
}
}
/**
* The single quote tracking loop behind both entry points, so the escaping rules live in one
* place. Only a quote opening a field starts a quoted run: a quote further in is literal, which
* is what lets an unquoted field carry a doubled quote. Always returns at least one record.
*/
private static List<Record> scan(String content, char delimiter, boolean backslashEscapes) {
List<Record> records = new ArrayList<>();
List<String> fields = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean inQuotes = false;
boolean quoted = false;
boolean fieldStart = true;
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
char next = i + 1 < content.length() ? content.charAt(i + 1) : '\0';
if (backslashEscapes && c == '\\' && i + 1 < content.length()) {
if (next == '\\' || next == '"' || next == delimiter) {
field.append(next);
i++;
}
fieldStart = false;
continue;
}
if (c == '"') {
if (inQuotes) {
if (next == '"') {
field.append('"');
i++;
} else {
inQuotes = false;
}
} else if (fieldStart) {
inQuotes = true;
quoted = true;
} else {
field.append('"');
if (next == '"') {
i++;
}
}
fieldStart = false;
continue;
}
if (inQuotes) {
field.append(c);
continue;
}
if (c == delimiter) {
fields.add(field.toString());
field.setLength(0);
fieldStart = true;
} else if (c == '\n' || c == '\r') {
if (c == '\r' && next == '\n') {
i++;
}
fields.add(field.toString());
field.setLength(0);
records.add(new Record(fields, quoted));
fields = new ArrayList<>();
quoted = false;
fieldStart = true;
} else {
field.append(c);
fieldStart = false;
}
}
fields.add(field.toString());
records.add(new Record(fields, quoted));
return records;
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.CsvParser;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.XmlParser;
@@ -3077,7 +3078,7 @@ public class AslExecutor {
}
String inputType = itemReader.path("ReaderConfig").path("InputType").asText(null);
if (!"JSON".equals(inputType) && !"JSONL".equals(inputType)) {
if (!"JSON".equals(inputType) && !"JSONL".equals(inputType) && !"CSV".equals(inputType)) {
throw new FailStateException("States.ItemReaderFailed",
"ItemReader InputType " + inputType + " is not yet implemented by the emulator");
}
@@ -3095,6 +3096,10 @@ public class AslExecutor {
return new ResolvedMapItems(applyMaxItems(itemReader, readJsonLines(object.getData())),
MapItemsSource.ITEM_READER_ARRAY);
}
if ("CSV".equals(inputType)) {
return new ResolvedMapItems(applyMaxItems(itemReader, readCsvRows(itemReader, object.getData())),
MapItemsSource.ITEM_READER_ARRAY);
}
JsonNode items = objectMapper.readTree(object.getData());
items = applyItemsPointer(itemReader, items);
if (items.isObject()) {
@@ -3130,6 +3135,56 @@ public class AslExecutor {
return items;
}
/**
* Each data row becomes an object keyed by the headers. A row shorter than the headers pads
* with empty strings and a longer one drops the surplus, as on AWS. Every value is a string.
*/
private ArrayNode readCsvRows(JsonNode itemReader, byte[] data) {
JsonNode readerConfig = itemReader.path("ReaderConfig");
String headerLocation = readerConfig.path("CSVHeaderLocation").asText("FIRST_ROW");
List<List<String>> rows = CsvParser.parseAll(new String(data, StandardCharsets.UTF_8),
csvDelimiter(readerConfig.path("CSVDelimiter").asText("COMMA")));
List<String> headers;
int firstDataRow;
if ("GIVEN".equals(headerLocation)) {
headers = new ArrayList<>();
for (JsonNode header : readerConfig.path("CSVHeaders")) {
headers.add(header.asText());
}
firstDataRow = 0;
} else if ("FIRST_ROW".equals(headerLocation)) {
headers = rows.isEmpty() ? List.of() : rows.get(0);
firstDataRow = 1;
} else {
throw new FailStateException("States.ItemReaderFailed",
"ItemReader CSVHeaderLocation " + headerLocation + " is not supported");
}
ArrayNode items = objectMapper.createArrayNode();
for (int row = firstDataRow; row < rows.size(); row++) {
List<String> values = rows.get(row);
ObjectNode item = objectMapper.createObjectNode();
for (int column = 0; column < headers.size(); column++) {
item.put(headers.get(column), column < values.size() ? values.get(column) : "");
}
items.add(item);
}
return items;
}
private char csvDelimiter(String delimiter) {
return switch (delimiter) {
case "COMMA" -> ',';
case "PIPE" -> '|';
case "SEMICOLON" -> ';';
case "SPACE" -> ' ';
case "TAB" -> '\t';
default -> throw new FailStateException("States.ItemReaderFailed",
"ItemReader CSVDelimiter " + delimiter + " is not supported");
};
}
private JsonNode resolveItemReaderParameters(JsonNode itemReader, JsonNode input, JsonNode context,
boolean jsonata, ObjectNode variables) throws Exception {
if (jsonata && itemReader.has("Arguments")) {