|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import { FsSafeError } from "./errors.js"; |
| 4 | +import { createNativeExclusiveFile, type NativeFileHandle } from "./native-operations.js"; |
| 5 | +import type { Root } from "./root-impl.js"; |
| 6 | +import { |
| 7 | + computeSidecarLockDelayMs, |
| 8 | + defaultSidecarLockShouldReclaim, |
| 9 | + isTransientLockFileDenial, |
| 10 | + maxTransientLockDenials, |
| 11 | +} from "./sidecar-lock-policy.js"; |
| 12 | +import { |
| 13 | + readSidecarLockSnapshot, |
| 14 | + relativeSidecarLockPath, |
| 15 | + releaseSidecarReclaimGuard, |
| 16 | + removeSidecarLockIfUnchanged, |
| 17 | + removeStaleSidecarLockIfAllowed, |
| 18 | + serializeSidecarLockPayload, |
| 19 | + sidecarLockSnapshotStillPresent, |
| 20 | + sidecarReclaimGuardExists, |
| 21 | + tryAcquireSidecarReclaimGuard, |
| 22 | + type SidecarLockSnapshot, |
| 23 | +} from "./sidecar-lock-reclaim.js"; |
| 24 | +import type { SidecarLockAcquireOptions, SidecarLockHandle } from "./sidecar-lock-types.js"; |
| 25 | + |
| 26 | +type SidecarFileHandle = Pick<NativeFileHandle, "close" | "stat" | "writeFile">; |
| 27 | + |
| 28 | +export type HeldSidecarLock = { |
| 29 | + refCount: number; |
| 30 | + reentrantOwner?: string; |
| 31 | + handle: SidecarFileHandle; |
| 32 | + lockPath: string; |
| 33 | + snapshot: SidecarLockSnapshot; |
| 34 | + acquiredAt: number; |
| 35 | + metadata: Record<string, unknown>; |
| 36 | + releasePromise?: Promise<void>; |
| 37 | + lockRoot?: Root; |
| 38 | + parsePayload?: (raw: string) => unknown; |
| 39 | + compromiseTimer?: NodeJS.Timeout; |
| 40 | +}; |
| 41 | + |
| 42 | +type SidecarLockAcquisitionContext = { |
| 43 | + held: Map<string, HeldSidecarLock>; |
| 44 | + reclaimGuards: Set<string>; |
| 45 | + ensureExitCleanupRegistered(): void; |
| 46 | + handleForHeldLock(normalizedTargetPath: string, held: HeldSidecarLock): SidecarLockHandle; |
| 47 | + releaseHeldLock( |
| 48 | + normalizedTargetPath: string, |
| 49 | + held: HeldSidecarLock, |
| 50 | + options?: { force?: boolean }, |
| 51 | + ): Promise<boolean>; |
| 52 | +}; |
| 53 | + |
| 54 | +async function resolveNormalizedTargetPath(targetPath: string): Promise<string> { |
| 55 | + const resolved = path.resolve(targetPath); |
| 56 | + const dir = path.dirname(resolved); |
| 57 | + await fs.mkdir(dir, { recursive: true }); |
| 58 | + try { |
| 59 | + return path.join(await fs.realpath(dir), path.basename(resolved)); |
| 60 | + } catch { |
| 61 | + return resolved; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export async function acquireSidecarLock<TPayload extends Record<string, unknown>>( |
| 66 | + options: SidecarLockAcquireOptions<TPayload>, |
| 67 | + context: SidecarLockAcquisitionContext, |
| 68 | +): Promise<SidecarLockHandle> { |
| 69 | + context.ensureExitCleanupRegistered(); |
| 70 | + const normalizedTargetPath = await resolveNormalizedTargetPath(options.targetPath); |
| 71 | + const lockPath = options.lockPath ?? `${normalizedTargetPath}.lock`; |
| 72 | + const held = context.held.get(normalizedTargetPath); |
| 73 | + if ( |
| 74 | + held && |
| 75 | + options.reentrantOwner !== undefined && |
| 76 | + held.reentrantOwner !== undefined && |
| 77 | + options.reentrantOwner === held.reentrantOwner |
| 78 | + ) { |
| 79 | + held.refCount += 1; |
| 80 | + return context.handleForHeldLock(normalizedTargetPath, held); |
| 81 | + } |
| 82 | + |
| 83 | + const startedAt = Date.now(); |
| 84 | + const retry = options.retry ?? {}; |
| 85 | + const maxRetries = options.timeoutMs === Number.POSITIVE_INFINITY ? undefined : retry.retries; |
| 86 | + const reclaimGuardPath = `${lockPath}.reclaim`; |
| 87 | + let ownsReclaimGuard = false; |
| 88 | + let attempt = 0; |
| 89 | + // Bounded so a genuine denial still surfaces as EPERM, not a lock timeout. |
| 90 | + let transientDenials = 0; |
| 91 | + const withinDenialBudget = (): boolean => ++transientDenials <= maxTransientLockDenials; |
| 92 | + const waitForRetry = async (): Promise<void> => { |
| 93 | + const elapsed = Date.now() - startedAt; |
| 94 | + if ( |
| 95 | + (options.timeoutMs !== undefined && |
| 96 | + options.timeoutMs !== Number.POSITIVE_INFINITY && |
| 97 | + elapsed >= options.timeoutMs) || |
| 98 | + (maxRetries !== undefined && attempt >= maxRetries) |
| 99 | + ) { |
| 100 | + throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), { |
| 101 | + code: "file_lock_timeout", |
| 102 | + lockPath, |
| 103 | + normalizedTargetPath, |
| 104 | + }); |
| 105 | + } |
| 106 | + const remaining = |
| 107 | + options.timeoutMs === undefined || options.timeoutMs === Number.POSITIVE_INFINITY |
| 108 | + ? Number.POSITIVE_INFINITY |
| 109 | + : Math.max(0, options.timeoutMs - elapsed); |
| 110 | + const delay = Math.min(computeSidecarLockDelayMs(retry, attempt), remaining); |
| 111 | + attempt += 1; |
| 112 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 113 | + }; |
| 114 | + // Waiting can fail on the caller's own retry or deadline limits. Classifying |
| 115 | + // a denial as contention must not cost them the original diagnosis, so hand |
| 116 | + // the denial back when no further attempt can be scheduled. |
| 117 | + const retryOrRethrowDenial = async (denial: unknown): Promise<void> => { |
| 118 | + try { |
| 119 | + await waitForRetry(); |
| 120 | + } catch (waitError) { |
| 121 | + if ((waitError as NodeJS.ErrnoException).code === "file_lock_timeout") throw denial; |
| 122 | + throw waitError; |
| 123 | + } |
| 124 | + }; |
| 125 | + |
| 126 | + try { |
| 127 | + while (true) { |
| 128 | + if (!ownsReclaimGuard && (await sidecarReclaimGuardExists(reclaimGuardPath))) { |
| 129 | + await waitForRetry(); |
| 130 | + continue; |
| 131 | + } |
| 132 | + let handle: SidecarFileHandle | null = null; |
| 133 | + let lockFileCreateDenied = false; |
| 134 | + try { |
| 135 | + const payload = await options.payload(); |
| 136 | + const { raw, ownershipToken } = serializeSidecarLockPayload(payload); |
| 137 | + if (options.lockRoot) { |
| 138 | + const relativeLockPath = relativeSidecarLockPath(options.lockRoot, lockPath); |
| 139 | + try { |
| 140 | + await options.lockRoot.create(relativeLockPath, raw, { mkdir: true, mode: 0o600 }); |
| 141 | + } catch (error) { |
| 142 | + if (error instanceof FsSafeError && error.code === "already-exists") { |
| 143 | + throw Object.assign(new Error("sidecar lock exists"), { code: "EEXIST" }); |
| 144 | + } |
| 145 | + throw error; |
| 146 | + } |
| 147 | + handle = (await options.lockRoot.open(relativeLockPath)).handle; |
| 148 | + } else { |
| 149 | + try { |
| 150 | + handle = |
| 151 | + (await createNativeExclusiveFile(lockPath, 0o600)) ?? |
| 152 | + (await fs.open(lockPath, "wx")); |
| 153 | + } catch (createError) { |
| 154 | + lockFileCreateDenied = isTransientLockFileDenial(createError, lockPath); |
| 155 | + throw createError; |
| 156 | + } |
| 157 | + await handle.writeFile(raw, "utf8"); |
| 158 | + } |
| 159 | + const snapshot = { raw, payload, stat: await handle.stat(), ownershipToken }; |
| 160 | + const createdHeld: HeldSidecarLock = { |
| 161 | + refCount: 1, |
| 162 | + reentrantOwner: options.reentrantOwner, |
| 163 | + handle, |
| 164 | + lockPath, |
| 165 | + snapshot, |
| 166 | + acquiredAt: Date.now(), |
| 167 | + metadata: options.metadata ?? {}, |
| 168 | + lockRoot: options.lockRoot, |
| 169 | + parsePayload: options.parsePayload, |
| 170 | + }; |
| 171 | + context.held.set(normalizedTargetPath, createdHeld); |
| 172 | + if (ownsReclaimGuard) { |
| 173 | + try { |
| 174 | + await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath); |
| 175 | + ownsReclaimGuard = false; |
| 176 | + } catch (err) { |
| 177 | + await context.releaseHeldLock(normalizedTargetPath, createdHeld, { force: true }); |
| 178 | + throw err; |
| 179 | + } |
| 180 | + } |
| 181 | + const returnedHandle = context.handleForHeldLock(normalizedTargetPath, createdHeld); |
| 182 | + const interval = options.compromiseCheckIntervalMs; |
| 183 | + if (options.onCompromised && interval !== undefined && interval > 0) { |
| 184 | + createdHeld.compromiseTimer = setInterval(() => { |
| 185 | + void returnedHandle.verifyStillHeld().then((stillHeld) => { |
| 186 | + if (!stillHeld && createdHeld.compromiseTimer) { |
| 187 | + clearInterval(createdHeld.compromiseTimer); |
| 188 | + createdHeld.compromiseTimer = undefined; |
| 189 | + options.onCompromised?.({ lockPath, normalizedTargetPath }); |
| 190 | + } |
| 191 | + }); |
| 192 | + }, interval); |
| 193 | + createdHeld.compromiseTimer.unref(); |
| 194 | + } |
| 195 | + return returnedHandle; |
| 196 | + } catch (err) { |
| 197 | + if (handle) { |
| 198 | + const failedSnapshot: SidecarLockSnapshot = { payload: null }; |
| 199 | + try { |
| 200 | + failedSnapshot.stat = await handle.stat(); |
| 201 | + } catch { |
| 202 | + // Best-effort cleanup of a failed exclusive create. |
| 203 | + } |
| 204 | + const current = context.held.get(normalizedTargetPath); |
| 205 | + if (current?.handle === handle) { |
| 206 | + context.held.delete(normalizedTargetPath); |
| 207 | + } |
| 208 | + // If payload serialization/write fails, the file may be empty or |
| 209 | + // partial JSON, so remove while our exclusive handle is still open. |
| 210 | + if (!options.lockRoot) { |
| 211 | + await fs.rm(lockPath, { force: true }).catch(() => undefined); |
| 212 | + } |
| 213 | + await handle.close().catch(() => undefined); |
| 214 | + // Windows can refuse removing an open file; retry after close but |
| 215 | + // only if the path still points at the file identity we created. |
| 216 | + await removeSidecarLockIfUnchanged(lockPath, failedSnapshot, { |
| 217 | + lockRoot: options.lockRoot, |
| 218 | + parsePayload: options.parsePayload, |
| 219 | + }); |
| 220 | + } |
| 221 | + if (lockFileCreateDenied && withinDenialBudget()) { |
| 222 | + await retryOrRethrowDenial(err); |
| 223 | + continue; |
| 224 | + } |
| 225 | + if ((err as { code?: unknown }).code !== "EEXIST") { |
| 226 | + throw err; |
| 227 | + } |
| 228 | + if (ownsReclaimGuard) { |
| 229 | + await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath); |
| 230 | + ownsReclaimGuard = false; |
| 231 | + continue; |
| 232 | + } |
| 233 | + const nowMs = Date.now(); |
| 234 | + let snapshot: SidecarLockSnapshot | null; |
| 235 | + try { |
| 236 | + snapshot = await readSidecarLockSnapshot(lockPath, { |
| 237 | + lockRoot: options.lockRoot, |
| 238 | + parsePayload: options.parsePayload, |
| 239 | + }); |
| 240 | + } catch (readErr) { |
| 241 | + if (!isTransientLockFileDenial(readErr, lockPath) || !withinDenialBudget()) throw readErr; |
| 242 | + await retryOrRethrowDenial(readErr); |
| 243 | + continue; |
| 244 | + } |
| 245 | + if (!snapshot) { |
| 246 | + continue; |
| 247 | + } |
| 248 | + if (context.held.has(normalizedTargetPath)) { |
| 249 | + await waitForRetry(); |
| 250 | + continue; |
| 251 | + } |
| 252 | + const shouldReclaim = options.shouldReclaim ?? defaultSidecarLockShouldReclaim; |
| 253 | + if ( |
| 254 | + await shouldReclaim({ |
| 255 | + lockPath, |
| 256 | + normalizedTargetPath, |
| 257 | + payload: snapshot?.payload ?? null, |
| 258 | + staleMs: options.staleMs, |
| 259 | + nowMs, |
| 260 | + heldByThisProcess: context.held.has(normalizedTargetPath), |
| 261 | + }) |
| 262 | + ) { |
| 263 | + if ( |
| 264 | + !(await sidecarLockSnapshotStillPresent(lockPath, snapshot, { |
| 265 | + lockRoot: options.lockRoot, |
| 266 | + parsePayload: options.parsePayload, |
| 267 | + })) |
| 268 | + ) { |
| 269 | + continue; |
| 270 | + } |
| 271 | + const staleRecovery = options.staleRecovery ?? "fail-closed"; |
| 272 | + if (staleRecovery === "remove-if-unchanged") { |
| 273 | + if (!(await tryAcquireSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath))) { |
| 274 | + await waitForRetry(); |
| 275 | + continue; |
| 276 | + } |
| 277 | + ownsReclaimGuard = true; |
| 278 | + const removal = await removeStaleSidecarLockIfAllowed({ |
| 279 | + lockPath, |
| 280 | + normalizedTargetPath, |
| 281 | + snapshot, |
| 282 | + shouldRemoveStaleLock: options.shouldRemoveStaleLock, |
| 283 | + lockRoot: options.lockRoot, |
| 284 | + parsePayload: options.parsePayload, |
| 285 | + }); |
| 286 | + if (removal === "removed" || removal === "changed") { |
| 287 | + continue; |
| 288 | + } |
| 289 | + await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath); |
| 290 | + ownsReclaimGuard = false; |
| 291 | + } |
| 292 | + throw Object.assign(new Error(`file lock stale for ${normalizedTargetPath}`), { |
| 293 | + code: "file_lock_stale", |
| 294 | + lockPath, |
| 295 | + normalizedTargetPath, |
| 296 | + }); |
| 297 | + } |
| 298 | + await waitForRetry(); |
| 299 | + } |
| 300 | + } |
| 301 | + } finally { |
| 302 | + if (ownsReclaimGuard) { |
| 303 | + await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath).catch( |
| 304 | + () => undefined, |
| 305 | + ); |
| 306 | + } |
| 307 | + } |
| 308 | +} |
0 commit comments