@antasphere/cli-core 0.6.0 → 0.7.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 +324 -96
- package/dist/auth.d.ts +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/config.d.ts +120 -73
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +207 -109
- package/dist/config.js.map +1 -1
- package/dist/connect-on-demand.d.ts +194 -132
- package/dist/connect-on-demand.d.ts.map +1 -1
- package/dist/connect-on-demand.js +561 -148
- package/dist/connect-on-demand.js.map +1 -1
- package/dist/connect.d.ts +8 -8
- package/dist/connect.d.ts.map +1 -1
- package/dist/index.d.ts +25 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -15
- package/dist/index.js.map +1 -1
- package/dist/kept-keys.d.ts +208 -0
- package/dist/kept-keys.d.ts.map +1 -0
- package/dist/kept-keys.js +484 -0
- package/dist/kept-keys.js.map +1 -0
- package/dist/lock.d.ts +65 -0
- package/dist/lock.d.ts.map +1 -0
- package/dist/lock.js +408 -0
- package/dist/lock.js.map +1 -0
- package/dist/migrate.d.ts +9 -3
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +32 -11
- package/dist/migrate.js.map +1 -1
- package/dist/resolve.d.ts +12 -4
- package/dist/resolve.d.ts.map +1 -1
- package/dist/resolve.js +12 -8
- package/dist/resolve.js.map +1 -1
- package/dist/sign-in.d.ts +266 -0
- package/dist/sign-in.d.ts.map +1 -0
- package/dist/sign-in.js +398 -0
- package/dist/sign-in.js.map +1 -0
- package/package.json +1 -1
- package/src/auth.ts +1 -1
- package/src/config.ts +303 -158
- package/src/connect-on-demand.ts +797 -271
- package/src/connect.ts +8 -8
- package/src/index.ts +40 -27
- package/src/kept-keys.ts +561 -0
- package/src/lock.ts +479 -0
- package/src/migrate.ts +33 -11
- package/src/resolve.ts +20 -15
- package/src/sign-in.ts +601 -0
package/src/lock.ts
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
fstatSync,
|
|
5
|
+
linkSync,
|
|
6
|
+
lstatSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
openSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
renameSync,
|
|
12
|
+
unlinkSync,
|
|
13
|
+
writeFileSync,
|
|
14
|
+
type BigIntStats
|
|
15
|
+
} from 'node:fs';
|
|
16
|
+
import { hostname } from 'node:os';
|
|
17
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
18
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
19
|
+
import { CliConfigError } from './config.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A synchronous, re-entrant, cross-process file lock: the guard every
|
|
23
|
+
* read-modify-write of a config file holds (`updateConfig`), so two commands
|
|
24
|
+
* that both add something both keep it.
|
|
25
|
+
*
|
|
26
|
+
* The lock is a file created exclusively beside the one it guards
|
|
27
|
+
* (`<file>.lock`, 0600) and holding `{ pid, host, token, at }`. A dead
|
|
28
|
+
* holder's lock is taken over instead of waited on: its pid is gone on this
|
|
29
|
+
* host, it is older than `staleMs`, or it is empty or partial (its holder
|
|
30
|
+
* died between creating and writing it) and older than `emptyStaleMs`. A
|
|
31
|
+
* live holder is waited on with a short synchronous back-off up to
|
|
32
|
+
* `timeoutMs`, then the wait fails with a `CliConfigError` naming the holder
|
|
33
|
+
* and the lock file. Release removes the lock only while it still holds this
|
|
34
|
+
* holder's token.
|
|
35
|
+
*
|
|
36
|
+
* A lock is judged on ONE file: a look opens it and takes its identity
|
|
37
|
+
* (device, inode, mtime) and its bytes from that one descriptor, so a lock
|
|
38
|
+
* released and created again between two calls is never judged on the old
|
|
39
|
+
* holder's pid and the new file's age. The takers of one dead lock take
|
|
40
|
+
* turns through markers named for that lock and their turn
|
|
41
|
+
* (`<lockPath>.break.<dev>-<ino>.<n>`, the same holder shape): the taker
|
|
42
|
+
* that creates the marker of its turn looks at the lock again and moves it
|
|
43
|
+
* aside only while it is still the very file it judged, still stale; the
|
|
44
|
+
* moved file is removed only when it is that file, and any other is put
|
|
45
|
+
* back. A live taker's marker (younger than 10 s) is waited on like any
|
|
46
|
+
* holder; a dead taker's is skipped, never moved, and the next turn taken.
|
|
47
|
+
* No taker ever moves, links or removes a marker it did not create, and a
|
|
48
|
+
* marker of another lock never blocks this one. What take-overs leave beside
|
|
49
|
+
* the lock is removed by a later holder once it is older than `staleMs`,
|
|
50
|
+
* never sooner.
|
|
51
|
+
*
|
|
52
|
+
* `withFileLockAsync` is the same lock file protocol for work that spans the
|
|
53
|
+
* network (the single-flight mint of a kept key): its waits are awaited
|
|
54
|
+
* instead of blocking the thread, and it is not re-entrant.
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
export interface FileLockOptions {
|
|
58
|
+
/** How long a live holder is waited on before the wait fails. Default 10 000 ms. */
|
|
59
|
+
timeoutMs?: number;
|
|
60
|
+
/** A lock older than this is a dead holder's, whoever it names. Default 30 000 ms. */
|
|
61
|
+
staleMs?: number;
|
|
62
|
+
/** An empty or partial lock older than this is a dead holder's. Default 2 000 ms. */
|
|
63
|
+
emptyStaleMs?: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Holder {
|
|
67
|
+
pid: number;
|
|
68
|
+
host: string;
|
|
69
|
+
token: string;
|
|
70
|
+
at: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Which file a path held when it was looked at: two files are one only when all three match. */
|
|
74
|
+
interface Identity {
|
|
75
|
+
dev: bigint;
|
|
76
|
+
ino: bigint;
|
|
77
|
+
mtimeNs: bigint;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What a look at someone else's lock (or marker) saw, all through one descriptor. */
|
|
81
|
+
interface Seen extends Identity {
|
|
82
|
+
/** The mtime, for the age rules. */
|
|
83
|
+
mtimeMs: number;
|
|
84
|
+
raw: Buffer;
|
|
85
|
+
/** The holder its bytes name, when they parse into one. */
|
|
86
|
+
holder: Holder | undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A marker older than this is a dead taker's, whoever it names: a take-over lasts a few calls. */
|
|
90
|
+
const BREAK_STALE_MS = 10_000;
|
|
91
|
+
|
|
92
|
+
/** How many takers of one dead lock may die in turn before a waiter waits as on a live holder. */
|
|
93
|
+
const MAX_TAKERS = 64;
|
|
94
|
+
|
|
95
|
+
/** The lock paths this process holds, with their nesting depth. */
|
|
96
|
+
const held = new Map<string, number>();
|
|
97
|
+
|
|
98
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
99
|
+
|
|
100
|
+
/** Block this thread for `ms` milliseconds: the waits of a synchronous API. */
|
|
101
|
+
export function sleepSync(ms: number): void {
|
|
102
|
+
Atomics.wait(pause, 0, 0, ms);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The `code` of a Node system error (`ENOENT`, `EEXIST`, …), if it has one. */
|
|
106
|
+
export function errorCode(e: unknown): string | undefined {
|
|
107
|
+
if (typeof e !== 'object' || e === null || !('code' in e)) return undefined;
|
|
108
|
+
return typeof e.code === 'string' ? e.code : undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Run `fn` holding the lock file `lockPath`, created when free, waited on
|
|
113
|
+
* while a live holder has it, taken over when its holder is dead, and
|
|
114
|
+
* released when `fn` returns or throws. Re-entrant within one process: a
|
|
115
|
+
* nested call on a path this process holds runs `fn` at once. `fn` is
|
|
116
|
+
* synchronous; the lock is released as soon as it returns.
|
|
117
|
+
*/
|
|
118
|
+
export function withFileLock<T>(lockPath: string, fn: () => T, opts: FileLockOptions = {}): T {
|
|
119
|
+
const key = resolve(lockPath);
|
|
120
|
+
const depth = held.get(key);
|
|
121
|
+
if (depth !== undefined) {
|
|
122
|
+
held.set(key, depth + 1);
|
|
123
|
+
try {
|
|
124
|
+
return fn();
|
|
125
|
+
} finally {
|
|
126
|
+
held.set(key, depth);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const token = acquire(lockPath, opts);
|
|
130
|
+
held.set(key, 1);
|
|
131
|
+
try {
|
|
132
|
+
return fn();
|
|
133
|
+
} finally {
|
|
134
|
+
held.delete(key);
|
|
135
|
+
release(lockPath, token);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Run the asynchronous `fn` holding the lock file `lockPath`: the protocol of
|
|
141
|
+
* `withFileLock` (created when free, waited on while a live holder has it,
|
|
142
|
+
* taken over when its holder is dead, released by token when `fn` settles),
|
|
143
|
+
* with the waits awaited, so the lock may span network calls. NOT re-entrant:
|
|
144
|
+
* two calls of one process on one path take turns like two processes, and a
|
|
145
|
+
* nested call on a path this call holds waits for itself until `timeoutMs`.
|
|
146
|
+
*/
|
|
147
|
+
export async function withFileLockAsync<T>(
|
|
148
|
+
lockPath: string,
|
|
149
|
+
fn: () => Promise<T>,
|
|
150
|
+
opts: FileLockOptions = {}
|
|
151
|
+
): Promise<T> {
|
|
152
|
+
const wait = startWait(opts);
|
|
153
|
+
for (;;) {
|
|
154
|
+
const step = attempt(lockPath, wait);
|
|
155
|
+
if (step === 'acquired') break;
|
|
156
|
+
if (step === 'again') continue;
|
|
157
|
+
if (Date.now() >= wait.deadline) throw lockedError(lockPath, step.holder);
|
|
158
|
+
await delay(wait.backoff);
|
|
159
|
+
wait.backoff = Math.min(wait.backoff * 2, 50);
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
return await fn();
|
|
163
|
+
} finally {
|
|
164
|
+
release(lockPath, wait.token);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** One acquisition in progress: who we are, until when we wait, the next pause. */
|
|
169
|
+
interface Wait {
|
|
170
|
+
host: string;
|
|
171
|
+
token: string;
|
|
172
|
+
deadline: number;
|
|
173
|
+
staleMs: number;
|
|
174
|
+
emptyStaleMs: number;
|
|
175
|
+
backoff: number;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function startWait(opts: FileLockOptions): Wait {
|
|
179
|
+
return {
|
|
180
|
+
host: hostname(),
|
|
181
|
+
token: randomUUID(),
|
|
182
|
+
deadline: Date.now() + (opts.timeoutMs ?? 10_000),
|
|
183
|
+
staleMs: opts.staleMs ?? 30_000,
|
|
184
|
+
emptyStaleMs: opts.emptyStaleMs ?? 2_000,
|
|
185
|
+
backoff: 10
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** What a lock or a marker of this process holds. */
|
|
190
|
+
function holderText(host: string, token: string): string {
|
|
191
|
+
const holder: Holder = { pid: process.pid, host, token, at: new Date().toISOString() };
|
|
192
|
+
return JSON.stringify(holder);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* One try at the lock: `acquired`; `again` when it is worth trying again at
|
|
197
|
+
* once (it was released between our try and our look, a dead holder's lock
|
|
198
|
+
* was moved out of the way, or a taker's marker went meanwhile); otherwise
|
|
199
|
+
* the live lock to wait on.
|
|
200
|
+
*/
|
|
201
|
+
function attempt(lockPath: string, wait: Wait): 'acquired' | 'again' | Seen {
|
|
202
|
+
if (create(lockPath, holderText(wait.host, wait.token))) {
|
|
203
|
+
sweep(lockPath, wait.staleMs);
|
|
204
|
+
return 'acquired';
|
|
205
|
+
}
|
|
206
|
+
const seen = look(lockPath);
|
|
207
|
+
if (!seen) return 'again';
|
|
208
|
+
if (!isStale(seen, wait.host, wait.staleMs, wait.emptyStaleMs)) return seen;
|
|
209
|
+
return takeOver(lockPath, seen, wait);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function acquire(lockPath: string, opts: FileLockOptions): string {
|
|
213
|
+
const wait = startWait(opts);
|
|
214
|
+
for (;;) {
|
|
215
|
+
const step = attempt(lockPath, wait);
|
|
216
|
+
if (step === 'acquired') return wait.token;
|
|
217
|
+
if (step === 'again') continue;
|
|
218
|
+
if (Date.now() >= wait.deadline) throw lockedError(lockPath, step.holder);
|
|
219
|
+
sleepSync(wait.backoff);
|
|
220
|
+
wait.backoff = Math.min(wait.backoff * 2, 50);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Create the lock (or a marker) exclusively and write its holder; false when it already exists. */
|
|
225
|
+
function create(path: string, content: string): boolean {
|
|
226
|
+
let fd: number;
|
|
227
|
+
try {
|
|
228
|
+
fd = openSync(path, 'wx', 0o600);
|
|
229
|
+
} catch (e) {
|
|
230
|
+
const code = errorCode(e);
|
|
231
|
+
if (code === 'EEXIST') return false;
|
|
232
|
+
if (code !== 'ENOENT') throw e;
|
|
233
|
+
// The directory is not there yet: make it, as every write does.
|
|
234
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
235
|
+
try {
|
|
236
|
+
fd = openSync(path, 'wx', 0o600);
|
|
237
|
+
} catch (again) {
|
|
238
|
+
if (errorCode(again) === 'EEXIST') return false;
|
|
239
|
+
throw again;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
writeFileSync(fd, content);
|
|
244
|
+
} catch (e) {
|
|
245
|
+
// An empty lock of ours would hold everyone for `emptyStaleMs`.
|
|
246
|
+
closeSync(fd);
|
|
247
|
+
try {
|
|
248
|
+
unlinkSync(path);
|
|
249
|
+
} catch {
|
|
250
|
+
// The write's own error is the one to report.
|
|
251
|
+
}
|
|
252
|
+
throw e;
|
|
253
|
+
}
|
|
254
|
+
closeSync(fd);
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function identityOf(stats: BigIntStats): Identity {
|
|
259
|
+
return { dev: stats.dev, ino: stats.ino, mtimeNs: stats.mtimeNs };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Whether two looks saw one file: the same device, the same inode, the same mtime. */
|
|
263
|
+
function sameFile(a: Identity, b: Identity): boolean {
|
|
264
|
+
return a.dev === b.dev && a.ino === b.ino && a.mtimeNs === b.mtimeNs;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Look at someone else's lock (or marker) through ONE descriptor: the
|
|
269
|
+
* file's identity and its bytes come from the same file, whatever happens to
|
|
270
|
+
* the path meanwhile. Undefined when it is gone (just released).
|
|
271
|
+
*/
|
|
272
|
+
function look(path: string): Seen | undefined {
|
|
273
|
+
let fd: number;
|
|
274
|
+
try {
|
|
275
|
+
fd = openSync(path, 'r');
|
|
276
|
+
} catch (e) {
|
|
277
|
+
if (errorCode(e) === 'ENOENT') return undefined;
|
|
278
|
+
throw e;
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
const stats = fstatSync(fd, { bigint: true });
|
|
282
|
+
const raw = readFileSync(fd);
|
|
283
|
+
return {
|
|
284
|
+
...identityOf(stats),
|
|
285
|
+
mtimeMs: Number(stats.mtimeMs),
|
|
286
|
+
raw,
|
|
287
|
+
holder: parseHolder(raw.toString('utf8'))
|
|
288
|
+
};
|
|
289
|
+
} finally {
|
|
290
|
+
closeSync(fd);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** The holder a lock names, or undefined when it does not parse into one (empty, partial, foreign). */
|
|
295
|
+
function parseHolder(text: string): Holder | undefined {
|
|
296
|
+
let value: unknown;
|
|
297
|
+
try {
|
|
298
|
+
value = JSON.parse(text);
|
|
299
|
+
} catch {
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
|
302
|
+
if (typeof value !== 'object' || value === null) return undefined;
|
|
303
|
+
const { pid, host, token, at } = value as Record<string, unknown>;
|
|
304
|
+
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return undefined;
|
|
305
|
+
if (typeof host !== 'string' || typeof token !== 'string' || typeof at !== 'string') return undefined;
|
|
306
|
+
return { pid, host, token, at };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function isStale(seen: Seen, host: string, staleMs: number, emptyStaleMs: number): boolean {
|
|
310
|
+
const age = Date.now() - seen.mtimeMs;
|
|
311
|
+
if (age > staleMs) return true;
|
|
312
|
+
if (!seen.holder) return age > emptyStaleMs;
|
|
313
|
+
return seen.holder.host === host && !pidAlive(seen.holder.pid);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** A pid is alive when signal 0 reaches it, or reaches a process we may not signal (EPERM). */
|
|
317
|
+
function pidAlive(pid: number): boolean {
|
|
318
|
+
try {
|
|
319
|
+
process.kill(pid, 0);
|
|
320
|
+
return true;
|
|
321
|
+
} catch (e) {
|
|
322
|
+
return errorCode(e) === 'EPERM';
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Take over the lock judged stale on the look `seen`, one taker at a time:
|
|
328
|
+
* the takers of that file take turns through markers named for it (its
|
|
329
|
+
* device and inode, not its mtime: a lock created empty and written later
|
|
330
|
+
* keeps its inode) and for their turn, `<lockPath>.break.<dev>-<ino>.<n>`.
|
|
331
|
+
* Holding the marker of its turn, a taker looks at the lock again and moves
|
|
332
|
+
* it aside only while it is still the very file judged, and still stale on a
|
|
333
|
+
* fresh judgement. A live taker's marker is waited on; a dead taker's is left
|
|
334
|
+
* where it is, and the next turn tried. Answers `again` when the acquire is
|
|
335
|
+
* worth trying again at once (the lock is gone or was removed, or a marker
|
|
336
|
+
* went meanwhile), or the lock to wait on (a live taker holds a turn, every
|
|
337
|
+
* turn is a dead taker's, the lock is another file now or no longer stale,
|
|
338
|
+
* or a moved file was put back).
|
|
339
|
+
*/
|
|
340
|
+
function takeOver(lockPath: string, seen: Seen, wait: Wait): 'again' | Seen {
|
|
341
|
+
for (let n = 0; n < MAX_TAKERS; n += 1) {
|
|
342
|
+
const marker = `${lockPath}.break.${seen.dev}-${seen.ino}.${n}`;
|
|
343
|
+
const token = randomUUID();
|
|
344
|
+
if (create(marker, holderText(wait.host, token))) {
|
|
345
|
+
try {
|
|
346
|
+
const now = look(lockPath);
|
|
347
|
+
if (!now) return 'again';
|
|
348
|
+
if (!sameFile(now, seen) || !isStale(now, wait.host, wait.staleMs, wait.emptyStaleMs)) return now;
|
|
349
|
+
const moved = moveAside(lockPath, now);
|
|
350
|
+
if (moved === 'removed' || moved === 'gone') return 'again';
|
|
351
|
+
return look(lockPath) ?? 'again';
|
|
352
|
+
} finally {
|
|
353
|
+
release(marker, token);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const taker = look(marker);
|
|
357
|
+
if (!taker) return 'again';
|
|
358
|
+
// A live taker younger than 10 s is waited on like any holder. A dead taker's marker is never
|
|
359
|
+
// moved: it stays where it is, and the next turn is tried.
|
|
360
|
+
if (!isStale(taker, wait.host, BREAK_STALE_MS, wait.emptyStaleMs)) return seen;
|
|
361
|
+
}
|
|
362
|
+
return seen;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Move a lock judged dead (`judged`, the look it was judged on) out of the
|
|
367
|
+
* way: renamed to `<path>.<ms>.<uuid>.stale` (the time of the move in its
|
|
368
|
+
* name), then removed only when the moved file is that very file (the same
|
|
369
|
+
* device, inode and mtime). Any other file moved by mistake is put back.
|
|
370
|
+
* Answers `removed`, `gone` (nothing was there to move), `restored` (put
|
|
371
|
+
* back), or `left` (it could not be put back).
|
|
372
|
+
*/
|
|
373
|
+
function moveAside(path: string, judged: Identity): 'removed' | 'gone' | 'restored' | 'left' {
|
|
374
|
+
const moved = `${path}.${Date.now()}.${randomUUID()}.stale`;
|
|
375
|
+
try {
|
|
376
|
+
renameSync(path, moved);
|
|
377
|
+
} catch (e) {
|
|
378
|
+
if (errorCode(e) === 'ENOENT') return 'gone';
|
|
379
|
+
throw e;
|
|
380
|
+
}
|
|
381
|
+
if (sameFile(identityOf(lstatSync(moved, { bigint: true })), judged)) {
|
|
382
|
+
unlinkSync(moved);
|
|
383
|
+
return 'removed';
|
|
384
|
+
}
|
|
385
|
+
try {
|
|
386
|
+
linkSync(moved, path);
|
|
387
|
+
} catch (e) {
|
|
388
|
+
if (errorCode(e) !== 'EEXIST') throw e;
|
|
389
|
+
// Another file took the path meanwhile, so the moved one cannot go back, and it may be a live
|
|
390
|
+
// holder's: it is never unlinked here, it stays where it is (`<path>.<ms>.<uuid>.stale`) until a
|
|
391
|
+
// later holder sweeps it, once older than `staleMs`. The path can only change under a taker that
|
|
392
|
+
// holds its marker when a holder judged dead by age was in fact alive: the lock's (older than
|
|
393
|
+
// `staleMs`, or empty and older than `emptyStaleMs`), letting go in between, or another taker's
|
|
394
|
+
// (its marker older than 10 s), still taking the lock over.
|
|
395
|
+
return 'left';
|
|
396
|
+
}
|
|
397
|
+
// Back in place: the moved name is a second link to the same file, and goes.
|
|
398
|
+
unlinkSync(moved);
|
|
399
|
+
return 'restored';
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** A take-over marker, after `<lock>.`: `break.<dev>-<ino>.<n>`. */
|
|
403
|
+
const MARKER_NAME = /^break\.\d+-\d+\.\d+$/;
|
|
404
|
+
|
|
405
|
+
/** A lock moved aside, after `<lock>.`: `<ms>.<uuid>.stale`, the time of the move in its name. */
|
|
406
|
+
const MOVED_NAME = /^(\d+)\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.stale$/;
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Remove what take-overs left beside the lock just acquired, once it is older
|
|
410
|
+
* than `staleMs` (the age at which any lock is a dead holder's), never
|
|
411
|
+
* younger: the markers (`<lock>.break.<dev>-<ino>.<n>`, aged by their mtime:
|
|
412
|
+
* a marker is written once, at its creation) and the locks moved aside
|
|
413
|
+
* (`<lock>.<ms>.<uuid>.stale`, aged by the time in their name: a moved file
|
|
414
|
+
* keeps the mtime of the lock it was). Removing a marker is safe here: the
|
|
415
|
+
* sweeper holds the lock, so every marker beside it is of a lock that is
|
|
416
|
+
* gone. Nothing else is ever removed, and nothing here throws: a directory
|
|
417
|
+
* that cannot be read, an entry gone meanwhile or one that cannot be removed
|
|
418
|
+
* is skipped, and the next holder looks again.
|
|
419
|
+
*/
|
|
420
|
+
function sweep(lockPath: string, staleMs: number): void {
|
|
421
|
+
const dir = dirname(lockPath);
|
|
422
|
+
const prefix = `${basename(lockPath)}.`;
|
|
423
|
+
let names: string[];
|
|
424
|
+
try {
|
|
425
|
+
names = readdirSync(dir);
|
|
426
|
+
} catch {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const now = Date.now();
|
|
430
|
+
for (const name of names) {
|
|
431
|
+
if (!name.startsWith(prefix)) continue;
|
|
432
|
+
const rest = name.slice(prefix.length);
|
|
433
|
+
const path = join(dir, name);
|
|
434
|
+
let at: number;
|
|
435
|
+
if (MARKER_NAME.test(rest)) {
|
|
436
|
+
try {
|
|
437
|
+
at = lstatSync(path).mtimeMs;
|
|
438
|
+
} catch {
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
} else {
|
|
442
|
+
const moved = MOVED_NAME.exec(rest);
|
|
443
|
+
if (!moved) continue;
|
|
444
|
+
at = Number(moved[1]);
|
|
445
|
+
}
|
|
446
|
+
if (!(now - at > staleMs)) continue;
|
|
447
|
+
try {
|
|
448
|
+
unlinkSync(path);
|
|
449
|
+
} catch {
|
|
450
|
+
// Gone meanwhile, or not an entry this holder can remove: the next holder looks again.
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Remove a lock (or a marker) only while it still holds our token; one already gone is fine. */
|
|
456
|
+
function release(path: string, token: string): void {
|
|
457
|
+
let text: string;
|
|
458
|
+
try {
|
|
459
|
+
text = readFileSync(path, 'utf8');
|
|
460
|
+
} catch (e) {
|
|
461
|
+
if (errorCode(e) === 'ENOENT') return;
|
|
462
|
+
throw e;
|
|
463
|
+
}
|
|
464
|
+
if (parseHolder(text)?.token !== token) return;
|
|
465
|
+
try {
|
|
466
|
+
unlinkSync(path);
|
|
467
|
+
} catch (e) {
|
|
468
|
+
if (errorCode(e) !== 'ENOENT') throw e;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function lockedError(lockPath: string, holder: Holder | undefined): CliConfigError {
|
|
473
|
+
const file = lockPath.replace(/\.lock$/, '');
|
|
474
|
+
const by = holder ? `process ${holder.pid} on ${holder.host} since ${holder.at}` : 'an unknown process';
|
|
475
|
+
return new CliConfigError(
|
|
476
|
+
`The config file ${file} is locked by ${by} (${lockPath}). If no command of this CLI is running, ` +
|
|
477
|
+
'delete that lock file, then retry.'
|
|
478
|
+
);
|
|
479
|
+
}
|
package/src/migrate.ts
CHANGED
|
@@ -3,9 +3,9 @@ import { join } from 'node:path';
|
|
|
3
3
|
import {
|
|
4
4
|
assertToolNamespace,
|
|
5
5
|
configPath,
|
|
6
|
-
loadConfig,
|
|
7
6
|
parseConfig,
|
|
8
|
-
|
|
7
|
+
updateConfig,
|
|
8
|
+
type CliConfig,
|
|
9
9
|
type CliEnv
|
|
10
10
|
} from './config.js';
|
|
11
11
|
|
|
@@ -31,19 +31,27 @@ export interface MigrationResult {
|
|
|
31
31
|
to?: string;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
35
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
34
38
|
/**
|
|
35
39
|
* Imports iff (a) the tool has NO profiles in the shared home yet, and
|
|
36
|
-
* (b) the legacy file exists and holds at least one profile
|
|
37
|
-
*
|
|
38
|
-
*
|
|
40
|
+
* (b) the legacy file exists and holds at least one profile that is a plain
|
|
41
|
+
* object. Only those come across, so the shared file stays one the strict
|
|
42
|
+
* loader reads: a list of profiles, or a profile that is not an object, is
|
|
43
|
+
* left behind. Anything else — no home, no legacy file, empty/corrupt legacy
|
|
44
|
+
* content, no profile that is an object, or a shared-home config already
|
|
45
|
+
* carrying profiles — is a no-op that writes nothing. The
|
|
46
|
+
* check of (a) and the import are one `updateConfig` on the shared file, so
|
|
47
|
+
* a command writing its first profile meanwhile is never overwritten; a
|
|
48
|
+
* shared file that does not parse is a `CliConfigError`, never imported over.
|
|
39
49
|
*/
|
|
40
50
|
export function migrateLegacyConfig(env: CliEnv, spec: LegacyMigrationSpec): MigrationResult {
|
|
41
51
|
assertToolNamespace(spec.tool);
|
|
42
52
|
assertToolNamespace(spec.legacyDir);
|
|
43
53
|
const to = configPath(env, spec.tool);
|
|
44
54
|
if (!to) return { migrated: false };
|
|
45
|
-
const current = loadConfig(env, spec.tool);
|
|
46
|
-
if (Object.keys(current.profiles).length > 0) return { migrated: false };
|
|
47
55
|
const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
|
|
48
56
|
if (!base) return { migrated: false };
|
|
49
57
|
const from = join(base, spec.legacyDir, 'config.json');
|
|
@@ -54,8 +62,22 @@ export function migrateLegacyConfig(env: CliEnv, spec: LegacyMigrationSpec): Mig
|
|
|
54
62
|
} catch {
|
|
55
63
|
return { migrated: false };
|
|
56
64
|
}
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
65
|
+
const parsed = parseConfig(raw);
|
|
66
|
+
// Only the profiles that are plain objects come across: the shared file must stay one the strict
|
|
67
|
+
// loader reads (a list of profiles, or a profile that is a string, is no profile).
|
|
68
|
+
const kept = isPlainObject(parsed.profiles)
|
|
69
|
+
? Object.entries(parsed.profiles).filter(([, profile]) => isPlainObject(profile))
|
|
70
|
+
: [];
|
|
71
|
+
if (kept.length === 0) return { migrated: false };
|
|
72
|
+
const legacy: CliConfig = {
|
|
73
|
+
...(parsed.activeProfile !== undefined ? { activeProfile: parsed.activeProfile } : {}),
|
|
74
|
+
profiles: Object.fromEntries(kept)
|
|
75
|
+
};
|
|
76
|
+
let migrated = false;
|
|
77
|
+
updateConfig(env, spec.tool, (draft) => {
|
|
78
|
+
if (Object.keys(draft.profiles).length > 0) return;
|
|
79
|
+
migrated = true;
|
|
80
|
+
return legacy;
|
|
81
|
+
});
|
|
82
|
+
return migrated ? { migrated: true, from, to } : { migrated: false };
|
|
61
83
|
}
|
package/src/resolve.ts
CHANGED
|
@@ -78,7 +78,7 @@ export function sameInstance(a: string, b: string): boolean {
|
|
|
78
78
|
/**
|
|
79
79
|
* The name an instance URL's profile gets when nothing named it: `cloud`
|
|
80
80
|
* for the tool's cloud URL, else the host with its port
|
|
81
|
-
* (`share.
|
|
81
|
+
* (`share.example.com`, `localhost:3400`). The person may rename it.
|
|
82
82
|
*/
|
|
83
83
|
export function profileNameFor(url: string, cloudUrl?: string | undefined): string {
|
|
84
84
|
if (cloudUrl && sameInstance(url, cloudUrl)) return CLOUD_PROFILE;
|
|
@@ -129,23 +129,28 @@ function profileAt(
|
|
|
129
129
|
}
|
|
130
130
|
|
|
131
131
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
* profile
|
|
132
|
+
* The name a new profile at an instance gets, one nothing in `config` has:
|
|
133
|
+
* `cloud` for the cloud URL, else the host; when that name is taken, the
|
|
134
|
+
* host, then `<host>-2`, `<host>-3`, … so a key is never written onto a
|
|
135
|
+
* profile that is not this instance's. The name `selectProfile` gives the
|
|
136
|
+
* profile it makes in memory; a hub file's new login is named the same way.
|
|
137
137
|
*/
|
|
138
|
-
function
|
|
139
|
-
config: CliConfig,
|
|
140
|
-
url: string,
|
|
141
|
-
cloudUrl: string | undefined
|
|
142
|
-
): { name: string; profile: CliProfile } {
|
|
138
|
+
export function freshProfileName(config: CliConfig, url: string, cloudUrl?: string | undefined): string {
|
|
143
139
|
const host = profileNameFor(url);
|
|
144
140
|
let name = [profileNameFor(url, cloudUrl), host].find((c) => !(c in config.profiles));
|
|
145
141
|
for (let n = 2; name === undefined; n += 1) {
|
|
146
142
|
if (!(`${host}-${n}` in config.profiles)) name = `${host}-${n}`;
|
|
147
143
|
}
|
|
148
|
-
return
|
|
144
|
+
return name;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A profile made in memory for an instance nothing on disk names, under `freshProfileName`. */
|
|
148
|
+
function freshProfileAt(
|
|
149
|
+
config: CliConfig,
|
|
150
|
+
url: string,
|
|
151
|
+
cloudUrl: string | undefined
|
|
152
|
+
): { name: string; profile: CliProfile } {
|
|
153
|
+
return { name: freshProfileName(config, url, cloudUrl), profile: { baseUrl: normalizeUrl(url) } };
|
|
149
154
|
}
|
|
150
155
|
|
|
151
156
|
/** The rule that picked the profile. */
|
|
@@ -157,8 +162,8 @@ export interface SelectedProfile extends ResolvedProfile {
|
|
|
157
162
|
/**
|
|
158
163
|
* true = the profile is not on disk yet: it was made in memory for the
|
|
159
164
|
* instance URL given, or it is the implicit cloud profile, under a name
|
|
160
|
-
* no profile on disk has.
|
|
161
|
-
*
|
|
165
|
+
* no profile on disk has. The first kept key `connectOnDemand` stores
|
|
166
|
+
* writes it; selection never does.
|
|
162
167
|
*/
|
|
163
168
|
created: boolean;
|
|
164
169
|
}
|
|
@@ -238,7 +243,7 @@ export interface ResolveBaseUrlOptions {
|
|
|
238
243
|
profile?: CliProfile | undefined;
|
|
239
244
|
/**
|
|
240
245
|
* The tool's cloud home, the last fallback: every CLI that has a cloud
|
|
241
|
-
* instance ships it (`https://
|
|
246
|
+
* instance ships it (`https://tool.example.com`), so a clean
|
|
242
247
|
* machine with an `antasphere login` needs no flag. A tool with none (a
|
|
243
248
|
* template placeholder) errors with `missingMessage` as before.
|
|
244
249
|
*/
|