UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

170 lines (169 loc) • 6.36 kB
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs"; import { n as isLockOwnerDefinitelyStale, r as shouldRemoveDeadOwnerOrExpiredLock, t as inspectStaleLockOwner } from "./stale-lock-file-9Xx-iI7Y.mjs"; import fs from "node:fs/promises"; import { acquireFileLock, drainFileLockManagerForTest, resetFileLockManagerForTest } from "@openclaw/fs-safe/file-lock"; //#region src/plugin-sdk/file-lock.ts /** Stable error code used when lock acquisition retries are exhausted. */ const FILE_LOCK_TIMEOUT_ERROR_CODE = "file_lock_timeout"; /** Stable error code used when stale lock recovery cannot proceed safely. */ const FILE_LOCK_STALE_ERROR_CODE = "file_lock_stale"; const FILE_LOCK_MANAGER_KEY = "openclaw.plugin-sdk.file-lock"; const STALE_FILE_LOCK_RECLAIM_MANAGER_KEY = "openclaw.plugin-sdk.stale-file-lock-reclaim"; let currentProcessStartTime; function getCurrentProcessStartTime() { if (currentProcessStartTime === void 0) currentProcessStartTime = getFileLockProcessStartTime(process.pid); return currentProcessStartTime; } function createCurrentProcessLockPayload() { const e = { pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() }; const t = getCurrentProcessStartTime(); if (t !== null) e.starttime = t; return e; } function sameStatValue(e, t) { return typeof e === typeof t ? e === t : BigInt(e) === BigInt(t); } function sameFileIdentity(e, t) { if (!sameStatValue(e.ino, t.ino)) return false; if (sameStatValue(e.dev, t.dev)) return true; return process.platform === "win32" && (e.dev === 0 || e.dev === 0n || t.dev === 0 || t.dev === 0n); } async function isSameRegularFile(e, t) { try { const n = await fs.lstat(e, { bigint: true }); return n.isFile() && sameFileIdentity(n, t); } catch { return false; } } function normalizeLockError(e, t = null) { if (e.code === "file_lock_timeout") throw Object.assign(new Error(e.message), { code: FILE_LOCK_TIMEOUT_ERROR_CODE, lockPath: e.lockPath ?? "" }); if (e.code === "file_lock_stale") { const n = t ? ` [${t.reason} pid=${t.pid} recorded-start=${t.recordedStarttime ?? "unknown"} observed-start=${t.observedStarttime ?? "unknown"}]` : ""; throw Object.assign(/* @__PURE__ */ new Error(`${e.message}${n}`), { code: FILE_LOCK_STALE_ERROR_CODE, lockPath: e.lockPath ?? "" }); } throw e; } /** Reset process-local file-lock state for tests that isolate lock managers. */ function resetFileLockStateForTest() { resetFileLockManagerForTest(FILE_LOCK_MANAGER_KEY, FILE_LOCK_MANAGER_KEY); } /** Wait for process-local file-lock state to drain before test teardown. */ async function drainFileLockStateForTest() { await drainFileLockManagerForTest(FILE_LOCK_MANAGER_KEY, FILE_LOCK_MANAGER_KEY); } /** Acquire an owner-scoped process-local file lock backed by a `.lock` sidecar file. */ async function acquireFileLock$1(e, t) { t.assertResourceUnborrowed?.(e); const n = t.staleRecovery ?? "remove-if-unchanged"; let r = null; try { const i = await acquireFileLock(e, { managerKey: FILE_LOCK_MANAGER_KEY, staleMs: t.stale, retry: t.retries, staleRecovery: n === "remove-if-definitely-stale" ? "remove-if-unchanged" : n, reentrantOwner: t.reentrantOwner, payload: () => { t.assertResourceUnborrowed?.(e); return createCurrentProcessLockPayload(); }, shouldReclaim: (e) => { if (n === "fail-closed") { r = inspectStaleLockOwner({ payload: asNullableRecord(e.payload) }); return r !== null; } if (n === "remove-if-definitely-stale") return isLockOwnerDefinitelyStale({ payload: asNullableRecord(e.payload) }); return shouldRemoveDeadOwnerOrExpiredLock({ payload: asNullableRecord(e.payload), staleMs: e.staleMs, nowMs: e.nowMs }); }, ...n === "remove-if-unchanged" || n === "remove-if-definitely-stale" ? { shouldRemoveStaleLock: (e) => { t.assertResourceUnborrowed?.(e.normalizedTargetPath); if (n === "remove-if-definitely-stale") return isLockOwnerDefinitelyStale({ payload: asNullableRecord(e.payload) }); return shouldRemoveDeadOwnerOrExpiredLock({ payload: asNullableRecord(e.payload), staleMs: t.stale }); } } : {} }); const a = i.lockPath.slice(0, -5); try { t.assertResourceUnborrowed?.(a); } catch (e) { await i.release(); throw e; } return { lockPath: i.lockPath, release: async () => { t.assertResourceUnborrowed?.(a); await i.release(); } }; } catch (e) { return normalizeLockError(e, r); } } /** Remove one definitely stale, unchanged regular lock sidecar; retain every ambiguous owner. */ async function reclaimDefinitelyStaleFileLock(e) { let t; try { t = await fs.lstat(e, { bigint: true }); } catch (e) { if (e.code === "ENOENT") return "missing"; throw e; } if (!t.isFile()) return "retained"; const ownerIsDefinitelyStale = async (n) => await isSameRegularFile(e, t) && isLockOwnerDefinitelyStale({ payload: asNullableRecord(n) }); const n = e.endsWith(".lock") ? e.slice(0, -5) : e; try { await (await acquireFileLock(n, { managerKey: STALE_FILE_LOCK_RECLAIM_MANAGER_KEY, lockPath: e, staleMs: 0, retry: { retries: 0 }, staleRecovery: "remove-if-unchanged", payload: createCurrentProcessLockPayload, shouldReclaim: ({ payload: e }) => ownerIsDefinitelyStale(e), shouldRemoveStaleLock: ({ payload: e }) => ownerIsDefinitelyStale(e) })).release(); return "removed"; } catch (e) { const t = e.code; if (t === "file_lock_timeout" || t === "file_lock_stale") return "retained"; throw e; } } /** Run an async callback while holding a file lock, always releasing the lock afterward. */ async function withFileLock(e, t, n) { const r = await acquireFileLock$1(e, t); let i; try { i = { value: await n() }; } catch (e) { i = { error: e }; } try { await r.release(); } catch (e) { if ("error" in i) throw new AggregateError([i.error, e], "File operation failed and lock release is unresolved", { cause: e }); throw e; } if ("error" in i) throw i.error; return i.value; } //#endregion export { reclaimDefinitelyStaleFileLock as a, drainFileLockStateForTest as i, FILE_LOCK_TIMEOUT_ERROR_CODE as n, resetFileLockStateForTest as o, acquireFileLock$1 as r, withFileLock as s, FILE_LOCK_STALE_ERROR_CODE as t };