@tnunamak/dalan 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +25 -64
- package/bin/dalan.mjs +9 -0
- package/bin/dot-worker.mjs +16 -2
- package/docs/chatgpt-worker-onboarding.md +10 -14
- package/docs/claude-worker-onboarding.md +9 -8
- package/docs/codex-to-muse.md +21 -35
- package/docs/connect-chatgpt.md +10 -16
- package/docs/dalan-upgrade.md +4 -2
- package/docs/local-agent-mcp.md +24 -4
- package/docs/manual-setup.md +2 -2
- package/docs/operations.md +10 -11
- package/docs/pull-workers.md +1 -2
- package/docs/service-setup.md +99 -145
- package/docs/setup-reference.md +5 -5
- package/docs/worker-clients.md +4 -4
- package/package.json +2 -3
- package/scripts/dalan-try-selfcheck.mjs +8 -7
- package/scripts/worker-bridge-setup.mjs +91 -81
- package/src/as-store.mjs +5 -3
- package/src/as.mjs +35 -26
- package/src/auth-check.mjs +53 -0
- package/src/cli-help.mjs +20 -15
- package/src/client-approval.mjs +57 -0
- package/src/client-convenience.mjs +166 -0
- package/src/client-conveniences.json +106 -0
- package/src/client-conveniences.schema.json +97 -0
- package/src/connect-cli.mjs +5 -5
- package/src/default-home.mjs +36 -0
- package/src/follow-current.mjs +25 -0
- package/src/gozar-routes.mjs +314 -0
- package/src/redirect-policy.mjs +61 -0
- package/src/route-setting.mjs +71 -12
- package/src/server.mjs +38 -2
- package/src/service-auto-update.mjs +68 -0
- package/src/service-launchd.mjs +166 -0
- package/src/service-update-gate.mjs +20 -0
- package/src/service-update-lock.mjs +22 -0
- package/src/service-update-runtime.mjs +290 -0
- package/src/service-update.mjs +399 -0
- package/src/service.mjs +241 -58
- package/src/setup.mjs +55 -44
- package/src/try-exposure.mjs +7 -657
- package/src/try-hosted.mjs +71 -101
- package/src/try-selfcheck.mjs +15 -8
- package/src/try.mjs +9 -13
- package/scripts/lib/expose-tailscale.mjs +0 -408
- package/src/try-hosted-clients.mjs +0 -46
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
5
|
+
import { defaultPath } from './paths.mjs';
|
|
6
|
+
import { acquireUpdateLock } from './service-update-lock.mjs';
|
|
7
|
+
import { writeAtomic } from './as-files.mjs';
|
|
8
|
+
import { latestRelease as defaultLatest, installRelease as defaultInstall, probeService as defaultProbe, probeCandidate as defaultCandidate, controlService as defaultControl } from './service-update-runtime.mjs';
|
|
9
|
+
|
|
10
|
+
const PACKAGE = '@tnunamak/dalan';
|
|
11
|
+
const HEALTH_TIMEOUT_MS = 30_000;
|
|
12
|
+
const fail = message => { throw new Error(message); };
|
|
13
|
+
const privateDir = dir => fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
14
|
+
function readReceipt(home) {
|
|
15
|
+
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
|
|
16
|
+
let st, value;
|
|
17
|
+
try { st = fs.lstatSync(file); value = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
18
|
+
catch { fail(`service receipt is missing or invalid: ${file}`); }
|
|
19
|
+
if (!st.isFile() || st.isSymbolicLink() || (st.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
|
|
20
|
+
if (!value || value.schema_version !== 1 || value.home !== home || !value.unit) fail(`${file} has an unsupported service receipt`);
|
|
21
|
+
return { file, value };
|
|
22
|
+
}
|
|
23
|
+
function canonical(x) {
|
|
24
|
+
if (Array.isArray(x)) return `[${x.map(canonical).join(',')}]`;
|
|
25
|
+
if (x && typeof x === 'object') return `{${Object.keys(x).sort().map(k => `${JSON.stringify(k)}:${canonical(x[k])}`).join(',')}}`;
|
|
26
|
+
return JSON.stringify(x);
|
|
27
|
+
}
|
|
28
|
+
function canonicalCatalogs(catalogs) {
|
|
29
|
+
return canonical(Object.fromEntries(Object.keys(catalogs ?? {}).sort().map(worker => [worker,
|
|
30
|
+
[...(catalogs[worker] ?? [])].sort((a, b) => String(a?.name).localeCompare(String(b?.name)))])));
|
|
31
|
+
}
|
|
32
|
+
function configurationDigest(home, receipt) {
|
|
33
|
+
const root = defaultPath(home, '.config/dot-bridge');
|
|
34
|
+
const hash = createHash('sha256');
|
|
35
|
+
hash.update(canonical({ enable_workspace: !!receipt.enable_workspace, enable_t3: !!receipt.enable_t3 }));
|
|
36
|
+
for (const name of ['workers.json', 'workers-repos.json', 'as.json', 'as-jwks.json', 'as-cookie-keys.json', 'as-storage.key', 'operator.key', 'env']) {
|
|
37
|
+
const file = path.join(root, name);
|
|
38
|
+
let st;
|
|
39
|
+
try { st = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') { hash.update(`missing:${name}`); continue; } throw error; }
|
|
40
|
+
if (!st.isFile() || st.isSymbolicLink()) fail(`configuration input must be a regular file: ${file}`);
|
|
41
|
+
hash.update(`file:${name}:${st.mode & 0o777}:`); hash.update(fs.readFileSync(file));
|
|
42
|
+
}
|
|
43
|
+
return hash.digest('hex');
|
|
44
|
+
}
|
|
45
|
+
function completeCatalogs(a, b, workers) {
|
|
46
|
+
if (!a?.catalogs || !b?.catalogs) return false;
|
|
47
|
+
const keysA = Object.keys(a.catalogs).sort(), keysB = Object.keys(b.catalogs).sort();
|
|
48
|
+
if (canonical(keysA) !== canonical(keysB) || canonical(keysA) !== canonical([...workers].sort())) return false;
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
function catalogsEqual(a, b, workers) {
|
|
52
|
+
return completeCatalogs(a, b, workers) && canonicalCatalogs(a.catalogs) === canonicalCatalogs(b.catalogs);
|
|
53
|
+
}
|
|
54
|
+
// A 0.6.0 or 0.6.1 server has no /service-check, so its catalogs are unknown (stored as {}); nothing can be compared against them.
|
|
55
|
+
const hasCatalogs = catalogs => !!catalogs && Object.keys(catalogs).length > 0;
|
|
56
|
+
function releaseVersion(r, current) {
|
|
57
|
+
if (!r || r.name !== PACKAGE || typeof r.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(r.version) || typeof r.dist?.integrity !== 'string' || !r.dist.integrity.startsWith('sha512-')) fail('registry returned invalid stable release metadata');
|
|
58
|
+
const parts = s => s.split('.').map(Number), a = parts(r.version), b = parts(current);
|
|
59
|
+
if (!/^\d+\.\d+\.\d+$/.test(current) || a.some(n => !Number.isSafeInteger(n))) fail('installed service version is not a stable semantic version');
|
|
60
|
+
return a[0] > b[0] || a[0] === b[0] && (a[1] > b[1] || a[1] === b[1] && a[2] > b[2]);
|
|
61
|
+
}
|
|
62
|
+
function atomic(file, text) {
|
|
63
|
+
privateDir(path.dirname(file)); writeAtomic(file, text);
|
|
64
|
+
}
|
|
65
|
+
const failedFile = home => path.join(home, 'update-failed.json');
|
|
66
|
+
function readFailed(home) {
|
|
67
|
+
try {
|
|
68
|
+
const v = JSON.parse(fs.readFileSync(failedFile(home), 'utf8'));
|
|
69
|
+
return typeof v?.version === 'string' && typeof v.integrity === 'string' ? v : null;
|
|
70
|
+
} catch { return null; }
|
|
71
|
+
}
|
|
72
|
+
function copyTree(src, dst) {
|
|
73
|
+
const st = fs.lstatSync(src);
|
|
74
|
+
if (st.isSymbolicLink()) { fs.symlinkSync(fs.readlinkSync(src), dst); return; }
|
|
75
|
+
if (!st.isDirectory() && !st.isFile()) return;
|
|
76
|
+
if (st.isDirectory()) {
|
|
77
|
+
fs.mkdirSync(dst, { recursive: true, mode: st.mode & 0o777 });
|
|
78
|
+
for (const name of fs.readdirSync(src)) copyTree(path.join(src, name), path.join(dst, name));
|
|
79
|
+
fs.chmodSync(dst, st.mode & 0o777);
|
|
80
|
+
} else { fs.copyFileSync(src, dst); fs.chmodSync(dst, st.mode & 0o777); }
|
|
81
|
+
}
|
|
82
|
+
function replaceTree(src, dst) {
|
|
83
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
84
|
+
if (fs.existsSync(src)) copyTree(src, dst);
|
|
85
|
+
}
|
|
86
|
+
function snapshot(home, txn) {
|
|
87
|
+
const target = path.join(txn, 'snapshot.pending'); fs.rmSync(target, { recursive: true, force: true }); privateDir(target);
|
|
88
|
+
const roots = {};
|
|
89
|
+
for (const item of ['.config', '.local']) {
|
|
90
|
+
const src = path.join(home, item);
|
|
91
|
+
if (fs.existsSync(src)) {
|
|
92
|
+
const st = fs.lstatSync(src);
|
|
93
|
+
if (!st.isDirectory() || st.isSymbolicLink()) fail(`cannot snapshot non-directory service state: ${src}`);
|
|
94
|
+
roots[item] = true; copyTree(src, path.join(target, item));
|
|
95
|
+
} else roots[item] = false;
|
|
96
|
+
}
|
|
97
|
+
atomic(path.join(target, '.snapshot-complete.json'), JSON.stringify({ complete: true, roots }));
|
|
98
|
+
const ready = path.join(txn, 'snapshot'); fs.rmSync(ready, { recursive: true, force: true }); fs.renameSync(target, ready); return ready;
|
|
99
|
+
}
|
|
100
|
+
function validateSnapshot(tx) {
|
|
101
|
+
const root = tx.snapshot;
|
|
102
|
+
let marker;
|
|
103
|
+
try {
|
|
104
|
+
const st = fs.lstatSync(root);
|
|
105
|
+
if (!st.isDirectory() || st.isSymbolicLink()) fail('transaction snapshot is not a real directory');
|
|
106
|
+
marker = JSON.parse(fs.readFileSync(path.join(root, '.snapshot-complete.json'), 'utf8'));
|
|
107
|
+
} catch { fail('transaction snapshot is missing or incomplete; refusing to restore service state'); }
|
|
108
|
+
if (marker.complete !== true || !marker.roots || typeof marker.roots['.config'] !== 'boolean' || typeof marker.roots['.local'] !== 'boolean') fail('transaction snapshot completion marker is invalid');
|
|
109
|
+
for (const item of ['.config', '.local']) {
|
|
110
|
+
const file = path.join(root, item), exists = fs.existsSync(file);
|
|
111
|
+
if (exists !== marker.roots[item]) fail(`transaction snapshot is incomplete for ${item}; refusing to restore service state`);
|
|
112
|
+
if (exists) { const st = fs.lstatSync(file); if (!st.isDirectory() || st.isSymbolicLink()) fail(`transaction snapshot is invalid for ${item}`); }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function unitPath(receipt, home) {
|
|
116
|
+
if (!/^[A-Za-z0-9_.@-]+$/.test(String(receipt.unit ?? ''))) fail('invalid service unit name in receipt');
|
|
117
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
118
|
+
const dir = receipt.unit_dir || path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config'), 'systemd/user');
|
|
119
|
+
if (!path.isAbsolute(dir) || dir.includes('\n')) fail('invalid service unit directory in receipt');
|
|
120
|
+
const name = String(receipt.unit).endsWith('.service') ? String(receipt.unit) : `${receipt.unit}.service`;
|
|
121
|
+
return path.join(dir, name);
|
|
122
|
+
}
|
|
123
|
+
// A 0.6.0 or 0.6.1 receipt names no package, node binary or unit directory. Read them from the unit that runs the service,
|
|
124
|
+
// so the first update adopts the install with no hand step and keeps the node binary the service already uses.
|
|
125
|
+
function adoptInstall(receipt, home) {
|
|
126
|
+
if (receipt.repo && receipt.node && receipt.unit_dir) return receipt;
|
|
127
|
+
const file = unitPath(receipt, home);
|
|
128
|
+
let text;
|
|
129
|
+
try { const st = fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink()) fail('not a regular file'); text = fs.readFileSync(file, 'utf8'); }
|
|
130
|
+
catch { fail(`cannot read the service unit to adopt this install: ${file}`); }
|
|
131
|
+
// 0.6.0 and 0.6.1 wrote WorkingDirectory with a trailing slash; compare normalized paths and record the normalized repo.
|
|
132
|
+
const written = text.match(/^WorkingDirectory=(.+)$/m)?.[1], exec = text.match(/^ExecStart=(\S+) (\S+)$/m);
|
|
133
|
+
const repo = written && path.isAbsolute(written) ? path.resolve(written) : null;
|
|
134
|
+
if (!repo || !exec || !path.isAbsolute(exec[2]) || path.resolve(exec[2]) !== path.join(repo, 'src/server.mjs') || !path.isAbsolute(exec[1])) fail(`service unit does not contain a supported Dalan command: ${file}`);
|
|
135
|
+
return { ...receipt, repo: receipt.repo ?? repo, node: receipt.node ?? exec[1], unit_dir: receipt.unit_dir ?? path.dirname(file) };
|
|
136
|
+
}
|
|
137
|
+
function rewriteUnit(file, current, home) {
|
|
138
|
+
if (!fs.existsSync(file)) fail(`service unit is missing: ${file}`);
|
|
139
|
+
const st = fs.lstatSync(file);
|
|
140
|
+
if (!st.isFile() || st.isSymbolicLink()) fail(`service unit must be a regular file: ${file}`);
|
|
141
|
+
const before = fs.readFileSync(file, 'utf8');
|
|
142
|
+
const oldRepoWritten = before.match(/^WorkingDirectory=(.+)$/m)?.[1];
|
|
143
|
+
const oldRepo = oldRepoWritten && path.isAbsolute(oldRepoWritten) ? path.resolve(oldRepoWritten) : oldRepoWritten;
|
|
144
|
+
const exec = before.match(/^ExecStart=(.+)$/m)?.[1];
|
|
145
|
+
if (!oldRepo || !exec || !exec.endsWith('/src/server.mjs')) fail(`service unit does not contain a supported Dalan command: ${file}`);
|
|
146
|
+
const after = before.split('\n').map(line => /^WorkingDirectory=/.test(line) ? `WorkingDirectory=${current}` : /^ExecStart=/.test(line) ? line.replace(/\/src\/server\.mjs(?:\s.*)?$/, `${path.sep}src${path.sep}server.mjs`) : line).join('\n');
|
|
147
|
+
// Preserve the selected package in ExecStart, including its node executable prefix.
|
|
148
|
+
const fixed = after.replaceAll(`${oldRepo}/src/server.mjs`, `${current}/src/server.mjs`);
|
|
149
|
+
const lines = fixed.split('\n').filter(l => !/^ExecStartPre=.*\sservice recover\s/.test(l));
|
|
150
|
+
const i = lines.findIndex(l => /^ExecStart=/.test(l));
|
|
151
|
+
const execLine = lines[i].slice('ExecStart='.length), nodeBin = execLine.slice(0, execLine.indexOf(' '));
|
|
152
|
+
lines.splice(i + 1, 0, `ExecStartPre=${nodeBin} ${current}/bin/dalan.mjs service recover --home ${home} --quiet`);
|
|
153
|
+
atomic(file, lines.join('\n')); fs.chmodSync(file, st.mode & 0o777); return before;
|
|
154
|
+
}
|
|
155
|
+
function select(home, repo) {
|
|
156
|
+
const current = path.join(home, 'current'), tmp = path.join(home, `.current-${randomUUID()}`);
|
|
157
|
+
fs.symlinkSync(path.relative(home, repo), tmp); fs.renameSync(tmp, current);
|
|
158
|
+
}
|
|
159
|
+
function prune(home, active, previous) {
|
|
160
|
+
const root = path.join(home, 'versions'); if (!fs.existsSync(root)) return;
|
|
161
|
+
const dirs = fs.readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory() && !d.isSymbolicLink()).map(d => d.name).sort((a,b) => b.localeCompare(a, undefined, { numeric: true }));
|
|
162
|
+
const keep = new Set([active, previous]);
|
|
163
|
+
for (const name of dirs) { if (keep.size >= 3) break; keep.add(name); }
|
|
164
|
+
for (const name of dirs) if (!keep.has(name)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
async function probeReady(probe, home, receipt, healthTimeoutMs = HEALTH_TIMEOUT_MS) {
|
|
167
|
+
const deadline = performance.now() + healthTimeoutMs;
|
|
168
|
+
let error;
|
|
169
|
+
while (performance.now() < deadline) {
|
|
170
|
+
const remaining = deadline - performance.now();
|
|
171
|
+
try { return await probe(home, receipt, { timeout: Math.max(1, Math.min(remaining, 1000)) }); }
|
|
172
|
+
catch (e) {
|
|
173
|
+
error = e;
|
|
174
|
+
const delay = Math.min(150, Math.max(0, deadline - performance.now()));
|
|
175
|
+
if (delay) await new Promise(resolve => setTimeout(resolve, delay));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
throw new Error(`service health check timed out after ${healthTimeoutMs}ms${error ? `: ${error.message}` : ''}`);
|
|
179
|
+
}
|
|
180
|
+
function readJournal(home) {
|
|
181
|
+
const file = path.join(home, 'update-transaction.json');
|
|
182
|
+
let txStat;
|
|
183
|
+
try { txStat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
184
|
+
if (!txStat.isFile() || txStat.isSymbolicLink() || (txStat.mode & 0o777) !== 0o600) fail('update transaction must be a private regular file');
|
|
185
|
+
let tx;
|
|
186
|
+
try { tx = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail('update transaction is invalid JSON'); }
|
|
187
|
+
const oldReceipt = tx?.oldReceipt;
|
|
188
|
+
if (tx.home !== home || !oldReceipt || oldReceipt.home !== home || oldReceipt.schema_version !== 1 || !oldReceipt.unit ||
|
|
189
|
+
!tx.oldRepo || !tx.oldVersion || !tx.snapshot || !['prepared', 'switched', 'committed'].includes(tx.phase)) fail('invalid interrupted update transaction');
|
|
190
|
+
if (tx.unitFile !== (oldReceipt.unit && oldReceipt.platform !== 'darwin' ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
|
|
191
|
+
if (path.resolve(tx.snapshot) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
|
|
192
|
+
return { file, tx };
|
|
193
|
+
}
|
|
194
|
+
// Put the old package, unit and saved state back on disk. Touches no service and probes nothing.
|
|
195
|
+
function restoreFiles(home, tx) {
|
|
196
|
+
validateSnapshot(tx);
|
|
197
|
+
select(home, tx.oldRepo);
|
|
198
|
+
if (tx.unitFile && tx.oldUnit != null) atomic(tx.unitFile, tx.oldUnit);
|
|
199
|
+
for (const item of ['.config', '.local']) replaceTree(path.join(tx.snapshot, item), path.join(home, item));
|
|
200
|
+
}
|
|
201
|
+
function discardJournal(home, tx) {
|
|
202
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
|
|
203
|
+
fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true });
|
|
204
|
+
}
|
|
205
|
+
function restoreFromJournal(home, tx) {
|
|
206
|
+
if (tx.phase === 'committed') {
|
|
207
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
|
|
208
|
+
try { fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true }); } catch { /* committed service stays selected */ }
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (tx.phase === 'switched') restoreFiles(home, tx);
|
|
212
|
+
discardJournal(home, tx);
|
|
213
|
+
}
|
|
214
|
+
// Run at service start (ExecStartPre): finish filesystem recovery without touching systemd.
|
|
215
|
+
export function recoverService({ home }) {
|
|
216
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
217
|
+
if (!fs.existsSync(path.join(home, 'update-transaction.json'))) return { outcome: 'nothing_pending' };
|
|
218
|
+
let release;
|
|
219
|
+
try { release = acquireUpdateLock(home); }
|
|
220
|
+
catch (error) { if (/already running/.test(error.message)) return { outcome: 'update_running' }; throw error; }
|
|
221
|
+
try {
|
|
222
|
+
const journal = readJournal(home);
|
|
223
|
+
if (!journal) return { outcome: 'nothing_pending' };
|
|
224
|
+
restoreFromJournal(home, journal.tx);
|
|
225
|
+
return { outcome: 'recovered' };
|
|
226
|
+
} finally { release(); }
|
|
227
|
+
}
|
|
228
|
+
async function recover(home, control, probe, healthTimeoutMs) {
|
|
229
|
+
const journal = readJournal(home);
|
|
230
|
+
if (!journal) return;
|
|
231
|
+
const { tx } = journal, oldReceipt = tx.oldReceipt;
|
|
232
|
+
if (tx.phase === 'committed') return restoreFromJournal(home, tx);
|
|
233
|
+
if (tx.phase === 'prepared') {
|
|
234
|
+
await control(oldReceipt, 'restart');
|
|
235
|
+
const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
|
|
236
|
+
if (live.version !== tx.oldVersion || hasCatalogs(tx.oldCatalogs) && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs))) fail('interrupted update recovery could not verify old service');
|
|
237
|
+
} else {
|
|
238
|
+
validateSnapshot(tx);
|
|
239
|
+
await control(oldReceipt, 'stop'); restoreFiles(home, tx);
|
|
240
|
+
await control(oldReceipt, 'daemon-reload'); await control(oldReceipt, 'restart');
|
|
241
|
+
const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
|
|
242
|
+
if (tx.oldCatalogs && (live.version !== tx.oldVersion || hasCatalogs(tx.oldCatalogs) && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs)))) fail('interrupted update recovery restored selection but old service health failed');
|
|
243
|
+
}
|
|
244
|
+
discardJournal(home, tx);
|
|
245
|
+
}
|
|
246
|
+
function actualWorkers(home) {
|
|
247
|
+
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'workers.json');
|
|
248
|
+
let value;
|
|
249
|
+
try { value = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail(`cannot read configured workers: ${file}`); }
|
|
250
|
+
const workers = Object.keys(value?.workers ?? {}).sort();
|
|
251
|
+
if (!workers.length) fail('configured worker set is empty');
|
|
252
|
+
return workers;
|
|
253
|
+
}
|
|
254
|
+
export async function updateService({ home, check = false, yes = false, retry = false }, seams = {}) {
|
|
255
|
+
if (check && retry) fail('--retry cannot be used with --check');
|
|
256
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
257
|
+
const latest = seams.latestRelease ?? defaultLatest, install = seams.installRelease ?? defaultInstall;
|
|
258
|
+
const probe = seams.probeService ?? defaultProbe, candidateProbe = seams.probeCandidate ?? defaultCandidate;
|
|
259
|
+
const control = seams.controlService ?? defaultControl, pruneVersions = seams.pruneVersions ?? prune;
|
|
260
|
+
const healthTimeoutMs = seams.healthTimeoutMs ?? HEALTH_TIMEOUT_MS;
|
|
261
|
+
if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0) fail('healthTimeoutMs must be a positive finite duration');
|
|
262
|
+
if (check) {
|
|
263
|
+
const receipt = adoptInstall(readReceipt(home).value, home), active = fs.existsSync(path.join(home, 'current')) ? fs.realpathSync(path.join(home, 'current')) : receipt.repo;
|
|
264
|
+
if (!active) fail('current service repository is missing');
|
|
265
|
+
const current = JSON.parse(fs.readFileSync(path.join(active, 'package.json'), 'utf8')).version;
|
|
266
|
+
const r = await latest(receipt); const forward = releaseVersion(r, current);
|
|
267
|
+
const result = { outcome: forward ? 'update_available' : 'up_to_date', current_version: current, latest_version: r.version };
|
|
268
|
+
if (!forward) result.outcome = 'up_to_date';
|
|
269
|
+
atomic(path.join(home, 'update-result.json'), JSON.stringify({ ...result, timestamp: new Date().toISOString() })); return result;
|
|
270
|
+
}
|
|
271
|
+
privateDir(home);
|
|
272
|
+
const releaseLock = acquireUpdateLock(home);
|
|
273
|
+
const resultFile = path.join(home, 'update-result.json');
|
|
274
|
+
let result, attempted;
|
|
275
|
+
try {
|
|
276
|
+
await recover(home, control, probe, healthTimeoutMs);
|
|
277
|
+
const { value: storedReceipt, file: receiptFile } = readReceipt(home);
|
|
278
|
+
const receipt = adoptInstall(storedReceipt, home);
|
|
279
|
+
let current = path.join(home, 'current');
|
|
280
|
+
let oldRepo = fs.existsSync(current) ? fs.realpathSync(current) : receipt.repo;
|
|
281
|
+
if (!oldRepo || !fs.existsSync(oldRepo)) fail('current service repository is missing');
|
|
282
|
+
const oldVersion = JSON.parse(fs.readFileSync(path.join(oldRepo, 'package.json'), 'utf8')).version;
|
|
283
|
+
const workers = actualWorkers(home);
|
|
284
|
+
const r = await latest(receipt), forward = releaseVersion(r, oldVersion);
|
|
285
|
+
if (!forward) { result = { outcome: 'up_to_date', current_version: oldVersion, latest_version: r.version }; return result; }
|
|
286
|
+
const failed = readFailed(home);
|
|
287
|
+
if (!retry && failed && failed.version === r.version && failed.integrity === r.dist.integrity) {
|
|
288
|
+
result = { outcome: 'skipped_failed_release', current_version: oldVersion, latest_version: r.version, failed_version: failed.version, message: `Release ${r.version} was rolled back earlier; not retrying automatically. Run dalan service update --retry to try it again.` };
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
attempted = r;
|
|
292
|
+
const installed = await install(home, r);
|
|
293
|
+
const candidate = path.resolve(installed), versions = path.resolve(home, 'versions');
|
|
294
|
+
if (candidate !== path.join(versions, r.version, 'node_modules', '@tnunamak', 'dalan') || !candidate.startsWith(`${versions}${path.sep}`) || fs.realpathSync(candidate) !== candidate) fail('candidate repository does not match exact package version path');
|
|
295
|
+
const packageInfo = JSON.parse(fs.readFileSync(path.join(candidate, 'package.json'), 'utf8'));
|
|
296
|
+
if (packageInfo.name !== PACKAGE || packageInfo.version !== r.version) fail('installed candidate package identity does not match registry release');
|
|
297
|
+
const base = await probe(home, receipt), legacy = base.legacy === true;
|
|
298
|
+
const configBeforeCandidate = configurationDigest(home, receipt);
|
|
299
|
+
const tested = await candidateProbe(home, receipt, candidate);
|
|
300
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed during candidate self-check; retry update');
|
|
301
|
+
if (base.version !== oldVersion || tested.version !== r.version) fail('service probe returned an unexpected package version');
|
|
302
|
+
if (!completeCatalogs(legacy ? tested : base, tested, workers)) fail('candidate self-check failed or worker catalogs are incomplete');
|
|
303
|
+
const changedCatalog = !legacy && !catalogsEqual(base, tested, workers);
|
|
304
|
+
if (changedCatalog && !yes) {
|
|
305
|
+
result = { outcome: 'connector_refresh_required', current_version: oldVersion, candidate_version: r.version, connector_refresh_required: true, message: 'Worker tool catalogs changed. Run dalan service update --yes with the same --home to switch, then refresh hosted connectors.' };
|
|
306
|
+
prune(home, oldVersion, r.version);
|
|
307
|
+
return result;
|
|
308
|
+
}
|
|
309
|
+
// A catalog difference requires explicit consent; exact parity may proceed without it.
|
|
310
|
+
const digestBeforeRecheck = configurationDigest(home, receipt);
|
|
311
|
+
const liveAgain = await probe(home, receipt);
|
|
312
|
+
if (liveAgain.version !== oldVersion || !legacy && !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
|
|
313
|
+
if (configurationDigest(home, receipt) !== digestBeforeRecheck || digestBeforeRecheck !== configBeforeCandidate) fail('service configuration changed during update; retry after connector refresh');
|
|
314
|
+
// A macOS agent runs the package through the home's `current` link, so a switch needs no plist rewrite.
|
|
315
|
+
const unitFile = receipt.unit && receipt.platform !== 'darwin' ? unitPath(receipt, home) : null;
|
|
316
|
+
const txDir = path.join(home, 'update-backup'); privateDir(txDir);
|
|
317
|
+
const tx = { home, oldRepo, candidate, snapshot: path.join(txDir, 'snapshot'), unitFile, oldUnit: unitFile && fs.existsSync(unitFile) ? fs.readFileSync(unitFile, 'utf8') : null, oldCatalogs: base.catalogs ?? {}, oldVersion, oldReceipt: { ...receipt }, phase: 'prepared' };
|
|
318
|
+
if (unitFile && tx.oldUnit == null) fail(`service unit is missing: ${unitFile}`);
|
|
319
|
+
atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
|
|
320
|
+
try {
|
|
321
|
+
await control(receipt, 'stop');
|
|
322
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while stopping; update cancelled');
|
|
323
|
+
snapshot(home, txDir);
|
|
324
|
+
if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while preparing switch; update cancelled');
|
|
325
|
+
tx.phase = 'switched'; atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
|
|
326
|
+
atomic(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), JSON.stringify({ version: r.version, catalogs: tested.catalogs }));
|
|
327
|
+
select(home, candidate);
|
|
328
|
+
if (unitFile) rewriteUnit(unitFile, current, home);
|
|
329
|
+
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
330
|
+
const live = await probeReady(probe, home, { ...receipt, repo: candidate }, healthTimeoutMs);
|
|
331
|
+
if (live.version !== r.version || !completeCatalogs(tested, live, workers) || !catalogsEqual(tested, live, workers)) fail('updated service health or worker catalogs failed');
|
|
332
|
+
receipt.repo = candidate; receipt.version = r.version;
|
|
333
|
+
atomic(receiptFile, JSON.stringify(receipt));
|
|
334
|
+
fs.rmSync(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), { force: true });
|
|
335
|
+
const committedTx = { ...tx, phase: 'committed' };
|
|
336
|
+
try { atomic(path.join(home, 'update-transaction.json'), JSON.stringify(committedTx)); }
|
|
337
|
+
catch (error) {
|
|
338
|
+
let journal;
|
|
339
|
+
try { journal = JSON.parse(fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8')); }
|
|
340
|
+
catch { error.preserveCandidate = true; throw error; }
|
|
341
|
+
if (journal.phase === 'committed' && journal.home === home) {
|
|
342
|
+
tx.phase = 'committed';
|
|
343
|
+
try { fs.rmSync(failedFile(home), { force: true }); } catch { /* see above */ }
|
|
344
|
+
result = { outcome: 'updated', previous_version: oldVersion, version: r.version, cleanup_warning: `committed journal is visible but its durability check failed: ${error.message}; recovery data was preserved` };
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
if (journal.phase !== 'switched') { error.preserveCandidate = true; throw error; }
|
|
348
|
+
throw error;
|
|
349
|
+
}
|
|
350
|
+
tx.phase = 'committed';
|
|
351
|
+
result = { outcome: 'updated', previous_version: oldVersion, version: r.version, ...(legacy ? { adopted_legacy_server: true } : {}) };
|
|
352
|
+
try { fs.rmSync(failedFile(home), { force: true }); } catch { /* stale record only skips the same release */ }
|
|
353
|
+
const cleanupWarnings = [];
|
|
354
|
+
try { fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); } catch (error) { cleanupWarnings.push(`transaction marker cleanup failed: ${error.message}`); }
|
|
355
|
+
try { fs.rmSync(txDir, { recursive: true, force: true }); } catch (error) { cleanupWarnings.push(`backup cleanup failed: ${error.message}`); }
|
|
356
|
+
try { pruneVersions(home, r.version, oldVersion); } catch (error) { cleanupWarnings.push(`version pruning failed: ${error.message}`); }
|
|
357
|
+
if (cleanupWarnings.length) result.cleanup_warning = cleanupWarnings.join('; ');
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (error.preserveCandidate) {
|
|
360
|
+
const uncertain = new Error(`update commit state is uncertain; candidate and recovery data were preserved: ${error.message}`);
|
|
361
|
+
uncertain.updateOutcome = 'rollback_failed';
|
|
362
|
+
throw uncertain;
|
|
363
|
+
}
|
|
364
|
+
let rollbackError;
|
|
365
|
+
try {
|
|
366
|
+
if (tx.phase === 'switched') validateSnapshot(tx);
|
|
367
|
+
await control(receipt, 'stop'); select(home, oldRepo); if (unitFile && tx.oldUnit != null) atomic(unitFile, tx.oldUnit);
|
|
368
|
+
if (tx.phase === 'switched') for (const item of ['.config', '.local']) replaceTree(path.join(txDir, 'snapshot', item), path.join(home, item));
|
|
369
|
+
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
370
|
+
const restored = await probeReady(probe, home, { ...receipt, repo: oldRepo }, healthTimeoutMs);
|
|
371
|
+
if (restored.version !== oldVersion || !legacy && !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
|
|
372
|
+
fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); fs.rmSync(txDir, { recursive: true, force: true });
|
|
373
|
+
} catch (e) { rollbackError = e; }
|
|
374
|
+
if (rollbackError) { const e = new Error(`update failed: ${error.message}; rollback failed: ${rollbackError.message}`); e.updateOutcome = 'rollback_failed'; throw e; }
|
|
375
|
+
error.updateOutcome = 'rolled_back';
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
} catch (error) {
|
|
380
|
+
result = { outcome: error.updateOutcome ?? 'failed', error: error.message };
|
|
381
|
+
if (attempted && (result.outcome === 'rolled_back' || result.outcome === 'rollback_failed')) {
|
|
382
|
+
try { atomic(failedFile(home), JSON.stringify({ version: attempted.version, integrity: attempted.dist.integrity, outcome: result.outcome, timestamp: new Date().toISOString() })); } catch { /* best effort */ }
|
|
383
|
+
}
|
|
384
|
+
throw error;
|
|
385
|
+
} finally {
|
|
386
|
+
try { if (result) atomic(resultFile, JSON.stringify({ ...result, timestamp: new Date().toISOString() })); }
|
|
387
|
+
finally { releaseLock(); }
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function serviceStatus({ home }) {
|
|
392
|
+
home = path.resolve(home ?? fail('home is required'));
|
|
393
|
+
const { value: receipt } = readReceipt(home), current = path.join(home, 'current');
|
|
394
|
+
let version = receipt.version;
|
|
395
|
+
if (fs.existsSync(current)) version = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(current), 'package.json'), 'utf8')).version;
|
|
396
|
+
let last_result = null;
|
|
397
|
+
try { last_result = JSON.parse(fs.readFileSync(path.join(home, 'update-result.json'), 'utf8')); } catch { /* no update attempt */ }
|
|
398
|
+
return { version, auto_update: receipt.auto_update ?? false, last_result, failed_release: readFailed(home)?.version ?? null };
|
|
399
|
+
}
|