@chroxy/server 0.11.10 → 0.11.11
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/CONFIG.md +4 -2
- package/package.json +3 -3
- package/src/acp-session.js +5 -1
- package/src/agent-connections.js +12 -1
- package/src/agent-control/client.js +29 -0
- package/src/agent-control/events.js +8 -4
- package/src/agent-control/local-connection.js +34 -16
- package/src/agent-control/mcp-server.js +2 -0
- package/src/anthropic-compatible-config.js +1 -0
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/base-session.js +319 -2
- package/src/bound-client-policy.js +12 -0
- package/src/byok-mcp-config.js +9 -5
- package/src/byok-mcp-trust.js +34 -20
- package/src/byok-session.js +62 -9
- package/src/byok-tool-executor.js +81 -1
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-tui/pty-driver.js +5 -1
- package/src/claude-tui/usage-limit.js +2 -2
- package/src/claude-tui-session.js +57 -4
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/schedule-cmd.js +25 -3
- package/src/cli/server-cmd.js +6 -0
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli-session.js +190 -11
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +78 -17
- package/src/codex-error-text.js +114 -0
- package/src/config-dir-migration.js +11 -6
- package/src/config.js +23 -3
- package/src/connection-info.js +73 -14
- package/src/continuations.js +153 -40
- package/src/conversation-scanner.js +2 -21
- package/src/conversation-search.js +4 -17
- package/src/dev-preview.js +2 -1
- package/src/docker-session.js +10 -1
- package/src/doctor.js +14 -3
- package/src/durable-write.js +35 -0
- package/src/environments/authority.js +7 -1
- package/src/event-normalizer.js +35 -2
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/handler-utils.js +6 -13
- package/src/handlers/checkpoint-handlers.js +8 -0
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +40 -11
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +4 -4
- package/src/handlers/session-handlers.js +10 -1
- package/src/handlers/settings-handlers.js +42 -8
- package/src/handlers/skills-handlers.js +7 -0
- package/src/history-page.js +8 -0
- package/src/jsonl-reader.js +90 -10
- package/src/jsonl-subprocess-session.js +4 -1
- package/src/logger.js +105 -15
- package/src/mailbox-route.js +102 -0
- package/src/notification-prefs.js +15 -0
- package/src/orchestration/orchestration-manager.js +38 -9
- package/src/orchestration/permission-gate.js +4 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +151 -33
- package/src/orphan-reaper.js +77 -20
- package/src/outgoing-policy.js +10 -4
- package/src/permission-floor.js +54 -2
- package/src/permission-manager.js +32 -13
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +7 -3
- package/src/platform.js +156 -4
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/providers.js +2 -0
- package/src/redaction.js +181 -22
- package/src/scheduled-task-store.js +12 -0
- package/src/scheduler.js +304 -17
- package/src/sdk-session.js +60 -7
- package/src/server-cli/push-notification-handler.js +6 -1
- package/src/server-cli.js +30 -1
- package/src/session-ci-watcher.js +210 -37
- package/src/session-manager.js +590 -19
- package/src/session-message-history.js +121 -2
- package/src/session-name-allocator.js +685 -0
- package/src/statusline.js +78 -19
- package/src/summarize-session.js +2 -0
- package/src/turn-outcome.js +5 -2
- package/src/utils/argv-safety.js +29 -0
- package/src/utils/binary-package-manifest.js +57 -15
- package/src/utils/bounded-regex-worker.js +4 -0
- package/src/utils/bounded-regex.js +16 -7
- package/src/utils/pid-liveness.js +47 -0
- package/src/web-task-manager.js +45 -4
- package/src/worktree-gc.js +195 -4
- package/src/ws-auth.js +103 -19
- package/src/ws-broadcaster.js +39 -7
- package/src/ws-client-manager.js +8 -0
- package/src/ws-file-ops/browser.js +35 -3
- package/src/ws-forwarding.js +23 -3
- package/src/ws-handler-context.js +18 -0
- package/src/ws-history.js +79 -12
- package/src/ws-message-handlers.js +10 -2
- package/src/ws-server.js +253 -13
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project-scoped incrementing session names ("chroxy 7") — the durable allocator.
|
|
3
|
+
*
|
|
4
|
+
* NOT WIRED INTO ANYTHING (slice N1). `SessionManager.createSession` is
|
|
5
|
+
* synchronous, so this module is synchronous end to end.
|
|
6
|
+
*
|
|
7
|
+
* ## No lock. Compare-and-swap on generations.
|
|
8
|
+
*
|
|
9
|
+
* State lives in numbered generations, each with a primary and a mirror copy:
|
|
10
|
+
*
|
|
11
|
+
* <dir>/session-names.g<12-digit gen>.json (primary)
|
|
12
|
+
* <dir>/session-names.g<12-digit gen>.mirror.json (mirror)
|
|
13
|
+
*
|
|
14
|
+
* Each file is `{ version: 1, gen, body, sha256 }`; `sha256` covers a canonical
|
|
15
|
+
* (sorted-key) serialization of `{ version, gen, body }`. Nothing else in the
|
|
16
|
+
* directory is ever parsed.
|
|
17
|
+
*
|
|
18
|
+
* A writer OWNS generation g+1 only if it creates BOTH names itself:
|
|
19
|
+
* 1. write the full text (every byte, short writes looped) to two unique temp
|
|
20
|
+
* files (`session-names.tmp.<pid>.<token>.a|b`, outside the generation
|
|
21
|
+
* pattern) and fsync each;
|
|
22
|
+
* 2. `linkSync(tmpA, primary)` then `linkSync(tmpB, mirror)` — each an atomic
|
|
23
|
+
* create-if-absent. EEXIST on EITHER means another writer owns g+1: unlink
|
|
24
|
+
* whichever of the two names THIS writer created, reload, retry. (A rename
|
|
25
|
+
* would overwrite and let a stale writer reclaim a generation whose other
|
|
26
|
+
* copy was lost.)
|
|
27
|
+
* 3. fsync the directory once, unlink the temps;
|
|
28
|
+
* 4. re-list the directory: if a generation GREATER than g+1 exists, this
|
|
29
|
+
* writer's view was stale (the store moved on and pruned g+1 — an ABA).
|
|
30
|
+
* Unlink our two names and retry; never issue;
|
|
31
|
+
* 5. issue the number only when both links succeeded and the directory fsync
|
|
32
|
+
* was confirmed. Otherwise the number may already be persisted as `next`:
|
|
33
|
+
* it becomes a gap, never a reuse.
|
|
34
|
+
* Contention is bounded (`maxAttempts`, default 8) and returns `contended`.
|
|
35
|
+
* No sleeps, no lock file, no wall clock in mutual exclusion. A filesystem
|
|
36
|
+
* without hard links returns `unsupported_fs` (non-closing, nothing issued).
|
|
37
|
+
* Every outcome after a load (issued, lost, failed) prunes: generations below
|
|
38
|
+
* top-2 and temp files older than 10 minutes are removed; the top three
|
|
39
|
+
* generations are never touched.
|
|
40
|
+
*
|
|
41
|
+
* Two consequences of the two-link publish, both on the safe side:
|
|
42
|
+
* - between a writer's two links a concurrent reader can see two valid copies
|
|
43
|
+
* with different sha256 and fail closed `inconsistent` for that one call;
|
|
44
|
+
* - a crash inside that window, in the lost-copy case, leaves a permanent
|
|
45
|
+
* `inconsistent`: no duplicate is possible, and operator recovery applies.
|
|
46
|
+
*
|
|
47
|
+
* ## Load
|
|
48
|
+
*
|
|
49
|
+
* Every call re-reads the directory (no cache). The highest generation that has
|
|
50
|
+
* any file is the state:
|
|
51
|
+
* - no naming files at all -> fresh (gen 0)
|
|
52
|
+
* - either copy valid -> use it (primary preferred)
|
|
53
|
+
* - both valid, different sha256 -> fail closed: 'inconsistent'
|
|
54
|
+
* - at least one copy present but bad, none valid -> fail closed: 'evidence_lost'
|
|
55
|
+
* - both copies ENOENT after listing (pruned under us) -> re-list, retry
|
|
56
|
+
* - any other read error (EIO, EMFILE, EACCES) -> 'io_error' (non-closing)
|
|
57
|
+
* An older generation is NEVER a fallback. Failing closed returns
|
|
58
|
+
* `{ ok: false, reason }` from allocate and bind and WRITES NOTHING, so corrupt
|
|
59
|
+
* evidence keeps the allocator closed across restarts (callers use their legacy
|
|
60
|
+
* names). Naming files are opened O_RDONLY|O_NONBLOCK|O_NOFOLLOW, fstat'd, and
|
|
61
|
+
* must be regular files of at most MAX_STORE_BYTES, so a FIFO planted at a
|
|
62
|
+
* naming path cannot block the daemon.
|
|
63
|
+
*
|
|
64
|
+
* ## Guarantee (narrowed on purpose)
|
|
65
|
+
*
|
|
66
|
+
* A number issued for a key is never issued again for that key while at least
|
|
67
|
+
* one durable copy of the generation that recorded it, or of any later
|
|
68
|
+
* generation, survives intact. If both copies of the highest generation are
|
|
69
|
+
* invalid, numbered allocation fails closed (callers use legacy names) and the
|
|
70
|
+
* allocator writes nothing until an operator removes the naming files. If all
|
|
71
|
+
* naming files are deleted, that is indistinguishable from first use: numbering
|
|
72
|
+
* restarts above the highest number in LIVE session names, and numbers that
|
|
73
|
+
* belonged only to deleted sessions or unused allocations may be issued again —
|
|
74
|
+
* this case is outside the guarantee.
|
|
75
|
+
*
|
|
76
|
+
* On win32 the guarantee holds across process crashes and restarts; durability
|
|
77
|
+
* of directory entries against POWER LOSS is not confirmed (the directory fsync
|
|
78
|
+
* is skipped there, and `writeFileRestricted` assumes rename is write-through).
|
|
79
|
+
*
|
|
80
|
+
* ## Operator recovery from a fail-closed state
|
|
81
|
+
*
|
|
82
|
+
* Stop the daemon and remove every `session-names.*` file in the config dir,
|
|
83
|
+
* then start it again. Accepted cost: numbers may repeat those of sessions that
|
|
84
|
+
* no longer exist. There is no lock and no stale-lock state to clean up.
|
|
85
|
+
*
|
|
86
|
+
* ## Other behaviour
|
|
87
|
+
*
|
|
88
|
+
* - Live floor: n = max(stored next, highest live "<key> <n>" + 1). Live
|
|
89
|
+
* numbers that are not safe integers or exceed 1,000,000 are ignored, so a
|
|
90
|
+
* user-typed "chroxy 99999999999" cannot exhaust a project.
|
|
91
|
+
* - Idempotency records (<= 512, <= 24 h by `now`, ordered by a persisted
|
|
92
|
+
* monotonic `seq`, never by wall clock) store key, canonical root, number and
|
|
93
|
+
* bound session. A retry of an unbound key returns the same number but ONLY
|
|
94
|
+
* after a new generation carrying it was published and confirmed. A key reused
|
|
95
|
+
* for a different project or root is refused, never remapped. Expiry (24 h) is
|
|
96
|
+
* applied BEFORE lookup, so a retry of an expired key is a new key; a clock
|
|
97
|
+
* that moves backwards never drops a fresh record.
|
|
98
|
+
* - The serialized size is checked BEFORE publishing against MAX_STORE_BYTES.
|
|
99
|
+
* Over budget: idempotency records are evicted oldest-seq first (never the
|
|
100
|
+
* current one); still over -> 'store_full' (non-closing, nothing written).
|
|
101
|
+
* - Numbers stop at MAX_SAFE_INTEGER - 1, and generations at 999999999999
|
|
102
|
+
* ('exhausted', nothing written).
|
|
103
|
+
* - `body.projects` is deliberately unbounded: after roughly 3,000 distinct
|
|
104
|
+
* projects, new projects get `store_full` while existing ones keep allocating.
|
|
105
|
+
* - A candidate name is checked against every live name; collisions are skipped
|
|
106
|
+
* (at most 64) and then fail with `live_collision` (non-closing).
|
|
107
|
+
* - Cost: every call is SYNCHRONOUS disk work on the caller's thread. Measured on a laptop:
|
|
108
|
+
* about 15 ms per allocation against an empty store, about 28 ms near the size budget, and
|
|
109
|
+
* 27-57 ms for a create that carries an idempotency key, because the follow-up `bind` publishes
|
|
110
|
+
* a second generation. A bind is not folded into the allocation's own publish on purpose: a
|
|
111
|
+
* record must only become "bound" once the session really exists, or a retry of a create that
|
|
112
|
+
* failed in between would burn a fresh number instead of reusing its reservation.
|
|
113
|
+
* - Nothing here throws for I/O or corruption problems; those return
|
|
114
|
+
* `{ ok: false, reason }`. Only bad arguments throw (programming errors).
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
118
|
+
import {
|
|
119
|
+
closeSync, constants as fsConstants, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readdirSync,
|
|
120
|
+
readSync, statSync, unlinkSync, writeSync,
|
|
121
|
+
} from 'node:fs'
|
|
122
|
+
import { join } from 'node:path'
|
|
123
|
+
import { canonicalProjectForCwd } from '@chroxy/protocol/project'
|
|
124
|
+
import { configDir } from './config-dir.js'
|
|
125
|
+
|
|
126
|
+
export const MAX_STORE_BYTES = 1024 * 1024
|
|
127
|
+
|
|
128
|
+
const VERSION = 1
|
|
129
|
+
const MAX_LABEL_CODE_POINTS = 64
|
|
130
|
+
const MAX_ROOT_CODE_POINTS = 512
|
|
131
|
+
const MAX_SESSION_ID_LEN = 128
|
|
132
|
+
const MAX_IDEM_KEY_LEN = 256
|
|
133
|
+
const MAX_KEYS = 512
|
|
134
|
+
const KEY_TTL_MS = 24 * 60 * 60 * 1000
|
|
135
|
+
const MAX_LIVE_NUMBER = 1_000_000
|
|
136
|
+
const DEFAULT_MAX_ATTEMPTS = 8
|
|
137
|
+
const KEEP_GENERATIONS = 3
|
|
138
|
+
const TMP_PREFIX = 'session-names.tmp.'
|
|
139
|
+
const TMP_STALE_MS = 10 * 60 * 1000
|
|
140
|
+
const FILE_RE = /^session-names\.g(\d{12})(\.mirror)?\.json$/
|
|
141
|
+
const MAX_GEN = 999_999_999_999
|
|
142
|
+
const MAX_LIVE_SKIPS = 64
|
|
143
|
+
|
|
144
|
+
const O_NONBLOCK = fsConstants.O_NONBLOCK ?? 0
|
|
145
|
+
const O_NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
const genName = (gen, mirror) => `session-names.g${String(gen).padStart(12, '0')}${mirror ? '.mirror' : ''}.json`
|
|
149
|
+
|
|
150
|
+
/** Read a naming file without ever blocking; non-regular or oversized files are refused. */
|
|
151
|
+
function defaultReadFile(path, maxBytes = MAX_STORE_BYTES) {
|
|
152
|
+
const fd = openSync(path, fsConstants.O_RDONLY | O_NONBLOCK | O_NOFOLLOW)
|
|
153
|
+
try {
|
|
154
|
+
const st = fstatSync(fd)
|
|
155
|
+
if (!st.isFile() || st.size > maxBytes) {
|
|
156
|
+
const err = new Error('naming file is not a regular file or is oversized')
|
|
157
|
+
err.code = 'ECHROXY_BADFILE'
|
|
158
|
+
throw err
|
|
159
|
+
}
|
|
160
|
+
const buf = Buffer.alloc(st.size)
|
|
161
|
+
let off = 0
|
|
162
|
+
while (off < st.size) {
|
|
163
|
+
const n = readSync(fd, buf, off, st.size - off, off)
|
|
164
|
+
if (n <= 0) break
|
|
165
|
+
off += n
|
|
166
|
+
}
|
|
167
|
+
return buf.subarray(0, off).toString('utf8')
|
|
168
|
+
} finally {
|
|
169
|
+
closeSync(fd)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** fsync a directory so a new entry survives power loss. Not possible on win32. */
|
|
174
|
+
function defaultSyncDir(dir) {
|
|
175
|
+
if (process.platform === 'win32') return
|
|
176
|
+
const fd = openSync(dir, fsConstants.O_RDONLY)
|
|
177
|
+
try {
|
|
178
|
+
fsyncSync(fd)
|
|
179
|
+
} finally {
|
|
180
|
+
closeSync(fd)
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Sorted-key JSON, so the digest does not depend on property order. */
|
|
185
|
+
function canonicalJson(value) {
|
|
186
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
|
|
187
|
+
if (value && typeof value === 'object') {
|
|
188
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`
|
|
189
|
+
}
|
|
190
|
+
return JSON.stringify(value)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function digest(version, gen, body) {
|
|
194
|
+
return createHash('sha256').update(canonicalJson({ version, gen, body })).digest('hex')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Label normalization: NFC, whitespace collapsed, control chars stripped, 64 code-point cap. */
|
|
198
|
+
export function normalizeLabel(raw) {
|
|
199
|
+
if (typeof raw !== 'string') return ''
|
|
200
|
+
let s = raw.normalize('NFC').replace(/\s+/gu, ' ')
|
|
201
|
+
s = s.replace(/\p{Cc}/gu, '')
|
|
202
|
+
s = Array.from(s.trim()).slice(0, MAX_LABEL_CODE_POINTS).join('')
|
|
203
|
+
return s.trim().normalize('NFC')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Is `name` an allocator-style name ("<label> <n>") for the project that `cwd` belongs to?
|
|
208
|
+
* Used to tell a name this module handed out from one a person typed.
|
|
209
|
+
*/
|
|
210
|
+
export function isAllocatorNameForCwd(name, cwd) {
|
|
211
|
+
if (typeof name !== 'string' || typeof cwd !== 'string' || cwd.length === 0) return false
|
|
212
|
+
let project
|
|
213
|
+
try {
|
|
214
|
+
project = canonicalProjectForCwd(cwd)
|
|
215
|
+
} catch {
|
|
216
|
+
return false
|
|
217
|
+
}
|
|
218
|
+
if (!project) return false
|
|
219
|
+
const label = normalizeLabel(project.label)
|
|
220
|
+
if (!label) return false
|
|
221
|
+
const key = keyForLabel(label)
|
|
222
|
+
return new RegExp(`^${escapeRegExp(key)} \\d+$`).test(name.normalize('NFC').toLowerCase())
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function keyForLabel(label) {
|
|
226
|
+
return label.normalize('NFC').toLowerCase()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function escapeRegExp(s) {
|
|
230
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const isInt = (v) => Number.isSafeInteger(v) && v >= 1
|
|
234
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
235
|
+
|
|
236
|
+
function validBody(body) {
|
|
237
|
+
if (!isObj(body) || !isObj(body.projects) || !isObj(body.keys)) return false
|
|
238
|
+
if (!Number.isSafeInteger(body.seq) || body.seq < 0) return false
|
|
239
|
+
for (const [k, p] of Object.entries(body.projects)) {
|
|
240
|
+
if (k.length > MAX_LABEL_CODE_POINTS * 2) return false
|
|
241
|
+
if (!isObj(p) || typeof p.label !== 'string' || typeof p.root !== 'string' || !isInt(p.next)) return false
|
|
242
|
+
}
|
|
243
|
+
for (const [id, e] of Object.entries(body.keys)) {
|
|
244
|
+
if (id.length > MAX_IDEM_KEY_LEN) return false
|
|
245
|
+
if (!isObj(e) || typeof e.key !== 'string' || !/^[0-9a-f]{64}$/.test(e.rootId) || !isInt(e.n)) return false
|
|
246
|
+
if (!(e.sessionId === null || (typeof e.sessionId === 'string' && e.sessionId.length <= MAX_SESSION_ID_LEN))) return false
|
|
247
|
+
if (typeof e.at !== 'number' || !Number.isFinite(e.at) || !Number.isSafeInteger(e.seq) || e.seq < 0) return false
|
|
248
|
+
}
|
|
249
|
+
return true
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Reasons a naming path is "present but not usable" (as opposed to a transient I/O error). */
|
|
253
|
+
const BAD_FILE_CODES = new Set(['ECHROXY_BADFILE', 'ELOOP', 'EISDIR'])
|
|
254
|
+
|
|
255
|
+
/** @returns {{state:'absent'}|{state:'error'}|{state:'invalid'}|{state:'valid',gen:number,sha256:string,body:object}} */
|
|
256
|
+
function readCopy(path, gen, readFile) {
|
|
257
|
+
let text
|
|
258
|
+
try {
|
|
259
|
+
text = readFile(path, MAX_STORE_BYTES)
|
|
260
|
+
} catch (err) {
|
|
261
|
+
if (err?.code === 'ENOENT') return { state: 'absent' }
|
|
262
|
+
return BAD_FILE_CODES.has(err?.code) ? { state: 'invalid' } : { state: 'error' }
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const doc = JSON.parse(text)
|
|
266
|
+
if (!isObj(doc) || doc.version !== VERSION || doc.gen !== gen || typeof doc.sha256 !== 'string') return { state: 'invalid' }
|
|
267
|
+
if (!validBody(doc.body)) return { state: 'invalid' }
|
|
268
|
+
if (digest(doc.version, doc.gen, doc.body) !== doc.sha256) return { state: 'invalid' }
|
|
269
|
+
return { state: 'valid', gen: doc.gen, sha256: doc.sha256, body: doc.body }
|
|
270
|
+
} catch {
|
|
271
|
+
return { state: 'invalid' }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const emptyBody = () => ({ projects: {}, keys: {}, seq: 0 })
|
|
276
|
+
const own = (obj, k) => Object.prototype.hasOwnProperty.call(obj, k)
|
|
277
|
+
// Plain `obj[k] = v` with k === '__proto__' would rewrite the prototype, not add a key.
|
|
278
|
+
const setOwn = (obj, k, v) => Object.defineProperty(obj, k, { value: v, enumerable: true, writable: true, configurable: true })
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* @param {object} opts
|
|
282
|
+
* @param {string} [opts.dir] defaults to the config dir (honours CHROXY_CONFIG_DIR)
|
|
283
|
+
* @param {() => string[]} [opts.liveNames] names of sessions that exist right now
|
|
284
|
+
* @param {() => number} [opts.now] wall clock (idempotency TTL only)
|
|
285
|
+
* @param {{warn?:Function,error?:Function,info?:Function}} [opts.log]
|
|
286
|
+
* @param {number} [opts.maxAttempts] bound on CAS retries
|
|
287
|
+
* @param {object} [opts.deps] test seams: readFile, readdir, linkSync, syncDir, writeSync, onSerialize,
|
|
288
|
+
* afterLoad, maxBytes
|
|
289
|
+
*/
|
|
290
|
+
export function createSessionNameAllocator({
|
|
291
|
+
dir = configDir(),
|
|
292
|
+
liveNames = () => [],
|
|
293
|
+
now = Date.now,
|
|
294
|
+
log = {},
|
|
295
|
+
maxAttempts = DEFAULT_MAX_ATTEMPTS,
|
|
296
|
+
deps = {},
|
|
297
|
+
} = {}) {
|
|
298
|
+
const readFile = deps.readFile ?? defaultReadFile
|
|
299
|
+
const link = deps.linkSync ?? linkSync
|
|
300
|
+
const syncDir = deps.syncDir ?? defaultSyncDir
|
|
301
|
+
const writeBytes = deps.writeSync ?? ((fd, buf, off, len) => writeSync(fd, buf, off, len))
|
|
302
|
+
const listDir = deps.readdir ?? readdirSync
|
|
303
|
+
const afterLoad = deps.afterLoad ?? null
|
|
304
|
+
// The budget can be tightened for tests but never loosened past what a load will accept.
|
|
305
|
+
const maxBytes = Math.min(deps.maxBytes ?? MAX_STORE_BYTES, MAX_STORE_BYTES)
|
|
306
|
+
|
|
307
|
+
// A refused git config makes the project fall back to legacy names: say so once per root.
|
|
308
|
+
const onRefuse = ({ reason, dir: where }) => {
|
|
309
|
+
const k = `${where}\u0000${reason}`
|
|
310
|
+
if (loggedRefusals.has(k)) return
|
|
311
|
+
loggedRefusals.add(k)
|
|
312
|
+
emit('warn', `session names: ${where} fell back to legacy naming (${reason}); its git config is outside the supported subset`, { reason, dir: where })
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Once per allocator per (dir, reason): a closed allocator is polled on every create.
|
|
316
|
+
const loggedFailClosed = new Set()
|
|
317
|
+
const loggedRefusals = new Set()
|
|
318
|
+
|
|
319
|
+
const emit = (level, msg, fields) => {
|
|
320
|
+
try {
|
|
321
|
+
log?.[level]?.(msg, fields)
|
|
322
|
+
} catch { /* a broken logger must not break allocation */ }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const listGens = () => {
|
|
326
|
+
const gens = new Map()
|
|
327
|
+
for (const name of listDir(dir)) {
|
|
328
|
+
const m = FILE_RE.exec(name)
|
|
329
|
+
if (!m) continue
|
|
330
|
+
const g = Number(m[1])
|
|
331
|
+
if (!Number.isSafeInteger(g) || g < 1) continue
|
|
332
|
+
const slot = gens.get(g) ?? { primary: false, mirror: false }
|
|
333
|
+
if (m[2]) slot.mirror = true
|
|
334
|
+
else slot.primary = true
|
|
335
|
+
gens.set(g, slot)
|
|
336
|
+
}
|
|
337
|
+
return gens
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// ---- evidence -------------------------------------------------------
|
|
341
|
+
const load = () => {
|
|
342
|
+
let gens
|
|
343
|
+
try {
|
|
344
|
+
gens = listGens()
|
|
345
|
+
} catch (err) {
|
|
346
|
+
if (err?.code === 'ENOENT') return { kind: 'ok', gen: 0, body: emptyBody() }
|
|
347
|
+
return { kind: 'error', reason: 'io_error' }
|
|
348
|
+
}
|
|
349
|
+
if (gens.size === 0) return { kind: 'ok', gen: 0, body: emptyBody() }
|
|
350
|
+
const top = Math.max(...gens.keys())
|
|
351
|
+
const a = readCopy(join(dir, genName(top, false)), top, readFile)
|
|
352
|
+
const b = readCopy(join(dir, genName(top, true)), top, readFile)
|
|
353
|
+
// Both gone: the store advanced and pruned this generation after we listed. Not corruption.
|
|
354
|
+
if (a.state === 'absent' && b.state === 'absent') return { kind: 'retry' }
|
|
355
|
+
const valid = [a, b].filter((c) => c.state === 'valid')
|
|
356
|
+
if (valid.length === 0) {
|
|
357
|
+
if (a.state === 'error' || b.state === 'error') return { kind: 'error', reason: 'io_error' }
|
|
358
|
+
return { kind: 'closed', reason: 'evidence_lost' }
|
|
359
|
+
}
|
|
360
|
+
if (valid.length === 2 && a.sha256 !== b.sha256) return { kind: 'closed', reason: 'inconsistent' }
|
|
361
|
+
return { kind: 'ok', gen: top, body: structuredClone(valid[0].body) }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const failClosed = (reason) => {
|
|
365
|
+
const k = `${dir}\u0000${reason}`
|
|
366
|
+
if (!loggedFailClosed.has(k)) {
|
|
367
|
+
loggedFailClosed.add(k)
|
|
368
|
+
emit('error', `session-name allocator closed (${reason}); numbered names disabled until the session-names.* files in ${dir} are removed`, { reason })
|
|
369
|
+
}
|
|
370
|
+
return { ok: false, reason }
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const serialize = (gen, body) => {
|
|
374
|
+
deps.onSerialize?.()
|
|
375
|
+
return JSON.stringify({ version: VERSION, gen, body, sha256: digest(VERSION, gen, body) })
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Fit the serialized store into the budget by evicting idempotency records, oldest seq first,
|
|
380
|
+
* never `keep`. The excess is worked out from per-record sizes and ONE batch is evicted, then
|
|
381
|
+
* the exact size is checked once (a re-serialization of a near-cap store costs tens of ms, so
|
|
382
|
+
* it must not happen once per evicted record). Returns the final text, or null (store_full).
|
|
383
|
+
*/
|
|
384
|
+
const fitBudget = (gen, body, keep) => {
|
|
385
|
+
let text = serialize(gen, body)
|
|
386
|
+
let size = Buffer.byteLength(text)
|
|
387
|
+
if (size <= maxBytes) return text
|
|
388
|
+
const victims = Object.entries(body.keys)
|
|
389
|
+
.filter(([id]) => id !== keep)
|
|
390
|
+
.sort((x, y) => x[1].seq - y[1].seq)
|
|
391
|
+
.map(([id, e]) => ({ id, bytes: Buffer.byteLength(JSON.stringify(id)) + Buffer.byteLength(JSON.stringify(e)) + 2 }))
|
|
392
|
+
let next = 0
|
|
393
|
+
while (size > maxBytes) {
|
|
394
|
+
if (next >= victims.length) return null
|
|
395
|
+
let excess = size - maxBytes
|
|
396
|
+
while (excess > 0 && next < victims.length) {
|
|
397
|
+
const v = victims[next++]
|
|
398
|
+
delete body.keys[v.id]
|
|
399
|
+
excess -= v.bytes
|
|
400
|
+
}
|
|
401
|
+
// `excess` is an estimate (separators, the digest is fixed width): confirm exactly, and
|
|
402
|
+
// if it fell short the loop evicts a further batch.
|
|
403
|
+
text = serialize(gen, body)
|
|
404
|
+
size = Buffer.byteLength(text)
|
|
405
|
+
}
|
|
406
|
+
return text
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const tryUnlink = (p) => {
|
|
410
|
+
try { unlinkSync(p) } catch { /* ignore */ }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Write every byte (looping over short writes) to a fresh file and fsync it. */
|
|
414
|
+
const writeTemp = (path, buf) => {
|
|
415
|
+
let fd
|
|
416
|
+
try {
|
|
417
|
+
fd = openSync(path, 'wx', 0o600)
|
|
418
|
+
let off = 0
|
|
419
|
+
while (off < buf.length) {
|
|
420
|
+
const n = writeBytes(fd, buf, off, buf.length - off)
|
|
421
|
+
if (!Number.isInteger(n) || n <= 0 || n > buf.length - off) throw new Error('incomplete write')
|
|
422
|
+
off += n
|
|
423
|
+
}
|
|
424
|
+
fsyncSync(fd)
|
|
425
|
+
const done = fd
|
|
426
|
+
fd = undefined
|
|
427
|
+
closeSync(done)
|
|
428
|
+
} catch (err) {
|
|
429
|
+
if (fd !== undefined) try { closeSync(fd) } catch { /* ignore */ }
|
|
430
|
+
tryUnlink(path)
|
|
431
|
+
throw err
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Publish `text` as generation `gen` by creating BOTH names. Returns 'won' | 'lost'
|
|
437
|
+
* (another writer owns it, or a stale view) | 'unsupported' | 'error'.
|
|
438
|
+
*/
|
|
439
|
+
const publish = (gen, text) => {
|
|
440
|
+
const buf = Buffer.from(text)
|
|
441
|
+
const primary = join(dir, genName(gen, false))
|
|
442
|
+
const mirror = join(dir, genName(gen, true))
|
|
443
|
+
const token = `${process.pid}.${randomBytes(6).toString('hex')}`
|
|
444
|
+
const tmpA = join(dir, `${TMP_PREFIX}${token}.a`)
|
|
445
|
+
const tmpB = join(dir, `${TMP_PREFIX}${token}.b`)
|
|
446
|
+
const dropTemps = () => {
|
|
447
|
+
tryUnlink(tmpA)
|
|
448
|
+
tryUnlink(tmpB)
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
writeTemp(tmpA, buf)
|
|
452
|
+
writeTemp(tmpB, buf)
|
|
453
|
+
} catch (err) {
|
|
454
|
+
emit('warn', `session-name temp write failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
|
|
455
|
+
dropTemps()
|
|
456
|
+
return 'error'
|
|
457
|
+
}
|
|
458
|
+
const classify = (err) => {
|
|
459
|
+
if (err?.code === 'EEXIST') return 'lost'
|
|
460
|
+
if (err?.code === 'EPERM' || err?.code === 'ENOTSUP' || err?.code === 'EOPNOTSUPP' || err?.code === 'ENOSYS') return 'unsupported'
|
|
461
|
+
emit('warn', `session-name publish failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
|
|
462
|
+
return 'error'
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
link(tmpA, primary)
|
|
466
|
+
} catch (err) {
|
|
467
|
+
dropTemps()
|
|
468
|
+
return classify(err)
|
|
469
|
+
}
|
|
470
|
+
try {
|
|
471
|
+
link(tmpB, mirror)
|
|
472
|
+
} catch (err) {
|
|
473
|
+
dropTemps()
|
|
474
|
+
// EEXIST: another writer owns this generation's mirror, so our primary is a loser's debris
|
|
475
|
+
// and is retracted. Any OTHER failure leaves the primary where it is: it may already have
|
|
476
|
+
// been read (and built upon) by a concurrent writer, and retracting a visible generation
|
|
477
|
+
// lets a stale writer re-create it and issue a number the later generation never saw. A
|
|
478
|
+
// primary-only generation is valid under the load rules; the number becomes a gap.
|
|
479
|
+
if (err?.code === 'EEXIST') tryUnlink(primary)
|
|
480
|
+
return classify(err)
|
|
481
|
+
}
|
|
482
|
+
dropTemps()
|
|
483
|
+
try {
|
|
484
|
+
syncDir(dir)
|
|
485
|
+
} catch (err) {
|
|
486
|
+
emit('warn', `session-name directory fsync failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
|
|
487
|
+
return 'error'
|
|
488
|
+
}
|
|
489
|
+
// ABA guard: a newer generation means our view was stale and g+1 had been pruned.
|
|
490
|
+
try {
|
|
491
|
+
if (Math.max(...listGens().keys()) > gen) {
|
|
492
|
+
tryUnlink(primary)
|
|
493
|
+
tryUnlink(mirror)
|
|
494
|
+
return 'lost'
|
|
495
|
+
}
|
|
496
|
+
} catch {
|
|
497
|
+
// Both names exist and may be visible: never retract them. Unconfirmed; the number is a gap.
|
|
498
|
+
return 'error'
|
|
499
|
+
}
|
|
500
|
+
return 'won'
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Remove generations below top-2 and stale temp files. Never touches the top three. */
|
|
504
|
+
const prune = () => {
|
|
505
|
+
try {
|
|
506
|
+
const names = readdirSync(dir)
|
|
507
|
+
let top = 0
|
|
508
|
+
for (const name of names) {
|
|
509
|
+
const m = FILE_RE.exec(name)
|
|
510
|
+
if (m) top = Math.max(top, Number(m[1]))
|
|
511
|
+
}
|
|
512
|
+
for (const name of names) {
|
|
513
|
+
const m = FILE_RE.exec(name)
|
|
514
|
+
if (m) {
|
|
515
|
+
if (Number(m[1]) < top - (KEEP_GENERATIONS - 1)) tryUnlink(join(dir, name))
|
|
516
|
+
} else if (name.startsWith(TMP_PREFIX)) {
|
|
517
|
+
try {
|
|
518
|
+
if (Date.now() - statSync(join(dir, name)).mtimeMs > TMP_STALE_MS) tryUnlink(join(dir, name))
|
|
519
|
+
} catch { /* ignore */ }
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
} catch { /* ignore */ }
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* The CAS loop. `step(state)` returns { done: result } to stop without writing, or
|
|
527
|
+
* { body, keep, result } to publish body as the next generation and return result once durable.
|
|
528
|
+
*/
|
|
529
|
+
const transact = (step) => {
|
|
530
|
+
try {
|
|
531
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
532
|
+
} catch {
|
|
533
|
+
return { ok: false, reason: 'io_error' }
|
|
534
|
+
}
|
|
535
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
536
|
+
const state = load()
|
|
537
|
+
if (state.kind === 'retry') continue
|
|
538
|
+
if (state.kind === 'closed') return failClosed(state.reason)
|
|
539
|
+
if (state.kind === 'error') return { ok: false, reason: state.reason }
|
|
540
|
+
afterLoad?.({ gen: state.gen, attempt })
|
|
541
|
+
const plan = step(state)
|
|
542
|
+
if (plan.done) return plan.done
|
|
543
|
+
const gen = state.gen + 1
|
|
544
|
+
if (gen > MAX_GEN) return { ok: false, reason: 'exhausted' }
|
|
545
|
+
const text = fitBudget(gen, plan.body, plan.keep)
|
|
546
|
+
if (text === null) return { ok: false, reason: 'store_full' }
|
|
547
|
+
const outcome = publish(gen, text)
|
|
548
|
+
prune()
|
|
549
|
+
if (outcome === 'lost') continue
|
|
550
|
+
if (outcome === 'unsupported') return { ok: false, reason: 'unsupported_fs' }
|
|
551
|
+
if (outcome === 'error') return { ok: false, reason: 'write_unconfirmed' }
|
|
552
|
+
return plan.result
|
|
553
|
+
}
|
|
554
|
+
return { ok: false, reason: 'contended' }
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** TTL expiry (by wall clock, applied before lookup). Backwards clocks never expire anything. */
|
|
558
|
+
const expire = (body) => {
|
|
559
|
+
const t = now()
|
|
560
|
+
for (const [id, e] of Object.entries(body.keys)) {
|
|
561
|
+
if (t - e.at > KEY_TTL_MS) delete body.keys[id]
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Keep the newest MAX_KEYS records by seq, always retaining `keep`. */
|
|
566
|
+
const capKeys = (body, keep) => {
|
|
567
|
+
const ids = Object.keys(body.keys)
|
|
568
|
+
if (ids.length <= MAX_KEYS) return
|
|
569
|
+
const victims = ids.filter((id) => id !== keep).sort((x, y) => body.keys[x].seq - body.keys[y].seq)
|
|
570
|
+
for (const id of victims.slice(0, ids.length - MAX_KEYS)) delete body.keys[id]
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ---- API ------------------------------------------------------------
|
|
574
|
+
function allocate({ cwd, idempotencyKey } = {}) {
|
|
575
|
+
if (typeof cwd !== 'string' || cwd.length === 0) throw new TypeError('allocate: cwd must be a non-empty string')
|
|
576
|
+
if (idempotencyKey !== undefined && (typeof idempotencyKey !== 'string' || idempotencyKey.length === 0 || idempotencyKey.length > MAX_IDEM_KEY_LEN)) {
|
|
577
|
+
throw new TypeError('allocate: idempotencyKey must be a non-empty string up to 256 chars')
|
|
578
|
+
}
|
|
579
|
+
let project
|
|
580
|
+
try {
|
|
581
|
+
project = canonicalProjectForCwd(cwd, undefined, onRefuse)
|
|
582
|
+
} catch {
|
|
583
|
+
project = null
|
|
584
|
+
}
|
|
585
|
+
if (!project) return { ok: false, reason: 'non_project' }
|
|
586
|
+
const label = normalizeLabel(project.label)
|
|
587
|
+
if (!label) return { ok: false, reason: 'non_project' }
|
|
588
|
+
const key = keyForLabel(label)
|
|
589
|
+
const root = Array.from(project.root).slice(0, MAX_ROOT_CODE_POINTS).join('')
|
|
590
|
+
// Identity of the FULL realpath: two roots sharing a 512-code-point prefix must not collide.
|
|
591
|
+
const rootId = createHash('sha256').update(project.root).digest('hex')
|
|
592
|
+
|
|
593
|
+
try {
|
|
594
|
+
return transact((state) => {
|
|
595
|
+
let live
|
|
596
|
+
try {
|
|
597
|
+
live = Array.from(liveNames() ?? [], (n) => String(n).normalize('NFC').toLowerCase())
|
|
598
|
+
} catch {
|
|
599
|
+
return { done: { ok: false, reason: 'live_names_failed' } }
|
|
600
|
+
}
|
|
601
|
+
const liveSet = new Set(live)
|
|
602
|
+
const re = new RegExp(`^${escapeRegExp(key)} (\\d+)$`)
|
|
603
|
+
let floor = 0
|
|
604
|
+
for (const name of live) {
|
|
605
|
+
const m = re.exec(name)
|
|
606
|
+
if (!m) continue
|
|
607
|
+
const v = Number(m[1])
|
|
608
|
+
if (!Number.isSafeInteger(v) || v > MAX_LIVE_NUMBER) continue // a typed-in huge number must not exhaust the project
|
|
609
|
+
if (v > floor) floor = v
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const body = state.body
|
|
613
|
+
expire(body)
|
|
614
|
+
const result = (n) => ({ ok: true, name: `${label} ${n}`, label, number: n, key })
|
|
615
|
+
const entry = idempotencyKey !== undefined && own(body.keys, idempotencyKey) ? body.keys[idempotencyKey] : null
|
|
616
|
+
// The same key for another project or root is a conflict only while the reservation is
|
|
617
|
+
// still open. A BOUND record is spent: the key is simply reused (agent-control retries
|
|
618
|
+
// across reconnects with one requestId), and the record is replaced like any other.
|
|
619
|
+
const differs = entry && (entry.key !== key || entry.rootId !== rootId)
|
|
620
|
+
if (differs && entry.sessionId === null) {
|
|
621
|
+
return { done: { ok: false, reason: 'idempotency_key_conflict' } }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
if (entry && !differs) {
|
|
625
|
+
const held = liveSet.has(`${key} ${entry.n}`)
|
|
626
|
+
if (entry.sessionId === null && !held) {
|
|
627
|
+
// A retry of a create whose number was never bound: same number, but only after
|
|
628
|
+
// a fresh generation carrying it is confirmed durable in both copies.
|
|
629
|
+
return { body, keep: idempotencyKey, result: result(entry.n) }
|
|
630
|
+
}
|
|
631
|
+
emit('warn', `duplicate_create_request: idempotency key already ${entry.sessionId !== null ? 'bound to a session' : 'held by a live session'}; allocating a fresh number`, {
|
|
632
|
+
reason: 'duplicate_create_request', key, n: entry.n,
|
|
633
|
+
})
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const stored = own(body.projects, key) ? body.projects[key].next : 1
|
|
637
|
+
let n = Math.max(stored, floor + 1)
|
|
638
|
+
// The floor ignores huge live numbers, but the name itself must still never duplicate a live one.
|
|
639
|
+
let skips = 0
|
|
640
|
+
while (liveSet.has(`${key} ${n}`)) {
|
|
641
|
+
if (++skips > MAX_LIVE_SKIPS) return { done: { ok: false, reason: 'live_collision' } }
|
|
642
|
+
n += 1
|
|
643
|
+
}
|
|
644
|
+
if (n >= Number.MAX_SAFE_INTEGER) return { done: { ok: false, reason: 'exhausted' } }
|
|
645
|
+
setOwn(body.projects, key, { label, root, next: n + 1 })
|
|
646
|
+
if (idempotencyKey !== undefined) {
|
|
647
|
+
body.seq += 1
|
|
648
|
+
setOwn(body.keys, idempotencyKey, { key, rootId, n, sessionId: null, at: now(), seq: body.seq })
|
|
649
|
+
capKeys(body, idempotencyKey)
|
|
650
|
+
}
|
|
651
|
+
return { body, keep: idempotencyKey, result: result(n) }
|
|
652
|
+
})
|
|
653
|
+
} catch (err) {
|
|
654
|
+
emit('error', `session-name allocator internal error: ${err?.message ?? err}`, { reason: 'internal_error' })
|
|
655
|
+
return { ok: false, reason: 'internal_error' }
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function bind(idempotencyKey, sessionId, { number } = {}) {
|
|
660
|
+
if (typeof idempotencyKey !== 'string' || idempotencyKey.length === 0) throw new TypeError('bind: idempotencyKey must be a non-empty string')
|
|
661
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_LEN) {
|
|
662
|
+
throw new TypeError('bind: sessionId must be a non-empty string up to 128 chars')
|
|
663
|
+
}
|
|
664
|
+
if (!isInt(number)) throw new TypeError('bind: { number } (the reserved number being bound) is required')
|
|
665
|
+
try {
|
|
666
|
+
return transact((state) => {
|
|
667
|
+
const body = state.body
|
|
668
|
+
expire(body)
|
|
669
|
+
if (!own(body.keys, idempotencyKey)) return { done: { ok: false, reason: 'unknown_key' } }
|
|
670
|
+
const entry = body.keys[idempotencyKey]
|
|
671
|
+
// A delayed bind must not attach to a replacement reservation for the same key.
|
|
672
|
+
if (entry.n !== number) return { done: { ok: false, reason: 'stale_reservation' } }
|
|
673
|
+
if (entry.sessionId !== null && entry.sessionId !== sessionId) return { done: { ok: false, reason: 'already_bound' } }
|
|
674
|
+
// Same-session retries publish too: `ok` is only ever reported behind a confirmed write.
|
|
675
|
+
entry.sessionId = sessionId
|
|
676
|
+
return { body, keep: idempotencyKey, result: { ok: true } }
|
|
677
|
+
})
|
|
678
|
+
} catch (err) {
|
|
679
|
+
emit('error', `session-name allocator internal error: ${err?.message ?? err}`, { reason: 'internal_error' })
|
|
680
|
+
return { ok: false, reason: 'internal_error' }
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
return { allocate, bind }
|
|
685
|
+
}
|