@agentage/extension 0.12.3 → 0.14.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/dist/api/openapi-doc.js +2 -1
- package/dist/api/routes.js +1 -1
- package/dist/context/context.d.ts +1 -0
- package/dist/context/context.js +3 -3
- package/dist/context/secrets.d.ts +1 -0
- package/dist/context/secrets.js +7 -5
- package/dist/context/settings.d.ts +4 -0
- package/dist/context/settings.js +6 -5
- package/dist/discovery/discovery.d.ts +1 -0
- package/dist/discovery/discovery.schema.d.ts +2 -0
- package/dist/discovery/discovery.schema.js +30 -12
- package/dist/discovery/openapi.d.ts +2 -1
- package/dist/discovery/openapi.js +3 -1
- package/dist/host/daemon/add.d.ts +9 -0
- package/dist/host/daemon/add.js +63 -0
- package/dist/host/daemon/child.d.ts +23 -0
- package/dist/host/daemon/child.js +100 -0
- package/dist/host/daemon/daemon-files.d.ts +17 -0
- package/dist/host/daemon/daemon-files.js +27 -0
- package/dist/host/daemon/daemon-owner.d.ts +1 -0
- package/dist/host/daemon/daemon-owner.js +32 -0
- package/dist/host/daemon/daemon.d.ts +17 -0
- package/dist/host/daemon/daemon.js +106 -0
- package/dist/host/daemon/entries.d.ts +21 -0
- package/dist/host/daemon/entries.js +24 -0
- package/dist/host/daemon/guard.d.ts +2 -0
- package/dist/host/daemon/guard.js +16 -0
- package/dist/host/daemon/installation.d.ts +36 -0
- package/dist/host/daemon/installation.js +92 -0
- package/dist/host/daemon/installer-call.d.ts +21 -0
- package/dist/host/daemon/installer-call.js +48 -0
- package/dist/host/daemon/json-file.d.ts +4 -0
- package/dist/host/daemon/json-file.js +62 -0
- package/dist/host/daemon/lane.d.ts +9 -0
- package/dist/host/daemon/lane.js +24 -0
- package/dist/host/daemon/limits.d.ts +11 -0
- package/dist/host/daemon/limits.js +22 -0
- package/dist/host/daemon/ops.d.ts +12 -0
- package/dist/host/daemon/ops.js +89 -0
- package/dist/host/daemon/patch-values.d.ts +6 -0
- package/dist/host/daemon/patch-values.js +39 -0
- package/dist/host/daemon/pending.d.ts +15 -0
- package/dist/host/daemon/pending.js +18 -0
- package/dist/host/daemon/proxy.d.ts +6 -0
- package/dist/host/daemon/proxy.js +89 -0
- package/dist/host/daemon/queue.d.ts +3 -0
- package/dist/host/daemon/queue.js +27 -0
- package/dist/host/daemon/routes.d.ts +13 -0
- package/dist/host/daemon/routes.js +98 -0
- package/dist/host/daemon/stopping.d.ts +10 -0
- package/dist/host/daemon/stopping.js +28 -0
- package/dist/host/daemon/supervisor.d.ts +54 -0
- package/dist/host/daemon/supervisor.js +115 -0
- package/dist/host/daemon/write-all.d.ts +8 -0
- package/dist/host/daemon/write-all.js +45 -0
- package/dist/host/data-lock.d.ts +3 -0
- package/dist/host/data-lock.js +121 -0
- package/dist/host/host-env.d.ts +18 -0
- package/dist/host/host-env.js +42 -0
- package/dist/host/host-extension.d.ts +29 -0
- package/dist/host/host-extension.js +91 -0
- package/dist/host/host-store.d.ts +11 -0
- package/dist/host/host-store.js +49 -0
- package/dist/host/index.d.ts +7 -0
- package/dist/host/index.js +7 -0
- package/dist/host/main.d.ts +2 -0
- package/dist/host/main.js +10 -0
- package/dist/host/serve-host.d.ts +17 -0
- package/dist/host/serve-host.js +64 -0
- package/dist/runtime/part-runners.d.ts +1 -0
- package/dist/runtime/part-runners.js +10 -1
- package/dist/runtime/run-part.js +2 -0
- package/dist/server/app.d.ts +6 -1
- package/dist/server/app.js +29 -19
- package/dist/server/request-line.d.ts +1 -1
- package/dist/server/request-line.js +4 -4
- package/dist/server/serve.d.ts +3 -0
- package/dist/server/serve.js +17 -4
- package/dist/store/pglite-store.d.ts +25 -0
- package/dist/store/pglite-store.js +59 -0
- package/dist/store/test-store.d.ts +2 -3
- package/dist/store/test-store.js +3 -38
- package/dist/testing/test-server.d.ts +2 -0
- package/dist/testing/test-server.js +1 -1
- package/dist/tool/build.d.ts +3 -0
- package/dist/tool/build.js +42 -27
- package/dist/tool/capabilities.d.ts +1 -0
- package/dist/tool/capabilities.js +8 -0
- package/dist/tool/container-parts.d.ts +7 -0
- package/dist/tool/container-parts.js +10 -0
- package/dist/tool/container-recipe.d.ts +4 -0
- package/dist/tool/container-recipe.js +55 -0
- package/dist/tool/container-stage.d.ts +3 -0
- package/dist/tool/container-stage.js +51 -0
- package/dist/tool/container.d.ts +73 -0
- package/dist/tool/container.js +28 -0
- package/dist/tool/docker.d.ts +5 -0
- package/dist/tool/docker.js +15 -0
- package/dist/tool/format.js +12 -5
- package/dist/tool/index.d.ts +2 -0
- package/dist/tool/index.js +2 -0
- package/dist/tool/kit-version.d.ts +1 -0
- package/dist/tool/kit-version.js +16 -2
- package/dist/tool/labels.d.ts +1 -1
- package/dist/tool/labels.js +4 -2
- package/dist/tool/main.js +10 -1
- package/dist/tool/record-extras.js +2 -2
- package/dist/tool/rules/surface.js +6 -6
- package/dist/tool/stage.d.ts +1 -0
- package/dist/tool/stage.js +1 -1
- package/dist/tool/up/gateway.d.ts +6 -2
- package/dist/tool/up/gateway.js +10 -7
- package/dist/tool/up/local-record.d.ts +1 -0
- package/dist/tool/up/token.js +1 -1
- package/dist/tool/up/up.js +2 -2
- package/dist/vendor/logs/events-client.js +1 -1
- package/package.json +5 -1
- package/schemas/extension-discovery.schema.json +8 -1
- package/schemas/extension-record.schema.json +8 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { fits } from '../../context/settings.js';
|
|
2
|
+
import { fail } from '../../envelope/envelope.js';
|
|
3
|
+
import {} from '../../manifest/manifest.schema.js';
|
|
4
|
+
import { readManifest } from '../../manifest/read-manifest.js';
|
|
5
|
+
const PARSE = {
|
|
6
|
+
number: (t) => (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t) ? Number(t) : t),
|
|
7
|
+
integer: (t) => (/^-?\d+$/.test(t) ? Number(t) : t),
|
|
8
|
+
boolean: (t) => (t === 'true' ? true : t === 'false' ? false : t),
|
|
9
|
+
};
|
|
10
|
+
const refused = (key, message) => fail('VALIDATION_ERROR', `setting ${key}: ${message}`, { code: 'INVALID_SETTING' });
|
|
11
|
+
const valueOf = (key, setting, given) => {
|
|
12
|
+
if (!setting)
|
|
13
|
+
throw refused(key, 'not declared in the manifest');
|
|
14
|
+
const value = typeof given === 'string' ? (PARSE[setting.type]?.(given) ?? given) : given;
|
|
15
|
+
if (!fits(setting, value))
|
|
16
|
+
throw refused(key, `${JSON.stringify(given)} is not a valid ${setting.type}`);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
// Only a secret the package declares: the name becomes a file name in the child's folder.
|
|
20
|
+
const checkSecrets = (pkg, names, id) => {
|
|
21
|
+
const known = (pkg.agentage.secrets ?? []).map((s) => (typeof s === 'string' ? s : s.name));
|
|
22
|
+
const unknown = names.filter((name) => !known.includes(name));
|
|
23
|
+
if (unknown.length)
|
|
24
|
+
throw fail('VALIDATION_ERROR', `${id} declares no secret ${unknown.join(', ')}`);
|
|
25
|
+
};
|
|
26
|
+
// The secret names checked, and each setting a client sent as text (`limit=5`) in its declared type.
|
|
27
|
+
export const checkedSettings = async (dir, given, id) => {
|
|
28
|
+
const settings = given.settings ?? {};
|
|
29
|
+
const names = Object.keys(given.secrets ?? {});
|
|
30
|
+
if (!names.length && !Object.keys(settings).length)
|
|
31
|
+
return settings;
|
|
32
|
+
if (!dir)
|
|
33
|
+
throw fail('VALIDATION_ERROR', `${id} has no package yet: install it first`);
|
|
34
|
+
const pkg = await readManifest(dir);
|
|
35
|
+
checkSecrets(pkg, names, id);
|
|
36
|
+
const declared = pkg.agentage.settings ?? {};
|
|
37
|
+
const typed = Object.entries(settings).map(([key, v]) => [key, valueOf(key, declared[key], v)]);
|
|
38
|
+
return Object.fromEntries(typed);
|
|
39
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type PendingOp = 'install' | 'update' | 'remove';
|
|
2
|
+
export interface Pending {
|
|
3
|
+
op: PendingOp;
|
|
4
|
+
id?: string;
|
|
5
|
+
source?: string;
|
|
6
|
+
since: string;
|
|
7
|
+
timedOut?: true;
|
|
8
|
+
}
|
|
9
|
+
export declare const pendingChanges: () => {
|
|
10
|
+
track: <T>(change: Omit<Pending, "since">, fn: () => Promise<T>) => Promise<T>;
|
|
11
|
+
linger: (id: string, since: string, work: Promise<unknown>) => void;
|
|
12
|
+
timedOut: (id: string) => Pending | undefined;
|
|
13
|
+
list: () => Pending[];
|
|
14
|
+
};
|
|
15
|
+
export type PendingChanges = ReturnType<typeof pendingChanges>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The changes taken and not yet answered, queued ones too: /health shows one the client gave up on.
|
|
2
|
+
export const pendingChanges = () => {
|
|
3
|
+
const open = new Set();
|
|
4
|
+
const until = async (row, work) => {
|
|
5
|
+
open.add(row);
|
|
6
|
+
try {
|
|
7
|
+
return await work;
|
|
8
|
+
}
|
|
9
|
+
finally {
|
|
10
|
+
open.delete(row);
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const track = (change, fn) => until({ ...change, since: new Date().toISOString() }, Promise.resolve().then(fn));
|
|
14
|
+
// A timed-out installer call stays listed until it settles.
|
|
15
|
+
const linger = (id, since, work) => void until({ op: 'install', id, since, timedOut: true }, work).catch(() => undefined);
|
|
16
|
+
const timedOut = (id) => [...open].find((row) => row.timedOut && row.id === id);
|
|
17
|
+
return { track, linger, timedOut, list: () => [...open] };
|
|
18
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type IncomingHttpHeaders } from 'node:http';
|
|
2
|
+
import { type RequestHandler } from 'express';
|
|
3
|
+
import { type Entries } from './entries.js';
|
|
4
|
+
import { type Limits } from './limits.js';
|
|
5
|
+
export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
|
|
6
|
+
export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">) => RequestHandler;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { request, } from 'node:http';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import {} from 'express';
|
|
4
|
+
import { fail } from '../../envelope/envelope.js';
|
|
5
|
+
import { enter } from './lane.js';
|
|
6
|
+
import {} from './entries.js';
|
|
7
|
+
import {} from './limits.js';
|
|
8
|
+
// 404 not installed or disabled (chosen, not to retry); 503 starting, failed, or held past gateMs.
|
|
9
|
+
const laneFor = async (entries, id, gateMs) => {
|
|
10
|
+
const entry = entries.get(id);
|
|
11
|
+
if (!entry)
|
|
12
|
+
throw fail('NOT_FOUND', `${id} is not installed`);
|
|
13
|
+
if (entry.state === 'disabled')
|
|
14
|
+
throw fail('NOT_FOUND', `${id} is disabled`);
|
|
15
|
+
if (entry.gate)
|
|
16
|
+
await Promise.race([entry.gate, sleep(gateMs, undefined, { ref: false })]);
|
|
17
|
+
const lane = entry.lane;
|
|
18
|
+
if (!lane)
|
|
19
|
+
throw fail('UNAVAILABLE', `${id} is ${entry.state}`, { retryAfter: 5 });
|
|
20
|
+
// Counted in the same tick it is read: a swap cannot stop this child before the request is open.
|
|
21
|
+
return { lane, leave: enter(lane) };
|
|
22
|
+
};
|
|
23
|
+
const HOP = [
|
|
24
|
+
'connection',
|
|
25
|
+
'keep-alive',
|
|
26
|
+
'proxy-authenticate',
|
|
27
|
+
'proxy-authorization',
|
|
28
|
+
'te',
|
|
29
|
+
'trailer',
|
|
30
|
+
'transfer-encoding',
|
|
31
|
+
'upgrade',
|
|
32
|
+
];
|
|
33
|
+
// RFC 9110 7.6.1: hop-by-hop headers, and those the Connection header names, stay on their hop.
|
|
34
|
+
export const endToEnd = (headers) => {
|
|
35
|
+
const named = String(headers['connection'] ?? '')
|
|
36
|
+
.toLowerCase()
|
|
37
|
+
.split(',');
|
|
38
|
+
const drop = new Set([...HOP, ...named.map((h) => h.trim())]);
|
|
39
|
+
return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.has(key)));
|
|
40
|
+
};
|
|
41
|
+
// No answer headers in answerMs: 504 TIMEOUT; the child may still apply the call.
|
|
42
|
+
const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did not answer in ${ms} ms`), {
|
|
43
|
+
code: 'TIMEOUT',
|
|
44
|
+
status: 504,
|
|
45
|
+
retryAfter: undefined,
|
|
46
|
+
});
|
|
47
|
+
const requestTo = (req, lane) => {
|
|
48
|
+
const { method, originalUrl: path } = req;
|
|
49
|
+
const headers = endToEnd(req.headers);
|
|
50
|
+
const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
|
|
51
|
+
return request(options);
|
|
52
|
+
};
|
|
53
|
+
// The child's answer as it streams; an error before its headers is the envelope (504 when late).
|
|
54
|
+
const relay = (upstream, res, next, ms) => {
|
|
55
|
+
let late = false;
|
|
56
|
+
const timer = setTimeout(() => ((late = true), upstream.destroy()), ms);
|
|
57
|
+
upstream.on('response', (up) => {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
|
|
60
|
+
// A child gone in the middle of its body: the answer is cut, not left open.
|
|
61
|
+
up.once('close', () => void (up.complete || res.destroy()));
|
|
62
|
+
up.pipe(res);
|
|
63
|
+
});
|
|
64
|
+
upstream.on('error', () => {
|
|
65
|
+
if (res.headersSent)
|
|
66
|
+
return void res.destroy();
|
|
67
|
+
next(late ? noAnswer(ms) : fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
|
|
68
|
+
});
|
|
69
|
+
return () => clearTimeout(timer);
|
|
70
|
+
};
|
|
71
|
+
// Streams the request to the child as it came (path and query kept), no pooled connection.
|
|
72
|
+
const forward = (req, res, next, to, ms) => {
|
|
73
|
+
const { lane, leave } = to;
|
|
74
|
+
const upstream = requestTo(req, lane);
|
|
75
|
+
const stop = relay(upstream, res, next, ms);
|
|
76
|
+
upstream.on('error', leave);
|
|
77
|
+
// A client that went away aborts the request to the child too.
|
|
78
|
+
res.on('close', () => {
|
|
79
|
+
stop();
|
|
80
|
+
if (!res.writableFinished)
|
|
81
|
+
upstream.destroy();
|
|
82
|
+
leave();
|
|
83
|
+
});
|
|
84
|
+
req.pipe(upstream);
|
|
85
|
+
};
|
|
86
|
+
export const proxyTo = (entries, limits) => async (req, res, next) => {
|
|
87
|
+
const taken = await laneFor(entries, String(req.params['id']), limits.gateMs);
|
|
88
|
+
forward(req, res, next, taken, limits.answerMs);
|
|
89
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
export const serialQueue = () => {
|
|
3
|
+
let chain = Promise.resolve();
|
|
4
|
+
return (fn) => {
|
|
5
|
+
const run = chain.then(fn, fn);
|
|
6
|
+
chain = run.catch(() => undefined);
|
|
7
|
+
return run;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
// A change that waited ms for the ones before it (the boot too) is 503 and never runs.
|
|
11
|
+
export const waitAtMost = (queue, ms, fn) => {
|
|
12
|
+
let gaveUp = false;
|
|
13
|
+
let timer;
|
|
14
|
+
const late = new Promise((_resolve, reject) => {
|
|
15
|
+
timer = setTimeout(() => {
|
|
16
|
+
gaveUp = true;
|
|
17
|
+
reject(fail('UNAVAILABLE', `other changes ran for ${ms} ms: try again`, { retryAfter: 5 }));
|
|
18
|
+
}, ms);
|
|
19
|
+
});
|
|
20
|
+
const run = queue(async () => {
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
if (gaveUp)
|
|
23
|
+
return undefined;
|
|
24
|
+
return fn();
|
|
25
|
+
});
|
|
26
|
+
return Promise.race([run, late]);
|
|
27
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
import { type Entries } from './entries.js';
|
|
3
|
+
import { type SupervisorDeps } from './supervisor.js';
|
|
4
|
+
interface DaemonInfo {
|
|
5
|
+
version: string;
|
|
6
|
+
pid: number;
|
|
7
|
+
protocol: number;
|
|
8
|
+
invalid: boolean;
|
|
9
|
+
unreadable?: string;
|
|
10
|
+
notJson?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo) => Express;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import express, {} from 'express';
|
|
2
|
+
import { agcidMiddleware } from '../../agcid/scope.js';
|
|
3
|
+
import { ok } from '../../envelope/envelope.js';
|
|
4
|
+
import { BODY_LIMIT } from '../../server/app.js';
|
|
5
|
+
import { errorHandler, notFound } from '../../server/errors.js';
|
|
6
|
+
import { localOnly } from './guard.js';
|
|
7
|
+
import { addExtension } from './add.js';
|
|
8
|
+
import { listed, summary } from './entries.js';
|
|
9
|
+
import { assertReadable } from './installation.js';
|
|
10
|
+
import { changeExtension, removeExtension } from './ops.js';
|
|
11
|
+
import {} from './pending.js';
|
|
12
|
+
import { waitAtMost } from './queue.js';
|
|
13
|
+
import { proxyTo } from './proxy.js';
|
|
14
|
+
import { stopsNow } from './stopping.js';
|
|
15
|
+
import {} from './supervisor.js';
|
|
16
|
+
// What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
|
|
17
|
+
const DAEMON_SERVICE = 'agentage-daemon';
|
|
18
|
+
const installationOf = ({ invalid, unreadable, notJson }) => {
|
|
19
|
+
if (unreadable)
|
|
20
|
+
return { installation: 'unreadable', installationError: unreadable };
|
|
21
|
+
return invalid || notJson ? { installation: 'invalid' } : {};
|
|
22
|
+
};
|
|
23
|
+
const reasonOf = (err) => err.details?.reason;
|
|
24
|
+
// A refusal for a file that turned not JSON shows in /health until a change reads the file again.
|
|
25
|
+
const checkReadable = (deps, info) => assertReadable(deps.configDir, info.unreadable).then(() => void (info.notJson = false), (err) => {
|
|
26
|
+
info.notJson = reasonOf(err) === 'not JSON';
|
|
27
|
+
throw err;
|
|
28
|
+
});
|
|
29
|
+
const healthOf = (deps, entries, info) => {
|
|
30
|
+
const all = [...entries.values()];
|
|
31
|
+
const settled = all.every((e) => e.state === 'running' || e.state === 'disabled');
|
|
32
|
+
const synced = !deps.unsynced.size;
|
|
33
|
+
const clean = !info.invalid && !info.unreadable && !info.notJson;
|
|
34
|
+
const status = settled && synced && clean ? 'ok' : 'degraded';
|
|
35
|
+
const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
|
|
36
|
+
const extensions = all.map(summary);
|
|
37
|
+
const changing = deps.pending.list();
|
|
38
|
+
const busy = changing.length ? { pending: changing } : {};
|
|
39
|
+
const marks = {
|
|
40
|
+
...busy,
|
|
41
|
+
...(!synced && { unsynced: [...deps.unsynced] }),
|
|
42
|
+
...installationOf(info),
|
|
43
|
+
};
|
|
44
|
+
return { status, version: info.version, ...self, extensions, ...marks };
|
|
45
|
+
};
|
|
46
|
+
// What a POST body names, for /health: the id, or the folder.
|
|
47
|
+
const named = (body) => {
|
|
48
|
+
const { id, source } = (body ?? {});
|
|
49
|
+
if (typeof id === 'string')
|
|
50
|
+
return { id };
|
|
51
|
+
return typeof source === 'string' ? { source } : {};
|
|
52
|
+
};
|
|
53
|
+
// Every change in the queue, and none while installation.json cannot be read.
|
|
54
|
+
const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(deps.queue, deps.installMs, async () => {
|
|
55
|
+
if (deps.stopping.signal.aborted)
|
|
56
|
+
throw stopsNow();
|
|
57
|
+
await checkReadable(deps, info);
|
|
58
|
+
return fn();
|
|
59
|
+
}));
|
|
60
|
+
const changes = (deps, entries, info, p) => {
|
|
61
|
+
const run = runner(deps, info, p);
|
|
62
|
+
const id = (params) => String(params['id']);
|
|
63
|
+
const add = async (req, res) => {
|
|
64
|
+
const what = { op: 'install', ...named(req.body) };
|
|
65
|
+
res.status(201).json(ok(await run(what, () => addExtension(deps, entries, req.body))));
|
|
66
|
+
};
|
|
67
|
+
const change = async ({ params, body }, res) => {
|
|
68
|
+
const what = { op: 'update', id: id(params) };
|
|
69
|
+
res.json(ok(await run(what, () => changeExtension(deps, entries, id(params), body))));
|
|
70
|
+
};
|
|
71
|
+
const purge = (q) => q['purge'] === 'true';
|
|
72
|
+
const remove = async ({ params, query }, res) => {
|
|
73
|
+
const what = { op: 'remove', id: id(params) };
|
|
74
|
+
res.json(ok(await run(what, () => removeExtension(deps, entries, what.id, purge(query)))));
|
|
75
|
+
};
|
|
76
|
+
return { add, change, remove };
|
|
77
|
+
};
|
|
78
|
+
const hostRoutes = (app, deps, entries, info, p) => {
|
|
79
|
+
app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
|
|
80
|
+
const json = express.json({ limit: BODY_LIMIT });
|
|
81
|
+
const { add, change, remove } = changes(deps, entries, info, p);
|
|
82
|
+
app.post('/host/extensions', json, add);
|
|
83
|
+
app.patch('/host/extensions/:id', json, change);
|
|
84
|
+
app.delete('/host/extensions/:id', remove);
|
|
85
|
+
};
|
|
86
|
+
// C5: /health, /host/extensions, and /api/{id}/* to the child of that id; Host and Origin first.
|
|
87
|
+
export const daemonApp = (deps, entries, port, info) => {
|
|
88
|
+
const app = express();
|
|
89
|
+
const pending = deps.pending;
|
|
90
|
+
app.disable('x-powered-by');
|
|
91
|
+
app.use(agcidMiddleware, localOnly(port));
|
|
92
|
+
app.use('/api/:id', proxyTo(entries, deps));
|
|
93
|
+
app.get('/health', (_req, res) => void res.set('Cache-Control', 'no-store').json(healthOf(deps, entries, info)));
|
|
94
|
+
hostRoutes(app, deps, entries, info, pending);
|
|
95
|
+
app.use(notFound);
|
|
96
|
+
app.use(errorHandler(deps.log));
|
|
97
|
+
return app;
|
|
98
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Child, type Launch } from './child.js';
|
|
2
|
+
export interface Stopping {
|
|
3
|
+
signal: AbortSignal;
|
|
4
|
+
launching: Set<Promise<unknown>>;
|
|
5
|
+
children: Set<Child>;
|
|
6
|
+
}
|
|
7
|
+
export declare const stoppingOf: (signal: AbortSignal) => Stopping;
|
|
8
|
+
export declare const stopsNow: () => import("../../envelope/envelope.js").Failure;
|
|
9
|
+
export declare const launchUnlessStopping: (stopping: Stopping, launch: Launch) => Launch;
|
|
10
|
+
export declare const stopAll: (stopping: Stopping) => Promise<void>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
import {} from './child.js';
|
|
3
|
+
export const stoppingOf = (signal) => ({
|
|
4
|
+
signal,
|
|
5
|
+
launching: new Set(),
|
|
6
|
+
children: new Set(),
|
|
7
|
+
});
|
|
8
|
+
export const stopsNow = () => fail('UNAVAILABLE', 'the daemon stops', { retryAfter: 5 });
|
|
9
|
+
const started = async (stopping, launch) => {
|
|
10
|
+
if (stopping.signal.aborted)
|
|
11
|
+
throw stopsNow();
|
|
12
|
+
const child = await launch();
|
|
13
|
+
stopping.children.add(child);
|
|
14
|
+
void child.exited.then(() => stopping.children.delete(child));
|
|
15
|
+
return child;
|
|
16
|
+
};
|
|
17
|
+
// No child outlives stop(): none starts once it began; stopAll waits for the ones in flight.
|
|
18
|
+
export const launchUnlessStopping = (stopping, launch) => (spec) => {
|
|
19
|
+
const run = started(stopping, () => launch(spec));
|
|
20
|
+
stopping.launching.add(run);
|
|
21
|
+
void run.catch(() => undefined).finally(() => stopping.launching.delete(run));
|
|
22
|
+
return run;
|
|
23
|
+
};
|
|
24
|
+
// After the drain of each route: a child still starting or swapping is stopped too.
|
|
25
|
+
export const stopAll = async (stopping) => {
|
|
26
|
+
await Promise.allSettled([...stopping.launching]);
|
|
27
|
+
await Promise.all([...stopping.children].map((child) => child.stop()));
|
|
28
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type Log } from '../../log/log.js';
|
|
2
|
+
import { type Launch } from './child.js';
|
|
3
|
+
import { type InstallEntry } from './installation.js';
|
|
4
|
+
import { type Lane } from './lane.js';
|
|
5
|
+
import { type Limits } from './limits.js';
|
|
6
|
+
import { type PendingChanges } from './pending.js';
|
|
7
|
+
import { type Queue } from './queue.js';
|
|
8
|
+
import { type Stopping } from './stopping.js';
|
|
9
|
+
export interface InstallSpec {
|
|
10
|
+
id: string;
|
|
11
|
+
version?: string;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
export type Installer = (spec: InstallSpec) => Promise<{
|
|
15
|
+
id: string;
|
|
16
|
+
version: string;
|
|
17
|
+
dir: string;
|
|
18
|
+
}>;
|
|
19
|
+
export type State = 'starting' | 'running' | 'failed' | 'disabled';
|
|
20
|
+
export interface Entry {
|
|
21
|
+
id: string;
|
|
22
|
+
install: InstallEntry;
|
|
23
|
+
state: State;
|
|
24
|
+
version: string;
|
|
25
|
+
dir?: string;
|
|
26
|
+
error?: string;
|
|
27
|
+
lane?: Lane;
|
|
28
|
+
gate?: Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export interface Values {
|
|
31
|
+
settings: Record<string, unknown>;
|
|
32
|
+
secrets: Record<string, string>;
|
|
33
|
+
}
|
|
34
|
+
export interface Next {
|
|
35
|
+
install: InstallEntry;
|
|
36
|
+
values: Values;
|
|
37
|
+
dir?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface SupervisorDeps extends Limits {
|
|
40
|
+
configDir: string;
|
|
41
|
+
launch: Launch;
|
|
42
|
+
origin: () => string;
|
|
43
|
+
install?: Installer;
|
|
44
|
+
log: Log;
|
|
45
|
+
queue: Queue;
|
|
46
|
+
pending: PendingChanges;
|
|
47
|
+
stopping: Stopping;
|
|
48
|
+
unsynced: Set<string>;
|
|
49
|
+
}
|
|
50
|
+
export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
|
|
51
|
+
export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
|
|
52
|
+
export declare const hold: (entry: Entry) => (() => void);
|
|
53
|
+
export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next, undo?: () => Promise<unknown>) => Promise<void>;
|
|
54
|
+
export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
import {} from '../../log/log.js';
|
|
3
|
+
import { readManifest } from '../../manifest/read-manifest.js';
|
|
4
|
+
import {} from './child.js';
|
|
5
|
+
import { dataDirOf, readValues } from './daemon-files.js';
|
|
6
|
+
import {} from './installation.js';
|
|
7
|
+
import { laneOf, retire } from './lane.js';
|
|
8
|
+
import {} from './limits.js';
|
|
9
|
+
import { runInstaller } from './installer-call.js';
|
|
10
|
+
import {} from './pending.js';
|
|
11
|
+
import {} from './queue.js';
|
|
12
|
+
import {} from './stopping.js';
|
|
13
|
+
export const valuesOf = async (configDir, id) => ({
|
|
14
|
+
settings: await readValues(configDir, 'settings', id),
|
|
15
|
+
secrets: (await readValues(configDir, 'secrets', id)),
|
|
16
|
+
});
|
|
17
|
+
// The package folder: the source itself, the folder an install gave, or the installer again.
|
|
18
|
+
const dirOf = async (deps, entry, install, given) => {
|
|
19
|
+
if (given)
|
|
20
|
+
return given;
|
|
21
|
+
if (install.source)
|
|
22
|
+
return install.source;
|
|
23
|
+
if (entry.dir && install.version === entry.install.version)
|
|
24
|
+
return entry.dir;
|
|
25
|
+
return (await runInstaller(deps, { id: entry.id, version: install.version })).dir;
|
|
26
|
+
};
|
|
27
|
+
// Healthy before it gets the route: the child's own /health answers 200.
|
|
28
|
+
const healthy = async (port, ms) => {
|
|
29
|
+
const signal = AbortSignal.timeout(ms);
|
|
30
|
+
const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
|
|
31
|
+
if (err.name === 'TimeoutError')
|
|
32
|
+
throw new Error(`health did not answer in ${ms} ms`);
|
|
33
|
+
const cause = err.cause?.code ?? err.message;
|
|
34
|
+
throw new Error(`health could not be reached (${cause})`);
|
|
35
|
+
});
|
|
36
|
+
if (res.status !== 200)
|
|
37
|
+
throw new Error(`health answered ${res.status}`);
|
|
38
|
+
};
|
|
39
|
+
// A new child for install with values, healthy; the entry learns the version the package has.
|
|
40
|
+
const launchFor = async (deps, entry, install, values, given) => {
|
|
41
|
+
const dir = await dirOf(deps, entry, install, given);
|
|
42
|
+
const pkg = await readManifest(dir);
|
|
43
|
+
const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...values };
|
|
44
|
+
const child = await deps.launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs });
|
|
45
|
+
await healthy(child.port, deps.healthMs).catch(async (err) => {
|
|
46
|
+
await child.stop();
|
|
47
|
+
throw err;
|
|
48
|
+
});
|
|
49
|
+
Object.assign(entry, { dir, version: pkg.version });
|
|
50
|
+
const lane = laneOf(child);
|
|
51
|
+
void child.exited.then((how) => exitedEarly(deps, entry, lane, how));
|
|
52
|
+
return lane;
|
|
53
|
+
};
|
|
54
|
+
// A child that exits while it is the route is failed; a retired one was detached first.
|
|
55
|
+
const exitedEarly = (deps, entry, lane, how) => {
|
|
56
|
+
if (entry.lane !== lane)
|
|
57
|
+
return;
|
|
58
|
+
const why = how.signal ? `signal ${how.signal}` : `code ${how.code}`;
|
|
59
|
+
Object.assign(entry, { lane: undefined, state: 'failed', error: `the process exited (${why})` });
|
|
60
|
+
deps.log.warn('extension process exited', { id: entry.id });
|
|
61
|
+
};
|
|
62
|
+
const failed = (deps, entry, err) => {
|
|
63
|
+
Object.assign(entry, { state: 'failed', error: err.message });
|
|
64
|
+
deps.log.warn('extension failed to start', { id: entry.id, reason: entry.error });
|
|
65
|
+
};
|
|
66
|
+
// The install and values of installation.json, as they are on disk.
|
|
67
|
+
export const startEntry = async (deps, entry) => {
|
|
68
|
+
entry.state = 'starting';
|
|
69
|
+
try {
|
|
70
|
+
const values = await valuesOf(deps.configDir, entry.id);
|
|
71
|
+
entry.lane = await launchFor(deps, entry, entry.install, values);
|
|
72
|
+
Object.assign(entry, { state: 'running', error: undefined });
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
failed(deps, entry, err);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
// New requests of the extension wait here (the proxy gives up after gateMs) until release.
|
|
79
|
+
export const hold = (entry) => {
|
|
80
|
+
let release = () => undefined;
|
|
81
|
+
entry.gate = new Promise((resolve) => (release = resolve));
|
|
82
|
+
return () => {
|
|
83
|
+
entry.gate = undefined;
|
|
84
|
+
release();
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
// The old install again after a refused change; a disabled one stays stopped.
|
|
88
|
+
const restore = async (deps, entry) => {
|
|
89
|
+
if (entry.install.enabled === false)
|
|
90
|
+
entry.state = 'disabled';
|
|
91
|
+
else
|
|
92
|
+
await startEntry(deps, entry);
|
|
93
|
+
};
|
|
94
|
+
const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
|
|
95
|
+
code: 'START_FAILED',
|
|
96
|
+
});
|
|
97
|
+
// One writer per data folder (the caller holds the gate): stop the old child, start the new one.
|
|
98
|
+
export const swap = async (deps, entry, to, undo = async () => undefined) => {
|
|
99
|
+
try {
|
|
100
|
+
await halt(entry, deps.drainMs);
|
|
101
|
+
entry.lane = await launchFor(deps, entry, to.install, to.values, to.dir);
|
|
102
|
+
Object.assign(entry, { state: 'running', error: undefined });
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
await undo();
|
|
106
|
+
await restore(deps, entry);
|
|
107
|
+
throw startFailed(entry, err);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
// Detached first, so its exit is not a failure; then drained and stopped.
|
|
111
|
+
export const halt = async (entry, drainMs) => {
|
|
112
|
+
const lane = entry.lane;
|
|
113
|
+
entry.lane = undefined;
|
|
114
|
+
await retire(lane, drainMs);
|
|
115
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type InstallEntry } from './installation.js';
|
|
2
|
+
import { type SupervisorDeps, type Values } from './supervisor.js';
|
|
3
|
+
export interface Written {
|
|
4
|
+
install?: InstallEntry;
|
|
5
|
+
values?: Values;
|
|
6
|
+
}
|
|
7
|
+
export declare const unsynced: (deps: SupervisorDeps, id: string) => void;
|
|
8
|
+
export declare const writeAll: (deps: SupervisorDeps, id: string, to: Written, was?: Written) => Promise<void>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { writeValues } from './daemon-files.js';
|
|
2
|
+
import { persist } from './entries.js';
|
|
3
|
+
import {} from './installation.js';
|
|
4
|
+
import {} from './supervisor.js';
|
|
5
|
+
const stepsOf = (deps, id, to, was) => {
|
|
6
|
+
// An empty object is no row: what valuesOf reads for an id the file does not name.
|
|
7
|
+
const values = (kind, v) => () => {
|
|
8
|
+
const rows = v?.[kind];
|
|
9
|
+
return writeValues(deps.configDir, kind, id, rows && Object.keys(rows).length ? rows : undefined, deps.lockMs);
|
|
10
|
+
};
|
|
11
|
+
const steps = [
|
|
12
|
+
[() => persist(deps, id, to.install), () => persist(deps, id, was.install)],
|
|
13
|
+
[values('settings', to.values), values('settings', was.values)],
|
|
14
|
+
// Last: a failed write before it leaves secrets.json as it was.
|
|
15
|
+
[values('secrets', to.values), values('secrets', was.values)],
|
|
16
|
+
];
|
|
17
|
+
// A remove deletes the secrets first: a crash half way leaves none for a later install of id.
|
|
18
|
+
return to.install ? steps : steps.reverse();
|
|
19
|
+
};
|
|
20
|
+
// An undo that failed leaves the files of id unlike the list: one warn line, and /health names it.
|
|
21
|
+
export const unsynced = (deps, id) => {
|
|
22
|
+
deps.unsynced.add(id);
|
|
23
|
+
deps.log.warn('a failed write could not be undone: the daemon files may not match the list', {
|
|
24
|
+
id,
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
// installation.json, settings.json, secrets.json in turn; a failed one undoes those written before it.
|
|
28
|
+
export const writeAll = async (deps, id, to, was = {}) => {
|
|
29
|
+
const done = [];
|
|
30
|
+
try {
|
|
31
|
+
for (const [run, undo] of stepsOf(deps, id, to, was)) {
|
|
32
|
+
await run();
|
|
33
|
+
done.unshift(undo);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
let lost = false;
|
|
38
|
+
for (const undo of done)
|
|
39
|
+
await undo().catch(() => (lost = true));
|
|
40
|
+
if (lost)
|
|
41
|
+
unsynced(deps, id);
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
deps.unsynced.delete(id);
|
|
45
|
+
};
|