@protobase/cli 0.51.2 → 0.52.0

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 (56) hide show
  1. package/dist/build/app-icons.js +2 -1
  2. package/dist/build/favicon-file.js +5 -0
  3. package/dist/build/favicon-ico.js +20 -0
  4. package/dist/build/favicon.js +1 -2
  5. package/dist/build/service-worker-code.js +1 -1
  6. package/dist/cli/package.js +1 -1
  7. package/dist/config/build-project.js +1 -0
  8. package/dist/dev/entry.js +2 -1
  9. package/dist/doctor/relation-issues.js +13 -0
  10. package/dist/doctor/run.js +6 -1
  11. package/dist/migration/adopt-public-record.js +15 -0
  12. package/dist/migration/apply-migrations.js +8 -4
  13. package/dist/migration/load-project.js +1 -0
  14. package/dist/migration/parts.js +6 -1
  15. package/dist/project/favicon-link.js +12 -2
  16. package/dist/project/project-admin.js +1 -0
  17. package/dist/project/service-worker.js +1 -1
  18. package/dist/scaffold/plan.d.ts +2 -0
  19. package/dist/scaffold/plan.js +7 -3
  20. package/dist/scaffold/protobase-tables.d.ts +1 -1
  21. package/dist/scaffold/protobase-tables.js +8 -1
  22. package/dist/scaffold/referenced.d.ts +6 -0
  23. package/dist/scaffold/referenced.js +38 -0
  24. package/dist/scaffold/run.js +2 -1
  25. package/dist/scaffold/tables.d.ts +2 -1
  26. package/dist/scaffold/tables.js +18 -9
  27. package/dist/scaffold-api.d.ts +2 -1
  28. package/dist/scaffold-api.js +2 -1
  29. package/dist/serve/lifecycle.js +2 -1
  30. package/dist/serve/static-site.js +3 -0
  31. package/dist/supabase/dump-phase.js +12 -10
  32. package/dist/supabase/load-phase.js +5 -6
  33. package/dist/supabase/platform-schemas.js +42 -0
  34. package/dist/supabase/project-users.d.ts +10 -0
  35. package/dist/supabase/project-users.js +38 -0
  36. package/dist/supabase/realtime-policies.js +8 -24
  37. package/dist/supabase/realtime-schema.js +73 -0
  38. package/dist/supabase/report.js +1 -1
  39. package/dist/supabase/source-facts.js +3 -35
  40. package/dist/supabase/users-migrations.js +2 -2
  41. package/package.json +7 -7
  42. package/skills/protobase/references/features/ai.md +5 -0
  43. package/skills/protobase/references/features/compatibility.md +1 -1
  44. package/skills/protobase/references/features/look-and-language.md +1 -1
  45. package/skills/protobase/references/getting-started.md +5 -3
  46. package/skills/protobase/references/guides/deploy.md +1 -1
  47. package/skills/protobase/references/reference/app-identity.md +3 -1
  48. package/skills/protobase/references/reference/assistant.md +2 -2
  49. package/skills/protobase/references/reference/cli.md +8 -8
  50. package/skills/protobase/references/reference/comments.md +2 -0
  51. package/skills/protobase/references/reference/config/api.md +13 -2
  52. package/skills/protobase/references/reference/config.md +1 -1
  53. package/skills/protobase/references/reference/mcp.md +43 -10
  54. package/skills/protobase/references/reference/notifications.md +1 -1
  55. package/skills/protobase/references/reference/supabase-realtime.md +30 -4
  56. package/skills/protobase/references/reference/webhooks.md +1 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  # API options
4
4
 
5
- The config keys of the REST API, its path, keys, CORS, access defaults, query limits, error reporting, write hooks, MCP tools, remote resources and runtime updates, and the files of the API's own hooks.
5
+ The config keys of the REST API, its path, keys, CORS, access defaults, query limits, error reporting, write hooks, MCP tools, remote resources, runtime updates and Realtime across processes, and the files of the API's own hooks.
6
6
 
7
7
  The keys of the API, at the top level of [`protobase.config.ts`](../config.md). The API itself is described in [REST API](../api.md).
8
8
 
@@ -115,7 +115,7 @@ export default defineConfig({ writeHooks: ['queue-sent-invoice'] })
115
115
  ## mcpEndpoint
116
116
 
117
117
  - **Type:** `{ sql?: boolean; writes?: boolean | { resources?: string[]; rolesWithoutApproval?: string[] } } | false`
118
- - **Default:** the read tools only: `list_resources`, `list_records` and `get_record`
118
+ - **Default:** the read tools only: `list_resources`, `list_records`, `count_records` and `get_record`
119
119
 
120
120
  The MCP endpoint's tools; [`auth.mcp`](sign-in.md#authmcp) turns the endpoint on. `sql: true` also offers admins and the `ai` role `run_read_only_query`, which reads the whole database outside the access rules. `writes: true` offers `create_record`, `update_record`, `delete_record` and `batch_write` through the REST API's rules, each approved by the person in their client; `writes.resources` limits them to the resources named, and `writes.rolesWithoutApproval` lets holders of those roles, such as a service account, write without the approval. `false` is for a host that serves its own MCP endpoint at `auth.mcp.path`, in front of this app. See [MCP](../mcp.md#the-tools).
121
121
 
@@ -149,6 +149,17 @@ The endpoint that reports the app's runtime version and updates it, such as a ho
149
149
  export default defineConfig({ runtimeUpdates: false })
150
150
  ```
151
151
 
152
+ ## realtime
153
+
154
+ - **Type:** `{ processes?: 'one' | 'many' }`
155
+ - **Default:** `{ processes: 'one' }`
156
+
157
+ How [Supabase Realtime](../supabase-realtime.md) is served. With `'one'`, one process serves the app, and broadcasts and presence go between its channels in memory. Set `'many'` when several processes serve the app behind one address: broadcasts and presence then go between the processes through the `realtime_relay` schema of the app's database, which [`protobase migration`](../cli.md#migration) writes and the server checks at start. See [Several processes](../supabase-realtime.md#several-processes).
158
+
159
+ ```ts
160
+ export default defineConfig({ realtime: { processes: 'many' } })
161
+ ```
162
+
152
163
  ## Code of the API
153
164
 
154
165
  Two files of the project's own change what the API does, each its default export, with no key in the config:
@@ -28,7 +28,7 @@ Each key is described with its type and default in the option pages:
28
28
  | --- | --- |
29
29
  | [App options](config/app.md) | `name`, `url`, `secret`, `previousSecrets`, `locale`, `timezone`, `themeColor`, `backgroundColor`, `mobile` |
30
30
  | [Sign-in options](config/sign-in.md) | `auth`, `authenticate`, `signingKeyDays`, `signingKeyGraceDays` |
31
- | [API options](config/api.md) | `apiPath`, `apiKeys`, `cors`, `defaultAccess`, `rowPermissions`, `statementTimeoutMs`, `scanGuard`, `errorReporting`, `writeHooks`, `mcpEndpoint`, `remoteResources`, `runtimeUpdates` |
31
+ | [API options](config/api.md) | `apiPath`, `apiKeys`, `cors`, `defaultAccess`, `rowPermissions`, `statementTimeoutMs`, `scanGuard`, `errorReporting`, `writeHooks`, `mcpEndpoint`, `remoteResources`, `runtimeUpdates`, `realtime` |
32
32
  | [Admin app options](config/admin-app.md) | `assistant`, `maps`, `plugins` |
33
33
  | [Jobs and events options](config/jobs-and-events.md) | `jobs`, `events`, `history`, `webhooks`, `notifications` |
34
34
  | [Files options](config/files.md) | `files` |
@@ -2,7 +2,7 @@
2
2
 
3
3
  # MCP
4
4
 
5
- The app's MCP endpoint, through which a person's AI client lists resources, finds and reads records, and, when turned on, creates and updates them with that person's access and approval.
5
+ The app's MCP endpoint, through which a person's AI client lists resources, finds and reads records and their comments, and, when turned on, creates and updates them with that person's access and approval.
6
6
 
7
7
  An app can serve an MCP endpoint: a person adds its address to an AI client that speaks MCP, such as a chat assistant or a code editor, signs in on the app and allows the client. The client then works with that person's access: it lists the resources and fields they may read, finds records with the API's filters, sorting and pages, and reads one record.
8
8
 
@@ -29,6 +29,10 @@ Give the client the endpoint's address. It finds the app's sign-in from there, o
29
29
 
30
30
  Some take the address on the command line instead, as a server with the HTTP transport, and sign in when you first use it.
31
31
 
32
+ ## The app's icon
33
+
34
+ The endpoint names the app's [icon](app-identity.md#the-icons) to the client when it connects (`serverInfo.icons`), at absolute addresses on the app's origin: the project's 192 pixel, touch and 512 pixel PNGs it has, then its `protobase.favicon.svg`, or Protobase's without one. A client that draws server icons shows it beside the app's name. <gap>An app without PNGs of its own cannot offer clients that draw no SVG an icon because PNG versions of Protobase's icon are not implemented.</gap>
35
+
32
36
  ## The tools
33
37
 
34
38
  Each tool reads as the signed-in person: their role's access rules, row filters, tenant and hidden fields apply as in the [REST API](api.md#access).
@@ -37,12 +41,30 @@ Each tool reads as the signed-in person: their role's access rules, row filters,
37
41
  | --- | --- |
38
42
  | `list_resources` | The resources the person may read, with their labels, key, whether they soft delete (`soft_delete`) and fields: each field's type, label, enum values, the resource a relation links to, and whether filters and sorts take it. |
39
43
  | `list_records` | A page of a resource's records: `filter` in the API's [filter syntax](api.md#filters), `order_by`, `page_size` (20 by default, at most 100) and `page_token`, with `next_page_token` for the next page. `show_deleted: true` also returns soft-deleted records. |
40
- | `get_record` | One record by its key, with its ETag. A composite key is passed as the values of its fields, in order. `show_deleted: true` also finds a soft-deleted record. |
44
+ | `count_records` | How many records a `filter` finds, without returning them: `{ count }` as the API's `count=exact` counts, or `{ more_than: 10000, estimate }` when more match. With `group_by`, a filterable field, the count per value instead, as [`:aggregate`](api.md#routes) gives it: `{ group_by, groups: [{ value, count }] }`, largest first, adding up to what the filter finds, the first `limit` (100 by default, at most 1,000), with `label` naming a relation's values by a field of the records they link to. A date or timestamp `group_by` counts per day over the last 30 days. `show_deleted: true` also counts soft-deleted records. |
45
+ | `get_record` | One record by its key, with its ETag. A composite key is passed as the values of its fields, in order. `show_deleted: true` also finds a soft-deleted record. With `field`, it reads that one field alone, `max_chars` characters (20,000 by default, at most 30,000) from `offset`, and gives its whole `length` and the `next_offset` to read on from. |
46
+
47
+ `show_deleted` works as the [REST API](api.md#routes)'s: it applies only to a resource with a soft delete, and is refused on any other. <gap>`count_records` cannot count soft-deleted records per value because `:aggregate` does not implement `show_deleted`.</gap> Soft-deleted records come under the same access rules, tenant and hidden fields as the rest, and carry the field their deletion set.
48
+
49
+ ### Result size
50
+
51
+ The result of each tool that returns records, and of `run_read_only_query`, stays within 40,000 characters of JSON, below what clients take as one tool result, and stays valid JSON when it is cut. Over that, long text values are cut first, each named in `cut_fields` with its path and full length, such as `{ "field": "items[3].body", "length": 52341 }`. When that is not enough, `list_records` returns fewer records, with the `next_page_token` that goes on after the last one, and `run_read_only_query` fewer rows, marked `truncated`. A `note` then says how to read the rest: `get_record` with `field` and `offset` for a cut field, or `OFFSET` and `substring` in SQL.
41
52
 
42
- `show_deleted` works as the [REST API](api.md#routes)'s: it applies only to a resource with a soft delete, and is refused on any other. Soft-deleted records come under the same access rules, tenant and hidden fields as the rest, and carry the field their deletion set.
53
+ <gap>`list_resources` and the app's own tools cannot cut a result to the size budget because a budget outside the record and SQL tools is not implemented.</gap> An app with very many resources, or a tool of its own, keeps its results small itself.
43
54
 
44
55
  A refusal, such as a resource the person may not read or a bad filter, comes back to the client as text it can act on, `{ "error": ..., "message": ... }`.
45
56
 
57
+ ### Comments
58
+
59
+ When a resource takes [comments](comments.md), the endpoint also offers `list_comments`, and with [writes](#writes) on, `add_comment`. They go through the same service as the REST API's comments, as the person: whoever may read a record may read its comments and add one, and everyone else gets the same refusal as from `GET` or `POST /api/v1/{resource}/{key}:comments`. An app without a resource with comments offers neither.
60
+
61
+ | Tool | What it does |
62
+ | --- | --- |
63
+ | `list_comments` | A page of a record's comments, newest first, each as `{ author, created_at, text }`, the author's `name` beside their `id` when the app's auth knows it. `page_size` (20 by default, at most 100) and `page_token`, with `next_page_token` for the next page. |
64
+ | `add_comment` | Adds `text` as the person's comment on one record, and returns it as `list_comments` gives it. |
65
+
66
+ `add_comment` is a write: the person approves each comment first, seeing the record's name and the whole comment, unless they hold one of the [roles without approval](#writes-without-approval). With writes limited to some resources, it comments only on those. A comment it adds mentions nobody, so it sends no emails. An empty comment, one over 10,000 characters, a resource without comments, and a record the person may not read, or one that is soft-deleted, are refused before asking.
67
+
46
68
  ### SQL for admins
47
69
 
48
70
  `mcpEndpoint.sql` also offers `run_read_only_query`, as in the [assistant](assistant.md#the-built-in-backend), to people with the `admin` or `ai` role:
@@ -63,8 +85,8 @@ export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: true }
63
85
 
64
86
  | Tool | What it does |
65
87
  | --- | --- |
66
- | `create_record` | Creates a record of a resource from `data`, field names to values, and returns it with its ETag. |
67
- | `update_record` | Changes the fields in `data` of one record by its key, and returns it with its new ETag. With the `etag` that `get_record` gave, it fails when someone changed the record since. It does not set the field a soft delete sets: a delete goes through `delete_record`. |
88
+ | `create_record` | Creates a record of a resource from `data`, field names to values, and returns its key and ETag with the fields it wrote, see [What a write returns](#what-a-write-returns). |
89
+ | `update_record` | Changes the fields in `data` of one record by its key, and returns its key and new ETag with the fields it set. With the `etag` that `get_record` gave, it fails when someone changed the record since. It does not set the field a soft delete sets: a delete goes through `delete_record`. |
68
90
  | `delete_record` | Deletes one record by its key and the `etag` that `get_record` gave, and fails when someone changed the record since. A resource with a [soft delete](data-config.md) keeps the record, deleted; any other loses it for good. |
69
91
  | `batch_write` | Creates, updates and deletes records across resources in one transaction, see [Batch writes](#batch-writes). |
70
92
 
@@ -82,6 +104,16 @@ mcpEndpoint: { writes: { resources: ['tasks'] } }
82
104
 
83
105
  The write tools then name those resources in their descriptions, and refuse a write to any other before asking, with `{ "error": "forbidden", "message": ... }` saying which resources they write; nothing is written. A name the app has no resource for stops the server at startup. The list only narrows the writes: the person's access rules still apply on the listed resources.
84
106
 
107
+ #### What a write returns
108
+
109
+ A write returns its record small, so changing one field of a large record does not send the whole record back:
110
+
111
+ ```json
112
+ { "key": 42, "etag": "\"7\"", "record": { "status": "done", "updated_at": "2026-10-27T09:00:00Z" } }
113
+ ```
114
+
115
+ `key` is the record's key as the tools take it, the values of its key fields in order when it has several; `etag` is its new ETag, for a later write. `record` holds the fields the write set, as stored, and the [read-only](data-config.md#field-options) fields that changed with it, such as a formula, a rollup or an update time; a create counts every read-only field that has a value. A `fields` argument, a list of field names, adds those fields, and `["*"]` returns the whole record. A field the person may not read stays out, and for a resource they may not read at all the key and the read-only fields stay out too.
116
+
85
117
  #### Writes without approval
86
118
 
87
119
  An app that runs service accounts over MCP, such as a backend job or an agent with no person present, names their roles in `mcpEndpoint.writes`:
@@ -109,9 +141,9 @@ No role is exempt unless named. The roles are checked against the signed-in user
109
141
  ] }
110
142
  ```
111
143
 
112
- An update needs the `etag` the record was read with, or `"*"` for any version; a delete's `etag` is optional, and without one it deletes any version. A create may name itself with `ref`, and a later operation's key or data value `{ "$ref": "<name>" }` is that record's key. The result is `{ "results": [...] }`, as the REST batch answers: each created or updated record with its new ETag, so the client can go on writing.
144
+ An update needs the `etag` the record was read with, or `"*"` for any version; a delete's `etag` is optional, and without one it deletes any version. A create may name itself with `ref`, and a later operation's key or data value `{ "$ref": "<name>" }` is that record's key. The result is `{ "results": [...] }`, one per operation in order: a create or an update gives its `op`, `resource`, a create's `ref`, and its record as [a write returns it](#what-a-write-returns), with an operation's own `fields` for more, and a delete `{ "op": "delete", "resource": ..., "deleted": true }`. The read-only fields an update changed are told against the record as read just before the batch runs; an update of a record created in the same batch, by `$ref`, counts every read-only field that has a value.
113
145
 
114
- The person approves the batch once, seeing each write in it: how many creates, updates and deletes it makes on each resource, then each operation with its key and data, the first 50 in full and the rest counted. The approval says plainly when deletes in it cannot be undone, which is every delete on a resource that does not [soft delete](data-config.md#resource).
146
+ The person approves the batch once, in their language, seeing each write in it named and listed as the approval of a single write names and lists it: `2. Update Task #42 "Fix the sign-in lockout"` with each field it changes, a create with the new record's fields, and a delete saying whether it can be restored. A key or value pointing at a create in the batch is named by that write's number, such as `the Task from write 1`. The first 50 writes are listed and the rest counted. The approval says plainly how many deletes in it cannot be undone, which is every delete on a resource that does not [soft delete](data-config.md#resource), and an update or delete among the listed writes of a record changed since its `etag` is refused before asking.
115
147
 
116
148
  A batch is checked before the person is asked: an operation other than a create, update or delete, a field an operation does not take, an update without an ETag or more than 500 operations come back as `{ "error": "invalid-argument", "message": ... }` naming the operation, and with writes limited to some resources an operation on any other refuses the whole batch. An update does not set the field a soft delete sets, as `update_record` does not: a delete goes through a delete operation. A refusal while it runs, such as an operation the person may not do or a stale ETag, comes back with the REST batch's `operation` (its index), `op` and `resource`. Either way nothing is written.
117
149
 
@@ -126,12 +158,13 @@ The endpoint serves each request on its own, without an MCP session: a `GET` or
126
158
  `@protobase/server` exports the pieces the endpoint is made of, for an MCP server of your own with tools of your own:
127
159
 
128
160
  - `mcpHandler({ authenticate, resource, scope, server })`: the endpoint as a fetch handler. It checks the host, admits a valid token (`mcpGate`) and serves the request with the server that `server(session, request)` builds for its caller; `request` is the HTTP request, such as for the language the person reads.
129
- - `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`, with the `locale` its approvals are asked in (English when absent): each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire.
130
- - `mcpTools({ db, sql, writes })`: the default tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`.
161
+ - `mcpServer({ info, tools, context, report, rolesWithoutApproval, approvals })`: an MCP server named by `info`, its `name`, `version` and `icons`, such as `mcpIcons(origin, icons)`, the app's icons on `origin`, and offering [assistant tools](assistant.md#the-apps-own-tools), each with its JSON Schema and its `annotations`, MCP's tool hints. `context` is the tools' context without `approve`, with the `locale` its approvals are asked in (English when absent): each call gets its own, which asks the client's user, or approves at once when the session's user holds one of `rolesWithoutApproval`. `approvals` is `mcpApprovals()`, built once and passed to every server the endpoint builds: it keeps the approvals asked for until they are answered or expire.
162
+ - `mcpTools({ db, sql, writes, commented })`: the default tools for a session; `writes` is `true`, `false` or `{ resources, rolesWithoutApproval }`, and `commented` names the resources with comments.
131
163
  - `readRecordTools()`, or `listResourcesTool()`, `listRecordsTool()` and `getRecordTool()`: the read tools alone; `readOnlyQueryTool(db)` is `run_read_only_query`, and `readWriteQueryTool(db)` proposes one write statement that the user approves before it runs.
164
+ - `commentTools({ commented }, writes)`, or `listCommentsTool({ commented })` and `addCommentTool({ commented, resources })`: the comment tools on the resources named in `commented`, which call the context's `comments`, and `add_comment` only when `writes` is not `false`.
132
165
  - `writeRecordTools({ resources })`, or `createRecordTool(...)`, `updateRecordTool(...)` and `deleteRecordTool(...)`: the single write tools alone, on the listed resources or, without `resources`, on any; `batchWriteTool({ resources })` is `batch_write` alone.
133
166
  - `mcpGate({ authenticate, resource, scope })`: the token check alone, answering 401 or 403 with a challenge that names the resource's metadata.
134
- - `mcpToolContext(...)`, `mcpRoutes(app, { path, handler })` and `sessionOf(authInfo)`: the tools' context as the app builds it, the routes with open CORS, and the session a request was admitted with.
167
+ - `mcpToolContext(...)`, with the records' comments as `comments`, `mcpRoutes(app, { path, handler })` and `sessionOf(authInfo)`: the tools' context as the app builds it, the routes with open CORS, and the session a request was admitted with.
135
168
 
136
169
  A host that builds its own server around `createAdmin`, rather than running the project with `protobase dev` or `protobase serve`, can serve its own endpoint at `auth.mcp.path` instead: `mcpEndpoint: false` (`createAdmin`'s `options.mcp`) turns Protobase's off, and the host mounts its own in front of `createAdmin`'s app. The OAuth provider and its discovery stay, and `createAdmin` answers 404 at the path and under it. `protobase dev` and `protobase serve` have no place to mount another endpoint, so in a project served by them `mcpEndpoint: false` only turns the endpoint off.
137
170
 
@@ -143,7 +143,7 @@ The paths come from `historyPath('/api')`, `historyPath('/api', 'unread')`, `his
143
143
  The bell lists notifications only in its panel; there is no page of all notifications.
144
144
  :::
145
145
 
146
- With notifications on, every signed-in user sees a bell in the top bar with how many of their notifications are unread. Its panel is their inbox: the newest notifications [sent](#sending) with the inbox flag on, never those sent without it, the unread ones in bold, each with how long ago it came. Opening one marks it read and goes to its page: in the app for your own pages, in a new tab for other sites. A notification without a `url` is not a link. "Mark all as read" marks those the panel shows read, and "Show more" brings older ones.
146
+ With notifications on, every signed-in user sees a bell in the top bar with how many of their notifications are unread. Its panel is their inbox: the newest notifications [sent](#sending) with the inbox flag on, never those sent without it, the unread ones in bold, each with how long ago it came. Opening one marks it read and goes to its page in the app, in the same tab: inbox links stay within the app, since the [history](#history) never answers a `url` on another site. A notification without a `url` is not a link. "Mark all as read" marks those the panel shows read, and "Show more" brings older ones.
147
147
 
148
148
  The panel also offers to turn push on for this device, where the device can receive it: a browser with Web Push, when the app has [its keys](#web-push). The browser asks for permission only once the user clicks "Turn on", never when a page loads. Once push is on, the panel says so with a way to turn it off. When the browser blocks notifications, the panel says so and how to allow them again, and offers to turn push on once they are allowed.
149
149
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Supabase Realtime
4
4
 
5
- The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence, on public and private channels.
5
+ The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence, on public and private channels, and broadcasts from the database.
6
6
 
7
7
  An app with API keys also serves `/api/sb/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app's `/api/sb` and give it the publishable key.
8
8
 
@@ -46,7 +46,9 @@ A broadcast reaches the topic's other channels, and the sender's own with `self`
46
46
 
47
47
  Limits, near Supabase's Free plan, apply per socket and per topic. A socket sends at most 100 broadcast and presence messages a second, joins at most 100 times a second and holds at most 100 channels; on each channel it sends at most 5 presence updates in 30 seconds, also counted across a rejoin. A topic takes 100 broadcasts a second, whoever sends them, so one busy sender can use up a topic's budget. A topic is at most 255 bytes, and a tracked presence at most 10 000 bytes of JSON. A message over a limit gets an error reply and goes to no one, where Supabase would close the channel. A frame over 256 KiB closes the socket with 1009. It closes with 1008 when the client leaves more than 4 MiB unread, or sends more than 300 messages or 4 MiB while earlier ones wait, such as behind a token check.
48
48
 
49
- Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap>
49
+ ### Several processes
50
+
51
+ By default, one process serves the app, and broadcasts and presence go between its channels. When several processes serve it behind one address, set [`realtime: { processes: 'many' }`](config/api.md#realtime) and apply the migration [`protobase migration`](cli.md#migration) writes. Every channel on a topic then hears its broadcasts and presence, whichever process it joined, and so do broadcasts over the REST endpoint and from the database. Private and public channels of a topic stay apart across processes as on one. The processes share them through the `realtime_relay` schema of the app's database: each adds what it sends, and reads what the others sent ten times a second while one of its sockets is open, so a broadcast reaches another process's channels within about 100 ms. A topic's 100 broadcasts a second are counted across all the processes. A process that stops gracefully removes the presence its channels tracked; one that is killed has it removed by the others about 15 seconds after its last heartbeat, and their channels hear the leaves.
50
52
 
51
53
  ### Broadcast without a channel
52
54
 
@@ -58,7 +60,31 @@ await room.httpSend('cursor', { x: 1, y: 2 })
58
60
  await supabase.removeChannel(room)
59
61
  ```
60
62
 
61
- `POST /api/sb/realtime/v1/api/broadcast` takes Supabase's batch, `{ "messages": [{ "topic": "room", "event": "cursor", "payload": { "x": 1 }, "private": false }] }`, of at most 100 messages, each with an object payload. `httpSend()` sends one message to `POST /api/sb/realtime/v1/api/broadcast/<topic>/events/<event>`, `?private=true` for a private one, with a JSON object or, as `application/octet-stream`, binary bytes. A message reaches the channels joined on its topic in this process, under a broadcast's limits: a body is at most 256 KiB, a topic and an event at most 255 bytes each, and a request that would take a topic over its 100 broadcasts a second is refused with `429` and reaches no one. A public message reaches the topic's public channels; a private one reaches only its private channels that may receive broadcasts, and only when the caller may send broadcasts there by the [policies on `realtime.messages`](#private-channels): a batch drops one it may not send, as Supabase does, and `httpSend()` is refused with `403`. <gap>A policy cannot read a broadcast request's headers in `request.headers` because passing them to the checks is not implemented.</gap>
63
+ `POST /api/sb/realtime/v1/api/broadcast` takes Supabase's batch, `{ "messages": [{ "topic": "room", "event": "cursor", "payload": { "x": 1 }, "private": false }] }`, of at most 100 messages, each with an object payload. `httpSend()` sends one message to `POST /api/sb/realtime/v1/api/broadcast/<topic>/events/<event>`, `?private=true` for a private one, with a JSON object or, as `application/octet-stream`, binary bytes. A message reaches the channels joined on its topic, under a broadcast's limits: a body is at most 256 KiB, a topic and an event at most 255 bytes each, and a request that would take a topic over its 100 broadcasts a second is refused with `429` and reaches no one. A public message reaches the topic's public channels; a private one reaches only its private channels that may receive broadcasts, and only when the caller may send broadcasts there by the [policies on `realtime.messages`](#private-channels): a batch drops one it may not send, as Supabase does, and `httpSend()` is refused with `403`. <gap>A policy cannot read a broadcast request's headers in `request.headers` because passing them to the checks is not implemented.</gap>
64
+
65
+ ### Broadcast from the database
66
+
67
+ SQL and triggers broadcast with Supabase's `realtime.send(payload, event, topic, private)` and `realtime.broadcast_changes(topic, event, operation, table, schema, new, old)`, which [`import supabase`](cli.md#import-supabase) makes in the project's database. A trigger as Supabase's docs write one keeps working:
68
+
69
+ ```sql
70
+ create function public.todos_broadcast() returns trigger security definer language plpgsql as $$
71
+ begin
72
+ perform realtime.broadcast_changes('todos:' || coalesce(new.list_id, old.list_id), tg_op, tg_op, tg_table_name, tg_table_schema, new, old);
73
+ return null;
74
+ end
75
+ $$;
76
+
77
+ create trigger todos_broadcast after insert or update or delete on public.todos for each row execute function public.todos_broadcast();
78
+ ```
79
+
80
+ ```ts
81
+ supabase
82
+ .channel('todos:42', { config: { private: true } })
83
+ .on('broadcast', { event: 'INSERT' }, ({ payload }) => console.log(payload.record))
84
+ .subscribe()
85
+ ```
86
+
87
+ Each call inserts a message into `realtime.messages` in the caller's transaction, as on Supabase, so a transaction rolled back sends nothing. Within a second of its commit, the server takes the message out of the table and sends it to the channels joined on its topic, in the order the transaction sent them, with the message's id in the payload's `id` and in the broadcast's `meta.id`. `broadcast_changes()` sends `{ operation, table, schema, record, old_record }`, `record` and `old_record` each the whole row or `null`. `private` is `true` unless the call says `false`, as on Supabase: a private message reaches only the topic's private channels whose [policies](#private-channels) let them receive broadcasts, and a public one only its public channels. A message goes under the topic's 100 broadcasts a second, and one whose topic or event is over 255 bytes or whose payload is over 256 KiB is dropped. The server reads the table while one of its sockets is open, and a message no channel hears is dropped, as on Supabase. A call as a role the policies on `realtime.messages` do not let insert sends nothing and raises a warning, as Supabase's does, so a trigger function that sends for its callers is `security definer`. <gap>Messages sent while no socket is open stay in `realtime.messages` until one opens, because nothing else prunes the table.</gap> <gap>A project that was not imported cannot call `realtime.send()` without making Supabase's functions in a migration of its own, because Protobase's migrations do not make them.</gap>
62
88
 
63
89
  ## Private channels
64
90
 
@@ -92,7 +118,7 @@ grant usage on schema realtime to anon, authenticated;
92
118
  grant select, insert on realtime.messages to anon, authenticated;
93
119
  ```
94
120
 
95
- Each check inserts its messages in a transaction it rolls back, so the table stays empty: the app's database role must own it, or bypass row security, to insert the message a join checks. Without `realtime.messages`, every private channel is refused.
121
+ Each check inserts its messages in a transaction it rolls back, so they stay out of the table: the app's database role must own it, or bypass row security, to insert the message a join checks and to take out the messages the database broadcasts. Without `realtime.messages`, every private channel is refused.
96
122
 
97
123
  ## What a subscriber receives
98
124
 
@@ -95,6 +95,7 @@ A function target is called as the subscription's `as`, so `context.caller()` an
95
95
  - **`410 Gone`** fails the delivery at once.
96
96
  - **After the last try** the job is kept as failed, on the [failed jobs page](jobs.md#failed-jobs-page), where it can be retried.
97
97
  - **Ordered subscriptions** get no first try from the dispatch job: a `webhooks.deliver-ordered` job delivers a record's events of one dispatch in order, retried with doubling waits from 5 s up to a day, 10 tries. Meanwhile the record's later events to that subscription wait. A retry sends again the events of that job that went through before the one that failed.
98
+ - **Every retry and resend follows the subscription as it is now:** its event leaves out fields that became sensitive since it was first made, and a subscription with `as` roles that may no longer read the record gets nothing. <gap>A retry of a thin event cannot check the row rules of `as` roles again because reading the current record for it is not implemented.</gap>
98
99
  - **At least once:** a process that stops after delivering but before recording it delivers again when the dispatch job is retried, under the same `webhook-id`.
99
100
  - **Event code that throws**, such as a `match` that reads a field it did not expect to be empty, a subscription's `when` or an access rule of its `as` roles, keeps that change as a failed `webhooks.dispatch-change` job on the failed jobs page, naming the event or subscription and the error, and dispatch moves on to later changes. Retry it once the code is fixed to deliver the change's events. An access rule of `as` roles keeps the change as failed for that subscription only: the other subscriptions still receive it, and the retry delivers it to that subscription alone. A database error instead fails the whole dispatch job, which is retried.
100
101