Course › Week 3 · Iterators, real data, speed › Day 6 · lesson 20 of 42 · 50 min reading + 2–3 h practice
Build csv2json
100K survey rows to JSON Lines with validation, benchmarked against PHP.
On this page
This week’s tool joins everything the week taught: closures and iterators, serde, the csv crate and rayon. It turns a school-evaluation export into JSON Lines, one validated answer per line, the format an AI analysis pipeline or a bulk insert reads most easily.
Then the question the course started with: is it worth it? The same tool in PHP, the same input, measured on the same machine.
#dataWednesday 15:40
Sara · dataThe weekly evaluation export is over a million answers now. The Laravel import job reads it with collect(), hits the memory limit at about 600K rows, and when it does finish, a few bad rows have quietly become score 0.
Sara · dataWhat the analysis pipeline wants: JSON Lines, comments cleaned (lower-case, no punctuation, and Arabic must survive), and every rejected row listed with its line number so the schools can fix their data.
The layout
The same shape as logstat v2: a library that does the work, a thin main.rs.
csv2json/
├── Cargo.toml
└── src/
├── main.rs (flags, files, the summary line)
├── lib.rs (declares the modules)
├── error.rs (ConvertError: what stops a run)
├── row.rs (Answer in, Cleaned out: validation and normalising)
└── convert.rs (stream, batch, convert in parallel, write in order)
Step 1: dependencies
cargo new csv2json && cd csv2json
cargo add clap --features derive
cargo add serde --features derive
cargo add csv rayon serde_json thiserror
[package]
name = "csv2json"
version = "0.1.0"
edition = "2024"
[dependencies]
clap = { version = "4.6.10", features = ["derive"] }
csv = "1.4.0"
rayon = "1.12.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
thiserror = "2.0.21"
[profile.release]
codegen-units = 1
The [profile.release] line is optional: it makes the release build slower to compile and a little faster to run, by letting the compiler optimise the whole crate at once. The benchmark below uses it.
Step 2: what can stop a run
A bad row is not an error here: it is expected, reported and skipped. ConvertError is only for what makes the whole run impossible: a file that cannot be opened or created, a CSV that cannot be read, a disk that cannot be written to.
#[from] (from the Week 2 checkpoint) lets ? convert csv::Error and io::Error on its own. Open and Create carry the path instead, because “No such file or directory” without the file name helps nobody.
use std::io;
use thiserror::Error;
/// Everything that stops a conversion. A bad row is not an error: it is reported and skipped.
#[derive(Debug, Error)]
pub enum ConvertError {
#[error("cannot open {path}: {source}")]
Open { path: String, source: io::Error },
#[error("cannot create {path}: {source}")]
Create { path: String, source: io::Error },
#[error("cannot read the CSV: {0}")]
Csv(#[from] csv::Error),
#[error("cannot write the output: {0}")]
Write(#[from] io::Error),
}
Step 3: one answer, validated and cleaned
Answer is the row as exported, Cleaned the row as written. clean takes ownership of an Answer (it is not needed afterwards) and returns a Cleaned or the reason it was rejected, as a String.
Three Option methods do the comment in one chain. as_deref() turns Option<String> into Option<&str>, a borrow, without moving the String. map(normalise) runs normalise on the text if there is one; a function name works wherever a closure is expected. filter(…) turns Some("") into None, so a comment that was only punctuation is written as missing, not as an empty string.
normalise is the rayon lesson’s function, unchanged, and its last test is the Arabic comma case from that lesson.
use serde::{Deserialize, Serialize};
/// One answer, as exported: evaluation_id,school,question,score,comment
#[derive(Deserialize)]
pub struct Answer {
pub evaluation_id: u64,
pub school: String,
pub question: String,
pub score: u8,
pub comment: Option<String>,
}
/// One answer, as written to the JSON Lines file.
#[derive(Serialize)]
pub struct Cleaned {
pub evaluation_id: u64,
pub school: String,
pub question: String,
pub score: u8,
pub comment: Option<String>,
pub words: usize,
}
/// The rules a type cannot express. Returns the cleaned answer, or why it was rejected.
pub fn clean(answer: Answer) -> Result<Cleaned, String> {
if !(1..=5).contains(&answer.score) {
return Err(format!("score {} is outside 1 to 5", answer.score));
}
let school = answer.school.trim();
if school.is_empty() {
return Err(String::from("school is empty"));
}
if !is_question(&answer.question) {
return Err(format!("question '{}' is not like Q1", answer.question));
}
let comment = answer
.comment
.as_deref()
.map(normalise)
.filter(|c| !c.is_empty());
let words = comment.as_deref().map_or(0, |c| c.split(' ').count());
Ok(Cleaned {
evaluation_id: answer.evaluation_id,
school: school.to_string(),
question: answer.question,
score: answer.score,
comment,
words,
})
}
/// "Q" followed by one or more digits.
fn is_question(text: &str) -> bool {
match text.strip_prefix('Q') {
Some(digits) => !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()),
None => false,
}
}
/// Lower-case letters and digits; anything else becomes one space: "Too FAST!!" → "too fast".
pub fn normalise(comment: &str) -> String {
let mut out = String::with_capacity(comment.len());
for c in comment.chars() {
if c.is_alphanumeric() {
out.extend(c.to_lowercase());
} else if !out.is_empty() && !out.ends_with(' ') {
out.push(' ');
}
}
out.trim_end().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn answer(score: u8, question: &str, comment: Option<&str>) -> Answer {
Answer {
evaluation_id: 1001,
school: String::from(" Alexandria STEM "),
question: question.to_string(),
score,
comment: comment.map(String::from),
}
}
#[test]
fn cleans_a_good_answer() {
let cleaned = clean(answer(5, "Q1", Some("Too FAST!!"))).unwrap();
assert_eq!(cleaned.school, "Alexandria STEM");
assert_eq!(cleaned.comment.as_deref(), Some("too fast"));
assert_eq!(cleaned.words, 2);
}
#[test]
fn a_comment_of_only_punctuation_becomes_none() {
let cleaned = clean(answer(4, "Q2", Some("!!!"))).unwrap();
assert_eq!(cleaned.comment, None);
assert_eq!(cleaned.words, 0);
}
#[test]
fn rejects_scores_outside_the_scale() {
assert!(clean(answer(0, "Q1", None)).is_err());
assert!(clean(answer(6, "Q1", None)).is_err());
}
#[test]
fn rejects_bad_question_codes() {
for question in ["1", "Q", "Qa", "q1", ""] {
assert!(
clean(answer(3, question, None)).is_err(),
"accepted: {question}"
);
}
}
#[test]
fn keeps_arabic_words_apart() {
assert_eq!(normalise("شرح،واضح"), "شرح واضح");
}
}
map_or(0, …) gives 0 for None and the closure’s result for Some: the number of words, counted only when there is a comment.
Step 4: stream, batch, convert in parallel, write in order
The heart of the tool is the batch loop from the rayon lesson. Three decisions make it survive a real export:
| Decision | Why |
|---|---|
flexible(true) | A row with too few fields (like 1004,Luxor Prep) would otherwise be a csv::Error that ends the whole run. Now it reaches deserialize, fails there, and is rejected like any other bad row. |
ByteRecord instead of StringRecord | A StringRecord must be valid UTF-8, so one row with a broken byte would also end the run. A ByteRecord is raw bytes; the UTF-8 check moves into deserialize, per row. |
record.position() for the line number | The line the row starts on, as an editor shows it. The enumerate() + 2 trick from the CSV lesson goes wrong as soon as a quoted comment contains a line break. |
convert takes impl Read and impl Write (the traits lesson): main passes files, the tests pass a &[u8] and two Vec<u8>, which implement those traits, so the whole pipeline is tested in memory.
Inside convert_row, reject is a closure that captures line: every way a row can fail turns into a Rejected with the right line through the same three characters, map_err(reject).
use std::io::{Read, Write};
use csv::{ByteRecord, ReaderBuilder, Trim};
use rayon::prelude::*;
use serde::Serialize;
use crate::error::ConvertError;
use crate::row::{Answer, clean};
/// What happened to the rows.
#[derive(Debug, Default, PartialEq)]
pub struct Summary {
pub rows: u64,
pub written: u64,
pub rejected: u64,
}
/// A row that was not written, and why: one line of the errors CSV.
#[derive(Serialize)]
struct Rejected {
line: u64,
reason: String,
}
/// Streams the CSV in batches: each batch is converted on every core, then written in order.
pub fn convert(
input: impl Read,
mut output: impl Write,
errors: impl Write,
batch_size: usize,
) -> Result<Summary, ConvertError> {
// flexible: a row with too few fields becomes a rejected row, not the end of the run.
let mut reader = ReaderBuilder::new()
.trim(Trim::All)
.flexible(true)
.from_reader(input);
let headers = reader.byte_headers()?.clone();
let mut rejects = csv::Writer::from_writer(errors);
let mut summary = Summary::default();
let mut batch: Vec<ByteRecord> = Vec::with_capacity(batch_size);
// Byte records: a row with invalid UTF-8 is rejected on its own instead of stopping the run.
for record in reader.byte_records() {
batch.push(record?);
if batch.len() == batch_size {
write_batch(&batch, &headers, &mut output, &mut rejects, &mut summary)?;
batch.clear();
}
}
write_batch(&batch, &headers, &mut output, &mut rejects, &mut summary)?; // the last, smaller batch
output.flush()?;
rejects.flush()?;
Ok(summary)
}
fn write_batch(
batch: &[ByteRecord],
headers: &ByteRecord,
output: &mut impl Write,
rejects: &mut csv::Writer<impl Write>,
summary: &mut Summary,
) -> Result<(), ConvertError> {
let converted: Vec<Result<String, Rejected>> = batch
.par_iter()
.map(|record| convert_row(record, headers))
.collect();
for result in converted {
summary.rows += 1;
match result {
Ok(json) => {
writeln!(output, "{json}")?;
summary.written += 1;
}
Err(rejected) => {
rejects.serialize(&rejected)?;
summary.rejected += 1;
}
}
}
Ok(())
}
/// One row to one line of JSON, or the reason it was rejected.
fn convert_row(record: &ByteRecord, headers: &ByteRecord) -> Result<String, Rejected> {
// The line the row starts on, as an editor shows it, even if a quoted field spans several lines.
let line = record.position().map_or(0, |p| p.line());
let reject = |reason: String| Rejected { line, reason };
let answer: Answer = record
.deserialize(Some(headers))
.map_err(|error| reject(error.to_string()))?;
let cleaned = clean(answer).map_err(reject)?;
serde_json::to_string(&cleaned).map_err(|error| reject(error.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
const CSV: &str = "evaluation_id,school,question,score,comment
1001,Alexandria STEM,Q1,5,Clear explanations
1002,Cairo Language School,Q2,five,
1003,Giza Primary,Q1,9,
1003,Giza Primary,Q2,2,\"Needs more examples,
and a slower pace\"
1004,Luxor Prep
";
fn run(batch_size: usize) -> (Summary, String, String) {
let mut output: Vec<u8> = Vec::new();
let mut errors: Vec<u8> = Vec::new();
let summary = convert(CSV.as_bytes(), &mut output, &mut errors, batch_size).unwrap();
(
summary,
String::from_utf8(output).unwrap(),
String::from_utf8(errors).unwrap(),
)
}
#[test]
fn writes_good_rows_and_rejects_bad_ones() {
let (summary, output, _) = run(2);
assert_eq!(
summary,
Summary {
rows: 5,
written: 2,
rejected: 3
}
);
assert_eq!(output.lines().count(), 2);
assert!(output.contains(r#""comment":"needs more examples and a slower pace""#));
}
#[test]
fn reports_the_line_each_rejected_row_starts_on() {
let (_, _, errors) = run(2);
let lines: Vec<&str> = errors
.lines()
.map(|l| l.split(',').next().unwrap())
.collect();
assert_eq!(lines, ["line", "3", "4", "7"]);
}
#[test]
fn the_batch_size_does_not_change_the_result() {
assert_eq!(run(1), run(10_000));
}
}
The parallel part is one expression: batch.par_iter().map(…).collect(). Writing stays sequential, after it, so the output is in the input order whatever order the cores finished in. The third test proves it: a batch of 1 and a batch of 10,000 give identical results.
Step 5: main.rs
NonZeroUsize is a usize that cannot be 0: clap rejects --batch 0 before the program starts, with no check of your own. .get() gives the plain number back.
Box<dyn Write> holds “some type that implements Write, decided at runtime”: stdout when the path is - (the usual convention for command-line tools), a file otherwise, and io::sink(), a writer that discards everything, when --errors is not given. impl Write needs one type known at compile time; dyn is for when the type depends on a value.
BufWriter collects small writes into large ones. Without it, every line of JSON would be a separate write to the disk.
//! csv2json: convert a survey export to JSON Lines, validating every row on every core.
pub mod convert;
pub mod error;
pub mod row;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::num::NonZeroUsize;
use std::process::ExitCode;
use clap::Parser;
use csv2json::convert::{Summary, convert};
use csv2json::error::ConvertError;
/// Convert a survey export (CSV) to JSON Lines, validating every row.
#[derive(Parser)]
#[command(version)]
struct Args {
/// The CSV export: evaluation_id,school,question,score,comment
input: String,
/// Where to write the JSON Lines, one answer per line ("-" for stdout)
#[arg(short, long)]
output: String,
/// Also write every rejected row, with its line and the reason, to this CSV ("-" for stdout)
#[arg(long)]
errors: Option<String>,
/// How many rows to convert in parallel at a time
#[arg(long, default_value = "10000")]
batch: NonZeroUsize,
}
fn main() -> ExitCode {
let args = Args::parse();
match run(&args) {
Ok(summary) => {
report(&args, &summary);
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("csv2json: {error}");
ExitCode::FAILURE
}
}
}
fn run(args: &Args) -> Result<Summary, ConvertError> {
let input = File::open(&args.input).map_err(|source| ConvertError::Open {
path: args.input.clone(),
source,
})?;
let output = create(&args.output)?;
let errors = match &args.errors {
Some(path) => create(path)?,
None => Box::new(io::sink()), // a writer that discards everything
};
convert(BufReader::new(input), output, errors, args.batch.get())
}
/// Box<dyn Write>: "some writer", decided at runtime: stdout for "-", otherwise a new file.
fn create(path: &str) -> Result<Box<dyn Write>, ConvertError> {
if path == "-" {
return Ok(Box::new(BufWriter::new(io::stdout())));
}
let file = File::create(path).map_err(|source| ConvertError::Create {
path: path.to_string(),
source,
})?;
Ok(Box::new(BufWriter::new(file)))
}
fn report(args: &Args, summary: &Summary) {
eprint!(
"csv2json: {} rows, {} written to {}, {} rejected",
summary.rows,
summary.written,
if args.output == "-" {
"stdout"
} else {
&args.output
},
summary.rejected
);
match (&args.errors, summary.rejected) {
(_, 0) => eprintln!(),
(Some(path), _) if path == "-" => eprintln!(" (listed above)"),
(Some(path), _) => eprintln!(" (see {path})"),
(None, _) => eprintln!(" (add --errors <file> to see why)"),
}
}
match (&args.errors, summary.rejected) matches on a pair, so the three endings of the summary line are three readable arms. (_, 0) comes first: no rejections, nothing to add.
Run the tests
running 8 tests
test convert::tests::reports_the_line_each_rejected_row_starts_on ... ok
test convert::tests::the_batch_size_does_not_change_the_result ... ok
test row::tests::a_comment_of_only_punctuation_becomes_none ... ok
test row::tests::cleans_a_good_answer ... ok
test row::tests::keeps_arabic_words_apart ... ok
test row::tests::rejects_bad_question_codes ... ok
test row::tests::rejects_scores_outside_the_scale ... ok
test convert::tests::writes_good_rows_and_rejects_bad_ones ... ok
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sThe CSV in the tests has every kind of row the sample below has: a word for a score, a score outside the scale, a comment over two lines, and a row with missing fields.
Run it
The sample: 8 answers, 3 of them bad, one comment over two lines, one in Arabic.
evaluation_id,school,question,score,comment
1001,Alexandria STEM,Q1,5,Clear explanations
1001,Alexandria STEM,Q2,4,
1002,Cairo Language School,Q1,3,"Too FAST!!"
1002,Cairo Language School,Q2,five,
1003,Giza Primary,Q1,9,
1003,Giza Primary,Q2,2,"Needs more examples,
and a slower pace"
1004,Luxor Prep
1005,Aswan Secondary,Q1,4,"شرح واضح جدا، شكرا"
csv2json: 8 rows, 5 written to answers.jsonl, 3 rejected (see errors.csv)The summary goes to stderr, so it never mixes with data.
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q1","score":5,"comment":"clear explanations","words":2}
{"evaluation_id":1001,"school":"Alexandria STEM","question":"Q2","score":4,"comment":null,"words":0}
{"evaluation_id":1002,"school":"Cairo Language School","question":"Q1","score":3,"comment":"too fast","words":2}
{"evaluation_id":1003,"school":"Giza Primary","question":"Q2","score":2,"comment":"needs more examples and a slower pace","words":7}
{"evaluation_id":1005,"school":"Aswan Secondary","question":"Q1","score":4,"comment":"شرح واضح جدا شكرا","words":4}
csv2json: 8 rows, 5 written to stdout, 3 rejected (add --errors <file> to see why)-o - sends the JSON Lines to stdout, to see them. The two-line comment is one line of JSON, punctuation gone, and the Arabic comment kept its words with the Arabic comma removed. Without --errors, the summary says how to see why rows were rejected.
line,reason
5,"CSV deserialize error: record 4 (line: 5, byte: 162): field 3: invalid digit found in string"
6,score 9 is outside 1 to 5
9,"CSV deserialize error: record 7 (line: 9, byte: 286): expected field, but got end of row"
csv2json: 8 rows, 5 written to answers.jsonl, 3 rejected (listed above)The rejected rows, each with the line it starts on. Line 9 is 1004,Luxor Prep: line 7 and 8 are the two-line comment, which enumerate() + 2 would have miscounted.
csv2json: cannot create out/answers.jsonl: No such file or directory (os error 2)
exit code 1A folder that does not exist: one sentence with the path, exit code 1, and no half-written output.
error: invalid value '0' for '--batch <BATCH>': number would be zero for non-zero type
For more information, try '--help'.
exit code 2The benchmark: the same tool in PHP
To compare fairly, the PHP version does the same work: stream with fgetcsv, the same five rules, the same normalising with mb_strtolower and a Unicode regex, json_encode per line, every rejected row written with its line. On the generated files, both tools write byte-for-byte identical JSON Lines and reject the same lines.
Generating the input
<?php
// Usage: php generate.php 100000 > survey.csv
// A school-evaluation export with realistic free text and about 1 bad row in 1,000.
$rows = (int) ($argv[1] ?? 100_000);
mt_srand(42);
$schools = ['Alexandria STEM', 'Cairo Language School', 'Giza Primary', 'Luxor Prep', 'Aswan Secondary'];
$comments = [
'Clear explanations, thank you.',
'Too FAST!! Needs more examples.',
'شرح واضح جدا، شكرا',
'The teacher was patient and the homework was useful',
'',
'',
];
$out = fopen('php://stdout', 'w');
fputcsv($out, ['evaluation_id', 'school', 'question', 'score', 'comment'], escape: '');
for ($i = 0; $i < $rows; $i++) {
$score = mt_rand(1, 1000) === 1 ? 'five' : (string) mt_rand(1, 5); // ~0.1% bad scores
fputcsv($out, [
intdiv($i, 10) + 1000,
$schools[mt_rand(0, count($schools) - 1)],
'Q' . ($i % 10 + 1),
$score,
$comments[mt_rand(0, count($comments) - 1)],
], escape: '');
}
csv2json in PHP
<?php
// The same job as the Rust csv2json: php csv2json.php survey.csv answers.jsonl errors.csv
[$_, $inputPath, $outputPath, $errorsPath] = $argv;
$input = fopen($inputPath, 'r') ?: exit("cannot open $inputPath\n");
$output = fopen($outputPath, 'w');
$errors = fopen($errorsPath, 'w');
fputcsv($errors, ['line', 'reason'], escape: '');
$headers = fgetcsv($input, escape: '');
$line = 1;
$rows = $written = $rejected = 0;
while (($fields = fgetcsv($input, escape: '')) !== false) {
$line++;
$rows++;
$row = count($fields) === count($headers) ? array_combine($headers, array_map('trim', $fields)) : null;
$reason = match (true) {
$row === null => 'wrong number of fields',
!ctype_digit($row['score']) => "score '{$row['score']}' is not a number",
(int) $row['score'] < 1 || (int) $row['score'] > 5 => "score {$row['score']} is outside 1 to 5",
$row['school'] === '' => 'school is empty',
!preg_match('/^Q\d+$/', $row['question']) => "question '{$row['question']}' is not like Q1",
default => null,
};
if ($reason !== null) {
fputcsv($errors, [$line, $reason], escape: '');
$rejected++;
continue;
}
$comment = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower($row['comment'])));
fwrite($output, json_encode([
'evaluation_id' => (int) $row['evaluation_id'],
'school' => $row['school'],
'question' => $row['question'],
'score' => (int) $row['score'],
'comment' => $comment === '' ? null : $comment,
'words' => $comment === '' ? 0 : count(explode(' ', $comment)),
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
$written++;
}
fwrite(STDERR, "csv2json.php: $rows rows, $written written, $rejected rejected\n");
The numbers
Measured on the machine this site is built on: 2 cores, Linux, PHP 8.3.6 CLI, Rust 1.100.1 with --release. Each run twice in the same sitting; the table shows both runs’ range.
| Input | Tool | Time | Peak memory |
|---|---|---|---|
| 100K rows (5.4 MB) | PHP 8.3 | 0.5 s | 32 MB |
| 100K rows (5.4 MB) | Rust csv2json | 0.1 s | 13 MB |
| 1M rows (55 MB) | PHP 8.3 | 5.6–5.8 s | 32 MB |
| 1M rows (55 MB) | PHP 8.3 with the JIT on | 5.3–5.7 s | 36 MB |
| 1M rows (55 MB) | Rust csv2json, 1 core (RAYON_NUM_THREADS=1) | 1.7 s | 13 MB |
| 1M rows (55 MB) | Rust csv2json, 2 cores | 1.4–1.5 s | 13 MB |
What the numbers say, honestly. Both tools stream, so both keep memory flat: the 600K-row crash in Sara’s message came from collect(), not from PHP itself, and LazyCollection would fix that part. Rust is about 3 to 4 times faster here, and most of that is not parallelism: on one core it is still about 3 times faster than PHP. On a machine with more cores the gap grows, because only the Rust version uses them.
For a weekly 100K-row export, half a second of PHP is fine, and rewriting it in Rust would be a waste. At millions of rows a day, or when the same validation runs inside an HTTP request, the difference starts to pay. That judgement, not the language, is the skill.
Run it yourself
php generate.php 1000000 > survey.csv
cargo build --release
time php csv2json.php survey.csv php.jsonl php-errors.csv
time ./target/release/csv2json survey.csv -o rust.jsonl --errors rust-errors.csv
cmp php.jsonl rust.jsonl && echo "identical"
For peak memory on macOS use /usr/bin/time -l instead of time, on Linux /usr/bin/time -v.
Where it fits in Laravel
Nothing in the Laravel app has to change shape to use this. The import job calls the binary and reads its result, which is the whole of Week 4:
<?php
$result = Process::timeout(600)->run([
base_path('bin/csv2json'), $csvPath, '-o', $jsonlPath, '--errors', $errorsPath,
]);
if ($result->failed()) {
throw new RuntimeException('csv2json: ' . trim($result->errorOutput()));
}
The PHP side keeps the queue, the retries, the notifications and the database; Rust does the one heavy loop. That split is the realistic way a Laravel team adopts Rust.
PracticeTwo extensions, each with a test first
Extension 1: --fail-on-reject
For a CI check of the export format: with --fail-on-reject, exit with code 3 when any row was rejected, after writing everything as usual.
Show a solution for extension 1
/// Exit with code 3 if any row was rejected
#[arg(long)]
fail_on_reject: bool,
// in main:
Ok(summary) => {
report(&args, &summary);
if args.fail_on_reject && summary.rejected > 0 {
ExitCode::from(3)
} else {
ExitCode::SUCCESS
}
}
A bool field with #[arg(long)] becomes a flag that takes no value: present means true.
Extension 2: shorter reasons
A rejected row’s reason repeats the position: CSV deserialize error: record 3 (line: 4, …): field 3: invalid digit found in string. The line is already in its own column. Make the reason score: invalid digit found in string: csv::Error has kind(), and for a deserialize error csv::ErrorKind::Deserialize { err, .. } holds a DeserializeError with field() (the column index) and kind(). Map the index to the header name with headers.get(i).
Remember
- Stream in batches: read a batch, process it in parallel, write it in order, and never forget the last partial batch.
- Rust is worth it for the heavy loop; keep the queue, retries and database work in Laravel.
Tomorrow is the Week 3 checkpoint: flat memory on a million rows, and bad rows that never stop a run.