@tpsdev-ai/flair 0.62.0 → 0.63.0
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.md +6 -6
- package/SECURITY.md +18 -10
- package/config.yaml +11 -11
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +66 -122
- package/dist/commands/agent.js +27 -65
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +37 -33
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/deploy.js +37 -7
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/export.js +3 -4
- package/dist/commands/federation.js +653 -68
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/idp.js +14 -19
- package/dist/commands/import.js +131 -19
- package/dist/commands/init.js +7 -7
- package/dist/commands/integrity.js +5 -6
- package/dist/commands/mcp.js +11 -17
- package/dist/commands/memory.js +33 -15
- package/dist/commands/orgevent.js +5 -10
- package/dist/commands/principal.js +13 -25
- package/dist/commands/quality.js +3 -0
- package/dist/commands/rem.js +484 -65
- package/dist/commands/restore.js +352 -44
- package/dist/commands/service.js +84 -2
- package/dist/commands/soul.js +0 -6
- package/dist/commands/status.js +51 -33
- package/dist/commands/test.js +4 -1
- package/dist/commands/upgrade.js +53 -22
- package/dist/commands/workspace.js +7 -8
- package/dist/deploy.js +59 -3
- package/dist/doctor-client.js +7 -2
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +269 -177
- package/dist/install/clients.js +171 -35
- package/dist/lib/agent-id-rule.js +44 -2
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1028 -52
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/daemon-liveness.js +2 -1
- package/dist/lib/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +14 -3
- package/dist/lib/mcp-enable.js +14 -15
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +1 -1
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed.js +91 -8
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/mcp-client-assertion.js +2 -10
- package/dist/memory-id-checkpoint.js +28 -7
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +302 -26
- package/dist/rem/runner.js +220 -58
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +155 -45
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +56 -22
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +232 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -84
- package/dist/resources/Credential.js +6 -8
- package/dist/resources/Federation.js +219 -57
- package/dist/resources/FederationRetry.js +4 -4
- package/dist/resources/InstructionVersion.js +1 -1
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +1303 -270
- package/dist/resources/MemoryArchive.js +149 -64
- package/dist/resources/MemoryBootstrap.js +12 -22
- package/dist/resources/MemoryCandidate.js +16 -2
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryFeed.js +360 -147
- package/dist/resources/MemoryMaintenance.js +290 -72
- package/dist/resources/MemoryPurge.js +138 -22
- package/dist/resources/MemoryReflect.js +68 -14
- package/dist/resources/MemoryReindex.js +91 -13
- package/dist/resources/Message.js +11 -2
- package/dist/resources/OAuth.js +156 -39
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +292 -29
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +31 -11
- package/dist/resources/PromoteMemoryCandidate.js +8 -2
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Soul.js +2 -0
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/XAA.js +36 -10
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +98 -68
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +166 -42
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/federation-classify.js +89 -0
- package/dist/resources/federation-retry-lib.js +6 -81
- package/dist/resources/health.js +43 -4
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instruction-version-record.js +251 -7
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/mcp-handler.js +106 -12
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +430 -53
- package/dist/resources/mcp-tools.js +60 -22
- package/dist/resources/memory-declared-attributes.js +1 -0
- package/dist/resources/memory-embed-hash.js +56 -0
- package/dist/resources/memory-host-source.js +5 -2
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-write-lock.js +202 -23
- package/dist/resources/memory-write-response.js +1 -1
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +16 -3
- package/dist/resources/migrations/dir-safety.js +60 -2
- package/dist/resources/migrations/embedding-stamp.js +315 -49
- package/dist/resources/migrations/graph-heal.js +9 -2
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +867 -80
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +78 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +111 -70
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +12 -5
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/owner-field-guard.js +1 -1
- package/dist/resources/owner-scoped-write-policy.js +65 -21
- package/dist/resources/owner-scoped-writes.js +37 -6
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +124 -33
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/request-target.js +28 -1
- package/dist/resources/request-transaction.js +11 -1
- package/dist/resources/seed-reservation.js +1 -2
- package/dist/resources/semantic-retrieval-core.js +7 -6
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +4 -3
- package/dist/resources/skill-version-write.js +384 -27
- package/dist/resources/skill-write-fault.js +6 -3
- package/dist/resources/skill-write-policy.js +2 -1
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +1 -1
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/txn-pause-point.js +122 -5
- package/dist/resources/usage-recording.js +54 -46
- package/dist/resources/write-back.js +176 -11
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/lib/agent-id-rule.js +44 -2
- package/dist/src/lib/atomic-write.js +1 -1
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +18 -9
- package/docs/api-reference.md +126 -28
- package/docs/auth.md +40 -18
- package/docs/claude-code.md +3 -3
- package/docs/deploying-on-fabric.md +108 -0
- package/docs/deployment.md +17 -0
- package/docs/embedding-in-a-harper-app.md +16 -14
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +29 -2
- package/docs/integrations.md +11 -11
- package/docs/mcp-clients.md +7 -5
- package/docs/notes/mcp-agent-auth-consumer.md +4 -9
- package/docs/notes/mcp-oauth-model2.md +6 -6
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +3 -3
- package/docs/releasing.md +13 -13
- package/docs/rem.md +24 -3
- package/docs/secrets-and-keys.md +2 -2
- package/docs/standalone-local.md +29 -2
- package/docs/supply-chain-policy.md +28 -20
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +14 -0
- package/package.json +18 -11
- package/schemas/agent.graphql +3 -3
- package/schemas/federation.graphql +10 -7
- package/schemas/memory.graphql +7 -2
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
|
@@ -1,40 +1,191 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* lock.ts — single-flight guard
|
|
3
|
-
* "Single-flight v1 = in-process mutex + stale-tolerant file lock (flock on
|
|
4
|
-
* well-known path; dead-holder → break and proceed). Fabric-wide ordering =
|
|
5
|
-
* follow-on with its own review, NOT this slice."
|
|
2
|
+
* lock.ts — single-flight guard for migration cycles.
|
|
6
3
|
*
|
|
7
4
|
* Two layers:
|
|
8
|
-
* 1. An in-process
|
|
9
|
-
*
|
|
10
|
-
* duplicate boot-trigger firing twice).
|
|
5
|
+
* 1. An in-process flag — cheapest guard against two concurrent async
|
|
6
|
+
* callers inside the SAME process.
|
|
11
7
|
* 2. A file lock at a well-known path under the data dir. Node has no
|
|
12
|
-
* portable flock() binding, so
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
8
|
+
* portable flock() binding, so a contender publishes a complete holder
|
|
9
|
+
* record to a unique temporary file in the same directory, flushes it,
|
|
10
|
+
* and hard-links it to the lock path (`link(2)`, which fails with EEXIST
|
|
11
|
+
* when a lock exists). A reader sees no lock file, a complete record, or
|
|
12
|
+
* a record this module refuses as unreadable; it never treats a partial
|
|
13
|
+
* or unknown record as stale.
|
|
14
|
+
*
|
|
15
|
+
* Every ownership transition on the migration lock is serialized by a sibling directory mutex
|
|
16
|
+
* (`<lock>.guard`). A process publishes that mutex by renaming an
|
|
17
|
+
* already-populated directory over the guard path: replacing an empty
|
|
18
|
+
* directory succeeds; replacing a non-empty one fails, and either EEXIST or
|
|
19
|
+
* ENOTEMPTY from that rename is treated as contention. The
|
|
20
|
+
* mutex is released by unlinking only the owner entry of the generation it
|
|
21
|
+
* published, leaving the directory empty when the unlink succeeds. A dead
|
|
22
|
+
* owner is recovered by
|
|
23
|
+
* unlinking that same generation-specific entry; the recovering process must
|
|
24
|
+
* then win publication of its own directory, so recovery never grants
|
|
25
|
+
* ownership by itself.
|
|
26
|
+
*
|
|
27
|
+
* The lock file holds `{pid, hostname, startedAt}`. Another live local pid
|
|
28
|
+
* is held regardless of age. After abandoned-record cleanup, this process's
|
|
29
|
+
* own pid is judged by heartbeat age unless this module holds it, because the pid probe cannot
|
|
30
|
+
* distinguish an earlier process with that pid from this one. A holder on
|
|
31
|
+
* another host is also judged by age (`staleMs`). Same host compares the
|
|
32
|
+
* hostname string: the discriminator is a name, not an identity, so two
|
|
33
|
+
* hosts sharing a hostname and a data dir can misclassify a remote holder as
|
|
34
|
+
* local. A holder record that cannot be read or parsed is not treated as stale:
|
|
35
|
+
* acquisition refuses with a named error.
|
|
21
36
|
*
|
|
22
37
|
* This is a SINGLE-HOST guard, not a Fabric-wide one — multiple Flair
|
|
23
|
-
* instances in a Fabric cluster each have their OWN data dir today
|
|
24
|
-
*
|
|
25
|
-
*
|
|
38
|
+
* instances in a Fabric cluster each have their OWN data dir today. Fabric-
|
|
39
|
+
* wide ordering (one lock across a cluster sharing storage) is deferred.
|
|
40
|
+
*
|
|
41
|
+
* Known windows: a holder recorded on another host is still judged by age,
|
|
42
|
+
* for the mutex as well as the migration record, so a remote holder that
|
|
43
|
+
* resumes after takeover is not fenced. A same-pid holder that stops
|
|
44
|
+
* heartbeating for longer than staleMs while alive is treated as stale unless
|
|
45
|
+
* this module holds it. A process killed while preparing a
|
|
46
|
+
* record leaves an unpublished staging directory or temporary file; one
|
|
47
|
+
* killed after publication and before that record is cleaned up leaves a
|
|
48
|
+
* complete owner record that another process may recover.
|
|
26
49
|
*/
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
50
|
+
import { closeSync, constants as fsConstants, fstatSync, fsyncSync, futimesSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
51
|
+
import { randomBytes } from "node:crypto";
|
|
52
|
+
import { basename, dirname, join } from "node:path";
|
|
29
53
|
import { hostname as osHostname } from "node:os";
|
|
54
|
+
import { ensureSecureDir } from "./dir-safety.js";
|
|
55
|
+
import { txnPausePointSync } from "../txn-pause-point.js";
|
|
30
56
|
export const DEFAULT_STALE_MS = 5 * 60 * 1000; // 5 minutes with no heartbeat touch = stale
|
|
57
|
+
/** Bounds every acquisition loop; each failed attempt settles briefly, and the loop can end while contention continues. */
|
|
58
|
+
const GUARD_ACQUISITION_ATTEMPTS = 24;
|
|
59
|
+
const LOCK_ACQUISITION_ROUNDS = 8;
|
|
60
|
+
const CONTENTION_SETTLE_MS = 2;
|
|
61
|
+
const liveHandles = new WeakSet();
|
|
62
|
+
const revokedHandles = new WeakSet();
|
|
63
|
+
/** Module-private identity: never read from a property a caller can shadow. */
|
|
64
|
+
const identities = new WeakMap();
|
|
65
|
+
const HANDLE_KEY = Symbol("migration-lock-handle");
|
|
66
|
+
/** Holder identities this process currently has a live handle for, per lock path. */
|
|
67
|
+
const liveHolderKeys = new Set();
|
|
68
|
+
const ownedGuardGenerations = new Map();
|
|
69
|
+
/**
|
|
70
|
+
* A later acquisition may finish abandoned-record cleanup after taking the mutex, finding
|
|
71
|
+
* this exact identity still at the lock path, and finding no live handle for it
|
|
72
|
+
* (flair#2866).
|
|
73
|
+
*/
|
|
74
|
+
const abandonedOwnRecords = new Map();
|
|
75
|
+
const abandonedGuardGenerations = new Map();
|
|
76
|
+
function holderKey(lockPath, holder) {
|
|
77
|
+
return `${lockPath}\u0000${holder.pid}\u0000${holder.hostname}\u0000${holder.startedAt}`;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* An acquired migration lock. Only {@link acquireMigrationLock} constructs a
|
|
81
|
+
* live one; {@link MigrationLockHandle.release} revokes it. The lock path and
|
|
82
|
+
* holder record live in module-private storage keyed by this object. The
|
|
83
|
+
* `lockPath` and `holder` getters return a snapshot for diagnostics; neither
|
|
84
|
+
* `state.ts` nor `release()` consults them (flair#2866).
|
|
85
|
+
*/
|
|
86
|
+
export class MigrationLockHandle {
|
|
87
|
+
acquired = true;
|
|
88
|
+
constructor(key, identity) {
|
|
89
|
+
if (key !== HANDLE_KEY) {
|
|
90
|
+
throw new TypeError("MigrationLockHandle is created only by acquireMigrationLock");
|
|
91
|
+
}
|
|
92
|
+
identities.set(this, identity);
|
|
93
|
+
liveHandles.add(this);
|
|
94
|
+
}
|
|
95
|
+
get lockPath() {
|
|
96
|
+
return identityFor(this).lockPath;
|
|
97
|
+
}
|
|
98
|
+
get holder() {
|
|
99
|
+
return identityFor(this).holder;
|
|
100
|
+
}
|
|
101
|
+
release() {
|
|
102
|
+
const identity = identities.get(this);
|
|
103
|
+
if (!liveHandles.has(this) || identity === undefined)
|
|
104
|
+
return;
|
|
105
|
+
liveHandles.delete(this);
|
|
106
|
+
revokedHandles.add(this);
|
|
107
|
+
liveHolderKeys.delete(holderKey(identity.lockPath, identity.holder));
|
|
108
|
+
identity.release();
|
|
109
|
+
}
|
|
110
|
+
touch() {
|
|
111
|
+
if (!liveHandles.has(this))
|
|
112
|
+
return;
|
|
113
|
+
identities.get(this)?.touch();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function identityFor(handle) {
|
|
117
|
+
const identity = identities.get(handle);
|
|
118
|
+
if (identity === undefined)
|
|
119
|
+
throw new TypeError("not a migration lock handle");
|
|
120
|
+
return identity;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The lock path and holder a handle was issued for, or null for any other
|
|
124
|
+
* value. This is the only way `state.ts` reads a handle's identity.
|
|
125
|
+
*/
|
|
126
|
+
export function migrationLockIdentity(value) {
|
|
127
|
+
if (typeof value !== "object" || value === null)
|
|
128
|
+
return null;
|
|
129
|
+
const identity = identities.get(value);
|
|
130
|
+
if (identity === undefined)
|
|
131
|
+
return null;
|
|
132
|
+
return Object.freeze({ lockPath: identity.lockPath, holder: identity.holder });
|
|
133
|
+
}
|
|
134
|
+
/** Classify a value without exposing whether a forged object imitates a handle. */
|
|
135
|
+
export function migrationLockHandleStatus(value) {
|
|
136
|
+
if (typeof value === "object" && value !== null) {
|
|
137
|
+
if (liveHandles.has(value))
|
|
138
|
+
return "live";
|
|
139
|
+
if (revokedHandles.has(value))
|
|
140
|
+
return "released";
|
|
141
|
+
}
|
|
142
|
+
return "unknown";
|
|
143
|
+
}
|
|
144
|
+
export function isLiveMigrationLockHandle(value) {
|
|
145
|
+
return migrationLockHandleStatus(value) === "live";
|
|
146
|
+
}
|
|
147
|
+
/** The named refusal when a pid probe fails for a reason other than ESRCH/EPERM. */
|
|
148
|
+
export class MigrationLockProbeError extends Error {
|
|
149
|
+
constructor(pid, code) {
|
|
150
|
+
super(`refusing to treat holder pid ${pid} as dead: the liveness probe failed with ` +
|
|
151
|
+
`${code ?? "an unknown error"}. Inspect pid ${pid} on this host (for example, ` +
|
|
152
|
+
`ps -p ${pid}); only when it is gone, and no other writer is running, remove the lock file by hand`);
|
|
153
|
+
this.name = "MigrationLockProbeError";
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** The named refusal when a lock file's holder record cannot be trusted. */
|
|
157
|
+
export class MigrationLockUnreadableError extends Error {
|
|
158
|
+
constructor(lockPath, detail) {
|
|
159
|
+
super(`refusing to break ${lockPath}: ${detail}. Inspect ${lockPath}; if no process on ` +
|
|
160
|
+
`this host still holds it, stop every writer and remove that file by hand, then retry`);
|
|
161
|
+
this.name = "MigrationLockUnreadableError";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** The named refusal when the directory mutex cannot be trusted. */
|
|
165
|
+
export class MigrationLockMutexError extends Error {
|
|
166
|
+
constructor(guardPath, detail) {
|
|
167
|
+
super(`refusing to change the migration lock at ${guardPath}: ${detail}. Inspect ${guardPath}; ` +
|
|
168
|
+
`if no process on this host still holds the mutex, stop every writer and remove it by hand, then retry`);
|
|
169
|
+
this.name = "MigrationLockMutexError";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* True when the pid is alive. ESRCH means dead; EPERM means alive (the process
|
|
174
|
+
* exists but is not ours to signal); every other probe error refuses
|
|
175
|
+
* acquisition by name rather than guessing (flair#2866).
|
|
176
|
+
*/
|
|
31
177
|
export function defaultIsProcessAlive(pid) {
|
|
32
178
|
try {
|
|
33
179
|
process.kill(pid, 0);
|
|
34
180
|
return true;
|
|
35
181
|
}
|
|
36
|
-
catch {
|
|
37
|
-
|
|
182
|
+
catch (err) {
|
|
183
|
+
const code = err?.code;
|
|
184
|
+
if (code === "ESRCH")
|
|
185
|
+
return false;
|
|
186
|
+
if (code === "EPERM")
|
|
187
|
+
return true;
|
|
188
|
+
throw new MigrationLockProbeError(pid, code);
|
|
38
189
|
}
|
|
39
190
|
}
|
|
40
191
|
export function defaultLockDeps(lockPath) {
|
|
@@ -53,108 +204,744 @@ let inProcessHeld = false;
|
|
|
53
204
|
export function _resetInProcessLockForTests() {
|
|
54
205
|
inProcessHeld = false;
|
|
55
206
|
}
|
|
56
|
-
|
|
207
|
+
/**
|
|
208
|
+
* True only when this module issued the handle and the file it opens at the
|
|
209
|
+
* lock pathname records that handle's holder at the device and inode recorded
|
|
210
|
+
* when the lock was published. The inspection describes the file opened, not
|
|
211
|
+
* the pathname afterwards: a replacement during that descriptor read can
|
|
212
|
+
* occur before this returns. Any read or parse failure answers false: an
|
|
213
|
+
* unknown lock state never licenses a write (flair#2866).
|
|
214
|
+
*/
|
|
215
|
+
export function migrationLockStillHeld(lock) {
|
|
216
|
+
if (!liveHandles.has(lock))
|
|
217
|
+
return false;
|
|
218
|
+
const identity = identities.get(lock);
|
|
219
|
+
if (identity === undefined)
|
|
220
|
+
return false;
|
|
221
|
+
const current = inspectLock(identity.lockPath);
|
|
222
|
+
return (current.state === "held" &&
|
|
223
|
+
current.dev === identity.dev &&
|
|
224
|
+
current.ino === identity.ino &&
|
|
225
|
+
sameHolder(current.holder, identity.holder));
|
|
226
|
+
}
|
|
227
|
+
function sameHolder(a, b) {
|
|
228
|
+
return a.pid === b.pid && a.hostname === b.hostname && a.startedAt === b.startedAt;
|
|
229
|
+
}
|
|
230
|
+
function parseHolder(raw) {
|
|
231
|
+
if (typeof raw === "object" &&
|
|
232
|
+
raw !== null &&
|
|
233
|
+
Number.isInteger(raw.pid) &&
|
|
234
|
+
raw.pid > 0 &&
|
|
235
|
+
typeof raw.hostname === "string" &&
|
|
236
|
+
raw.hostname.length > 0 &&
|
|
237
|
+
typeof raw.startedAt === "string" &&
|
|
238
|
+
raw.startedAt.length > 0) {
|
|
239
|
+
return {
|
|
240
|
+
pid: raw.pid,
|
|
241
|
+
hostname: raw.hostname,
|
|
242
|
+
startedAt: raw.startedAt,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Read the lock's holder, device and inode from one open file descriptor, so
|
|
249
|
+
* the three facts describe the same file even if the name is replaced while
|
|
250
|
+
* the read runs. A missing file is absent; anything else that prevents a
|
|
251
|
+
* complete regular-file record is unreadable and never breakable.
|
|
252
|
+
*/
|
|
253
|
+
function inspectLock(lockPath) {
|
|
254
|
+
let fd;
|
|
57
255
|
try {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
256
|
+
fd = openSync(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
if (err?.code === "ENOENT")
|
|
260
|
+
return { state: "absent" };
|
|
261
|
+
return { state: "unreadable", detail: `the lock file cannot be opened (${err?.code ?? String(err)})` };
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
const st = fstatSync(fd);
|
|
265
|
+
if (!st.isFile())
|
|
266
|
+
return { state: "unreadable", detail: "it is not a regular file" };
|
|
267
|
+
const text = readFileSync(fd, "utf-8");
|
|
268
|
+
let raw;
|
|
269
|
+
try {
|
|
270
|
+
raw = JSON.parse(text);
|
|
61
271
|
}
|
|
62
|
-
|
|
272
|
+
catch {
|
|
273
|
+
return { state: "unreadable", detail: "its holder record is not valid JSON" };
|
|
274
|
+
}
|
|
275
|
+
const holder = parseHolder(raw);
|
|
276
|
+
if (holder === null) {
|
|
277
|
+
return { state: "unreadable", detail: "its holder record lacks a positive integer pid, a hostname or a startedAt" };
|
|
278
|
+
}
|
|
279
|
+
return { state: "held", holder, dev: st.dev, ino: st.ino, mtimeMs: st.mtimeMs };
|
|
63
280
|
}
|
|
64
|
-
catch {
|
|
65
|
-
return
|
|
281
|
+
catch (err) {
|
|
282
|
+
return { state: "unreadable", detail: `the lock file cannot be read (${err?.code ?? String(err)})` };
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
closeSync(fd);
|
|
66
286
|
}
|
|
67
287
|
}
|
|
68
288
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
289
|
+
* Write the complete holder record to a unique temporary file in the lock's
|
|
290
|
+
* directory, flush it, then hard-link it to the lock path. `link` is atomic
|
|
291
|
+
* and fails with EEXIST when a lock already exists, so a reader never sees a
|
|
292
|
+
* partial record. The temporary name is removed best-effort; a cleanup
|
|
293
|
+
* failure leaves an extra temporary file and does not affect a published lock.
|
|
74
294
|
*/
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
295
|
+
function publishLock(lockPath, holder) {
|
|
296
|
+
const temp = join(dirname(lockPath), `.${basename(lockPath)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
|
|
297
|
+
let fd;
|
|
298
|
+
let created = false;
|
|
299
|
+
let dev = 0;
|
|
300
|
+
let ino = 0;
|
|
301
|
+
try {
|
|
302
|
+
fd = openSync(temp, "wx", 0o600);
|
|
303
|
+
created = true;
|
|
304
|
+
writeFileSync(fd, JSON.stringify(holder));
|
|
305
|
+
fsyncSync(fd);
|
|
306
|
+
const st = fstatSync(fd);
|
|
307
|
+
dev = st.dev;
|
|
308
|
+
ino = st.ino;
|
|
309
|
+
closeSync(fd);
|
|
310
|
+
fd = undefined;
|
|
311
|
+
// Test-only pause between the complete temporary record and the link that
|
|
312
|
+
// publishes it, so a test can put a second contender into that window
|
|
313
|
+
// deterministically (flair#2866).
|
|
314
|
+
txnPausePointSync("migration-lock-publish", process.env, undefined, { lockPath, temp });
|
|
315
|
+
try {
|
|
316
|
+
linkSync(temp, lockPath);
|
|
317
|
+
}
|
|
318
|
+
catch (err) {
|
|
319
|
+
if (err?.code === "EEXIST")
|
|
320
|
+
return { published: false };
|
|
321
|
+
throw err;
|
|
322
|
+
}
|
|
323
|
+
txnPausePointSync("migration-lock-published", process.env, undefined, { lockPath });
|
|
324
|
+
return { published: true, dev, ino };
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
if (fd !== undefined) {
|
|
328
|
+
try {
|
|
329
|
+
closeSync(fd);
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
/* the original error is the one to surface */
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
if (created)
|
|
337
|
+
unlinkSync(temp);
|
|
338
|
+
}
|
|
339
|
+
catch {
|
|
340
|
+
/* best-effort cleanup: an extra temporary name does not affect the lock */
|
|
341
|
+
}
|
|
80
342
|
}
|
|
343
|
+
}
|
|
344
|
+
function prepareLockRecord(lockPath, holder) {
|
|
345
|
+
const temp = join(dirname(lockPath), `.${basename(lockPath)}.${process.pid}.${randomBytes(8).toString("hex")}.reclaim.tmp`);
|
|
346
|
+
const fd = openSync(temp, "wx", 0o600);
|
|
81
347
|
try {
|
|
82
|
-
|
|
348
|
+
writeFileSync(fd, JSON.stringify(holder));
|
|
349
|
+
fsyncSync(fd);
|
|
350
|
+
const st = fstatSync(fd);
|
|
351
|
+
return { temp, dev: st.dev, ino: st.ino };
|
|
83
352
|
}
|
|
84
353
|
catch (err) {
|
|
85
|
-
|
|
86
|
-
|
|
354
|
+
try {
|
|
355
|
+
unlinkSync(temp);
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
/* best-effort cleanup of our own unpublished record */
|
|
359
|
+
}
|
|
360
|
+
throw err;
|
|
87
361
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
362
|
+
finally {
|
|
363
|
+
closeSync(fd);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
// ─── directory mutex ────────────────────────────────────────────────────────
|
|
367
|
+
function guardPathFor(lockPath) {
|
|
368
|
+
return `${lockPath}.guard`;
|
|
369
|
+
}
|
|
370
|
+
function ownerEntryName(generation) {
|
|
371
|
+
return `owner-${generation}.json`;
|
|
372
|
+
}
|
|
373
|
+
const GENERATION_PATTERN = /^[0-9a-f]{16}$/;
|
|
374
|
+
const OWNER_ENTRY_PATTERN = /^owner-([0-9a-f]{16})\.json$/;
|
|
375
|
+
function parseGuardHolder(raw, nameGeneration) {
|
|
376
|
+
if (typeof raw === "object" &&
|
|
377
|
+
raw !== null &&
|
|
378
|
+
Number.isInteger(raw.pid) &&
|
|
379
|
+
raw.pid > 0 &&
|
|
380
|
+
typeof raw.hostname === "string" &&
|
|
381
|
+
raw.hostname.length > 0 &&
|
|
382
|
+
typeof raw.startedAt === "string" &&
|
|
383
|
+
raw.startedAt.length > 0 &&
|
|
384
|
+
typeof raw.generation === "string" &&
|
|
385
|
+
raw.generation === nameGeneration) {
|
|
386
|
+
return {
|
|
387
|
+
pid: raw.pid,
|
|
388
|
+
hostname: raw.hostname,
|
|
389
|
+
startedAt: raw.startedAt,
|
|
390
|
+
generation: raw.generation,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Inspect the mutex directory without accepting a symlink or unexpected type.
|
|
397
|
+
* It is either absent, empty, or holds exactly one owner entry whose record
|
|
398
|
+
* and filename name the same generation. Everything else refuses.
|
|
399
|
+
*/
|
|
400
|
+
function inspectGuard(guardPath) {
|
|
401
|
+
let st;
|
|
402
|
+
try {
|
|
403
|
+
st = lstatSync(guardPath);
|
|
404
|
+
}
|
|
405
|
+
catch (err) {
|
|
406
|
+
if (err?.code === "ENOENT")
|
|
407
|
+
return { state: "absent" };
|
|
408
|
+
return { state: "unreadable", detail: `the mutex cannot be inspected (${err?.code ?? String(err)})` };
|
|
409
|
+
}
|
|
410
|
+
if (!st.isDirectory())
|
|
411
|
+
return { state: "unreadable", detail: "it is not a directory" };
|
|
412
|
+
let entries;
|
|
413
|
+
try {
|
|
414
|
+
entries = readdirSync(guardPath);
|
|
415
|
+
}
|
|
416
|
+
catch (err) {
|
|
417
|
+
return { state: "unreadable", detail: `its entries cannot be listed (${err?.code ?? String(err)})` };
|
|
418
|
+
}
|
|
419
|
+
if (entries.length === 0)
|
|
420
|
+
return { state: "empty" };
|
|
421
|
+
if (entries.length !== 1) {
|
|
422
|
+
return { state: "unreadable", detail: `it contains ${entries.length} entries instead of none or one` };
|
|
423
|
+
}
|
|
424
|
+
const name = entries[0];
|
|
425
|
+
const match = OWNER_ENTRY_PATTERN.exec(name);
|
|
426
|
+
if (match === null)
|
|
427
|
+
return { state: "unreadable", detail: `it contains an unexpected entry ${name}` };
|
|
428
|
+
let fd;
|
|
429
|
+
try {
|
|
430
|
+
fd = openSync(join(guardPath, name), fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
|
431
|
+
}
|
|
432
|
+
catch (err) {
|
|
433
|
+
return { state: "unreadable", detail: `its owner entry cannot be opened (${err?.code ?? String(err)})` };
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const entryStat = fstatSync(fd);
|
|
437
|
+
if (!entryStat.isFile())
|
|
438
|
+
return { state: "unreadable", detail: "its owner entry is not a regular file" };
|
|
439
|
+
const text = readFileSync(fd, "utf-8");
|
|
440
|
+
let raw;
|
|
91
441
|
try {
|
|
92
|
-
|
|
442
|
+
raw = JSON.parse(text);
|
|
93
443
|
}
|
|
94
444
|
catch {
|
|
95
|
-
|
|
445
|
+
return { state: "unreadable", detail: "its owner entry is not valid JSON" };
|
|
96
446
|
}
|
|
97
|
-
const
|
|
98
|
-
if (
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
447
|
+
const holder = parseGuardHolder(raw, match[1]);
|
|
448
|
+
if (holder === null) {
|
|
449
|
+
return { state: "unreadable", detail: "its owner entry does not name the generation in its filename or lacks a holder field" };
|
|
450
|
+
}
|
|
451
|
+
return { state: "occupied", holder, name, mtimeMs: entryStat.mtimeMs };
|
|
452
|
+
}
|
|
453
|
+
catch (err) {
|
|
454
|
+
return { state: "unreadable", detail: `its owner entry cannot be read (${err?.code ?? String(err)})` };
|
|
455
|
+
}
|
|
456
|
+
finally {
|
|
457
|
+
closeSync(fd);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
function publishGuard(guardPath, holder) {
|
|
461
|
+
const staging = join(dirname(guardPath), `.${basename(guardPath)}.${process.pid}.${randomBytes(8).toString("hex")}.stage`);
|
|
462
|
+
try {
|
|
463
|
+
mkdirSync(staging, { mode: 0o700 });
|
|
464
|
+
const fd = openSync(join(staging, ownerEntryName(holder.generation)), "wx", 0o600);
|
|
465
|
+
try {
|
|
466
|
+
writeFileSync(fd, JSON.stringify(holder));
|
|
467
|
+
fsyncSync(fd);
|
|
468
|
+
}
|
|
469
|
+
finally {
|
|
470
|
+
closeSync(fd);
|
|
471
|
+
}
|
|
472
|
+
// Test-only pause after the populated staging directory is complete and
|
|
473
|
+
// before the rename that publishes it (flair#2866).
|
|
474
|
+
txnPausePointSync("migration-lock-guard-publish", process.env, undefined, {
|
|
475
|
+
guardPath,
|
|
476
|
+
generation: holder.generation,
|
|
477
|
+
});
|
|
478
|
+
try {
|
|
479
|
+
renameSync(staging, guardPath);
|
|
480
|
+
return { published: true };
|
|
481
|
+
}
|
|
482
|
+
catch (err) {
|
|
483
|
+
const code = err?.code;
|
|
484
|
+
if (code === "EEXIST" || code === "ENOTEMPTY")
|
|
485
|
+
return { published: false, contention: true };
|
|
486
|
+
return { published: false, contention: false, code };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
catch (err) {
|
|
490
|
+
return { published: false, contention: false, code: err?.code };
|
|
491
|
+
}
|
|
492
|
+
finally {
|
|
493
|
+
try {
|
|
494
|
+
rmSync(staging, { recursive: true, force: true });
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
/* best-effort cleanup of our own staging directory */
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
function releaseGuard(guardPath, generation) {
|
|
502
|
+
try {
|
|
503
|
+
unlinkSync(join(guardPath, ownerEntryName(generation)));
|
|
504
|
+
return { ok: true };
|
|
505
|
+
}
|
|
506
|
+
catch (err) {
|
|
507
|
+
if (err?.code === "ENOENT")
|
|
508
|
+
return { ok: true };
|
|
509
|
+
abandonedGuardGenerations.set(guardPath, generation);
|
|
510
|
+
return {
|
|
511
|
+
ok: false,
|
|
512
|
+
reason: `its owner entry ${ownerEntryName(generation)} cannot be removed (${err?.code ?? String(err)})`,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
finally {
|
|
516
|
+
if (ownedGuardGenerations.get(guardPath) === generation)
|
|
517
|
+
ownedGuardGenerations.delete(guardPath);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
function settleContention() {
|
|
521
|
+
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
522
|
+
Atomics.wait(sleeper, 0, 0, CONTENTION_SETTLE_MS);
|
|
523
|
+
}
|
|
524
|
+
function makeGuardHolder(now) {
|
|
525
|
+
return {
|
|
526
|
+
pid: process.pid,
|
|
527
|
+
hostname: osHostname(),
|
|
528
|
+
startedAt: new Date(now()).toISOString(),
|
|
529
|
+
generation: randomBytes(8).toString("hex"),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Acquire the directory mutex, recovering a generation at most as often
|
|
534
|
+
* as the bounded loop allows.
|
|
535
|
+
*/
|
|
536
|
+
function acquireGuard(guardPath, deps) {
|
|
537
|
+
for (let attempt = 0; attempt < GUARD_ACQUISITION_ATTEMPTS; attempt++) {
|
|
538
|
+
const holder = makeGuardHolder(deps.now);
|
|
539
|
+
const published = publishGuard(guardPath, holder);
|
|
540
|
+
if (published.published) {
|
|
541
|
+
ownedGuardGenerations.set(guardPath, holder.generation);
|
|
542
|
+
txnPausePointSync("migration-lock-guard-published", process.env, undefined, {
|
|
543
|
+
guardPath,
|
|
544
|
+
generation: holder.generation,
|
|
545
|
+
});
|
|
546
|
+
return { generation: holder.generation };
|
|
547
|
+
}
|
|
548
|
+
if (!published.contention) {
|
|
549
|
+
return {
|
|
550
|
+
acquired: false,
|
|
551
|
+
kind: "error",
|
|
552
|
+
reason: `${MigrationLockMutexError.name}: the mutex at ${guardPath} cannot be published (${published.code ?? "unknown error"})`,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const inspected = inspectGuard(guardPath);
|
|
556
|
+
if (inspected.state === "unreadable") {
|
|
557
|
+
return { acquired: false, kind: "error", reason: `${MigrationLockMutexError.name}: ${inspected.detail}` };
|
|
558
|
+
}
|
|
559
|
+
if (inspected.state !== "occupied") {
|
|
560
|
+
settleContention();
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
let breakable;
|
|
564
|
+
try {
|
|
565
|
+
breakable = guardHolderIsBreakable(guardPath, inspected.holder, inspected.mtimeMs, deps);
|
|
566
|
+
}
|
|
567
|
+
catch (err) {
|
|
568
|
+
if (err instanceof MigrationLockProbeError) {
|
|
569
|
+
return { acquired: false, kind: "error", reason: `${err.name}: ${err.message}` };
|
|
104
570
|
}
|
|
571
|
+
throw err;
|
|
105
572
|
}
|
|
106
|
-
|
|
573
|
+
if (!breakable) {
|
|
107
574
|
return {
|
|
108
575
|
acquired: false,
|
|
109
|
-
|
|
110
|
-
holder
|
|
576
|
+
kind: "held",
|
|
577
|
+
reason: `the migration-lock mutex is held by pid ${inspected.holder.pid} on ${inspected.holder.hostname} ` +
|
|
578
|
+
`since ${inspected.holder.startedAt} (${guardPath})`,
|
|
111
579
|
};
|
|
112
580
|
}
|
|
581
|
+
// Test-only pause after the breakable generation is inspected and before its
|
|
582
|
+
// owner entry is unlinked, so a test can let a successor recover and
|
|
583
|
+
// publish before this process resumes its old cleanup (flair#2866).
|
|
584
|
+
txnPausePointSync("migration-lock-guard-reclaim", process.env, undefined, {
|
|
585
|
+
guardPath,
|
|
586
|
+
generation: inspected.holder.generation,
|
|
587
|
+
});
|
|
588
|
+
try {
|
|
589
|
+
// Unlink only the entry this inspection named; never a fresh listing.
|
|
590
|
+
unlinkSync(join(guardPath, inspected.name));
|
|
591
|
+
}
|
|
592
|
+
catch (err) {
|
|
593
|
+
if (err?.code !== "ENOENT") {
|
|
594
|
+
return {
|
|
595
|
+
acquired: false,
|
|
596
|
+
kind: "error",
|
|
597
|
+
reason: `${MigrationLockMutexError.name}: ${inspected.name} cannot be removed (${err?.code ?? String(err)})`,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
settleContention();
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (abandonedGuardGenerations.get(guardPath) === inspected.holder.generation) {
|
|
604
|
+
abandonedGuardGenerations.delete(guardPath);
|
|
605
|
+
}
|
|
606
|
+
txnPausePointSync("migration-lock-guard-reclaimed", process.env, undefined, {
|
|
607
|
+
guardPath,
|
|
608
|
+
generation: inspected.holder.generation,
|
|
609
|
+
});
|
|
610
|
+
settleContention();
|
|
113
611
|
}
|
|
114
|
-
|
|
612
|
+
return { acquired: false, kind: "held", reason: `lost the race to acquire the migration-lock mutex (${guardPath})` };
|
|
613
|
+
}
|
|
614
|
+
function guardHolderIsBreakable(guardPath, holder, mtimeMs, deps) {
|
|
615
|
+
if (holder.hostname === osHostname()) {
|
|
616
|
+
if (holder.pid === process.pid) {
|
|
617
|
+
if (abandonedGuardGenerations.get(guardPath) === holder.generation)
|
|
618
|
+
return true;
|
|
619
|
+
return ownedGuardGenerations.get(guardPath) !== holder.generation && deps.now() - mtimeMs > deps.staleMs;
|
|
620
|
+
}
|
|
621
|
+
return !deps.isProcessAlive(holder.pid);
|
|
622
|
+
}
|
|
623
|
+
return deps.now() - mtimeMs > deps.staleMs;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* True only for the exact record this process wrote, with
|
|
627
|
+
* no live handle for it. The path and the full identity must match: a pid
|
|
628
|
+
* alone never authorizes deleting a record (flair#2866).
|
|
629
|
+
*/
|
|
630
|
+
function isAbandonedOwnRecord(lockPath, holder) {
|
|
631
|
+
const remembered = abandonedOwnRecords.get(lockPath);
|
|
632
|
+
return (remembered !== undefined &&
|
|
633
|
+
sameHolder(remembered, holder) &&
|
|
634
|
+
!liveHolderKeys.has(holderKey(lockPath, holder)));
|
|
635
|
+
}
|
|
636
|
+
function rememberAbandonedRecord(lockPath, holder) {
|
|
637
|
+
abandonedOwnRecords.set(lockPath, holder);
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* One inspection-and-transition inside the mutex. The lock is inspected
|
|
641
|
+
* afresh here: an inspection made before the mutex was acquired never
|
|
642
|
+
* authorizes replacement.
|
|
643
|
+
*/
|
|
644
|
+
function transitionUnderGuard(lockPath, deps, staleMs, now) {
|
|
645
|
+
const inspected = inspectLock(lockPath);
|
|
646
|
+
if (inspected.state === "absent") {
|
|
647
|
+
abandonedOwnRecords.delete(lockPath);
|
|
648
|
+
const holder = makeHolder(now);
|
|
649
|
+
const published = publishLock(lockPath, holder);
|
|
650
|
+
if (!published.published)
|
|
651
|
+
return { kind: "retry" };
|
|
652
|
+
return { kind: "handle", holder, dev: published.dev, ino: published.ino };
|
|
653
|
+
}
|
|
654
|
+
if (inspected.state === "unreadable") {
|
|
655
|
+
const err = new MigrationLockUnreadableError(lockPath, inspected.detail);
|
|
656
|
+
return { kind: "refused", reason: `${err.name}: ${err.message}` };
|
|
657
|
+
}
|
|
658
|
+
const holder = inspected.holder;
|
|
659
|
+
if (isAbandonedOwnRecord(lockPath, holder)) {
|
|
660
|
+
try {
|
|
661
|
+
unlinkSync(lockPath);
|
|
662
|
+
}
|
|
663
|
+
catch (err) {
|
|
664
|
+
if (err?.code !== "ENOENT") {
|
|
665
|
+
return {
|
|
666
|
+
kind: "refused",
|
|
667
|
+
reason: `refusing to reclaim ${lockPath}: this process's abandoned lock record cannot be removed ` +
|
|
668
|
+
`(${err?.code ?? String(err)})`,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
abandonedOwnRecords.delete(lockPath);
|
|
673
|
+
const fresh = makeHolder(now);
|
|
674
|
+
const published = publishLock(lockPath, fresh);
|
|
675
|
+
if (!published.published)
|
|
676
|
+
return { kind: "retry" };
|
|
677
|
+
return { kind: "handle", holder: fresh, dev: published.dev, ino: published.ino };
|
|
678
|
+
}
|
|
679
|
+
// A different (or live) record means the abandoned one is gone.
|
|
680
|
+
abandonedOwnRecords.delete(lockPath);
|
|
681
|
+
let breakable;
|
|
115
682
|
try {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
683
|
+
if (holder.hostname === osHostname()) {
|
|
684
|
+
breakable = holder.pid === process.pid
|
|
685
|
+
? !liveHolderKeys.has(holderKey(lockPath, holder)) && now() - inspected.mtimeMs > staleMs
|
|
686
|
+
: !deps.isProcessAlive(holder.pid);
|
|
687
|
+
}
|
|
688
|
+
else {
|
|
689
|
+
breakable = now() - inspected.mtimeMs > staleMs;
|
|
690
|
+
}
|
|
119
691
|
}
|
|
120
692
|
catch (err) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
return { acquired: false, reason: "lost the race to acquire the lock file" };
|
|
693
|
+
if (err instanceof MigrationLockProbeError) {
|
|
694
|
+
return { kind: "refused", reason: `${err.name}: ${err.message}` };
|
|
124
695
|
}
|
|
125
696
|
throw err;
|
|
126
697
|
}
|
|
698
|
+
if (!breakable)
|
|
699
|
+
return { kind: "held", holder };
|
|
700
|
+
// Test-only pause between the holder inspection and the rename-over
|
|
701
|
+
// replacement, so a test can put a second contender into that window
|
|
702
|
+
// deterministically (flair#2866).
|
|
703
|
+
txnPausePointSync("migration-lock-reclaim", process.env, undefined, { lockPath });
|
|
704
|
+
const fresh = makeHolder(now);
|
|
705
|
+
let prepared;
|
|
127
706
|
try {
|
|
128
|
-
|
|
129
|
-
writeSync(fd, JSON.stringify(info));
|
|
707
|
+
prepared = prepareLockRecord(lockPath, fresh);
|
|
130
708
|
}
|
|
131
|
-
|
|
132
|
-
|
|
709
|
+
catch (err) {
|
|
710
|
+
return {
|
|
711
|
+
kind: "refused",
|
|
712
|
+
reason: `refusing to reclaim ${lockPath}: a new holder record cannot be prepared (${err?.code ?? String(err)})`,
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
try {
|
|
716
|
+
// Atomic replacement: the old record occupies the name before, the new
|
|
717
|
+
// one after. There is no unlink-first window and no restore step.
|
|
718
|
+
renameSync(prepared.temp, lockPath);
|
|
719
|
+
}
|
|
720
|
+
catch (err) {
|
|
721
|
+
try {
|
|
722
|
+
unlinkSync(prepared.temp);
|
|
723
|
+
}
|
|
724
|
+
catch {
|
|
725
|
+
/* best-effort cleanup of our own unpublished record */
|
|
726
|
+
}
|
|
727
|
+
return {
|
|
728
|
+
kind: "refused",
|
|
729
|
+
reason: `refusing to reclaim ${lockPath}: the new holder record cannot be renamed over it (${err?.code ?? String(err)})`,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
txnPausePointSync("migration-lock-reclaimed", process.env, undefined, { lockPath });
|
|
733
|
+
return { kind: "handle", holder: fresh, dev: prepared.dev, ino: prepared.ino };
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Attempts to acquire the migration lock. On success, returns a handle whose
|
|
737
|
+
* `release()` removes the lock file only when it still holds this handle's
|
|
738
|
+
* record, for cooperating holders under the mutex. The cross-host takeover is
|
|
739
|
+
* unfenced, so a replacement between that inspection and the pathname unlink
|
|
740
|
+
* is outside the guarantee. `touch()` updates the mtime of the verified
|
|
741
|
+
* descriptor.
|
|
742
|
+
*/
|
|
743
|
+
export function acquireMigrationLock(deps) {
|
|
744
|
+
const defaults = defaultLockDeps(deps.lockPath);
|
|
745
|
+
const resolved = {
|
|
746
|
+
lockPath: deps.lockPath,
|
|
747
|
+
staleMs: deps.staleMs ?? defaults.staleMs,
|
|
748
|
+
isProcessAlive: deps.isProcessAlive ?? defaults.isProcessAlive,
|
|
749
|
+
now: deps.now ?? defaults.now,
|
|
750
|
+
};
|
|
751
|
+
const { lockPath, staleMs, now } = resolved;
|
|
752
|
+
const guardPath = guardPathFor(lockPath);
|
|
753
|
+
if (inProcessHeld) {
|
|
754
|
+
return {
|
|
755
|
+
acquired: false,
|
|
756
|
+
kind: "held",
|
|
757
|
+
reason: "already held in-process (another async caller in this process holds it)",
|
|
758
|
+
};
|
|
133
759
|
}
|
|
134
760
|
inProcessHeld = true;
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
761
|
+
const abortHeld = (reason, holder) => {
|
|
762
|
+
inProcessHeld = false;
|
|
763
|
+
return holder === undefined
|
|
764
|
+
? { acquired: false, kind: "held", reason }
|
|
765
|
+
: { acquired: false, kind: "held", reason, holder };
|
|
766
|
+
};
|
|
767
|
+
const abortError = (reason) => {
|
|
768
|
+
inProcessHeld = false;
|
|
769
|
+
return { acquired: false, kind: "error", reason };
|
|
770
|
+
};
|
|
771
|
+
try {
|
|
772
|
+
ensureSecureDir(dirname(lockPath));
|
|
773
|
+
}
|
|
774
|
+
catch (err) {
|
|
775
|
+
inProcessHeld = false;
|
|
776
|
+
throw err;
|
|
777
|
+
}
|
|
778
|
+
for (let round = 0; round < LOCK_ACQUISITION_ROUNDS; round++) {
|
|
779
|
+
const guard = acquireGuard(guardPath, resolved);
|
|
780
|
+
if (!("generation" in guard))
|
|
781
|
+
return guard.kind === "held" ? abortHeld(guard.reason) : abortError(guard.reason);
|
|
782
|
+
let outcome;
|
|
783
|
+
try {
|
|
784
|
+
outcome = transitionUnderGuard(lockPath, resolved, staleMs, now);
|
|
785
|
+
}
|
|
786
|
+
catch (err) {
|
|
787
|
+
const released = releaseGuard(guardPath, guard.generation);
|
|
788
|
+
if (!released.ok) {
|
|
789
|
+
return abortError(`${String(err)}; the mutex at ${guardPath} could not be released (${released.reason})`);
|
|
790
|
+
}
|
|
142
791
|
inProcessHeld = false;
|
|
792
|
+
throw err;
|
|
793
|
+
}
|
|
794
|
+
const released = releaseGuard(guardPath, guard.generation);
|
|
795
|
+
if (!released.ok) {
|
|
796
|
+
if (outcome.kind === "handle")
|
|
797
|
+
rememberAbandonedRecord(lockPath, outcome.holder);
|
|
798
|
+
return abortError(`refusing to return the migration lock at ${lockPath}: the mutex could not be released ` +
|
|
799
|
+
`(${released.reason})`);
|
|
800
|
+
}
|
|
801
|
+
if (outcome.kind === "retry") {
|
|
802
|
+
settleContention();
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (outcome.kind === "refused")
|
|
806
|
+
return abortError(outcome.reason);
|
|
807
|
+
if (outcome.kind === "held") {
|
|
808
|
+
return abortHeld(`held by pid ${outcome.holder.pid} on ${outcome.holder.hostname} since ${outcome.holder.startedAt} (lock ${lockPath})`, outcome.holder);
|
|
809
|
+
}
|
|
810
|
+
return issueHandle(lockPath, outcome.holder, outcome.dev, outcome.ino, now);
|
|
811
|
+
}
|
|
812
|
+
return abortHeld(`lost the race to acquire the lock file (${lockPath})`);
|
|
813
|
+
}
|
|
814
|
+
function makeHolder(now) {
|
|
815
|
+
return { pid: process.pid, hostname: osHostname(), startedAt: new Date(now()).toISOString() };
|
|
816
|
+
}
|
|
817
|
+
function issueHandle(lockPath, holder, dev, ino, now) {
|
|
818
|
+
Object.freeze(holder);
|
|
819
|
+
const guardPath = guardPathFor(lockPath);
|
|
820
|
+
const identity = {
|
|
821
|
+
lockPath,
|
|
822
|
+
holder,
|
|
823
|
+
dev,
|
|
824
|
+
ino,
|
|
825
|
+
release: () => {
|
|
826
|
+
// The public handle was revoked before this runs. End protected work
|
|
827
|
+
// first, then serialize the identity-checked unlink with the mutex.
|
|
828
|
+
txnPausePointSync("migration-lock-release-revoked", process.env, undefined, { lockPath });
|
|
829
|
+
let cleanupFailure = null;
|
|
830
|
+
// What this release established about the record, so a later failure
|
|
831
|
+
// does not claim more than the release observed.
|
|
832
|
+
let recordOutcome = "unknown";
|
|
833
|
+
let recordNotInspected = false;
|
|
143
834
|
try {
|
|
144
|
-
|
|
835
|
+
const guard = acquireGuard(guardPath, defaultLockDeps(lockPath));
|
|
836
|
+
if (!("generation" in guard)) {
|
|
837
|
+
rememberAbandonedRecord(lockPath, holder);
|
|
838
|
+
recordNotInspected = true;
|
|
839
|
+
cleanupFailure = `the mutex could not be acquired: ${guard.reason}`;
|
|
840
|
+
}
|
|
841
|
+
else {
|
|
842
|
+
txnPausePointSync("migration-lock-release-guard", process.env, undefined, { lockPath, guardPath });
|
|
843
|
+
try {
|
|
844
|
+
const inspected = inspectLock(lockPath);
|
|
845
|
+
if (inspected.state === "unreadable") {
|
|
846
|
+
cleanupFailure = `the lock file cannot be inspected: ${inspected.detail}`;
|
|
847
|
+
}
|
|
848
|
+
else if (inspected.state === "held" &&
|
|
849
|
+
inspected.dev === dev &&
|
|
850
|
+
inspected.ino === ino &&
|
|
851
|
+
sameHolder(inspected.holder, holder)) {
|
|
852
|
+
txnPausePointSync("migration-lock-release-verified", process.env, undefined, { lockPath });
|
|
853
|
+
try {
|
|
854
|
+
unlinkSync(lockPath);
|
|
855
|
+
recordOutcome = "removed";
|
|
856
|
+
txnPausePointSync("migration-lock-release-unlinked", process.env, undefined, { lockPath });
|
|
857
|
+
}
|
|
858
|
+
catch (err) {
|
|
859
|
+
if (err?.code === "ENOENT") {
|
|
860
|
+
recordOutcome = "absent";
|
|
861
|
+
}
|
|
862
|
+
else {
|
|
863
|
+
recordOutcome = "unknown";
|
|
864
|
+
cleanupFailure = `the lock file cannot be removed (${err?.code ?? String(err)})`;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
else if (inspected.state === "absent") {
|
|
869
|
+
recordOutcome = "absent";
|
|
870
|
+
}
|
|
871
|
+
else {
|
|
872
|
+
recordOutcome = "present";
|
|
873
|
+
}
|
|
874
|
+
// A different record belongs to someone else and an absent record
|
|
875
|
+
// belongs to nobody: leave both.
|
|
876
|
+
}
|
|
877
|
+
catch (err) {
|
|
878
|
+
cleanupFailure = `the lock file cannot be inspected (${err?.code ?? String(err)})`;
|
|
879
|
+
}
|
|
880
|
+
const released = releaseGuard(guardPath, guard.generation);
|
|
881
|
+
if (!released.ok && cleanupFailure === null)
|
|
882
|
+
cleanupFailure = released.reason;
|
|
883
|
+
}
|
|
145
884
|
}
|
|
146
|
-
catch {
|
|
147
|
-
|
|
885
|
+
catch (err) {
|
|
886
|
+
cleanupFailure = `the mutex could not be used (${err?.code ?? String(err)})`;
|
|
887
|
+
}
|
|
888
|
+
finally {
|
|
889
|
+
inProcessHeld = false;
|
|
890
|
+
}
|
|
891
|
+
if (cleanupFailure !== null) {
|
|
892
|
+
// Release runs in the runner's finally: it must not throw, but an
|
|
893
|
+
// uncertain cleanup is reported rather than silently ignored.
|
|
894
|
+
const recordState = recordOutcome === "removed"
|
|
895
|
+
? "The lock record was removed by this release"
|
|
896
|
+
: recordOutcome === "absent"
|
|
897
|
+
? "No lock record was present"
|
|
898
|
+
: recordOutcome === "present"
|
|
899
|
+
? "The lock record is left in place"
|
|
900
|
+
: recordNotInspected
|
|
901
|
+
? "The lock record was not inspected because the mutex could not be taken, so its state is unknown; a later acquisition by this process removes it only after taking the mutex and finding this exact record with no live handle"
|
|
902
|
+
: "The lock record's state is unknown";
|
|
903
|
+
console.warn(`[flair-migrations] migration lock cleanup failed for ${lockPath}: ${cleanupFailure}. ` +
|
|
904
|
+
`${recordState}; inspect the lock and its mutex before the next migration cycle`);
|
|
148
905
|
}
|
|
149
906
|
},
|
|
150
907
|
touch: () => {
|
|
151
908
|
const t = new Date(now());
|
|
909
|
+
let fd;
|
|
152
910
|
try {
|
|
153
|
-
|
|
911
|
+
fd = openSync(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
|
912
|
+
const st = fstatSync(fd);
|
|
913
|
+
if (!st.isFile() || st.dev !== dev || st.ino !== ino)
|
|
914
|
+
return;
|
|
915
|
+
let raw;
|
|
916
|
+
try {
|
|
917
|
+
raw = JSON.parse(readFileSync(fd, "utf-8"));
|
|
918
|
+
}
|
|
919
|
+
catch {
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const record = parseHolder(raw);
|
|
923
|
+
if (record === null || !sameHolder(record, holder))
|
|
924
|
+
return;
|
|
925
|
+
txnPausePointSync("migration-lock-touch-verified", process.env, undefined, { lockPath });
|
|
926
|
+
// Same still-open descriptor: a later pathname replacement cannot
|
|
927
|
+
// redirect this update to a successor's file.
|
|
928
|
+
futimesSync(fd, t, t);
|
|
154
929
|
}
|
|
155
930
|
catch {
|
|
156
931
|
/* best-effort heartbeat — a failed touch must never break the migration */
|
|
157
932
|
}
|
|
933
|
+
finally {
|
|
934
|
+
if (fd !== undefined) {
|
|
935
|
+
try {
|
|
936
|
+
closeSync(fd);
|
|
937
|
+
}
|
|
938
|
+
catch {
|
|
939
|
+
/* best-effort close */
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
158
943
|
},
|
|
159
944
|
};
|
|
945
|
+
liveHolderKeys.add(holderKey(lockPath, holder));
|
|
946
|
+
return new MigrationLockHandle(HANDLE_KEY, identity);
|
|
160
947
|
}
|