Laravel Rust✓ Human-reviewed

Bounded CSV exports in Laravel Rust

Inline a single CSV export using the csv crate, bounded scoped reads and explicit artifact/write-error ownership, with formula policy separate from CSV quoting.

Approved 2026-12-04T13:20:42.861743Z · Submission 63

Bounded CSV exports in Laravel Rust

Scope and attribution

Inline one CSV export using app-owned authorization/projection plus the csv crate. Do not port FastExcel's workbook, import, formatting, multi-sheet or transpose APIs. If any caller needs XLSX/ODS cell types or styles, retain an appropriate workbook library instead. The package/framework refs are in this recipe's metadata and the additional writer ref is below; reconcile them with the destination Cargo.lock first.

Writer source checked on 2026-12-04: BurntSushi/rust-csv, commit 05612e87e6e92910d40d7214b70952b8434fef9b (source manifest version 1.4.0). Inspect src/writer.rs.

FastExcel by Raphaël Huchet is MIT licensed. Inspect src/FastExcel.php, src/Exportable.php and tests/FastExcelTest.php; preserve notices when adapting source/fixtures. FastExcel delegates encoding to OpenSpout; this path does not copy that engine. The Rust csv crate offers MIT/Unlicense licensing; retain the applicable chosen license. This guidance has not been trialed in your app.

At the time of writing, the Package Port catalog listed spatie/simple-excel-rust as an equivalent Rust package, explicitly not a direct port; check get-recipe's current port catalog. Offer it before inlining if workbook support matters. The smaller CSV path deliberately owns only a single application export contract.

Compatibility conditions and output contract

If the installed FastExcel uses the inspected implementation, filenames select the writer, the first projected row supplies headers, callback null/false values skip rows, and CSV settings control delimiter/enclosure/BOM. Traversable data can stream; materialized collections already occupy memory, and transpose buffers data. Avoid assuming that a generator downstream undoes an eager upstream query.

Define this replacement as UTF-8 comma-separated CSV, CRLF record endings, no BOM, and exactly ID,Name,JoinedAt headers even for an empty result. Every row contains all cells in this order; a null name is empty, IDs are decimal strings, and timestamps use an explicit UTC format. This changes empty-result/header inference behavior. CSV text does not prevent spreadsheet applications coercing long IDs or leading zeros; use a typed workbook if preservation is required when opening directly in a spreadsheet.

Implement in the existing export operation

  1. Authorize before querying, apply tenant/user scope to every chunk and project only explicitly allowed fields. Reject request-chosen raw SQL/column names or filesystem paths. Use fixed safe attachment filenames. Bound rows, cell sizes, total output bytes and run time.
  2. Create an exclusively owned private staged file under a trusted root. Do not expose it until query iteration, projection, CSV encoding, flush and close/finalization all succeed. Remove partial files on error/cancellation. Keep completed file ownership alive until the HTTP stream finishes; returning a path to a file already dropped by a temporary owner is incorrect.
  3. Read by stable keyset pagination or a verified bounded cursor, not get() of all records. Include a unique deterministic ordering key. Decide snapshot versus live-scan semantics explicitly; a high-water ID alone does not freeze updates/deletes. Bound prefetch and background work; synchronous filesystem writes should not block the async runtime's request executor.
  4. With the inspected csv API, the core write fragment is:
let mut writer = csv::WriterBuilder::new()
    .has_headers(false)
    .terminator(csv::Terminator::CRLF)
    .from_writer(file);
writer.write_record(["ID", "Name", "JoinedAt"])?;
// For each authorized row, validate policy and write_record([id, name, joined_at]).
// Propagate query/projection errors instead of silently ending the iterator.
writer.flush()?;
let file = writer.into_inner().map_err(|error| error.into_error())?;
// Finalize the file and only then promote the artifact as ready.

This fragment belongs inside a fallible operation that owns the file and accepts CSV/I/O errors. file after into_inner() is the original writer sink. Dropping a buffered writer can hide errors; explicit flush/finalization is necessary. If crash-durable completion is required, sync data according to the storage contract before readiness; ordinary flush alone is not durability.

  1. CSV escaping is not formula protection. For this bounded human-viewed export, reject untrusted text starting with =, +, - or @ after stripping leading whitespace/control characters, and reject leading tab/CR/LF controls. Apply that policy before writing each row, including any dynamic headings; fixed headings here need no such transformation. Trusted generated numbers are separate from untrusted text. This rejects some legitimate text and is not a universal spreadsheet safety guarantee. For lossless arbitrary input, use a typed workbook and test its real consumer.
  2. Serve only a completed, freshly authorized artifact with text/csv; charset=utf-8, private caching and a safe attachment filename. Keep sensitive exports outside public storage and URLs. Handle expiry, failed jobs and interrupted downloads; a retry cannot hand one tenant another tenant's artifact.

Acceptance trial

Use an independent CSV reader to assert header order and complete cell values: commas, doubled quotes, Unicode, embedded LF/CRLF/lone CR, null names, empty results, leading-zero and large IDs. Test the exact spreadsheet/importer separately for coercion and formula policy; do not substitute CSV round-trip tests for client behavior.

  • Formula-looking untrusted strings and leading controls reject without a ready artifact or partial successful download.
  • Cross-tenant/concurrent exports cannot share rows or artifacts; every database chunk retains the scope.
  • More than two chunks return each expected ID exactly once. Concurrent writes exercise the documented consistency choice.
  • Inject query, disk-full, short-write, flush/finalization and cancellation failures; all propagate and remove partial artifacts.
  • Measure peak memory with growing row counts and bounded cell sizes to catch accidental collection or buffering of the entire file.

Run the app's cargo fmt --check, cargo test and strict Clippy checks. Record framework/Rust/csv versions, database/filesystem, output dialect, peak memory and decisive outputs with the change.