@anhlp/alp-daemon 0.0.0-beta.1 → 0.10.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 +0 -2
- package/dist/alpd.js +1176 -3617
- package/dist/build-manifest.json +1 -28
- package/dist/lock.d.ts +0 -5
- package/dist/lock.js +17 -11
- package/dist/main.js +34 -97
- package/dist/server.d.ts +1 -8
- package/dist/server.js +91 -393
- package/dist/store.d.ts +6 -67
- package/dist/store.js +29 -191
- package/package.json +9 -16
- package/src/lock.ts +20 -17
- package/src/main.ts +24 -102
- package/src/server.ts +75 -422
- package/src/store.ts +27 -207
- package/LICENSE +0 -202
- package/NOTICE +0 -7
- package/dist/THIRD-PARTY-NOTICES.txt +0 -431
- package/dist/alp-templates.d.ts +0 -5
- package/dist/operations.d.ts +0 -23
- package/dist/operations.js +0 -272
- package/dist/rpc-error.d.ts +0 -6
- package/dist/rpc-error.js +0 -11
- package/src/alp-templates.d.ts +0 -5
- package/src/operations.ts +0 -298
- package/src/rpc-error.ts +0 -4
package/dist/store.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
|
|
2
2
|
import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
|
|
3
3
|
/**
|
|
4
|
-
* alpd's durable state (plans/reference/ALPD.md §5
|
|
4
|
+
* alpd's durable state (plans/reference/ALPD.md §5): one JSON record per session,
|
|
5
5
|
* written atomically, one append-only JSONL timeline per tree, and one receipt per
|
|
6
|
-
* delivered prompt.
|
|
7
|
-
* resolves; nothing is fsynced, so a power loss or a failing disk may lose recent writes.
|
|
6
|
+
* delivered prompt.
|
|
8
7
|
*/
|
|
9
8
|
export type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
|
|
10
9
|
export type SessionRecord = {
|
|
@@ -23,85 +22,25 @@ export type SessionRecord = {
|
|
|
23
22
|
createdAt: string;
|
|
24
23
|
updatedAt: string;
|
|
25
24
|
};
|
|
26
|
-
/**
|
|
27
|
-
* Delivery of one clientMessageId; `pending` means alpd may have stopped while sending it.
|
|
28
|
-
* A completed receipt says what the runtime answered: `unknown` when the provider may or
|
|
29
|
-
* may not have the message (its process died or timed out mid-request).
|
|
30
|
-
*/
|
|
25
|
+
/** Delivery of one clientMessageId; `pending` means alpd may have stopped while sending it. */
|
|
31
26
|
export type Receipt = {
|
|
32
27
|
version: 1;
|
|
33
28
|
sessionId: string;
|
|
34
29
|
clientMessageId: string;
|
|
35
30
|
fingerprint: string;
|
|
36
31
|
state: 'pending' | 'completed';
|
|
37
|
-
outcome?: 'accepted' | 'failed' | 'unknown';
|
|
38
|
-
error?: {
|
|
39
|
-
message: string;
|
|
40
|
-
code?: string;
|
|
41
|
-
};
|
|
42
|
-
/** Completed at the next start from the tree's timeline, not by the delivery itself. */
|
|
43
|
-
reconciled?: boolean;
|
|
44
32
|
updatedAt: string;
|
|
45
33
|
};
|
|
46
|
-
/** A receipt file that exists but cannot be read as one: its delivery's outcome is unknown. */
|
|
47
|
-
export type UnreadableReceipt = {
|
|
48
|
-
version: 1;
|
|
49
|
-
state: 'unreadable';
|
|
50
|
-
};
|
|
51
|
-
/** Failed writes since alpd started; `ok` until the first one (ALPD §66). */
|
|
52
|
-
export type StoreHealth = {
|
|
53
|
-
ok: boolean;
|
|
54
|
-
failures: number;
|
|
55
|
-
lastError?: {
|
|
56
|
-
at: string;
|
|
57
|
-
operation: string;
|
|
58
|
-
message: string;
|
|
59
|
-
};
|
|
60
|
-
};
|
|
61
34
|
export type Store = ReturnType<typeof createStore>;
|
|
62
35
|
export declare function createStore(root: string): {
|
|
63
36
|
put(record: SessionRecord): Promise<void>;
|
|
64
|
-
receipt(key: string): Promise<Receipt |
|
|
37
|
+
receipt(key: string): Promise<Receipt | undefined>;
|
|
65
38
|
putReceipt(key: string, receipt: Receipt): Promise<void>;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
receipts(): Promise<Array<{
|
|
69
|
-
key: string;
|
|
70
|
-
receipt: Receipt;
|
|
71
|
-
writtenAt: number;
|
|
72
|
-
}>>;
|
|
73
|
-
/** When the newest of these records' files was written (a restore writes them anew); 0 when none is there. */
|
|
74
|
-
writtenAt(ids: string[]): Promise<number>;
|
|
75
|
-
/**
|
|
76
|
-
* Deletes receipts not written for `maxAgeMs` and, with `temporaries` (only at start, when no
|
|
77
|
-
* write can be under way), temporary files a crash left behind.
|
|
78
|
-
*/
|
|
79
|
-
pruneReceipts(maxAgeMs: number, { temporaries }?: {
|
|
80
|
-
temporaries?: boolean | undefined;
|
|
81
|
-
}): Promise<void>;
|
|
39
|
+
/** Deletes receipts not written for `maxAgeMs`. */
|
|
40
|
+
pruneReceipts(maxAgeMs: number): Promise<void>;
|
|
82
41
|
list(): Promise<SessionRecord[]>;
|
|
83
42
|
append(rootId: string, envelope: Envelope): Promise<void>;
|
|
84
43
|
timeline(rootId: string): Promise<Envelope[]>;
|
|
85
|
-
/**
|
|
86
|
-
* Waits for the queued writes of these records and timelines, and names those that
|
|
87
|
-
* failed: a record whose last write failed, or a timeline that lost a line.
|
|
88
|
-
*/
|
|
89
|
-
drain({ records, timelines }: {
|
|
90
|
-
records?: string[] | undefined;
|
|
91
|
-
timelines?: string[] | undefined;
|
|
92
|
-
}): Promise<string[]>;
|
|
93
|
-
/**
|
|
94
|
-
* Whether the state directory can be read and written right now: a small file is written,
|
|
95
|
-
* read back and removed. `StoreHealth` only says what failed since alpd started.
|
|
96
|
-
*/
|
|
97
|
-
probe(): Promise<{
|
|
98
|
-
ok: boolean;
|
|
99
|
-
code?: string;
|
|
100
|
-
message?: string;
|
|
101
|
-
}>;
|
|
102
|
-
/** How many records, receipts and timelines are failed now: a later successful write clears a record, a lost timeline line never clears. */
|
|
103
|
-
failing(): number;
|
|
104
|
-
health(): StoreHealth;
|
|
105
44
|
/** Removes a whole tree: its records and its timeline. */
|
|
106
45
|
remove(rootId: string, ids: string[]): Promise<void>;
|
|
107
46
|
flush(): Promise<void>;
|
package/dist/store.js
CHANGED
|
@@ -1,188 +1,66 @@
|
|
|
1
1
|
// packages/daemon/src/store.ts
|
|
2
|
-
import { appendFile, mkdir,
|
|
3
|
-
import { replaceFile } from "./lock.js";
|
|
2
|
+
import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
4
3
|
import { randomBytes } from "node:crypto";
|
|
5
4
|
import path from "node:path";
|
|
6
|
-
import { createLogger } from "@anhlp/alp-core/log";
|
|
7
|
-
var log = createLogger({ component: "store" });
|
|
8
5
|
var SAFE = /[^\w.:-]/g;
|
|
9
6
|
var fileName = (id) => id.replace(SAFE, "_");
|
|
10
|
-
var TAIL_CHUNK = 64 * 1024;
|
|
11
7
|
function createStore(root) {
|
|
12
8
|
const sessionsDir = path.join(root, "sessions");
|
|
13
9
|
const timelineDir = path.join(root, "timeline");
|
|
14
10
|
const receiptsDir = path.join(root, "receipts");
|
|
15
11
|
const writes = /* @__PURE__ */ new Map();
|
|
16
12
|
const appends = /* @__PURE__ */ new Map();
|
|
17
|
-
const failed = /* @__PURE__ */ new Map();
|
|
18
|
-
const repaired = /* @__PURE__ */ new Set();
|
|
19
|
-
const health = { ok: true, failures: 0 };
|
|
20
13
|
let ready;
|
|
21
14
|
const prepare = () => ready ??= Promise.all([
|
|
22
15
|
mkdir(sessionsDir, { recursive: true, mode: 448 }),
|
|
23
16
|
mkdir(timelineDir, { recursive: true, mode: 448 }),
|
|
24
17
|
mkdir(receiptsDir, { recursive: true, mode: 448 })
|
|
25
18
|
]).then(() => {
|
|
26
|
-
}, (error) => {
|
|
27
|
-
ready = void 0;
|
|
28
|
-
throw error;
|
|
29
19
|
});
|
|
30
20
|
async function writeAtomic(file, body) {
|
|
31
21
|
const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
await replaceFile(temporary, file);
|
|
35
|
-
} catch (error) {
|
|
36
|
-
await rm(temporary, { force: true }).catch(() => {
|
|
37
|
-
});
|
|
38
|
-
throw error;
|
|
39
|
-
}
|
|
22
|
+
await writeFile(temporary, body, { mode: 384 });
|
|
23
|
+
await rename(temporary, file);
|
|
40
24
|
}
|
|
41
|
-
function queue(map, key,
|
|
25
|
+
function queue(map, key, work) {
|
|
42
26
|
const next = (map.get(key) ?? Promise.resolve()).then(prepare).then(work);
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (!sticky) failed.delete(failure);
|
|
47
|
-
},
|
|
48
|
-
(error) => {
|
|
49
|
-
failed.set(failure, error);
|
|
50
|
-
health.ok = false;
|
|
51
|
-
health.failures++;
|
|
52
|
-
health.lastError = { at: (/* @__PURE__ */ new Date()).toISOString(), operation, message: error?.message ?? String(error) };
|
|
53
|
-
log.error(`${operation} failed`, { code: "ALP_PERSISTENCE_WRITE_FAILED", operation, error, ...ids });
|
|
54
|
-
}
|
|
55
|
-
);
|
|
27
|
+
const settled = next.catch((error) => {
|
|
28
|
+
console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store`, error);
|
|
29
|
+
});
|
|
56
30
|
map.set(key, settled);
|
|
57
31
|
void settled.then(() => {
|
|
58
32
|
if (map.get(key) === settled) map.delete(key);
|
|
59
33
|
});
|
|
60
|
-
return
|
|
61
|
-
}
|
|
62
|
-
async function repairTail(file) {
|
|
63
|
-
const handle = await open(file, "r+").catch((error) => {
|
|
64
|
-
if (error?.code === "ENOENT") return void 0;
|
|
65
|
-
throw error;
|
|
66
|
-
});
|
|
67
|
-
if (!handle) return;
|
|
68
|
-
try {
|
|
69
|
-
const { size } = await handle.stat();
|
|
70
|
-
if (!size) return;
|
|
71
|
-
const last = Buffer.alloc(1);
|
|
72
|
-
await handle.read(last, 0, 1, size - 1);
|
|
73
|
-
if (last[0] === 10) return;
|
|
74
|
-
let start = 0;
|
|
75
|
-
for (let end = size; end > 0 && !start; end -= TAIL_CHUNK) {
|
|
76
|
-
const from = Math.max(0, end - TAIL_CHUNK);
|
|
77
|
-
const chunk = Buffer.alloc(end - from);
|
|
78
|
-
await handle.read(chunk, 0, chunk.length, from);
|
|
79
|
-
const newline = chunk.lastIndexOf(10);
|
|
80
|
-
if (newline >= 0) start = from + newline + 1;
|
|
81
|
-
}
|
|
82
|
-
const tail = Buffer.alloc(size - start);
|
|
83
|
-
await handle.read(tail, 0, tail.length, start);
|
|
84
|
-
let whole = false;
|
|
85
|
-
try {
|
|
86
|
-
JSON.parse(tail.toString("utf8"));
|
|
87
|
-
whole = true;
|
|
88
|
-
} catch {
|
|
89
|
-
}
|
|
90
|
-
if (whole) await handle.write("\n", size);
|
|
91
|
-
else await handle.truncate(start);
|
|
92
|
-
log.warn(`${whole ? "completed" : "removed"} a timeline line cut short in ${path.basename(file)} (${tail.length} bytes)`, { code: "ALP_TIMELINE_REPAIRED", file: path.basename(file), bytes: tail.length });
|
|
93
|
-
} finally {
|
|
94
|
-
await handle.close();
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
function parseTimeline(text, name) {
|
|
98
|
-
const envelopes = [];
|
|
99
|
-
let cursor = 0;
|
|
100
|
-
let skipped = 0;
|
|
101
|
-
for (const line of text.split("\n")) {
|
|
102
|
-
if (!line) continue;
|
|
103
|
-
let envelope;
|
|
104
|
-
try {
|
|
105
|
-
envelope = JSON.parse(line);
|
|
106
|
-
} catch {
|
|
107
|
-
skipped++;
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
cursor = typeof envelope.cursor === "number" && envelope.cursor > cursor ? envelope.cursor : cursor + 1;
|
|
111
|
-
envelopes.push({ ...envelope, cursor });
|
|
112
|
-
}
|
|
113
|
-
if (skipped) log.warn(`skipped ${skipped} unreadable timeline lines in ${name}`, { code: "ALP_TIMELINE_UNREADABLE", file: name, skipped });
|
|
114
|
-
return envelopes;
|
|
34
|
+
return settled;
|
|
115
35
|
}
|
|
116
|
-
const receiptFile = (key) => path.join(receiptsDir, `${fileName(key)}.json`);
|
|
117
36
|
return {
|
|
118
37
|
put(record) {
|
|
119
38
|
const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
|
|
120
39
|
const body = JSON.stringify(record);
|
|
121
|
-
return queue(writes, record.id,
|
|
40
|
+
return queue(writes, record.id, () => writeAtomic(file, body));
|
|
122
41
|
},
|
|
123
42
|
async receipt(key) {
|
|
124
43
|
await writes.get(`receipt:${key}`);
|
|
125
|
-
let text;
|
|
126
44
|
try {
|
|
127
|
-
|
|
45
|
+
const receipt = JSON.parse(await readFile(path.join(receiptsDir, `${fileName(key)}.json`), "utf8"));
|
|
46
|
+
return receipt?.version === 1 ? receipt : void 0;
|
|
128
47
|
} catch (error) {
|
|
129
48
|
if (error?.code === "ENOENT") return void 0;
|
|
130
49
|
throw error;
|
|
131
50
|
}
|
|
132
|
-
try {
|
|
133
|
-
const receipt = JSON.parse(text);
|
|
134
|
-
if (receipt?.version === 1 && typeof receipt.fingerprint === "string" && (receipt.state === "pending" || receipt.state === "completed")) return receipt;
|
|
135
|
-
} catch {
|
|
136
|
-
}
|
|
137
|
-
return { version: 1, state: "unreadable" };
|
|
138
51
|
},
|
|
139
52
|
putReceipt(key, receipt) {
|
|
140
53
|
const body = JSON.stringify(receipt);
|
|
141
|
-
return queue(writes, `receipt:${key}`,
|
|
54
|
+
return queue(writes, `receipt:${key}`, () => writeAtomic(path.join(receiptsDir, `${fileName(key)}.json`), body));
|
|
142
55
|
},
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
},
|
|
146
|
-
/** Every readable receipt with its key and when its file was last written. */
|
|
147
|
-
async receipts() {
|
|
148
|
-
await prepare();
|
|
149
|
-
const found = [];
|
|
150
|
-
for (const name of await readdir(receiptsDir)) {
|
|
151
|
-
if (!name.endsWith(".json")) continue;
|
|
152
|
-
const key = name.slice(0, -".json".length);
|
|
153
|
-
try {
|
|
154
|
-
const file = path.join(receiptsDir, name);
|
|
155
|
-
const receipt = JSON.parse(await readFile(file, "utf8"));
|
|
156
|
-
if (receipt?.version === 1 && typeof receipt.sessionId === "string") found.push({ key, receipt, writtenAt: (await stat(file)).mtimeMs });
|
|
157
|
-
} catch {
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return found;
|
|
161
|
-
},
|
|
162
|
-
/** When the newest of these records' files was written (a restore writes them anew); 0 when none is there. */
|
|
163
|
-
async writtenAt(ids) {
|
|
164
|
-
let newest = 0;
|
|
165
|
-
for (const id of ids) newest = Math.max(newest, await stat(path.join(sessionsDir, `${fileName(id)}.json`)).then((info) => info.mtimeMs, () => 0));
|
|
166
|
-
return newest;
|
|
167
|
-
},
|
|
168
|
-
/**
|
|
169
|
-
* Deletes receipts not written for `maxAgeMs` and, with `temporaries` (only at start, when no
|
|
170
|
-
* write can be under way), temporary files a crash left behind.
|
|
171
|
-
*/
|
|
172
|
-
async pruneReceipts(maxAgeMs, { temporaries = true } = {}) {
|
|
56
|
+
/** Deletes receipts not written for `maxAgeMs`. */
|
|
57
|
+
async pruneReceipts(maxAgeMs) {
|
|
173
58
|
await prepare();
|
|
174
59
|
const now = Date.now();
|
|
175
|
-
for (const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
if (temporaries) await rm(file, { force: true });
|
|
180
|
-
continue;
|
|
181
|
-
}
|
|
182
|
-
if (directory !== receiptsDir) continue;
|
|
183
|
-
const info = await stat(file).catch(() => void 0);
|
|
184
|
-
if (info && now - info.mtimeMs > maxAgeMs) await rm(file, { force: true });
|
|
185
|
-
}
|
|
60
|
+
for (const name of await readdir(receiptsDir)) {
|
|
61
|
+
const file = path.join(receiptsDir, name);
|
|
62
|
+
const info = await stat(file).catch(() => void 0);
|
|
63
|
+
if (info && now - info.mtimeMs > maxAgeMs) await rm(file, { force: true });
|
|
186
64
|
}
|
|
187
65
|
},
|
|
188
66
|
async list() {
|
|
@@ -193,71 +71,34 @@ function createStore(root) {
|
|
|
193
71
|
try {
|
|
194
72
|
const record = JSON.parse(await readFile(path.join(sessionsDir, name), "utf8"));
|
|
195
73
|
if (record?.version === 1 && typeof record.id === "string") records.push(record);
|
|
196
|
-
else
|
|
74
|
+
else console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store: skipped invalid record ${name}`);
|
|
197
75
|
} catch {
|
|
198
|
-
|
|
76
|
+
console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store: skipped unreadable record ${name}`);
|
|
199
77
|
}
|
|
200
78
|
}
|
|
201
79
|
return records;
|
|
202
80
|
},
|
|
203
81
|
append(rootId, envelope) {
|
|
204
|
-
const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
|
|
205
82
|
const line = `${JSON.stringify(envelope)}
|
|
206
83
|
`;
|
|
207
|
-
return queue(appends, rootId,
|
|
208
|
-
if (!repaired.has(rootId)) {
|
|
209
|
-
await repairTail(file);
|
|
210
|
-
repaired.add(rootId);
|
|
211
|
-
}
|
|
212
|
-
await appendFile(file, line, { mode: 384 });
|
|
213
|
-
}, true, { rootId });
|
|
84
|
+
return queue(appends, rootId, () => appendFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), line, { mode: 384 }));
|
|
214
85
|
},
|
|
215
86
|
async timeline(rootId) {
|
|
216
87
|
await appends.get(rootId);
|
|
217
|
-
const name = `${fileName(rootId)}.jsonl`;
|
|
218
88
|
try {
|
|
219
|
-
|
|
89
|
+
const text = await readFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), "utf8");
|
|
90
|
+
return text.split("\n").filter(Boolean).flatMap((line) => {
|
|
91
|
+
try {
|
|
92
|
+
return [JSON.parse(line)];
|
|
93
|
+
} catch {
|
|
94
|
+
return [];
|
|
95
|
+
}
|
|
96
|
+
});
|
|
220
97
|
} catch (error) {
|
|
221
98
|
if (error?.code === "ENOENT") return [];
|
|
222
99
|
throw error;
|
|
223
100
|
}
|
|
224
101
|
},
|
|
225
|
-
/**
|
|
226
|
-
* Waits for the queued writes of these records and timelines, and names those that
|
|
227
|
-
* failed: a record whose last write failed, or a timeline that lost a line.
|
|
228
|
-
*/
|
|
229
|
-
async drain({ records = [], timelines = [] }) {
|
|
230
|
-
await Promise.all([...records.map((id) => writes.get(id)), ...timelines.map((id) => appends.get(id))]);
|
|
231
|
-
return [...records.filter((id) => failed.has(id)), ...timelines.filter((id) => failed.has(`timeline:${id}`))];
|
|
232
|
-
},
|
|
233
|
-
/**
|
|
234
|
-
* Whether the state directory can be read and written right now: a small file is written,
|
|
235
|
-
* read back and removed. `StoreHealth` only says what failed since alpd started.
|
|
236
|
-
*/
|
|
237
|
-
async probe() {
|
|
238
|
-
const file = path.join(root, `.probe-${process.pid}-${randomBytes(3).toString("hex")}.tmp`);
|
|
239
|
-
const token = randomBytes(8).toString("hex");
|
|
240
|
-
let step = "write";
|
|
241
|
-
try {
|
|
242
|
-
await prepare();
|
|
243
|
-
await writeFile(file, token, { mode: 384 });
|
|
244
|
-
step = "read";
|
|
245
|
-
if (await readFile(file, "utf8") !== token) throw new Error("what was written is not what was read back");
|
|
246
|
-
return { ok: true };
|
|
247
|
-
} catch (error) {
|
|
248
|
-
return { ok: false, code: step === "write" ? "ALP_STATE_NOT_WRITABLE" : "ALP_STATE_NOT_READABLE", message: `${error?.code ? `${error.code}: ` : ""}${error?.message ?? error}` };
|
|
249
|
-
} finally {
|
|
250
|
-
await rm(file, { force: true }).catch(() => {
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
},
|
|
254
|
-
/** How many records, receipts and timelines are failed now: a later successful write clears a record, a lost timeline line never clears. */
|
|
255
|
-
failing() {
|
|
256
|
-
return failed.size;
|
|
257
|
-
},
|
|
258
|
-
health() {
|
|
259
|
-
return { ...health, ...health.lastError ? { lastError: { ...health.lastError } } : {} };
|
|
260
|
-
},
|
|
261
102
|
/** Removes a whole tree: its records and its timeline. */
|
|
262
103
|
async remove(rootId, ids) {
|
|
263
104
|
await Promise.all([...ids.map((id) => writes.get(id)), appends.get(rootId)]);
|
|
@@ -265,9 +106,6 @@ function createStore(root) {
|
|
|
265
106
|
...ids.map((id) => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
|
|
266
107
|
rm(path.join(timelineDir, `${fileName(rootId)}.jsonl`), { force: true })
|
|
267
108
|
]);
|
|
268
|
-
for (const id of ids) failed.delete(id);
|
|
269
|
-
failed.delete(`timeline:${rootId}`);
|
|
270
|
-
repaired.delete(rootId);
|
|
271
109
|
},
|
|
272
110
|
async flush() {
|
|
273
111
|
await Promise.all([...writes.values(), ...appends.values()]);
|
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-daemon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP daemon module",
|
|
6
6
|
"files": [
|
|
7
7
|
"src",
|
|
8
|
-
"dist"
|
|
9
|
-
"NOTICE"
|
|
8
|
+
"dist"
|
|
10
9
|
],
|
|
11
10
|
"exports": {
|
|
12
11
|
"./index": {
|
|
@@ -59,13 +58,13 @@
|
|
|
59
58
|
}
|
|
60
59
|
},
|
|
61
60
|
"engines": {
|
|
62
|
-
"node": ">=
|
|
61
|
+
"node": ">=20"
|
|
63
62
|
},
|
|
64
63
|
"dependencies": {
|
|
65
|
-
"@anhlp/alp-core": "0.
|
|
66
|
-
"@anhlp/alp-runtime": "0.
|
|
67
|
-
"@anhlp/alp-client": "0.
|
|
68
|
-
"@anhlp/alp-protocol": "0.
|
|
64
|
+
"@anhlp/alp-core": "0.10.0",
|
|
65
|
+
"@anhlp/alp-runtime": "0.10.0",
|
|
66
|
+
"@anhlp/alp-client": "0.10.0",
|
|
67
|
+
"@anhlp/alp-protocol": "0.10.0",
|
|
69
68
|
"@anthropic-ai/sdk": "^0.131.0",
|
|
70
69
|
"ws": "^8.22.0",
|
|
71
70
|
"zod": "4.4.3",
|
|
@@ -78,17 +77,11 @@
|
|
|
78
77
|
},
|
|
79
78
|
"publishConfig": {
|
|
80
79
|
"access": "public",
|
|
81
|
-
"registry": "https://registry.npmjs.org/"
|
|
82
|
-
"tag": "beta"
|
|
80
|
+
"registry": "https://registry.npmjs.org/"
|
|
83
81
|
},
|
|
84
|
-
"license": "Apache-2.0",
|
|
85
82
|
"repository": {
|
|
86
83
|
"type": "git",
|
|
87
|
-
"url": "git+https://github.com/phucanh08/alp.git",
|
|
84
|
+
"url": "git+https://github.com/phucanh08/alp-paseo.git",
|
|
88
85
|
"directory": "packages/daemon"
|
|
89
|
-
},
|
|
90
|
-
"homepage": "https://github.com/phucanh08/alp/tree/main/packages/daemon#readme",
|
|
91
|
-
"bugs": {
|
|
92
|
-
"url": "https://github.com/phucanh08/alp/issues"
|
|
93
86
|
}
|
|
94
87
|
}
|
package/src/lock.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { unlink, utimes, writeFile, rename } from 'node:fs/promises';
|
|
2
|
-
import {
|
|
1
|
+
import { open, readFile, unlink, utimes, writeFile, rename } from 'node:fs/promises';
|
|
2
|
+
import { bootTime, daemonPaths, lockAlive, readLock } from '@anhlp/alp-client/index';
|
|
3
3
|
|
|
4
4
|
export type LockContents = {
|
|
5
5
|
pid: number;
|
|
@@ -13,29 +13,32 @@ export type LockContents = {
|
|
|
13
13
|
};
|
|
14
14
|
|
|
15
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'>)
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if (
|
|
29
|
-
|
|
16
|
+
export async function acquireLock(home: string, contents: Omit<LockContents, 'pid' | 'startedAt' | 'bootTime' | 'uid' | 'ready'>) {
|
|
17
|
+
const file = daemonPaths(home).lock;
|
|
18
|
+
const lock: LockContents = { pid: process.pid, startedAt: new Date().toISOString(), bootTime: bootTime(), uid: process.getuid?.() ?? -1, ready: false, ...contents };
|
|
19
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
20
|
+
try {
|
|
21
|
+
const handle = await open(file, 'wx', 0o600);
|
|
22
|
+
await handle.writeFile(JSON.stringify(lock));
|
|
23
|
+
await handle.close();
|
|
24
|
+
return lock;
|
|
25
|
+
} catch (error: any) {
|
|
26
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
27
|
+
const current = await readLock(home);
|
|
28
|
+
if (lockAlive(current)) throw new Error(`ALP daemon already running (pid ${current.pid})`);
|
|
29
|
+
// Remove the stale lock only if nobody replaced it meanwhile.
|
|
30
|
+
const again = await readFile(file, 'utf8').catch(() => undefined);
|
|
31
|
+
if (again === undefined || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {});
|
|
30
32
|
}
|
|
31
33
|
}
|
|
34
|
+
throw new Error('Could not acquire the ALP daemon lock');
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
export async function updateLock(home: string, lock: LockContents) {
|
|
35
38
|
const file = daemonPaths(home).lock;
|
|
36
39
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
37
40
|
await writeFile(temporary, JSON.stringify(lock), { mode: 0o600 });
|
|
38
|
-
await
|
|
41
|
+
await rename(temporary, file);
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
/** True while this process still owns the lock; refreshes its mtime as a heartbeat. */
|