Files
sencho/backend
Anso 668eda6cc8 fix(stack-files): atomic write via tmp+rename with optional exclusive mode (#1205)
* fix(stack-files): atomic write via tmp+rename with optional exclusive mode

writeStackFile and writeStackFileBuffer previously called fs.writeFile
directly, which truncates the target then streams the new bytes. A
crash, disk-full event, or process kill between the truncate and the
write left the target with partial content and no easy way to detect
the half-write at read time.

A private writeStackFileAtomic helper stages every write into a
sibling .sencho-tmp-<suffix> file in the same directory, fsyncs, then
promotes via fs.rename. A crash now leaves either the original target
intact or a leftover .sencho-tmp file (cleaned up on the next failure
path); a torn target file is no longer reachable through this path.

The helper accepts an optional `exclusive: true` flag that swaps the
final promote step from rename to link+unlink. link is atomic against
EEXIST so a caller that needs "create only if not present" gets a
race-free FILE_EXISTS error instead of a clobber. The upload route's
overwrite-confirm flow (PR #1204) will wire this through in a
follow-up so the existence check becomes authoritative.

Behaviour for current callers (writeStackFile, writeStackFileBuffer,
BlueprintService deploy) is unchanged: the non-exclusive default
matches the prior fs.writeFile semantics from the caller's perspective.

* fix(stack-files): tighten atomic write entropy + concurrent / failure tests

Tmp suffix now uses crypto.randomBytes(6) so the per-process collision
window is a true 48-bit space (Math.random().toString(36).slice(2,6)
could drop leading zeros and narrow entropy unpredictably). Adds a
short comment on the Windows link path noting NTFS / same-FS POSIX is
required, both guaranteed by tmp+target being siblings.

Two new tests close coverage gaps the first round missed:
- a write step that throws (writeFile rejected) leaves no tmp leak and
  no partial target;
- concurrent non-exclusive writers settle with at least one success
  and the final file is exactly one of the inputs (POSIX silently
  overwrites; Windows EPERMs the loser, both consistent).
2026-05-24 23:34:26 -04:00
..