@protobase/server 0.133.1 → 0.133.3

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.
Files changed (49) hide show
  1. package/dist/api-cors.js +4 -1
  2. package/dist/api-keys/caller-settings.js +10 -5
  3. package/dist/batch/run-batch.js +2 -2
  4. package/dist/changes/actor.js +7 -6
  5. package/dist/changes/capture-schema-sql.d.ts +2 -1
  6. package/dist/changes/capture-schema-sql.js +2 -1
  7. package/dist/changes/events-options.d.ts +5 -0
  8. package/dist/changes/logical-message.js +17 -0
  9. package/dist/changes/stream/schema-messages-sql.js +42 -0
  10. package/dist/changes/stream/stream-module.js +48 -0
  11. package/dist/comments/post-comment.js +2 -1
  12. package/dist/create-admin.js +23 -8
  13. package/dist/deps.d.ts +3 -0
  14. package/dist/functions/define-function.d.ts +5 -0
  15. package/dist/functions/routes.js +4 -1
  16. package/dist/functions/supabase-routes.js +6 -3
  17. package/dist/list-service.js +15 -5
  18. package/dist/live/live-route.js +20 -5
  19. package/dist/live/refresh/live-refresh.d.ts +13 -0
  20. package/dist/live/refresh/live-refresh.js +8 -0
  21. package/dist/live/refresh/refresh-notices.js +21 -0
  22. package/dist/live/token/key-filter.js +31 -0
  23. package/dist/live/token/live-headers.js +9 -0
  24. package/dist/live/token/live-key.js +16 -0
  25. package/dist/live/token/live-preference.js +11 -0
  26. package/dist/live/token/live-subject.js +26 -0
  27. package/dist/live/token/live-token.d.ts +14 -0
  28. package/dist/live/token/live-token.js +24 -0
  29. package/dist/live/token/live-tokens.d.ts +20 -0
  30. package/dist/live/token/live-tokens.js +28 -0
  31. package/dist/live/visible-notices.js +5 -1
  32. package/dist/package.js +1 -1
  33. package/dist/read-service.js +27 -6
  34. package/dist/records.d.ts +1 -1
  35. package/dist/request-access.d.ts +1 -1
  36. package/dist/rest/rest-context.js +4 -2
  37. package/dist/routes/collection.js +17 -6
  38. package/dist/routes/record.js +8 -8
  39. package/dist/schema-modules/modules.d.ts +2 -1
  40. package/dist/schema-modules/modules.js +2 -0
  41. package/dist/schema-modules/needed-modules.js +1 -0
  42. package/dist/sql-parts.d.ts +1 -1
  43. package/dist/storage/storage-db.js +6 -7
  44. package/dist/transactions.js +16 -6
  45. package/dist/webhooks/attempt.js +1 -0
  46. package/dist/webhooks/webhooks.js +3 -1
  47. package/dist/write-pipeline.js +2 -2
  48. package/dist/write-shared.d.ts +1 -1
  49. package/package.json +6 -6
package/dist/api-cors.js CHANGED
@@ -28,6 +28,7 @@ const allowHeaders = [
28
28
  "content-type",
29
29
  "if-match",
30
30
  "if-none-match",
31
+ "prefer",
31
32
  "apikey",
32
33
  "x-client-info",
33
34
  "x-supabase-api-version"
@@ -36,7 +37,9 @@ const exposeHeaders = [
36
37
  "location",
37
38
  "etag",
38
39
  "x-meta-version",
39
- "x-protobase-warning"
40
+ "x-protobase-warning",
41
+ "preference-applied",
42
+ "protobase-live"
40
43
  ];
41
44
  /**
42
45
  * CORS for the API: an allowed origin gets `Access-Control-Allow-Origin` (`*` when any is), preflights are answered
@@ -1,4 +1,12 @@
1
1
  //#region src/api-keys/caller-settings.ts
2
+ /** Who a request admitted by key writes as: its signed-in user, or none for the anonymous and the app's own key. */
3
+ const callerActor = (caller) => {
4
+ const sub = caller.role === "authenticated" ? caller.claims.sub : void 0;
5
+ return sub === void 0 ? void 0 : {
6
+ id: sub,
7
+ roles: []
8
+ };
9
+ };
2
10
  /**
3
11
  * The transaction settings a request admitted by key (`/api/sb/rest/v1`, `/api/sb/storage/v1`) runs with, as Supabase's PostgREST
4
12
  * sets them: `role`, which is `SET LOCAL ROLE`, to `anon` or `authenticated`, and the caller's claims in `request.jwt.claims` and its user in
@@ -9,10 +17,7 @@
9
17
  const callerSettings = (caller, actorSetting) => {
10
18
  const role = caller.role === "app" ? "service_role" : caller.role;
11
19
  const sub = caller.role === "authenticated" ? caller.claims.sub : void 0;
12
- const actor = sub === void 0 ? void 0 : {
13
- id: sub,
14
- roles: []
15
- };
20
+ const actor = callerActor(caller);
16
21
  return {
17
22
  ...caller.role !== "app" && { role: caller.role },
18
23
  "request.jwt.claims": JSON.stringify({
@@ -24,4 +29,4 @@ const callerSettings = (caller, actorSetting) => {
24
29
  };
25
30
  };
26
31
  //#endregion
27
- export { callerSettings };
32
+ export { callerActor, callerSettings };
@@ -1,7 +1,7 @@
1
1
  import { HttpProblem, badRequest, notFound } from "../problem.js";
2
2
  import { requestAccess } from "../request-access.js";
3
3
  import { writeTransaction } from "../transactions.js";
4
- import { actorSettings, wakeDispatch } from "../changes/actor.js";
4
+ import { actorSettings, sessionActor, wakeDispatch } from "../changes/actor.js";
5
5
  import { problemOf } from "../error-handler.js";
6
6
  import { once } from "../idempotency.js";
7
7
  import { scheduleRemovedFiles } from "../files/attach.js";
@@ -151,7 +151,7 @@ const runBatch = async (deps, session, operations, idempotency) => {
151
151
  throw atOperation(deps, error, index, operation);
152
152
  }
153
153
  return results;
154
- }), actorSettings(deps, session)));
154
+ }), actorSettings(deps, session), sessionActor(session)));
155
155
  await scheduleRemovedFiles(deps, removed);
156
156
  wakeDispatch(deps);
157
157
  return written;
@@ -1,18 +1,19 @@
1
1
  import { runningJobs } from "../jobs/current.js";
2
2
  import { dispatchJobName } from "./capture-sql.js";
3
3
  //#region src/changes/actor.ts
4
+ /** Who writes in a session's write transaction: the actor its `protobase_actor` message and the change capture name. */
5
+ const sessionActor = (session) => ({
6
+ id: session.user.id,
7
+ roles: session.user.roles
8
+ });
4
9
  /** The setting a write transaction sets so the change capture records who wrote, when a resource has events or history. */
5
10
  const actorSettings = (deps, session) => {
6
11
  if (!deps.actorSetting) return {};
7
- const actor = {
8
- id: session.user.id,
9
- roles: session.user.roles
10
- };
11
- return { [deps.actorSetting]: JSON.stringify(actor) };
12
+ return { [deps.actorSetting]: JSON.stringify(sessionActor(session)) };
12
13
  };
13
14
  /** After a write committed: has this process's dispatcher deliver its events now, rather than at its next poll. */
14
15
  const wakeDispatch = (deps) => {
15
16
  if (deps.actorSetting) runningJobs()?.wake(dispatchJobName);
16
17
  };
17
18
  //#endregion
18
- export { actorSettings, wakeDispatch };
19
+ export { actorSettings, sessionActor, wakeDispatch };
@@ -3,7 +3,8 @@ import { ResourceModel } from "@protobase/schema";
3
3
  //#region src/changes/capture-schema-sql.d.ts
4
4
  /**
5
5
  * The change capture `models` need, as a migration writes it on a database without it: the change capture module, and
6
- * the history and notices tables when a resource has history or live updates. The jobs schema it enqueues into is not
6
+ * the history and notices tables when a resource has history or live updates, and with `events.stream` the schema
7
+ * change messages. The jobs schema it enqueues into is not
7
8
  * part of it (`jobsSchemaSql`), nor are the rollups and formulas of `models` (`computedSchemaSql`).
8
9
  */
9
10
  export declare const captureSchemaSql: (models: readonly ResourceModel[], events?: EventsOptions) => string;
@@ -4,7 +4,8 @@ import { neededModules } from "../schema-modules/needed-modules.js";
4
4
  //#region src/changes/capture-schema-sql.ts
5
5
  /**
6
6
  * The change capture `models` need, as a migration writes it on a database without it: the change capture module, and
7
- * the history and notices tables when a resource has history or live updates. The jobs schema it enqueues into is not
7
+ * the history and notices tables when a resource has history or live updates, and with `events.stream` the schema
8
+ * change messages. The jobs schema it enqueues into is not
8
9
  * part of it (`jobsSchemaSql`), nor are the rollups and formulas of `models` (`computedSchemaSql`).
9
10
  */
10
11
  const captureSchemaSql = (models, events) => {
@@ -6,5 +6,10 @@ export type EventsOptions = {
6
6
  * (`changes.actor`, `changes.capture`); default `changes`. Rename it when the database already has a schema by that name.
7
7
  */
8
8
  schema?: string;
9
+ /**
10
+ * Whether `protobase migration` writes the event triggers that put schema changes into the WAL as logical messages,
11
+ * which the change stream reads in order with the rows. Creating them takes a superuser.
12
+ */
13
+ stream?: boolean;
9
14
  };
10
15
  //#endregion
@@ -0,0 +1,17 @@
1
+ import { sql } from "kysely";
2
+ //#region src/changes/logical-message.ts
3
+ /** The prefix of the message every API write transaction emits with who wrote, as the change stream reads it. */
4
+ const actorPrefix = "protobase_actor";
5
+ /** The prefix of the message emitted for each command a schema change runs (`ddl_command_end`). */
6
+ const ddlPrefix = "protobase_ddl";
7
+ /** The prefix of the message emitted for each object a schema change drops (`sql_drop`). */
8
+ const dropPrefix = "protobase_drop";
9
+ /**
10
+ * A transactional logical decoding message, as an expression of a select: it reaches the WAL with the transaction's
11
+ * rows, in their order, and only when the transaction commits. The `text` cast picks the text overload over bytea's.
12
+ */
13
+ const emitMessage = (prefix, content) => sql`pg_logical_emit_message(true, ${prefix}, ${content}::text)`;
14
+ /** The same message in the SQL of a function body: `content` is an SQL expression of type text. */
15
+ const emitMessageSql = (prefix, content) => `pg_logical_emit_message(true, '${prefix}', ${content})`;
16
+ //#endregion
17
+ export { actorPrefix, ddlPrefix, dropPrefix, emitMessage, emitMessageSql };
@@ -0,0 +1,42 @@
1
+ import { ddlPrefix, dropPrefix, emitMessageSql } from "../logical-message.js";
2
+ import { quoteIdent } from "../capture-sql.js";
3
+ //#region src/changes/stream/schema-messages-sql.ts
4
+ /** The function the schema change event triggers call, in the changes schema. */
5
+ const schemaMessagesFunction = "emit_schema_messages";
6
+ /** The event triggers' names, one per event; they are the database's own, so the changes schema prefixes them. */
7
+ const schemaMessagesTriggers = (schema) => ({
8
+ ddl: `${schema}_ddl_messages`,
9
+ drop: `${schema}_drop_messages`
10
+ });
11
+ /**
12
+ * The function and the event triggers that write each schema change into the WAL as logical messages, in its
13
+ * transaction, so a reader of the change stream meets them in order with the rows: a `protobase_ddl` message for each
14
+ * command a statement such as ALTER TABLE ran (`ddl_command_end`), a `protobase_drop` message for each object a
15
+ * statement dropped (`sql_drop`), each a JSON object of Postgres's own fields. Creating an event trigger takes a
16
+ * superuser, so applying it as another role fails with Postgres's own error.
17
+ */
18
+ const schemaMessagesSql = (schema) => {
19
+ const fn = `${quoteIdent(schema)}.${quoteIdent(schemaMessagesFunction)}`;
20
+ const { ddl, drop } = schemaMessagesTriggers(schema);
21
+ return `create or replace function ${fn}() returns event_trigger language plpgsql as $$
22
+ declare
23
+ command record;
24
+ begin
25
+ if tg_event = 'sql_drop' then
26
+ for command in select object_type, schema_name, object_identity from pg_event_trigger_dropped_objects() loop
27
+ perform ${emitMessageSql(dropPrefix, "json_build_object('object_type', command.object_type, 'schema_name', command.schema_name, 'object_identity', command.object_identity)::text")};
28
+ end loop;
29
+ return;
30
+ end if;
31
+ for command in select command_tag, object_type, schema_name, object_identity from pg_event_trigger_ddl_commands() loop
32
+ perform ${emitMessageSql(ddlPrefix, "json_build_object('command_tag', command.command_tag, 'object_type', command.object_type, 'schema_name', command.schema_name, 'object_identity', command.object_identity)::text")};
33
+ end loop;
34
+ end
35
+ $$;
36
+ drop event trigger if exists ${quoteIdent(ddl)};
37
+ create event trigger ${quoteIdent(ddl)} on ddl_command_end execute function ${fn}();
38
+ drop event trigger if exists ${quoteIdent(drop)};
39
+ create event trigger ${quoteIdent(drop)} on sql_drop execute function ${fn}();`;
40
+ };
41
+ //#endregion
42
+ export { schemaMessagesFunction, schemaMessagesSql, schemaMessagesTriggers };
@@ -0,0 +1,48 @@
1
+ import { quoteIdent } from "../capture-sql.js";
2
+ import { schemaMessagesFunction, schemaMessagesSql, schemaMessagesTriggers } from "./schema-messages-sql.js";
3
+ import { sql } from "kysely";
4
+ //#region src/changes/stream/stream-module.ts
5
+ /**
6
+ * The schema change messages as the database has them: step 1 once the function is there, and the triggers at version 1
7
+ * when both event triggers are there, enabled and calling it, else at none, so they are written again.
8
+ */
9
+ const readStream = async (db, { names }) => {
10
+ const schema = names.schema;
11
+ const { ddl, drop } = schemaMessagesTriggers(schema);
12
+ const fn = `${quoteIdent(schema)}.${quoteIdent(schemaMessagesFunction)}`;
13
+ const { rows } = await sql`select to_regprocedure(${`${fn}()`}) is not null as found,
14
+ (select count(*)::int from pg_event_trigger where evtname = any(${[ddl, drop]}::text[]) and evtenabled in ('O', 'A') and evtfoid = to_regprocedure(${`${fn}()`})) as triggers`.execute(db);
15
+ const { found, triggers } = rows[0];
16
+ if (!found) return;
17
+ return {
18
+ lastStep: 1,
19
+ replaceables: triggers === 2 ? { schema_messages: 1 } : {},
20
+ names
21
+ };
22
+ };
23
+ /**
24
+ * What the change stream needs in the app's database besides the WAL itself, with `events.stream`: the event triggers
25
+ * that write schema changes as logical messages (`schemaMessagesSql`), in the schema `events` names (`names.schema`).
26
+ */
27
+ const streamModule = {
28
+ label: "the schema change messages",
29
+ title: "The schema change messages the change stream reads",
30
+ steps: [{
31
+ step: 1,
32
+ name: "schema",
33
+ title: "The changes schema",
34
+ additive: true,
35
+ sql: (names) => `create schema if not exists ${quoteIdent(names.schema)};`
36
+ }],
37
+ replaceables: [{
38
+ name: "schema_messages",
39
+ title: "The event triggers that write schema changes as logical messages",
40
+ version: 1,
41
+ compatibleFrom: 1,
42
+ sql: (names) => schemaMessagesSql(names.schema)
43
+ }],
44
+ resourceReplaceables: [],
45
+ read: readStream
46
+ };
47
+ //#endregion
48
+ export { streamModule };
@@ -1,6 +1,7 @@
1
1
  import { badRequest, notFound } from "../problem.js";
2
2
  import { tenantScope } from "../tenant.js";
3
3
  import { writeTransaction } from "../transactions.js";
4
+ import { sessionActor } from "../changes/actor.js";
4
5
  import { commentAccess, mayRead, readableRecord, requireSignedIn, userSessions } from "./comment-access.js";
5
6
  import { parseCommentInput } from "./comment-input.js";
6
7
  import { commentColumns, commentItem, namedUsers } from "./comment-item.js";
@@ -51,7 +52,7 @@ const postComment = async (deps, entry, session, key, body, requestURL) => {
51
52
  options: { key: `${inserted.id}:${user}` }
52
53
  })));
53
54
  return inserted;
54
- });
55
+ }, {}, sessionActor(session));
55
56
  if (!row) throw notFound(`No ${entry.name} with this key`);
56
57
  const names = deps.comments?.users ? await deps.comments.users.names(namedUsers([row])) : {};
57
58
  return commentItem(row, names);
@@ -62,6 +62,7 @@ import { bucketsRefreshJob } from "./computed/buckets-job.js";
62
62
  import { hasBuckets } from "./computed/buckets-targets.js";
63
63
  import { callerRecords } from "./functions/records.js";
64
64
  import { toApiFunction } from "./functions/define-function.js";
65
+ import { liveRefresh } from "./live/refresh/live-refresh.js";
65
66
  import { createWebhooks } from "./webhooks/webhooks.js";
66
67
  import { webhookTable } from "./webhooks/table/webhook-table.js";
67
68
  import { subscriptionUrlCheck, subscriptionWriteCheck } from "./webhooks/table/validate-hook.js";
@@ -93,8 +94,11 @@ import { appRelayChannels } from "./relay/realtime-channels.js";
93
94
  import { appRelaySettings } from "./relay/relay-switch.js";
94
95
  import { idleRelayJobs } from "./relay/relay-jobs.js";
95
96
  import { relayPresencePath } from "./relay/presence-route.js";
97
+ import { sessionEnd } from "./relay/session-end.js";
96
98
  import { relayTicketPath } from "./relay/ticket-route.js";
97
99
  import { relayRuntime } from "./relay/relay-runtime.js";
100
+ import { liveTokens } from "./live/token/live-tokens.js";
101
+ import { writeRefreshNotices } from "./live/refresh/refresh-notices.js";
98
102
  import { typingViewErrors } from "./relay/typing-views.js";
99
103
  import { liveSessions } from "./better-auth/live-sessions.js";
100
104
  import { mailSenderUse } from "./personal-mail/mail-sender-use.js";
@@ -290,6 +294,17 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
290
294
  ...options.roles && { roles: options.roles },
291
295
  ...options.defaultAccess && { defaultAccess: options.defaultAccess }
292
296
  };
297
+ const relayApp = {
298
+ views: viewModels,
299
+ models: appModels,
300
+ signIn: Boolean(auth)
301
+ };
302
+ const relaySettings = appRelaySettings(realtime?.relay, globalThis.process?.env ?? {}, relayApp);
303
+ const tokens = relaySettings && auth && liveTokens({
304
+ app: relaySettings.app,
305
+ ticketKey: relaySettings.ticketKey,
306
+ sessionEnd: sessionEnd(auth)
307
+ });
293
308
  const deps = {
294
309
  db,
295
310
  registry,
@@ -352,14 +367,9 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
352
367
  organizations: Boolean(auth?.organizations),
353
368
  ...auth?.origins[0] && { origin: auth.origins[0] },
354
369
  ...statusTables && { doNotDisturb: (ringDb, userIds) => onDoNotDisturb(ringDb, statusTables.statuses, userIds) }
355
- }) }
370
+ }) },
371
+ ...tokens && { liveTokens: tokens }
356
372
  };
357
- const relayApp = {
358
- views: viewModels,
359
- models: appModels,
360
- signIn: Boolean(auth)
361
- };
362
- const relaySettings = appRelaySettings(realtime?.relay, globalThis.process?.env ?? {}, relayApp);
363
373
  const relay = relaySettings && relayRuntime(relaySettings, auth, deps);
364
374
  const relayJobList = relay ? relay.jobs : appRelayChannels(realtime?.relay, relayApp) ? idleRelayJobs() : [];
365
375
  const typingErrors = typingViewErrors(viewModels, relaySettings && new Set(Object.keys(relaySettings.channels)));
@@ -522,6 +532,8 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
522
532
  const decryptField = fieldDecrypter(deps);
523
533
  const hubs = realtimeHubs(deps, realtime, report);
524
534
  const channels = channelSender(registry, hubs.records.broadcasts);
535
+ const noticed = appModels.some((model) => model.live) || deps.calls !== void 0;
536
+ const refresh = liveRefresh(noticed ? (userIds) => writeRefreshNotices(db, changes, userIds) : void 0);
525
537
  app.route("/", functionRoutes({
526
538
  basePath: `${systemPath}/functions`,
527
539
  functions: apiFunctions,
@@ -531,6 +543,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
531
543
  scope,
532
544
  records: (session) => callerRecords(deps, session),
533
545
  channels,
546
+ live: refresh,
534
547
  decryptField,
535
548
  ...auth && auth.personalMail.length > 0 && { personalMailer: auth.personalMailer },
536
549
  onError,
@@ -575,6 +588,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
575
588
  keys: apiKeys,
576
589
  verify: verifyGoTrue
577
590
  }),
591
+ live: refresh,
578
592
  onError
579
593
  }));
580
594
  app.route("/", batchRoute(deps, authenticate, meta));
@@ -663,7 +677,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
663
677
  if (engine) app.route(`${systemPath}/workflows/tasks`, engine.routes.tasks());
664
678
  if (engine?.routes.runners) app.route(`${systemPath}/runners/v1`, engine.routes.runners());
665
679
  if (engine?.routes.runnerInstall) app.route(`${systemPath}/runners/install.sh`, engine.routes.runnerInstall());
666
- if (appModels.some((model) => model.live) || deps.calls) app.route(systemPath || "/", guarded((live) => void live.route("/", liveRoutes(feed, (session) => visibleNotices(deps, session))), withAnonymous(authenticate, options.roles)));
680
+ if (noticed) app.route(systemPath || "/", guarded((live) => void live.route("/", liveRoutes(feed, (session) => visibleNotices(deps, session))), withAnonymous(authenticate, options.roles)));
667
681
  if (engine) app.route(`${systemPath}/workflows`, guarded((routes) => void routes.route("/", engine.routes.issue())));
668
682
  app.route(basePath, api);
669
683
  app.route(`${deps.systemPath}/meta`, metaApp);
@@ -684,6 +698,7 @@ const createAdmin = ({ resources: appResources, views: appViews = [], userTables
684
698
  subscriptions,
685
699
  functions: apiFunctions,
686
700
  channels,
701
+ live: refresh,
687
702
  schema: changes,
688
703
  log: (line) => console.log(line),
689
704
  ...table && { table },
package/dist/deps.d.ts CHANGED
@@ -13,6 +13,7 @@ import { MapSettings } from "./maps/map-settings.js";
13
13
  import { PluginOption } from "./plugins/plugin-settings.js";
14
14
  import { SourceOption } from "./sources/source-settings.js";
15
15
  import { ScanGuard } from "./scan-guard.js";
16
+ import { LiveTokens } from "./live/token/live-tokens.js";
16
17
  import { PageModel, Translations } from "@protobase/layout";
17
18
  import { Locale } from "@protobase/schema/internal";
18
19
  import { BottomBarModel, ResolveOptions, UserMenuModel, ViewModel } from "@protobase/schema";
@@ -104,5 +105,7 @@ export type Deps = {
104
105
  mailSenders?: (userId: string) => Promise<MailSender[]>;
105
106
  /** With `calls`: the app's calls, which functions admit members to and the records' readers follow. */
106
107
  calls?: CallsService;
108
+ /** With the relay: the live tokens a list or record read of a live resource gives on `Prefer: live`. */
109
+ liveTokens?: LiveTokens;
107
110
  };
108
111
  //#endregion
@@ -5,6 +5,7 @@ import { Caller } from "../api-keys/resolve-caller.js";
5
5
  import { SocketEvents } from "./function-socket.js";
6
6
  import { CallsAccess } from "../calls/calls-access.js";
7
7
  import { ChannelSender } from "../channels/channel-sender.js";
8
+ import { LiveRefresh } from "../live/refresh/live-refresh.js";
8
9
  import { FunctionRecords } from "./records.js";
9
10
  import { Capability } from "@protobase/schema";
10
11
  import { ScopedDb } from "@protobase/query";
@@ -34,6 +35,8 @@ export type PublicFunctionContext = {
34
35
  acceptWebSocket: (events: SocketEvents) => Response;
35
36
  /** Admits a member to a call's media, over the socket the function accepts: see `CallsAccess`. */
36
37
  calls: CallsAccess;
38
+ /** Tells a person's open pages to read again once their access changed: `live.refresh({ user })`, see `LiveRefresh`. */
39
+ live: LiveRefresh;
37
40
  };
38
41
  /** Who called a function, and the app's resources as them. */
39
42
  export type FunctionCaller = {
@@ -72,6 +75,8 @@ export type KeyFunctionContext = {
72
75
  db: ScopedDb;
73
76
  /** The caller of the `apikey` header and bearer token: rejects with a 401 problem when they admit nobody. */
74
77
  caller: () => Promise<Caller>;
78
+ /** Tells a person's open pages to read again once their access changed: `live.refresh({ user })`, see `LiveRefresh`. */
79
+ live: LiveRefresh;
75
80
  };
76
81
  /** A Web-standard handler. Its request's path is the part after `/api/functions/<name>`: `/` or `/more/parts`. */
77
82
  export type FunctionHandler = (request: Request, context: FunctionContext) => Response | Promise<Response>;
@@ -2,6 +2,7 @@ import { forbidden, notFound } from "../problem.js";
2
2
  import { namingTimeouts } from "../statement-timeout.js";
3
3
  import { auditOrigin } from "../audit/origin.js";
4
4
  import { invokeFunction } from "./define-function.js";
5
+ import { liveRefresh } from "../live/refresh/live-refresh.js";
5
6
  import { socketAcceptor } from "./accept-socket.js";
6
7
  import { functionGate, requireGate } from "./function-gate.js";
7
8
  import { runInBackground } from "../background-work.js";
@@ -33,7 +34,7 @@ const isUpgrade = (request) => request.headers.get("upgrade")?.toLowerCase() ===
33
34
  * A function may answer an upgrade with a socket, only once it returned. While it is open, its caller is checked again
34
35
  * every minute: a protected function's always, a public one's once `caller()` resolved.
35
36
  */
36
- const functionRoutes = ({ basePath, functions, authenticate, access, db, records, channels, decryptField, personalMailer = noPersonalMail, onError, wake, upgradeWebSocket, upgradeAuthenticate = authenticate, calls, report, scope }) => {
37
+ const functionRoutes = ({ basePath, functions, authenticate, access, db, records, channels, live = liveRefresh(void 0), decryptField, personalMailer = noPersonalMail, onError, wake, upgradeWebSocket, upgradeAuthenticate = authenticate, calls, report, scope }) => {
37
38
  const app = new Hono().basePath(basePath);
38
39
  app.onError(onError);
39
40
  const sessionOf = (request) => isUpgrade(request) ? upgradeAuthenticate(request) : authenticate(request);
@@ -77,6 +78,7 @@ const functionRoutes = ({ basePath, functions, authenticate, access, db, records
77
78
  name,
78
79
  db: scopedDb(db, (await scope()).tables, void 0),
79
80
  channels,
81
+ live,
80
82
  caller: resolveCaller,
81
83
  acceptWebSocket: acceptor.accept,
82
84
  calls: callsAccess(calls, resolveCaller)
@@ -106,6 +108,7 @@ const functionRoutes = ({ basePath, functions, authenticate, access, db, records
106
108
  name,
107
109
  db: scopedDb(db, tables, organizationOf(caller.session)),
108
110
  channels,
111
+ live,
109
112
  ...caller,
110
113
  caller: async () => caller,
111
114
  decryptField: decryptField(reader),
@@ -2,6 +2,7 @@ import { notFound, unauthorized } from "../problem.js";
2
2
  import { namingTimeouts } from "../statement-timeout.js";
3
3
  import { supabaseFunctionsPath } from "../supabase-paths.js";
4
4
  import { invokeFunction } from "./define-function.js";
5
+ import { liveRefresh } from "../live/refresh/live-refresh.js";
5
6
  import { runInBackground } from "../background-work.js";
6
7
  import { relativeRequest } from "./routes.js";
7
8
  import { Hono } from "hono";
@@ -16,7 +17,7 @@ import { cors } from "hono/cors";
16
17
  * `/<name>/more/parts`, and a CORS preflight, which carries no key, reaches it unchecked. Every other function is a 404
17
18
  * here, and none of its code runs.
18
19
  */
19
- const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError }) => {
20
+ const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, live = liveRefresh(void 0), onError }) => {
20
21
  const app = new Hono().basePath(supabaseFunctionsPath);
21
22
  app.onError(onError);
22
23
  const hasKeys = keys.publishable !== void 0 || keys.secret !== void 0;
@@ -40,7 +41,8 @@ const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError })
40
41
  const context = {
41
42
  name,
42
43
  db: scopedDb(db, (await scope()).tables, void 0),
43
- caller: () => resolved ??= caller(c.req.raw)
44
+ caller: () => resolved ??= caller(c.req.raw),
45
+ live
44
46
  };
45
47
  return invokeFunction(name, fn, request, context);
46
48
  }
@@ -49,7 +51,8 @@ const supabaseFunctionRoutes = ({ functions, db, scope, keys, caller, onError })
49
51
  return invokeFunction(name, fn, request, {
50
52
  name,
51
53
  db: scopedDb(db, (await scope()).tables, void 0),
52
- caller: async () => resolved
54
+ caller: async () => resolved,
55
+ live
53
56
  });
54
57
  }), { longQueries: options.longQueries }));
55
58
  }
@@ -3,7 +3,7 @@ import { checkedSort } from "./filter-input.js";
3
3
  import { requestAccess, requireOperation } from "./request-access.js";
4
4
  import { exposeRow, pickFields } from "./rows.js";
5
5
  import { labelRequests, relatedLabels } from "./related-labels.js";
6
- import { readTransaction } from "./transactions.js";
6
+ import { readTransaction, snapshotReadTransaction } from "./transactions.js";
7
7
  import { deletedRows, listParams, pageSizeOf, parseParams, seekParams, selectedFields } from "./params.js";
8
8
  import { readFilter } from "./related-filter.js";
9
9
  import { etagAlias } from "./sql-parts.js";
@@ -21,9 +21,10 @@ const exactCountLimit = 1e4;
21
21
  * so a hidden field is refused exactly like an unknown one; the access row filter is applied by the query layer.
22
22
  * `labels` names the records the returned relations point at, each read under the related resource's own access, and
23
23
  * `photos` brings each record's first photos, read under the photos' resource's own access. `limit_per` keeps the first
24
- * rows per value of a field, by value and in the list's order within each, with no further page.
24
+ * rows per value of a field, by value and in the list's order within each, with no further page. `live` asks for a live
25
+ * token of the read (`token`), for a live resource when the app has one to give: the read then runs in one snapshot.
25
26
  */
26
- const listRecords = async (deps, entry, session, input, maxFilterLength, jump = false, within) => {
27
+ const listRecords = async (deps, entry, session, input, maxFilterLength, jump = false, within, live = false) => {
27
28
  const params = jump ? parseParams(seekParams, input) : parseParams(listParams, input);
28
29
  const access = await requestAccess(deps, entry, session);
29
30
  requireOperation(access, "list");
@@ -77,7 +78,8 @@ const listRecords = async (deps, entry, session, input, maxFilterLength, jump =
77
78
  scope
78
79
  });
79
80
  const position = jump ? params.position : void 0;
80
- const result = await readTransaction(deps.db, deps.statementTimeoutMs, async (trx) => {
81
+ const subject = live && entry.model.live && deps.liveTokens ? await deps.liveTokens.subject(session) : void 0;
82
+ const result = await (subject ? snapshotReadTransaction : readTransaction)(deps.db, deps.statementTimeoutMs, async (trx) => {
81
83
  const extraColumns = entry.etag && etags ? [{
82
84
  field: entry.etag.field.name,
83
85
  as: "text",
@@ -110,13 +112,21 @@ const listRecords = async (deps, entry, session, input, maxFilterLength, jump =
110
112
  permissions: permitted ? await rowPermissions(trx, access, rows) : void 0,
111
113
  estimate: await estimateCount(trx, queryModel, filter, scope),
112
114
  ...params.count === "exact" && { counted: await countUpTo(trx, queryModel, 10001, filter, scope) },
113
- ...params.labels !== void 0 && { labels: await relatedLabels(trx, labels, rows) }
115
+ ...params.labels !== void 0 && { labels: await relatedLabels(trx, labels, rows) },
116
+ token: subject && await deps.liveTokens.seal(trx, subject, {
117
+ resource: entry.name,
118
+ model: queryModel,
119
+ scope,
120
+ ...filter && { filter },
121
+ fields: columns ?? Object.keys(model.fields)
122
+ })
114
123
  };
115
124
  });
116
125
  const shown = await presentFiles(access, result.rows);
117
126
  const included = photos && await recordPhotos(deps, photos, model, result.rows);
118
127
  return {
119
128
  warning: warning ?? included?.warning,
129
+ token: result.token,
120
130
  body: {
121
131
  items: shown.map((row, i) => ({
122
132
  ...pickFields(row, columns),
@@ -1,4 +1,5 @@
1
1
  import { parseParams } from "../params.js";
2
+ import "./refresh/refresh-notices.js";
2
3
  import { Hono } from "hono";
3
4
  import { z } from "zod";
4
5
  import { streamSSE } from "hono/streaming";
@@ -10,18 +11,20 @@ const heartbeatMs = 25e3;
10
11
  const later = (id, than) => BigInt(id) > BigInt(than);
11
12
  /**
12
13
  * `GET /live`: the changes of the live resources the caller may read, as they come, keys only. `visibleTo` says which
13
- * notices a caller hears of (`visibleNotices`).
14
+ * notices a caller hears of (`visibleNotices`), for the access the caller connected with: a `refresh` ends the stream,
15
+ * so the page connects again from its cursor as its access is now.
14
16
  */
15
17
  const liveRoutes = (feed, visibleTo) => {
16
18
  const app = new Hono();
17
19
  app.get("/live", async (c) => {
18
20
  const { after } = parseParams(params, c.req.query());
19
21
  const visible = await visibleTo(c.get("session"));
20
- const changesOf = (notices) => notices.filter(visible).map(({ resource, key, operation }) => ({
22
+ const changesOf = (notices) => notices.filter((notice) => notice.resource !== "$live" && visible(notice)).map(({ resource, key, operation }) => ({
21
23
  resource,
22
24
  key,
23
25
  operation
24
26
  }));
27
+ const refreshes = (notices) => notices.some((notice) => notice.resource === "$live" && visible(notice));
25
28
  const queue = [];
26
29
  let wake = () => {};
27
30
  const held = [];
@@ -38,6 +41,10 @@ const liveRoutes = (feed, visibleTo) => {
38
41
  type: "resync",
39
42
  cursor
40
43
  });
44
+ else if (refreshes(caught)) queue.push({
45
+ type: "refresh",
46
+ cursor
47
+ });
41
48
  else if (changesOf(caught).length > 0) queue.push({
42
49
  type: "changes",
43
50
  cursor,
@@ -52,7 +59,11 @@ const liveRoutes = (feed, visibleTo) => {
52
59
  if (fresh.length === 0) return;
53
60
  cursor = fresh.at(-1).id;
54
61
  const changes = changesOf(fresh);
55
- if (changes.length > 0) queue.push({
62
+ if (refreshes(fresh)) queue.push({
63
+ type: "refresh",
64
+ cursor
65
+ });
66
+ else if (changes.length > 0) queue.push({
56
67
  type: "changes",
57
68
  cursor,
58
69
  changes
@@ -69,8 +80,12 @@ const liveRoutes = (feed, visibleTo) => {
69
80
  }, heartbeatMs);
70
81
  while (!stream.aborted) {
71
82
  const event = queue.shift();
72
- if (event) await stream.writeSSE({ data: JSON.stringify(event) });
73
- else await new Promise((resolve) => wake = resolve);
83
+ if (!event) {
84
+ await new Promise((resolve) => wake = resolve);
85
+ continue;
86
+ }
87
+ await stream.writeSSE({ data: JSON.stringify(event) });
88
+ if (event.type === "refresh") return;
74
89
  }
75
90
  };
76
91
  return streamSSE(c, (stream) => follow(stream).finally(() => {
@@ -0,0 +1,13 @@
1
+ //#region src/live/refresh/live-refresh.d.ts
2
+ /** What a server function tells open pages with: `refresh({ user })` once a person's access changed. */
3
+ export type LiveRefresh = {
4
+ /**
5
+ * Tells the open pages of `user`, by their id, to read what they show again, which gives them new live tokens for
6
+ * their access as it is now: call it once the change of their roles or memberships committed. Subqueries of access
7
+ * rules are evaluated when a token is issued, so a token made before stays as it was until then.
8
+ */
9
+ refresh: (options: {
10
+ user: string;
11
+ }) => Promise<void>;
12
+ };
13
+ //#endregion
@@ -0,0 +1,8 @@
1
+ //#region src/live/refresh/live-refresh.ts
2
+ /** Refreshes through `write`, the notices' writer, or does nothing for an app without live resources, whose pages hold no tokens. */
3
+ const liveRefresh = (write) => ({ refresh: async ({ user }) => {
4
+ if (!write) return;
5
+ await write([user]);
6
+ } });
7
+ //#endregion
8
+ export { liveRefresh };
@@ -0,0 +1,21 @@
1
+ import { quoteIdent } from "../../changes/capture-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/live/refresh/refresh-notices.ts
4
+ /** The resource of a notice that tells one user's pages their access changed, keyed by the user's id. */
5
+ const refreshNotice = "$live";
6
+ const textArray = (values) => `{${values.map((value) => JSON.stringify(value)).join(",")}}`;
7
+ /**
8
+ * Tells these users' open pages, through the live stream's notices, that what they may read changed, so they read
9
+ * again and get new live tokens. The table is locked against other writers first, so the notice commits in the order
10
+ * of its id and no reader skips it.
11
+ */
12
+ const writeRefreshNotices = async (db, schema, userIds) => {
13
+ if (userIds.length === 0) return;
14
+ const table = sql.raw(`${quoteIdent(schema)}."notices"`);
15
+ await db.transaction().execute(async (trx) => {
16
+ await sql`lock table ${table} in share row exclusive mode`.execute(trx);
17
+ await sql`insert into ${table} ("resource", "record_key", "operation") select ${refreshNotice}, u, 'update' from unnest(${textArray([...new Set(userIds)])}::text[]) as u`.execute(trx);
18
+ });
19
+ };
20
+ //#endregion
21
+ export { refreshNotice, writeRefreshNotices };