@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.10
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 +456 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +64050 -0
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +150 -0
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +262 -0
- package/dist/files.js +674 -0
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -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 +11 -0
- package/dist/index.js +28 -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 +363 -0
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-entry.d.ts +2 -0
- package/dist/native-entry.js +3 -0
- package/dist/native-register.d.ts +1 -0
- package/dist/native-register.js +13 -0
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +201 -0
- package/dist/operations.d.ts +40 -0
- package/dist/operations.js +313 -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 +298 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +60 -0
- package/dist/server.js +1958 -0
- package/dist/store.d.ts +178 -0
- package/dist/store.js +386 -0
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +203 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +32 -0
- package/dist/windows-terminal.js +79 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +163 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +884 -0
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +12 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +381 -0
- package/src/model-catalog.ts +36 -0
- package/src/native-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +127 -0
- package/src/operations.ts +329 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +2238 -0
- package/src/store.ts +449 -0
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +653 -0
- package/src/windows-terminal.ts +74 -0
- package/src/worktrees.ts +382 -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
|
+
}
|