|
| 1 | +--- |
| 2 | +title: Retained-directory staging |
| 3 | +description: "Prepare and publish one file while retaining its original directory for abort cleanup." |
| 4 | +--- |
| 5 | + |
| 6 | +# Retained-directory staging |
| 7 | + |
| 8 | +`stageFileInDirectory()` from `@openclaw/fs-safe/advanced` prepares one file in |
| 9 | +an existing directory and keeps that directory open until cleanup or disposal. |
| 10 | +It requires the native binding on Linux or macOS, even in native mode `auto`. |
| 11 | +Native off, an unavailable binding, or a binding without the required mechanism |
| 12 | +fails before file creation. Windows is explicitly unsupported for this API. |
| 13 | +Existing root, output, temp, lock, and durability APIs retain their documented |
| 14 | +platform and fallback contracts. |
| 15 | + |
| 16 | +```ts |
| 17 | +import type { DirectoryReceipt } from "@openclaw/fs-safe/durability"; |
| 18 | +import { |
| 19 | + stageFileInDirectory, |
| 20 | + type PublishedFileReceipt, |
| 21 | +} from "@openclaw/fs-safe/advanced"; |
| 22 | + |
| 23 | +// Call while holding the application's cooperative writer lock. The caller |
| 24 | +// supplies its authorization, manager, snapshot, and fingerprint checks. |
| 25 | +export async function publishReviewedUpdate(options: { |
| 26 | + directory: DirectoryReceipt; |
| 27 | + basename: string; |
| 28 | + bytes: Uint8Array; |
| 29 | + assertAuthorizedAndCurrent(): Promise<void>; |
| 30 | +}): Promise<PublishedFileReceipt> { |
| 31 | + await options.assertAuthorizedAndCurrent(); |
| 32 | + await using staged = await stageFileInDirectory({ |
| 33 | + directory: options.directory, |
| 34 | + content: options.bytes, |
| 35 | + }); |
| 36 | + await options.assertAuthorizedAndCurrent(); |
| 37 | + await staged.assertCurrent(); |
| 38 | + return await staged.publish(options.basename, { overwrite: true }); |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +`await using` always disposes, including on exceptions. If both the body and |
| 43 | +disposal fail, JavaScript preserves both errors in a `SuppressedError`. A |
| 44 | +successful return means publication was observed and verified, not that a |
| 45 | +separate application transaction committed. Application rollback and recovery |
| 46 | +remain with the caller. |
| 47 | + |
| 48 | +## API |
| 49 | + |
| 50 | +```ts |
| 51 | +function stageFileInDirectory(options: { |
| 52 | + directory: string | DirectoryReceipt; |
| 53 | + content: string | Uint8Array; |
| 54 | + mode?: number; |
| 55 | +}): Promise<StagedFile>; |
| 56 | + |
| 57 | +interface StagedFile extends AsyncDisposable { |
| 58 | + readonly receipt: StagedFileReceipt; |
| 59 | + assertCurrent(): Promise<void>; |
| 60 | + publish(basename: string, options: { overwrite: boolean }): Promise<PublishedFileReceipt>; |
| 61 | + cleanup(): Promise<StagedFileCleanupReceipt>; |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +Strings are UTF-8. `mode` is the requested **published** mode and defaults to |
| 66 | +`0600`; exact final modes, including `000`, are supported. The unpublished file |
| 67 | +stays at `0600` throughout preparation and any awaited application checks. |
| 68 | +After rename succeeds and the published entry passes identity validation, the |
| 69 | +owner applies the requested mode through its retained file descriptor and |
| 70 | +synchronizes the file. No parent is created or chmodded. |
| 71 | +Creation uses an exclusive, no-follow, close-on-exec open of a generated direct |
| 72 | +child name. Writes use that descriptor. Inspection uses non-following metadata |
| 73 | +operations, never a potentially blocking reopen of the leaf. |
| 74 | + |
| 75 | +A supplied directory receipt must still match at admission. Its numeric |
| 76 | +identity must be exactly representable; ambiguous identity fails closed. |
| 77 | +Returned receipts are frozen descriptive snapshots, not mutable authority. |
| 78 | +Changing a supplied receipt after admission cannot retarget the lifecycle. |
| 79 | + |
| 80 | +`StagedFileReceipt` contains `directory` (`path`, `realPath`, and exact bigint |
| 81 | +`identity.dev`/`identity.ino`), `temporaryBasename`, and the prepared file's |
| 82 | +`identity` (`dev`, `ino`, `size`, `nlink`, `mtimeNs`, `ctimeNs` as bigint; |
| 83 | +`mode`, `uid`, `gid` as numbers). This is a preparation-time snapshot of the |
| 84 | +private stage: its mode is `0600`. Publication does not refresh this snapshot; |
| 85 | +neither its mode nor its timestamps are a final-file fingerprint. No raw |
| 86 | +descriptors are exposed. |
| 87 | + |
| 88 | +`assertCurrent()` verifies the original pathname's directory identity and the |
| 89 | +staged name against the retained file. A failed check does not disable cleanup. |
| 90 | +After successful publication there is no staged name to check, so further |
| 91 | +checks or publication reject. Cleanup closes the lifecycle; later checks and |
| 92 | +publication reject before descriptor use. Rejected publication still carries its |
| 93 | +phase, cause, and recorded publication outcome after closure. Concurrent calls |
| 94 | +are serialized in invocation order, including cleanup and disposal. Repeated |
| 95 | +cleanup returns the recorded outcome, or repeats the recorded error, without |
| 96 | +touching descriptors. |
| 97 | + |
| 98 | +## Publication and failure evidence |
| 99 | + |
| 100 | +`publish()` requires an explicit boolean `overwrite` and one direct-child |
| 101 | +basename. Empty, dot, dotdot, separators, absolute paths, NUL, control characters, |
| 102 | +drive-relative spellings, and the stage's own name are rejected. |
| 103 | + |
| 104 | +With `overwrite: false`, publication is genuine kernel no-replace rename; a |
| 105 | +collision leaves both names unchanged and raises `FsSafeError("already-exists")`. |
| 106 | +The stage may then be cleaned or published under another name. With |
| 107 | +`overwrite: true`, publication is plain atomic replacement. Neither route |
| 108 | +copies. Both source and destination resolve through the retained original |
| 109 | +parent, with checks immediately before rename and after publication. |
| 110 | + |
| 111 | +`PublishedFileReceipt` has `status: "published"`, `staged`, `basename`, and |
| 112 | +`overwrite`. Its `staged` field retains the private preparation snapshot, not |
| 113 | +final metadata. Errors from publication carry typed `StagedFileFailureDetails` |
| 114 | +in `FsSafeError.details`, including `phase` and `publication`. Publication is |
| 115 | +`not-published`, `published` (with its receipt), or `indeterminate` (with the |
| 116 | +attempted basename and overwrite policy) if a rename error cannot establish |
| 117 | +whether it committed. The underlying error remains in `cause`. |
| 118 | + |
| 119 | +A parent move after the final pre-check cannot divert the rename to a |
| 120 | +replacement parent. It can publish inside the moved original and then fail |
| 121 | +post-validation. Successful rename is recorded before those checks; cleanup |
| 122 | +never deletes or rolls back a published final name. Indeterminate publication |
| 123 | +also preserves names for caller-directed recovery. |
| 124 | + |
| 125 | +The same rule applies if applying the published mode, synchronizing, or a later |
| 126 | +check fails: the error reports `published`, and cleanup preserves the final |
| 127 | +name. The file may still have mode `0600` or may already have the requested |
| 128 | +mode, depending on which operation failed. A `published` failure receipt records |
| 129 | +rename success, not successful permission finalization. |
| 130 | + |
| 131 | +## Cleanup guarantee and limits |
| 132 | + |
| 133 | +If the temporary basename still names the object created by this lifecycle and |
| 134 | +filesystem removal remains permitted, moving or replacing the actual parent |
| 135 | +(or an ancestor) does not strand the unpublished temp. Cleanup resolves through |
| 136 | +the retained original directory, even after `assertCurrent()` rejects drift. |
| 137 | +Same-name sentinels in the replacement parent are not touched. |
| 138 | + |
| 139 | +`StagedFileCleanupReceipt` records `temporaryBasename`, `publication`, |
| 140 | +`resources` (`closed` or `close-failed`), and `status`: |
| 141 | + |
| 142 | +| Status | Meaning | |
| 143 | +|---|---| |
| 144 | +| `removed` | The owned recorded name was unlinked through the retained directory. | |
| 145 | +| `name-absent` | That name was absent in the original directory; this does not prove the inode has no other names. | |
| 146 | +| `preserved` | An observed substitute or an indeterminate publication was left alone. | |
| 147 | +| `failed` | Inspection or removal failed. | |
| 148 | +| `not-needed` | Publication was recorded, or preparation failed before creating a file. | |
| 149 | + |
| 150 | +Explicit cleanup returns preservation outcomes. Removal or close failures throw |
| 151 | +an `FsSafeError` with the receipt in `details.cleanup` and underlying errors in |
| 152 | +`cause`. Disposal also throws for preservation, so ignoring its return value |
| 153 | +cannot hide incomplete cleanup. Setup failures preserve the original error; |
| 154 | +when cleanup also fails, an aggregate cause retains both failures. Descriptors |
| 155 | +are closed on every cleanup outcome, with no retry through recycled numbers. |
| 156 | + |
| 157 | +This is **directory-relative targeting**, not expected-destination-inode/CAS |
| 158 | +publication. Checking an identity before rename does not make rename CAS. |
| 159 | +Likewise, the identity check followed by `unlinkat` is not an atomic conditional |
| 160 | +unlink: an adversary can replace the leaf in that final syscall gap. Observed |
| 161 | +substitutions are preserved, but this API does not guarantee recovery after |
| 162 | +arbitrary child renames, permission revocation, I/O failure, or process death. |
| 163 | +Keep application authorization, manager checks, snapshots, fingerprints, |
| 164 | +cooperative locks, and conditional rollback. |
| 165 | + |
| 166 | +Namespace cleanup is not crash durability. Staging retains the native writer's |
| 167 | +file synchronization behavior, and publication synchronizes its directory |
| 168 | +(with the existing `EPERM` exception); cleanup does not promise a durable unlink. |
| 169 | +No successful receipt promises survival across a crash. See [Directory |
| 170 | +durability](durability.md) when an application needs a separate durability proof. |
| 171 | +`pinDirectory().assertCurrent()` and `.sync()` still require a current pathname; |
| 172 | +they do not gain this cleanup authority. |
| 173 | + |
| 174 | +## Related pages |
| 175 | + |
| 176 | +- [Advanced composition](advanced.md) |
| 177 | +- [Native architecture](native.md) |
| 178 | +- [Security model](security-model.md) |
0 commit comments