High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: recordingsOutputPath re-implements fileout.ReservePath and drops the removal it has, so a failed close leaves a 0-byte recording (PIN-173)
Luigi Agosti6c5c27201e29
diff --git a/internal/fileout/fileout.go b/internal/fileout/fileout.goindex 04207497..e55714e3 100644--- a/internal/fileout/fileout.go+++ b/internal/fileout/fileout.go@@ -93,17 +93,27 @@ func WriteUniquePath(path string, buf []byte) (string, error) {return WriteUnique(dir, base, ext, buf)}-// ReservePath claims a path for a caller that will not write the bytes itself — one-// moving an already-written file into place with os.Rename. The placeholder is created-// exclusively and closed, and the rename then replaces it atomically on POSIX, so the-// reservation is what stops a second process taking the name in between.+// ReserveUnique claims a path for a caller that will not write the bytes itself — one+// moving an already-written file into place with os.Rename, or handing the name to an+// encoder that writes over the placeholder. The placeholder is created exclusively and+// closed, and a rename then replaces it atomically on POSIX, so the reservation is what+// stops a second process taking the name in between.+//+// A failed close removes the placeholder, for the reason WriteUnique removes a failed+// write: the alternative is an error alongside a 0-byte file wearing the output's name.//// A reservation is a side effect: every path that then gives up must Remove the// returned path, or an abandoned run litters an empty file under a name that reads// like a real output.-func ReservePath(path string) (string, error) {- dir, base, ext := splitPath(path)- f, reserved, err := CreateUnique(dir, base, ext)+func ReserveUnique(dir, base, ext string) (string, error) {+ return reserveUnique(dir, base, ext, CreateUnique)+}++// reserveUnique takes its creator as a parameter for the reason writeUnique does: a+// close failure on a freshly created file needs a full or revoked filesystem, and an+// unpinned removal is an unproven one.+func reserveUnique(dir, base, ext string, create func(string, string, string) (*os.File, string, error)) (string, error) {+ f, reserved, err := create(dir, base, ext)if err != nil {return "", err}@@ -114,6 +124,15 @@ func ReservePath(path string) (string, error) {return reserved, nil}+// ReservePath is ReserveUnique for a caller holding a whole path rather than its three+// parts. splitPath takes the extension with filepath.Ext, so a base carrying dots of+// its own does not survive the round trip — a caller that knows its three parts should+// pass them.+func ReservePath(path string) (string, error) {+ dir, base, ext := splitPath(path)+ return ReserveUnique(dir, base, ext)+}+// splitPath cuts a path into the three parts CreateUnique numbers, so the suffix lands// before the extension (capture-<ts>-1.jpg) rather than after it.func splitPath(path string) (dir, base, ext string) {diff --git a/internal/fileout/fileout_test.go b/internal/fileout/fileout_test.goindex b556a6a0..24d7d86d 100644--- a/internal/fileout/fileout_test.go+++ b/internal/fileout/fileout_test.go@@ -131,6 +131,96 @@ func assertContents(t *testing.T, path string, want []byte) {}}+// A reservation that cannot be closed must not survive: the caller gets an error and+// would otherwise be left with a 0-byte file wearing the output's name — the same+// defect the write path removes one layer down. Pinned through the creator seam,+// because a real close failure needs a full or revoked filesystem.+func TestReserveUniqueRemovesThePlaceholderWhenTheCloseFails(t *testing.T) {+ dir := t.TempDir()+ created := ""+ closedHandle := func(dir, base, ext string) (*os.File, string, error) {+ f, path, err := CreateUnique(dir, base, ext)+ if err != nil {+ return nil, "", err+ }+ if err := f.Close(); err != nil {+ return nil, "", err+ }+ created = path+ return f, path, nil+ }++ path, err := reserveUnique(dir, "rec_20260101_000000", ".gif", closedHandle)+ if err == nil {+ t.Fatal("precondition: closing an already-closed handle must fail")+ }+ if path != "" {+ t.Errorf("reserveUnique returned %q alongside its error; a failed reservation has no path to report", path)+ }+ if created == "" {+ t.Fatal("the stub creator never ran, so this guard checked nothing")+ }+ if _, err := os.Stat(created); !os.IsNotExist(err) {+ t.Errorf("%s survived a failed close (stat err = %v); the placeholder must be removed", created, err)+ }+}++// ReservePath is a shape over ReserveUnique, not a second implementation: it must hand+// back a real reservation, and the numbering must land before the extension exactly as+// the three-part form does.+func TestReservePathDelegatesToTheThreePartForm(t *testing.T) {+ dir := t.TempDir()++ first, err := ReservePath(filepath.Join(dir, "rec_20260101_000000.gif"))+ if err != nil {+ t.Fatal(err)+ }+ second, err := ReservePath(filepath.Join(dir, "rec_20260101_000000.gif"))+ if err != nil {+ t.Fatal(err)+ }+ if first == second {+ t.Fatalf("both reservations returned %q", first)+ }+ if want := filepath.Join(dir, "rec_20260101_000000-1.gif"); second != want {+ t.Errorf("second reservation = %q, want %q", second, want)+ }+ for _, path := range []string{first, second} {+ if _, err := os.Stat(path); err != nil {+ t.Errorf("%q was returned but not reserved on disk: %v", path, err)+ }+ }+}++// The whole-path form is a SHAPE over the three-part one, not a second implementation:+// two copies of the close-and-remove pair is how the rule drifted out of one of them+// before. Behavioural tests cannot see the difference — a copy passes them — so this is+// a structural check on the delegation itself.+func TestReservePathHoldsNoSecondImplementation(t *testing.T) {+ raw, err := os.ReadFile("fileout.go")+ if err != nil {+ t.Fatal(err)+ }+ const declaration = "func ReservePath("+ start := strings.Index(string(raw), declaration)+ if start < 0 {+ t.Fatalf("%s not found; this guard is pinned to a function that no longer exists", declaration)+ }+ body := string(raw)[start:]+ if end := strings.Index(body, "\n}\n"); end >= 0 {+ body = body[:end]+ }++ if !strings.Contains(body, "ReserveUnique(dir, base, ext)") {+ t.Error("ReservePath no longer delegates to ReserveUnique")+ }+ for _, reimplemented := range []string{"CreateUnique(", "os.Remove(", ".Close()"} {+ if strings.Contains(body, reimplemented) {+ t.Errorf("ReservePath contains %q; the reserve-and-close sequence has one implementation and this is meant to be a shape over it", reimplemented)+ }+ }+}+// TestWriteUniqueRemovesTheFileItCreatedWhenTheWriteFails pins the removal through// the creator seam: the stub creates a REAL file and hands back a closed handle, so// the write fails for a reason the caller cannot control and the file it left is thediff --git a/internal/handlers/binary_export.go b/internal/handlers/binary_export.goindex 062373c1..0220db2b 100644--- a/internal/handlers/binary_export.go+++ b/internal/handlers/binary_export.go@@ -37,18 +37,16 @@ func writeRawImage(w http.ResponseWriter, buf []byte, contentType, logLabel stri// The no-overwrite rule itself lives in internal/fileout, a leaf both this package and// internal/cli/actions can import — the CLI sites had the same defect and a second copy-// of the loop is the drift worth avoiding. These two keep the names every call site in-// this package already uses, and delegate.-func createUniqueFile(dir, base, ext string) (*os.File, string, error) {- return fileout.CreateUnique(dir, base, ext)-}-+// of the loop is the drift worth avoiding. This keeps the name every call site in this+// package already uses, and delegates. A caller that reserves a name without writing+// the bytes calls fileout.ReserveUnique directly: routing that through a local handle+// is what let this package lose the removal on a failed close.func writeUniqueFile(dir, base, ext string, buf []byte) (string, error) {return fileout.WriteUnique(dir, base, ext, buf)}// exportTimestamp is the second-resolution stamp every auto-named export shares. It is-// no longer load-bearing for uniqueness — createUniqueFile is — so it stays at second+// no longer load-bearing for uniqueness — the exclusive create is — so it stays at second// granularity to keep filenames readable.func exportTimestamp() string {return time.Now().Format("20060102-150405")diff --git a/internal/handlers/binary_export_test.go b/internal/handlers/binary_export_test.goindex bb162e57..43e26a5e 100644--- a/internal/handlers/binary_export_test.go+++ b/internal/handlers/binary_export_test.go@@ -13,7 +13,6 @@ import ("github.com/pinchtab/pinchtab/internal/bridge/observe""github.com/pinchtab/pinchtab/internal/config"- "github.com/pinchtab/pinchtab/internal/fileout")// Two saves in immediate succession must land on different paths with both files intact.@@ -112,54 +111,6 @@ func assertFileHolds(t *testing.T, path string, want []byte) {}}-// The suffix ladder is bounded, and running out is an error rather than a silent-// overwrite: a directory with this many same-second names is a runaway caller.-func TestCreateUniqueFileRefusesRatherThanOverwriteWhenTheLadderIsExhausted(t *testing.T) {- dir := t.TempDir()- base, ext := "cap-fixed", ".png"-- occupy := func(name string) {- if err := os.WriteFile(filepath.Join(dir, name), []byte("held"), 0600); err != nil {- t.Fatal(err)- }- }- occupy(base + ext)- for i := 1; i < fileout.MaxUniqueNameAttempts; i++ {- occupy(fmt.Sprintf("%s-%d%s", base, i, ext))- }-- if _, _, err := createUniqueFile(dir, base, ext); err == nil {- t.Fatal("createUniqueFile succeeded with every name taken; it must refuse rather than overwrite")- }- // Nothing it touched may have changed.- assertFileHolds(t, filepath.Join(dir, base+ext), []byte("held"))-}--// createUniqueFile returns an OPEN handle on purpose: a stat-then-write leaves a window-// where a concurrent caller takes the name between the check and the write.-func TestCreateUniqueFileReservesTheNameItReturns(t *testing.T) {- dir := t.TempDir()-- first, firstPath, err := createUniqueFile(dir, "rec_fixed", ".gif")- if err != nil {- t.Fatal(err)- }- defer func() { _ = first.Close() }()-- second, secondPath, err := createUniqueFile(dir, "rec_fixed", ".gif")- if err != nil {- t.Fatal(err)- }- defer func() { _ = second.Close() }()-- if firstPath == secondPath {- t.Fatalf("the second reservation returned the same path %q, so the first was not held", firstPath)- }- if _, err := os.Stat(firstPath); err != nil {- t.Errorf("the first reservation does not exist on disk: %v", err)- }-}-// AC6, recording: recordingsOutputPath's own comment claimed the path was unique while// nothing checked — two stops in the same second returned one path and the encoder that// finished second overwrote the first recording. The path is now reserved, so a second@@ -188,6 +139,35 @@ func TestRecordingsOutputPathReservesEachPath(t *testing.T) {}}+// The reservation rule — create exclusively, close, remove the placeholder if the close+// fails — belongs to internal/fileout, which pins the removal itself through an injected+// creator. This site owes only proof that it ROUTES there and keeps no second copy of+// the sequence: a local create-then-close is how the removal came to be missing here.+func TestRecordingsOutputPathReservesThroughFileout(t *testing.T) {+ raw, err := os.ReadFile("record_handlers.go")+ if err != nil {+ t.Fatal(err)+ }+ const declaration = "func (h *Handlers) recordingsOutputPath("+ start := strings.Index(string(raw), declaration)+ if start < 0 {+ t.Fatalf("%s not found in record_handlers.go; this guard is pinned to a function that no longer exists", declaration)+ }+ body := string(raw)[start:]+ if end := strings.Index(body, "\n}\n"); end >= 0 {+ body = body[:end]+ }++ if !strings.Contains(body, "fileout.ReserveUnique(") {+ t.Error("recordingsOutputPath no longer reserves through fileout.ReserveUnique, so the removal on a failed close is not inherited")+ }+ for _, reimplemented := range []string{"createUniqueFile(", ".Close()", "os.Remove("} {+ if strings.Contains(body, reimplemented) {+ t.Errorf("recordingsOutputPath contains %q; the reserve-and-close sequence has one owner in internal/fileout, and a local copy is how its removal went missing", reimplemented)+ }+ }+}+// stubExportEncoder is the smallest ExportEncoder writeExportFile will accept, so the// naming and overwrite policy can be driven without a browser.type stubExportEncoder struct {@@ -324,7 +304,7 @@ func TestNoHandlerAutoNamesAFileItThenOverwrites(t *testing.T) {// file -> why its timestamp is not an overwrite risk.accounted := map[string]string{"binary_export.go": "exportTimestamp only builds the base name; createUniqueFile reserves the path",- "record_handlers.go": "the recording base name is reserved by createUniqueFile before it is returned",+ "record_handlers.go": "the recording base name is reserved by fileout.ReserveUnique before it is returned",}var scanned int@@ -342,7 +322,7 @@ func TestNoHandlerAutoNamesAFileItThenOverwrites(t *testing.T) {continue}if accounted[name] == "" {- t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through createUniqueFile or record why it cannot collide", name)+ t.Errorf("%s builds a name from a second-resolution timestamp and is not accounted for; route it through fileout (WriteUnique or ReserveUnique) or record why it cannot collide", name)}}if scanned < 2 {diff --git a/internal/handlers/network_export.go b/internal/handlers/network_export.goindex ea4a6f1f..30e1efee 100644--- a/internal/handlers/network_export.go+++ b/internal/handlers/network_export.go@@ -13,6 +13,7 @@ import ("github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/bridge/observe"+ "github.com/pinchtab/pinchtab/internal/fileout""github.com/pinchtab/pinchtab/internal/httpx")@@ -332,11 +333,10 @@ func (h *Handlers) writeExportFile(if err := os.MkdirAll(exportDir, 0750); err != nil {return fmt.Errorf("create dir: %w", err)}- reserved, path, err := createUniqueFile(exportDir, "network-"+exportTimestamp(), enc.FileExtension())+ path, err := fileout.ReserveUnique(exportDir, "network-"+exportTimestamp(), enc.FileExtension())if err != nil {return fmt.Errorf("reserve export name: %w", err)}- _ = reserved.Close()reservedPath = pathuserPath = filepath.Base(reservedPath)}diff --git a/internal/handlers/record_handlers.go b/internal/handlers/record_handlers.goindex 10f8cc90..992d6678 100644--- a/internal/handlers/record_handlers.go+++ b/internal/handlers/record_handlers.go@@ -10,6 +10,7 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/fileout""github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/session")@@ -157,27 +158,19 @@ func (h *Handlers) HandleRecordStop(w http.ResponseWriter, r *http.Request) {})}-// recordingsOutputPath returns a unique output path inside the server-controlled-// recordings directory. The caller never chooses the path — only the server does.-//-// "Unique" used to be an unbacked claim in this comment: the name came from a-// second-resolution timestamp and nothing checked whether it existed, so two stops in-// the same second returned one path and the encoder that finished second overwrote the-// first recording. The path is now RESERVED by creating it exclusively; the encoder-// writes over its own 0-byte placeholder afterwards.+// recordingsOutputPath returns a reserved output path inside the server-controlled+// recordings directory. The caller never chooses the path — only the server does. The+// encoder writes over the 0-byte placeholder fileout leaves behind.func (h *Handlers) recordingsOutputPath() (string, error) {dir := filepath.Join(h.Config.StateDir, "recordings")if err := os.MkdirAll(dir, 0700); err != nil {return "", fmt.Errorf("create recordings dir: %w", err)}base := "rec_" + time.Now().Format("20060102_150405")- f, path, err := createUniqueFile(dir, base, "."+h.recorder.activeFormat())+ path, err := fileout.ReserveUnique(dir, base, "."+h.recorder.activeFormat())if err != nil {return "", fmt.Errorf("reserve recording path: %w", err)}- if err := f.Close(); err != nil {- return "", fmt.Errorf("reserve recording path: %w", err)- }return path, nil}