sanoma 0.6.0 → 0.7.1

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/postgres.js CHANGED
@@ -1,10 +1,27 @@
1
- import { execFile } from "node:child_process";
2
- import { isLoopback } from "@sanoma-ai/workflows/shared";
1
+ import { execFile, spawn, spawnSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync, } from "node:fs";
4
+ import { createServer } from "node:net";
5
+ import { homedir } from "node:os";
6
+ import { basename, dirname, join, relative } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { promisify } from "node:util";
3
9
  import { Client } from "pg";
10
+ import { UsageError } from "./config.js";
11
+ import { postgresBin } from "./postgres-bin.js";
12
+ /**
13
+ * The URL `sanoma` (through `.env`) and the runtime named by default before the launcher started
14
+ * the company's own Postgres: the Postgres in Docker that earlier versions started there.
15
+ */
16
+ export const OLD_DEFAULT_URL = "postgresql://postgres:dbos@localhost:5433/sanoma";
17
+ /** The `stop` of a database this call did not start. */
18
+ const noStop = async () => { };
4
19
  /** How long one probe waits for a connection. */
5
20
  const PROBE_TIMEOUT_MS = 2000;
6
- /** How long Postgres in a container has to answer. */
21
+ /** How long `pg_ctl` waits for Postgres to accept connections once started. */
7
22
  const WAIT_MS = 60_000;
23
+ /** How long a launcher waits for another to make and start the cluster: an extraction, `initdb` and a start. */
24
+ const LOCK_WAIT_MS = 5 * 60_000;
8
25
  /** The URL with its password hidden, for a message. */
9
26
  export function masked(databaseUrl) {
10
27
  const url = new URL(databaseUrl);
@@ -12,97 +29,316 @@ export function masked(databaseUrl) {
12
29
  url.password = "***";
13
30
  return url.toString();
14
31
  }
15
- /** `docker <args>`, its stdout trimmed: the one place the bin runs Docker. */
16
- const docker = (args) => new Promise((resolve, reject) => execFile("docker", args, (err, stdout) => (err ? reject(err) : resolve(String(stdout).trim()))));
17
32
  /**
18
- * Makes sure Postgres answers at `databaseUrl`, starting it in Docker when nothing does and the
19
- * host is this machine (`isLoopback`). It probes the server (`SELECT 1` on the `postgres`
20
- * database, with the URL's user and password); an answer is enough. Nothing answering at a
21
- * loopback host means Docker: the container `sanoma-<appName>-postgres` is started when it
22
- * exists and stopped, created from `postgres:17` on the URL's port, user, password and database
23
- * when it does not, and left as it is when it runs already; then the probe is repeated until it
24
- * answers. A container is never removed. Throws when the server answers with an error (a wrong
25
- * password), when nothing answers at another host, when Docker is not installed, and when the
26
- * container does not answer within a minute.
33
+ * Makes sure Postgres answers. A URL named (`databaseUrl`) is probed (`SELECT 1` on the `postgres`
34
+ * database, as its user) and used as it is, or the call throws, saying what to do. With none, the
35
+ * company's own: a PostgreSQL 18 cluster in `clusterDir(root)` (`password`, mode 0600, `server.log`
36
+ * and `data/`), on 127.0.0.1 alone at a port of its own, as `postgres` with the password. A
37
+ * cluster another launcher runs is used as it is (`answered`); else, unless `start` is false, it
38
+ * is started (`started`), made first with `initdb` when there is no `data/` (`created`), under the
39
+ * `starting` lock so two launchers never start it twice. Its port is rewritten when another
40
+ * process took it. `pg_ctl` runs in a process group of its own, so a terminal's ctrl-c reaches
41
+ * the launcher alone, which stops it last (`stop`).
27
42
  */
28
- export async function ensurePostgres(databaseUrl, { appName, log = () => { } }) {
29
- const url = new URL(databaseUrl);
30
- if (await answers(url, PROBE_TIMEOUT_MS)) {
31
- log(`Postgres answers at ${masked(databaseUrl)}`);
32
- return { how: "answered" };
43
+ export async function ensurePostgres(databaseUrl, { root, log = () => { }, start = true, bin }) {
44
+ if (databaseUrl !== undefined) {
45
+ // A deployment's worker or app: its database's own to answer, as the runtime retries.
46
+ if (!start)
47
+ return { how: "answered", databaseUrl, stop: noStop };
48
+ if (await answers(databaseUrl)) {
49
+ log(`Postgres answers at ${masked(databaseUrl)}`);
50
+ return { how: "answered", databaseUrl, stop: noStop };
51
+ }
52
+ throw new Error(`nothing answers at ${masked(databaseUrl)}; ${databaseUrl === OLD_DEFAULT_URL
53
+ ? "earlier versions started this in Docker: start that container to keep its records, " +
54
+ "or remove SANOMA_DATABASE_URL from .env to use the embedded Postgres"
55
+ : "start Postgres there, or remove SANOMA_DATABASE_URL to use the embedded Postgres"}`);
33
56
  }
34
- if (!isLoopback(url.hostname)) {
35
- throw new Error(`nothing answers at ${masked(databaseUrl)}; start Postgres or set SANOMA_DATABASE_URL`);
57
+ const cluster = paths(await clusterDir(root));
58
+ const found = await running(cluster);
59
+ if (found !== undefined)
60
+ return answered(cluster, found, log);
61
+ if (!start) {
62
+ throw new UsageError(`no Postgres runs in ${cluster.dir}: set SANOMA_DATABASE_URL, or run \`sanoma\``);
36
63
  }
37
- if (!url.password) {
38
- throw new Error(`nothing answers at ${masked(databaseUrl)}, and the URL has no password to create Postgres with`);
64
+ if (process.getuid?.() === 0) {
65
+ throw new Error("PostgreSQL refuses to run as root, so sanoma cannot start the company's own: " +
66
+ "set SANOMA_DATABASE_URL to a Postgres of your own, or run sanoma as another user");
39
67
  }
40
- const container = `sanoma-${slug(appName)}-postgres`;
41
- let state;
68
+ mkdirSync(cluster.dir, { recursive: true });
69
+ // Nothing in it is the repo's, the records least of all.
70
+ if (!existsSync(join(cluster.dir, ".gitignore")))
71
+ writeFileSync(join(cluster.dir, ".gitignore"), "*\n");
72
+ if (cluster.dir.startsWith(join(homedir(), "Library", "Mobile Documents"))) {
73
+ log(`warning: ${cluster.dir} is in iCloud Drive, which may sync the records while Postgres writes them`);
74
+ }
75
+ return locked(cluster, async () => {
76
+ // Started meanwhile, by the launcher that held the lock.
77
+ const meanwhile = await running(cluster);
78
+ if (meanwhile !== undefined)
79
+ return answered(cluster, meanwhile, log);
80
+ const pg = bin ?? postgresBin();
81
+ const how = existsSync(cluster.data) ? "started" : "created";
82
+ if (how === "created")
83
+ await initdb(pg, cluster);
84
+ else if (!existsSync(cluster.password)) {
85
+ throw new Error(`${cluster.password} is missing: it is the password of the records in ${cluster.data}`);
86
+ }
87
+ else
88
+ clearStale(cluster);
89
+ const port = await portOf(cluster);
90
+ const url = urlOf(cluster, port);
91
+ log(`starting Postgres in ${cluster.dir} on port ${port}`);
92
+ await pgCtl(pg, cluster, ["start", "-D", cluster.data, "-l", cluster.log, "-w", "-t", String(WAIT_MS / 1000)]);
93
+ // `pg_ctl -w` waited for it to accept connections.
94
+ if (!(await answers(url)))
95
+ throw new Error(`Postgres in ${cluster.dir} did not answer; see ${cluster.log}`);
96
+ if (how === "created") {
97
+ log(`created Postgres in ${cluster.dir}: the company's records live there, and deleting it deletes them`);
98
+ }
99
+ return { how, databaseUrl: url, stop: () => stopAlone(pg, cluster, url, log) };
100
+ });
101
+ }
102
+ const paths = (dir) => ({
103
+ dir,
104
+ data: join(dir, "data"),
105
+ password: join(dir, "password"),
106
+ log: join(dir, "server.log"),
107
+ lock: join(dir, "starting"),
108
+ });
109
+ /**
110
+ * Where the company's own Postgres lives: `.sanoma/postgres` in the company's root as its main
111
+ * checkout has it (the directory of git's common dir), so a worktree of the repo (a draft in
112
+ * `.sanoma/drafts/<id>`) finds the same cluster; `root` itself outside git.
113
+ */
114
+ export async function clusterDir(root) {
115
+ const real = realpathSync(root);
116
+ const [common, top] = await promisify(execFile)("git", ["rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel"], { cwd: real }).then(({ stdout }) => stdout.trim().split("\n"), () => []);
117
+ const main = common && top && basename(common) === ".git" ? join(dirname(common), relative(top, real)) : real;
118
+ return join(main, ".sanoma", "postgres");
119
+ }
120
+ const urlOf = ({ password }, port) => `postgresql://postgres:${readFileSync(password, "utf8").trim()}@127.0.0.1:${port}/sanoma`;
121
+ function answered(cluster, url, log) {
122
+ log(`Postgres answers in ${cluster.dir}, started by another launcher`);
123
+ return { how: "answered", databaseUrl: url, stop: noStop };
124
+ }
125
+ /** `data/postmaster.pid`'s process (its first line) and port (its fourth), when there is one. */
126
+ function postmaster({ data }) {
127
+ const file = join(data, "postmaster.pid");
128
+ if (!existsSync(file))
129
+ return undefined;
130
+ const lines = readFileSync(file, "utf8").split("\n");
131
+ return { file, pid: Number(lines[0]), port: Number(lines[3]) };
132
+ }
133
+ /** The cluster's URL when its postmaster runs and answers: `postmaster.pid` names a live process, and its port answers. */
134
+ async function running(cluster) {
135
+ const pm = postmaster(cluster);
136
+ if (!pm || !alive(pm.pid) || !pm.port || !existsSync(cluster.password))
137
+ return undefined;
138
+ const url = urlOf(cluster, pm.port);
139
+ return (await answers(url)) ? url : undefined;
140
+ }
141
+ /**
142
+ * Deletes a stale `postmaster.pid` whose process is another program's now (its pid reused, after
143
+ * a restart), which Postgres would take for a server still running. One whose process is gone is
144
+ * left to Postgres, which replaces it once no backend of the old server holds its shared memory;
145
+ * a Postgres that runs there but does not answer is a mistake to report, never a second server.
146
+ */
147
+ function clearStale(cluster) {
148
+ const pm = postmaster(cluster);
149
+ if (!pm || !alive(pm.pid))
150
+ return;
151
+ const ps = spawnSync("ps", ["-o", "comm=", "-p", String(pm.pid)], { encoding: "utf8" });
152
+ // Without `ps` to tell, the process may be the server: never a second one on its data.
153
+ if (ps.error || /(^|\/)postgres$/.test(ps.stdout.trim())) {
154
+ throw new Error(`Postgres (pid ${pm.pid}) may run in ${cluster.data} but does not answer; see ${cluster.log}`);
155
+ }
156
+ rmSync(pm.file, { force: true });
157
+ }
158
+ /** Whether a process runs as `pid` (another user's too). */
159
+ function alive(pid) {
160
+ if (!Number.isInteger(pid) || pid <= 0)
161
+ return false;
42
162
  try {
43
- state = await docker(["inspect", "-f", "{{.State.Running}}", container]);
163
+ process.kill(pid, 0);
164
+ return true;
44
165
  }
45
166
  catch (err) {
46
- if (err.code === "ENOENT") {
47
- throw new Error("docker is not installed; start Postgres and set SANOMA_DATABASE_URL", { cause: err });
167
+ return err.code === "EPERM";
168
+ }
169
+ }
170
+ /**
171
+ * Runs `fn` holding the cluster's `starting` lock: the file made exclusively (`wx`), this pid in
172
+ * it, removed after. A lock whose process is gone (or, empty, older than a few seconds) is
173
+ * stale and taken over; a live one is waited for, up to `LOCK_WAIT_MS`.
174
+ */
175
+ async function locked(cluster, fn) {
176
+ const deadline = Date.now() + LOCK_WAIT_MS;
177
+ for (;;) {
178
+ try {
179
+ const fd = openSync(cluster.lock, "wx");
180
+ writeSync(fd, String(process.pid));
181
+ closeSync(fd);
182
+ break;
183
+ }
184
+ catch (err) {
185
+ if (err.code !== "EEXIST")
186
+ throw err;
187
+ }
188
+ let holder;
189
+ let fresh;
190
+ try {
191
+ holder = readFileSync(cluster.lock, "utf8");
192
+ const age = Date.now() - statSync(cluster.lock).mtimeMs;
193
+ // Being written: its maker is between making it and writing its pid. Older than any start
194
+ // takes: left by a crash, its pid perhaps another process's since.
195
+ fresh = !holder && age < 5000;
196
+ if (age > LOCK_WAIT_MS)
197
+ holder = "";
198
+ }
199
+ catch {
200
+ continue; // Removed meanwhile.
201
+ }
202
+ if (!fresh && !alive(Number(holder))) {
203
+ rmSync(cluster.lock, { force: true });
204
+ continue;
48
205
  }
49
- // No such container.
50
- }
51
- let how;
52
- if (state === "true") {
53
- log(`Postgres container ${container} is running; waiting for it to answer`);
54
- how = "reused";
55
- }
56
- else if (state === "false") {
57
- log(`starting Postgres container ${container}`);
58
- await docker(["start", container]);
59
- how = "reused";
60
- }
61
- else {
62
- log(`creating Postgres container ${container} on port ${port(url)} (postgres:17)`);
63
- await docker([
64
- "run",
65
- "-d",
66
- "--name",
67
- container,
68
- "-e",
69
- `POSTGRES_USER=${decodeURIComponent(url.username || "postgres")}`,
70
- "-e",
71
- `POSTGRES_PASSWORD=${decodeURIComponent(url.password)}`,
72
- "-e",
73
- `POSTGRES_DB=${decodeURIComponent(url.pathname.slice(1)) || "postgres"}`,
74
- "-p",
75
- `${port(url)}:5432`,
76
- "postgres:17",
77
- ]);
78
- how = "created";
79
- }
80
- const deadline = Date.now() + WAIT_MS;
81
- while (!(await answers(url, PROBE_TIMEOUT_MS))) {
82
206
  if (Date.now() >= deadline) {
83
- throw new Error(`Postgres in container ${container} did not answer at ${masked(databaseUrl)} within ${WAIT_MS} ms`);
207
+ throw new Error(`another sanoma (pid ${holder}) is still starting Postgres in ${cluster.dir}`);
208
+ }
209
+ await delay(200);
210
+ }
211
+ try {
212
+ return await fn();
213
+ }
214
+ finally {
215
+ rmSync(cluster.lock, { force: true });
216
+ }
217
+ }
218
+ /**
219
+ * Makes the cluster: `initdb` into `data.tmp` (the password made first when there is none: 24
220
+ * random bytes, hex), as `postgres` with that password over SCRAM, UTF-8 with the builtin
221
+ * C.UTF-8 locale (and C for the rest, whatever this machine's `LANG`); then on 127.0.0.1 alone,
222
+ * at a free port, with no Unix socket; renamed to `data` once whole.
223
+ */
224
+ async function initdb(bin, cluster) {
225
+ if (!existsSync(cluster.password)) {
226
+ writeFileSync(cluster.password, randomBytes(24).toString("hex"), { mode: 0o600 });
227
+ }
228
+ const temp = `${cluster.data}.tmp`;
229
+ rmSync(temp, { recursive: true, force: true });
230
+ await runPg(bin, "initdb", cluster, [
231
+ "-D",
232
+ temp,
233
+ "-U",
234
+ "postgres",
235
+ `--pwfile=${cluster.password}`,
236
+ "--auth=scram-sha-256",
237
+ "--encoding=UTF8",
238
+ "--locale=C",
239
+ "--locale-provider=builtin",
240
+ "--builtin-locale=C.UTF-8",
241
+ ]);
242
+ appendFileSync(join(temp, "postgresql.conf"), `\n# sanoma\nlisten_addresses = '127.0.0.1'\nport = ${await freePort()}\nunix_socket_directories = ''\n`);
243
+ renameSync(temp, cluster.data);
244
+ }
245
+ /** The cluster's port (`port = …` in `postgresql.conf`), rewritten to a free one when another process holds it. */
246
+ async function portOf(cluster) {
247
+ const conf = join(cluster.data, "postgresql.conf");
248
+ const text = readFileSync(conf, "utf8");
249
+ const set = [...text.matchAll(/^port = (\d+)$/gm)].at(-1);
250
+ if (set && !(await taken(Number(set[1]))))
251
+ return Number(set[1]);
252
+ const port = await freePort();
253
+ writeFileSync(conf, set ? text.replaceAll(/^port = \d+$/gm, `port = ${port}`) : `${text}\nport = ${port}\n`);
254
+ return port;
255
+ }
256
+ /** Whether something listens on 127.0.0.1 at `port`. */
257
+ const taken = (port) => new Promise((resolve) => {
258
+ const server = createServer();
259
+ server.once("error", () => resolve(true));
260
+ server.listen(port, "127.0.0.1", () => server.close(() => resolve(false)));
261
+ });
262
+ /** A port nothing listens on at 127.0.0.1 now. */
263
+ const freePort = () => new Promise((resolve, reject) => {
264
+ const server = createServer();
265
+ server.once("error", reject);
266
+ server.listen(0, "127.0.0.1", () => {
267
+ const { port } = server.address();
268
+ server.close(() => resolve(port));
269
+ });
270
+ });
271
+ /**
272
+ * Stops the cluster (`pg_ctl stop -m fast`) unless a client but this one is connected: then it
273
+ * stays up for them, and says so. A cluster that no longer answers is left alone.
274
+ */
275
+ async function stopAlone(bin, cluster, databaseUrl, log) {
276
+ const url = new URL(databaseUrl);
277
+ url.pathname = "/postgres";
278
+ const client = new Client({ connectionString: url.toString(), connectionTimeoutMillis: PROBE_TIMEOUT_MS });
279
+ let others;
280
+ try {
281
+ await client.connect();
282
+ const count = async () => (await client.query("SELECT count(*)::int AS others FROM pg_stat_activity WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()")).rows[0].others;
283
+ // The worker's and the app's backends end a moment after their pools close: a second for them.
284
+ others = await count();
285
+ for (let i = 0; others > 0 && i < 5; i++) {
286
+ await delay(200);
287
+ others = await count();
84
288
  }
85
- await new Promise((resolve) => setTimeout(resolve, 500));
86
289
  }
87
- log(`Postgres ${how} in Docker: container ${container}`);
88
- return { how, container };
290
+ catch (err) {
291
+ if (isSilent(err))
292
+ return;
293
+ throw err;
294
+ }
295
+ finally {
296
+ await client.end().catch(() => { });
297
+ }
298
+ if (others > 0) {
299
+ log(`leaving Postgres running in ${cluster.dir}: ${others} other connection${others === 1 ? "" : "s"}`);
300
+ return;
301
+ }
302
+ await pgCtl(bin, cluster, ["stop", "-D", cluster.data, "-m", "fast", "-w"]);
303
+ log(`stopped Postgres in ${cluster.dir}`);
304
+ }
305
+ const pgCtl = (bin, cluster, args) => runPg(bin, "pg_ctl", cluster, args);
306
+ /**
307
+ * Runs PostgreSQL's `program` from `bin`, in a process group of its own (`pg_ctl start` leaves
308
+ * the server in it), its output appended to `server.log`; throws, with the log's last lines,
309
+ * when it fails.
310
+ */
311
+ async function runPg(bin, program, cluster, args) {
312
+ const out = openSync(cluster.log, "a");
313
+ try {
314
+ const code = await new Promise((resolve, reject) => {
315
+ const child = spawn(join(bin, "bin", program), args, { detached: true, stdio: ["ignore", out, out] });
316
+ child.once("error", reject);
317
+ child.once("exit", resolve);
318
+ });
319
+ if (code === 0)
320
+ return;
321
+ const tail = readFileSync(cluster.log, "utf8").trimEnd().split("\n").slice(-5).join("\n");
322
+ throw new Error(`${program} ${args[0]} failed (exit ${code}); the end of ${cluster.log}:\n${tail}`);
323
+ }
324
+ finally {
325
+ closeSync(out);
326
+ }
89
327
  }
90
- const port = (url) => url.port || "5432";
91
- /** A container name from an app name: lowercase, anything but `[a-z0-9_.-]` as `-`. */
92
- const slug = (appName) => appName.toLowerCase().replaceAll(/[^a-z0-9_.-]/g, "-");
93
328
  /**
94
329
  * Whether a Postgres server answers at the URL's host and port, as its user: `SELECT 1` on the
95
330
  * `postgres` database. False when the connection is refused, unreachable or not answered within
96
- * `timeoutMs`; any other failure (a refused password, a user that does not exist) is thrown.
331
+ * `PROBE_TIMEOUT_MS`; any other failure (a refused password, a user that does not exist) is thrown.
97
332
  */
98
- export async function answers(url, timeoutMs) {
333
+ async function answers(databaseUrl) {
334
+ const url = new URL(databaseUrl);
99
335
  const client = new Client({
100
336
  host: url.hostname.replace(/^\[(.*)\]$/, "$1"),
101
- port: Number(port(url)),
337
+ port: Number(url.port || "5432"),
102
338
  user: decodeURIComponent(url.username || "postgres"),
103
339
  password: decodeURIComponent(url.password),
104
340
  database: "postgres",
105
- connectionTimeoutMillis: timeoutMs,
341
+ connectionTimeoutMillis: PROBE_TIMEOUT_MS,
106
342
  });
107
343
  try {
108
344
  await client.connect();
@@ -1 +1 @@
1
- {"version":3,"file":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,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QAChC,MAAM,GAAG,CAAC;IACZ,CAAC;YAAS,CAAC;QACT,MAAM,MAAM,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAED,wGAAwG;AACxG,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;AAE5G;;;GAGG;AACH,SAAS,QAAQ,CAAC,GAAY;IAC5B,MAAM,MAAM,GAAG,GAAG,YAAY,cAAc,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;QACxB,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,CAA0B,CAAC;QACrD,OAAO,CAAC,IAAI,KAAK,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,kCAAkC,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;IAC5G,CAAC,CAAC,CAAC;AACL,CAAC"}
package/dist/serve.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AppOptions } from "@sanoma-ai/app";
1
+ import { type AppOptions, type IngressRoute } from "@sanoma-ai/app";
2
2
  import { type ResolvedConfig, type SanomaConfig } from "@sanoma-ai/workflows";
3
3
  export interface Stoppable {
4
4
  stop(): Promise<void>;
@@ -9,7 +9,10 @@ export interface Served extends Stoppable {
9
9
  /** Each public site, by name, at its own host on this machine: `http://www.localhost:3000` (`App.sites`). */
10
10
  sites: Record<string, string>;
11
11
  }
12
- /** Starts the worker, promoted: a local worker is always the version to take queued runs, even one seen before. */
12
+ /**
13
+ * Starts the worker, for `sanoma worker`: it never stops itself, since nothing in this process
14
+ * would start it again (no app hears a write or a wake). `serve` supervises its own.
15
+ */
13
16
  export declare function runWorker(config: SanomaConfig): Promise<Stoppable>;
14
17
  export interface ServeOptions {
15
18
  /** The app's port: 0 for any free port. */
@@ -21,8 +24,20 @@ export interface ServeOptions {
21
24
  /** The config, resolved, when the caller has it: the Cedar schema is made from it. */
22
25
  resolved?: ResolvedConfig;
23
26
  }
27
+ /** The wakeup's route's: what it hands each wake to, and where a failure of that is said. */
28
+ export interface WakeRouteOptions {
29
+ /** Called for each `GET /wake` the app answers. Default: nothing. */
30
+ onWake?: () => void | Promise<void>;
31
+ log: (line: string) => void;
32
+ }
24
33
  /** Starts the app on `port`, with the host and login `appOptions` reads, and the sites built; `url` says where. */
25
34
  export declare function runApp(config: SanomaConfig, options: ServeOptions): Promise<Served>;
35
+ /**
36
+ * The wakeup's `GET /wake`, a machine route with no login: handed to `onWake` and answered 204,
37
+ * always (a wake is "resume if stopped": one late, twice or for a replaced registration starts a
38
+ * worker that finds nothing to do). `onWake` throwing or rejecting is logged, never the wakeup's failure.
39
+ */
40
+ export declare function wakeRoute({ onWake, log }: WakeRouteOptions): IngressRoute;
26
41
  /** Reads stored secrets by name (`SanomaClient.secrets`): the values found, the environment's first. */
27
42
  export type ReadSecrets = (names: string[]) => Promise<Map<string, string>>;
28
43
  /**
@@ -40,5 +55,11 @@ export declare function parseDomains(value: string | undefined): Record<string,
40
55
  * app's connect page put them. A mistake in them is a UsageError.
41
56
  */
42
57
  export declare function appOptions(readSecrets?: ReadSecrets): Promise<Pick<AppOptions, "host" | "login" | "domains">>;
43
- /** The sites' build, the worker, then the app, in this process; `stop` stops the app, then the worker. */
58
+ /**
59
+ * The sites' build, the worker under a supervisor (`superviseWorker`), the wakeup service when
60
+ * the config runs it (`wakeup: true`), then the app, serving `/wake` and the service's routes, in
61
+ * this process. A worker that stopped itself starts again on a wake, or on a write from the app
62
+ * (`AppOptions.onWrite`: a run's start, an approval's decision), never on a page read. `stop`
63
+ * stops the app, the service, then the worker.
64
+ */
44
65
  export declare function serve(config: SanomaConfig, serveOptions: ServeOptions): Promise<Served>;
package/dist/serve.js CHANGED
@@ -3,7 +3,7 @@ import { realpathSync } from "node:fs";
3
3
  import { dirname, extname, isAbsolute, relative, sep } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { githubLogin, startApp } from "@sanoma-ai/app";
6
- import { errorMessage, isLoopback, resolveConfig, SanomaClient, startWorker, } from "@sanoma-ai/workflows";
6
+ import { errorMessage, isLoopback, resolveConfig, resolveDatabaseUrl, SanomaClient, startWorker, superviseWorker, } from "@sanoma-ai/workflows";
7
7
  import { describeConfig, readPeople, schemaOf, writeGenerated } from "@sanoma-ai/workflows/describe";
8
8
  import { domainsOf } from "@sanoma-ai/workflows/shared";
9
9
  import { UsageError } from "./config.js";
@@ -11,16 +11,37 @@ import { runtimeFrom, siteBuild } from "./sites.js";
11
11
  import { localGitSource } from "./source.js";
12
12
  /** The checkout the config was loaded from (`loadConfig` sets its `file`). */
13
13
  const rootOf = (config) => config.root ?? dirname(config.file);
14
- /** The checkout, as the worker's and the app's `source`. */
15
- const sourceOf = (config) => localGitSource(rootOf(config));
16
- /** Starts the worker, promoted: a local worker is always the version to take queued runs, even one seen before. */
14
+ /** The checkout, as the worker's and the app's `source`, a draft's check on the config's database. */
15
+ const sourceOf = (config) => localGitSource(rootOf(config), { databaseUrl: resolveDatabaseUrl(config) });
16
+ /** What a worker of the launcher's starts with: promoted, since a local worker is always the version to take queued runs, even one seen before, and the checkout as its source. */
17
+ const workerOptions = (config) => ({ promote: true, source: sourceOf(config) });
18
+ /**
19
+ * Starts the worker, for `sanoma worker`: it never stops itself, since nothing in this process
20
+ * would start it again (no app hears a write or a wake). `serve` supervises its own.
21
+ */
17
22
  export async function runWorker(config) {
18
- const worker = await startWorker(config, { promote: true, source: sourceOf(config) });
23
+ const worker = await startWorker(config, workerOptions(config));
19
24
  return { stop: () => worker.stop() };
20
25
  }
21
26
  /** Starts the app on `port`, with the host and login `appOptions` reads, and the sites built; `url` says where. */
22
27
  export async function runApp(config, options) {
23
- return served(config, await appStart(config, options));
28
+ return served(config, await appStart(config, options), []);
29
+ }
30
+ /**
31
+ * The wakeup's `GET /wake`, a machine route with no login: handed to `onWake` and answered 204,
32
+ * always (a wake is "resume if stopped": one late, twice or for a replaced registration starts a
33
+ * worker that finds nothing to do). `onWake` throwing or rejecting is logged, never the wakeup's failure.
34
+ */
35
+ export function wakeRoute({ onWake, log }) {
36
+ return {
37
+ method: "GET",
38
+ path: "/wake",
39
+ async handle() {
40
+ // Not awaited: the wakeup's answer never waits on what the wake starts.
41
+ void (async () => onWake?.())().catch((err) => log(`a wake failed: ${errorMessage(err)}`));
42
+ return new Response(null, { status: 204, headers: { "cache-control": "no-store" } });
43
+ },
44
+ };
24
45
  }
25
46
  /**
26
47
  * What the app starts with: the port, the host and login `appOptions` reads, and what it serves
@@ -34,8 +55,9 @@ async function appStart(config, { port, log, dev = false, resolved = resolveConf
34
55
  const sites = await appSites(rootOf(config), log, dev ? options.host : false);
35
56
  return { ...options, ...sites, ...(sites.dev && { dev: { ...sites.dev, onFileChange: apiWriter(config, log) } }) };
36
57
  }
37
- async function served(config, options) {
38
- const app = await startApp(config, { ...options, source: sourceOf(config) });
58
+ /** Starts the app with `options`, the checkout as its source, and the machine routes `ingress` (`/wake`). */
59
+ async function served(config, options, ingress) {
60
+ const app = await startApp(config, { ...options, source: sourceOf(config), ingress });
39
61
  return { url: app.url, sites: app.sites, stop: () => app.close() };
40
62
  }
41
63
  /**
@@ -95,7 +117,8 @@ function apiWriter(config, log) {
95
117
  const run = () => {
96
118
  running = true;
97
119
  again = false;
98
- spawn(process.execPath, [cli, "api"], { cwd, stdio: "inherit" })
120
+ // Not a launcher: its failure is no `error` event for a parent process (SANOMA_EVENTS).
121
+ spawn(process.execPath, [cli, "api"], { cwd, stdio: "inherit", env: { ...process.env, SANOMA_EVENTS: undefined } })
99
122
  .once("error", (err) => log(`could not write .sanoma/: ${err.message}`))
100
123
  .once("close", () => {
101
124
  running = false;
@@ -178,17 +201,37 @@ export async function appOptions(readSecrets) {
178
201
  throw new UsageError(errorMessage(err));
179
202
  }
180
203
  }
181
- /** The sites' build, the worker, then the app, in this process; `stop` stops the app, then the worker. */
204
+ /**
205
+ * The sites' build, the worker under a supervisor (`superviseWorker`), the wakeup service when
206
+ * the config runs it (`wakeup: true`), then the app, serving `/wake` and the service's routes, in
207
+ * this process. A worker that stopped itself starts again on a wake, or on a write from the app
208
+ * (`AppOptions.onWrite`: a run's start, an approval's decision), never on a page read. `stop`
209
+ * stops the app, the service, then the worker.
210
+ */
182
211
  export async function serve(config, serveOptions) {
183
212
  // Read and built before the worker starts, so a mistake in the variables or a site starts nothing.
184
213
  const options = await appStart(config, serveOptions);
185
- const worker = await runWorker(config);
214
+ const { log } = serveOptions;
215
+ // An app on this machine alone is not the instance the host runs: its worker never stops
216
+ // itself (its wakeup would wake that instance).
217
+ const here = isLoopback(options.host ?? "127.0.0.1");
218
+ const supervised = await superviseWorker(config, { ...workerOptions(config), selfStop: !here });
219
+ let wakeup;
186
220
  let app;
187
221
  try {
188
- app = await served(config, options);
222
+ if (config.wakeup === true) {
223
+ const { databaseUrl } = serveOptions.resolved ?? resolveConfig(config);
224
+ const { startWakeupService } = await import("@sanoma-ai/workflows/wakeup-service");
225
+ wakeup = await startWakeupService({ databaseUrl, log: { info: log, warn: log } });
226
+ }
227
+ app = await served(config, { ...options, onWrite: () => void supervised.resume() }, [
228
+ wakeRoute({ log, onWake: () => supervised.wake() }),
229
+ ...(wakeup?.routes ?? []),
230
+ ]);
189
231
  }
190
232
  catch (err) {
191
- await worker.stop().catch(() => { });
233
+ await wakeup?.stop().catch(() => { });
234
+ await supervised.stop().catch(() => { });
192
235
  throw err;
193
236
  }
194
237
  return {
@@ -199,7 +242,12 @@ export async function serve(config, serveOptions) {
199
242
  await app.stop();
200
243
  }
201
244
  finally {
202
- await worker.stop();
245
+ try {
246
+ await wakeup?.stop();
247
+ }
248
+ finally {
249
+ await supervised.stop();
250
+ }
203
251
  }
204
252
  },
205
253
  };