@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.4
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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +431 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +49562 -0
- package/dist/attachments.d.ts +211 -0
- package/dist/attachments.js +819 -0
- package/dist/build-manifest.json +131 -0
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +672 -0
- package/dist/files.d.ts +123 -0
- package/dist/files.js +365 -0
- package/dist/git.d.ts +87 -0
- package/dist/git.js +1093 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +25 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +277 -0
- package/dist/operations.d.ts +23 -0
- package/dist/operations.js +275 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +290 -0
- package/dist/schedules.d.ts +69 -0
- package/dist/schedules.js +244 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +1780 -0
- package/dist/store.d.ts +176 -0
- package/dist/store.js +385 -0
- package/dist/terminals.d.ts +157 -0
- package/dist/terminals.js +487 -0
- package/dist/worktrees.d.ts +41 -0
- package/dist/worktrees.js +246 -0
- package/package.json +159 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +870 -0
- package/src/conversation.ts +837 -0
- package/src/files.ts +459 -0
- package/src/git.ts +1045 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +11 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +292 -0
- package/src/operations.ts +300 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +422 -0
- package/src/schedules.ts +294 -0
- package/src/server.ts +2056 -0
- package/src/store.ts +448 -0
- package/src/terminals.ts +591 -0
- package/src/worktrees.ts +287 -0
package/src/lifecycle.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { replaceFile } from './lock.js';
|
|
5
|
+
import { RpcError } from './rpc-error.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The lifecycle journal (docs/protocol/alp-json-rpc-v1.md §12.7): one record per mutation of a session's
|
|
9
|
+
* native conversation (fork, rewind; later reload and live configure), keyed by resource, operation and
|
|
10
|
+
* the client's requestId. A mutation crosses the native runtime and alpd's own files, which no rename
|
|
11
|
+
* makes atomic, so it is journaled before the native step and replayed from the journal:
|
|
12
|
+
*
|
|
13
|
+
* prepared → written before the native step; nothing native happened yet, or it is in flight.
|
|
14
|
+
* applied → the native step answered; `native` holds what it made. alpd's own commit may follow.
|
|
15
|
+
* committed → alpd's commit is on disk; `result` answers every repeat of the request.
|
|
16
|
+
* failed → the native runtime refused it for certain; `error` answers every repeat.
|
|
17
|
+
* unknown → the native runtime may or may not have acted (a crash or a lost answer after prepared).
|
|
18
|
+
*
|
|
19
|
+
* A start of alpd turns `prepared` into `unknown` (never sends the native step again) and rolls `applied`
|
|
20
|
+
* forward with the operation's commit, which must therefore be idempotent. Refusals before `prepared`
|
|
21
|
+
* (validation, busy, stale) record nothing, so the same requestId may be tried again. As the rest of
|
|
22
|
+
* alpd's store, a resolved write survives a crash of alpd, not a power loss (no fsync).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export type LifecycleState = 'prepared' | 'applied' | 'committed' | 'failed' | 'unknown';
|
|
26
|
+
|
|
27
|
+
export type LifecycleEntry<Plan = any, Native = any, Result = any> = {
|
|
28
|
+
version: 1;
|
|
29
|
+
key: string;
|
|
30
|
+
/** The resource the operation changes or reads: a root session id. */
|
|
31
|
+
resource: string;
|
|
32
|
+
operation: string;
|
|
33
|
+
requestId: string;
|
|
34
|
+
/** A digest of the request; another payload under the same requestId is a conflict. */
|
|
35
|
+
fingerprint: string;
|
|
36
|
+
/** Unique attempt, so a retained completion witness cannot match a reused journal key. */
|
|
37
|
+
attemptId?: string;
|
|
38
|
+
state: LifecycleState;
|
|
39
|
+
/** Startup has observed this unknown outcome. It remains unknown for retries and audit. */
|
|
40
|
+
recoverySeenAt?: string;
|
|
41
|
+
/** What prepare decided; everything commit needs, so a restart can roll the operation forward. */
|
|
42
|
+
plan: Plan;
|
|
43
|
+
native?: Native;
|
|
44
|
+
result?: Result;
|
|
45
|
+
error?: { code: number; message: string; data?: unknown };
|
|
46
|
+
createdAt: string;
|
|
47
|
+
updatedAt: string;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Terminal entries are kept this long after their last write, as prompt receipts are (§10). */
|
|
51
|
+
export const LIFECYCLE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
52
|
+
|
|
53
|
+
const keyOf = (resource: string, operation: string, requestId: string) =>
|
|
54
|
+
createHash('sha256').update(JSON.stringify(['lifecycle', resource, operation, requestId])).digest('hex');
|
|
55
|
+
|
|
56
|
+
export type LifecycleJournal = ReturnType<typeof createLifecycleJournal>;
|
|
57
|
+
|
|
58
|
+
export function createLifecycleJournal(directory: string) {
|
|
59
|
+
const writes = new Map<string, Promise<void>>();
|
|
60
|
+
let ready: Promise<void> | undefined;
|
|
61
|
+
const prepare = () => ready ??= mkdir(directory, { recursive: true, mode: 0o700 }).then(() => {}, error => { ready = undefined; throw error; });
|
|
62
|
+
const file = (key: string) => path.join(directory, `${key}.json`);
|
|
63
|
+
|
|
64
|
+
async function read(name: string): Promise<LifecycleEntry | undefined> {
|
|
65
|
+
let text: string;
|
|
66
|
+
try { text = await readFile(path.join(directory, name), 'utf8'); }
|
|
67
|
+
catch (error: any) { if (error?.code === 'ENOENT') return undefined; throw error; }
|
|
68
|
+
const entry = JSON.parse(text);
|
|
69
|
+
if (entry?.version !== 1 || typeof entry.key !== 'string' || typeof entry.state !== 'string') throw new Error(`unreadable lifecycle entry ${name}`);
|
|
70
|
+
return entry;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
keyOf,
|
|
75
|
+
async get(resource: string, operation: string, requestId: string): Promise<LifecycleEntry | undefined> {
|
|
76
|
+
const key = keyOf(resource, operation, requestId);
|
|
77
|
+
await writes.get(key);
|
|
78
|
+
await prepare();
|
|
79
|
+
return read(`${key}.json`);
|
|
80
|
+
},
|
|
81
|
+
/** Writes an entry atomically; writes of one key never land out of order. */
|
|
82
|
+
put(entry: LifecycleEntry) {
|
|
83
|
+
const body = JSON.stringify({ ...entry, updatedAt: new Date().toISOString() });
|
|
84
|
+
const next = (writes.get(entry.key) ?? Promise.resolve()).catch(() => {}).then(prepare).then(async () => {
|
|
85
|
+
const temporary = `${file(entry.key)}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
86
|
+
try {
|
|
87
|
+
await writeFile(temporary, body, { mode: 0o600 });
|
|
88
|
+
await replaceFile(temporary, file(entry.key));
|
|
89
|
+
} catch (error) {
|
|
90
|
+
await rm(temporary, { force: true }).catch(() => {});
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
writes.set(entry.key, next);
|
|
95
|
+
void next.finally(() => { if (writes.get(entry.key) === next) writes.delete(entry.key); }).catch(() => {});
|
|
96
|
+
return next;
|
|
97
|
+
},
|
|
98
|
+
/** Every readable entry; an unreadable one is skipped (and named), never deleted. */
|
|
99
|
+
async list(onUnreadable?: (name: string, error: unknown) => void): Promise<LifecycleEntry[]> {
|
|
100
|
+
await prepare();
|
|
101
|
+
const entries: LifecycleEntry[] = [];
|
|
102
|
+
for (const name of await readdir(directory)) {
|
|
103
|
+
if (!name.endsWith('.json')) continue;
|
|
104
|
+
try { const entry = await read(name); if (entry) entries.push(entry); }
|
|
105
|
+
catch (error) { onUnreadable?.(name, error); }
|
|
106
|
+
}
|
|
107
|
+
return entries;
|
|
108
|
+
},
|
|
109
|
+
/** Removes terminal entries not written for `maxAgeMs`, and temporary files a crash left (only at start). */
|
|
110
|
+
async prune(maxAgeMs = LIFECYCLE_RETENTION_MS, { temporaries = false } = {}) {
|
|
111
|
+
await prepare();
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
for (const name of await readdir(directory)) {
|
|
114
|
+
const target = path.join(directory, name);
|
|
115
|
+
if (name.endsWith('.tmp')) { if (temporaries) await rm(target, { force: true }); continue; }
|
|
116
|
+
if (!name.endsWith('.json')) continue;
|
|
117
|
+
const entry = await read(name).catch(() => undefined);
|
|
118
|
+
if (!entry || !['committed', 'failed', 'unknown'].includes(entry.state)) continue;
|
|
119
|
+
const info = await stat(target).catch(() => undefined);
|
|
120
|
+
if (info && now - info.mtimeMs > maxAgeMs) await rm(target, { force: true });
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
async flush() { await Promise.all([...writes.values()].map(write => write.catch(() => {}))); },
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A failure the journal keeps as the answer of every repeat: its code, message and data. */
|
|
128
|
+
const answerOf = (error: unknown): { code: number; message: string; data?: unknown } =>
|
|
129
|
+
error instanceof RpcError ? { code: error.code, message: error.message, ...(error.data !== undefined ? { data: error.data } : {}) }
|
|
130
|
+
: { code: 1000, message: error instanceof Error ? error.message : String(error) };
|
|
131
|
+
|
|
132
|
+
export const outcomeUnknown = (operation: string, requestId: string) =>
|
|
133
|
+
new RpcError(1004, `alpd cannot tell whether ${operation} ${requestId} reached the runtime; check the session, then try again with a new requestId`, { reason: 'outcome_unknown' });
|
|
134
|
+
|
|
135
|
+
export type LifecycleSteps<Plan, Native, Result> = {
|
|
136
|
+
/** Validates and decides; may refuse (nothing is recorded). Runs inside the resource's queue. */
|
|
137
|
+
prepare(): Promise<Plan>;
|
|
138
|
+
/** The native step; a thrown error with `outcomeUnknown: true` records unknown, any other records failed. */
|
|
139
|
+
apply(plan: Plan): Promise<Native>;
|
|
140
|
+
/** alpd's own, idempotent commit from the entry alone (a restart replays it). */
|
|
141
|
+
commit(entry: LifecycleEntry<Plan, Native, Result>): Promise<Result>;
|
|
142
|
+
/** How a repeat answers from a committed entry (e.g. with a fresh session summary). */
|
|
143
|
+
repeat?(entry: LifecycleEntry<Plan, Native, Result>): Result | Promise<Result>;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Runs journaled operations: one at a time per resource, at most once per (resource, operation,
|
|
148
|
+
* requestId). The seam later lifecycle operations (live configure, reload) reuse with their own steps.
|
|
149
|
+
*/
|
|
150
|
+
export function createLifecycle(journal: LifecycleJournal, {
|
|
151
|
+
crashPoint = (_name: string) => {}, completed = async (_entry: LifecycleEntry): Promise<{ result: any } | undefined> => undefined,
|
|
152
|
+
}: { crashPoint?: (name: string) => void; completed?: (entry: LifecycleEntry) => Promise<{ result: any } | undefined> } = {}) {
|
|
153
|
+
const queues = new Map<string, Promise<unknown>>();
|
|
154
|
+
const inflight = new Map<string, Promise<unknown>>();
|
|
155
|
+
|
|
156
|
+
/** Runs `work` after every earlier operation of `resource` settled. */
|
|
157
|
+
function serial<T>(resource: string, work: () => Promise<T>): Promise<T> {
|
|
158
|
+
const run = (queues.get(resource) ?? Promise.resolve()).catch(() => {}).then(work);
|
|
159
|
+
queues.set(resource, run);
|
|
160
|
+
void run.finally(() => { if (queues.get(resource) === run) queues.delete(resource); }).catch(() => {});
|
|
161
|
+
return run;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function run<Plan, Native, Result>(
|
|
165
|
+
request: { resource: string; operation: string; requestId: string; fingerprint: string },
|
|
166
|
+
steps: LifecycleSteps<Plan, Native, Result>,
|
|
167
|
+
): Promise<{ result: Result; duplicate: boolean; entry: LifecycleEntry<Plan, Native, Result> }> {
|
|
168
|
+
const key = journal.keyOf(request.resource, request.operation, request.requestId);
|
|
169
|
+
const earlier = inflight.get(key);
|
|
170
|
+
if (earlier) await earlier.catch(() => {});
|
|
171
|
+
const attempt = serial(request.resource, async () => {
|
|
172
|
+
let entry: LifecycleEntry<Plan, Native, Result> | undefined;
|
|
173
|
+
try { entry = await journal.get(request.resource, request.operation, request.requestId); }
|
|
174
|
+
catch (error) { throw new RpcError(1000, `alpd cannot read the journal of ${request.operation} ${request.requestId}`, { reason: 'persistence_failed' }); }
|
|
175
|
+
if (entry) {
|
|
176
|
+
if (entry.fingerprint !== request.fingerprint) throw new RpcError(1004, `${request.operation} ${request.requestId} was already requested with other parameters`, { reason: 'key_conflict' });
|
|
177
|
+
if (entry.state === 'committed') return { result: steps.repeat ? await steps.repeat(entry) : entry.result as Result, duplicate: true, entry };
|
|
178
|
+
if (entry.state === 'failed') throw new RpcError(entry.error?.code ?? 1000, entry.error?.message ?? `${request.operation} failed`, entry.error?.data);
|
|
179
|
+
// A commit that failed earlier finishes now; this is its first answer.
|
|
180
|
+
if (entry.state === 'applied') {
|
|
181
|
+
const saved = await completed(entry);
|
|
182
|
+
const done = await commit(entry, steps, saved);
|
|
183
|
+
return { result: done.result as Result, duplicate: saved !== undefined, entry: done };
|
|
184
|
+
}
|
|
185
|
+
throw outcomeUnknown(request.operation, request.requestId);
|
|
186
|
+
}
|
|
187
|
+
// A failed store commit is not success. Keep later native mutations behind it until a
|
|
188
|
+
// retry/start finishes it; a durable receipt permits progress despite a lost final marker.
|
|
189
|
+
for (const pending of await journal.list()) {
|
|
190
|
+
if (pending.resource === request.resource && ['configure', 'rewind'].includes(pending.operation) && pending.state === 'applied' && !await completed(pending)) {
|
|
191
|
+
throw new RpcError(1000, `alpd must finish ${pending.operation} ${pending.requestId} before another conversation mutation`, { reason: 'persistence_failed' });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const plan = await steps.prepare();
|
|
195
|
+
const now = new Date().toISOString();
|
|
196
|
+
entry = { version: 1, key, ...request, attemptId: randomBytes(16).toString('hex'), state: 'prepared', plan, createdAt: now, updatedAt: now };
|
|
197
|
+
try { await journal.put(entry); }
|
|
198
|
+
catch (error) { throw new RpcError(1000, `alpd could not record ${request.operation} ${request.requestId}; nothing was changed`, { reason: 'persistence_failed' }); }
|
|
199
|
+
crashPoint(`${request.operation}.after-prepared`);
|
|
200
|
+
let native: Native;
|
|
201
|
+
try {
|
|
202
|
+
native = await steps.apply(plan);
|
|
203
|
+
} catch (error: any) {
|
|
204
|
+
const unknown = error?.outcomeUnknown === true;
|
|
205
|
+
entry = { ...entry, state: unknown ? 'unknown' : 'failed', ...(unknown ? {} : { error: answerOf(error) }) };
|
|
206
|
+
await journal.put(entry).catch(() => {});
|
|
207
|
+
if (unknown) throw outcomeUnknown(request.operation, request.requestId);
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
entry = { ...entry, state: 'applied', native };
|
|
211
|
+
try { await journal.put(entry); }
|
|
212
|
+
catch {
|
|
213
|
+
// The native step happened but its record did not: what a repeat finds is `prepared`, answered unknown.
|
|
214
|
+
throw outcomeUnknown(request.operation, request.requestId);
|
|
215
|
+
}
|
|
216
|
+
crashPoint(`${request.operation}.after-applied`);
|
|
217
|
+
const done = await commit(entry, steps);
|
|
218
|
+
return { result: done.result as Result, duplicate: false, entry: done };
|
|
219
|
+
});
|
|
220
|
+
inflight.set(key, attempt);
|
|
221
|
+
void attempt.finally(() => { if (inflight.get(key) === attempt) inflight.delete(key); }).catch(() => {});
|
|
222
|
+
return attempt;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function commit<Plan, Native, Result>(entry: LifecycleEntry<Plan, Native, Result>, steps: Pick<LifecycleSteps<Plan, Native, Result>, 'commit'>, saved?: { result: Result }) {
|
|
226
|
+
let result: Result;
|
|
227
|
+
try {
|
|
228
|
+
if (!saved && !entry.attemptId && ['configure', 'rewind'].includes(entry.operation)) {
|
|
229
|
+
// Legacy applied entries have no atomic completion witness. A strictly later
|
|
230
|
+
// applied/committed attempt proves a newer native operation ran; replaying this
|
|
231
|
+
// ambiguous older commit could undo it. Keep it unfinished, never invent success.
|
|
232
|
+
const newer = (await journal.list()).some(other => other.resource === entry.resource && other.key !== entry.key
|
|
233
|
+
&& other.createdAt > entry.createdAt && ['applied', 'committed'].includes(other.state));
|
|
234
|
+
if (newer) throw new RpcError(1000, `alpd cannot safely replay ${entry.operation} ${entry.requestId} over a later conversation mutation`, { reason: 'persistence_failed' });
|
|
235
|
+
}
|
|
236
|
+
result = saved ? saved.result : await steps.commit(entry);
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
if (error instanceof RpcError) throw error;
|
|
240
|
+
throw new RpcError(1000, `alpd could not finish ${entry.operation} ${entry.requestId}; it finishes when tried again or when alpd starts`, { reason: 'persistence_failed' });
|
|
241
|
+
}
|
|
242
|
+
crashPoint(`${entry.operation}.before-committed`);
|
|
243
|
+
const done = { ...entry, state: 'committed' as const, result };
|
|
244
|
+
await journal.put(done).catch(() => {});
|
|
245
|
+
crashPoint(`${entry.operation}.after-committed`);
|
|
246
|
+
return done;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
run,
|
|
251
|
+
serial,
|
|
252
|
+
/**
|
|
253
|
+
* At start, before any request: `prepared` becomes `unknown` (the native step is never sent again),
|
|
254
|
+
* and unknown outcomes are durably observed once, without claiming success or replaying a commit.
|
|
255
|
+
* `applied` rolls forward through the operation's commit (left `applied` when that fails, to be
|
|
256
|
+
* finished by a repeat or the next start; such entries are answered).
|
|
257
|
+
*/
|
|
258
|
+
async recover(commits: Record<string, (entry: LifecycleEntry) => Promise<unknown>>, log?: (message: string, fields: Record<string, unknown>) => void) {
|
|
259
|
+
const entries = await journal.list((name, error) => log?.(`unreadable lifecycle entry ${name}`, { error }));
|
|
260
|
+
const unfinished: LifecycleEntry[] = [];
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
if (entry.state === 'prepared' || (entry.state === 'unknown' && !entry.recoverySeenAt)) {
|
|
263
|
+
try {
|
|
264
|
+
await journal.put({ ...entry, state: 'unknown', recoverySeenAt: new Date().toISOString() });
|
|
265
|
+
log?.(`${entry.operation} ${entry.requestId} of ${entry.resource} may or may not have reached the runtime`, { code: 'ALPD_LIFECYCLE_UNKNOWN', operation: entry.operation, resource: entry.resource, requestId: entry.requestId });
|
|
266
|
+
} catch (error) {
|
|
267
|
+
// No commit or native step was attempted; the next start may retry the observation.
|
|
268
|
+
log?.(`could not record unknown ${entry.operation} ${entry.requestId} of ${entry.resource}`, { code: 'ALPD_LIFECYCLE_OBSERVE_FAILED', error });
|
|
269
|
+
}
|
|
270
|
+
} else if (entry.state === 'applied') {
|
|
271
|
+
const committer = commits[entry.operation];
|
|
272
|
+
if (!committer) continue;
|
|
273
|
+
await serial(entry.resource, async () => commit(entry, { commit: committer }, await completed(entry))).catch(error => {
|
|
274
|
+
unfinished.push(entry);
|
|
275
|
+
log?.(`could not finish ${entry.operation} ${entry.requestId} of ${entry.resource}`, { code: 'ALPD_LIFECYCLE_ROLLFORWARD_FAILED', error });
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** Entries still applied: their resources wait for a repeat to finish them. */
|
|
280
|
+
return unfinished;
|
|
281
|
+
},
|
|
282
|
+
};
|
|
283
|
+
}
|
package/src/lock.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { unlink, utimes, writeFile, rename } from 'node:fs/promises';
|
|
2
|
+
import { acquireDaemonLock, daemonPaths, readLock } from '@anhlp/alp-client/index';
|
|
3
|
+
|
|
4
|
+
export type LockContents = {
|
|
5
|
+
pid: number;
|
|
6
|
+
startedAt: string;
|
|
7
|
+
bootTime: number;
|
|
8
|
+
uid: number;
|
|
9
|
+
version: string;
|
|
10
|
+
protocolVersion: number;
|
|
11
|
+
socket: string;
|
|
12
|
+
ready: boolean;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Single-instance lock (Paseo acquirePidLock, simplified): exclusive create, stale when its pid or boot is gone. */
|
|
16
|
+
export async function acquireLock(home: string, contents: Omit<LockContents, 'pid' | 'startedAt' | 'bootTime' | 'uid' | 'ready'>): Promise<LockContents> {
|
|
17
|
+
return acquireDaemonLock(home, contents) as Promise<LockContents>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Moves `temporary` over `file`. On Windows the move fails with EPERM, EACCES or EBUSY while
|
|
22
|
+
* another process has `file` open, such as a client reading the lock; it is tried again then.
|
|
23
|
+
*/
|
|
24
|
+
export async function replaceFile(temporary: string, file: string) {
|
|
25
|
+
for (let attempt = 0; ; attempt++) {
|
|
26
|
+
try { return await rename(temporary, file); }
|
|
27
|
+
catch (error: any) {
|
|
28
|
+
if (process.platform !== 'win32' || attempt >= 20 || !['EPERM', 'EACCES', 'EBUSY'].includes(error?.code)) throw error;
|
|
29
|
+
await new Promise(resolve => setTimeout(resolve, 10 + attempt * 10));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function updateLock(home: string, lock: LockContents) {
|
|
35
|
+
const file = daemonPaths(home).lock;
|
|
36
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
37
|
+
await writeFile(temporary, JSON.stringify(lock), { mode: 0o600 });
|
|
38
|
+
await replaceFile(temporary, file);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** True while this process still owns the lock; refreshes its mtime as a heartbeat. */
|
|
42
|
+
export async function heartbeat(home: string) {
|
|
43
|
+
const current = await readLock(home);
|
|
44
|
+
if (current?.pid !== process.pid) return false;
|
|
45
|
+
const now = new Date();
|
|
46
|
+
await utimes(daemonPaths(home).lock, now, now).catch(() => {});
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function releaseLock(home: string) {
|
|
51
|
+
const current = await readLock(home);
|
|
52
|
+
if (current?.pid === process.pid) await unlink(daemonPaths(home).lock).catch(() => {});
|
|
53
|
+
}
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { openSync, writeSync } from 'node:fs';
|
|
3
|
+
import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import templates from 'alp:templates';
|
|
7
|
+
import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } from '@anhlp/alp-client/index';
|
|
8
|
+
import { attachmentStageDir, createAlpRuntime, reclaimCopies, reclaimWorktrees } from '@anhlp/alp-runtime/index';
|
|
9
|
+
import { createDaemonServer } from './server.js';
|
|
10
|
+
import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
|
|
11
|
+
import { createStore } from './store.js';
|
|
12
|
+
import { readAttachmentConfig } from './attachments.js';
|
|
13
|
+
import { validateUserSettings } from '@anhlp/alp-core/validation';
|
|
14
|
+
import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
|
|
15
|
+
import { migrateState } from '@anhlp/alp-core/migrations';
|
|
16
|
+
import { createLogger } from '@anhlp/alp-core/log';
|
|
17
|
+
|
|
18
|
+
declare const __ALP_VERSION__: string;
|
|
19
|
+
const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
|
|
20
|
+
const LOG_BYTES = 10 * 1024 * 1024;
|
|
21
|
+
const LOG_FILES = 3;
|
|
22
|
+
const log = createLogger({ component: 'alpd' });
|
|
23
|
+
|
|
24
|
+
async function rotate(log: string) {
|
|
25
|
+
const size = await stat(log).then(info => info.size, () => 0);
|
|
26
|
+
if (size < LOG_BYTES) return;
|
|
27
|
+
for (let index = LOG_FILES - 1; index >= 1; index--) {
|
|
28
|
+
await rename(index === 1 ? log : `${log}.${index - 1}`, `${log}.${index}`).catch(() => {});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The launcher owns its detached child until that child acknowledges readiness or exits.
|
|
33
|
+
* A ready lock belonging to some other process cannot settle this launch.
|
|
34
|
+
*/
|
|
35
|
+
async function detach(home: string) {
|
|
36
|
+
await assertPrivateDirectory(home, { create: true });
|
|
37
|
+
const { log } = daemonPaths(home);
|
|
38
|
+
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
39
|
+
await rotate(log);
|
|
40
|
+
const output = await open(log, 'a', 0o600);
|
|
41
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
|
|
42
|
+
detached: true,
|
|
43
|
+
stdio: ['ignore', output.fd, output.fd, 'ipc'],
|
|
44
|
+
env: process.env,
|
|
45
|
+
windowsHide: true,
|
|
46
|
+
});
|
|
47
|
+
await output.close();
|
|
48
|
+
await new Promise<void>((resolve, reject) => {
|
|
49
|
+
const requested = Number(process.argv.find(arg => arg.startsWith('--startup-timeout='))?.split('=')[1]);
|
|
50
|
+
const timeoutMs = Number.isFinite(requested) && requested > 0 ? requested : 15_000;
|
|
51
|
+
let timedOut = false;
|
|
52
|
+
let force: ReturnType<typeof setTimeout> | undefined;
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
timedOut = true;
|
|
55
|
+
child.kill();
|
|
56
|
+
force = setTimeout(() => child.kill('SIGKILL'), 1_000);
|
|
57
|
+
}, timeoutMs);
|
|
58
|
+
child.once('error', error => { clearTimeout(timer); clearTimeout(force); reject(error); });
|
|
59
|
+
child.once('exit', (code, signal) => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
clearTimeout(force);
|
|
62
|
+
reject(new Error(timedOut ? `alpd startup timed out after ${timeoutMs} ms` : `alpd exited during startup (${code ?? signal})`));
|
|
63
|
+
});
|
|
64
|
+
child.once('message', message => {
|
|
65
|
+
if (message !== 'alpd.ready' || timedOut) return;
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
child.disconnect();
|
|
68
|
+
child.unref();
|
|
69
|
+
resolve();
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Under a service manager (ALPD §37), which holds alpd's stdout open: alpd rotates its
|
|
76
|
+
* log at start as the detached launcher does, then writes its output there itself. The
|
|
77
|
+
* manager's own file keeps only what Node prints when it dies.
|
|
78
|
+
*/
|
|
79
|
+
async function serviceLog(home: string) {
|
|
80
|
+
await assertPrivateDirectory(home, { create: true });
|
|
81
|
+
const { log } = daemonPaths(home);
|
|
82
|
+
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
83
|
+
await rotate(log);
|
|
84
|
+
const fd = openSync(log, 'a', 0o600);
|
|
85
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
86
|
+
stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
|
|
87
|
+
try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch {}
|
|
88
|
+
const done = typeof encoding === 'function' ? encoding : callback;
|
|
89
|
+
if (typeof done === 'function') done();
|
|
90
|
+
return true;
|
|
91
|
+
}) as typeof stream.write;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The user's alpd settings in $ALP_HOME/settings.json; none when it is missing.
|
|
97
|
+
* Invalid settings are logged and alpd starts with the defaults, so a typo never
|
|
98
|
+
* keeps it from running; alp doctor reports them too.
|
|
99
|
+
*/
|
|
100
|
+
async function userSettings(home: string): Promise<any> {
|
|
101
|
+
const file = path.join(home, 'settings.json');
|
|
102
|
+
let text: string;
|
|
103
|
+
try { text = await readFile(file, 'utf8'); } catch { return {}; }
|
|
104
|
+
try { return validateUserSettings(JSON.parse(text), file); }
|
|
105
|
+
catch (error: any) {
|
|
106
|
+
log.warn(`ignoring ${file}: ${error?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' });
|
|
107
|
+
return {};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* How the previous alpd ended (ALPD §31). A running alpd keeps a marker file and
|
|
113
|
+
* touches it with its heartbeat; a clean stop removes it last. A marker found at
|
|
114
|
+
* start means the previous alpd crashed, around the marker's last touch.
|
|
115
|
+
*/
|
|
116
|
+
async function previousExit(marker: string): Promise<{ kind: 'clean' | 'crash'; at?: string }> {
|
|
117
|
+
const info = await stat(marker).catch(() => undefined);
|
|
118
|
+
return info ? { kind: 'crash', at: info.mtime.toISOString() } : { kind: 'clean' };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Whether a process group `id` exists; on POSIX a pid is never reused while its group lives. */
|
|
122
|
+
function groupAlive(id: number) {
|
|
123
|
+
try { process.kill(-id, 0); return true; } catch (error: any) { return error?.code === 'EPERM'; }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** alpd leads its own process group when started detached or by a service manager. */
|
|
127
|
+
const leadsGroup = () => process.platform !== 'win32' && groupAlive(process.pid);
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Stops what a crashed alpd left running (ALPD §66): its provider processes normally exit
|
|
131
|
+
* when their stdin closes, but a stuck one, or a command an agent started, can outlive it.
|
|
132
|
+
* They stay in the crashed alpd's process group, so alpd ends that group when the crashed
|
|
133
|
+
* one led its group and this one leads its own (so it is not a member). Not on Windows.
|
|
134
|
+
*/
|
|
135
|
+
async function stopLeftovers(previous: { pid?: number; groupLeader?: boolean } | undefined) {
|
|
136
|
+
const pid = previous?.pid;
|
|
137
|
+
if (!previous?.groupLeader || !Number.isSafeInteger(pid) || pid === process.pid || !leadsGroup() || !groupAlive(pid!)) return;
|
|
138
|
+
log.warn(`stopping processes the previous alpd (pid ${pid}) left running`, { code: 'ALP_LEFTOVER_PROCESSES', previousPid: pid });
|
|
139
|
+
const signal = (name: NodeJS.Signals) => { try { process.kill(-pid!, name); } catch {} };
|
|
140
|
+
signal('SIGTERM');
|
|
141
|
+
for (let waited = 0; waited < 3000 && groupAlive(pid!); waited += 50) await new Promise(resolve => setTimeout(resolve, 50));
|
|
142
|
+
if (groupAlive(pid!)) signal('SIGKILL');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Where start-up stands, so a failure says which step it stopped at. */
|
|
146
|
+
type Phase = 'home' | 'lock' | 'state' | 'recovery' | 'listen' | 'ready';
|
|
147
|
+
let phase: Phase = 'home';
|
|
148
|
+
const STARTUP_CODES = { home: 'ALP_HOME_UNUSABLE', lock: 'ALP_LOCK_FAILED', state: 'ALP_STATE_UNUSABLE', recovery: 'ALP_STARTUP_FAILED', listen: 'ALP_IPC_LISTEN_FAILED', ready: 'ALP_STARTUP_FAILED' } as const;
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Before anything reads or writes the state (ALPD §68): a restore cut short is settled, a
|
|
152
|
+
* state of a newer schema is refused untouched, an older one is migrated forward, and a
|
|
153
|
+
* restore's marker says to continue no work by itself this time; it is cleared once alpd is
|
|
154
|
+
* ready, so a start that fails keeps it for the next.
|
|
155
|
+
*/
|
|
156
|
+
async function openState(home: string) {
|
|
157
|
+
const settled = await recoverInterruptedRestore(home);
|
|
158
|
+
if (settled) log.warn(`a restore from ${settled.file} was cut short and has been ${settled.outcome}`, { code: 'ALP_RESTORE_SETTLED', outcome: settled.outcome });
|
|
159
|
+
const migrated = await migrateState(home, { by: `alpd ${VERSION}`, log });
|
|
160
|
+
for (const step of migrated.steps) log.info(`state migrated from schema ${step.from} to ${step.to} (${step.name}); the state before it is in ${step.backup}`, { code: 'ALP_STATE_MIGRATED', from: step.from, to: step.to, migration: step.name });
|
|
161
|
+
const restored = await readRestoredMarker(home);
|
|
162
|
+
if (restored) log.info(`state restored${restored.from ? ` from ${restored.from}` : ''}; sessions that were working wait for the user`, { code: 'ALP_STATE_RESTORED' });
|
|
163
|
+
return { restored: !!restored };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function run(home: string) {
|
|
167
|
+
await assertPrivateDirectory(home, { create: true });
|
|
168
|
+
phase = 'lock';
|
|
169
|
+
const { socket } = daemonPaths(home);
|
|
170
|
+
let lock;
|
|
171
|
+
try {
|
|
172
|
+
lock = await acquireLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket });
|
|
173
|
+
} catch (error: any) {
|
|
174
|
+
// Under a service manager, another alpd serving this home is no failure to retry.
|
|
175
|
+
if (process.argv.includes('--service') && /already running|ALP is busy/.test(error?.message ?? '')) {
|
|
176
|
+
log.info(`${error.message}; this one exits`, { code: 'ALP_LOCK_HELD' });
|
|
177
|
+
process.exit(0);
|
|
178
|
+
}
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
phase = 'state';
|
|
182
|
+
let opened;
|
|
183
|
+
try {
|
|
184
|
+
opened = await openState(home);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
await releaseLock(home);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
phase = 'recovery';
|
|
190
|
+
// First: nothing a crashed alpd left running may still write while this one recovers.
|
|
191
|
+
const marker = path.join(home, 'state', 'alpd.running');
|
|
192
|
+
const exit = await previousExit(marker);
|
|
193
|
+
if (exit.kind === 'crash') {
|
|
194
|
+
log.warn(`the previous alpd stopped unexpectedly around ${exit.at}`, { code: 'ALP_PREVIOUS_CRASH', at: exit.at });
|
|
195
|
+
await stopLeftovers(await readFile(marker, 'utf8').then(JSON.parse).catch(() => undefined));
|
|
196
|
+
}
|
|
197
|
+
await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
|
|
198
|
+
await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
|
|
199
|
+
const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
|
|
200
|
+
const worktreeDir = path.join(home, 'worktrees');
|
|
201
|
+
// Worktrees of assignments a crash interrupted: their work goes to their branches.
|
|
202
|
+
for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
|
|
203
|
+
// Review copies of interrupted assignments hold nothing to keep.
|
|
204
|
+
const copyDir = path.join(home, 'copies');
|
|
205
|
+
await reclaimCopies(copyDir).catch(() => 0);
|
|
206
|
+
// Requested starts lift the existing hold before launching. Never erase a stop
|
|
207
|
+
// published while this daemon was starting.
|
|
208
|
+
const settings = await userSettings(home);
|
|
209
|
+
const runtime = createAlpRuntime({
|
|
210
|
+
templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
|
|
211
|
+
// Read-only copies of attached files for the sessions' tools (§12.6); not on Windows, as the store.
|
|
212
|
+
...(process.platform !== 'win32' ? { attachmentStageDir: attachmentStageDir(home) } : {}),
|
|
213
|
+
assignmentResultFile: path.join(home, 'state', 'assignment-results.json'), recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
|
|
214
|
+
autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false && !opened.restored, previousExit: exit,
|
|
215
|
+
});
|
|
216
|
+
const store = createStore(path.join(home, 'state'));
|
|
217
|
+
let stopping: Promise<void> | undefined;
|
|
218
|
+
const shutdown = (code = 0) => {
|
|
219
|
+
stopping ??= (async () => {
|
|
220
|
+
const force = setTimeout(() => process.exit(code), 10_000);
|
|
221
|
+
force.unref();
|
|
222
|
+
clearInterval(beat);
|
|
223
|
+
await server.close().catch(() => {});
|
|
224
|
+
await runtime.shutdown().catch(() => {});
|
|
225
|
+
await store.flush();
|
|
226
|
+
// Last: what remains is a clean stop.
|
|
227
|
+
await unlink(marker).catch(() => {});
|
|
228
|
+
await releaseLock(home);
|
|
229
|
+
log.info('alpd stopped', { event: 'stopped', exitCode: code });
|
|
230
|
+
process.exit(code);
|
|
231
|
+
})();
|
|
232
|
+
return stopping;
|
|
233
|
+
};
|
|
234
|
+
// The operator may lower the attachment limits (never raise them): <ALP_HOME>/attachments.json.
|
|
235
|
+
const attachmentConfig = await readAttachmentConfig(home);
|
|
236
|
+
for (const problem of attachmentConfig.problems) log.warn(problem, { code: 'ALP_ATTACHMENT_CONFIG' });
|
|
237
|
+
const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, attachmentOptions: { limits: attachmentConfig.limits }, onShutdown: () => void shutdown() });
|
|
238
|
+
const beat = setInterval(() => {
|
|
239
|
+
void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
|
|
240
|
+
const now = new Date();
|
|
241
|
+
void utimes(marker, now, now).catch(() => {});
|
|
242
|
+
}, 30_000);
|
|
243
|
+
beat.unref();
|
|
244
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
|
|
245
|
+
process.on('uncaughtException', error => { log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
|
|
246
|
+
process.on('unhandledRejection', error => { log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
|
|
247
|
+
phase = 'listen';
|
|
248
|
+
try {
|
|
249
|
+
await server.listen();
|
|
250
|
+
} catch (error) {
|
|
251
|
+
await releaseLock(home);
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
phase = 'ready';
|
|
255
|
+
// Web app and relay are owned by the optional Paseo integration process.
|
|
256
|
+
await updateLock(home, { ...lock, ready: true });
|
|
257
|
+
// Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
|
|
258
|
+
const { install } = daemonPaths(home);
|
|
259
|
+
await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
|
|
260
|
+
.then(() => rename(`${install}.tmp`, install))
|
|
261
|
+
.catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
|
|
262
|
+
if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
|
|
263
|
+
if (process.connected) process.send?.('alpd.ready');
|
|
264
|
+
log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const home = alpHome();
|
|
268
|
+
try {
|
|
269
|
+
if (process.argv.includes('--detach')) await detach(home);
|
|
270
|
+
else {
|
|
271
|
+
// A direct foreground/login invocation is an explicit start. Do this before
|
|
272
|
+
// admission registration, so a stop published during startup is preserved.
|
|
273
|
+
if (!process.connected) await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
|
|
274
|
+
if (process.argv.includes('--service')) await serviceLog(home);
|
|
275
|
+
if (process.connected) await run(home);
|
|
276
|
+
else {
|
|
277
|
+
// Retain admission through readiness even if the requesting service client
|
|
278
|
+
// times out. An invocation without a requester (including login) is explicit.
|
|
279
|
+
await withDaemonLifecycle(home, 'start', async () => {
|
|
280
|
+
await run(home);
|
|
281
|
+
}, { joinStart: true });
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
} catch (error: any) {
|
|
285
|
+
// The log says where start-up stopped; alp doctor reads it from there.
|
|
286
|
+
const stoppedIn = phase as Phase;
|
|
287
|
+
// Opening the state fails with the state's own code (a newer schema, a failed migration).
|
|
288
|
+
const code = /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
|
|
289
|
+
: stoppedIn === 'state' && typeof error?.code === 'string' && /^[A-Z_]+$/.test(error.code) ? `ALP_${error.code}` : STARTUP_CODES[stoppedIn];
|
|
290
|
+
log.error(`alpd failed to start while ${{ home: 'preparing its home', lock: 'taking its lock', state: 'opening its state', recovery: 'recovering earlier work', listen: 'opening its IPC endpoint', ready: 'finishing start-up' }[stoppedIn]}${stoppedIn === 'state' ? `: ${error?.message ?? error}` : ''}`, { code, phase: stoppedIn, error });
|
|
291
|
+
process.exit(1);
|
|
292
|
+
}
|