copilotz 1.0.0-rc.27 → 1.0.0-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  ## Unreleased
2
2
 
3
+ ## 1.0.0-rc.28 — 2026-11-07
4
+
5
+ - **A deploy hands over instead of fencing** (`serve` in `copilotz/web/node`, `lease` in
6
+ `copilotz/stores/postgres`). While a deploy moves traffic, the platform keeps the old process
7
+ running for as long as its browsers' sockets stay open, and the new process's store fenced it:
8
+ every write those browsers sent failed ("This owner was fenced"). Now one process at a time holds
9
+ the store's lease: `serve` listens first (a request is told it's starting: a 503 to retry, a page
10
+ that reloads itself), waits for the lease, then opens the app; the old process, asked for it,
11
+ stops listening (its browsers reconnect, to the new one), lets running work finish, and lets go.
12
+ Only a deploy at least as new asks (`revision`); a process that loses the lease stops. Its table
13
+ is `copilotz_lease`, in the schema it's given (`public` by default).
14
+ - **A contact's message may go to nobody** (`chat.send` with `to: []`), as a person's already could:
15
+ it's kept in the chat, its agents read it the next time they answer there (with its `tap`, as
16
+ `[tapped: <id>]`), and none answers it. It's how a page beside the chat says what the customer did
17
+ there (a trip chosen in a booking panel) without a turn for each tap. A contact still names no
18
+ agent: any other `to` goes to its chat's agents, as before. `contactSend` hooks are told
19
+ (`to: []`): a web line's visitor's message to nobody counts against its limits but holds none of
20
+ the line's budget, since no turn will be charged for it.
21
+
3
22
  ## 1.0.0-rc.27 — 2026-11-06
4
23
 
5
24
  **Upgrading.** Chat's `file.content` query is `file.about`, and answers a file without its content
package/README.md CHANGED
@@ -22,7 +22,7 @@ bun add copilotz # Bun
22
22
  deno add jsr:@copilotz/copilotz # Deno (or `deno add npm:copilotz`)
23
23
  ```
24
24
 
25
- On Deno, name it `copilotz` in `deno.json` (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.27"`),
25
+ On Deno, name it `copilotz` in `deno.json` (`"copilotz": "jsr:@copilotz/copilotz@^1.0.0-rc.28"`),
26
26
  and the imports below are the same everywhere. Some pieces need a package of their own, installed
27
27
  beside it: `esbuild` to bundle the page's code on Node (`bundle`), `@electric-sql/pglite` for
28
28
  PostgreSQL in the process, and `@types/react` for the front ends' types.
@@ -631,7 +631,7 @@ and an app serves it from there by default:
631
631
  import { computerDownloads } from "copilotz/plugins/compute/downloads";
632
632
 
633
633
  plugins: [...plugins, await computerDownloads()], // this Copilotz's release
634
- plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.27" })], // its own: /computer/download/
634
+ plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.28" })], // its own: /computer/download/
635
635
  plugins: [...plugins, await computerDownloads({ url: "https://downloads.example.com/computer/" })], // or elsewhere
636
636
  ```
637
637
 
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Copilotz on Node: what an app needs beside its runtime to serve it there.
3
3
  * `listen` serves a fetch handler with Node's HTTP server, through Oxian's
4
- * Node adapter, sockets included (`runtime.fetch` accepts its own); `bundle`
4
+ * Node adapter, sockets included (`runtime.fetch` accepts its own); `serve`
5
+ * serves a runtime through a deploy (below); `bundle`
5
6
  * makes the browser's code with esbuild (code splitting, as on Deno), for
6
7
  * the page (`webPage`'s `code`). Bun and Deno run it too.
7
8
  *
@@ -22,6 +23,33 @@
22
23
  * await runtime.close({ drain: 8_000 });
23
24
  * });
24
25
  * ```
26
+ *
27
+ * `serve` does what a deploy needs around that: it listens first (requests
28
+ * are told it's starting), takes the store's lease (`lease` from
29
+ * `copilotz/stores/postgres`), waiting for the previous process to hand
30
+ * over, then opens the runtime; and it hands over in turn when a newer
31
+ * process asks, so no two processes write the store at once and browsers
32
+ * reconnect to the newer one instead of being fenced.
33
+ *
34
+ * ```ts
35
+ * import { lease, postgresPool, postgresStore } from "copilotz/stores/postgres";
36
+ * import { serve } from "copilotz/web/node";
37
+ *
38
+ * const pool = await postgresPool({ url: process.env.DATABASE_URL!, writes: 5, reads: 5 });
39
+ * const sigterm = new AbortController();
40
+ * process.once("SIGTERM", () => sigterm.abort());
41
+ * const { server } = await serve(
42
+ * async () => createRuntime({ store: await postgresStore({ pool }), plugins }),
43
+ * {
44
+ * hostname: "0.0.0.0",
45
+ * port: 8080,
46
+ * signal: sigterm.signal,
47
+ * // Each deploy's number (Cloud Run's revision: app-00015-8bs is 15) asks older ones only.
48
+ * hold: (on) => lease(pool, { revision: Number(process.env.K_REVISION?.split("-").at(-2) ?? 0), ...on }),
49
+ * stopped: (code) => void pool.close().finally(() => process.exit(code)),
50
+ * },
51
+ * );
52
+ * ```
25
53
  */
26
54
  export { bundle, type BundleOptions } from "./bundle.js";
27
- export { listen, type Listener, type ListenOptions } from "./serve.js";
55
+ export { type App, type Holding, listen, type Listener, type ListenOptions, serve, type ServeOptions, } from "./serve.js";
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Copilotz on Node: what an app needs beside its runtime to serve it there.
3
3
  * `listen` serves a fetch handler with Node's HTTP server, through Oxian's
4
- * Node adapter, sockets included (`runtime.fetch` accepts its own); `bundle`
4
+ * Node adapter, sockets included (`runtime.fetch` accepts its own); `serve`
5
+ * serves a runtime through a deploy (below); `bundle`
5
6
  * makes the browser's code with esbuild (code splitting, as on Deno), for
6
7
  * the page (`webPage`'s `code`). Bun and Deno run it too.
7
8
  *
@@ -22,6 +23,33 @@
22
23
  * await runtime.close({ drain: 8_000 });
23
24
  * });
24
25
  * ```
26
+ *
27
+ * `serve` does what a deploy needs around that: it listens first (requests
28
+ * are told it's starting), takes the store's lease (`lease` from
29
+ * `copilotz/stores/postgres`), waiting for the previous process to hand
30
+ * over, then opens the runtime; and it hands over in turn when a newer
31
+ * process asks, so no two processes write the store at once and browsers
32
+ * reconnect to the newer one instead of being fenced.
33
+ *
34
+ * ```ts
35
+ * import { lease, postgresPool, postgresStore } from "copilotz/stores/postgres";
36
+ * import { serve } from "copilotz/web/node";
37
+ *
38
+ * const pool = await postgresPool({ url: process.env.DATABASE_URL!, writes: 5, reads: 5 });
39
+ * const sigterm = new AbortController();
40
+ * process.once("SIGTERM", () => sigterm.abort());
41
+ * const { server } = await serve(
42
+ * async () => createRuntime({ store: await postgresStore({ pool }), plugins }),
43
+ * {
44
+ * hostname: "0.0.0.0",
45
+ * port: 8080,
46
+ * signal: sigterm.signal,
47
+ * // Each deploy's number (Cloud Run's revision: app-00015-8bs is 15) asks older ones only.
48
+ * hold: (on) => lease(pool, { revision: Number(process.env.K_REVISION?.split("-").at(-2) ?? 0), ...on }),
49
+ * stopped: (code) => void pool.close().finally(() => process.exit(code)),
50
+ * },
51
+ * );
52
+ * ```
25
53
  */
26
54
  export { bundle } from "./bundle.js";
27
- export { listen } from "./serve.js";
55
+ export { listen, serve, } from "./serve.js";
@@ -18,3 +18,58 @@ export type Listener = {
18
18
  };
19
19
  /** Serves a fetch handler (`runtime.fetch`): every request, sockets' upgrades included. */
20
20
  export declare function listen(fetch: (request: Request) => Response | Promise<Response>, options?: ListenOptions): Promise<Listener>;
21
+ /** What `serve` serves: a runtime, or anything that answers requests and closes like one. */
22
+ export type App = {
23
+ fetch(request: Request): Response | Promise<Response>;
24
+ close(options?: {
25
+ drain?: number;
26
+ }): Promise<void>;
27
+ };
28
+ /** What `serve` gives the lease it holds (`lease` from `copilotz/stores/postgres` takes it all). */
29
+ export type Holding = {
30
+ /** Aborts when it stops while still waiting for the lease. */
31
+ signal: AbortSignal;
32
+ /** Another process holds it, and this one waits. */
33
+ waiting(): void;
34
+ /** A newer process waits for it: this one hands over. */
35
+ asked(): void;
36
+ /** It was lost: this one stops. */
37
+ lost(why: string): void;
38
+ };
39
+ export type ServeOptions = ListenOptions & {
40
+ /**
41
+ * Takes the store's lease before the app opens, so one process at a time
42
+ * writes it (`(on) => lease(pool, { revision, ...on })`): this process waits
43
+ * for the one holding it, and hands over to the next.
44
+ */
45
+ hold?: (holding: Holding) => Promise<{
46
+ release(): Promise<void>;
47
+ }>;
48
+ /** What a request gets until the app is open: a 503 to retry in 2 s (a page that reloads itself) by default. */
49
+ starting?: (request: Request) => Response | Promise<Response>;
50
+ /** How long running work gets to finish when it stops, in ms: 8 000 by default. */
51
+ drain?: number;
52
+ /**
53
+ * Said once it has stopped by itself (it handed over: 0; it lost the lease:
54
+ * 1) or by its `signal` (0); a process exits with it.
55
+ */
56
+ stopped?: (code: number) => void;
57
+ };
58
+ /**
59
+ * Serves an app the way a deploy needs: it listens first, so the platform
60
+ * sees it's up (requests are told it's starting), takes the store's lease if
61
+ * it's given one (`hold`), then opens the app and serves it. It stops when
62
+ * its `signal` aborts (SIGTERM), when `stop` is called, or when a newer
63
+ * process asks for the lease: it stops listening (its sockets close, and
64
+ * browsers reconnect, to the newer process), the app's running work gets
65
+ * `drain` to finish, and the lease goes to whoever waits. A process that
66
+ * loses the lease stops too, rather than write beside another.
67
+ *
68
+ * It rejects when it stops before the app is open, or the app fails to open.
69
+ * What the app's `open` opened (its pool) stays the app's to close.
70
+ */
71
+ export declare function serve<A extends App>(open: () => Promise<A>, options?: ServeOptions): Promise<{
72
+ app: A;
73
+ server: Listener;
74
+ stop(): Promise<void>;
75
+ }>;
@@ -15,3 +15,86 @@ export async function listen(fetch, options = {}) {
15
15
  };
16
16
  return await oxian({ hypervisor: front, hostname, port, signal });
17
17
  }
18
+ /**
19
+ * Serves an app the way a deploy needs: it listens first, so the platform
20
+ * sees it's up (requests are told it's starting), takes the store's lease if
21
+ * it's given one (`hold`), then opens the app and serves it. It stops when
22
+ * its `signal` aborts (SIGTERM), when `stop` is called, or when a newer
23
+ * process asks for the lease: it stops listening (its sockets close, and
24
+ * browsers reconnect, to the newer process), the app's running work gets
25
+ * `drain` to finish, and the lease goes to whoever waits. A process that
26
+ * loses the lease stops too, rather than write beside another.
27
+ *
28
+ * It rejects when it stops before the app is open, or the app fails to open.
29
+ * What the app's `open` opened (its pool) stays the app's to close.
30
+ */
31
+ export async function serve(open, options = {}) {
32
+ const { hold, starting = startingPage, drain = 8_000, stopped, signal, ...where } = options;
33
+ signal?.throwIfAborted();
34
+ /** The app once it's open; until then, requests are told it's starting. */
35
+ let app;
36
+ const server = await listen((request) => app ? app.fetch(request) : starting(request), where);
37
+ const waiting = new AbortController();
38
+ let held;
39
+ let opening;
40
+ let stopping;
41
+ const stop = () => stopping ??= (async () => {
42
+ waiting.abort(new DOMException("It stopped before the app opened", "AbortError"));
43
+ try {
44
+ await server.shutdown();
45
+ }
46
+ finally {
47
+ try {
48
+ // An app still opening closes once it's open.
49
+ await (await opening?.catch(() => undefined))?.close({ drain });
50
+ }
51
+ finally {
52
+ await held?.release();
53
+ }
54
+ }
55
+ })();
56
+ let said = false;
57
+ /** It stops by itself (or by its signal), and says so, once. */
58
+ const stopBy = (code, why) => {
59
+ if (said)
60
+ return;
61
+ said = true;
62
+ if (why)
63
+ (code ? console.error : console.log)(why);
64
+ void stop().finally(() => stopped?.(code));
65
+ };
66
+ const aborted = () => stopBy(0);
67
+ signal?.addEventListener("abort", aborted, { once: true });
68
+ try {
69
+ if (hold) {
70
+ held = await hold({
71
+ signal: waiting.signal,
72
+ waiting: () => console.log("Waiting for the previous process to let go of the store…"),
73
+ asked: () => stopBy(0, "A newer process asks for the store: handing over"),
74
+ lost: (why) => stopBy(1, `Lost the store's lease (${why}): stopping`),
75
+ });
76
+ // Taken just as it stopped: let go of it again.
77
+ if (stopping)
78
+ await held.release();
79
+ waiting.signal.throwIfAborted();
80
+ }
81
+ opening = open();
82
+ app = await opening;
83
+ }
84
+ catch (error) {
85
+ signal?.removeEventListener("abort", aborted);
86
+ await stop();
87
+ throw error;
88
+ }
89
+ return { app, server, stop };
90
+ }
91
+ /** While it waits for the store: a page that tries again by itself, or a 503 to retry. */
92
+ function startingPage(request) {
93
+ const headers = { "retry-after": "2" };
94
+ if (request.method === "GET" && request.headers.get("accept")?.includes("text/html")) {
95
+ return new Response('<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="2">' +
96
+ '<meta name="viewport" content="width=device-width, initial-scale=1">' +
97
+ "<title>Starting</title><p>Starting, one moment…</p>", { status: 503, headers: { ...headers, "content-type": "text/html; charset=utf-8" } });
98
+ }
99
+ return Response.json({ error: "starting" }, { status: 503, headers });
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilotz",
3
- "version": "1.0.0-rc.27",
3
+ "version": "1.0.0-rc.28",
4
4
  "description": "Copilotz: one runtime for Node, Deno, Bun, Cloudflare Workers and the browser.",
5
5
  "keywords": [
6
6
  "agents",
@@ -11,8 +11,9 @@ export declare const MEDIA_TYPE: RegExp;
11
11
  /**
12
12
  * A `contactSend` resource: the Action that lets a contact's message in,
13
13
  * asked as the contact before anything's sent, with where it goes (`thread`,
14
- * when it names one) and what it carries (each file's name, media type and
15
- * size). It refuses it (a limit), or answers where it goes when it names no
14
+ * when it names one), what it carries (each file's name, media type and
15
+ * size), and `to: []` when it goes to nobody (no agent answers it: no turn
16
+ * to pay for). It refuses it (a limit), or answers where it goes when it names no
16
17
  * chat (`thread`: the contact's own) and `transcribe: false` when its audio
17
18
  * goes untranscribed.
18
19
  */
@@ -3,9 +3,11 @@
3
3
  * shared with them: the rules keep them to it). It goes to `to` when given,
4
4
  * else to the agents `@mentioned` in it, else to the sender of the message
5
5
  * it replies to, else to the thread's agents (a new thread's: those it
6
- * names, or who answers new chats in its space). A contact's goes to the
7
- * sender of what it replies to, else the thread's agents: never whom it
8
- * names. It replies only to a message of the same conversation that its
6
+ * names, or who answers new chats in its space); `to: []`, to nobody: it's
7
+ * said, agents read it later, and none answers it (what someone did on a
8
+ * page beside the chat). A contact's goes to the sender of what it replies
9
+ * to, else the thread's agents: never whom it names, though it too may say
10
+ * something to nobody (`to: []`). It replies only to a message of the same conversation that its
9
11
  * sender reads. Only agents answering in
10
12
  * its space answer there: naming one that doesn't fails (`not_here`). Audio
11
13
  * sent with it is transcribed first (what agents read): if that fails,
@@ -51,6 +53,7 @@ async function letIn(ctx, asked) {
51
53
  const answer = await ctx.call(hook.action, {
52
54
  ...(asked.thread ? { thread: asked.thread } : {}),
53
55
  files: asked.files,
56
+ ...(asked.to ? { to: asked.to } : {}),
54
57
  });
55
58
  said = {
56
59
  ...said,
@@ -182,6 +185,8 @@ export const sendAction = defineAction({
182
185
  // A contact talks with whom its chat is with: what it says names nobody else, and the app
183
186
  // lets it in first (its line's limits, the files it takes, its own chat).
184
187
  const contact = ctx.actor?.kind === "contact";
188
+ // A contact names no agent, but may say something to nobody: no agent answers it.
189
+ const nobody = input.to?.length === 0;
185
190
  if (contact && said.length > CONTACT_TEXT) {
186
191
  throw failure("invalid", `A message says ${CONTACT_TEXT} characters at most.`, {
187
192
  public: true,
@@ -195,6 +200,7 @@ export const sendAction = defineAction({
195
200
  ...(f.type ? { type: f.type } : {}),
196
201
  size: sizeOf(f.data),
197
202
  })),
203
+ ...(nobody ? { to: [] } : {}),
198
204
  })
199
205
  : {};
200
206
  const threads = ctx.db.collection("thread");
@@ -210,7 +216,7 @@ export const sendAction = defineAction({
210
216
  const roster = await rosterOf(ctx, where);
211
217
  const members = existing ? existing.agents ?? [] : roster.default;
212
218
  const mentioned = contact ? [] : await mentionsIn(ctx, said, threadId, roster, members);
213
- const asked = (contact ? undefined : input.to) ??
219
+ const asked = (contact ? (nobody ? [] : undefined) : input.to) ??
214
220
  (mentioned.length ? mentioned : replied ? [replied.from] : members);
215
221
  // Agents answer only where they work: one named that doesn't is refused; one gone, left out.
216
222
  const agents = await agentsNamed(ctx, asked);
@@ -102,8 +102,8 @@ export declare const envVar: {
102
102
  queries?: Record<string, import("../../../../runtime/define.js").QueryDef<{
103
103
  [x: string]: unknown;
104
104
  value?: string | undefined;
105
- hint?: string | undefined;
106
105
  app?: string | undefined;
106
+ hint?: string | undefined;
107
107
  sealed?: string | undefined;
108
108
  at: string;
109
109
  by: string;
@@ -1,2 +1,2 @@
1
1
  /** The computer program's version, as `computer.info` and `--version` say it, and its builds are named. */
2
- export declare const VERSION = "1.0.0-rc.27";
2
+ export declare const VERSION = "1.0.0-rc.28";
@@ -1,2 +1,2 @@
1
1
  /** The computer program's version, as `computer.info` and `--version` say it, and its builds are named. */
2
- export const VERSION = "1.0.0-rc.27";
2
+ export const VERSION = "1.0.0-rc.28";
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * ```ts
16
16
  * plugins: [...plugins, await computerDownloads()]
17
- * plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.27" })]
17
+ * plugins: [...plugins, await computerDownloads({ dir: "dist/computer/1.0.0-rc.28" })]
18
18
  * plugins: [...plugins, await computerDownloads({ url: "https://downloads.example.com/computer/" })]
19
19
  * ```
20
20
  */
@@ -21,7 +21,9 @@
21
21
  * (`contact.spent`, as the usage plugin prices them), and what's held for
22
22
  * messages let in not yet charged: each holds an estimate as it goes in
23
23
  * (see shared/budget.ts). Past it, it waits for tomorrow; with no room
24
- * beside what's held, a moment.
24
+ * beside what's held, a moment. A message to nobody (`to: []`: what the
25
+ * visitor did on the page, which no agent answers) holds nothing, since no
26
+ * turn will be charged for it; it counts against the limits all the same.
25
27
  * - **What it may carry:** files only when the line takes them (`files`),
26
28
  * as many and as large as it says, each saying what it is in a media type
27
29
  * of 127 characters at most; audio goes untranscribed unless the line
@@ -80,6 +82,8 @@ export const sendingAction = defineAction({
80
82
  required: ["size"],
81
83
  },
82
84
  },
85
+ /** To nobody: no agent answers it. */
86
+ to: { type: "array", maxItems: 0 },
83
87
  },
84
88
  additionalProperties: false,
85
89
  },
@@ -178,7 +182,7 @@ export const sendingAction = defineAction({
178
182
  }
179
183
  }
180
184
  // Its turn's cost, estimated, held against the line's budget until it's charged.
181
- if (line.budget !== undefined) {
185
+ if (line.budget !== undefined && !input.to) {
182
186
  await hold(system.db.collection("contact_rate"), { name: line.name, budget: line.budget }, contact, now);
183
187
  }
184
188
  const transcribe = line.transcribe ? {} : { transcribe: false };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * One process at a time writes a database: a lease, a row renewed every few
3
+ * seconds, taken before the process opens its stores and let go when it
4
+ * stops; the next process waits for it.
5
+ *
6
+ * A store's epoch already fences an owner another has taken over, but a
7
+ * deploy runs two processes for a while: the new one starts while the old
8
+ * one still serves its browsers' sockets (Cloud Run keeps a retired revision
9
+ * running for as long as a socket stays open), and every write those
10
+ * browsers send is then refused. With the lease, the new process waits and
11
+ * marks it wanted; the holder hears so as it renews (`asked`) and hands over:
12
+ * it stops listening (its sockets close, and browsers reconnect, to the new
13
+ * process), finishes what's running, and lets go. `serve`
14
+ * (`copilotz/web/node`) does all of that.
15
+ *
16
+ * Only a process of a revision at least as new as the holder's asks: the
17
+ * platform may restart the old revision's process while traffic moves over,
18
+ * and that one would otherwise ask for it back. A script that writes while
19
+ * the app runs (a data load) takes it with a revision above any deploy's
20
+ * (`Number.MAX_SAFE_INTEGER`): the app hands over, waits, and takes it back
21
+ * once the script lets go.
22
+ *
23
+ * A process that can't renew it in time has lost it: `lost` says so, and the
24
+ * process stops rather than write beside another.
25
+ */
26
+ import type { PostgresPool } from "./pool.js";
27
+ /** A lease held. */
28
+ export type Lease = {
29
+ /** Stops renewing it and lets it go, for the next process. */
30
+ release(): Promise<void>;
31
+ };
32
+ export type LeaseOptions = {
33
+ /** The schema its table (`copilotz_lease`) is in: `public` by default. */
34
+ schema?: string;
35
+ /** What's held: one per deployment sharing the database. `app` by default. */
36
+ name?: string;
37
+ /** How long it lasts unrenewed, in ms: 15 000 by default. It's renewed every third of it. */
38
+ ttlMs?: number;
39
+ /**
40
+ * Which deploy this process is, a number each deploy raises (Cloud Run's
41
+ * revision's: `app-00015-8bs` is 15): a process asks no newer one to hand
42
+ * over. 0 by default.
43
+ */
44
+ revision?: number;
45
+ /** Stops waiting for it: `lease` rejects with the signal's reason. */
46
+ signal?: AbortSignal;
47
+ /** Said once, when another process holds it and this one waits. */
48
+ waiting?: () => void;
49
+ /** Another process waits for it: close what's open, then let it go. Said once. */
50
+ asked?: () => void;
51
+ /** It was lost: renewing failed past its time, or another process holds it. */
52
+ lost: (why: string) => void;
53
+ };
54
+ /** Takes the lease, once the process holding it lets go (or its time runs out). */
55
+ export declare function lease(pool: PostgresPool, options: LeaseOptions): Promise<Lease>;
@@ -0,0 +1,102 @@
1
+ /** How often a waiting process tries again, in ms, at most. */
2
+ const RETRY = 1_000;
3
+ /** Takes the lease, once the process holding it lets go (or its time runs out). */
4
+ export async function lease(pool, options) {
5
+ const name = options.name ?? "app";
6
+ const ttl = options.ttlMs ?? 15_000;
7
+ const revision = options.revision ?? 0;
8
+ const holder = crypto.randomUUID();
9
+ const db = pool.writes;
10
+ const schema = options.schema ?? "public";
11
+ const quoted = `"${schema.replaceAll('"', '""')}"`;
12
+ const table = `${quoted}.copilotz_lease`;
13
+ // A schema made already is left as it is: making one needs a right on the database the
14
+ // process's role may not have.
15
+ const { rows: found } = await db.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [schema]);
16
+ if (!found.length)
17
+ await db.query(`CREATE SCHEMA IF NOT EXISTS ${quoted}`);
18
+ await db.query(`CREATE TABLE IF NOT EXISTS ${table} (name text PRIMARY KEY, holder text NOT NULL, ` +
19
+ "until timestamptz NOT NULL, wanted timestamptz, revision bigint)").catch(async () => {
20
+ // Two processes making it at once: one wins, and it's there for both.
21
+ await db.query(`SELECT 1 FROM ${table} LIMIT 1`);
22
+ });
23
+ /**
24
+ * Takes it, or renews it: this process's when it's free, run out, or its
25
+ * own already. Says whether another process wants it (within its time).
26
+ */
27
+ const take = async () => {
28
+ const { rows } = await db.query(`INSERT INTO ${table} AS l (name, holder, until, revision) ` +
29
+ "VALUES ($1, $2, now() + $3 * interval '1 millisecond', $4) " +
30
+ "ON CONFLICT (name) DO UPDATE SET holder = EXCLUDED.holder, until = EXCLUDED.until, " +
31
+ "revision = EXCLUDED.revision, " +
32
+ "wanted = CASE WHEN l.holder = EXCLUDED.holder THEN l.wanted END " +
33
+ "WHERE l.until < now() OR l.holder = EXCLUDED.holder " +
34
+ "RETURNING coalesce(wanted > now() - $3 * interval '1 millisecond', false) AS wanted", [name, holder, ttl, revision]);
35
+ return rows.length ? { wanted: Boolean(rows[0].wanted) } : undefined;
36
+ };
37
+ let told = false;
38
+ while (!await take()) {
39
+ options.signal?.throwIfAborted();
40
+ if (!told)
41
+ options.waiting?.();
42
+ told = true;
43
+ // The holder hears it's wanted as it renews, unless it's newer than this process.
44
+ await db.query(`UPDATE ${table} SET wanted = now() ` +
45
+ "WHERE name = $1 AND holder <> $2 AND coalesce(revision, 0) <= $3", [name, holder, revision]).catch(() => { });
46
+ await new Promise((resolve) => {
47
+ const timer = setTimeout(done, Math.min(RETRY, Math.floor(ttl / 3)));
48
+ options.signal?.addEventListener("abort", done, { once: true });
49
+ function done() {
50
+ clearTimeout(timer);
51
+ options.signal?.removeEventListener("abort", done);
52
+ resolve();
53
+ }
54
+ });
55
+ options.signal?.throwIfAborted();
56
+ }
57
+ let renewed = Date.now();
58
+ let asked = false;
59
+ let over = false;
60
+ /** The renewal under way, if any: one at a time, and none once it's let go. */
61
+ let renewing;
62
+ const renew = async () => {
63
+ try {
64
+ const held = await take();
65
+ if (over)
66
+ return;
67
+ if (!held) {
68
+ over = true;
69
+ clearInterval(timer);
70
+ options.lost("another process holds it");
71
+ return;
72
+ }
73
+ renewed = Date.now();
74
+ if (held.wanted && !asked) {
75
+ asked = true;
76
+ options.asked?.();
77
+ }
78
+ }
79
+ catch (error) {
80
+ if (!over && Date.now() - renewed > ttl) {
81
+ over = true;
82
+ clearInterval(timer);
83
+ options.lost(`it couldn't be renewed: ${error.message}`);
84
+ }
85
+ }
86
+ };
87
+ const timer = setInterval(() => {
88
+ renewing ??= renew().finally(() => renewing = undefined);
89
+ }, Math.floor(ttl / 3));
90
+ return {
91
+ async release() {
92
+ if (over)
93
+ return;
94
+ over = true;
95
+ clearInterval(timer);
96
+ // A renewal under way would write the row back after it's gone.
97
+ await renewing;
98
+ await db.query(`DELETE FROM ${table} WHERE name = $1 AND holder = $2`, [name, holder])
99
+ .catch(() => { });
100
+ },
101
+ };
102
+ }
@@ -24,6 +24,7 @@
24
24
  import type { JSONSchema } from "../../../runtime/define.js";
25
25
  import { type IndexSpec, type Inspected, type Store } from "../../../runtime/store.js";
26
26
  import { type PostgresPool } from "./pool.js";
27
+ export { type Lease, lease, type LeaseOptions } from "./lease.js";
27
28
  export { type PostgresPool, postgresPool } from "./pool.js";
28
29
  export { copyTenant, dropTenant, exportTenant, type Location } from "./tenants.js";
29
30
  export declare function postgresStore(options: {
@@ -14,6 +14,7 @@ import { statement } from "../shared/statement.js";
14
14
  import { allowed, alone, confined, connect, noRole, triggers } from "./maintenance.js";
15
15
  import { connections } from "../shared/capped.js";
16
16
  import { upTo, weight } from "../shared/rows.js";
17
+ export { lease } from "./lease.js";
17
18
  export { postgresPool } from "./pool.js";
18
19
  export { copyTenant, dropTenant, exportTenant } from "./tenants.js";
19
20
  const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");