clavarium 0.2.18 → 0.2.19-next.2
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/deploy/clavarium-host +367 -2
- package/deploy/install.sh +29 -1
- package/deploy/maintenance.html +109 -0
- package/deploy/updater.mjs +99 -5
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/api.mjs +17 -3
- package/server/conversations.mjs +170 -39
- package/server/events.mjs +5 -1
- package/server/health.mjs +3 -2
- package/server/main.mjs +23 -4
- package/server/talk.mjs +6 -3
- package/server/updates.mjs +28 -3
- package/server/wifi.mjs +125 -0
- package/web/app.js +173 -6
- package/web/index.html +31 -0
- package/web/style.css +12 -0
package/deploy/updater.mjs
CHANGED
|
@@ -37,7 +37,8 @@
|
|
|
37
37
|
*
|
|
38
38
|
* AN UPDATE (apply), never while a machine is being built, moved or restarted:
|
|
39
39
|
* a release is made; a backup of the server's data is taken (backup.sh
|
|
40
|
-
* --server-only); the
|
|
40
|
+
* --server-only); the open pages are told and given NOTICE_MS to show the
|
|
41
|
+
* maintenance page (MAINTENANCE_BLOCK); the link is switched; the privileged programs of the new
|
|
41
42
|
* release are put in place; the server restarts and must come up (health).
|
|
42
43
|
* If it does not: the link goes back, the previous programs too, the data
|
|
43
44
|
* backup is put back if the data format moved, the server restarts, and the
|
|
@@ -48,8 +49,9 @@
|
|
|
48
49
|
* --------------------------------------------------------------------------- */
|
|
49
50
|
import { spawn } from 'node:child_process';
|
|
50
51
|
import { createHash } from 'node:crypto';
|
|
51
|
-
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, statSync, chmodSync } from 'node:fs';
|
|
52
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync, readdirSync, existsSync, symlinkSync, realpathSync, cpSync, openSync, closeSync, statfsSync, statSync, chmodSync, mkdtempSync } from 'node:fs';
|
|
52
53
|
import { dirname, join, basename } from 'node:path';
|
|
54
|
+
import { tmpdir } from 'node:os';
|
|
53
55
|
import { fileURLToPath } from 'node:url';
|
|
54
56
|
import { fetchParleyArchive, REGISTRY } from './parley-archive.mjs';
|
|
55
57
|
import { ensureTunnel, tunnelUnit, relayOfUnit, TUNNEL_UNIT, TUNNEL_PROGRAM } from './tunnel.mjs';
|
|
@@ -79,6 +81,10 @@ const WATCH_EVERY_MS = 3600_000;
|
|
|
79
81
|
const WATCH_RECENT_MS = 24 * 3600_000;
|
|
80
82
|
const HISTORY_MAX = 30;
|
|
81
83
|
const ASK_EVERY_MS = 6 * 3600_000;
|
|
84
|
+
/* Between "Switching" said in state.json and the server stopped: the pages ask the server every
|
|
85
|
+
10 seconds at most (app.js), and the server says it in each answer (updates.mjs, notice): each
|
|
86
|
+
gives way to the maintenance page before the server goes. */
|
|
87
|
+
export const NOTICE_MS = 15_000;
|
|
82
88
|
const PROVENANCE = 'https://slsa.dev/provenance/v1';
|
|
83
89
|
/* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
|
|
84
90
|
const LOG_MAX = 12_000;
|
|
@@ -104,6 +110,85 @@ export async function ensureProxySettings({ file = PROXY_CFG, run = runCommand }
|
|
|
104
110
|
return true;
|
|
105
111
|
}
|
|
106
112
|
|
|
113
|
+
/* THE MAINTENANCE PAGE, kept by the updater: while the server is down (an update, a restart) the
|
|
114
|
+
front (Caddy) answers it instead of the sign-in proxy's "Bad Gateway". The sign-in proxy answers
|
|
115
|
+
502 in HTML when the server does not; the server's own errors are JSON and pass as they are. A
|
|
116
|
+
page gets the page (deploy/maintenance.html, copied OUTSIDE the releases: it is there during the
|
|
117
|
+
switch); a request of the page (/api/, /c/api/) gets JSON. install.sh writes the same block. */
|
|
118
|
+
export const CADDYFILE = '/etc/caddy/Caddyfile';
|
|
119
|
+
export const CADDY = '/usr/local/bin/caddy';
|
|
120
|
+
export const MAINTENANCE_DIR = '/var/lib/clavarium/maintenance';
|
|
121
|
+
export const MAINTENANCE_PAGE = fileURLToPath(new URL('maintenance.html', import.meta.url));
|
|
122
|
+
/* What install.sh wrote before the maintenance page: replaced, once, by MAINTENANCE_BLOCK. */
|
|
123
|
+
export const PLAIN_BLOCK = '\thandle {\n\t\treverse_proxy 127.0.0.1:4180\n\t}\n';
|
|
124
|
+
export const MAINTENANCE_BLOCK = [
|
|
125
|
+
'\thandle {',
|
|
126
|
+
'\t\t# The server down (an update, a restart): the maintenance page (deploy/updater.mjs, MAINTENANCE_BLOCK).',
|
|
127
|
+
'\t\treverse_proxy 127.0.0.1:4180 {',
|
|
128
|
+
'\t\t\t@down {',
|
|
129
|
+
'\t\t\t\tstatus 502 503 504',
|
|
130
|
+
'\t\t\t\theader Content-Type text/html*',
|
|
131
|
+
'\t\t\t}',
|
|
132
|
+
'\t\t\thandle_response @down {',
|
|
133
|
+
'\t\t\t\theader Cache-Control no-store',
|
|
134
|
+
'\t\t\t\theader Retry-After 3',
|
|
135
|
+
'\t\t\t\theader X-Clavarium-Down 1',
|
|
136
|
+
'\t\t\t\t@api path /api/* /c/api/*',
|
|
137
|
+
'\t\t\t\thandle @api {',
|
|
138
|
+
'\t\t\t\t\theader Content-Type "application/json; charset=utf-8"',
|
|
139
|
+
'\t\t\t\t\trespond "{\\"error\\":\\"Clavarium is being updated or restarted: it comes back by itself in a moment.\\",\\"down\\":true}" 503',
|
|
140
|
+
'\t\t\t\t}',
|
|
141
|
+
'\t\t\t\thandle {',
|
|
142
|
+
`\t\t\t\t\troot * ${MAINTENANCE_DIR}`,
|
|
143
|
+
'\t\t\t\t\trewrite * /index.html',
|
|
144
|
+
'\t\t\t\t\tfile_server {',
|
|
145
|
+
'\t\t\t\t\t\tstatus 503',
|
|
146
|
+
'\t\t\t\t\t}',
|
|
147
|
+
'\t\t\t\t}',
|
|
148
|
+
'\t\t\t}',
|
|
149
|
+
'\t\t}',
|
|
150
|
+
'\t}',
|
|
151
|
+
'',
|
|
152
|
+
].join('\n');
|
|
153
|
+
|
|
154
|
+
/* Idempotent, at each timer turn: the page copied when it differs; the block put in a Caddyfile
|
|
155
|
+
that has the plain one, checked by `caddy validate` first, then Caddy reloaded (a reload Caddy
|
|
156
|
+
refuses leaves the running site as it was: the file is put back). A Caddyfile changed by hand is
|
|
157
|
+
not touched. No Caddyfile (local mode, --core-only): nothing. { page, edge, why } */
|
|
158
|
+
export async function ensureMaintenance({ caddyfile = CADDYFILE, caddy = CADDY, page = MAINTENANCE_PAGE, dir = MAINTENANCE_DIR, run = runCommand } = {}) {
|
|
159
|
+
let text;
|
|
160
|
+
try { text = readFileSync(caddyfile, 'utf8'); } catch { return { page: false, edge: false, why: '' }; }
|
|
161
|
+
const said = { page: false, edge: false, why: '' };
|
|
162
|
+
const html = readFileSync(page);
|
|
163
|
+
const file = join(dir, 'index.html');
|
|
164
|
+
let had = null;
|
|
165
|
+
try { had = readFileSync(file); } catch { /* not there */ }
|
|
166
|
+
if (!had?.equals(html)) {
|
|
167
|
+
mkdirSync(dir, { recursive: true, mode: 0o755 });
|
|
168
|
+
writeFileSync(`${file}.new`, html, { mode: 0o644 });
|
|
169
|
+
chmodSync(`${file}.new`, 0o644);
|
|
170
|
+
renameSync(`${file}.new`, file);
|
|
171
|
+
said.page = true;
|
|
172
|
+
}
|
|
173
|
+
if (text.includes(MAINTENANCE_BLOCK)) return said;
|
|
174
|
+
if (text.split(PLAIN_BLOCK).length !== 2) return { ...said, why: 'the Caddyfile is not the one install.sh wrote: the maintenance page is not added to it' };
|
|
175
|
+
const tmp = `${caddyfile}.new`;
|
|
176
|
+
writeFileSync(tmp, text.replace(PLAIN_BLOCK, MAINTENANCE_BLOCK), { mode: 0o644 });
|
|
177
|
+
/* Checked apart: what `caddy validate` keeps of its own goes to a folder of its own, never Caddy's. */
|
|
178
|
+
const own = mkdtempSync(join(tmpdir(), 'clavarium-caddy-'));
|
|
179
|
+
let checked;
|
|
180
|
+
try { checked = await run([caddy, 'validate', '--config', tmp, '--adapter', 'caddyfile'], { env: { ...process.env, XDG_DATA_HOME: own, XDG_CONFIG_HOME: own, HOME: own }, timeoutMs: 60_000 }); } finally { rmSync(own, { recursive: true, force: true }); }
|
|
181
|
+
if (checked.code !== 0) { rmSync(tmp, { force: true }); return { ...said, why: `caddy validate refused it: ${lastLine(checked)}` }; }
|
|
182
|
+
chmodSync(tmp, 0o644);
|
|
183
|
+
renameSync(tmp, caddyfile);
|
|
184
|
+
const reloaded = await run(['systemctl', 'try-reload-or-restart', 'caddy.service'], { timeoutMs: 60_000 });
|
|
185
|
+
if (reloaded.code === 0) return { ...said, edge: true };
|
|
186
|
+
writeFileSync(tmp, text, { mode: 0o644 });
|
|
187
|
+
renameSync(tmp, caddyfile);
|
|
188
|
+
await run(['systemctl', 'try-reload-or-restart', 'caddy.service'], { timeoutMs: 60_000 });
|
|
189
|
+
return { ...said, why: `Caddy did not take it (${lastLine(reloaded)}): the Caddyfile was put back` };
|
|
190
|
+
}
|
|
191
|
+
|
|
107
192
|
export class Refused extends Error {}
|
|
108
193
|
|
|
109
194
|
/* SEMANTIC VERSIONS, compared as npm does: a pre-release comes before its release. */
|
|
@@ -178,8 +263,8 @@ export class Updater {
|
|
|
178
263
|
#o; #run; #fetch;
|
|
179
264
|
constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, tunnelTarget = PATHS.tunnel, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
|
|
180
265
|
verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
|
|
181
|
-
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000 } = {}) {
|
|
182
|
-
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, clock, sleep, dropIn };
|
|
266
|
+
clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS } = {}) {
|
|
267
|
+
this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, clock, sleep, dropIn };
|
|
183
268
|
this.#run = run; this.#fetch = fetcher;
|
|
184
269
|
this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
|
|
185
270
|
this.restart = restart ?? (() => this.#restart());
|
|
@@ -214,7 +299,8 @@ export class Updater {
|
|
|
214
299
|
renameSync(`${file}.new`, file);
|
|
215
300
|
return state;
|
|
216
301
|
}
|
|
217
|
-
|
|
302
|
+
/* `since`: when the action began; `at`: when this step did (the server ignores an old step: updates.mjs, notice). */
|
|
303
|
+
#step(action, version, step) { this.#o.log(`${action} ${version}: ${step}`); this.#save({ running: { action, version, step, since: (this.#state().running?.since) ?? this.#o.now().toISOString(), at: this.#o.now().toISOString() } }); }
|
|
218
304
|
#history(entry) {
|
|
219
305
|
const state = this.#state();
|
|
220
306
|
const history = [{ id: createHash('sha256').update(`${Date.now()}${Math.random()}`).digest('hex').slice(0, 12), at: this.#o.now().toISOString(), ...entry }, ...(state.history ?? [])].slice(0, HISTORY_MAX);
|
|
@@ -505,6 +591,8 @@ export class Updater {
|
|
|
505
591
|
async #switchAndCheck(release, action, version) {
|
|
506
592
|
try {
|
|
507
593
|
this.#step(action, version, 'Switching');
|
|
594
|
+
/* The pages told first: they give way to the maintenance page while the server still answers. */
|
|
595
|
+
await this.#o.sleep(this.#o.noticeMs);
|
|
508
596
|
this.switchTo(release.id);
|
|
509
597
|
await this.installPrivileged(release.app);
|
|
510
598
|
} catch (error) { return `it could not be put in place: ${error.message}`; }
|
|
@@ -823,6 +911,12 @@ async function main(argv) {
|
|
|
823
911
|
writeFileSync(join(PATHS.stateDir, 'relay.json.new'), `${JSON.stringify({ ...outcome, at: new Date().toISOString() })}\n`, { mode: 0o644 });
|
|
824
912
|
renameSync(join(PATHS.stateDir, 'relay.json.new'), join(PATHS.stateDir, 'relay.json'));
|
|
825
913
|
} catch (error) { console.error(`updater: the relay could not be looked at: ${error.message}`); }
|
|
914
|
+
try {
|
|
915
|
+
const m = await ensureMaintenance();
|
|
916
|
+
if (m.page) console.error('updater: the maintenance page written');
|
|
917
|
+
if (m.edge) console.error('updater: the front serves the maintenance page while the server is down');
|
|
918
|
+
if (m.why) console.error(`updater: the maintenance page: ${m.why}`);
|
|
919
|
+
} catch (error) { console.error(`updater: the maintenance page could not be set: ${error.message}`); }
|
|
826
920
|
const r = await u.runOnce(); console.log(typeof r === 'string' ? r : 'done'); return; }
|
|
827
921
|
case 'set': if (rest.length !== 2) throw new Refused('set <mode|channel|window|port> <value>'); return print(u.set(rest[0], rest[1]));
|
|
828
922
|
case 'prepare': { const r = await u.prepare({ version: value('--version'), fromDir: value('--from-dir') }); console.log(r.id); return; }
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.19-next.2",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.19-next.2",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
13
13
|
"@xterm/xterm": "^6.0.0",
|
|
14
|
-
"clavarium-parley": "0.
|
|
14
|
+
"clavarium-parley": "0.13.0-next.1",
|
|
15
15
|
"mermaid": "11.17.2",
|
|
16
16
|
"node-pty": "^1.1.0",
|
|
17
17
|
"pdfjs-dist": "6.4.299",
|
|
@@ -686,9 +686,9 @@
|
|
|
686
686
|
}
|
|
687
687
|
},
|
|
688
688
|
"node_modules/clavarium-parley": {
|
|
689
|
-
"version": "0.
|
|
690
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.
|
|
691
|
-
"integrity": "sha512-
|
|
689
|
+
"version": "0.13.0-next.1",
|
|
690
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.13.0-next.1.tgz",
|
|
691
|
+
"integrity": "sha512-BoZlSrshotRD+jK2jg8eJECbTQplTou5pQV7nG+uqPq+n/Mag+tdWwiCtLvrI0RFPQ2teC6+8Ci8rPgH9EaX2w==",
|
|
692
692
|
"license": "MIT",
|
|
693
693
|
"bin": {
|
|
694
694
|
"parley": "bin/parley.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.19-next.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@xterm/addon-fit": "^0.11.0",
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
|
-
"clavarium-parley": "0.
|
|
47
|
+
"clavarium-parley": "0.13.0-next.1",
|
|
48
48
|
"mermaid": "11.17.2",
|
|
49
49
|
"node-pty": "^1.1.0",
|
|
50
50
|
"pdfjs-dist": "6.4.299",
|
package/server/api.mjs
CHANGED
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
* POST /api/conversations {name, tool, memoryMb?}
|
|
6
6
|
* POST /api/conversations/<name>/sleep
|
|
7
7
|
* POST /api/conversations/<name>/restart a clean stop (by force if it hangs), then a start
|
|
8
|
-
* POST /api/conversations/<name>/machine {memoryMb?, diskGb?}: stopped, set, started again
|
|
8
|
+
* POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
|
|
9
|
+
* asleep: checked and kept for its wake, as `sizeAtWake` (200)
|
|
10
|
+
* POST /api/conversations/<name>/machine/cancel the size kept for its wake, given up
|
|
9
11
|
* GET /api/conversations/<name>/health what was last seen of its machine
|
|
10
12
|
* POST /api/conversations/<name>/health look now (never wakes a machine)
|
|
11
13
|
* POST /api/conversations/<name>/health/seen what it says now no longer calls its owner (Needs you)
|
|
@@ -72,6 +74,9 @@
|
|
|
72
74
|
* POST /api/machines/forget-old: the copy a move left behind, removed
|
|
73
75
|
* POST /api/machines/grow {mount}: room set aside and unused, given to that file system
|
|
74
76
|
* GET /api/machines/disks: every disk, whole POST /api/machines/mount {path} POST /api/machines/prepare {path, typed}: erased
|
|
77
|
+
* GET /api/wifi: this server's Wi-Fi GET /api/wifi/scan: the networks it sees (looked for again)
|
|
78
|
+
* POST /api/wifi/join {ssid, password}: the switch started, back by itself if it does not work
|
|
79
|
+
* POST /api/wifi/forget {ssid}: a kept network deleted (never the one in use)
|
|
75
80
|
* GET /api/events?kind=&conversation=&q=&before=&limit= what happened, newest first
|
|
76
81
|
* GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
|
|
77
82
|
* GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
|
|
@@ -130,7 +135,7 @@ function readBody(request, max = BODY_MAX) {
|
|
|
130
135
|
}
|
|
131
136
|
|
|
132
137
|
/* Returns true when the request was an API request (answered here). */
|
|
133
|
-
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles) {
|
|
138
|
+
export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi) {
|
|
134
139
|
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
135
140
|
if (!pathname.startsWith('/api/')) return false;
|
|
136
141
|
let send = (status, body) => {
|
|
@@ -263,6 +268,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
263
268
|
if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
|
|
264
269
|
if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
|
|
265
270
|
if (pathname === '/api/machines/moving' && machinesMove) return send(200, await machinesMove.moving()), true;
|
|
271
|
+
if (pathname === '/api/wifi' && wifi) return send(200, await wifi.status()), true;
|
|
272
|
+
if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
|
|
266
273
|
if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
|
|
267
274
|
if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
|
|
268
275
|
/* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
|
|
@@ -390,6 +397,9 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
390
397
|
if (pathname === '/api/machines/mount' && machinesMove) return send(200, await machinesMove.mount(String(body.path ?? ''))), true;
|
|
391
398
|
if (pathname === '/api/machines/prepare' && machinesMove) return send(200, await machinesMove.prepare(String(body.path ?? ''), body.typed)), true;
|
|
392
399
|
if (pathname === '/api/machines/forget-old' && machinesMove) return send(200, await machinesMove.forgetOld()), true;
|
|
400
|
+
/* The password goes on to the host program and nowhere else: not in an answer, not in What happened. */
|
|
401
|
+
if (pathname === '/api/wifi/join' && wifi) return send(202, await wifi.join(body.ssid, body.password ?? '')), true;
|
|
402
|
+
if (pathname === '/api/wifi/forget' && wifi) return send(200, await wifi.forget(body.ssid)), true;
|
|
393
403
|
if (pathname === '/api/operators' && team) return send(201, await team.add(body.email)), true;
|
|
394
404
|
const op = /^\/api\/operators\/([^/]{3,200})\/(password|disable|enable|remove)$/.exec(pathname);
|
|
395
405
|
if (op && team) {
|
|
@@ -540,8 +550,12 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
540
550
|
await health.check(conversation, { asked: true }); return send(200, health.of(conversation)), true;
|
|
541
551
|
}
|
|
542
552
|
if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
|
|
543
|
-
|
|
553
|
+
const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
|
|
554
|
+
/* Asleep, nothing was started: the choice is only kept, for its wake. */
|
|
555
|
+
return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
|
|
544
556
|
}
|
|
557
|
+
const later = /^\/api\/conversations\/([^/]+)\/machine\/cancel$/.exec(pathname);
|
|
558
|
+
if (later) return send(200, conversations.cancelResize(decodeURIComponent(later[1]))), true;
|
|
545
559
|
const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
|
|
546
560
|
if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
|
|
547
561
|
const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
|
package/server/conversations.mjs
CHANGED
|
@@ -62,6 +62,12 @@ export class Refusal extends Error {
|
|
|
62
62
|
the tool starts -- a new disk holds no session to take up. */
|
|
63
63
|
const buildProgress = (since) => ({ kind: 'build', steps: ['starting', 'preparing', 'installing', 'folders', 'tool'], at: 0, since, stepSince: since });
|
|
64
64
|
|
|
65
|
+
/* What a machine has, in words: what its record says, else what was asked (`asked`). */
|
|
66
|
+
const sizeSaid = (c, asked = {}) => {
|
|
67
|
+
const cpus = c?.cpus ?? asked.cpus;
|
|
68
|
+
return `${c?.memoryMb ?? asked.memoryMb} MB of memory, ${cpus} core${cpus > 1 ? 's' : ''}, ${c?.diskGb ?? asked.diskGb} GB of disk`;
|
|
69
|
+
};
|
|
70
|
+
|
|
65
71
|
const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
|
|
66
72
|
|
|
67
73
|
export class Conversations {
|
|
@@ -92,6 +98,9 @@ export class Conversations {
|
|
|
92
98
|
them (#calm). Stopping a machine while the VM manager mounts a folder
|
|
93
99
|
in it was seen to hang the VM manager itself, for every machine. */
|
|
94
100
|
#mounting = new Map();
|
|
101
|
+
/* A size kept for its wake being applied, by name: a second opening waits
|
|
102
|
+
for it, and a restart, a resize or a move is refused meanwhile. */
|
|
103
|
+
#resizing = new Map();
|
|
95
104
|
/* Set by the server: told when its machine was restarted or built again
|
|
96
105
|
by this server, in words for its chat, and whether the tool runs again
|
|
97
106
|
(its chat says it, and the tool is told to read it again: talk.mjs). */
|
|
@@ -389,6 +398,8 @@ export class Conversations {
|
|
|
389
398
|
/* Opening is the explicit gesture that ends a sleep. */
|
|
390
399
|
if (c.asleep) this.#store.patch(name, { asleep: false });
|
|
391
400
|
this.#watching.set(name, (this.#watching.get(name) ?? 0) + 1);
|
|
401
|
+
/* Another screen is applying the size kept for its wake: this one opens once it is over. */
|
|
402
|
+
await this.#resizing.get(name)?.catch(() => {});
|
|
392
403
|
/* A start that fails here ends what the page was shown of it: the
|
|
393
404
|
page then opens the terminal itself, and says what went wrong. */
|
|
394
405
|
try { return await this.#opening(name, c, say); } catch (error) { this.#end(name); throw error; }
|
|
@@ -415,10 +426,20 @@ export class Conversations {
|
|
|
415
426
|
if (state === 'Starting' || state === 'Restarting') { this.left(name); throw new Refusal(504, 'Its machine is still starting.', { retry: true }); }
|
|
416
427
|
this.#reach(name, 'answering');
|
|
417
428
|
}
|
|
429
|
+
/* A NEW SIZE WAS CHOSEN WHILE IT SLEPT: applied now, before anything
|
|
430
|
+
else; it runs after, with the new size or, failing that, the old. */
|
|
431
|
+
let resized = false;
|
|
432
|
+
if (this.#store.get(name)?.sizeAtWake) {
|
|
433
|
+
const applying = this.#wakeResized(name, c, tool, state, tell);
|
|
434
|
+
this.#resizing.set(name, applying);
|
|
435
|
+
try { state = await applying; } catch (error) { this.left(name); throw error; }
|
|
436
|
+
finally { this.#resizing.delete(name); }
|
|
437
|
+
resized = true;
|
|
438
|
+
}
|
|
418
439
|
const stopped = state !== 'Running';
|
|
419
440
|
/* Asleep, its memory was kept: the tool may still be there, as it was. */
|
|
420
441
|
const asleep = state === 'Suspended';
|
|
421
|
-
let woke = this.#fresh.delete(name) || stopped;
|
|
442
|
+
let woke = this.#fresh.delete(name) || stopped || resized;
|
|
422
443
|
if (stopped) {
|
|
423
444
|
try { await this.room({ kind: 'start', name, memoryMb: c.memoryMb }); } catch (error) { this.left(name); throw error; }
|
|
424
445
|
waking(asleep ? 'waking' : 'starting');
|
|
@@ -474,6 +495,63 @@ export class Conversations {
|
|
|
474
495
|
return argv;
|
|
475
496
|
}
|
|
476
497
|
|
|
498
|
+
/* THE SIZE KEPT FOR ITS WAKE, APPLIED as it wakes. Taken out of its
|
|
499
|
+
* record first: it is tried once, and its outcome said either way.
|
|
500
|
+
* 1. this server's reserve, looked at again (what is free may have
|
|
501
|
+
* changed since it was chosen); refused, it wakes as it was;
|
|
502
|
+
* 2. asleep, it is woken first: a machine asleep cannot be stopped
|
|
503
|
+
* cleanly, and a stop by force would lose what its memory holds;
|
|
504
|
+
* 3. stopped cleanly (by force if that hangs), set, started (#cycle);
|
|
505
|
+
* 4. not running after that, what was set is put back where it can be
|
|
506
|
+
* (a disk never shrinks) and it is started again: never left stopped.
|
|
507
|
+
* Said in Settings (`restarted`) and in its chat. The tool is started by
|
|
508
|
+
* the opening, which takes up its last session, as after any restart.
|
|
509
|
+
* Resolves with the state of its machine. */
|
|
510
|
+
async #wakeResized(name, c, tool, state, tell) {
|
|
511
|
+
const want = this.#store.get(name).sizeAtWake;
|
|
512
|
+
this.#store.patch(name, { sizeAtWake: undefined, restarted: undefined });
|
|
513
|
+
const had = { memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB };
|
|
514
|
+
try { await this.#roomAtWake(name, had, want, state, true); } catch (error) {
|
|
515
|
+
const why = error instanceof Refusal ? error.message : 'the room of this server could not be looked at.';
|
|
516
|
+
this.#store.patch(name, { restarted: `Not changed as it woke: ${why} It kept ${sizeSaid(had)}.` });
|
|
517
|
+
try { this.renewed(name, `Its machine was not changed as it woke: ${why} It kept ${sizeSaid(had)}.`, false); } catch { /* told, nothing more */ }
|
|
518
|
+
return state;
|
|
519
|
+
}
|
|
520
|
+
this.#begin(name, 'wake', [...(state === 'Suspended' ? ['waking'] : []), ...(state === 'Stopped' ? [] : ['stopping']), 'setting', 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)]);
|
|
521
|
+
tell('Changing its machine as it wakes...');
|
|
522
|
+
if (state === 'Suspended') await this.#watched(name, 'start', this.#vms.start(name)).catch(() => {});
|
|
523
|
+
this.#reach(name, 'stopping'); tell();
|
|
524
|
+
const set = [];
|
|
525
|
+
let failure = await this.#cycle(name, c, this.#setter(name, c, want, (what) => set.push(what)), true);
|
|
526
|
+
let now = await this.#vms.state(name).catch(() => undefined);
|
|
527
|
+
if (now !== 'Running') {
|
|
528
|
+
if (set.includes('memory')) await this.#vms.setMemory(name, had.memoryMb).catch(() => {});
|
|
529
|
+
if (set.includes('cpus')) await this.#vms.setCpus(name, had.cpus).catch(() => {});
|
|
530
|
+
const again = await this.#watched(name, 'start', this.#vms.start(name)).catch(() => ({ code: 1 }));
|
|
531
|
+
now = await this.#vms.state(name).catch(() => undefined);
|
|
532
|
+
if (again.code === 0 || now === 'Running') { this.#fresh.add(name); this.#mountAgain.add(name); }
|
|
533
|
+
failure ??= 'the machine did not start.';
|
|
534
|
+
}
|
|
535
|
+
await this.reconcile(name);
|
|
536
|
+
const said = sizeSaid(this.#store.get(name), had);
|
|
537
|
+
const running = now === 'Running';
|
|
538
|
+
this.#store.patch(name, { restarted: failure ? `Not changed as it woke: ${failure} It has ${said}.` : `Changed as it woke: it now has ${said}.` });
|
|
539
|
+
try { this.renewed(name, failure ? `Its machine was not changed as it woke: ${failure} It has ${said}.` : `Its machine was restarted as it woke, with ${said}: the tool started again.`, running); } catch { /* told, nothing more */ }
|
|
540
|
+
if (!running) throw new Refusal(502, `The machine did not wake: ${failure}`);
|
|
541
|
+
return now;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/* This server's reserve, for a size kept for its wake: running, it holds
|
|
545
|
+
its memory already; otherwise it takes all of it as it starts -- and
|
|
546
|
+
its old size first, when it is woken to be stopped (`woken`). */
|
|
547
|
+
async #roomAtWake(name, had, want, state, woken) {
|
|
548
|
+
const growth = Math.max(0, want.diskGb - had.diskGb) * 1024;
|
|
549
|
+
await this.room(state === 'Running'
|
|
550
|
+
? { kind: 'grow', name, memoryMb: Math.max(0, want.memoryMb - had.memoryMb), diskMb: growth }
|
|
551
|
+
: { kind: 'start', name, memoryMb: woken && state === 'Suspended' ? Math.max(want.memoryMb, had.memoryMb) : want.memoryMb });
|
|
552
|
+
if (state !== 'Running' && growth > 0) await this.room({ kind: 'grow', name, memoryMb: 0, diskMb: growth });
|
|
553
|
+
}
|
|
554
|
+
|
|
477
555
|
/* WHAT STARTS THE TOOL. Its last session is taken up (`resume` in
|
|
478
556
|
config/tools.json: "claude --continue"...) unless the owner chose to
|
|
479
557
|
start fresh -- but never at its very first start on a disk: there is no
|
|
@@ -681,24 +759,31 @@ export class Conversations {
|
|
|
681
759
|
terminal come back as after any start (`ready`); its folders are
|
|
682
760
|
looked at after (health.mjs). The answer comes at once; `restarted`
|
|
683
761
|
says how it ended. A machine asleep is restarted too: that is what
|
|
684
|
-
was asked. */
|
|
762
|
+
was asked -- and the size kept for its wake is applied on the way. */
|
|
685
763
|
async restart(name) {
|
|
686
764
|
const c = this.#busyCheck(name);
|
|
765
|
+
const want = c.sizeAtWake;
|
|
766
|
+
const had = { memoryMb: c.memoryMb, cpus: c.cpus ?? 1, diskGb: c.diskGb ?? DISK_GB };
|
|
687
767
|
const release = this.#claim(name, 'restarting', 'Looking at the machine');
|
|
688
768
|
let state;
|
|
689
769
|
try {
|
|
690
770
|
state = await this.#vms.state(name);
|
|
691
771
|
if (state === undefined) throw new Refusal(410, 'The machine of this conversation no longer exists.');
|
|
692
772
|
/* A machine that does not run is started: it takes its memory again. */
|
|
693
|
-
if (
|
|
773
|
+
if (want) await this.#roomAtWake(name, had, want, state, false);
|
|
774
|
+
else if (state !== 'Running') await this.room({ kind: 'start', name, memoryMb: c.memoryMb });
|
|
694
775
|
} catch (error) { release(); throw error; }
|
|
695
776
|
this.#cancelStop(name);
|
|
696
777
|
const since = new Date().toISOString();
|
|
697
|
-
this.#store.patch(name, { phase: 'restarting', restartingSince: since, step: 'Stopping the machine', restarted: undefined });
|
|
778
|
+
this.#store.patch(name, { phase: 'restarting', restartingSince: since, step: 'Stopping the machine', restarted: undefined, sizeAtWake: undefined });
|
|
698
779
|
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
699
|
-
this.#begin(name, 'restart', [...(state === 'Stopped' ? [] : ['stopping']), 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)], since);
|
|
700
|
-
this.restarted = this.#cycle(name, c, async () => undefined, true)
|
|
701
|
-
|
|
780
|
+
this.#begin(name, 'restart', [...(state === 'Stopped' ? [] : ['stopping']), ...(want ? ['setting'] : []), 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)], since);
|
|
781
|
+
this.restarted = this.#cycle(name, c, want ? this.#setter(name, c, want) : async () => undefined, true).then(async (failure) => {
|
|
782
|
+
if (!want) return this.#settle(name, failure ? `Not restarted: ${failure}` : 'Restarted.', failure ? `Its machine was not restarted: ${failure}` : 'Its machine was restarted: the tool started again.', Boolean(failure));
|
|
783
|
+
await this.reconcile(name);
|
|
784
|
+
const said = sizeSaid(this.#store.get(name), had);
|
|
785
|
+
return this.#settle(name, failure ? `Not changed: ${failure} It has ${said}.` : `Restarted: it now has ${said}.`, failure ? `Its machine was not changed: ${failure} It has ${said}.` : `Its machine was restarted with ${said}: the tool started again.`, Boolean(failure));
|
|
786
|
+
});
|
|
702
787
|
return this.#store.get(name);
|
|
703
788
|
}
|
|
704
789
|
|
|
@@ -706,24 +791,13 @@ export class Conversations {
|
|
|
706
791
|
manager takes it only from a stopped machine: a running one is
|
|
707
792
|
stopped (cleanly first), set, and started again -- its work folder,
|
|
708
793
|
its folders and its branches are not touched. A disk only grows.
|
|
709
|
-
What is recorded afterwards is what the VM manager says it has.
|
|
710
|
-
|
|
794
|
+
What is recorded afterwards is what the VM manager says it has.
|
|
795
|
+
Asleep, it is not woken for it: the choice is kept for its wake (#later). */
|
|
796
|
+
async resize(name, asked = {}) {
|
|
711
797
|
const c = this.#busyCheck(name);
|
|
712
798
|
const tool = this.#tools.find((t) => t.id === c.tool);
|
|
713
|
-
const memory
|
|
714
|
-
|
|
715
|
-
const cpusNow = c.cpus ?? 1;
|
|
716
|
-
const cpus = cpusAsked === undefined || cpusAsked === null || cpusAsked === '' ? cpusNow : Number(cpusAsked);
|
|
717
|
-
const hostCpus = availableParallelism();
|
|
718
|
-
if (cpus !== cpusNow && (!Number.isInteger(cpus) || cpus < 1 || cpus > hostCpus)) throw new Refusal(400, `Cores: 1 to ${hostCpus}, those of this server, which its machines share.`);
|
|
719
|
-
const least = tool?.memoryMb ?? 512;
|
|
720
|
-
/* Memory is checked only when it changes: a machine made when its tool
|
|
721
|
-
needed less keeps what it has, and its disk can still grow. */
|
|
722
|
-
if (memory !== c.memoryMb && (!Number.isInteger(memory) || memory < least || memory > MEMORY_MAX_MB)) throw new Refusal(400, `Memory is between ${least} MB (what ${tool?.label ?? 'its tool'} needs) and ${MEMORY_MAX_MB} MB.`);
|
|
723
|
-
if (!Number.isInteger(disk) || disk > DISK_MAX_GB) throw new Refusal(400, `A disk is at most ${DISK_MAX_GB} GB.`);
|
|
724
|
-
if (disk < (c.diskGb ?? DISK_GB)) throw new Refusal(400, `A disk can only grow: it has ${c.diskGb ?? DISK_GB} GB.`);
|
|
725
|
-
if (memory === c.memoryMb && disk === (c.diskGb ?? DISK_GB) && cpus === cpusNow) throw new Refusal(409, 'Nothing to change: it already has this.');
|
|
726
|
-
if (c.asleep === true) throw new Refusal(409, 'It is asleep: wake it first, then change its memory, cores or disk.');
|
|
799
|
+
const { memory, disk, cpus } = this.#sizeAsked(c, tool, asked);
|
|
800
|
+
if (c.asleep === true) return this.#later(name, c, { memoryMb: memory, cpus, diskGb: disk });
|
|
727
801
|
const release = this.#claim(name, 'restarting', 'Looking at the machine');
|
|
728
802
|
let state;
|
|
729
803
|
try {
|
|
@@ -737,31 +811,84 @@ export class Conversations {
|
|
|
737
811
|
this.#store.patch(name, { phase: 'restarting', restartingSince: since, step: state === 'Running' ? 'Stopping the machine' : 'Setting its memory and disk', restarted: undefined });
|
|
738
812
|
/* Started again only when it ran: then the page is told each step to its tool. */
|
|
739
813
|
if (state === 'Running') this.#begin(name, 'resize', ['stopping', 'setting', 'starting', 'answering', 'folders', 'tool', ...this.#resumeStep(c, tool)], since);
|
|
740
|
-
const set =
|
|
814
|
+
const set = this.#setter(name, c, { memoryMb: memory, cpus, diskGb: disk });
|
|
815
|
+
this.resized = this.#cycle(name, c, set, state === 'Running').then(async (failure) => {
|
|
816
|
+
await this.reconcile(name);
|
|
817
|
+
const said = sizeSaid(this.#store.get(name), { memoryMb: memory, cpus, diskGb: disk });
|
|
818
|
+
await this.#settle(name, failure ? `Not changed: ${failure} It has ${said}.` : `It now has ${said}.`, failure ? `Its machine was not changed: ${failure} It has ${said}.` : `Its machine was restarted with ${said}: the tool started again.`, Boolean(failure));
|
|
819
|
+
});
|
|
820
|
+
return this.#store.get(name);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/* WHAT A NEW SIZE ASKS, checked the same whether it is applied now or at
|
|
824
|
+
its wake. Refused, with why, before anything is touched. */
|
|
825
|
+
#sizeAsked(c, tool, { memoryMb, diskGb, cpus: cpusAsked } = {}) {
|
|
826
|
+
const memory = memoryMb === undefined || memoryMb === null || memoryMb === '' ? c.memoryMb : Number(memoryMb);
|
|
827
|
+
const disk = diskGb === undefined || diskGb === null || diskGb === '' ? c.diskGb ?? DISK_GB : Number(diskGb);
|
|
828
|
+
const cpusNow = c.cpus ?? 1;
|
|
829
|
+
const cpus = cpusAsked === undefined || cpusAsked === null || cpusAsked === '' ? cpusNow : Number(cpusAsked);
|
|
830
|
+
const hostCpus = availableParallelism();
|
|
831
|
+
if (cpus !== cpusNow && (!Number.isInteger(cpus) || cpus < 1 || cpus > hostCpus)) throw new Refusal(400, `Cores: 1 to ${hostCpus}, those of this server, which its machines share.`);
|
|
832
|
+
const least = tool?.memoryMb ?? 512;
|
|
833
|
+
/* Memory is checked only when it changes: a machine made when its tool
|
|
834
|
+
needed less keeps what it has, and its disk can still grow. */
|
|
835
|
+
if (memory !== c.memoryMb && (!Number.isInteger(memory) || memory < least || memory > MEMORY_MAX_MB)) throw new Refusal(400, `Memory is between ${least} MB (what ${tool?.label ?? 'its tool'} needs) and ${MEMORY_MAX_MB} MB.`);
|
|
836
|
+
if (!Number.isInteger(disk) || disk > DISK_MAX_GB) throw new Refusal(400, `A disk is at most ${DISK_MAX_GB} GB.`);
|
|
837
|
+
if (disk < (c.diskGb ?? DISK_GB)) throw new Refusal(400, `A disk can only grow: it has ${c.diskGb ?? DISK_GB} GB.`);
|
|
838
|
+
if (memory === c.memoryMb && disk === (c.diskGb ?? DISK_GB) && cpus === cpusNow) throw new Refusal(409, 'Nothing to change: it already has this.');
|
|
839
|
+
return { memory, disk, cpus };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/* What sets the sizes `want` on its stopped machine, beside what it has
|
|
843
|
+
(`c`): only what differs. Returns what went wrong, in words, or
|
|
844
|
+
undefined; `done` is told each one that was set. */
|
|
845
|
+
#setter(name, c, want, done = () => {}) {
|
|
846
|
+
return async () => {
|
|
741
847
|
this.#reach(name, 'setting');
|
|
742
|
-
if (
|
|
743
|
-
this.#store.patch(name, { step: `Setting its memory to ${
|
|
744
|
-
const r = await this.#vms.setMemory(name,
|
|
848
|
+
if (want.memoryMb !== c.memoryMb) {
|
|
849
|
+
this.#store.patch(name, { step: `Setting its memory to ${want.memoryMb} MB` });
|
|
850
|
+
const r = await this.#vms.setMemory(name, want.memoryMb);
|
|
745
851
|
if (r.code !== 0) return `its memory could not be set (${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}).`;
|
|
852
|
+
done('memory');
|
|
746
853
|
}
|
|
747
|
-
if (cpus !==
|
|
748
|
-
this.#store.patch(name, { step: `Setting its cores to ${cpus}` });
|
|
749
|
-
const r = await this.#vms.setCpus(name, cpus);
|
|
854
|
+
if (want.cpus !== (c.cpus ?? 1)) {
|
|
855
|
+
this.#store.patch(name, { step: `Setting its cores to ${want.cpus}` });
|
|
856
|
+
const r = await this.#vms.setCpus(name, want.cpus);
|
|
750
857
|
if (r.code !== 0) return `its cores could not be set (${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}).`;
|
|
858
|
+
done('cpus');
|
|
751
859
|
}
|
|
752
|
-
if (
|
|
753
|
-
this.#store.patch(name, { step: `Growing its disk to ${
|
|
754
|
-
const r = await this.#vms.setDisk(name,
|
|
860
|
+
if (want.diskGb !== (c.diskGb ?? DISK_GB)) {
|
|
861
|
+
this.#store.patch(name, { step: `Growing its disk to ${want.diskGb} GB` });
|
|
862
|
+
const r = await this.#vms.setDisk(name, want.diskGb);
|
|
755
863
|
if (r.code !== 0) return `its disk could not be grown (${firstLine(r.stderr) || firstLine(r.stdout) || `exit ${r.code}`}).`;
|
|
864
|
+
done('disk');
|
|
756
865
|
}
|
|
757
866
|
return undefined;
|
|
758
867
|
};
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/* A NEW SIZE CHOSEN WHILE IT SLEEPS. A machine asleep cannot be set (the
|
|
871
|
+
VM manager sets only a stopped one), and stopping it would throw away
|
|
872
|
+
what its memory holds: the choice is checked as a resize would be --
|
|
873
|
+
its bounds, and this server's reserve for what it grows by -- then
|
|
874
|
+
kept in its record, which outlives a restart of this server, and
|
|
875
|
+
applied at its wake (#wakeResized). A second choice replaces the first. */
|
|
876
|
+
async #later(name, c, want) {
|
|
877
|
+
await this.room({ kind: 'grow', name, memoryMb: Math.max(0, want.memoryMb - c.memoryMb), diskMb: Math.max(0, want.diskGb - (c.diskGb ?? DISK_GB)) * 1024 });
|
|
878
|
+
/* Woken while the room was looked at: it is no longer for later. */
|
|
879
|
+
const now = this.#store.get(name);
|
|
880
|
+
if (!now) throw new Refusal(404, 'No such conversation.');
|
|
881
|
+
if (now.asleep !== true) throw new Refusal(409, 'It has just woken: choose its size again.');
|
|
882
|
+
this.#store.patch(name, { sizeAtWake: { ...want, at: new Date().toISOString() }, restarted: undefined });
|
|
883
|
+
return this.#store.get(name);
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/* The size kept for its wake, given up: it wakes as it is. */
|
|
887
|
+
cancelResize(name) {
|
|
888
|
+
const c = this.#store.get(name);
|
|
889
|
+
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
890
|
+
if (!c.sizeAtWake) throw new Refusal(409, 'No new size is waiting for its wake.');
|
|
891
|
+
this.#store.patch(name, { sizeAtWake: undefined });
|
|
765
892
|
return this.#store.get(name);
|
|
766
893
|
}
|
|
767
894
|
|
|
@@ -796,6 +923,7 @@ export class Conversations {
|
|
|
796
923
|
const c = this.#store.get(name);
|
|
797
924
|
if (!c) throw new Refusal(404, 'No such conversation.');
|
|
798
925
|
if (c.phase !== 'ready') throw new Refusal(409, c.phase === 'restarting' ? 'Its machine is being restarted already.' : c.phase === 'moving' ? 'It is moving its work folder.' : 'This conversation is not ready.');
|
|
926
|
+
if (this.#resizing.has(name)) throw new Refusal(409, 'Its machine is being given its new size as it wakes.', { retry: true });
|
|
799
927
|
return c;
|
|
800
928
|
}
|
|
801
929
|
|
|
@@ -1035,6 +1163,9 @@ export class Conversations {
|
|
|
1035
1163
|
return failed;
|
|
1036
1164
|
}
|
|
1037
1165
|
|
|
1166
|
+
/* Whether its machine is being given the size kept for its wake just now (it stops and starts meanwhile). */
|
|
1167
|
+
resizing(name) { return this.#resizing.has(name); }
|
|
1168
|
+
|
|
1038
1169
|
/* The conversations whose machine should be running: built, not asleep. */
|
|
1039
1170
|
awake() { return this.#store.all().filter((c) => c.phase === 'ready' && c.asleep !== true).map((c) => c.name); }
|
|
1040
1171
|
|
package/server/events.mjs
CHANGED
|
@@ -29,7 +29,8 @@ const SAID = [
|
|
|
29
29
|
[/^\/api\/conversations\/([^/]+)\/archive$/, 'conversation', (m) => `Conversation ${m[1]} archived`],
|
|
30
30
|
[/^\/api\/conversations\/([^/]+)\/title$/, 'conversation', (m, b) => `Conversation ${m[1]} renamed "${clip(b.title)}"`],
|
|
31
31
|
[/^\/api\/conversations\/([^/]+)\/restart$/, 'machine', (m) => `Machine of ${m[1]} restarted`],
|
|
32
|
-
[/^\/api\/conversations\/([^/]+)\/machine$/, 'machine', (m, b) => `Machine of ${m[1]} resized${b.memoryMb ? `: ${b.memoryMb} MB of memory` : ''}${b.diskGb ? `, ${b.diskGb} GB of disk` : ''}${b.cpus ? `, ${b.cpus} core${b.cpus > 1 ? 's' : ''}` : ''}`],
|
|
32
|
+
[/^\/api\/conversations\/([^/]+)\/machine$/, 'machine', (m, b, a) => `Machine of ${m[1]} ${a?.sizeAtWake && a.phase === 'ready' ? 'to be resized as it wakes' : 'resized'}${b.memoryMb ? `: ${b.memoryMb} MB of memory` : ''}${b.diskGb ? `, ${b.diskGb} GB of disk` : ''}${b.cpus ? `, ${b.cpus} core${b.cpus > 1 ? 's' : ''}` : ''}`],
|
|
33
|
+
[/^\/api\/conversations\/([^/]+)\/machine\/cancel$/, 'machine', (m) => `Machine of ${m[1]}: the size kept for its wake given up`],
|
|
33
34
|
[/^\/api\/conversations\/([^/]+)\/sleep$/, 'machine', (m) => `Machine of ${m[1]} put to sleep`],
|
|
34
35
|
[/^\/api\/conversations\/([^/]+)\/rebuild$/, 'machine', (m) => `Machine of ${m[1]} built again`],
|
|
35
36
|
[/^\/api\/conversations\/([^/]+)\/network$/, 'machine', (m, b) => `${m[1]} ${b.online ? 'put online' : 'put offline'}`],
|
|
@@ -54,6 +55,9 @@ const SAID = [
|
|
|
54
55
|
[/^\/api\/machines\/grow$/, 'server', (m, b, a) => `${clip(b.mount, 60)} grown with the room set aside on its disk${a?.sizeMb ? `: now ${Math.round(a.sizeMb / 1024)} GB` : ''}`],
|
|
55
56
|
[/^\/api\/machines\/mount$/, 'server', (m, b) => `Disk ${clip(b.path, 40)} mounted`],
|
|
56
57
|
[/^\/api\/machines\/forget-old$/, 'server', () => 'The old copy of the machines removed'],
|
|
58
|
+
/* Its name only: the password of a network is never said. */
|
|
59
|
+
[/^\/api\/wifi\/join$/, 'server', (m, b) => `Wi-Fi: joining "${clip(b.ssid, 40)}" asked`],
|
|
60
|
+
[/^\/api\/wifi\/forget$/, 'server', (m, b) => `Wi-Fi: "${clip(b.ssid, 40)}" forgotten`],
|
|
57
61
|
[/^\/api\/instance$/, 'server', (m, b) => (String(b.name ?? '').trim() ? `This Clavarium named "${clip(b.name, 40)}"` : 'This Clavarium given back the name drawn from its address')],
|
|
58
62
|
[/^\/api\/operators$/, 'sign-in', (m, b) => `Administrator ${clip(b.email, 80)} added`],
|
|
59
63
|
[/^\/api\/operators\/([^/]+)\/(password|disable|enable|remove)$/, 'sign-in', (m) => `Administrator ${clip(decodeURIComponent(m[1]), 80)}: ${{ password: 'new password', disable: 'disabled', enable: 'enabled', remove: 'removed' }[m[2]]}`],
|
package/server/health.mjs
CHANGED
|
@@ -163,8 +163,9 @@ export class Health {
|
|
|
163
163
|
const c = this.#conversations.get(name);
|
|
164
164
|
if (!c) return null;
|
|
165
165
|
const at = new Date().toISOString();
|
|
166
|
-
/* A machine being built, moved or restarted
|
|
167
|
-
|
|
166
|
+
/* A machine being built, moved or restarted -- or given its new size as
|
|
167
|
+
it wakes (conversations.mjs) -- is somebody else's business just now. */
|
|
168
|
+
if (c.phase !== 'ready' || this.#conversations.resizing?.(name)) return this.#keep(name, { at, state: c.phase === 'restarting' || c.phase === 'ready' ? 'Restarting' : 'Starting', busy: true });
|
|
168
169
|
const state = await this.#vms.state(name).catch(() => 'Unknown');
|
|
169
170
|
if (state !== 'Running') return this.#keep(name, { at, state });
|
|
170
171
|
const paths = this.#resources ? this.#resources.expected(name, c.work === 'kept') : (c.work === 'kept' ? ['/work'] : []);
|