@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,106 @@
|
|
|
1
|
+
import { mkdir } from 'node:fs/promises';
|
|
2
|
+
import {} from 'node:http';
|
|
3
|
+
import {} from 'node:net';
|
|
4
|
+
import { createLog } from '../../log/log.js';
|
|
5
|
+
import { closeNow, listen } from '../../server/serve.js';
|
|
6
|
+
import { forkLaunch } from './child.js';
|
|
7
|
+
import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
|
|
8
|
+
import { assertNoOtherDaemon } from './daemon-owner.js';
|
|
9
|
+
import { bootInstallation, updateInstallation } from './installation.js';
|
|
10
|
+
import {} from './entries.js';
|
|
11
|
+
import { limitsOf } from './limits.js';
|
|
12
|
+
import { pendingChanges } from './pending.js';
|
|
13
|
+
import { serialQueue } from './queue.js';
|
|
14
|
+
import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
|
|
15
|
+
import { daemonApp } from './routes.js';
|
|
16
|
+
import { runInstaller } from './installer-call.js';
|
|
17
|
+
import { halt, startEntry } from './supervisor.js';
|
|
18
|
+
export const DAEMON_PORT = 4243;
|
|
19
|
+
const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
|
|
20
|
+
// The valid rows of installation.json; a bad file is kept aside, replaced by them, and in /health.
|
|
21
|
+
const loadEntries = async (deps) => {
|
|
22
|
+
const { doc, invalid, unreadable } = await bootInstallation(deps.configDir);
|
|
23
|
+
if (invalid)
|
|
24
|
+
await updateInstallation(deps.configDir, () => doc, deps.lockMs).catch(warnOf(deps));
|
|
25
|
+
const entries = new Map();
|
|
26
|
+
for (const install of doc.extensions) {
|
|
27
|
+
const state = install.enabled === false ? 'disabled' : 'starting';
|
|
28
|
+
entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
|
|
29
|
+
}
|
|
30
|
+
return { entries, invalid, unreadable };
|
|
31
|
+
};
|
|
32
|
+
// A disabled entry gets its folder (configure and enable work); a failure is kept as its error.
|
|
33
|
+
const resolveDir = async (deps, entry) => {
|
|
34
|
+
const { id, install } = entry;
|
|
35
|
+
if (install.source)
|
|
36
|
+
return void (entry.dir = install.source);
|
|
37
|
+
await runInstaller(deps, { id, version: install.version }).then((got) => void Object.assign(entry, { dir: got.dir, version: got.version, error: undefined }), (err) => void (entry.error = err.message));
|
|
38
|
+
};
|
|
39
|
+
// Enabled folders first (no installer), then enabled versions one at a time, disabled ones last.
|
|
40
|
+
const boot = async (deps, entries) => {
|
|
41
|
+
const all = [...entries.values()];
|
|
42
|
+
const off = all.filter((e) => e.state === 'disabled');
|
|
43
|
+
const on = all.filter((e) => e.state !== 'disabled');
|
|
44
|
+
const ordered = [...on.filter((e) => e.install.source), ...on.filter((e) => !e.install.source)];
|
|
45
|
+
for (const entry of ordered)
|
|
46
|
+
await startEntry(deps, entry);
|
|
47
|
+
for (const entry of off)
|
|
48
|
+
await resolveDir(deps, entry);
|
|
49
|
+
};
|
|
50
|
+
const stopper = (server, entries, deps, life) => {
|
|
51
|
+
let stopped;
|
|
52
|
+
const stop = async () => {
|
|
53
|
+
life.abort();
|
|
54
|
+
await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
|
|
55
|
+
await stopAll(deps.stopping);
|
|
56
|
+
await closeNow(server);
|
|
57
|
+
await removeDaemonFile(deps.configDir);
|
|
58
|
+
};
|
|
59
|
+
return () => (stopped ??= stop());
|
|
60
|
+
};
|
|
61
|
+
// C4: how a client finds this daemon.
|
|
62
|
+
const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(configDir, {
|
|
63
|
+
pid: process.pid,
|
|
64
|
+
port,
|
|
65
|
+
version,
|
|
66
|
+
protocol: DAEMON_PROTOCOL,
|
|
67
|
+
startedBy,
|
|
68
|
+
});
|
|
69
|
+
const depsOf = (opts, launch, origin, stopping) => ({
|
|
70
|
+
configDir: opts.configDir,
|
|
71
|
+
launch: launchUnlessStopping(stopping, launch),
|
|
72
|
+
stopping,
|
|
73
|
+
install: opts.install,
|
|
74
|
+
log: createLog({ extension: 'host', part: 'api', version: opts.version }),
|
|
75
|
+
origin,
|
|
76
|
+
...limitsOf(opts),
|
|
77
|
+
queue: serialQueue(),
|
|
78
|
+
pending: pendingChanges(),
|
|
79
|
+
unsynced: new Set(),
|
|
80
|
+
});
|
|
81
|
+
// No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
|
|
82
|
+
export const startDaemon = async (opts, launch) => {
|
|
83
|
+
await mkdir(opts.configDir, { recursive: true });
|
|
84
|
+
// A live daemon owns the folder: a second one fails before it writes any file there.
|
|
85
|
+
await assertNoOtherDaemon(opts.configDir);
|
|
86
|
+
let port = opts.port ?? DAEMON_PORT;
|
|
87
|
+
const life = new AbortController();
|
|
88
|
+
const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
|
|
89
|
+
const { entries, ...file } = await loadEntries(deps);
|
|
90
|
+
const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, ...file };
|
|
91
|
+
const app = daemonApp(deps, entries, () => port, info);
|
|
92
|
+
const server = await listen(app, port, '127.0.0.1');
|
|
93
|
+
port = server.address().port;
|
|
94
|
+
const stop = stopper(server, entries, deps, life);
|
|
95
|
+
try {
|
|
96
|
+
await announce(opts, port);
|
|
97
|
+
await deps.queue(() => boot(deps, entries));
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
await stop();
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
return { port, stop };
|
|
104
|
+
};
|
|
105
|
+
// One daemon on 127.0.0.1, one child process for each extension (D1).
|
|
106
|
+
export const createDaemon = (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs));
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type InstallEntry } from './installation.js';
|
|
2
|
+
import { type Entry, type SupervisorDeps } from './supervisor.js';
|
|
3
|
+
export type Entries = Map<string, Entry>;
|
|
4
|
+
export declare const summary: ({ id, version, state, error, lane }: Entry) => {
|
|
5
|
+
error?: string | undefined;
|
|
6
|
+
pid?: number | undefined;
|
|
7
|
+
id: string;
|
|
8
|
+
version: string;
|
|
9
|
+
state: import("./supervisor.js").State;
|
|
10
|
+
};
|
|
11
|
+
export declare const listed: (entry: Entry) => {
|
|
12
|
+
source: string;
|
|
13
|
+
enabled: boolean;
|
|
14
|
+
error?: string | undefined;
|
|
15
|
+
pid?: number | undefined;
|
|
16
|
+
id: string;
|
|
17
|
+
version: string;
|
|
18
|
+
state: import("./supervisor.js").State;
|
|
19
|
+
};
|
|
20
|
+
export declare const entryOf: (entries: Entries, id: string) => Entry;
|
|
21
|
+
export declare const persist: (deps: SupervisorDeps, id: string, install?: InstallEntry) => Promise<import("./installation.js").Installation>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
import { persistInstallation, withEntry } from './installation.js';
|
|
3
|
+
import {} from './supervisor.js';
|
|
4
|
+
// pid of a running child: the e2e teardown reads it.
|
|
5
|
+
export const summary = ({ id, version, state, error, lane }) => ({
|
|
6
|
+
id,
|
|
7
|
+
version,
|
|
8
|
+
state,
|
|
9
|
+
...(lane && { pid: lane.child.pid }),
|
|
10
|
+
...(error && { error }),
|
|
11
|
+
});
|
|
12
|
+
export const listed = (entry) => ({
|
|
13
|
+
...summary(entry),
|
|
14
|
+
source: entry.install.source ?? 'market',
|
|
15
|
+
enabled: entry.install.enabled !== false,
|
|
16
|
+
});
|
|
17
|
+
export const entryOf = (entries, id) => {
|
|
18
|
+
const entry = entries.get(id);
|
|
19
|
+
if (!entry)
|
|
20
|
+
throw fail('NOT_FOUND', `${id} is not installed`);
|
|
21
|
+
return entry;
|
|
22
|
+
};
|
|
23
|
+
// The entry of id in installation.json replaced, added, or (no install) removed.
|
|
24
|
+
export const persist = (deps, id, install) => persistInstallation(deps.configDir, (doc) => withEntry(doc, id, install), deps.lockMs);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {} from 'express';
|
|
2
|
+
import { fail } from '../../envelope/envelope.js';
|
|
3
|
+
// What a browser says of a request another site started (an <img>, a link, a form).
|
|
4
|
+
const FOREIGN = ['cross-site', 'same-site'];
|
|
5
|
+
// Only this machine by name (DNS rebinding, a cross-site form): no port given, the socket's own.
|
|
6
|
+
export const localOnly = (port) => (req, _res, next) => {
|
|
7
|
+
const at = port?.() ?? req.socket.localPort;
|
|
8
|
+
const hosts = [`127.0.0.1:${at}`, `localhost:${at}`];
|
|
9
|
+
const origin = req.get('origin');
|
|
10
|
+
const hostOk = hosts.includes(req.get('host') ?? '');
|
|
11
|
+
const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
|
|
12
|
+
const siteOk = !FOREIGN.includes(req.get('sec-fetch-site') ?? '');
|
|
13
|
+
if (!hostOk || !originOk || !siteOk)
|
|
14
|
+
throw fail('FORBIDDEN', 'Only this machine may call this server');
|
|
15
|
+
next();
|
|
16
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
declare const InstallEntrySchema: z.ZodObject<{
|
|
3
|
+
id: z.ZodString;
|
|
4
|
+
version: z.ZodOptional<z.ZodString>;
|
|
5
|
+
source: z.ZodOptional<z.ZodString>;
|
|
6
|
+
enabled: z.ZodOptional<z.ZodBoolean>;
|
|
7
|
+
}, z.core.$loose>;
|
|
8
|
+
export type InstallEntry = z.infer<typeof InstallEntrySchema>;
|
|
9
|
+
export interface Installation {
|
|
10
|
+
host: string;
|
|
11
|
+
extensions: InstallEntry[];
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
interface CheckedInstallation {
|
|
15
|
+
doc: Installation;
|
|
16
|
+
invalid: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare const bootInstallation: (configDir: string) => Promise<{
|
|
19
|
+
doc: Installation;
|
|
20
|
+
invalid: boolean;
|
|
21
|
+
unreadable: string;
|
|
22
|
+
} | (CheckedInstallation & {
|
|
23
|
+
unreadable?: string;
|
|
24
|
+
})>;
|
|
25
|
+
export declare const assertReadable: (configDir: string, why?: string) => Promise<void>;
|
|
26
|
+
export declare const keepBadCopy: (configDir: string) => Promise<void>;
|
|
27
|
+
type Change = (doc: Installation) => Installation;
|
|
28
|
+
/**
|
|
29
|
+
* Read, change and write installation.json under the kit's lock, the path the daemon uses.
|
|
30
|
+
* Only while no daemon runs on configDir (it reads the file at its start and owns it after):
|
|
31
|
+
* a live daemon named by daemon.json is refused, unless this is that daemon's process.
|
|
32
|
+
*/
|
|
33
|
+
export declare const updateInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
|
|
34
|
+
export declare const persistInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
|
|
35
|
+
export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { copyFile } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { fail } from '../../envelope/envelope.js';
|
|
5
|
+
import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
|
|
6
|
+
import { assertNoOtherDaemon } from './daemon-owner.js';
|
|
7
|
+
import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
|
|
8
|
+
// One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
|
|
9
|
+
const InstallEntrySchema = z.looseObject({
|
|
10
|
+
id: ExtensionIdSchema,
|
|
11
|
+
version: z.string().min(1).optional(),
|
|
12
|
+
source: z.string().refine(isAbsolute).optional(),
|
|
13
|
+
enabled: z.boolean().optional(),
|
|
14
|
+
});
|
|
15
|
+
const InstallationSchema = z.looseObject({
|
|
16
|
+
host: z.string().default('local'),
|
|
17
|
+
extensions: z.array(z.unknown()),
|
|
18
|
+
});
|
|
19
|
+
const INSTALLATION_FILE = 'installation.json';
|
|
20
|
+
const EMPTY = { host: 'local', extensions: [] };
|
|
21
|
+
const checked = (raw) => {
|
|
22
|
+
const top = InstallationSchema.safeParse(raw);
|
|
23
|
+
if (!top.success)
|
|
24
|
+
return { doc: EMPTY, invalid: true };
|
|
25
|
+
const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
|
|
26
|
+
const valid = rows.flatMap((row) => (row.success ? [row.data] : []));
|
|
27
|
+
const extensions = valid.filter((row, at) => valid.findIndex((e) => e.id === row.id) === at);
|
|
28
|
+
return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
|
|
29
|
+
};
|
|
30
|
+
// At boot the daemon has no rows from it, so a fix needs a restart; later a fix is enough.
|
|
31
|
+
const unreadable = (why, atBoot = false) => fail('CONFLICT', `${INSTALLATION_FILE} cannot be read (${why}): fix it${atBoot ? ', then restart the daemon' : ''}; no change is written`, { code: 'INSTALLATION_UNREADABLE', details: { reason: why } });
|
|
32
|
+
const reasonOf = (err) => err instanceof SyntaxError
|
|
33
|
+
? 'not JSON'
|
|
34
|
+
: String(err.code ?? err.message);
|
|
35
|
+
// Not readable (EACCES, EISDIR): thrown.
|
|
36
|
+
const rawOf = (configDir, notJson = 'empty') => readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch((err) => {
|
|
37
|
+
if (err instanceof SyntaxError && notJson === 'empty')
|
|
38
|
+
return null;
|
|
39
|
+
throw err;
|
|
40
|
+
});
|
|
41
|
+
const readInstallation = async (configDir, notJson) => checked(await rawOf(configDir, notJson).catch((err) => {
|
|
42
|
+
throw unreadable(reasonOf(err));
|
|
43
|
+
}));
|
|
44
|
+
// At boot an unreadable file gives no rows and its reason; the daemon then refuses every change.
|
|
45
|
+
export const bootInstallation = (configDir) => rawOf(configDir).then((raw) => checked(raw), (err) => ({ doc: EMPTY, invalid: false, unreadable: reasonOf(err) }));
|
|
46
|
+
// A change is refused when the file was unreadable at boot (why) or is unreadable now.
|
|
47
|
+
export const assertReadable = async (configDir, why) => {
|
|
48
|
+
if (why)
|
|
49
|
+
throw unreadable(why, true);
|
|
50
|
+
await readInstallation(configDir, 'refuse');
|
|
51
|
+
};
|
|
52
|
+
// A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
|
|
53
|
+
export const keepBadCopy = (configDir) => copyFile(join(configDir, INSTALLATION_FILE), join(configDir, `${INSTALLATION_FILE}.bad`));
|
|
54
|
+
// Only rows C3 accepts are written, and each id once.
|
|
55
|
+
const checkedDoc = (next) => {
|
|
56
|
+
const ids = next.extensions.map((row) => row.id);
|
|
57
|
+
const bad = next.extensions.find((row) => !InstallEntrySchema.safeParse(row).success);
|
|
58
|
+
if (bad || new Set(ids).size < ids.length || !InstallationSchema.safeParse(next).success)
|
|
59
|
+
throw fail('VALIDATION_ERROR', `${INSTALLATION_FILE}: a row C3 refuses, or an id twice`);
|
|
60
|
+
return next;
|
|
61
|
+
};
|
|
62
|
+
const changeInstallation = (notJson) => async (configDir, change, waitMs) => {
|
|
63
|
+
await assertNoOtherDaemon(configDir);
|
|
64
|
+
const file = join(configDir, INSTALLATION_FILE);
|
|
65
|
+
const write = async () => {
|
|
66
|
+
const read = await readInstallation(configDir, notJson);
|
|
67
|
+
if (read.invalid)
|
|
68
|
+
await keepBadCopy(configDir);
|
|
69
|
+
const next = checkedDoc(change(read.doc));
|
|
70
|
+
await writeJsonFile(file, next);
|
|
71
|
+
return next;
|
|
72
|
+
};
|
|
73
|
+
return withFileLock(file, write, waitMs);
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Read, change and write installation.json under the kit's lock, the path the daemon uses.
|
|
77
|
+
* Only while no daemon runs on configDir (it reads the file at its start and owns it after):
|
|
78
|
+
* a live daemon named by daemon.json is refused, unless this is that daemon's process.
|
|
79
|
+
*/
|
|
80
|
+
export const updateInstallation = changeInstallation('empty');
|
|
81
|
+
// The daemon after its boot: its rows are in the file, so a file that is not JSON is never replaced.
|
|
82
|
+
export const persistInstallation = changeInstallation('refuse');
|
|
83
|
+
// The entry of id replaced (or added), the order kept; undefined removes it.
|
|
84
|
+
export const withEntry = (doc, id, entry) => {
|
|
85
|
+
const at = doc.extensions.findIndex((e) => e.id === id);
|
|
86
|
+
const rest = doc.extensions.filter((e) => e.id !== id);
|
|
87
|
+
if (!entry)
|
|
88
|
+
return { ...doc, extensions: rest };
|
|
89
|
+
if (at < 0)
|
|
90
|
+
return { ...doc, extensions: [...rest, entry] };
|
|
91
|
+
return { ...doc, extensions: doc.extensions.map((e) => (e.id === id ? entry : e)) };
|
|
92
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type InstallSpec, type SupervisorDeps } from './supervisor.js';
|
|
2
|
+
export declare const NO_INSTALLER = "this daemon has no installer: install a folder with { source }";
|
|
3
|
+
declare const BASE: {
|
|
4
|
+
readonly 400: "VALIDATION_ERROR";
|
|
5
|
+
readonly 404: "NOT_FOUND";
|
|
6
|
+
readonly 409: "CONFLICT";
|
|
7
|
+
readonly 501: "UNAVAILABLE";
|
|
8
|
+
readonly 502: "UNAVAILABLE";
|
|
9
|
+
readonly 504: "UNAVAILABLE";
|
|
10
|
+
};
|
|
11
|
+
export declare const answer: (status: keyof typeof BASE, message: string, code?: string, details?: Record<string, unknown>) => import("../../envelope/envelope.js").Failure & {
|
|
12
|
+
code: string;
|
|
13
|
+
status: 400 | 404 | 409 | 501 | 502 | 504;
|
|
14
|
+
retryAfter: undefined;
|
|
15
|
+
};
|
|
16
|
+
export declare const runInstaller: (deps: SupervisorDeps, spec: Omit<InstallSpec, "signal">) => Promise<{
|
|
17
|
+
id: string;
|
|
18
|
+
version: string;
|
|
19
|
+
dir: string;
|
|
20
|
+
}>;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import { fail } from '../../envelope/envelope.js';
|
|
3
|
+
import {} from './supervisor.js';
|
|
4
|
+
export const NO_INSTALLER = 'this daemon has no installer: install a folder with { source }';
|
|
5
|
+
const BASE = {
|
|
6
|
+
400: 'VALIDATION_ERROR',
|
|
7
|
+
404: 'NOT_FOUND',
|
|
8
|
+
409: 'CONFLICT',
|
|
9
|
+
501: 'UNAVAILABLE',
|
|
10
|
+
502: 'UNAVAILABLE',
|
|
11
|
+
504: 'UNAVAILABLE',
|
|
12
|
+
};
|
|
13
|
+
// The envelope with a status or a code the closed set has not (501, 504, the installer's own code).
|
|
14
|
+
export const answer = (status, message, code = BASE[status], details) => Object.assign(fail(BASE[status], message, { details }), { code, status, retryAfter: undefined });
|
|
15
|
+
// An installer error with a string code is the client's envelope; any other stays a 500.
|
|
16
|
+
const answerOf = (err) => {
|
|
17
|
+
const { code, status, message } = (err ?? {});
|
|
18
|
+
if (typeof code !== 'string' || !code)
|
|
19
|
+
return err;
|
|
20
|
+
const at = status === 404 || status === 502 ? status : 400;
|
|
21
|
+
return answer(at, typeof message === 'string' && message ? message : code, code);
|
|
22
|
+
};
|
|
23
|
+
// A second call while a timed-out one of that id still runs would overlap it.
|
|
24
|
+
const notTwice = (deps, id) => {
|
|
25
|
+
const row = deps.pending.timedOut(id);
|
|
26
|
+
if (row)
|
|
27
|
+
throw answer(409, `the installer of ${id} still runs`, 'CONFLICT', { ...row });
|
|
28
|
+
};
|
|
29
|
+
// At most installMs, then 504 TIMEOUT; only then the signal asks the installer to stop.
|
|
30
|
+
export const runInstaller = async (deps, spec) => {
|
|
31
|
+
if (!deps.install)
|
|
32
|
+
throw answer(501, NO_INSTALLER);
|
|
33
|
+
notTwice(deps, spec.id);
|
|
34
|
+
const since = new Date().toISOString();
|
|
35
|
+
const stop = new AbortController();
|
|
36
|
+
const timer = new AbortController();
|
|
37
|
+
const call = deps.install({ ...spec, signal: stop.signal });
|
|
38
|
+
const late = sleep(deps.installMs, undefined, { ref: false, signal: timer.signal }).then(() => {
|
|
39
|
+
stop.abort();
|
|
40
|
+
deps.pending.linger(spec.id, since, call);
|
|
41
|
+
throw answer(504, `the installer did not answer in ${deps.installMs} ms`, 'TIMEOUT');
|
|
42
|
+
});
|
|
43
|
+
late.catch(() => undefined);
|
|
44
|
+
const answered = call.catch((err) => {
|
|
45
|
+
throw answerOf(err);
|
|
46
|
+
});
|
|
47
|
+
return Promise.race([answered, late]).finally(() => timer.abort());
|
|
48
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const readJsonFile: <T>(file: string, fallback: T) => Promise<T>;
|
|
2
|
+
export declare const writeJsonFile: (file: string, value: unknown, given?: number) => Promise<void>;
|
|
3
|
+
export declare const LOCK_WAIT_MS = 5000;
|
|
4
|
+
export declare const withFileLock: <T>(file: string, fn: () => T | Promise<T>, waitMs?: number) => Promise<T>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, open, readFile, rename, stat } from 'node:fs/promises';
|
|
3
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
+
import { basename } from 'node:path';
|
|
5
|
+
import { fail } from '../../envelope/envelope.js';
|
|
6
|
+
import { DATA_DIR_LOCKED, lockDataDir } from '../data-lock.js';
|
|
7
|
+
export const readJsonFile = async (file, fallback) => {
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(await readFile(file, 'utf8'));
|
|
10
|
+
}
|
|
11
|
+
catch (err) {
|
|
12
|
+
if (err.code === 'ENOENT')
|
|
13
|
+
return fallback;
|
|
14
|
+
throw err;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
// The mode of a file already there, narrowed by the default: a 0600 file is never widened.
|
|
18
|
+
const modeOf = (file, mode) => stat(file).then((st) => st.mode & mode & 0o777, () => mode);
|
|
19
|
+
// A reader sees the old file or the new one, never half of one, also after a power loss.
|
|
20
|
+
export const writeJsonFile = async (file, value, given = 0o644) => {
|
|
21
|
+
const mode = await modeOf(file, given);
|
|
22
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
23
|
+
const handle = await open(tmp, 'w', mode);
|
|
24
|
+
try {
|
|
25
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`);
|
|
26
|
+
await handle.sync();
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
await handle.close();
|
|
30
|
+
}
|
|
31
|
+
await chmod(tmp, mode);
|
|
32
|
+
await rename(tmp, file);
|
|
33
|
+
};
|
|
34
|
+
export const LOCK_WAIT_MS = 5_000;
|
|
35
|
+
// A live holder (or a reused pid of a dead one) named, so a person can check that process.
|
|
36
|
+
const lockedBy = (file, err, waitMs) => fail('UNAVAILABLE', `${basename(file)} is locked by process ${err.pid ?? 0}: waited ${waitMs} ms`, { retryAfter: 1 });
|
|
37
|
+
// The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one waited for waitMs.
|
|
38
|
+
const acquire = async (file, waitMs) => {
|
|
39
|
+
const until = Date.now() + waitMs;
|
|
40
|
+
for (;;) {
|
|
41
|
+
try {
|
|
42
|
+
return await lockDataDir(file);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (err.code !== DATA_DIR_LOCKED)
|
|
46
|
+
throw err;
|
|
47
|
+
if (Date.now() >= until)
|
|
48
|
+
throw lockedBy(file, err, waitMs);
|
|
49
|
+
await sleep(25);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
// One writer at a time across processes: an exclusive lock file (<file>.lock) beside the file.
|
|
54
|
+
export const withFileLock = async (file, fn, waitMs = LOCK_WAIT_MS) => {
|
|
55
|
+
const release = await acquire(file, waitMs);
|
|
56
|
+
try {
|
|
57
|
+
return await fn();
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await release();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Child } from './child.js';
|
|
2
|
+
export interface Lane {
|
|
3
|
+
child: Child;
|
|
4
|
+
open: number;
|
|
5
|
+
idle: (() => void)[];
|
|
6
|
+
}
|
|
7
|
+
export declare const laneOf: (child: Child) => Lane;
|
|
8
|
+
export declare const enter: (lane: Lane) => (() => void);
|
|
9
|
+
export declare const retire: (lane: Lane | undefined, drainMs: number) => Promise<void>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import {} from './child.js';
|
|
3
|
+
export const laneOf = (child) => ({ child, open: 0, idle: [] });
|
|
4
|
+
// Counts one request until leave() is called (once).
|
|
5
|
+
export const enter = (lane) => {
|
|
6
|
+
lane.open += 1;
|
|
7
|
+
let left = false;
|
|
8
|
+
return () => {
|
|
9
|
+
if (left)
|
|
10
|
+
return;
|
|
11
|
+
left = true;
|
|
12
|
+
lane.open -= 1;
|
|
13
|
+
if (lane.open === 0)
|
|
14
|
+
lane.idle.splice(0).forEach((resolve) => resolve());
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
const drained = (lane) => lane.open === 0 ? Promise.resolve() : new Promise((resolve) => lane.idle.push(resolve));
|
|
18
|
+
// Waits for the open requests (at most drainMs, so a hung one blocks nothing), then stops the child.
|
|
19
|
+
export const retire = async (lane, drainMs) => {
|
|
20
|
+
if (!lane)
|
|
21
|
+
return;
|
|
22
|
+
await Promise.race([drained(lane), sleep(drainMs, undefined, { ref: false })]);
|
|
23
|
+
await lane.child.stop();
|
|
24
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const LIMITS: {
|
|
2
|
+
drainMs: number;
|
|
3
|
+
startMs: number;
|
|
4
|
+
healthMs: number;
|
|
5
|
+
lockMs: number;
|
|
6
|
+
gateMs: number;
|
|
7
|
+
answerMs: number;
|
|
8
|
+
installMs: number;
|
|
9
|
+
};
|
|
10
|
+
export type Limits = typeof LIMITS;
|
|
11
|
+
export declare const limitsOf: (given: Partial<Limits>) => Limits;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Every wait of the daemon has a bound; each is a createDaemon option (docs/part-image.md).
|
|
2
|
+
export const LIMITS = {
|
|
3
|
+
// An old child's open requests before it is stopped.
|
|
4
|
+
drainMs: 10_000,
|
|
5
|
+
// A forked child's port report; then SIGKILL.
|
|
6
|
+
startMs: 60_000,
|
|
7
|
+
// A new child's own /health, once it reported its port.
|
|
8
|
+
healthMs: 60_000,
|
|
9
|
+
// A write waits for another process that holds the lock of a daemon file.
|
|
10
|
+
lockMs: 5_000,
|
|
11
|
+
// A request held while its extension swaps children.
|
|
12
|
+
gateMs: 30_000,
|
|
13
|
+
// A child's answer headers; then 504.
|
|
14
|
+
answerMs: 60_000,
|
|
15
|
+
// One Installer call (POST, PATCH, each entry at boot), and a change queued behind others:
|
|
16
|
+
// above the cli's npm bound (10 min), below its client wait (12 min).
|
|
17
|
+
installMs: 660_000,
|
|
18
|
+
};
|
|
19
|
+
export const limitsOf = (given) => {
|
|
20
|
+
const keys = Object.keys(LIMITS);
|
|
21
|
+
return Object.fromEntries(keys.map((key) => [key, given[key] ?? LIMITS[key]]));
|
|
22
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Entries } from './entries.js';
|
|
2
|
+
import { type SupervisorDeps } from './supervisor.js';
|
|
3
|
+
export declare const changeExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
|
|
4
|
+
error?: string | undefined;
|
|
5
|
+
pid?: number | undefined;
|
|
6
|
+
id: string;
|
|
7
|
+
version: string;
|
|
8
|
+
state: import("./supervisor.js").State;
|
|
9
|
+
}>;
|
|
10
|
+
export declare const removeExtension: (deps: SupervisorDeps, entries: Entries, id: string, purge: boolean) => Promise<{
|
|
11
|
+
id: string;
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { fail } from '../../envelope/envelope.js';
|
|
4
|
+
import { parse } from '../../envelope/parse.js';
|
|
5
|
+
import { SecretNameSchema } from '../../manifest/primitives.schema.js';
|
|
6
|
+
import { purgeData } from './daemon-files.js';
|
|
7
|
+
import { entryOf, summary } from './entries.js';
|
|
8
|
+
import { unsynced, writeAll } from './write-all.js';
|
|
9
|
+
import { runInstaller } from './installer-call.js';
|
|
10
|
+
import { checkedSettings } from './patch-values.js';
|
|
11
|
+
import {} from './installation.js';
|
|
12
|
+
import { halt, hold, swap, valuesOf, } from './supervisor.js';
|
|
13
|
+
const PatchSchema = z.strictObject({
|
|
14
|
+
version: z.string().min(1).optional(),
|
|
15
|
+
enabled: z.boolean().optional(),
|
|
16
|
+
settings: z.record(z.string(), z.unknown()).optional(),
|
|
17
|
+
secrets: z.record(SecretNameSchema, z.string()).optional(),
|
|
18
|
+
});
|
|
19
|
+
// The install entry a patch asks for; a new version is installed first and its folder kept aside.
|
|
20
|
+
const nextInstall = async (deps, entry, patch) => {
|
|
21
|
+
// enabled absent means true (C3), so only false is written.
|
|
22
|
+
const install = { ...entry.install };
|
|
23
|
+
delete install.enabled;
|
|
24
|
+
if ((patch.enabled ?? entry.install.enabled) === false)
|
|
25
|
+
install.enabled = false;
|
|
26
|
+
if (!patch.version || patch.version === entry.install.version)
|
|
27
|
+
return { install };
|
|
28
|
+
if (install.source)
|
|
29
|
+
throw fail('VALIDATION_ERROR', `${entry.id} runs a folder: it has no version`);
|
|
30
|
+
const got = await runInstaller(deps, { id: entry.id, version: patch.version });
|
|
31
|
+
return { install: { ...install, version: got.version }, dir: got.dir };
|
|
32
|
+
};
|
|
33
|
+
// The change, and the values on disk now: what a failed write puts back.
|
|
34
|
+
const nextOf = async (deps, entry, patch) => {
|
|
35
|
+
const next = await nextInstall(deps, entry, patch);
|
|
36
|
+
const dir = next.dir ?? entry.dir ?? entry.install.source;
|
|
37
|
+
const given = await checkedSettings(dir, patch, entry.id);
|
|
38
|
+
const was = await valuesOf(deps.configDir, entry.id);
|
|
39
|
+
const settings = { ...was.settings, ...given };
|
|
40
|
+
const values = { settings, secrets: { ...was.secrets, ...patch.secrets } };
|
|
41
|
+
return { to: { ...next, values }, was };
|
|
42
|
+
};
|
|
43
|
+
// Disabled: written, then stopped. Else written, then swapped; a refused start puts the files back.
|
|
44
|
+
const apply = async (deps, entry, to, was) => {
|
|
45
|
+
const back = { install: entry.install, values: was };
|
|
46
|
+
await writeAll(deps, entry.id, to, back);
|
|
47
|
+
const undo = () => writeAll(deps, entry.id, back, to).catch(() => unsynced(deps, entry.id));
|
|
48
|
+
if (to.install.enabled !== false)
|
|
49
|
+
await swap(deps, entry, to, undo);
|
|
50
|
+
else
|
|
51
|
+
await halt(entry, deps.drainMs);
|
|
52
|
+
Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
|
|
53
|
+
if (to.install.enabled === false)
|
|
54
|
+
entry.state = 'disabled';
|
|
55
|
+
};
|
|
56
|
+
// A request sent once the change is decided waits (gateMs) and goes to the result.
|
|
57
|
+
const held = async (deps, entry, to, was) => {
|
|
58
|
+
const release = hold(entry);
|
|
59
|
+
try {
|
|
60
|
+
await apply(deps, entry, to, was);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
release();
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
// Nothing to do: the same files, and the entry already runs (or is stopped) as they say.
|
|
67
|
+
const unchanged = (entry, to, was) => entry.state === (to.install.enabled === false ? 'disabled' : 'running') &&
|
|
68
|
+
(!to.dir || to.dir === entry.dir) &&
|
|
69
|
+
isDeepStrictEqual(to.install, entry.install) &&
|
|
70
|
+
isDeepStrictEqual(to.values, was);
|
|
71
|
+
// PATCH: a refused change keeps the old one and is 400 START_FAILED; a failed entry is started again.
|
|
72
|
+
export const changeExtension = async (deps, entries, id, body) => {
|
|
73
|
+
const patch = parse(PatchSchema, body, 'Invalid body');
|
|
74
|
+
const entry = entryOf(entries, id);
|
|
75
|
+
const { to, was } = await nextOf(deps, entry, patch);
|
|
76
|
+
if (!unchanged(entry, to, was))
|
|
77
|
+
await held(deps, entry, to, was);
|
|
78
|
+
return summary(entry);
|
|
79
|
+
};
|
|
80
|
+
// DELETE: the files first (all or none), then the child stops; purge also deletes its data folder.
|
|
81
|
+
export const removeExtension = async (deps, entries, id, purge) => {
|
|
82
|
+
const entry = entryOf(entries, id);
|
|
83
|
+
await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
|
|
84
|
+
entries.delete(id);
|
|
85
|
+
await halt(entry, deps.drainMs);
|
|
86
|
+
if (purge)
|
|
87
|
+
await purgeData(deps.configDir, id);
|
|
88
|
+
return { id };
|
|
89
|
+
};
|