@rljson/fs-agent 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.api.md CHANGED
@@ -446,6 +446,12 @@ produce bytes nobody wrote — measured at 1 520 blended pairs in 2 000.
446
446
 
447
447
  Writes to a temporary file beside the target and renames it into place.
448
448
 
449
+ On Windows, a rename onto a target that another rename or a program holds
450
+ (EPERM, EBUSY, EACCES) is tried again for about half a second before the error
451
+ reaches the caller. A name the filesystem refuses — on Windows one over 255
452
+ characters or with `?`, `*`, `:` — throws EINVAL, not the ENOENT Windows
453
+ reports for it.
454
+
449
455
  ### `atomicWriteFileSync(path, content)`
450
456
 
451
457
  The same, synchronously — for a small file that must be on disk before the
@@ -751,11 +751,23 @@ an mtime to the nearest millisecond, `Date.now()` truncates — so the scan
751
751
  reuses the version before it, and a receiver authors that older version as an
752
752
  edit, which reverts the writer's own copy everywhere.
753
753
 
754
+ **A file that refuses to open is kept — unless it is being deleted.** Windows
755
+ refuses an open while a program copies or holds a file (EBUSY, EPERM, EACCES).
756
+ The scan keeps the version it read last and reads the file again on the next
757
+ scan, so one held file does not stop the rest of the folder. The same EPERM
758
+ answers an open in the moment between a delete marking a file and its name
759
+ going, so a refusal is looked at again after `LOCK_RECHECK_MS` (10, 20 and
760
+ 40 ms): a deleted file is gone by then, and the scan treats it as vanished —
761
+ a partial picture, which is not published — instead of keeping a version
762
+ nobody holds. Keeping it was field defect F6: the deletion was never authored,
763
+ and the next apply wrote the file back on its own node.
764
+
754
765
  What no rule over `stat` can decide is a writer that pauses for a long time, and
755
766
  `README.public.md` → "Known constraints" says what that costs.
756
767
 
757
- **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half and
758
- `test/fs-slow-copy.spec.ts` (3) for the deferral itself.
768
+ **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half,
769
+ `test/fs-slow-copy.spec.ts` (3) for the deferral itself, and
770
+ `test/fs-scanner-vanish.spec.ts` for the locked file and the one being deleted.
759
771
 
760
772
  ## Ignore Matching (`src/fs-ignore.ts`)
761
773
 
package/README.md CHANGED
@@ -20,7 +20,7 @@ decision everything else follows from.
20
20
 
21
21
  ```bash
22
22
  npm install @rljson/fs-agent
23
- pnpm test # 70 files, 807 scenarios, 100 % coverage, then eslint
23
+ pnpm test # 71 files, 823 scenarios, 100 % coverage, then eslint
24
24
  ```
25
25
 
26
26
  ## Where to start
@@ -28,7 +28,7 @@ pnpm test # 70 files, 807 scenarios, 100 % coverage, then eslint
28
28
  | if you are | read |
29
29
  | --- | --- |
30
30
  | **using the package** | [README.public.md](README.public.md) — install, the production configuration, every option and what it costs, troubleshooting |
31
- | **deciding whether to trust it** | [README.tests.md](README.tests.md) — what the 807 scenarios actually prove, and what they cannot |
31
+ | **deciding whether to trust it** | [README.tests.md](README.tests.md) — what the 823 scenarios actually prove, and what they cannot |
32
32
  | **changing the sync** | [README.architecture.md](README.architecture.md) — the mechanism, and why each rule exists |
33
33
  | **calling the API** | [README.api.md](README.api.md) — every export, grouped by module, with what it costs |
34
34
  | **setting the repo up** | [README.contributors.md](README.contributors.md) — run, debug, build, publish |
package/README.tests.md CHANGED
@@ -8,8 +8,8 @@ found in the LICENSE file in the root of this package.
8
8
 
9
9
  # The test suite, as a document
10
10
 
11
- **70 files, 807 scenarios, 100 % coverage on statements, branches, functions and
12
- lines.** 806 must pass; one is committed inverted, and §2.11 says which and why.
11
+ **71 files, 823 scenarios, 100 % coverage on statements, branches, functions and
12
+ lines.** 822 must pass; one is committed inverted, and §2.11 says which and why.
13
13
  One command runs all of it:
14
14
 
15
15
  ```bash
@@ -23,7 +23,7 @@ failures. Four different tests once failed
23
23
  across four CI runs of the same commit, each passing on re-run — not four bugs,
24
24
  one scheduler.
25
25
 
26
- This document says what the suite actually proves, because the number 807 does
26
+ This document says what the suite actually proves, because the number 823 does
27
27
  not. It is organised by the question answered rather than by file; the file
28
28
  index is at the end.
29
29
 
@@ -34,7 +34,7 @@ index is at the end.
34
34
  | tier | what it is | files |
35
35
  | --- | --- | --- |
36
36
  | **mesh** | a real `Server`, real sockets (`createSocketPair`), real watchers, real files on disk, two to four nodes, with cuts, heals, mutes, deafenings and stopped processes | 12 |
37
- | **client–server** | two or three clients and a real hub, each suite run **twice** — once over `SocketMock`, once over a real socket.io server configured at production's 50 MB limit | 6 |
37
+ | **client–server** | two or three clients and a real hub, each suite run **twice** — once over `SocketMock`, once over a real socket.io server configured at production's 50 MB limit | 7 |
38
38
  | **unit / decision** | one agent, or a pure function with no filesystem and no clock | 55 |
39
39
 
40
40
  A decision-tier test proves a RULE. It does not prove the rule is ever
@@ -296,7 +296,7 @@ visible files all vanished is refused however many it carries.
296
296
  | `fs-filenames.spec.ts` (5) | a German filename round-tripping byte for byte, two Unicode spellings of one name not destroying each other, a case-only rename |
297
297
  | `fs-hostile-tree.spec.ts` (7) | a tree from a peer is not trusted with paths — no escaping the sync root |
298
298
  | `fs-filetype-changes.spec.ts` (6) | a path that changes what it IS: file → directory, directory → file, symlinks |
299
- | `fs-scanner-vanish.spec.ts` (12) | an entry deleted between `readdir` and `stat` |
299
+ | `fs-scanner-vanish.spec.ts` (17) | an entry deleted between `readdir` and `stat`, a locked file, and a file refused while it is being deleted |
300
300
  | `fs-disk-full.spec.ts` (3) | ENOSPC — a clean abort with a message, not a silent standstill |
301
301
  | `fs-slow-copy.spec.ts` (3) | a file still being written: never hashed half-done, and one unsettled file does not stop the folder |
302
302
  | `fs-clock-skew.spec.ts` (6) | a machine whose clock is wrong — a file is visible whatever its timestamp says |
@@ -425,7 +425,7 @@ Open items are in
425
425
  ## 5. File index
426
426
 
427
427
  Counts are what `pnpm test` reports per file, so suites that generate cases in a
428
- loop are counted as they run. They sum to the 807 above.
428
+ loop are counted as they run. They sum to the 823 above.
429
429
 
430
430
  ### Mesh tier
431
431
 
@@ -450,6 +450,7 @@ loop are counted as they run. They sum to the 807 above.
450
450
  | --- | --- | --- |
451
451
  | `client-server/socket-mock.spec.ts` | 35 | the shared suite (`shared-sync-tests.ts`) over `SocketMock` |
452
452
  | `client-server/socket-io.spec.ts` | 35 | the same shared suite over a real socket.io server at production's 50 MB limit |
453
+ | `client-server/large-file.spec.ts` | 2 | a 60 MB file over a real socket.io server at the 50 MB limit: added, changed, deleted, and edited on both sides while apart; counts the bytes the hub carries |
453
454
  | `client-server/advanced-sync.spec.ts` | 15 | three clients, catch-up, teardown and restart, 10 MB, 100 files, rapid overwrites |
454
455
  | `client-server/heals-after-forced-divergence.spec.ts` | 14 | deliberately dropped messages |
455
456
  | `client-server/conflict-sync.spec.ts` | 2 | a real offline divergent edit, both versions preserved |
@@ -460,8 +461,8 @@ loop are counted as they run. They sum to the 807 above.
460
461
  | file | n | what it covers |
461
462
  | --- | --- | --- |
462
463
  | `fs-agent.spec.ts` | 81 | the agent's surface |
463
- | `fs-scanner.spec.ts` | 62 | scanning, watching, the scan cache, the agent's own writes |
464
- | `fs-agent-degradation.spec.ts` | 15 | what the agent does when a dependency fails, and the shapes no scenario reaches |
464
+ | `fs-scanner.spec.ts` | 65 | scanning, watching, the scan cache, the agent's own writes |
465
+ | `fs-agent-degradation.spec.ts` | 16 | what the agent does when a dependency fails, and the shapes no scenario reaches |
465
466
  | `fs-agent-receive-degradation.spec.ts` | 16 | receiving when a part of it fails — a tree it cannot read, a stamp or state it cannot file, a folder that moves under the apply, a join |
466
467
  | `fs-receive.spec.ts` | 11 | what a node does with a head that arrived |
467
468
  | `fs-relate.spec.ts` | 11 | same / behind / ahead / fork / incomplete |
@@ -478,7 +479,7 @@ loop are counted as they run. They sum to the 807 above.
478
479
  | `fs-agent-authorship.spec.ts` | 4 | a node claims only what it changed |
479
480
  | `fs-divergence-is-content.spec.ts` | 2 | a divergence is a difference in CONTENT |
480
481
  | `fs-ref-vs-content.spec.ts` | 6 | ref identity vs content identity |
481
- | `fs-agent-concurrent-write.spec.ts` | 12 | two writes of one path must not blend — 200 rounds per assertion — and the synchronous writer the bookkeeping uses |
482
+ | `fs-agent-concurrent-write.spec.ts` | 17 | two writes of one path must not blend — 200 rounds per assertion — the synchronous writer the bookkeeping uses, and a rename that waits out a held file and names a refused name |
482
483
  | `fs-agent-incremental-restore.spec.ts` | 8 | a restore writes only what changed |
483
484
  | `fs-agent-locked-file.spec.ts` | 8 | a file held open by another process |
484
485
  | `fs-agent-blob-stream.spec.ts` | 3 | a restore streams the blob |
@@ -491,7 +492,7 @@ loop are counted as they run. They sum to the 807 above.
491
492
  | `fs-blob-adapter.spec.ts` | 26 | file ↔ blob |
492
493
  | `fs-db-adapter.spec.ts` | 6 | storing a tree with its predecessors |
493
494
  | `blob-io.spec.ts` | 5 | storing a file as a blob |
494
- | `fs-scanner-vanish.spec.ts` | 12 | an entry that vanishes mid-scan |
495
+ | `fs-scanner-vanish.spec.ts` | 17 | an entry that vanishes mid-scan, a locked file, one being deleted |
495
496
  | `fs-scanner-scan-coalescing.spec.ts` | 4 | a burst collapses into at most two passes |
496
497
  | `fs-hostile-tree.spec.ts` | 7 | a peer's tree is not trusted with paths |
497
498
  | `fs-impossible-filename.spec.ts` | 4 | a path the filesystem refuses |
@@ -446,6 +446,12 @@ produce bytes nobody wrote — measured at 1 520 blended pairs in 2 000.
446
446
 
447
447
  Writes to a temporary file beside the target and renames it into place.
448
448
 
449
+ On Windows, a rename onto a target that another rename or a program holds
450
+ (EPERM, EBUSY, EACCES) is tried again for about half a second before the error
451
+ reaches the caller. A name the filesystem refuses — on Windows one over 255
452
+ characters or with `?`, `*`, `:` — throws EINVAL, not the ENOENT Windows
453
+ reports for it.
454
+
449
455
  ### `atomicWriteFileSync(path, content)`
450
456
 
451
457
  The same, synchronously — for a small file that must be on disk before the
@@ -751,11 +751,23 @@ an mtime to the nearest millisecond, `Date.now()` truncates — so the scan
751
751
  reuses the version before it, and a receiver authors that older version as an
752
752
  edit, which reverts the writer's own copy everywhere.
753
753
 
754
+ **A file that refuses to open is kept — unless it is being deleted.** Windows
755
+ refuses an open while a program copies or holds a file (EBUSY, EPERM, EACCES).
756
+ The scan keeps the version it read last and reads the file again on the next
757
+ scan, so one held file does not stop the rest of the folder. The same EPERM
758
+ answers an open in the moment between a delete marking a file and its name
759
+ going, so a refusal is looked at again after `LOCK_RECHECK_MS` (10, 20 and
760
+ 40 ms): a deleted file is gone by then, and the scan treats it as vanished —
761
+ a partial picture, which is not published — instead of keeping a version
762
+ nobody holds. Keeping it was field defect F6: the deletion was never authored,
763
+ and the next apply wrote the file back on its own node.
764
+
754
765
  What no rule over `stat` can decide is a writer that pauses for a long time, and
755
766
  `README.public.md` → "Known constraints" says what that costs.
756
767
 
757
- **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half and
758
- `test/fs-slow-copy.spec.ts` (3) for the deferral itself.
768
+ **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half,
769
+ `test/fs-slow-copy.spec.ts` (3) for the deferral itself, and
770
+ `test/fs-scanner-vanish.spec.ts` for the locked file and the one being deleted.
759
771
 
760
772
  ## Ignore Matching (`src/fs-ignore.ts`)
761
773
 
package/dist/README.md CHANGED
@@ -20,7 +20,7 @@ decision everything else follows from.
20
20
 
21
21
  ```bash
22
22
  npm install @rljson/fs-agent
23
- pnpm test # 70 files, 807 scenarios, 100 % coverage, then eslint
23
+ pnpm test # 71 files, 823 scenarios, 100 % coverage, then eslint
24
24
  ```
25
25
 
26
26
  ## Where to start
@@ -28,7 +28,7 @@ pnpm test # 70 files, 807 scenarios, 100 % coverage, then eslint
28
28
  | if you are | read |
29
29
  | --- | --- |
30
30
  | **using the package** | [README.public.md](README.public.md) — install, the production configuration, every option and what it costs, troubleshooting |
31
- | **deciding whether to trust it** | [README.tests.md](README.tests.md) — what the 807 scenarios actually prove, and what they cannot |
31
+ | **deciding whether to trust it** | [README.tests.md](README.tests.md) — what the 823 scenarios actually prove, and what they cannot |
32
32
  | **changing the sync** | [README.architecture.md](README.architecture.md) — the mechanism, and why each rule exists |
33
33
  | **calling the API** | [README.api.md](README.api.md) — every export, grouped by module, with what it costs |
34
34
  | **setting the repo up** | [README.contributors.md](README.contributors.md) — run, debug, build, publish |
@@ -8,8 +8,8 @@ found in the LICENSE file in the root of this package.
8
8
 
9
9
  # The test suite, as a document
10
10
 
11
- **70 files, 807 scenarios, 100 % coverage on statements, branches, functions and
12
- lines.** 806 must pass; one is committed inverted, and §2.11 says which and why.
11
+ **71 files, 823 scenarios, 100 % coverage on statements, branches, functions and
12
+ lines.** 822 must pass; one is committed inverted, and §2.11 says which and why.
13
13
  One command runs all of it:
14
14
 
15
15
  ```bash
@@ -23,7 +23,7 @@ failures. Four different tests once failed
23
23
  across four CI runs of the same commit, each passing on re-run — not four bugs,
24
24
  one scheduler.
25
25
 
26
- This document says what the suite actually proves, because the number 807 does
26
+ This document says what the suite actually proves, because the number 823 does
27
27
  not. It is organised by the question answered rather than by file; the file
28
28
  index is at the end.
29
29
 
@@ -34,7 +34,7 @@ index is at the end.
34
34
  | tier | what it is | files |
35
35
  | --- | --- | --- |
36
36
  | **mesh** | a real `Server`, real sockets (`createSocketPair`), real watchers, real files on disk, two to four nodes, with cuts, heals, mutes, deafenings and stopped processes | 12 |
37
- | **client–server** | two or three clients and a real hub, each suite run **twice** — once over `SocketMock`, once over a real socket.io server configured at production's 50 MB limit | 6 |
37
+ | **client–server** | two or three clients and a real hub, each suite run **twice** — once over `SocketMock`, once over a real socket.io server configured at production's 50 MB limit | 7 |
38
38
  | **unit / decision** | one agent, or a pure function with no filesystem and no clock | 55 |
39
39
 
40
40
  A decision-tier test proves a RULE. It does not prove the rule is ever
@@ -296,7 +296,7 @@ visible files all vanished is refused however many it carries.
296
296
  | `fs-filenames.spec.ts` (5) | a German filename round-tripping byte for byte, two Unicode spellings of one name not destroying each other, a case-only rename |
297
297
  | `fs-hostile-tree.spec.ts` (7) | a tree from a peer is not trusted with paths — no escaping the sync root |
298
298
  | `fs-filetype-changes.spec.ts` (6) | a path that changes what it IS: file → directory, directory → file, symlinks |
299
- | `fs-scanner-vanish.spec.ts` (12) | an entry deleted between `readdir` and `stat` |
299
+ | `fs-scanner-vanish.spec.ts` (17) | an entry deleted between `readdir` and `stat`, a locked file, and a file refused while it is being deleted |
300
300
  | `fs-disk-full.spec.ts` (3) | ENOSPC — a clean abort with a message, not a silent standstill |
301
301
  | `fs-slow-copy.spec.ts` (3) | a file still being written: never hashed half-done, and one unsettled file does not stop the folder |
302
302
  | `fs-clock-skew.spec.ts` (6) | a machine whose clock is wrong — a file is visible whatever its timestamp says |
@@ -425,7 +425,7 @@ Open items are in
425
425
  ## 5. File index
426
426
 
427
427
  Counts are what `pnpm test` reports per file, so suites that generate cases in a
428
- loop are counted as they run. They sum to the 807 above.
428
+ loop are counted as they run. They sum to the 823 above.
429
429
 
430
430
  ### Mesh tier
431
431
 
@@ -450,6 +450,7 @@ loop are counted as they run. They sum to the 807 above.
450
450
  | --- | --- | --- |
451
451
  | `client-server/socket-mock.spec.ts` | 35 | the shared suite (`shared-sync-tests.ts`) over `SocketMock` |
452
452
  | `client-server/socket-io.spec.ts` | 35 | the same shared suite over a real socket.io server at production's 50 MB limit |
453
+ | `client-server/large-file.spec.ts` | 2 | a 60 MB file over a real socket.io server at the 50 MB limit: added, changed, deleted, and edited on both sides while apart; counts the bytes the hub carries |
453
454
  | `client-server/advanced-sync.spec.ts` | 15 | three clients, catch-up, teardown and restart, 10 MB, 100 files, rapid overwrites |
454
455
  | `client-server/heals-after-forced-divergence.spec.ts` | 14 | deliberately dropped messages |
455
456
  | `client-server/conflict-sync.spec.ts` | 2 | a real offline divergent edit, both versions preserved |
@@ -460,8 +461,8 @@ loop are counted as they run. They sum to the 807 above.
460
461
  | file | n | what it covers |
461
462
  | --- | --- | --- |
462
463
  | `fs-agent.spec.ts` | 81 | the agent's surface |
463
- | `fs-scanner.spec.ts` | 62 | scanning, watching, the scan cache, the agent's own writes |
464
- | `fs-agent-degradation.spec.ts` | 15 | what the agent does when a dependency fails, and the shapes no scenario reaches |
464
+ | `fs-scanner.spec.ts` | 65 | scanning, watching, the scan cache, the agent's own writes |
465
+ | `fs-agent-degradation.spec.ts` | 16 | what the agent does when a dependency fails, and the shapes no scenario reaches |
465
466
  | `fs-agent-receive-degradation.spec.ts` | 16 | receiving when a part of it fails — a tree it cannot read, a stamp or state it cannot file, a folder that moves under the apply, a join |
466
467
  | `fs-receive.spec.ts` | 11 | what a node does with a head that arrived |
467
468
  | `fs-relate.spec.ts` | 11 | same / behind / ahead / fork / incomplete |
@@ -478,7 +479,7 @@ loop are counted as they run. They sum to the 807 above.
478
479
  | `fs-agent-authorship.spec.ts` | 4 | a node claims only what it changed |
479
480
  | `fs-divergence-is-content.spec.ts` | 2 | a divergence is a difference in CONTENT |
480
481
  | `fs-ref-vs-content.spec.ts` | 6 | ref identity vs content identity |
481
- | `fs-agent-concurrent-write.spec.ts` | 12 | two writes of one path must not blend — 200 rounds per assertion — and the synchronous writer the bookkeeping uses |
482
+ | `fs-agent-concurrent-write.spec.ts` | 17 | two writes of one path must not blend — 200 rounds per assertion — the synchronous writer the bookkeeping uses, and a rename that waits out a held file and names a refused name |
482
483
  | `fs-agent-incremental-restore.spec.ts` | 8 | a restore writes only what changed |
483
484
  | `fs-agent-locked-file.spec.ts` | 8 | a file held open by another process |
484
485
  | `fs-agent-blob-stream.spec.ts` | 3 | a restore streams the blob |
@@ -491,7 +492,7 @@ loop are counted as they run. They sum to the 807 above.
491
492
  | `fs-blob-adapter.spec.ts` | 26 | file ↔ blob |
492
493
  | `fs-db-adapter.spec.ts` | 6 | storing a tree with its predecessors |
493
494
  | `blob-io.spec.ts` | 5 | storing a file as a blob |
494
- | `fs-scanner-vanish.spec.ts` | 12 | an entry that vanishes mid-scan |
495
+ | `fs-scanner-vanish.spec.ts` | 17 | an entry that vanishes mid-scan, a locked file, one being deleted |
495
496
  | `fs-scanner-scan-coalescing.spec.ts` | 4 | a burst collapses into at most two passes |
496
497
  | `fs-hostile-tree.spec.ts` | 7 | a peer's tree is not trusted with paths |
497
498
  | `fs-impossible-filename.spec.ts` | 4 | a path the filesystem refuses |
@@ -611,17 +611,6 @@ export declare class FsAgent {
611
611
  * @param err - The error value caught
612
612
  */
613
613
  _writeSyncError(context: string, err: unknown): void;
614
- /**
615
- * Writes a file through a staging file and a rename.
616
- *
617
- * Kept as a thin named wrapper because the restore path reads as a pair with
618
- * {@link FsAgent._atomicWriteStream}. The rule, and the byte-level
619
- * corruption that made it a rule on every platform rather than on Windows
620
- * only, are in `fs-atomic-write.ts`.
621
- * @param filePath - Destination path
622
- * @param content - Bytes to write
623
- */
624
- private static _atomicWriteFile;
625
614
  /**
626
615
  * Whether this error came from reading the blob rather than writing the file.
627
616
  *
@@ -639,8 +628,9 @@ export declare class FsAgent {
639
628
  /**
640
629
  * Writes a file from a stream, holding one chunk at a time.
641
630
  *
642
- * The twin of {@link FsAgent._atomicWriteFile} — temp and rename on every
643
- * platform, for the same reasons — but never materialising the whole file. A
631
+ * Temp and rename on every platform — the rule, and the byte-level
632
+ * corruption that made it a rule, are in `fs-atomic-write.ts` — and never
633
+ * materialising the whole file. A
644
634
  * 500 MB file used to cost 500 MB of Buffer on the receiving agent, another
645
635
  * copy in the socket parser, and — on the serving hub — the same again. That
646
636
  * is the shape that exhausted a cloud relay: memory that is work in flight
package/dist/fs-agent.js CHANGED
@@ -222,6 +222,74 @@ var atomicTmpPath = (filePath) => {
222
222
  return join(dirname(filePath), `${ATOMIC_TMP_PREFIX}${rnd}`);
223
223
  };
224
224
  /**
225
+ * How often a rename onto a held file is tried again on this platform.
226
+ *
227
+ * Windows refuses to replace a file while another rename onto it is under way,
228
+ * or while a program holds it open, with EPERM, EBUSY or EACCES: two writes
229
+ * racing on one path then failed instead of one of them winning. Ten retries
230
+ * wait about half a second in all, long enough for a colliding rename and
231
+ * short enough that a real lock still reaches the caller soon. POSIX replaces
232
+ * the target regardless, so a refusal there is final and not retried.
233
+ * @returns The number of retries.
234
+ */
235
+ var renameRetries = () => {
236
+ /* v8 ignore start -- @preserve Windows-only arm; CI runs on Linux */
237
+ return process.platform === "win32" ? 10 : 0;
238
+ /* v8 ignore stop -- @preserve */
239
+ };
240
+ var isHeld = (err) => {
241
+ const code = err?.code;
242
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
243
+ };
244
+ /**
245
+ * The error for a rename the filesystem refused because of the destination
246
+ * NAME, coded EINVAL, the code of an invalid argument.
247
+ *
248
+ * Windows reports an invalid name — a component over 255 characters, `?`,
249
+ * `*`, `:` and the other reserved characters — as ENOENT, the code of a
250
+ * missing file. A staged file renamed within its own directory is not missing,
251
+ * though: when it and the directory both still exist after the refusal, the
252
+ * name is what was refused. Anything else stays the ENOENT it was.
253
+ * @param err - What the rename threw.
254
+ * @param from - The staged file.
255
+ * @param to - The destination.
256
+ * @returns The EINVAL error, or `undefined` when the name is not the cause.
257
+ */
258
+ var nameRefused = async (err, from, to) => {
259
+ if (err?.code !== "ENOENT") return;
260
+ try {
261
+ await stat(from);
262
+ await stat(dirname(to));
263
+ } catch {
264
+ return;
265
+ }
266
+ return Object.assign(/* @__PURE__ */ new Error(`EINVAL: the filesystem refuses the name '${to}'`), {
267
+ code: "EINVAL",
268
+ syscall: "rename",
269
+ path: from,
270
+ dest: to,
271
+ cause: err
272
+ });
273
+ };
274
+ /**
275
+ * Renames `from` onto `to`, trying again while the target is held.
276
+ * @param from - The staged file.
277
+ * @param to - The destination.
278
+ * @param retries - How often to try again after a held-file refusal.
279
+ * @param doRename - The rename to call.
280
+ */
281
+ var renameOver = async (from, to, retries = renameRetries(), doRename = rename) => {
282
+ for (let attempt = 0;; attempt++) try {
283
+ return await doRename(from, to);
284
+ } catch (err) {
285
+ if (attempt < retries && isHeld(err)) {
286
+ await new Promise((r) => setTimeout(r, 10 * (attempt + 1)));
287
+ continue;
288
+ }
289
+ throw await nameRefused(err, from, to) ?? err;
290
+ }
291
+ };
292
+ /**
225
293
  * Writes bytes to `filePath` through a staging file.
226
294
  *
227
295
  * We do not `fsync` the temp: it adds significant per-file latency under
@@ -234,7 +302,7 @@ var atomicWriteFile = async (filePath, content) => {
234
302
  const tmp = atomicTmpPath(filePath);
235
303
  try {
236
304
  await writeFile(tmp, content);
237
- await rename(tmp, filePath);
305
+ await renameOver(tmp, filePath);
238
306
  } catch (err) {
239
307
  try {
240
308
  await unlink(tmp);
@@ -302,7 +370,7 @@ var atomicWriteStream = async (filePath, stream, wrapReadError) => {
302
370
  }
303
371
  await handle.close();
304
372
  try {
305
- await rename(tmp, filePath);
373
+ await renameOver(tmp, filePath);
306
374
  } catch (err) {
307
375
  await unlink(tmp).catch(() => {});
308
376
  throw err;
@@ -360,7 +428,7 @@ var FsBlobAdapter = class FsBlobAdapter {
360
428
  await handle.close();
361
429
  }
362
430
  return {
363
- name: filePath.split("/").pop() || filePath.split("\\").pop() || "",
431
+ name: filePath.split(/[\\/]/).pop(),
364
432
  blobId: blobProps.blobId,
365
433
  size: stats.size,
366
434
  mtime: stats.mtime.getTime(),
@@ -2018,6 +2086,23 @@ var STUCK_PAUSE_MS = 15e3;
2018
2086
  /** How many of this process's own writes the scanner remembers. */
2019
2087
  var OWN_WRITES_MAX = 1e4;
2020
2088
  /**
2089
+ * The pauses, in ms, before the scanner opens a refused file again.
2090
+ *
2091
+ * Windows deletes a file in two steps: the deleting call opens the file, marks
2092
+ * it and closes it, and the name goes with the close. An open in between is
2093
+ * refused with EPERM, the code of a file another program holds. Taken for a
2094
+ * lock, the deleted file kept the version the last scan read — so its deletion
2095
+ * was never authored, and the next apply wrote it back (field defect F6). The
2096
+ * window lasts microseconds; a look after these pauses finds a deleted file
2097
+ * gone and a held one still refused. Seventy milliseconds in all, paid only
2098
+ * by a file that refuses.
2099
+ */
2100
+ var LOCK_RECHECK_MS = [
2101
+ 10,
2102
+ 20,
2103
+ 40
2104
+ ];
2105
+ /**
2021
2106
  * Scans and watches file system changes, extracting RLJSON tree structure
2022
2107
  */
2023
2108
  var FsScanner = class FsScanner {
@@ -2040,6 +2125,10 @@ var FsScanner = class FsScanner {
2040
2125
  _missedChangesDuringPause = false;
2041
2126
  /** Periodic full-rescan timer that catches events the native watcher drops. */
2042
2127
  _safetyTimer = null;
2128
+ /** Whether a safety rescan is running; a tick meanwhile is skipped. */
2129
+ _safetyRescanRunning = false;
2130
+ /** Files that could not be opened, reported once until they can be. */
2131
+ _locked = /* @__PURE__ */ new Set();
2043
2132
  /** When the current pause began, or null when not paused. */
2044
2133
  _pausedAt = null;
2045
2134
  /** Releases a pause whose resume never arrived (see {@link pauseWatch}). */
@@ -2291,11 +2380,17 @@ var FsScanner = class FsScanner {
2291
2380
  else {
2292
2381
  let handle;
2293
2382
  try {
2294
- handle = await open(childPath, "r");
2383
+ handle = await FsScanner._openToRead(childPath);
2295
2384
  } catch (error) {
2296
2385
  if (FsScanner._isVanished(error)) throw error;
2386
+ if (this._watcher !== null && FsScanner._isLocked(error)) {
2387
+ this._reportLocked(childRelPath, error);
2388
+ this._keepPrevious(childRelPath, trees, childTrees, childRefs);
2389
+ continue;
2390
+ }
2297
2391
  throw new Error(`Failed to read file "${childRelPath}": ${error instanceof Error ? error.message : String(error)}`);
2298
2392
  }
2393
+ this._locked.delete(childRelPath);
2299
2394
  let blobProps;
2300
2395
  try {
2301
2396
  blobProps = await storeFileAsBlob(this._bs, handle, childStats.size);
@@ -2371,7 +2466,7 @@ var FsScanner = class FsScanner {
2371
2466
  try {
2372
2467
  const raw = await readFile(this._scanCachePath, "utf8");
2373
2468
  const parsed = JSON.parse(raw);
2374
- if (Array.isArray(parsed.entries)) this._blobCache = new Map(parsed.entries);
2469
+ if (parsed.version === 2 && Array.isArray(parsed.entries)) this._blobCache = new Map(parsed.entries);
2375
2470
  } catch {}
2376
2471
  }
2377
2472
  /**
@@ -2382,7 +2477,7 @@ var FsScanner = class FsScanner {
2382
2477
  /* v8 ignore next -- @preserve: only called when scanCachePath is set */
2383
2478
  if (!this._scanCachePath) return;
2384
2479
  const body = JSON.stringify({
2385
- version: 1,
2480
+ version: 2,
2386
2481
  entries: [...this._blobCache.entries()]
2387
2482
  });
2388
2483
  const tmp = `${this._scanCachePath}.${Date.now().toString(36)}.tmp`;
@@ -2518,6 +2613,17 @@ var FsScanner = class FsScanner {
2518
2613
  */
2519
2614
  _reuse(relativePath, trees, childTrees, childRefs) {
2520
2615
  this._unsettledDuringScan.push(relativePath);
2616
+ this._keepPrevious(relativePath, trees, childTrees, childRefs);
2617
+ }
2618
+ /**
2619
+ * Puts the node the last scan had for a path into this scan's tree, when
2620
+ * there was one.
2621
+ * @param relativePath - The path.
2622
+ * @param trees - The tree map being built.
2623
+ * @param childTrees - The parent's child nodes.
2624
+ * @param childRefs - The parent's child hashes.
2625
+ */
2626
+ _keepPrevious(relativePath, trees, childTrees, childRefs) {
2521
2627
  const previous = this.getTreeByPath(relativePath);
2522
2628
  if (!previous) return;
2523
2629
  const hash = previous._hash;
@@ -2544,7 +2650,26 @@ var FsScanner = class FsScanner {
2544
2650
  }
2545
2651
  /* v8 ignore stop -- @preserve */
2546
2652
  }
2653
+ /**
2654
+ * Runs one safety rescan, unless one is still running.
2655
+ *
2656
+ * The timer fires every {@link SAFETY_RESCAN_INTERVAL_MS} whatever a scan
2657
+ * costs, and a scan that waits on a large file being copied takes far
2658
+ * longer. Every tick then joined the same scan and, when it ended, each
2659
+ * reported the same drift — seven times in one millisecond on the lab
2660
+ * during a 400 MB copy, and seven notifications for one change. The tick
2661
+ * that finds a rescan running is covered by it.
2662
+ */
2547
2663
  async _runSafetyRescan() {
2664
+ if (this._safetyRescanRunning) return;
2665
+ this._safetyRescanRunning = true;
2666
+ try {
2667
+ await this._safetyRescan();
2668
+ } finally {
2669
+ this._safetyRescanRunning = false;
2670
+ }
2671
+ }
2672
+ async _safetyRescan() {
2548
2673
  if (this._stopRequested) return;
2549
2674
  if (this._paused && !this._pauseLooksStuck({
2550
2675
  type: "safety-rescan",
@@ -2622,6 +2747,46 @@ var FsScanner = class FsScanner {
2622
2747
  * @param err - The caught value.
2623
2748
  * @returns `true` for ENOENT / ENOTDIR.
2624
2749
  */
2750
+ /**
2751
+ * Whether an open failed because the file is held by another program, or
2752
+ * may not be read: Windows answers a copy in progress with EBUSY.
2753
+ * @param err - What the open threw.
2754
+ * @returns True for EBUSY, EPERM and EACCES.
2755
+ */
2756
+ static _isLocked(err) {
2757
+ const code = err?.code;
2758
+ return code === "EBUSY" || code === "EPERM" || code === "EACCES";
2759
+ }
2760
+ /**
2761
+ * Opens a file to read it, and opens it again after each of
2762
+ * {@link LOCK_RECHECK_MS} while it is refused as held.
2763
+ *
2764
+ * A file refused because it is being deleted is gone at the next look, and
2765
+ * that open throws ENOENT: the scan then treats it as vanished, not as
2766
+ * locked. A file a program really holds is refused every time, and the last
2767
+ * refusal is thrown as before.
2768
+ * @param path - The file.
2769
+ * @returns The open handle.
2770
+ */
2771
+ static async _openToRead(path) {
2772
+ for (const pause of LOCK_RECHECK_MS) try {
2773
+ return await open(path, "r");
2774
+ } catch (error) {
2775
+ if (!FsScanner._isLocked(error)) throw error;
2776
+ await new Promise((r) => setTimeout(r, pause));
2777
+ }
2778
+ return open(path, "r");
2779
+ }
2780
+ /**
2781
+ * Reports a file that could not be opened, once until it can be again.
2782
+ * @param relativePath - The file.
2783
+ * @param err - Why it could not be opened.
2784
+ */
2785
+ _reportLocked(relativePath, err) {
2786
+ if (this._locked.has(relativePath)) return;
2787
+ this._locked.add(relativePath);
2788
+ console.warn(`[fs-scanner] "${relativePath}" is locked (${FsScanner._errMessage(err)}) — keeping its last version, read again on the next scan`);
2789
+ }
2625
2790
  static _isVanished(err) {
2626
2791
  const code = err?.code;
2627
2792
  return code === "ENOENT" || code === "ENOTDIR";
@@ -3436,19 +3601,6 @@ var FsAgent = class FsAgent {
3436
3601
  } catch {}
3437
3602
  }
3438
3603
  /**
3439
- * Writes a file through a staging file and a rename.
3440
- *
3441
- * Kept as a thin named wrapper because the restore path reads as a pair with
3442
- * {@link FsAgent._atomicWriteStream}. The rule, and the byte-level
3443
- * corruption that made it a rule on every platform rather than on Windows
3444
- * only, are in `fs-atomic-write.ts`.
3445
- * @param filePath - Destination path
3446
- * @param content - Bytes to write
3447
- */
3448
- static async _atomicWriteFile(filePath, content) {
3449
- return atomicWriteFile(filePath, content);
3450
- }
3451
- /**
3452
3604
  * Whether this error came from reading the blob rather than writing the file.
3453
3605
  *
3454
3606
  * The two have different answers. A blob that cannot be fetched costs one
@@ -3467,8 +3619,9 @@ var FsAgent = class FsAgent {
3467
3619
  /**
3468
3620
  * Writes a file from a stream, holding one chunk at a time.
3469
3621
  *
3470
- * The twin of {@link FsAgent._atomicWriteFile} — temp and rename on every
3471
- * platform, for the same reasons — but never materialising the whole file. A
3622
+ * Temp and rename on every platform — the rule, and the byte-level
3623
+ * corruption that made it a rule, are in `fs-atomic-write.ts` — and never
3624
+ * materialising the whole file. A
3472
3625
  * 500 MB file used to cost 500 MB of Buffer on the receiving agent, another
3473
3626
  * copy in the socket parser, and — on the serving hub — the same again. That
3474
3627
  * is the shape that exhausted a cloud relay: memory that is work in flight
@@ -5159,7 +5312,7 @@ var FsAgent = class FsAgent {
5159
5312
  const blob = outcome.merged.get(path);
5160
5313
  const full = join(this._rootPath, ...path.split("/"));
5161
5314
  await mkdir(dirname(full), { recursive: true });
5162
- await FsAgent._atomicWriteFile(full, await this._adapter.getFileContent(blob));
5315
+ await FsAgent._atomicWriteStream(full, await this._bs.getBlobStream(blob));
5163
5316
  const st = await stat(full);
5164
5317
  this._scanner.noteWrite(path, blob, st.size, st.mtime.getTime());
5165
5318
  }
@@ -18,6 +18,31 @@ export declare const ATOMIC_TMP_PREFIX = ".fsagent-tmp-";
18
18
  * @returns A path to stage into.
19
19
  */
20
20
  export declare const atomicTmpPath: (filePath: string) => string;
21
+ /**
22
+ * The pause before the first retry of a refused rename, in ms; each further
23
+ * pause is one step longer.
24
+ */
25
+ export declare const RENAME_RETRY_STEP_MS = 10;
26
+ /**
27
+ * How often a rename onto a held file is tried again on this platform.
28
+ *
29
+ * Windows refuses to replace a file while another rename onto it is under way,
30
+ * or while a program holds it open, with EPERM, EBUSY or EACCES: two writes
31
+ * racing on one path then failed instead of one of them winning. Ten retries
32
+ * wait about half a second in all, long enough for a colliding rename and
33
+ * short enough that a real lock still reaches the caller soon. POSIX replaces
34
+ * the target regardless, so a refusal there is final and not retried.
35
+ * @returns The number of retries.
36
+ */
37
+ export declare const renameRetries: () => number;
38
+ /**
39
+ * Renames `from` onto `to`, trying again while the target is held.
40
+ * @param from - The staged file.
41
+ * @param to - The destination.
42
+ * @param retries - How often to try again after a held-file refusal.
43
+ * @param doRename - The rename to call.
44
+ */
45
+ export declare const renameOver: (from: string, to: string, retries?: number, doRename?: (from: string, to: string) => Promise<void>) => Promise<void>;
21
46
  /**
22
47
  * Writes bytes to `filePath` through a staging file.
23
48
  *
@@ -76,6 +76,29 @@ export type FsChangeCallback = (change: FsChange) => void | Promise<void>;
76
76
  * already covered.
77
77
  */
78
78
  export declare const DEFAULT_SETTLE_MS = 100;
79
+ /**
80
+ * The pauses, in ms, before the scanner opens a refused file again.
81
+ *
82
+ * Windows deletes a file in two steps: the deleting call opens the file, marks
83
+ * it and closes it, and the name goes with the close. An open in between is
84
+ * refused with EPERM, the code of a file another program holds. Taken for a
85
+ * lock, the deleted file kept the version the last scan read — so its deletion
86
+ * was never authored, and the next apply wrote it back (field defect F6). The
87
+ * window lasts microseconds; a look after these pauses finds a deleted file
88
+ * gone and a held one still refused. Seventy milliseconds in all, paid only
89
+ * by a file that refuses.
90
+ */
91
+ export declare const LOCK_RECHECK_MS: readonly number[];
92
+ /**
93
+ * The format of a persisted scan cache. A cache of any other version is
94
+ * discarded, and the next scan reads and stores every file once.
95
+ *
96
+ * A cached blobId is only worth reusing while the blob store still holds that
97
+ * blob. Version 2 came with a blob store that keeps blobs as blocks in a new
98
+ * layout: a node coming up with an older cache would announce blobs its store
99
+ * no longer holds, and nobody could fetch them until each file changed again.
100
+ */
101
+ export declare const SCAN_CACHE_VERSION = 2;
79
102
  export interface FsScanOptions {
80
103
  /** Patterns to ignore (glob patterns) */
81
104
  ignore?: string[];
@@ -140,6 +163,10 @@ export declare class FsScanner {
140
163
  private _missedChangesDuringPause;
141
164
  /** Periodic full-rescan timer that catches events the native watcher drops. */
142
165
  private _safetyTimer;
166
+ /** Whether a safety rescan is running; a tick meanwhile is skipped. */
167
+ private _safetyRescanRunning;
168
+ /** Files that could not be opened, reported once until they can be. */
169
+ private readonly _locked;
143
170
  /** When the current pause began, or null when not paused. */
144
171
  private _pausedAt;
145
172
  /** Releases a pause whose resume never arrived (see {@link pauseWatch}). */
@@ -335,8 +362,28 @@ export declare class FsScanner {
335
362
  * @param childRefs - The parent's child hashes.
336
363
  */
337
364
  private _reuse;
365
+ /**
366
+ * Puts the node the last scan had for a path into this scan's tree, when
367
+ * there was one.
368
+ * @param relativePath - The path.
369
+ * @param trees - The tree map being built.
370
+ * @param childTrees - The parent's child nodes.
371
+ * @param childRefs - The parent's child hashes.
372
+ */
373
+ private _keepPrevious;
338
374
  private _rescanAfterSettle;
375
+ /**
376
+ * Runs one safety rescan, unless one is still running.
377
+ *
378
+ * The timer fires every {@link SAFETY_RESCAN_INTERVAL_MS} whatever a scan
379
+ * costs, and a scan that waits on a large file being copied takes far
380
+ * longer. Every tick then joined the same scan and, when it ended, each
381
+ * reported the same drift — seven times in one millisecond on the lab
382
+ * during a 400 MB copy, and seven notifications for one change. The tick
383
+ * that finds a rescan running is covered by it.
384
+ */
339
385
  private _runSafetyRescan;
386
+ private _safetyRescan;
340
387
  /**
341
388
  * Path+blobId content fingerprint used by the safety rescan to detect drift
342
389
  * the native watcher missed (mtime-independent, same idea as the agent's
@@ -372,6 +419,31 @@ export declare class FsScanner {
372
419
  * @param err - The caught value.
373
420
  * @returns `true` for ENOENT / ENOTDIR.
374
421
  */
422
+ /**
423
+ * Whether an open failed because the file is held by another program, or
424
+ * may not be read: Windows answers a copy in progress with EBUSY.
425
+ * @param err - What the open threw.
426
+ * @returns True for EBUSY, EPERM and EACCES.
427
+ */
428
+ private static _isLocked;
429
+ /**
430
+ * Opens a file to read it, and opens it again after each of
431
+ * {@link LOCK_RECHECK_MS} while it is refused as held.
432
+ *
433
+ * A file refused because it is being deleted is gone at the next look, and
434
+ * that open throws ENOENT: the scan then treats it as vanished, not as
435
+ * locked. A file a program really holds is refused every time, and the last
436
+ * refusal is thrown as before.
437
+ * @param path - The file.
438
+ * @returns The open handle.
439
+ */
440
+ private static _openToRead;
441
+ /**
442
+ * Reports a file that could not be opened, once until it can be again.
443
+ * @param relativePath - The file.
444
+ * @param err - Why it could not be opened.
445
+ */
446
+ private _reportLocked;
375
447
  private static _isVanished;
376
448
  /** Whether the host is Windows — gates Windows-specific watcher hardening. */
377
449
  private static get _isWindows();
@@ -1,2 +1,2 @@
1
1
  /** The version of the `@rljson/fs-agent` package. */
2
- export declare const fsAgentVersion = "0.2.6";
2
+ export declare const fsAgentVersion = "0.2.8";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rljson/fs-agent",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Rljson fs-agent description",
5
5
  "homepage": "https://github.com/rljson/fs-agent",
6
6
  "bugs": "https://github.com/rljson/fs-agent/issues",
@@ -21,30 +21,30 @@
21
21
  "type": "module",
22
22
  "devDependencies": {
23
23
  "@rljson/dna-rljson": "^0.3.2",
24
- "@rljson/server": "0.1.0",
25
- "@tssuite/helix-js": "0.5.1",
26
- "@types/node": "^26.6.6",
27
- "@typescript-eslint/eslint-plugin": "^8.72.1",
28
- "@typescript-eslint/parser": "^8.72.1",
29
- "@vitest/coverage-v8": "^5.1.0",
24
+ "@rljson/server": "0.2.0",
25
+ "@tssuite/helix-js": "0.7.0",
26
+ "@types/node": "^26.6.11",
27
+ "@typescript-eslint/eslint-plugin": "^8.74.0",
28
+ "@typescript-eslint/parser": "^8.74.0",
29
+ "@vitest/coverage-v8": "^5.1.2",
30
30
  "cross-env": "^10.1.0",
31
- "eslint": "~10.14.0",
32
- "eslint-plugin-jsdoc": "^65.4.2",
31
+ "eslint": "~10.15.0",
32
+ "eslint-plugin-jsdoc": "^65.5.5",
33
33
  "eslint-plugin-tsdoc": "^0.5.4",
34
34
  "globals": "^17.14.0",
35
35
  "jsdoc": "^4.0.5",
36
36
  "read-pkg": "^10.1.0",
37
37
  "typescript": "~6.0.3",
38
- "typescript-eslint": "^8.72.1",
39
- "vite": "^8.3.5",
38
+ "typescript-eslint": "^8.74.0",
39
+ "vite": "^8.3.8",
40
40
  "vite-node": "^6.0.0",
41
41
  "vite-plugin-dts": "^5.1.2",
42
42
  "vite-tsconfig-paths": "^6.1.1",
43
- "vitest": "^5.1.0",
43
+ "vitest": "^5.1.2",
44
44
  "vitest-dom": "^0.1.1"
45
45
  },
46
46
  "dependencies": {
47
- "@rljson/bs": "0.0.32",
47
+ "@rljson/bs": "0.1.1",
48
48
  "@rljson/db": "0.1.4",
49
49
  "@rljson/hash": "0.0.21",
50
50
  "@rljson/io": "0.0.88",