@rebasepro/server-postgres 0.25.1 → 0.27.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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/{BranchService-ClklxyAQ.js → BranchService-B9Lu8e-P.js} +25 -9
  3. package/dist/BranchService-B9Lu8e-P.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +20 -0
  5. package/dist/PostgresBootstrapper.d.ts +7 -0
  6. package/dist/auth/services.d.ts +23 -2
  7. package/dist/auth/verify-auth-tables.d.ts +21 -0
  8. package/dist/{backup-cli-gijeXe0u.js → backup-cli-BZM2Fj1I.js} +4 -4
  9. package/dist/backup-cli-BZM2Fj1I.js.map +1 -0
  10. package/dist/{boot-ddl-DYH95Qeg.js → boot-ddl-yukSebLA.js} +2 -2
  11. package/dist/{boot-ddl-DYH95Qeg.js.map → boot-ddl-yukSebLA.js.map} +1 -1
  12. package/dist/branch-diff-CxE4VlxT.js +1396 -0
  13. package/dist/branch-diff-CxE4VlxT.js.map +1 -0
  14. package/dist/branch-diff-report-DpvVf7hR.js +48 -0
  15. package/dist/branch-diff-report-DpvVf7hR.js.map +1 -0
  16. package/dist/branching/branch-diff-report.d.ts +7 -0
  17. package/dist/branching/branch-diff.d.ts +115 -0
  18. package/dist/{cli-console-CQrQ0lAY.js → cli-console-BtzxzzvU.js} +38 -5
  19. package/dist/cli-console-BtzxzzvU.js.map +1 -0
  20. package/dist/cli-console.d.ts +17 -1
  21. package/dist/{cli-errors-DiA0XFIS.js → cli-errors-BBSJqlYX.js} +58 -7
  22. package/dist/cli-errors-BBSJqlYX.js.map +1 -0
  23. package/dist/cli.js +107 -127
  24. package/dist/cli.js.map +1 -1
  25. package/dist/{collections-schema-version-T6cGvrDi.js → collections-schema-version-D7bDI0PJ.js} +13 -9
  26. package/dist/collections-schema-version-D7bDI0PJ.js.map +1 -0
  27. package/dist/{column-plan-helpers-IG6uFb1s.js → column-plan-helpers-BeSztMor.js} +5 -1
  28. package/dist/{column-plan-helpers-IG6uFb1s.js.map → column-plan-helpers-BeSztMor.js.map} +1 -1
  29. package/dist/{deferred-index-build-BE0I6sYU.js → deferred-index-build-DRnoMq-O.js} +5 -5
  30. package/dist/{deferred-index-build-BE0I6sYU.js.map → deferred-index-build-DRnoMq-O.js.map} +1 -1
  31. package/dist/{doctor-BT--1kq3.js → doctor-Cs6AtizY.js} +85 -37
  32. package/dist/doctor-Cs6AtizY.js.map +1 -0
  33. package/dist/{ensure-collection-policies-BnGOURpG.js → ensure-collection-policies-H8HN1Gbd.js} +8 -8
  34. package/dist/{ensure-collection-policies-BnGOURpG.js.map → ensure-collection-policies-H8HN1Gbd.js.map} +1 -1
  35. package/dist/{ensure-collection-tables-Cet4650m.js → ensure-collection-tables-BeF1lArf.js} +7 -7
  36. package/dist/{ensure-collection-tables-Cet4650m.js.map → ensure-collection-tables-BeF1lArf.js.map} +1 -1
  37. package/dist/{ensure-tables-l_OgFQjN.js → ensure-tables-DDkNaPN2.js} +4 -4
  38. package/dist/{ensure-tables-l_OgFQjN.js.map → ensure-tables-DDkNaPN2.js.map} +1 -1
  39. package/dist/{enum-labels-kept-nheku1pB.js → enum-labels-kept-B6loB2U_.js} +3 -3
  40. package/dist/{enum-labels-kept-nheku1pB.js.map → enum-labels-kept-B6loB2U_.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-DC0BOUpn.js → generate-drizzle-schema-D_O8_iyT.js} +2 -2
  42. package/dist/{generate-drizzle-schema-DC0BOUpn.js.map → generate-drizzle-schema-D_O8_iyT.js.map} +1 -1
  43. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js → generate-drizzle-schema-logic-D0E64iwx.js} +2 -2
  44. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js.map → generate-drizzle-schema-logic-D0E64iwx.js.map} +1 -1
  45. package/dist/{generate-files-BP-4W_gm.js → generate-files-BpgyRwhU.js} +3 -3
  46. package/dist/{generate-files-BP-4W_gm.js.map → generate-files-BpgyRwhU.js.map} +1 -1
  47. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js → generate-postgres-ddl-logic-CogQBrzs.js} +3 -3
  48. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js.map → generate-postgres-ddl-logic-CogQBrzs.js.map} +1 -1
  49. package/dist/{generated-schema-diff-eZCklRZQ.js → generated-schema-diff-X9NA2Vig.js} +2 -2
  50. package/dist/{generated-schema-diff-eZCklRZQ.js.map → generated-schema-diff-X9NA2Vig.js.map} +1 -1
  51. package/dist/history/HistoryService.d.ts +7 -0
  52. package/dist/index.d.ts +20 -0
  53. package/dist/index.es.js +228 -10
  54. package/dist/index.es.js.map +1 -1
  55. package/dist/{db-subcommands-BPoHCxJR.js → migrate-baseline-Bfk1LGC6.js} +266 -41
  56. package/dist/migrate-baseline-Bfk1LGC6.js.map +1 -0
  57. package/dist/{migrate-policy-stamps-3eqfhes6.js → migrate-policy-stamps-DHxwcawC.js} +6 -6
  58. package/dist/{migrate-policy-stamps-3eqfhes6.js.map → migrate-policy-stamps-DHxwcawC.js.map} +1 -1
  59. package/dist/{open-rebase-EmqVmS14.js → open-rebase-DZ5JbZpg.js} +546 -52
  60. package/dist/open-rebase-DZ5JbZpg.js.map +1 -0
  61. package/dist/open-rebase.d.ts +9 -1
  62. package/dist/{pg-error-utils-CFEnm2m9.js → pg-error-utils-BueZEJ0S.js} +2 -2
  63. package/dist/{pg-error-utils-CFEnm2m9.js.map → pg-error-utils-BueZEJ0S.js.map} +1 -1
  64. package/dist/{plan-schema-Czf3q4-Q.js → plan-schema-YagMlmNE.js} +2 -2
  65. package/dist/{plan-schema-Czf3q4-Q.js.map → plan-schema-YagMlmNE.js.map} +1 -1
  66. package/dist/{policy-drift-X4A-xAzv.js → policy-drift-Dqp_yFeE.js} +2 -2
  67. package/dist/{policy-drift-X4A-xAzv.js.map → policy-drift-Dqp_yFeE.js.map} +1 -1
  68. package/dist/{push-index-prebuild-COd7i6wm.js → push-index-prebuild-hVRrfTi-.js} +4 -4
  69. package/dist/{push-index-prebuild-COd7i6wm.js.map → push-index-prebuild-hVRrfTi-.js.map} +1 -1
  70. package/dist/push-kept-defaults-M_ZCcXuy.js +137 -0
  71. package/dist/push-kept-defaults-M_ZCcXuy.js.map +1 -0
  72. package/dist/{push-legacy-renames-CLgYYwPE.js → push-legacy-renames-DcoAWmGt.js} +4 -4
  73. package/dist/{push-legacy-renames-CLgYYwPE.js.map → push-legacy-renames-DcoAWmGt.js.map} +1 -1
  74. package/dist/{push-policy-plan-D2gpQsdv.js → push-policy-plan-Bq1bcb3Y.js} +4 -4
  75. package/dist/{push-policy-plan-D2gpQsdv.js.map → push-policy-plan-Bq1bcb3Y.js.map} +1 -1
  76. package/dist/{render-ddl-4v88y-Gv.js → render-ddl-D5jeXKR-.js} +2 -2
  77. package/dist/{render-ddl-4v88y-Gv.js.map → render-ddl-D5jeXKR-.js.map} +1 -1
  78. package/dist/{rls-enforcement-DDyNoOSy.js → rls-enforcement-BOHuHVlc.js} +42 -3
  79. package/dist/rls-enforcement-BOHuHVlc.js.map +1 -0
  80. package/dist/schema/destructive-sql.d.ts +16 -0
  81. package/dist/schema/doctor-cli.js +4 -4
  82. package/dist/schema/generate-drizzle-schema.js +1 -1
  83. package/dist/schema/generate-postgres-ddl.js +1 -1
  84. package/dist/schema/introspect-db.js +1 -1
  85. package/dist/schema/migration-freshness.d.ts +69 -0
  86. package/dist/schema/push-kept-defaults.d.ts +57 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +47 -10
  88. package/dist/security/rls-enforcement.d.ts +18 -0
  89. package/dist/services/FetchService.d.ts +12 -0
  90. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -0
  91. package/dist/services/channel-presence.d.ts +3 -1
  92. package/dist/services/nested-path.d.ts +16 -0
  93. package/dist/services/realtimeService.d.ts +48 -2
  94. package/dist/{websocket-BKZwsjmf.js → websocket-C9Fx7iSx.js} +70 -15
  95. package/dist/websocket-C9Fx7iSx.js.map +1 -0
  96. package/package.json +7 -7
  97. package/dist/BranchService-ClklxyAQ.js.map +0 -1
  98. package/dist/backup-cli-gijeXe0u.js.map +0 -1
  99. package/dist/cli-console-CQrQ0lAY.js.map +0 -1
  100. package/dist/cli-errors-DiA0XFIS.js.map +0 -1
  101. package/dist/collections-schema-version-T6cGvrDi.js.map +0 -1
  102. package/dist/db-subcommands-BPoHCxJR.js.map +0 -1
  103. package/dist/doctor-BT--1kq3.js.map +0 -1
  104. package/dist/open-rebase-EmqVmS14.js.map +0 -1
  105. package/dist/rls-enforcement-DDyNoOSy.js.map +0 -1
  106. package/dist/websocket-BKZwsjmf.js.map +0 -1
@@ -70,11 +70,12 @@ export declare const RLS_BOOTSTRAP_SQL: string;
70
70
  * Two independent guards, and both have to pass:
71
71
  *
72
72
  * 1. **Each function is identified before it is dropped.** Ours returns `text`
73
- * and reads the `app.uid` GUC; Supabase's returns `uuid` and reads
74
- * `request.jwt.claims`. Nothing is dropped on a signature we did not write,
75
- * so a Supabase database — where our `CREATE OR REPLACE` could never have
76
- * succeeded in the first place, Postgres refusing to change a return type —
77
- * matches nothing and this is a no-op.
73
+ * and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`
74
+ * and reads `request.jwt.claims`. Nothing is dropped on a signature we did
75
+ * not write, so a Supabase database — where our `CREATE OR REPLACE` could
76
+ * never have succeeded in the first place, Postgres refusing to change a
77
+ * return type — matches nothing and this is a no-op. See
78
+ * {@link LEGACY_AUTH_HELPERS} for exactly what is matched.
78
79
  * 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still
79
80
  * lives in `auth` (Supabase's `users` table, its other helpers), the drop
80
81
  * fails and the schema stays. CASCADE here would be unrecoverable.
@@ -88,7 +89,31 @@ export declare const RLS_BOOTSTRAP_SQL: string;
88
89
  * Callers therefore run this *after* applying policies, and treat a failure as
89
90
  * "not yet — try again next boot" rather than as an error.
90
91
  */
91
- export declare const DROP_LEGACY_AUTH_SCHEMA_SQL = "\nDO $rebase_drop_legacy$\nDECLARE\n dropped_any boolean := false;\nBEGIN\n -- Each function is matched on its own result type and body, so a schema\n -- that merely shares the name keeps everything it has.\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'uid'\n AND pg_get_function_result(p.oid) = 'text'\n AND p.prosrc LIKE '%app.uid%'\n ) THEN\n DROP FUNCTION auth.uid();\n dropped_any := true;\n END IF;\n\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'jwt'\n AND pg_get_function_result(p.oid) = 'jsonb'\n AND p.prosrc LIKE '%app.jwt%'\n ) THEN\n DROP FUNCTION auth.jwt();\n dropped_any := true;\n END IF;\n\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'roles'\n AND pg_get_function_result(p.oid) = 'text'\n AND p.prosrc LIKE '%app.user_roles%'\n ) THEN\n DROP FUNCTION auth.roles();\n dropped_any := true;\n END IF;\n\n -- RESTRICT: only an empty schema goes. Anything else in there \u2014 including a\n -- Supabase installation left untouched above \u2014 keeps it.\n IF dropped_any THEN\n BEGIN\n EXECUTE 'DROP SCHEMA auth RESTRICT';\n EXCEPTION WHEN OTHERS THEN\n NULL;\n END;\n END IF;\nEND\n$rebase_drop_legacy$;\n";
92
+ export declare const DROP_LEGACY_AUTH_SCHEMA_SQL: string;
93
+ /** One object in the `auth` schema that `DROP SCHEMA … RESTRICT` refuses on. */
94
+ export interface LegacyAuthSchemaObject {
95
+ /**
96
+ * As Postgres names it: `function auth.uid()`, `table auth.sessions`.
97
+ * `null` on the one row an empty schema answers with.
98
+ */
99
+ object: string | null;
100
+ /**
101
+ * `ours` is a helper Rebase wrote, which the drop removes. `lookalike` has a
102
+ * helper's name and result type but a body no release wrote, so the drop
103
+ * leaves it alone. `null` for everything else.
104
+ */
105
+ helper: "ours" | "lookalike" | null;
106
+ }
107
+ /**
108
+ * What the `auth` schema holds, one row per object keeping it alive.
109
+ *
110
+ * No rows: the schema does not exist. A single row with a `null` object: it
111
+ * exists and is empty. Read from the namespace entries in `pg_depend`, which
112
+ * are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with
113
+ * its owner (a serial's sequence, an identity column's), which Postgres does not
114
+ * name either.
115
+ */
116
+ export declare const LEGACY_AUTH_SCHEMA_CONTENTS_SQL: string;
92
117
  /** Somebody's policy that still calls a pre-1.0 helper. */
93
118
  export interface LegacyRlsDependent {
94
119
  schema: string;
@@ -123,11 +148,12 @@ export interface LegacyRlsFunctionDependent {
123
148
  * exists, which fails at *query* time rather than at boot.
124
149
  *
125
150
  * A downstream project building on these helpers is not hypothetical: the Rebase
126
- * control plane defines `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
151
+ * control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
127
152
  * in this very schema, each calling `auth.uid()` in a string body, and eleven of
128
- * its row-level-security policies go through them. Every one of those would have
129
- * started failing the first time a recompile left no policy referencing
130
- * `auth.uid()` directly — the drop's own precondition.
153
+ * its row-level-security policies went through them. Every one of those would
154
+ * have started failing the first time a recompile left no policy referencing
155
+ * `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has
156
+ * since moved both to `public`, calling `rebase.uid()`.)
131
157
  *
132
158
  * Matching on the body text is the only option available, and it is deliberately
133
159
  * broad: a false positive costs a schema that stays one release longer and says
@@ -143,6 +169,17 @@ export declare const LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = "\n SELECT n.nspnam
143
169
  * table not recompiled *yet* — and wrong for the one that never resolves: a
144
170
  * hand-written policy nothing will ever rewrite. Then the schema stays forever
145
171
  * and nothing ever says why.
172
+ *
173
+ * The drop itself had the same blind spot. A helper it did not recognise as
174
+ * Rebase's stayed, and so did anything else in the schema, behind a
175
+ * `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did
176
+ * drop stay dropped. The control plane's `auth.uid()` was one such: it read
177
+ * `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed
178
+ * with no word said. So the schema is read twice. Before, so that one with no
179
+ * Rebase helper in it is left alone: one already gone, as on every boot after
180
+ * the drop, or one that was never Rebase's, like Supabase's — whose own
181
+ * policies the checks below would otherwise report as blockers. After, to name
182
+ * whatever is still there.
146
183
  */
147
184
  export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Record<string, unknown>[]>, report: {
148
185
  info: (m: string) => void;
@@ -204,6 +204,24 @@ export declare function appRoleSetupInstructions(connectionRole: string, schemas
204
204
  * connection cannot create it.
205
205
  */
206
206
  export declare function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promise<void>;
207
+ /**
208
+ * The framework's internal tables in `schemas` that the request role can
209
+ * reach — `schema.table`, sorted — when nothing is left to take it back off.
210
+ *
211
+ * Every provisioning boot repairs this: each store revokes on its own table
212
+ * and {@link ensureAppRole}'s sweep revokes on the rest, because the grant
213
+ * tier hands the request role DML on whole schemas. A backend that changes
214
+ * nothing in its database runs neither, so a database whose `rebase_user` can
215
+ * read `refresh_tokens` or `api_keys` would stay that way for as long as it
216
+ * served. This is the question the sweep would have answered, asked instead.
217
+ *
218
+ * "Can reach" is what the role can actually do — through a grant to it, to a
219
+ * role it inherits, or to PUBLIC, on the table or on any of its columns —
220
+ * because that, not how the ACL is spelled, is what a request running as it
221
+ * gets. A table with RLS on is somebody's collection by that same rule as the
222
+ * sweep's, and is left out.
223
+ */
224
+ export declare function findExposedInternalTables(run: RawSqlRunner, schemas: string[]): Promise<string[]>;
207
225
  /**
208
226
  * The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
209
227
  * schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
@@ -461,6 +461,18 @@ export declare class FetchService {
461
461
  * Process raw database results into flat rows with relations.
462
462
  */
463
463
  private processRowResults;
464
+ /**
465
+ * Every row of a collection's table, as stored, a page at a time, in key
466
+ * order — the driver's `scanStoredRows`.
467
+ *
468
+ * Deliberately none of the read pipeline: no `beforeQuery` (a sweep has no
469
+ * caller to scope to, and the documented hook narrows a caller-less read to
470
+ * the rows owned by nobody), no soft-delete filter, no `afterRead`, no
471
+ * field stripping. The columns come back under their table names; a sweep
472
+ * reads values, not keys. Paged by the key rather than an offset, so a row
473
+ * deleted during the scan never shifts another past the next page.
474
+ */
475
+ scanStoredRows(collectionPath: string, pageSize?: number): AsyncGenerator<Record<string, unknown>[]>;
464
476
  /**
465
477
  * Fetch a collection of rows
466
478
  */
@@ -51,6 +51,7 @@ export declare class PostgresChannelBus implements ChannelBus {
51
51
  private readonly connectionString;
52
52
  readonly kind: "postgres";
53
53
  readonly maxFrameBytes = 7500;
54
+ readonly publishesOnDemand = true;
54
55
  private listener?;
55
56
  private readonly batchWindowMs;
56
57
  /**
@@ -53,7 +53,9 @@ export declare class ChannelPresenceStore {
53
53
  * `tablesReady` is now set from a probe of what exists, not from having been
54
54
  * the instance that created it.
55
55
  */
56
- ensureTables(): Promise<void>;
56
+ ensureTables(options?: {
57
+ provision?: boolean;
58
+ }): Promise<boolean>;
57
59
  /** Record (or refresh) a client's presence. */
58
60
  track(channel: string, clientId: string, state: Record<string, unknown>): Promise<void>;
59
61
  /** Drop one client's presence in one channel. */
@@ -46,6 +46,22 @@ export declare function resolveNestedPath(path: string, registry: PostgresCollec
46
46
  * such a path addresses the *link*, not the row.
47
47
  */
48
48
  export declare function isJunctionBackedRelation(relation: ResolvedRelation): boolean;
49
+ /**
50
+ * Reject a create or update whose body names a relation Rebase does not write
51
+ * — a multi-hop `via` (`writable: false`) — before anything is read or written.
52
+ *
53
+ * A single-hop `via` is written through this door as it shipped (to-one: the
54
+ * target's key; to-many: one junction's rows). A longer chain used to get as
55
+ * far as the writer: a to-many one failed inside the transaction as a 500
56
+ * RELATION_MISCONFIGURED telling the caller to regenerate a schema that was
57
+ * fine, and a to-one one re-pointed the target at the first step's column.
58
+ *
59
+ * Matched the way the write path matches: a key that is a relation's own name
60
+ * (the to-many split), or a `relation` property that resolves to one (the
61
+ * to-one transformer). An `undefined` value is no value — the transformer skips
62
+ * it — so it is not a write; `null` is, since it would unlink.
63
+ */
64
+ export declare function assertNoReadOnlyRelationValues(values: Record<string, unknown>, collection: CollectionConfig): void;
49
65
  /**
50
66
  * Reject a nested write whose final segment is a to-one relation.
51
67
  *
@@ -5,7 +5,7 @@ import { NodePgDatabase } from "drizzle-orm/node-postgres";
5
5
  import { RealtimeProvider, CollectionSubscriptionConfig, SingleSubscriptionConfig } from "../interfaces.js";
6
6
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry.js";
7
7
  import { ChannelBus } from "./channel-bus/index.js";
8
- import type { ChannelRetentionRule, RealtimeListenerHealth } from "@rebasepro/types";
8
+ import type { ChannelRetentionRule, RealtimeCounts, RealtimeListenerHealth } from "@rebasepro/types";
9
9
  /**
10
10
  * Auth context stored per-subscription so real-time refetches respect RLS.
11
11
  * Mirrors the session variables set by PostgresBackendDriver.withAuth().
@@ -286,6 +286,17 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
286
286
  * per broadcast for company. See `channel-bus/ChannelBus.ts`.
287
287
  */
288
288
  private bus;
289
+ /**
290
+ * The other instances on an on-demand bus, and the channels each serves
291
+ * (`null`: it hasn't said, so assume all of them). See {@link hasRemoteMembers}.
292
+ */
293
+ private busPeers;
294
+ /** Frames the bus took, by kind. See {@link counts}. */
295
+ private busFramesPublished;
296
+ /** Frames not sent because no other instance had members. See {@link counts}. */
297
+ private busFramesSkipped;
298
+ private busStartedAt;
299
+ private busGossipInterval?;
289
300
  /**
290
301
  * The shared presence roster, present only when a real bus is active.
291
302
  *
@@ -367,6 +378,14 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
367
378
  private refetchQueue;
368
379
  /** Group refetches running now — at most {@link maxConcurrentRefetches}. */
369
380
  private refetchesRunning;
381
+ /**
382
+ * What a group refetch runs inside — see {@link setScopeRunner}. A refetch
383
+ * runs on a timer armed by whatever announced the change; one armed by a
384
+ * change-capture notification inherits the LISTEN connection's context,
385
+ * which is no backend's, so a hook the read reached saw the process
386
+ * default as `rebase`.
387
+ */
388
+ private runInScope;
370
389
  /** See {@link refetchConcurrencyFor}. */
371
390
  maxConcurrentRefetches: number;
372
391
  /**
@@ -758,6 +777,11 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
758
777
  * transaction of its own — see {@link collectionMeta}.
759
778
  */
760
779
  private fetchCollectionWithAuth;
780
+ /**
781
+ * Refetch `group` — and so count it again — at `at`, when the total its
782
+ * last frame reused expires. One pending at a time per group.
783
+ */
784
+ private scheduleRecount;
761
785
  /**
762
786
  * The `meta` a `collection_update` frame carries beside its rows, counted
763
787
  * through `service` — the subscriber's own transaction, read only, with
@@ -988,7 +1012,9 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
988
1012
  * what it was before this existed, whereas refusing to boot takes the whole
989
1013
  * backend down for it.
990
1014
  */
991
- configureChannelBus(bus: ChannelBus): Promise<void>;
1015
+ configureChannelBus(bus: ChannelBus, options?: {
1016
+ provision?: boolean;
1017
+ }): Promise<void>;
992
1018
  /** Which transport is in use — `"memory"` means per-instance only. */
993
1019
  getChannelBusKind(): ChannelBus["kind"];
994
1020
  /**
@@ -1079,6 +1105,22 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
1079
1105
  private deliverPresenceDiff;
1080
1106
  /** Tell the other instances about a presence change. */
1081
1107
  private publishPresenceDiff;
1108
+ private static readonly BUS_GOSSIP_INTERVAL_MS;
1109
+ private static readonly BUS_PEER_TTL_MS;
1110
+ private static readonly BUS_WARMUP_MS;
1111
+ /** The frames' `channel`: a transport drops a frame without one. */
1112
+ private static readonly BUS_PEERS_CHANNEL;
1113
+ /** Whether a frame on `channel` may have a reader on another instance. */
1114
+ private hasRemoteMembers;
1115
+ /** Tell the others about a channel's first member here. */
1116
+ private announceChannel;
1117
+ /** Every channel served here, in as many parts as the transport needs. */
1118
+ private announceChannels;
1119
+ /** Any frame from another instance: it's alive, and a new one needs to hear what's served here. */
1120
+ private notePeer;
1121
+ private readPeerChannels;
1122
+ /** Start gossiping on a bus that publishes on demand. */
1123
+ private startBusGossip;
1082
1124
  /** Run a roster write when there is a roster, and never let it throw. */
1083
1125
  private presenceStoreOp;
1084
1126
  /** Periodic cleanup for stale presences */
@@ -1116,6 +1158,10 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
1116
1158
  * down and being replaced.
1117
1159
  */
1118
1160
  isCdcActive(): boolean;
1161
+ /** See `RealtimeProvider.setScopeRunner`. */
1162
+ setScopeRunner(run: <T>(fn: () => T) => T): void;
1163
+ /** What this instance is carrying — see `RealtimeProvider.counts`. */
1164
+ counts(): RealtimeCounts;
1119
1165
  /** The LISTEN connections this service depends on — see `RealtimeProvider.health`. */
1120
1166
  health(): RealtimeListenerHealth[];
1121
1167
  /**
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { A as budgetSendBuffers, M as terminateIfBacklogged, N as assertReadRequestReadable, ct as SqlResultTooLargeError, it as effectiveSqlRole, j as reapSilentSockets, lt as isNestedPath, ot as sqlRoleRanAs, st as SQL_RESULT_BYTE_BUDGET, ut as resolveNestedPath } from "./open-rebase-EmqVmS14.js";
5
- import { r as BranchingUnsupportedError } from "./BranchService-ClklxyAQ.js";
4
+ import { A as budgetSendBuffers, M as terminateIfBacklogged, N as assertReadRequestReadable, ct as SqlResultTooLargeError, it as effectiveSqlRole, j as reapSilentSockets, lt as isNestedPath, ot as sqlRoleRanAs, st as SQL_RESULT_BYTE_BUDGET, ut as resolveNestedPath } from "./open-rebase-DZ5JbZpg.js";
5
+ import { r as BranchingUnsupportedError } from "./BranchService-B9Lu8e-P.js";
6
6
  import { ApiError, DATABASE_UNAVAILABLE_MESSAGE, RUNTIME_DEFAULT_MAX_BODY_SIZE, assertFieldOpsValid, assertNestedWriteAllowed, assertNoFieldOpsOnCreate, assertNoUserUpsert, assertUserCreationBodyValid, assertWriteRequestValid, createUserThroughAuthCollection, decideImpersonation, declaredErrorAnswer, extractUserFromToken, getAccessModel, isDatabaseUnreachable, logger, resolveConflictTarget, resolveRequireAuth, safeCompare } from "@rebasepro/server";
7
7
  import { ANONYMOUS_USER_ID, ListLimitError, hasAdminRole, isSQLAdmin, isSchemaAdmin, resolveClientListLimit, scopeGrants, scopesForRoles } from "@rebasepro/types";
8
8
  import { UnknownFilterOperatorError, deserializeFilter, redactSqlLiterals } from "@rebasepro/common";
@@ -226,8 +226,28 @@ var IDENTITY_SWEEP_CONCURRENCY = 4;
226
226
  * high-rate traffic (see `WS_CHANNEL_RATE_LIMIT`): a database read for every
227
227
  * cursor position would make realtime presence the busiest query a backend
228
228
  * runs, for a window no wider than this.
229
+ *
230
+ * At one second a busy backend's channel traffic was its busiest query all the
231
+ * same: a socket that answers a ping every few seconds and sends a state now
232
+ * and then is checked on nearly every frame, so 800 game sockets were several
233
+ * hundred auth lookups a second on the shared pool, and the lookups were what
234
+ * starved it (a load test of 100 rooms). Five seconds keeps a revocation's reach
235
+ * well inside the idle sweep's 30 s while taking that traffic down fivefold.
236
+ */
237
+ var CHANNEL_RECHECK_MIN_MS = 5e3;
238
+ /**
239
+ * How long a channel frame is still honoured on the strength of a successful
240
+ * check, in ms, while the auth store cannot answer.
241
+ *
242
+ * A lookup that fails because the database is busy (the pool's acquire
243
+ * timeout, a statement timeout) says nothing about the identity, yet dropping
244
+ * the frame lost a join or a broadcast without the client knowing to resend it,
245
+ * and every following frame asked again, adding to the load that made it fail.
246
+ * Within this window of the last confirmed check, a channel frame goes through
247
+ * and the next check waits {@link CHANNEL_RECHECK_MIN_MS}; past it, the frame
248
+ * is refused as before. Data frames get no grace: they read the database anyway.
229
249
  */
230
- var CHANNEL_RECHECK_MIN_MS = 1e3;
250
+ var CHANNEL_STALE_GRACE_MS = 6e4;
231
251
  /**
232
252
  * The close code for a socket whose identity ended: signed out, revoked,
233
253
  * demoted out of existence, deleted or expired. In the 4000–4999 range the
@@ -242,6 +262,23 @@ var SESSION_ENDED_CLOSE_CODE = 4001;
242
262
  */
243
263
  var TOO_MANY_SOCKETS_CLOSE_CODE = 4002;
244
264
  /**
265
+ * What a socket counts against under `REALTIME_MAX_SOCKETS_PER_USER`: the
266
+ * credential that opened it. That is the user it signed in as; for an API key,
267
+ * that key; and for an administrator impersonating someone, the administrator.
268
+ *
269
+ * A key acts as the account that made it, and a fleet of workers holding
270
+ * sockets under its keys counted against that account's ceiling, locking out
271
+ * its people and each other; each key is a credential of its own, with its own
272
+ * ceiling. An impersonating socket counted against the user it acts as: an
273
+ * administrator checking on someone spent that person's places, and could
274
+ * hold any number of sockets by spreading them over users. It is the
275
+ * administrator's traffic, as its rate-limit bucket already says.
276
+ */
277
+ function socketCeilingBucket(user) {
278
+ if (user.impersonator) return `user:${user.impersonator}`;
279
+ return user.apiKey ? `key:${user.apiKey.id}` : `user:${user.uid}`;
280
+ }
281
+ /**
245
282
  * When a JWT expires, in ms, or undefined for a credential that is not one
246
283
  * (an API key, the service key, an adapter's opaque token).
247
284
  *
@@ -535,12 +572,14 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
535
572
  logger.error("❌ [WebSocket Server] Error", { error: err });
536
573
  });
537
574
  const socketPath = normalizeSocketPath(options?.path ?? "/");
575
+ const runInScope = options?.runInScope;
576
+ const inBackendScope = (listener) => runInScope ? (...args) => runInScope(() => listener(...args)) : listener;
538
577
  const onUpgrade = (request, socket, head) => {
539
578
  if (upgradePathOf(request) !== socketPath) {
540
579
  if (server.listenerCount("upgrade") <= 1) refuseUpgrade(socket);
541
580
  return;
542
581
  }
543
- wss.handleUpgrade(request, socket, head, (client) => wss.emit("connection", client, request));
582
+ wss.handleUpgrade(request, socket, head, inBackendScope((client) => wss.emit("connection", client, request)));
544
583
  };
545
584
  if (typeof server.on === "function") {
546
585
  server.on("upgrade", onUpgrade);
@@ -573,6 +612,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
573
612
  ...resolved.apiKey ? { apiKey: {
574
613
  id: resolved.apiKey.id,
575
614
  rate_limit: resolved.apiKey.rate_limit
615
+ } } : {},
616
+ ...resolved.apiKey?.name !== void 0 && resolved.apiKey.kind !== void 0 ? { credential: {
617
+ kind: resolved.apiKey.kind,
618
+ id: resolved.apiKey.id,
619
+ name: resolved.apiKey.name
576
620
  } } : {}
577
621
  }
578
622
  };
@@ -892,7 +936,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
892
936
  ws.on("error", (error) => {
893
937
  wsDebug(`WebSocket client ${clientId} error: ${error.message}`);
894
938
  });
895
- ws.on("message", async (message) => {
939
+ ws.on("message", inBackendScope(async (message) => {
896
940
  if (terminateIfBacklogged(ws, clientId)) return;
897
941
  let requestId;
898
942
  try {
@@ -984,10 +1028,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
984
1028
  if (verifiedUser) {
985
1029
  const session = clientSessions.get(clientId);
986
1030
  if (maxSocketsPerUser !== void 0 && session) {
1031
+ const bucket = socketCeilingBucket(verifiedUser);
987
1032
  let held = 0;
988
- for (const other of clientSessions.values()) if (other !== session && other.user?.uid === verifiedUser.uid) held++;
1033
+ for (const other of clientSessions.values()) if (other !== session && other.user && socketCeilingBucket(other.user) === bucket) held++;
989
1034
  if (held >= maxSocketsPerUser) {
990
- logger.warn(`[WebSocket Server] Refused a socket for ${verifiedUser.uid}: ${held} already open, ceiling ${maxSocketsPerUser}`);
1035
+ logger.warn(`[WebSocket Server] Refused a socket for ${verifiedUser.uid} (counted as ${bucket}): ${held} already open, ceiling ${maxSocketsPerUser}`);
991
1036
  sendError("ERROR", "TOO_MANY_SOCKETS", `This user already has ${held} realtime connections open on this server, the most it allows (REALTIME_MAX_SOCKETS_PER_USER). Close another tab or client and try again.`);
992
1037
  ws.close(TOO_MANY_SOCKETS_CLOSE_CODE, "Too many realtime connections for this user");
993
1038
  return;
@@ -1020,10 +1065,16 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1020
1065
  }
1021
1066
  {
1022
1067
  const session = clientSessions.get(clientId);
1023
- if (session?.user && session.credential && Date.now() - session.checkedAt >= (CHANNEL_MESSAGE_TYPES.has(type) ? CHANNEL_RECHECK_MIN_MS : 0)) {
1068
+ const channelFrame = CHANNEL_MESSAGE_TYPES.has(type);
1069
+ const now = Date.now();
1070
+ if (session?.user && session.credential && now - session.checkedAt >= (channelFrame ? CHANNEL_RECHECK_MIN_MS : 0) && !(channelFrame && session.recheckAfter !== void 0 && now < session.recheckAfter)) {
1024
1071
  const outcome = await recheckIdentityForFrame(clientId);
1025
1072
  if (outcome === "ended") return;
1026
- if (outcome !== "live") {
1073
+ if (outcome === "live") session.recheckAfter = void 0;
1074
+ else if (channelFrame && Date.now() - session.checkedAt < CHANNEL_STALE_GRACE_MS) {
1075
+ session.recheckAfter = Date.now() + CHANNEL_RECHECK_MIN_MS;
1076
+ wsDebug(`[WebSocket Server] Auth store unavailable (${outcome.unavailable.code}); honouring ${clientId}'s last check for a channel frame`);
1077
+ } else {
1027
1078
  sendError("ERROR", outcome.unavailable.code, outcome.unavailable.message);
1028
1079
  return;
1029
1080
  }
@@ -1057,10 +1108,11 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1057
1108
  }
1058
1109
  }
1059
1110
  if (options?.dataRateLimit && (PUBLIC_TYPES.has(type) || FETCHING_REALTIME_TYPES.has(type) && !spendFetchAllowance(clientId))) {
1111
+ const sessionUser = clientSessions.get(clientId)?.user;
1060
1112
  const decision = await options.dataRateLimit({
1061
1113
  ...origin,
1062
- uid: clientSessions.get(clientId)?.user?.uid,
1063
- apiKey: clientSessions.get(clientId)?.user?.apiKey
1114
+ uid: sessionUser?.impersonator ?? sessionUser?.uid,
1115
+ apiKey: sessionUser?.impersonator ? void 0 : sessionUser?.apiKey
1064
1116
  });
1065
1117
  if (decision && !decision.allowed) {
1066
1118
  sendError("ERROR", "RATE_LIMITED", "Too many requests, please try again later.");
@@ -1168,7 +1220,9 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1168
1220
  };
1169
1221
  const getScopedDelegate = async () => {
1170
1222
  if (typeof driver.withAuth === "function") try {
1171
- const who = sessionAuthContext(clientSessions.get(clientId));
1223
+ const session = clientSessions.get(clientId);
1224
+ const who = sessionAuthContext(session);
1225
+ const credential = session?.user?.impersonator ? void 0 : session?.user?.credential;
1172
1226
  const userForAuth = {
1173
1227
  uid: who.uid,
1174
1228
  displayName: null,
@@ -1177,7 +1231,8 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1177
1231
  providerId: "websocket",
1178
1232
  isAnonymous: who.isAnonymous === true,
1179
1233
  roles: who.roles,
1180
- ...who.claims ? { claims: who.claims } : {}
1234
+ ...who.claims ? { claims: who.claims } : {},
1235
+ ...credential ? { credential } : {}
1181
1236
  };
1182
1237
  return await driver.withAuth(userForAuth);
1183
1238
  } catch (e) {
@@ -1627,7 +1682,7 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1627
1682
  };
1628
1683
  ws.send(JSON.stringify(errorResponse));
1629
1684
  }
1630
- });
1685
+ }));
1631
1686
  });
1632
1687
  const stopReaping = reapSilentSockets(wss);
1633
1688
  wss.on("close", stopReaping);
@@ -1642,4 +1697,4 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
1642
1697
  //#endregion
1643
1698
  export { createPostgresWebSocket as a, websocket_exports as c, TOO_MANY_SOCKETS_CLOSE_CODE as i, PUBLIC_TYPES as n, isSocketRealtimeService as o, SESSION_ENDED_CLOSE_CODE as r, socketRealtimeMissing as s, ADMIN_PLANE_TYPES as t };
1644
1699
 
1645
- //# sourceMappingURL=websocket-BKZwsjmf.js.map
1700
+ //# sourceMappingURL=websocket-C9Fx7iSx.js.map