@north-light/sdk 0.3.856 → 0.3.858

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/README.md CHANGED
@@ -113,9 +113,9 @@ CREATE INDEX connection_updated_at_idx ON connection (updated_at, user_id);
113
113
 
114
114
  `save` upserts all fields and sets `updated_at` to the database clock. `listStale(before)` selects connections with `updated_at < before`, oldest first; it is a **last save** timestamp, not necessarily last successful refresh if an app also calls `save` for another reason. For idle-token maintenance, schedule `oauth.refreshIdleConnections({olderThanMs: 30 * 24 * 60 * 60 * 1000})` (for example, daily). It selects stale connections, refreshes under the store lock, reloads there to avoid rotating an already-used token, saves a rotated connection, and reports `{refreshed, refused, failures}`. A connection the directory refuses goes to the client's `onRefusal(refusal)` and is then removed (`remove` deletes the row only while it still holds the refused token); `refusal.kind` is `'removed'` (`grant_removed`: the runtime deleted the app's runs; delete what you store for the person), `'paused'` (`grant_suspended`: nothing was deleted; keep the data until they sign in again), or `'reconnect'` (`refresh_token_expired`, `refresh_token_reused`, `grant_revoked`: nothing was deleted; ask them to sign in again). `refusalOf(error)` returns the same `Refusal` from a refused call's error. Load the signing key `crouter-sdk keygen` wrote with `privateKey: await privateKeyFromFile('local/app-key.json')` (Node), or check one from an environment variable with `parsePrivateJwk(text)`; both refuse anything but a private JWK with a `kid`. The SDK does not start a timer. `listStale` returns connections, not timestamps, so a worker needing a strict cutoff recheck must maintain that policy separately. The table contains credentials: restrict database access, encrypt backups, and delete a row when its user disconnects. PostgreSQL `timestamptz` must be returned as a JavaScript `Date` (the `pg` default parser).
115
115
 
116
- ## PostgreSQL object kit (Node)
116
+ ## Watchable objects (Node)
117
117
 
118
- `PostgresObjectStore` from `@north-light/sdk/stores/postgres` keeps per-person custom objects, the nodes watching them, and a durable publish outbox. `objectKitSchemaSql(tables?)` returns the DDL for the three tables (`watch_object`, `watch_watcher`, `watch_publish` by default) for your migration. `new PostgresObjectStore(pool, {providerId, runtime: (sub) => oauth.appClient(sub), tables?, log?})` has `instance(sub, kind, target, {name, description})`, `watch(objectId, node, machine?)`, `enqueue(client, objectId, {event, summary, state?})` (pass your open transaction's client), `tick(batch?)` and `startPublisher({tick: 5000, batch: 100})`. Delivery is at least once under an advisory lock, backs off to 15 minutes, and drops a row after 24 hours or a permanent refusal (HTTP 400, 404 or 422). Full guide: [Watchable objects](https://sdk.docs.northlight.ai/docs/guides/watchable-objects).
118
+ `WatchKit` from `@north-light/sdk/watch` keeps one canvas object per person and watched item, an outbox written inside your Prisma transaction (`changed`, `moved`, `ended`, `forget`, `connectionEnded`), and an ordered, idempotent delivery loop (`start()`, `nudge()`). `watchableKind` and `unwatchedLeaves` declare the plugin side. The tables are `schema/watch.prisma` plus `sql/001-watch.sql`. Full guide: [Watchable objects](https://sdk.docs.northlight.ai/docs/guides/watchable-objects).
119
119
 
120
120
  ## Reference
121
121
 
package/dist/client.d.ts CHANGED
@@ -53,10 +53,10 @@ export interface CrouterOptions {
53
53
  /** The namespaces of `Crouter` that only the owner's own daemon serves. A person's app listener answers them `404 unknown operation`. */
54
54
  export type OwnerOnly = 'spendLimits' | 'customObjects' | 'models';
55
55
  /** What an app reaches on a person's runtime (the app listener): `Crouter` without the owner-daemon namespaces, and
56
- * `customObjects` narrowed to register/publish/unregister. `Crouter` is assignable to it, so a function that takes `AppClient` takes either. */
56
+ * `customObjects` narrowed to register/publish/unregister/mergeInto. `Crouter` is assignable to it, so a function that takes `AppClient` takes either. */
57
57
  export type AppClient = Omit<Crouter, OwnerOnly> & {
58
58
  /** Register, publish to and unregister the custom objects the app owns (`receive` and `ack` are owner-daemon only). */
59
- readonly customObjects: Pick<CustomObjects, 'register' | 'publish' | 'unregister'>;
59
+ readonly customObjects: Pick<CustomObjects, 'register' | 'publish' | 'unregister' | 'mergeInto'>;
60
60
  };
61
61
  /**
62
62
  * The client an application constructs for a person's runtime. Each namespace below wraps a family of app
@@ -110,7 +110,7 @@ declare const AppCrouter: new (options: CrouterOptions) => AppClient;
110
110
  /** A runtime client on one person's stored connection (`oauth.client(userId)`): an `AppClient` that refreshes its
111
111
  * token through the `OAuth2Client`'s store, plus whose connection it is and the runtime it calls. It offers only what
112
112
  * the person's app listener serves. The owner-daemon namespaces (`spendLimits`, `models`) are absent from its
113
- * type and throw `CrouterError` if reached anyway; `customObjects` is `register`, `publish` and `unregister`.
113
+ * type and throw `CrouterError` if reached anyway; `customObjects` is `register`, `publish`, `unregister` and `mergeInto`.
114
114
  * `request` still sends any route. */
115
115
  export declare class ConnectedCrouter extends AppCrouter {
116
116
  /** The person whose connection this client uses (`user:<id>`). */
@@ -70,7 +70,7 @@ const AppCrouter = Crouter;
70
70
  /** A runtime client on one person's stored connection (`oauth.client(userId)`): an `AppClient` that refreshes its
71
71
  * token through the `OAuth2Client`'s store, plus whose connection it is and the runtime it calls. It offers only what
72
72
  * the person's app listener serves. The owner-daemon namespaces (`spendLimits`, `models`) are absent from its
73
- * type and throw `CrouterError` if reached anyway; `customObjects` is `register`, `publish` and `unregister`.
73
+ * type and throw `CrouterError` if reached anyway; `customObjects` is `register`, `publish`, `unregister` and `mergeInto`.
74
74
  * `request` still sends any route. */
75
75
  export class ConnectedCrouter extends AppCrouter {
76
76
  /** The person whose connection this client uses (`user:<id>`). */
@@ -87,7 +87,7 @@ export class ConnectedCrouter extends AppCrouter {
87
87
  } });
88
88
  }
89
89
  const { customObjects } = this;
90
- Object.defineProperty(this, 'customObjects', { value: { register: customObjects.register.bind(customObjects), publish: customObjects.publish.bind(customObjects), unregister: customObjects.unregister.bind(customObjects) } });
90
+ Object.defineProperty(this, 'customObjects', { value: { register: customObjects.register.bind(customObjects), publish: customObjects.publish.bind(customObjects), unregister: customObjects.unregister.bind(customObjects), mergeInto: customObjects.mergeInto.bind(customObjects) } });
91
91
  }
92
92
  /** Run `crtr <argv…>` in this app's sandbox on the person's runtime (`POST /v1/exec`, scopes `crtr:act` and `crtr:schedule`).
93
93
  * No shell and no stdin; the process starts in the app's files folder. A non-zero exit or a timeout resolves; a refusal
@@ -1,4 +1,4 @@
1
- import { type AckCustomDeliveriesResponseDTO, type PublishCustomObjectRequestDTO, type PublishCustomObjectResponseDTO, type QueueLineDTO, type RegisterCustomObjectRequestDTO, type RegisterCustomObjectResponseDTO } from '@north-light/api';
1
+ import { type AckCustomDeliveriesResponseDTO, type MergeCustomObjectResponseDTO, type PublishCustomObjectRequestDTO, type PublishCustomObjectResponseDTO, type QueueLineDTO, type RegisterCustomObjectRequestDTO, type RegisterCustomObjectResponseDTO } from '@north-light/api';
2
2
  import type { RequestOptions } from '../types.js';
3
3
  import type { Request } from './request.js';
4
4
  /** Queue streams replay every pending delivery on connect. `after` is accepted for compatibility but ignored for pending work. */
@@ -18,6 +18,8 @@ export declare class CustomObjects {
18
18
  unregister(ref: string, options?: RequestOptions & {
19
19
  onlyIfUnwatched?: boolean;
20
20
  }): Promise<void>;
21
+ /** Move every watcher of `ref` onto `into` and unregister `ref`, in one write. Both must be live and have the same owner. `404` when `ref` is already gone. */
22
+ mergeInto(ref: string, into: string, options?: RequestOptions): Promise<MergeCustomObjectResponseDTO>;
21
23
  ack(ref: string, deliveryIds: string[], options?: RequestOptions): Promise<AckCustomDeliveriesResponseDTO>;
22
24
  receive(ref: string, options?: ReceiveOptions): CustomDeliveryStream;
23
25
  }
@@ -19,6 +19,10 @@ export class CustomObjects {
19
19
  const { onlyIfUnwatched, ...request } = options ?? {};
20
20
  return this.request('DELETE', onlyIfUnwatched === true ? withQuery(routes.customObject(ref), { only_if_unwatched: '1' }) : routes.customObject(ref), undefined, request);
21
21
  }
22
+ /** Move every watcher of `ref` onto `into` and unregister `ref`, in one write. Both must be live and have the same owner. `404` when `ref` is already gone. */
23
+ mergeInto(ref, into, options) {
24
+ return this.request('POST', routes.customObjectMergeInto(ref), { into }, options);
25
+ }
22
26
  ack(ref, deliveryIds, options) {
23
27
  return this.request('POST', routes.customObjectAck(ref), { delivery_ids: deliveryIds }, options);
24
28
  }
@@ -2,7 +2,7 @@
2
2
  name: northlight
3
3
  description: "Use when building, debugging or shipping an app that signs people in with Northlight, starts runs on their Northlight runtime, or calls Northlight providers (sms, search, integrations, context, device) with @north-light/sdk."
4
4
  metadata:
5
- sdk-version: "0.3.856"
5
+ sdk-version: "0.3.858"
6
6
  ---
7
7
 
8
8
  # Building a Northlight app
@@ -27,7 +27,7 @@ Never text a person first: Comms refuses a send to anyone who has not texted you
27
27
 
28
28
  ## First: check this skill matches the SDK
29
29
 
30
- This skill is for SDK version `0.3.856`. If the project has `node_modules/@north-light/sdk/package.json`, compare its `version` with that number. If they differ, run `npx @north-light/sdk skill` in the project, then read the rewritten `.agents/skills/northlight/SKILL.md` (or `.claude/skills/northlight/SKILL.md`) instead of this copy. It needs no account. A project that has no SDK yet starts with `npx @north-light/sdk@latest init <dir>`.
30
+ This skill is for SDK version `0.3.858`. If the project has `node_modules/@north-light/sdk/package.json`, compare its `version` with that number. If they differ, run `npx @north-light/sdk skill` in the project, then read the rewritten `.agents/skills/northlight/SKILL.md` (or `.claude/skills/northlight/SKILL.md`) instead of this copy. It needs no account. A project that has no SDK yet starts with `npx @north-light/sdk@latest init <dir>`.
31
31
 
32
32
  ## Where things run
33
33
 
@@ -1,4 +1,3 @@
1
- import type { AppClient } from '../client.js';
2
1
  import type { Connection, ConnectionStore } from '../oauth/index.js';
3
2
  interface QueryResult {
4
3
  rows: Record<string, unknown>[];
@@ -30,89 +29,4 @@ export declare class PostgresConnectionStore implements ConnectionStore {
30
29
  /** Connections not saved since `before`, oldest first. Save activity is not necessarily refresh activity. */
31
30
  listStale(before: Date): Promise<Connection[]>;
32
31
  }
33
- /** Anything with `query`: a `pg.Pool`, a `pg.PoolClient`, or a client inside the caller's open transaction. */
34
- export interface PostgresQueryable {
35
- query(sql: string, values?: unknown[]): Promise<QueryResult>;
36
- }
37
- /** The part of a person's runtime client the kit uses. `ConnectedCrouter` (`oauth.appClient(sub)`) satisfies it. */
38
- export type ObjectRuntime = Pick<AppClient, 'customObjects' | 'canvas'>;
39
- export interface ObjectKitTables {
40
- /** One row per (person, kind, target): the registered custom object. Default `watch_object`. */
41
- object?: string;
42
- /** Nodes linked to an object. Default `watch_watcher`. */
43
- watcher?: string;
44
- /** The publish outbox. Default `watch_publish`. */
45
- publish?: string;
46
- }
47
- /** The DDL the app migrates for the object kit. Table names follow `ObjectKitTables` (lowercase identifiers, optionally schema-qualified). */
48
- export declare function objectKitSchemaSql(tables?: ObjectKitTables): string;
49
- export interface PostgresObjectStoreOptions {
50
- /** The app's provider id (`CROUTER_CLIENT_ID`). A kind `problem` registers as the custom-object kind `<providerId>.problem`, which the plugin's `objectKinds` declares. */
51
- providerId: string;
52
- /** The app's client on a person's runtime, e.g. `(sub) => oauth.appClient(sub)`. */
53
- runtime(sub: string): Promise<ObjectRuntime>;
54
- tables?: ObjectKitTables;
55
- /** Receives retry and drop notices from the publisher. Default `console`. */
56
- log?: {
57
- warn(message: string): void;
58
- error(message: string, error?: unknown): void;
59
- };
60
- }
61
- export interface ObjectInstance {
62
- objectId: string;
63
- sub: string;
64
- kind: string;
65
- target: string;
66
- name: string;
67
- }
68
- export interface PublishRequest {
69
- event: string;
70
- /** Truncated to 500 characters. */
71
- summary: string;
72
- state?: Record<string, unknown> | null;
73
- }
74
- export interface PublisherOptions {
75
- /** Milliseconds between ticks. Default 5000. */
76
- tick?: number;
77
- /** Rows delivered per tick. Default 100. */
78
- batch?: number;
79
- }
80
- export interface Publisher {
81
- /** Stops the timer and waits for a tick in progress. */
82
- stop(): Promise<void>;
83
- }
84
- /** A publish not delivered this long after it was enqueued is dropped. */
85
- export declare const PUBLISH_WINDOW_MS: number;
86
- /**
87
- * Per-person custom objects on each person's hosted runtime, the nodes that watch them, and an at-least-once publish
88
- * outbox. The app migrates the tables (`objectKitSchemaSql`), registers the kinds in its plugin, calls `instance` and
89
- * `watch` from its commands, calls `enqueue` inside the transaction of the write an event records, and runs
90
- * `startPublisher` in each process.
91
- */
92
- export declare class PostgresObjectStore {
93
- private readonly pool;
94
- private readonly options;
95
- private readonly object;
96
- private readonly watcher;
97
- private readonly publish;
98
- private readonly lockKey;
99
- private readonly log;
100
- constructor(pool: PostgresPool, options: PostgresObjectStoreOptions);
101
- /** The person's object for (kind, target), registered on their runtime the first time. A concurrent first call registers a second object; the row that committed first wins and the loser is unregistered. `target` is `''` for a kind with one object per person. */
102
- instance(sub: string, kind: string, target: string, meta: {
103
- name: string;
104
- description: string;
105
- }): Promise<ObjectInstance>;
106
- /** Links `node` to the object, then records the link. A node the runtime does not know rejects with `NotFoundError`. */
107
- watch(objectId: string, node: string): Promise<void>;
108
- /** Adds a publish row. Pass the client of the caller's open transaction so the row exists exactly when the write it records does. */
109
- enqueue(client: PostgresQueryable, objectId: string, event: PublishRequest): Promise<void>;
110
- /** Delivers due rows once under the advisory lock; false when another process holds it. */
111
- tick(batch?: number): Promise<boolean>;
112
- /** Runs `tick` every `tick` ms (default 5000, 100 rows). A failed tick is logged and the next one runs. */
113
- startPublisher(options?: PublisherOptions): Publisher;
114
- private find;
115
- private deliver;
116
- private end;
117
- }
118
32
  export {};
@@ -1,7 +1,4 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { randomUUID } from 'node:crypto';
3
- import { customObjectPublishFailure } from '@north-light/plugin';
4
- import { APIError } from '../errors.js';
5
2
  function tableName(name) {
6
3
  const parts = name.split('.');
7
4
  if (parts.length < 1 || parts.length > 2 || parts.some((part) => !/^[a-z_][a-z_0-9]*$/.test(part))) {
@@ -93,182 +90,3 @@ export class PostgresConnectionStore {
93
90
  return result.rows.map(toConnection);
94
91
  }
95
92
  }
96
- const DEFAULT_TABLES = { object: 'watch_object', watcher: 'watch_watcher', publish: 'watch_publish' };
97
- /** The DDL the app migrates for the object kit. Table names follow `ObjectKitTables` (lowercase identifiers, optionally schema-qualified). */
98
- export function objectKitSchemaSql(tables = {}) {
99
- const t = { ...DEFAULT_TABLES, ...tables };
100
- const [object, watcher, publish] = [t.object, t.watcher, t.publish].map(tableName);
101
- const base = t.publish.split('.').pop();
102
- return `CREATE TABLE ${object} (
103
- object_id text PRIMARY KEY,
104
- sub text NOT NULL,
105
- kind text NOT NULL,
106
- target text NOT NULL,
107
- name text NOT NULL,
108
- created_at timestamptz NOT NULL DEFAULT now(),
109
- UNIQUE (sub, kind, target)
110
- );
111
- CREATE TABLE ${watcher} (
112
- object_id text NOT NULL REFERENCES ${object} (object_id) ON DELETE CASCADE,
113
- node text NOT NULL,
114
- machine text NOT NULL DEFAULT '',
115
- PRIMARY KEY (object_id, node, machine)
116
- );
117
- CREATE TABLE ${publish} (
118
- id text PRIMARY KEY,
119
- object_id text NOT NULL REFERENCES ${object} (object_id) ON DELETE CASCADE,
120
- event text NOT NULL,
121
- summary text NOT NULL,
122
- state jsonb,
123
- status text NOT NULL DEFAULT 'pending',
124
- attempts integer NOT NULL DEFAULT 0,
125
- last_error text,
126
- next_attempt_at timestamptz NOT NULL DEFAULT now(),
127
- created_at timestamptz NOT NULL DEFAULT now()
128
- );
129
- CREATE INDEX "${base}_due_idx" ON ${publish} (status, next_attempt_at);
130
- CREATE INDEX "${base}_object_idx" ON ${publish} (object_id);
131
- `;
132
- }
133
- /** A publish not delivered this long after it was enqueued is dropped. */
134
- export const PUBLISH_WINDOW_MS = 24 * 60 * 60 * 1000;
135
- const MAX_BACKOFF_MS = 15 * 60 * 1000;
136
- /**
137
- * Per-person custom objects on each person's hosted runtime, the nodes that watch them, and an at-least-once publish
138
- * outbox. The app migrates the tables (`objectKitSchemaSql`), registers the kinds in its plugin, calls `instance` and
139
- * `watch` from its commands, calls `enqueue` inside the transaction of the write an event records, and runs
140
- * `startPublisher` in each process.
141
- */
142
- export class PostgresObjectStore {
143
- pool;
144
- options;
145
- object;
146
- watcher;
147
- publish;
148
- lockKey;
149
- log;
150
- constructor(pool, options) {
151
- this.pool = pool;
152
- this.options = options;
153
- const t = { ...DEFAULT_TABLES, ...options.tables };
154
- this.object = tableName(t.object);
155
- this.watcher = tableName(t.watcher);
156
- this.publish = tableName(t.publish);
157
- this.lockKey = `north-light-sdk-object-publish:${t.publish}`;
158
- this.log = options.log ?? { warn: (m) => console.warn(m), error: (m, e) => console.error(m, e) };
159
- }
160
- /** The person's object for (kind, target), registered on their runtime the first time. A concurrent first call registers a second object; the row that committed first wins and the loser is unregistered. `target` is `''` for a kind with one object per person. */
161
- async instance(sub, kind, target, meta) {
162
- const existing = await this.find(sub, kind, target);
163
- if (existing)
164
- return existing;
165
- const runtime = await this.options.runtime(sub);
166
- const registered = await runtime.customObjects.register({
167
- kind: `${this.options.providerId}.${kind}`,
168
- name: meta.name,
169
- description: meta.description,
170
- privacy: 'private',
171
- });
172
- const inserted = await this.pool.query(`INSERT INTO ${this.object} (object_id, sub, kind, target, name) VALUES ($1, $2, $3, $4, $5)
173
- ON CONFLICT (sub, kind, target) DO NOTHING RETURNING object_id`, [registered.id, sub, kind, target, meta.name]);
174
- if (inserted.rows.length > 0)
175
- return { objectId: registered.id, sub, kind, target, name: meta.name };
176
- const winner = await this.find(sub, kind, target);
177
- if (!winner)
178
- throw new Error(`object ${sub}/${kind}/${target} vanished during registration`);
179
- if (winner.objectId !== registered.id)
180
- await runtime.customObjects.unregister(registered.id);
181
- return winner;
182
- }
183
- /** Links `node` to the object, then records the link. A node the runtime does not know rejects with `NotFoundError`. */
184
- async watch(objectId, node) {
185
- const found = await this.pool.query(`SELECT sub FROM ${this.object} WHERE object_id = $1`, [objectId]);
186
- const sub = found.rows[0]?.sub;
187
- if (sub === undefined)
188
- throw new Error(`no object ${objectId}`);
189
- const runtime = await this.options.runtime(sub);
190
- await runtime.canvas.watch(objectId, { watcher: node });
191
- await this.pool.query(`INSERT INTO ${this.watcher} (object_id, node, machine) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [objectId, node, '']);
192
- }
193
- /** Adds a publish row. Pass the client of the caller's open transaction so the row exists exactly when the write it records does. */
194
- async enqueue(client, objectId, event) {
195
- await client.query(`INSERT INTO ${this.publish} (id, object_id, event, summary, state) VALUES ($1, $2, $3, $4, $5::jsonb)`, [randomUUID(), objectId, event.event, event.summary.slice(0, 500), event.state == null ? null : JSON.stringify(event.state)]);
196
- }
197
- /** Delivers due rows once under the advisory lock; false when another process holds it. */
198
- async tick(batch = 100) {
199
- const lock = await this.pool.connect();
200
- try {
201
- const got = await lock.query('SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS ok', [this.lockKey]);
202
- if (!got.rows[0]?.ok)
203
- return false;
204
- try {
205
- const due = await this.pool.query(`SELECT p.id, p.object_id, o.sub, p.event, p.summary, p.state, p.attempts, p.created_at
206
- FROM ${this.publish} p JOIN ${this.object} o ON o.object_id = p.object_id
207
- WHERE p.status = 'pending' AND p.next_attempt_at <= now()
208
- ORDER BY p.created_at ASC, p.id ASC LIMIT $1`, [batch]);
209
- for (const row of due.rows)
210
- await this.deliver(row);
211
- }
212
- finally {
213
- await lock.query('SELECT pg_advisory_unlock(hashtextextended($1, 0))', [this.lockKey]);
214
- }
215
- return true;
216
- }
217
- finally {
218
- lock.release();
219
- }
220
- }
221
- /** Runs `tick` every `tick` ms (default 5000, 100 rows). A failed tick is logged and the next one runs. */
222
- startPublisher(options = {}) {
223
- let running;
224
- const timer = setInterval(() => {
225
- if (running)
226
- return; // a pass is still delivering: skip this firing
227
- running = this.tick(options.batch)
228
- .catch((error) => this.log.error('object publish tick failed', error))
229
- .finally(() => { running = undefined; });
230
- }, options.tick ?? 5_000);
231
- timer.unref();
232
- return {
233
- stop: async () => {
234
- clearInterval(timer);
235
- await running;
236
- },
237
- };
238
- }
239
- async find(sub, kind, target) {
240
- const result = await this.pool.query(`SELECT object_id, name FROM ${this.object} WHERE sub = $1 AND kind = $2 AND target = $3`, [sub, kind, target]);
241
- const row = result.rows[0];
242
- return row ? { objectId: row.object_id, sub, kind, target, name: row.name } : null;
243
- }
244
- async deliver(row) {
245
- const now = Date.now();
246
- if (now - row.created_at.getTime() > PUBLISH_WINDOW_MS)
247
- return this.end(row, 'dropped', '24 h window elapsed');
248
- try {
249
- const runtime = await this.options.runtime(row.sub);
250
- await runtime.customObjects.publish(row.object_id, {
251
- event: row.event,
252
- summary: row.summary,
253
- ...(row.state == null ? {} : { state: row.state }),
254
- });
255
- }
256
- catch (error) {
257
- const message = error instanceof Error ? error.message : String(error);
258
- const refusal = error instanceof APIError ? { status: error.status, code: error.code } : undefined;
259
- if (refusal && customObjectPublishFailure(refusal) === 'drop') {
260
- return this.end(row, 'dropped', `${refusal.code}: ${message}`);
261
- }
262
- const attempts = row.attempts + 1;
263
- await this.pool.query(`UPDATE ${this.publish} SET attempts = $2, last_error = $3, next_attempt_at = now() + $4 * interval '1 millisecond' WHERE id = $1`, [row.id, attempts, message.slice(0, 500), Math.min(2 ** attempts * 10_000, MAX_BACKOFF_MS)]);
264
- this.log.warn(`publish ${row.id} attempt ${attempts} failed: ${message}`);
265
- return;
266
- }
267
- await this.end(row, 'done', null);
268
- }
269
- async end(row, status, lastError) {
270
- if (status === 'dropped')
271
- this.log.warn(`dropped publish ${row.id}: ${lastError}`);
272
- await this.pool.query(`UPDATE ${this.publish} SET status = $2, last_error = $3, attempts = attempts + 1 WHERE id = $1`, [row.id, status, lastError]);
273
- }
274
- }
package/dist/version.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** This SDK's release version. Informational only: compatibility is the contract level, not this number. */
2
- export declare const SDK_VERSION = "0.3.856";
2
+ export declare const SDK_VERSION = "0.3.858";
3
3
  /** The release sent in `Crouter-Minimum-Runtime-Version` on every request. It is frozen, so a runtime from before the
4
4
  * contract level existed (which only knows this header) refuses this SDK, while every later runtime accepts it. */
5
5
  export declare const LEGACY_FLOOR = "0.3.423";
package/dist/version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // SDK_VERSION is written by scripts/release-version.mjs on every release; do not edit by hand.
2
2
  /** This SDK's release version. Informational only: compatibility is the contract level, not this number. */
3
- export const SDK_VERSION = '0.3.856';
3
+ export const SDK_VERSION = '0.3.858';
4
4
  // LEGACY_FLOOR is written once by `scripts/contract.mjs release`, at the first release that carries the contract level
5
5
  // (the `0.0.0` placeholder is replaced there and never again); do not edit by hand.
6
6
  /** The release sent in `Crouter-Minimum-Runtime-Version` on every request. It is frozen, so a runtime from before the
@@ -0,0 +1,2 @@
1
+ export { WatchKit, WatchOps, WatchRefusedError, type WatchKitOptions, type WatchEventInput, type WatchObjectMeta, type WatchedObject, type WatchSql } from './kit.js';
2
+ export { watchableKind, unwatchedLeaves, WATCH_UNWATCHED_KEY } from './plugin.js';
@@ -0,0 +1,4 @@
1
+ // Watchable objects: one canvas object per person and watched item, an outbox written in the app's transaction, and an
2
+ // ordered, idempotent delivery loop to the person's hosted runtime. Tables: `schema/watch.prisma` and `sql/001-watch.sql`.
3
+ export { WatchKit, WatchOps, WatchRefusedError } from './kit.js';
4
+ export { watchableKind, unwatchedLeaves, WATCH_UNWATCHED_KEY } from './plugin.js';
@@ -0,0 +1,147 @@
1
+ import type { ConnectedCrouter } from '../oauth/index.js';
2
+ /** The part of Prisma (a client or an interactive-transaction client) the kit uses: tagged-template raw SQL. */
3
+ export interface WatchSql {
4
+ $queryRaw<T = unknown>(query: TemplateStringsArray, ...values: any[]): Promise<T>;
5
+ $executeRaw(query: TemplateStringsArray, ...values: any[]): Promise<number>;
6
+ }
7
+ export interface WatchKitOptions {
8
+ /** The app's provider id (`CROUTER_CLIENT_ID`). Kind `intent` registers as the custom-object kind `<providerId>.intent`. */
9
+ providerId: string;
10
+ /**
11
+ * The app's client on a person's runtime: `(sub) => oauth.appClient(sub)`. Only the SDK's own client is accepted: it sends
12
+ * the contract level on every request and refuses (426) a runtime that does not serve publish keys, merge-into and
13
+ * conditional unregister, so the kit never talks to a runtime it cannot rely on.
14
+ */
15
+ runtime(sub: string): Promise<ConnectedCrouter>;
16
+ /** The app's Prisma client. */
17
+ db: WatchSql;
18
+ /** Name and description of the object for an item; used by `watch` when it gets none, and when the kit registers a surviving object after a merge. Names must be unique for the person. */
19
+ describe(kind: string, target: string): WatchObjectMeta | Promise<WatchObjectMeta>;
20
+ /** Receives every warning and error the kit raises (a dropped event, an object retrying for over 24 h, a failed pass). Pass Sentry's capture here. */
21
+ report(message: string, error?: unknown): void;
22
+ }
23
+ /** What a registered object is called, and who may see it (`private` unless set). */
24
+ export interface WatchObjectMeta {
25
+ name: string;
26
+ description: string;
27
+ privacy?: 'public' | 'private';
28
+ }
29
+ export interface WatchEventInput {
30
+ event: string;
31
+ /** Truncated to 500 characters. */
32
+ summary: string;
33
+ state?: unknown;
34
+ /** One logical event: with the same `dedupe`, the runtime publishes it once per object, even when the app queues it again after the first was delivered. */
35
+ dedupe?: string;
36
+ }
37
+ export interface WatchedObject {
38
+ objectId: string;
39
+ name: string;
40
+ }
41
+ /** `watch` refuses with these: the status and wording an app maps onto its own error type. */
42
+ export declare class WatchRefusedError extends Error {
43
+ readonly status: number;
44
+ readonly next?: string | undefined;
45
+ constructor(status: number, message: string, next?: string | undefined);
46
+ }
47
+ type Outcome = 'connection' | 'gone' | 'drop' | 'retry';
48
+ /** What the runtime's answer to one call means (the refusal table of the design). */
49
+ export declare function classify(error: unknown): Outcome;
50
+ /**
51
+ * The transaction-only operations of the kit. They need no runtime client, so a writer that only records changes
52
+ * (a workspace service, a migration) constructs `new WatchOps()` instead of a full `WatchKit`. `WatchKit` extends it.
53
+ *
54
+ * `changed`, `moved`, `ended`, `forget` and `revoke` lock the object's row until their transaction commits, so
55
+ * events of one object get sequence numbers in commit order and a phase change sees every earlier event committed.
56
+ */
57
+ export declare class WatchOps {
58
+ /** Queues `event` for every live object of (kind, target), across every person. Answers how many objects got it; 0 when no one watches. */
59
+ changed(tx: WatchSql, kind: string, target: string, event: WatchEventInput): Promise<number>;
60
+ /** Queues `event` for one person's live object of (kind, target) only, for events that differ per watcher. Answers 1, or 0 when that person has no live object. */
61
+ changedFor(tx: WatchSql, sub: string, kind: string, target: string, event: WatchEventInput): Promise<number>;
62
+ private queue;
63
+ /** Marks every object of (kind, from) as merging into `to`: once its queued events are delivered, its watchers move to the survivor's object. Objects already merging into `from` now merge into `to`. */
64
+ moved(tx: WatchSql, kind: string, from: string, to: string): Promise<void>;
65
+ /** Marks every object of (kind, target) as ending: it is unregistered once its queued events are delivered. Objects still merging into `target` end too, so a merge never recreates an ended item. */
66
+ ended(tx: WatchSql, kind: string, target: string): Promise<void>;
67
+ /** Drops every object and queued event of a person whose sign-in or hosted runtime is gone. */
68
+ connectionEnded(tx: WatchSql, sub: string): Promise<void>;
69
+ /** Marks a person's objects as ending (a member leaves a workspace); queued events are still delivered first. Narrow with `kind` and `workspace` (the value given to `watch`). */
70
+ forget(tx: WatchSql, sub: string, kind?: string, filter?: {
71
+ workspace?: string;
72
+ }): Promise<void>;
73
+ /** The person lost access to one item (a repository they can no longer read): discards that person's queued events and retires the object. Other people's objects of the item are untouched. */
74
+ revoke(tx: WatchSql, sub: string, kind: string, target: string): Promise<void>;
75
+ }
76
+ /**
77
+ * Per-person custom objects on each person's hosted runtime, an outbox written inside the app's transactions, and an
78
+ * ordered, idempotent delivery loop. The app migrates the tables, declares its kinds with `watchableKind`, calls
79
+ * `watch` from its watch leaf, calls `changed`/`moved`/`ended` inside the transaction of each domain write, and calls
80
+ * `start()` once at bootstrap.
81
+ *
82
+ * Ordering: `changed`, `moved`, `ended`, `forget` and `revoke` lock the object's row until their transaction commits, so
83
+ * events of one object get sequence numbers in commit order and a phase change sees every earlier event committed.
84
+ * Ownership: a worker claims one object at a time with a lease token, renews it before each step and writes only while it holds it.
85
+ */
86
+ export declare class WatchKit extends WatchOps {
87
+ private readonly options;
88
+ private timer;
89
+ private running;
90
+ private again;
91
+ private stopping;
92
+ private lastCleanup;
93
+ constructor(options: WatchKitOptions);
94
+ private get db();
95
+ private kindId;
96
+ /**
97
+ * Finds or registers the person's object for (kind, target), then links the calling node to it. The app checks access to the item first.
98
+ * `recheck` closes the first-watch race: the app checked access and resolved the target before this call, and a member removal
99
+ * (`forget`) or merge (`moved`) may have committed before the object's row existed, so neither saw it. After the row is
100
+ * committed (from then on `forget`/`moved` see it) the kit calls `recheck`, which must repeat the app's access check and
101
+ * answer false when the item is no longer reachable under `target` (access lost, merged away, deleted). On false the kit
102
+ * removes the new object and refuses with 409. It is called only when this call created the object.
103
+ * `workspace` groups the person's objects so `forget` can retire them by workspace, whatever the item ids look like.
104
+ */
105
+ watch(sub: string, caller: {
106
+ node?: string | undefined;
107
+ }, kind: string, target: string, options?: {
108
+ meta?: WatchObjectMeta;
109
+ workspace?: string;
110
+ recheck?: () => Promise<boolean>;
111
+ }): Promise<WatchedObject>;
112
+ /** Unregisters `objectId` if no node watches it: `missing` (it was already gone), `unregistered`, or `watched` (left untouched). */
113
+ private probe;
114
+ /** The person's runtime client; a person with no hosted runtime or no sign-in gets a refusal that says what to do. */
115
+ private mint;
116
+ /** The person's object for (kind, target), registered the first time. A concurrent first call registers a second object; the row that committed first wins and the loser is unregistered. */
117
+ private ensure;
118
+ private find;
119
+ /** The runtime says the object's last watcher left. Unregisters it only if it is still unwatched, then drops the row and its queued events. A watch that came back in between keeps both. Throws on any other failure so the runtime retries. */
120
+ unwatched(input: {
121
+ id: string;
122
+ sub?: string;
123
+ }): Promise<void>;
124
+ /** Runs delivery passes every 2 s and on `nudge()`. Call once at bootstrap. Objects that predate the unwatched hook are checked by the first passes. */
125
+ start(): void;
126
+ /** Stops the timer and waits for the pass in progress; no further pass starts. */
127
+ stop(): Promise<void>;
128
+ /** Makes a pass run soon; passes never overlap. Call after the commit of a transaction that queued events. */
129
+ nudge(): void;
130
+ /** One delivery pass: workers claim one due object at a time and deliver its events in order. Resolves when every worker is done. */
131
+ tick(): Promise<void>;
132
+ /** Takes the lease of one due object. */
133
+ private claim;
134
+ /** Extends the lease and reads the object's current state; undefined when this worker no longer holds the lease. */
135
+ private renew;
136
+ private deliver;
137
+ /** Publishes the head event. True when the loop may go on to the next event. */
138
+ private publish;
139
+ /** Moves the object's watchers onto the surviving object of `target` (following any merge that already moved the target on), or retires it when the survivor ended. */
140
+ private finishMerge;
141
+ /** Deletes the claimed object's row (and its queued events) while this worker still holds the lease. */
142
+ private remove;
143
+ /** Applies the refusal table to a failed call on `claim`. */
144
+ private settle;
145
+ private release;
146
+ }
147
+ export {};
@@ -0,0 +1,442 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { APIError, NoHostedRuntimeError, NotGrantedError } from '../errors.js';
3
+ /** `watch` refuses with these: the status and wording an app maps onto its own error type. */
4
+ export class WatchRefusedError extends Error {
5
+ status;
6
+ next;
7
+ constructor(status, message, next) {
8
+ super(message);
9
+ this.status = status;
10
+ this.next = next;
11
+ this.name = 'WatchRefusedError';
12
+ }
13
+ }
14
+ const TICK_MS = 2_000;
15
+ const LEASE_S = 60;
16
+ const PASS_LIMIT = 50;
17
+ const CONCURRENCY = 8;
18
+ const MAX_BACKOFF_MS = 15 * 60 * 1000;
19
+ const BUSY_RETRY_S = 1;
20
+ const STUCK_MS = 24 * 60 * 60 * 1000;
21
+ const DROPPED_KEEP_DAYS = 30;
22
+ const WATCH_ATTEMPTS = 3;
23
+ const CHAIN_LIMIT = 16;
24
+ /** What the runtime's answer to one call means (the refusal table of the design). */
25
+ export function classify(error) {
26
+ if (error instanceof NoHostedRuntimeError || error instanceof NotGrantedError)
27
+ return 'connection';
28
+ if (error instanceof APIError) {
29
+ if (error.status === 401 || (error.status === 403 && error.code === 'grant_revoked'))
30
+ return 'connection';
31
+ if (error.status === 404 && error.code === 'not_found')
32
+ return 'gone';
33
+ if ((error.status === 400 && error.code === 'unknown_event') || (error.status === 409 && error.code === 'kind_inert'))
34
+ return 'retry';
35
+ if (error.status === 400 || error.status === 422)
36
+ return 'drop';
37
+ }
38
+ return 'retry';
39
+ }
40
+ const isNotFound = (error) => error instanceof APIError && error.status === 404 && error.code === 'not_found';
41
+ const isWatched = (error) => error instanceof APIError && error.status === 409 && error.code === 'watched';
42
+ const message = (error) => (error instanceof Error ? error.message : String(error)).slice(0, 500);
43
+ /**
44
+ * The transaction-only operations of the kit. They need no runtime client, so a writer that only records changes
45
+ * (a workspace service, a migration) constructs `new WatchOps()` instead of a full `WatchKit`. `WatchKit` extends it.
46
+ *
47
+ * `changed`, `moved`, `ended`, `forget` and `revoke` lock the object's row until their transaction commits, so
48
+ * events of one object get sequence numbers in commit order and a phase change sees every earlier event committed.
49
+ */
50
+ export class WatchOps {
51
+ // ---- the app's domain writes (pass the Prisma transaction client) -----------------------------------------------
52
+ /** Queues `event` for every live object of (kind, target), across every person. Answers how many objects got it; 0 when no one watches. */
53
+ async changed(tx, kind, target, event) {
54
+ return this.queue(tx, null, kind, target, event);
55
+ }
56
+ /** Queues `event` for one person's live object of (kind, target) only, for events that differ per watcher. Answers 1, or 0 when that person has no live object. */
57
+ async changedFor(tx, sub, kind, target, event) {
58
+ return this.queue(tx, sub, kind, target, event);
59
+ }
60
+ async queue(tx, sub, kind, target, event) {
61
+ const state = event.state == null ? null : JSON.stringify(event.state);
62
+ const dedupe = event.dedupe ?? null;
63
+ return tx.$executeRaw `
64
+ WITH locked AS MATERIALIZED (SELECT object_id FROM watch_object WHERE kind = ${kind} AND target = ${target} AND phase = 'live' AND (${sub}::text IS NULL OR sub = ${sub}) ORDER BY object_id FOR UPDATE)
65
+ INSERT INTO watch_event (object_id, event, summary, state, dedupe)
66
+ SELECT object_id, ${event.event}, ${event.summary.slice(0, 500)}, ${state}::jsonb, ${dedupe} FROM locked
67
+ ON CONFLICT DO NOTHING`;
68
+ }
69
+ /** Marks every object of (kind, from) as merging into `to`: once its queued events are delivered, its watchers move to the survivor's object. Objects already merging into `from` now merge into `to`. */
70
+ async moved(tx, kind, from, to) {
71
+ if (from === to)
72
+ return;
73
+ await tx.$executeRaw `
74
+ WITH locked AS MATERIALIZED (SELECT object_id, target FROM watch_object WHERE kind = ${kind} AND target <> ${to} AND ((target = ${from} AND phase = 'live') OR (phase = 'merging' AND merge_target = ${from})) ORDER BY object_id FOR UPDATE)
75
+ UPDATE watch_object o SET phase = 'merging', merge_target = ${to}, next_attempt_at = NULL FROM locked WHERE o.object_id = locked.object_id`;
76
+ }
77
+ /** Marks every object of (kind, target) as ending: it is unregistered once its queued events are delivered. Objects still merging into `target` end too, so a merge never recreates an ended item. */
78
+ async ended(tx, kind, target) {
79
+ await tx.$executeRaw `
80
+ WITH locked AS MATERIALIZED (SELECT object_id FROM watch_object WHERE kind = ${kind} AND phase <> 'ending' AND (target = ${target} OR (phase = 'merging' AND merge_target = ${target})) ORDER BY object_id FOR UPDATE)
81
+ UPDATE watch_object o SET phase = 'ending', merge_target = NULL, next_attempt_at = NULL FROM locked WHERE o.object_id = locked.object_id`;
82
+ }
83
+ /** Drops every object and queued event of a person whose sign-in or hosted runtime is gone. */
84
+ async connectionEnded(tx, sub) {
85
+ await tx.$executeRaw `DELETE FROM watch_object WHERE sub = ${sub}`;
86
+ }
87
+ /** Marks a person's objects as ending (a member leaves a workspace); queued events are still delivered first. Narrow with `kind` and `workspace` (the value given to `watch`). */
88
+ async forget(tx, sub, kind, filter = {}) {
89
+ const k = kind ?? null;
90
+ const workspace = filter.workspace ?? null;
91
+ await tx.$executeRaw `
92
+ WITH locked AS MATERIALIZED (SELECT object_id FROM watch_object WHERE sub = ${sub} AND phase <> 'ending' AND (${k}::text IS NULL OR kind = ${k}) AND (${workspace}::text IS NULL OR workspace = ${workspace}) ORDER BY object_id FOR UPDATE)
93
+ UPDATE watch_object o SET phase = 'ending', merge_target = NULL, next_attempt_at = NULL FROM locked WHERE o.object_id = locked.object_id`;
94
+ }
95
+ /** The person lost access to one item (a repository they can no longer read): discards that person's queued events and retires the object. Other people's objects of the item are untouched. */
96
+ async revoke(tx, sub, kind, target) {
97
+ await tx.$executeRaw `
98
+ WITH locked AS MATERIALIZED (SELECT object_id FROM watch_object WHERE sub = ${sub} AND kind = ${kind} AND target = ${target} ORDER BY object_id FOR UPDATE),
99
+ discarded AS (DELETE FROM watch_event WHERE object_id IN (SELECT object_id FROM locked))
100
+ UPDATE watch_object o SET phase = 'ending', merge_target = NULL, next_attempt_at = NULL FROM locked WHERE o.object_id = locked.object_id`;
101
+ }
102
+ }
103
+ /**
104
+ * Per-person custom objects on each person's hosted runtime, an outbox written inside the app's transactions, and an
105
+ * ordered, idempotent delivery loop. The app migrates the tables, declares its kinds with `watchableKind`, calls
106
+ * `watch` from its watch leaf, calls `changed`/`moved`/`ended` inside the transaction of each domain write, and calls
107
+ * `start()` once at bootstrap.
108
+ *
109
+ * Ordering: `changed`, `moved`, `ended`, `forget` and `revoke` lock the object's row until their transaction commits, so
110
+ * events of one object get sequence numbers in commit order and a phase change sees every earlier event committed.
111
+ * Ownership: a worker claims one object at a time with a lease token, renews it before each step and writes only while it holds it.
112
+ */
113
+ export class WatchKit extends WatchOps {
114
+ options;
115
+ timer;
116
+ running;
117
+ again = false;
118
+ stopping = false;
119
+ lastCleanup = 0;
120
+ constructor(options) {
121
+ super();
122
+ this.options = options;
123
+ }
124
+ get db() { return this.options.db; }
125
+ kindId(kind) { return `${this.options.providerId}.${kind}`; }
126
+ // ---- watching ------------------------------------------------------------------------------------------------
127
+ /**
128
+ * Finds or registers the person's object for (kind, target), then links the calling node to it. The app checks access to the item first.
129
+ * `recheck` closes the first-watch race: the app checked access and resolved the target before this call, and a member removal
130
+ * (`forget`) or merge (`moved`) may have committed before the object's row existed, so neither saw it. After the row is
131
+ * committed (from then on `forget`/`moved` see it) the kit calls `recheck`, which must repeat the app's access check and
132
+ * answer false when the item is no longer reachable under `target` (access lost, merged away, deleted). On false the kit
133
+ * removes the new object and refuses with 409. It is called only when this call created the object.
134
+ * `workspace` groups the person's objects so `forget` can retire them by workspace, whatever the item ids look like.
135
+ */
136
+ async watch(sub, caller, kind, target, options = {}) {
137
+ if (!caller.node)
138
+ throw new WatchRefusedError(400, 'watch must be run from a node');
139
+ const runtime = await this.mint(sub);
140
+ for (let attempt = 0; attempt < WATCH_ATTEMPTS; attempt++) {
141
+ const object = await this.ensure(runtime, sub, kind, target, options.meta, options.workspace ?? null, true);
142
+ if (object.created && options.recheck && !await options.recheck()) {
143
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE object_id = ${object.objectId}`;
144
+ await this.probe(runtime, object.objectId);
145
+ throw new WatchRefusedError(409, 'this item changed while it was being watched; run the command again');
146
+ }
147
+ try {
148
+ await runtime.canvas.watch(object.objectId, { watcher: caller.node });
149
+ return object;
150
+ }
151
+ catch (error) {
152
+ if (!isNotFound(error))
153
+ throw error;
154
+ // Either the object is gone from the runtime (retry on a fresh one) or the node is unknown. Unregistering it if
155
+ // unwatched tells them apart and removes a registration nobody will ever watch.
156
+ const state = await this.probe(runtime, object.objectId);
157
+ if (state !== 'watched')
158
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE object_id = ${object.objectId}`;
159
+ if (state !== 'missing')
160
+ throw new WatchRefusedError(404, 'the calling node was not found');
161
+ }
162
+ }
163
+ throw new WatchRefusedError(409, 'this item was being removed while it was watched; run the command again');
164
+ }
165
+ /** Unregisters `objectId` if no node watches it: `missing` (it was already gone), `unregistered`, or `watched` (left untouched). */
166
+ async probe(runtime, objectId) {
167
+ try {
168
+ await runtime.customObjects.unregister(objectId, { onlyIfUnwatched: true });
169
+ return 'unregistered';
170
+ }
171
+ catch (error) {
172
+ if (isWatched(error))
173
+ return 'watched';
174
+ if (isNotFound(error))
175
+ return 'missing';
176
+ throw error;
177
+ }
178
+ }
179
+ /** The person's runtime client; a person with no hosted runtime or no sign-in gets a refusal that says what to do. */
180
+ async mint(sub) {
181
+ try {
182
+ return await this.options.runtime(sub);
183
+ }
184
+ catch (error) {
185
+ if (error instanceof NoHostedRuntimeError)
186
+ throw new WatchRefusedError(409, 'this needs a hosted Northlight runtime', 'The read leaves still work without one.');
187
+ if (error instanceof NotGrantedError)
188
+ throw new WatchRefusedError(409, `sign in to ${this.options.providerId} once so it can reach your runtime`, `Open ${this.options.providerId} in a browser and sign in, then retry.`);
189
+ throw error;
190
+ }
191
+ }
192
+ /** The person's object for (kind, target), registered the first time. A concurrent first call registers a second object; the row that committed first wins and the loser is unregistered. */
193
+ async ensure(runtime, sub, kind, target, meta, workspace, forWatch) {
194
+ const existing = await this.find(sub, kind, target);
195
+ if (existing) {
196
+ if (forWatch && existing.phase === 'ending')
197
+ throw new WatchRefusedError(409, 'this item has ended, so there is nothing left to watch');
198
+ return { objectId: existing.object_id, name: existing.name, phase: existing.phase };
199
+ }
200
+ const { name, description, privacy = 'private' } = meta ?? await this.options.describe(kind, target);
201
+ const registered = await runtime.customObjects.register({ kind: this.kindId(kind), name, description, privacy });
202
+ const inserted = await this.db.$queryRaw `
203
+ INSERT INTO watch_object (object_id, sub, kind, target, name, workspace, unwatched_checked) VALUES (${registered.id}, ${sub}, ${kind}, ${target}, ${name}, ${workspace}, true)
204
+ ON CONFLICT (sub, kind, target) DO NOTHING RETURNING object_id`;
205
+ if (inserted.length > 0)
206
+ return { objectId: registered.id, name, phase: 'live', created: true };
207
+ const winner = await this.find(sub, kind, target);
208
+ if (!winner)
209
+ throw new Error(`object ${sub}/${kind}/${target} vanished during registration`);
210
+ if (winner.object_id !== registered.id)
211
+ await runtime.customObjects.unregister(registered.id);
212
+ return { objectId: winner.object_id, name: winner.name, phase: winner.phase };
213
+ }
214
+ async find(sub, kind, target) {
215
+ const rows = await this.db.$queryRaw `
216
+ SELECT object_id, sub, kind, target, name, workspace, phase, merge_target, attempts, unwatched_checked FROM watch_object WHERE sub = ${sub} AND kind = ${kind} AND target = ${target}`;
217
+ return rows[0];
218
+ }
219
+ // ---- unwatched -----------------------------------------------------------------------------------------------
220
+ /** The runtime says the object's last watcher left. Unregisters it only if it is still unwatched, then drops the row and its queued events. A watch that came back in between keeps both. Throws on any other failure so the runtime retries. */
221
+ async unwatched(input) {
222
+ const rows = await this.db.$queryRaw `SELECT object_id, sub FROM watch_object WHERE object_id = ${input.id}`;
223
+ const row = rows[0];
224
+ if (!row)
225
+ return;
226
+ if (input.sub !== undefined && row.sub !== input.sub)
227
+ throw new Error(`object ${input.id} belongs to another person`);
228
+ const runtime = await this.options.runtime(row.sub);
229
+ if (await this.probe(runtime, row.object_id) === 'watched')
230
+ return;
231
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE object_id = ${row.object_id}`;
232
+ }
233
+ // ---- delivery ------------------------------------------------------------------------------------------------
234
+ /** Runs delivery passes every 2 s and on `nudge()`. Call once at bootstrap. Objects that predate the unwatched hook are checked by the first passes. */
235
+ start() {
236
+ if (this.timer)
237
+ return;
238
+ this.stopping = false;
239
+ this.timer = setInterval(() => this.nudge(), TICK_MS);
240
+ this.timer.unref();
241
+ }
242
+ /** Stops the timer and waits for the pass in progress; no further pass starts. */
243
+ async stop() {
244
+ this.stopping = true;
245
+ if (this.timer)
246
+ clearInterval(this.timer);
247
+ this.timer = undefined;
248
+ await this.running;
249
+ }
250
+ /** Makes a pass run soon; passes never overlap. Call after the commit of a transaction that queued events. */
251
+ nudge() {
252
+ if (this.stopping)
253
+ return;
254
+ if (this.running) {
255
+ this.again = true;
256
+ return;
257
+ }
258
+ this.running = this.tick().catch((error) => this.options.report('watch delivery pass failed', error)).finally(() => {
259
+ this.running = undefined;
260
+ if (this.again && !this.stopping) {
261
+ this.again = false;
262
+ this.nudge();
263
+ }
264
+ });
265
+ }
266
+ /** One delivery pass: workers claim one due object at a time and deliver its events in order. Resolves when every worker is done. */
267
+ async tick() {
268
+ const clients = new Map();
269
+ const runtime = (sub) => {
270
+ let client = clients.get(sub);
271
+ if (!client) {
272
+ client = this.options.runtime(sub);
273
+ clients.set(sub, client);
274
+ }
275
+ return client;
276
+ };
277
+ let started = 0;
278
+ await Promise.allSettled(Array.from({ length: CONCURRENCY }, async () => {
279
+ while (!this.stopping && started < PASS_LIMIT) {
280
+ started++;
281
+ const claim = await this.claim();
282
+ if (!claim)
283
+ return;
284
+ try {
285
+ await this.deliver(claim, runtime);
286
+ }
287
+ catch (error) {
288
+ this.options.report(`delivery to ${claim.object_id} failed`, error);
289
+ }
290
+ await this.release(claim).catch((error) => this.options.report(`releasing ${claim.object_id} failed`, error));
291
+ }
292
+ }));
293
+ if (!this.stopping && Date.now() - this.lastCleanup > 3_600_000) {
294
+ this.lastCleanup = Date.now();
295
+ await this.db.$executeRaw `DELETE FROM watch_event WHERE status = 'dropped' AND created_at < now() - make_interval(days => ${DROPPED_KEEP_DAYS}::int)`;
296
+ }
297
+ }
298
+ /** Takes the lease of one due object. */
299
+ async claim() {
300
+ const token = randomUUID();
301
+ const rows = await this.db.$queryRaw `
302
+ UPDATE watch_object SET lease_owner = ${token}, lease_until = now() + make_interval(secs => ${LEASE_S}::double precision)
303
+ WHERE object_id = (
304
+ SELECT o.object_id FROM watch_object o
305
+ WHERE (o.lease_until IS NULL OR o.lease_until < now()) AND (o.next_attempt_at IS NULL OR o.next_attempt_at <= now())
306
+ AND (o.phase <> 'live' OR NOT o.unwatched_checked OR EXISTS (SELECT 1 FROM watch_event e WHERE e.object_id = o.object_id AND e.status = 'pending'))
307
+ ORDER BY o.created_at LIMIT 1 FOR UPDATE SKIP LOCKED)
308
+ RETURNING object_id, sub, kind, target, name, workspace, phase, merge_target, attempts, unwatched_checked`;
309
+ return rows[0] ? { ...rows[0], token } : undefined;
310
+ }
311
+ /** Extends the lease and reads the object's current state; undefined when this worker no longer holds the lease. */
312
+ async renew(claim) {
313
+ const rows = await this.db.$queryRaw `
314
+ UPDATE watch_object SET lease_until = now() + make_interval(secs => ${LEASE_S}::double precision)
315
+ WHERE object_id = ${claim.object_id} AND lease_owner = ${claim.token} AND lease_until > now()
316
+ RETURNING object_id, sub, kind, target, name, workspace, phase, merge_target, attempts, unwatched_checked`;
317
+ return rows[0];
318
+ }
319
+ async deliver(claim, runtime) {
320
+ let client;
321
+ try {
322
+ client = await runtime(claim.sub);
323
+ }
324
+ catch (error) {
325
+ return this.settle(claim, error);
326
+ }
327
+ for (;;) {
328
+ if (this.stopping)
329
+ return;
330
+ const row = await this.renew(claim);
331
+ if (!row)
332
+ return;
333
+ try {
334
+ if (!row.unwatched_checked) {
335
+ if (row.phase === 'live' && await this.probe(client, row.object_id) !== 'watched')
336
+ return await this.remove(claim);
337
+ await this.db.$executeRaw `UPDATE watch_object SET unwatched_checked = true WHERE object_id = ${row.object_id} AND lease_owner = ${claim.token}`;
338
+ continue;
339
+ }
340
+ const [head] = await this.db.$queryRaw `
341
+ SELECT seq, event, summary, state, dedupe, created_at FROM watch_event WHERE object_id = ${row.object_id} AND status = 'pending' ORDER BY seq LIMIT 1`;
342
+ if (head) {
343
+ if (!await this.publish(client, claim, head))
344
+ return;
345
+ continue;
346
+ }
347
+ if (row.phase === 'live') {
348
+ await this.db.$executeRaw `UPDATE watch_object SET attempts = 0, last_error = NULL, next_attempt_at = NULL WHERE object_id = ${row.object_id} AND lease_owner = ${claim.token}`;
349
+ return;
350
+ }
351
+ if (row.phase === 'merging' && row.merge_target !== null)
352
+ await this.finishMerge(client, claim, row, row.merge_target);
353
+ else
354
+ await client.customObjects.unregister(row.object_id);
355
+ return await this.remove(claim);
356
+ }
357
+ catch (error) {
358
+ return this.settle(claim, error);
359
+ }
360
+ }
361
+ }
362
+ /** Publishes the head event. True when the loop may go on to the next event. */
363
+ async publish(client, claim, head) {
364
+ const seq = String(head.seq);
365
+ // One logical event keeps one key however often the app queues it; any other event is keyed by its own row.
366
+ const key = `${this.options.providerId}:${claim.object_id}:${head.dedupe === null ? seq : `d:${createHash('sha256').update(head.dedupe).digest('hex')}`}`;
367
+ try {
368
+ await client.customObjects.publish(claim.object_id, {
369
+ event: head.event, summary: head.summary, ...(head.state == null ? {} : { state: head.state }), idempotency_key: key,
370
+ });
371
+ }
372
+ catch (error) {
373
+ if (classify(error) === 'drop') {
374
+ const reason = message(error);
375
+ this.options.report(`dropped event ${seq} of ${claim.object_id}: ${reason}`);
376
+ await this.db.$executeRaw `UPDATE watch_event SET status = 'dropped', drop_reason = ${reason} WHERE seq = ${seq}::bigint`;
377
+ return true;
378
+ }
379
+ if (Date.now() - new Date(head.created_at).getTime() > STUCK_MS)
380
+ this.options.report(`events of ${claim.object_id} have been retrying for over 24 h: ${message(error)}`, error);
381
+ await this.settle(claim, error);
382
+ return false;
383
+ }
384
+ await this.db.$executeRaw `DELETE FROM watch_event WHERE seq = ${seq}::bigint`;
385
+ return true;
386
+ }
387
+ /** Moves the object's watchers onto the surviving object of `target` (following any merge that already moved the target on), or retires it when the survivor ended. */
388
+ async finishMerge(client, claim, row, start) {
389
+ let target = start;
390
+ for (let hops = 0; hops < CHAIN_LIMIT; hops++) {
391
+ const next = await this.find(row.sub, row.kind, target);
392
+ if (next?.phase !== 'merging' || next.merge_target === null || next.merge_target === row.target)
393
+ break;
394
+ target = next.merge_target;
395
+ }
396
+ const survivor = await this.ensure(client, row.sub, row.kind, target, undefined, row.workspace, false);
397
+ if (survivor.phase === 'ending')
398
+ return void await client.customObjects.unregister(row.object_id);
399
+ if (survivor.objectId === row.object_id)
400
+ return;
401
+ try {
402
+ await client.customObjects.mergeInto(row.object_id, survivor.objectId);
403
+ }
404
+ catch (error) {
405
+ if (!isNotFound(error))
406
+ throw error;
407
+ // Either object may be the missing one. If the source still has watchers the survivor is gone: forget it and register a fresh one next pass.
408
+ if (await this.probe(client, row.object_id) !== 'watched')
409
+ return;
410
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE object_id = ${survivor.objectId}`;
411
+ throw new RetryLater(`the surviving object ${survivor.objectId} is gone`);
412
+ }
413
+ }
414
+ /** Deletes the claimed object's row (and its queued events) while this worker still holds the lease. */
415
+ async remove(claim) {
416
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE object_id = ${claim.object_id} AND lease_owner = ${claim.token}`;
417
+ }
418
+ /** Applies the refusal table to a failed call on `claim`. */
419
+ async settle(claim, error) {
420
+ switch (classify(error)) {
421
+ case 'connection':
422
+ await this.db.$executeRaw `DELETE FROM watch_object WHERE sub = ${claim.sub}`;
423
+ return;
424
+ case 'gone':
425
+ await this.remove(claim);
426
+ return;
427
+ default: {
428
+ const attempts = claim.attempts + 1;
429
+ const backoff = Math.min(2 ** attempts * 10_000, MAX_BACKOFF_MS) / 1000;
430
+ await this.db.$executeRaw `
431
+ UPDATE watch_object SET attempts = ${attempts}, last_error = ${message(error)}, next_attempt_at = now() + make_interval(secs => ${backoff}::double precision)
432
+ WHERE object_id = ${claim.object_id} AND lease_owner = ${claim.token}`;
433
+ }
434
+ }
435
+ }
436
+ async release(claim) {
437
+ await this.db.$executeRaw `UPDATE watch_object SET lease_until = NULL, lease_owner = NULL WHERE object_id = ${claim.object_id} AND lease_owner = ${claim.token}`;
438
+ }
439
+ }
440
+ /** A failure the delivery loop retries with backoff. */
441
+ class RetryLater extends Error {
442
+ }
@@ -0,0 +1,14 @@
1
+ import { type LeafNode, type ObjectKindSpec } from '@north-light/plugin';
2
+ import type { WatchKit } from './kit.js';
3
+ /** The key the hidden leaf is declared under in the plugin's `commands`; its command path is `watch-unwatched`. */
4
+ export declare const WATCH_UNWATCHED_KEY = "watchUnwatched";
5
+ /** Adds `onUnwatched` to a kind the app declares in `definePlugin({objectKinds})`, pointing at the hidden leaf from `unwatchedLeaves`. */
6
+ export declare function watchableKind<const T extends ObjectKindSpec>(spec: T): T & {
7
+ readonly onUnwatched: {
8
+ readonly command: readonly string[];
9
+ };
10
+ };
11
+ /** The hidden leaf the runtime calls when an object's last watcher leaves. Spread it into the plugin's `commands`. A provider plugin passes the `group` the leaf belongs to (a group it declares in `groups`). */
12
+ export declare function unwatchedLeaves(kit: WatchKit, options?: {
13
+ group?: string;
14
+ }): Record<typeof WATCH_UNWATCHED_KEY, LeafNode>;
@@ -0,0 +1,30 @@
1
+ import { defineLeaf, field, param } from '@north-light/plugin';
2
+ /** The key the hidden leaf is declared under in the plugin's `commands`; its command path is `watch-unwatched`. */
3
+ export const WATCH_UNWATCHED_KEY = 'watchUnwatched';
4
+ /** Adds `onUnwatched` to a kind the app declares in `definePlugin({objectKinds})`, pointing at the hidden leaf from `unwatchedLeaves`. */
5
+ export function watchableKind(spec) {
6
+ return { ...spec, onUnwatched: { command: ['watch-unwatched'] } };
7
+ }
8
+ /** The hidden leaf the runtime calls when an object's last watcher leaves. Spread it into the plugin's `commands`. A provider plugin passes the `group` the leaf belongs to (a group it declares in `groups`). */
9
+ export function unwatchedLeaves(kit, options = {}) {
10
+ return {
11
+ [WATCH_UNWATCHED_KEY]: defineLeaf({
12
+ description: 'Called by the runtime when the last watcher of one of this app\'s objects leaves: unregisters the object if it is still unwatched.',
13
+ whenToUse: 'Never run it by hand; the runtime calls it.',
14
+ summary: 'Unregister an unwatched object',
15
+ tier: 'hidden',
16
+ sideEffect: false,
17
+ ...(options.group !== undefined ? { group: options.group } : {}),
18
+ params: {
19
+ id: param.string('Canvas object id; the runtime passes this', { required: true }),
20
+ name: param.string('Object name; the runtime passes this'),
21
+ },
22
+ output: { ok: field.bool('True once the object is unregistered or was watched again.') },
23
+ effects: ['Unregisters the person\'s canvas object when no node watches it', 'Deletes its queued events'],
24
+ handler: async (input, ctx) => {
25
+ await kit.unwatched({ id: input.id, ...(ctx.caller ? { sub: ctx.caller.sub } : {}) });
26
+ return { ok: true };
27
+ },
28
+ }),
29
+ };
30
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@north-light/sdk",
3
- "version": "0.3.856",
4
- "crouterContract": "1.103",
3
+ "version": "0.3.858",
4
+ "crouterContract": "1.105",
5
5
  "description": "Typed Node and browser client for running crouter agents through the crtrd /v1 API.",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/stores/postgres.d.ts",
23
23
  "import": "./dist/stores/postgres.js"
24
24
  },
25
+ "./watch": {
26
+ "types": "./dist/watch/index.d.ts",
27
+ "import": "./dist/watch/index.js"
28
+ },
25
29
  "./testing": {
26
30
  "types": "./dist/testing/index.d.ts",
27
31
  "import": "./dist/testing/index.js"
@@ -33,6 +37,8 @@
33
37
  },
34
38
  "files": [
35
39
  "dist",
40
+ "schema",
41
+ "sql",
36
42
  "README.md"
37
43
  ],
38
44
  "engines": {
@@ -44,9 +50,9 @@
44
50
  "prepublishOnly": "node -e \"if (process.env.npm_config_tag !== 'next') { console.error('@north-light/sdk publishes only with --tag next; scripts/promote-sdk.mjs is the only mover of latest.'); process.exit(1); }\""
45
51
  },
46
52
  "dependencies": {
47
- "@north-light/api": "0.3.856",
48
- "@north-light/identity": "0.3.856",
49
- "@north-light/plugin": "0.3.856",
53
+ "@north-light/api": "0.3.858",
54
+ "@north-light/identity": "0.3.858",
55
+ "@north-light/plugin": "0.3.858",
50
56
  "jose": "^6.2.1"
51
57
  },
52
58
  "peerDependencies": {
@@ -0,0 +1,49 @@
1
+ // The watchable-objects tables (`@north-light/sdk/watch`). Paste these two models into the app's schema.prisma, then apply
2
+ // sql/001-watch.sql in the same migration (Prisma cannot express the partial index). Every app adopts them unchanged.
3
+
4
+ /// One row per person and watched item: the canvas object registered on that person's hosted runtime.
5
+ model WatchObject {
6
+ objectId String @id @map("object_id")
7
+ sub String
8
+ kind String
9
+ target String
10
+ name String
11
+ /// Optional grouping the app sets at `watch` (a workspace id), so `forget` can filter by it independently of the item id.
12
+ workspace String?
13
+ /// live | merging (into mergeTarget) | ending
14
+ phase String @default("live")
15
+ mergeTarget String? @map("merge_target")
16
+ nextAttemptAt DateTime? @map("next_attempt_at") @db.Timestamptz(6)
17
+ leaseUntil DateTime? @map("lease_until") @db.Timestamptz(6)
18
+ /// The delivery worker that holds the lease; every write of a worker is conditional on it.
19
+ leaseOwner String? @map("lease_owner")
20
+ /// False on rows that predate the unwatched hook: the first pass asks the runtime to unregister them if nobody watches.
21
+ unwatchedChecked Boolean @default(false) @map("unwatched_checked")
22
+ attempts Int @default(0)
23
+ lastError String? @map("last_error")
24
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
25
+ events WatchEvent[]
26
+
27
+ @@unique([sub, kind, target])
28
+ @@index([kind, target])
29
+ @@map("watch_object")
30
+ }
31
+
32
+ /// The outbox: one row per event per object. Delivered rows are deleted.
33
+ model WatchEvent {
34
+ seq BigInt @id @default(autoincrement())
35
+ objectId String @map("object_id")
36
+ event String
37
+ summary String
38
+ state Json?
39
+ /// Optional; unique with objectId, so one logical event is queued once.
40
+ dedupe String?
41
+ /// pending | dropped
42
+ status String @default("pending")
43
+ dropReason String? @map("drop_reason")
44
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
45
+ object WatchObject @relation(fields: [objectId], references: [objectId], onDelete: Cascade)
46
+
47
+ @@unique([objectId, dedupe])
48
+ @@map("watch_event")
49
+ }
@@ -0,0 +1,3 @@
1
+ -- Run after the Prisma migration that creates watch_object and watch_event (schema/watch.prisma).
2
+ -- The delivery loop reads only pending rows in order for one object; delivered rows are deleted, so this stays small.
3
+ CREATE INDEX IF NOT EXISTS watch_event_pending_idx ON watch_event (object_id, seq) WHERE status = 'pending';