@rebasepro/server-postgres 0.17.3-canary.gdd23447 → 0.18.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 (149) hide show
  1. package/LICENSE +0 -1
  2. package/README.md +31 -0
  3. package/dist/backup-argv.d.ts +19 -0
  4. package/dist/branch-argv.d.ts +28 -0
  5. package/dist/branch-prune.d.ts +77 -0
  6. package/dist/cli-collections-path.d.ts +31 -0
  7. package/dist/cli-errors.d.ts +123 -0
  8. package/dist/cli-flags.d.ts +101 -0
  9. package/dist/cli-helpers.d.ts +94 -10
  10. package/dist/collection-index-C7LopMyX.js +247 -0
  11. package/dist/collection-index-C7LopMyX.js.map +1 -0
  12. package/dist/databasePoolManager.d.ts +27 -0
  13. package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-CagOzEPS.js} +6 -6
  14. package/dist/{ensure-collection-policies-UCqgv_8c.js.map → ensure-collection-policies-CagOzEPS.js.map} +1 -1
  15. package/dist/{ensure-collection-tables-DgVixhX3.js → ensure-collection-tables-DbAhrjnG.js} +614 -52
  16. package/dist/ensure-collection-tables-DbAhrjnG.js.map +1 -0
  17. package/dist/index.d.ts +12 -0
  18. package/dist/index.es.js +19307 -3059
  19. package/dist/index.es.js.map +1 -1
  20. package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-ClJoTboT.js} +53 -189
  21. package/dist/rls-enforcement-ClJoTboT.js.map +1 -0
  22. package/dist/schema/column-type-drift.d.ts +79 -0
  23. package/dist/schema/doctor.d.ts +42 -0
  24. package/dist/schema/ensure-collection-tables.d.ts +90 -0
  25. package/dist/schema/generate-next-step.d.ts +30 -0
  26. package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
  27. package/dist/schema/generated-schema-staleness.d.ts +37 -0
  28. package/dist/schema/introspect-db-queries.d.ts +34 -0
  29. package/dist/security/rls-enforcement.d.ts +63 -2
  30. package/dist/services/BranchService.d.ts +86 -1
  31. package/dist/services/collection-helpers.d.ts +1 -1
  32. package/dist/services/realtimeService.d.ts +30 -2
  33. package/dist/services/row-pipeline.d.ts +12 -1
  34. package/dist/utils/pg-error-utils.d.ts +3 -1
  35. package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
  36. package/package.json +32 -27
  37. package/dist/backup-service-DCk7KhhL.js +0 -9044
  38. package/dist/backup-service-DCk7KhhL.js.map +0 -1
  39. package/dist/collection-index-BRUg10H5.js +0 -5690
  40. package/dist/collection-index-BRUg10H5.js.map +0 -1
  41. package/dist/connection-GOKU3Hu5.js +0 -277
  42. package/dist/connection-GOKU3Hu5.js.map +0 -1
  43. package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
  44. package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
  45. package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
  46. package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
  47. package/dist/src-DiB5RP2Z.js +0 -541
  48. package/dist/src-DiB5RP2Z.js.map +0 -1
  49. package/dist/websocket-BZ4H5wUz.js +0 -8198
  50. package/dist/websocket-BZ4H5wUz.js.map +0 -1
  51. package/src/PostgresAdapter.ts +0 -91
  52. package/src/PostgresBackendDriver.ts +0 -1857
  53. package/src/PostgresBootstrapper.ts +0 -1157
  54. package/src/auth/ensure-tables.ts +0 -896
  55. package/src/auth/schema-version.ts +0 -260
  56. package/src/auth/services.ts +0 -1610
  57. package/src/backup/backup-cli.ts +0 -520
  58. package/src/backup/backup-cron.ts +0 -212
  59. package/src/backup/backup-logic.ts +0 -93
  60. package/src/backup/backup-service.ts +0 -485
  61. package/src/backup/index.ts +0 -12
  62. package/src/backup/pg-tools.ts +0 -403
  63. package/src/backup/retention.ts +0 -86
  64. package/src/cli-errors.ts +0 -265
  65. package/src/cli-helpers.ts +0 -569
  66. package/src/cli-output.ts +0 -43
  67. package/src/cli.ts +0 -1339
  68. package/src/collections/PostgresCollectionRegistry.ts +0 -108
  69. package/src/collections/buildRegistry.ts +0 -68
  70. package/src/collections/validate-relations.ts +0 -402
  71. package/src/connection.ts +0 -333
  72. package/src/data-transformer.ts +0 -845
  73. package/src/databasePoolManager.ts +0 -95
  74. package/src/history/HistoryService.ts +0 -254
  75. package/src/history/ensure-history-table.ts +0 -53
  76. package/src/index.ts +0 -19
  77. package/src/interfaces.ts +0 -60
  78. package/src/module-dir.ts +0 -7
  79. package/src/schema/atlas-argv.ts +0 -94
  80. package/src/schema/auth-schema.ts +0 -298
  81. package/src/schema/auth-users-columns.ts +0 -131
  82. package/src/schema/carved-out-migration.ts +0 -404
  83. package/src/schema/classify-change.ts +0 -436
  84. package/src/schema/collection-index.ts +0 -427
  85. package/src/schema/collections-schema-version.ts +0 -103
  86. package/src/schema/destructive-sql.ts +0 -94
  87. package/src/schema/doctor-cli.ts +0 -66
  88. package/src/schema/doctor-policy-checks.ts +0 -105
  89. package/src/schema/doctor.ts +0 -837
  90. package/src/schema/drizzle-ddl.ts +0 -33
  91. package/src/schema/dynamic-tables.test.ts +0 -302
  92. package/src/schema/dynamic-tables.ts +0 -293
  93. package/src/schema/ensure-collection-policies.ts +0 -198
  94. package/src/schema/ensure-collection-tables.test.ts +0 -518
  95. package/src/schema/ensure-collection-tables.ts +0 -1267
  96. package/src/schema/generate-drizzle-schema-logic.ts +0 -957
  97. package/src/schema/generate-drizzle-schema.ts +0 -143
  98. package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
  99. package/src/schema/generate-postgres-ddl.ts +0 -180
  100. package/src/schema/generate-schema-commit.ts +0 -267
  101. package/src/schema/generated-schema-staleness.ts +0 -284
  102. package/src/schema/introspect-db-constraints.ts +0 -385
  103. package/src/schema/introspect-db-inference.ts +0 -255
  104. package/src/schema/introspect-db-logic.ts +0 -1387
  105. package/src/schema/introspect-db-naming.ts +0 -15
  106. package/src/schema/introspect-db-project.ts +0 -78
  107. package/src/schema/introspect-db-queries.ts +0 -326
  108. package/src/schema/introspect-db-structure.ts +0 -670
  109. package/src/schema/introspect-db-types.ts +0 -56
  110. package/src/schema/introspect-db.ts +0 -257
  111. package/src/schema/introspect-runtime.test.ts +0 -260
  112. package/src/schema/introspect-runtime.ts +0 -327
  113. package/src/schema/non-sql-collections.test.ts +0 -131
  114. package/src/schema/rls-bootstrap-sql.ts +0 -288
  115. package/src/schema/search-column.ts +0 -643
  116. package/src/schema/test-schema.ts +0 -11
  117. package/src/schema/vector-index.ts +0 -491
  118. package/src/security/anonymous-grants.test.ts +0 -73
  119. package/src/security/policy-drift.test.ts +0 -435
  120. package/src/security/policy-drift.ts +0 -473
  121. package/src/security/rls-enforcement.ts +0 -505
  122. package/src/services/BranchService.ts +0 -326
  123. package/src/services/FetchService.ts +0 -2115
  124. package/src/services/PersistService.ts +0 -557
  125. package/src/services/RelationService.ts +0 -978
  126. package/src/services/RelationWriteService.ts +0 -653
  127. package/src/services/cdc/CdcListener.ts +0 -103
  128. package/src/services/cdc/junction-tables.ts +0 -91
  129. package/src/services/cdc/trigger-cdc.ts +0 -173
  130. package/src/services/channel-bus/ChannelBus.ts +0 -44
  131. package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
  132. package/src/services/channel-bus/index.ts +0 -114
  133. package/src/services/channel-history.ts +0 -424
  134. package/src/services/channel-presence.ts +0 -185
  135. package/src/services/collection-helpers.ts +0 -420
  136. package/src/services/dataService.ts +0 -256
  137. package/src/services/index.ts +0 -14
  138. package/src/services/junction-writes.ts +0 -295
  139. package/src/services/nested-path.ts +0 -145
  140. package/src/services/pg-notify-listener.ts +0 -151
  141. package/src/services/realtimeService.ts +0 -2545
  142. package/src/services/row-pipeline.ts +0 -240
  143. package/src/services/write-denial.ts +0 -55
  144. package/src/types.ts +0 -4
  145. package/src/utils/connection-string.ts +0 -58
  146. package/src/utils/drizzle-conditions.ts +0 -2743
  147. package/src/utils/pg-array-null-patch.ts +0 -42
  148. package/src/utils/pg-error-utils.ts +0 -391
  149. package/src/websocket.ts +0 -855
@@ -1,277 +0,0 @@
1
- import { createRequire as __createRequire } from "module";
2
- import process from "process";
3
- const require = __createRequire(import.meta.url);
4
- import { Pool } from "pg";
5
- import { drizzle } from "drizzle-orm/node-postgres";
6
- import { logger } from "@rebasepro/server";
7
- //#region \0rolldown/runtime.js
8
- var __create = Object.create;
9
- var __defProp = Object.defineProperty;
10
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
- var __getOwnPropNames = Object.getOwnPropertyNames;
12
- var __getProtoOf = Object.getPrototypeOf;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
15
- var __exportAll = (all, no_symbols) => {
16
- let target = {};
17
- for (var name in all) __defProp(target, name, {
18
- get: all[name],
19
- enumerable: true
20
- });
21
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
22
- return target;
23
- };
24
- var __copyProps = (to, from, except, desc) => {
25
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
26
- key = keys[i];
27
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
28
- get: ((k) => from[k]).bind(null, key),
29
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
30
- });
31
- }
32
- return to;
33
- };
34
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
35
- value: mod,
36
- enumerable: true
37
- }) : target, mod));
38
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
39
- if (typeof require !== "undefined") return require.apply(this, arguments);
40
- throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
41
- });
42
- //#endregion
43
- //#region src/connection.ts
44
- var connection_exports = /* @__PURE__ */ __exportAll({
45
- cappedPoolMax: () => cappedPoolMax,
46
- createDirectDatabaseConnection: () => createDirectDatabaseConnection,
47
- createPostgresDatabaseConnection: () => createPostgresDatabaseConnection,
48
- createReadReplicaConnection: () => createReadReplicaConnection,
49
- guardPoolAgainstDirtyRelease: () => guardPoolAgainstDirtyRelease,
50
- pinSearchPath: () => pinSearchPath,
51
- poolMaxCeiling: () => poolMaxCeiling
52
- });
53
- /**
54
- * Ceiling on pool size, from the environment.
55
- *
56
- * Exists for the managed development database. PGlite is a single session
57
- * behind a multiplexing socket server, and two pooled clients holding
58
- * overlapping transactions deadlock there — which a request-per-transaction
59
- * server produces the moment two requests overlap. One connection turns that
60
- * deadlock into ordinary queueing.
61
- *
62
- * A ceiling rather than a value, so it constrains every pool in the process
63
- * without any of them having to know why. Ignored when unset or unparseable,
64
- * because a malformed limit must not silently serialize a production server.
65
- */
66
- function poolMaxCeiling(env = process.env) {
67
- const raw = env.REBASE_DB_POOL_MAX;
68
- if (typeof raw !== "string") return null;
69
- if (!/^[0-9]+$/.test(raw.trim())) return null;
70
- const parsed = Number(raw.trim());
71
- return parsed >= 1 ? parsed : null;
72
- }
73
- /** Apply {@link poolMaxCeiling} to a requested pool size. */
74
- function cappedPoolMax(requested, env = process.env) {
75
- const ceiling = poolMaxCeiling(env);
76
- return ceiling === null ? requested : Math.min(requested, ceiling);
77
- }
78
- var DEFAULT_POOL = {
79
- max: 20,
80
- searchPath: "public",
81
- idleTimeoutMillis: 3e4,
82
- connectionTimeoutMillis: 1e4,
83
- queryTimeout: 6e4,
84
- statementTimeout: 3e4,
85
- keepAlive: true
86
- };
87
- /** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
88
- var TX_IDLE = "I";
89
- /**
90
- * Pin `search_path` into a connection string, so unqualified SQL resolves to a
91
- * schema this framework chose rather than to one Postgres inferred.
92
- *
93
- * Postgres defaults `search_path` to `"$user", public`: the *first* candidate
94
- * is a schema named after the connecting role. Rebase creates a schema called
95
- * `rebase` (auth, history, api keys), and every template, compose file and
96
- * deployment doc names the database role `rebase` too — so `$user` resolves to
97
- * a schema that exists, and every unqualified statement lands there instead of
98
- * in `public`. The generated Drizzle schema emits bare `pgTable("posts", …)`
99
- * for any collection without an explicit `schema`, which makes the *runtime's*
100
- * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the
101
- * Studio SQL editor and any hand-written migration are unqualified too. The
102
- * result is collection tables created in, and served from, `rebase`.
103
- *
104
- * Drizzle cannot express the fix on its side: `pgSchema("public")` throws by
105
- * design ("just use pgTable() instead"), so there is no way to emit a
106
- * public-qualified table from the generator. The pin has to live on the
107
- * connection.
108
- *
109
- * Precedence is deliberate and verified against node-postgres: `options` in
110
- * the connection string wins over the `options` field passed to `Pool`, so
111
- * rewriting the URL — rather than setting the field — is what makes this
112
- * authoritative. Two escape hatches survive it:
113
- *
114
- * - an `options` that already mentions `search_path` is left untouched, so a
115
- * deployment that deliberately pins something else keeps it;
116
- * - `searchPath: false` (or an unparseable, non-URL connection string) sends
117
- * nothing and inherits the server default.
118
- *
119
- * Anything else in `options` (a `statement_timeout`, say) is preserved and the
120
- * `search_path` flag is appended to it.
121
- */
122
- function pinSearchPath(connectionString, searchPath = "public") {
123
- if (searchPath === false) return connectionString;
124
- let url;
125
- try {
126
- url = new URL(connectionString);
127
- } catch {
128
- return connectionString;
129
- }
130
- if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return connectionString;
131
- const existing = url.searchParams.get("options");
132
- if (existing && /(^|\s)-c\s*search_path\s*=/.test(existing)) return connectionString;
133
- const flag = `-c search_path=${searchPath}`;
134
- url.searchParams.set("options", existing ? `${existing} ${flag}` : flag);
135
- url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
136
- return url.toString();
137
- }
138
- /**
139
- * Destroy pool clients that are released while still inside a transaction.
140
- *
141
- * pg-pool returns a client to the idle list whenever `release()` is called
142
- * without an error — even if the connection is still mid-transaction (status
143
- * `T`/`E`). That happens in practice: drizzle's pool transaction releases in
144
- * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails
145
- * (e.g. it was queued behind a statement that hit the client-side
146
- * query_timeout), the client goes back dirty. The next checkout then runs
147
- * its statements inside the zombie transaction — with the previous request's
148
- * `app.*` RLS GUCs still applied, which turns unrelated queries into
149
- * RLS-scoped ones (observed in production as registration failing with
150
- * SQLSTATE 42501 under a leaked anonymous context).
151
- *
152
- * pg-pool emits `release` before it consults its private `_expired` set, so
153
- * marking the client expired here makes `_release()` destroy it instead of
154
- * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are
155
- * private APIs — feature-detect and fall back to loud logging so an upstream
156
- * change degrades to observability, never to silent corruption.
157
- */
158
- function guardPoolAgainstDirtyRelease(pool, label) {
159
- pool.on("release", (err, client) => {
160
- if (err) return;
161
- const txStatus = client?._txStatus;
162
- if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
163
- const expired = pool._expired;
164
- if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
165
- expired.add(client);
166
- logger.error(`[${label}] Client released back to the pool while still in a transaction (status '${txStatus}') — destroying it so the open transaction and its session state (RLS GUCs) cannot leak into the next request.`);
167
- } else logger.error(`[${label}] Client released mid-transaction (status '${txStatus}') but the pool's internal expiry set is unavailable (pg-pool internals changed?). The connection may leak its open transaction into subsequent requests.`);
168
- });
169
- }
170
- /**
171
- * Create a Drizzle-backed Postgres connection with a production-grade
172
- * connection pool.
173
- *
174
- * @param connectionString Postgres connection URL
175
- * @param schema Optional Drizzle schema for the relational API
176
- * @param poolConfig Optional pool tuning (merged over defaults)
177
- *
178
- * @returns `{ db, pool, connectionString }` — the `pool` is exposed so
179
- * callers can register shutdown hooks (`pool.end()`) or monitor
180
- * pool metrics.
181
- */
182
- function createPostgresDatabaseConnection(connectionString, schema, poolConfig) {
183
- const opts = {
184
- ...DEFAULT_POOL,
185
- ...poolConfig
186
- };
187
- connectionString = pinSearchPath(connectionString, opts.searchPath);
188
- const pool = new Pool({
189
- connectionString,
190
- max: cappedPoolMax(opts.max),
191
- idleTimeoutMillis: opts.idleTimeoutMillis,
192
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
193
- query_timeout: opts.queryTimeout,
194
- statement_timeout: opts.statementTimeout,
195
- keepAlive: opts.keepAlive,
196
- keepAliveInitialDelayMillis: 0
197
- });
198
- pool.on("error", (err) => {
199
- logger.error("[pg-pool] Unexpected pool error", { detail: err.message });
200
- if (err.message.includes("ETIMEDOUT")) logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
201
- });
202
- guardPoolAgainstDirtyRelease(pool, "pg-pool");
203
- return {
204
- db: schema ? drizzle(pool, { schema }) : drizzle(pool),
205
- pool,
206
- connectionString
207
- };
208
- }
209
- /**
210
- * Create a direct (non-pooled) connection for operations that require
211
- * session-level features incompatible with PgBouncer transaction mode,
212
- * such as LISTEN/NOTIFY, prepared statements, or advisory locks.
213
- *
214
- * Uses a smaller pool since this is only for specific use cases.
215
- */
216
- function createDirectDatabaseConnection(connectionString, schema, poolConfig) {
217
- const opts = {
218
- ...DEFAULT_POOL,
219
- max: 5,
220
- ...poolConfig
221
- };
222
- connectionString = pinSearchPath(connectionString, opts.searchPath);
223
- const pool = new Pool({
224
- connectionString,
225
- max: cappedPoolMax(opts.max),
226
- idleTimeoutMillis: opts.idleTimeoutMillis,
227
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
228
- query_timeout: opts.queryTimeout,
229
- statement_timeout: opts.statementTimeout,
230
- keepAlive: opts.keepAlive,
231
- keepAliveInitialDelayMillis: 0
232
- });
233
- pool.on("error", (err) => {
234
- logger.error("[pg-direct-pool] Unexpected pool error", { detail: err.message });
235
- });
236
- guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
237
- return {
238
- db: schema ? drizzle(pool, { schema }) : drizzle(pool),
239
- pool,
240
- connectionString
241
- };
242
- }
243
- /**
244
- * Create a read-only connection for routing read queries to replicas.
245
- * Uses a moderate pool size since reads are distributed across replicas.
246
- */
247
- function createReadReplicaConnection(connectionString, schema, poolConfig) {
248
- const opts = {
249
- ...DEFAULT_POOL,
250
- max: 10,
251
- ...poolConfig
252
- };
253
- connectionString = pinSearchPath(connectionString, opts.searchPath);
254
- const pool = new Pool({
255
- connectionString,
256
- max: cappedPoolMax(opts.max),
257
- idleTimeoutMillis: opts.idleTimeoutMillis,
258
- connectionTimeoutMillis: opts.connectionTimeoutMillis,
259
- query_timeout: opts.queryTimeout,
260
- statement_timeout: opts.statementTimeout,
261
- keepAlive: opts.keepAlive,
262
- keepAliveInitialDelayMillis: 0
263
- });
264
- pool.on("error", (err) => {
265
- logger.error("[pg-replica-pool] Unexpected pool error", { detail: err.message });
266
- });
267
- guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
268
- return {
269
- db: schema ? drizzle(pool, { schema }) : drizzle(pool),
270
- pool,
271
- connectionString
272
- };
273
- }
274
- //#endregion
275
- export { createReadReplicaConnection as a, poolMaxCeiling as c, __require as d, __toESM as f, createPostgresDatabaseConnection as i, __commonJSMin as l, connection_exports as n, guardPoolAgainstDirtyRelease as o, createDirectDatabaseConnection as r, pinSearchPath as s, cappedPoolMax as t, __exportAll as u };
276
-
277
- //# sourceMappingURL=connection-GOKU3Hu5.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connection-GOKU3Hu5.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n /**\n * `search_path` pinned on every connection (default: `\"public\"`).\n *\n * Pass `false` to send no `search_path` at all and inherit whatever the\n * server/role defaults to. See {@link pinSearchPath} for why the default\n * is not \"inherit\".\n */\n searchPath?: string | false;\n}\n\n/**\n * Ceiling on pool size, from the environment.\n *\n * Exists for the managed development database. PGlite is a single session\n * behind a multiplexing socket server, and two pooled clients holding\n * overlapping transactions deadlock there — which a request-per-transaction\n * server produces the moment two requests overlap. One connection turns that\n * deadlock into ordinary queueing.\n *\n * A ceiling rather than a value, so it constrains every pool in the process\n * without any of them having to know why. Ignored when unset or unparseable,\n * because a malformed limit must not silently serialize a production server.\n */\nexport function poolMaxCeiling(env: NodeJS.ProcessEnv = process.env): number | null {\n const raw = env.REBASE_DB_POOL_MAX;\n if (typeof raw !== \"string\") return null;\n\n // Plain decimal digits only. `Number` would also accept `1e3`, `0x10` and\n // ` 4 ` — none of which anyone writes on purpose in a config value, and all\n // of which would mean this silently did something other than it appears to.\n if (!/^[0-9]+$/.test(raw.trim())) return null;\n\n const parsed = Number(raw.trim());\n\n return parsed >= 1 ? parsed : null;\n}\n\n/** Apply {@link poolMaxCeiling} to a requested pool size. */\nexport function cappedPoolMax(requested: number, env: NodeJS.ProcessEnv = process.env): number {\n const ceiling = poolMaxCeiling(env);\n\n return ceiling === null ? requested : Math.min(requested, ceiling);\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n searchPath: \"public\",\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * Pin `search_path` into a connection string, so unqualified SQL resolves to a\n * schema this framework chose rather than to one Postgres inferred.\n *\n * Postgres defaults `search_path` to `\"$user\", public`: the *first* candidate\n * is a schema named after the connecting role. Rebase creates a schema called\n * `rebase` (auth, history, api keys), and every template, compose file and\n * deployment doc names the database role `rebase` too — so `$user` resolves to\n * a schema that exists, and every unqualified statement lands there instead of\n * in `public`. The generated Drizzle schema emits bare `pgTable(\"posts\", …)`\n * for any collection without an explicit `schema`, which makes the *runtime's*\n * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the\n * Studio SQL editor and any hand-written migration are unqualified too. The\n * result is collection tables created in, and served from, `rebase`.\n *\n * Drizzle cannot express the fix on its side: `pgSchema(\"public\")` throws by\n * design (\"just use pgTable() instead\"), so there is no way to emit a\n * public-qualified table from the generator. The pin has to live on the\n * connection.\n *\n * Precedence is deliberate and verified against node-postgres: `options` in\n * the connection string wins over the `options` field passed to `Pool`, so\n * rewriting the URL — rather than setting the field — is what makes this\n * authoritative. Two escape hatches survive it:\n *\n * - an `options` that already mentions `search_path` is left untouched, so a\n * deployment that deliberately pins something else keeps it;\n * - `searchPath: false` (or an unparseable, non-URL connection string) sends\n * nothing and inherits the server default.\n *\n * Anything else in `options` (a `statement_timeout`, say) is preserved and the\n * `search_path` flag is appended to it.\n */\nexport function pinSearchPath(connectionString: string, searchPath: string | false = \"public\"): string {\n if (searchPath === false) return connectionString;\n\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n // Key/value DSNs and anything else we cannot parse are returned as\n // given: a connection that works unpinned beats one we corrupted.\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n\n const existing = url.searchParams.get(\"options\");\n if (existing && /(^|\\s)-c\\s*search_path\\s*=/.test(existing)) return connectionString;\n\n const flag = `-c search_path=${searchPath}`;\n url.searchParams.set(\"options\", existing ? `${existing} ${flag}` : flag);\n // Re-serialize by hand. `URLSearchParams` writes a space as `+`, which\n // node-postgres happens to decode but libpq does not — and this same string\n // is handed to `pg_dump`/`psql` for backups. Percent-encoding is the form\n // both agree on, and is what the scaffolded `.env` already ships.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return url.toString();\n}\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;\n if (expired && typeof expired.add === \"function\" && typeof expired.has === \"function\" && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: cappedPoolMax(opts.max),\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-pool] Unexpected pool error\", { detail: err.message });\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: cappedPoolMax(opts.max),\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-direct-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n connectionString = pinSearchPath(connectionString, opts.searchPath);\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: cappedPoolMax(opts.max),\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-replica-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,eAAe,MAAyB,QAAQ,KAAoB;CAChF,MAAM,MAAM,IAAI;CAChB,IAAI,OAAO,QAAQ,UAAU,OAAO;CAKpC,IAAI,CAAC,WAAW,KAAK,IAAI,KAAK,CAAC,GAAG,OAAO;CAEzC,MAAM,SAAS,OAAO,IAAI,KAAK,CAAC;CAEhC,OAAO,UAAU,IAAI,SAAS;AAClC;;AAGA,SAAgB,cAAc,WAAmB,MAAyB,QAAQ,KAAa;CAC3F,MAAM,UAAU,eAAe,GAAG;CAElC,OAAO,YAAY,OAAO,YAAY,KAAK,IAAI,WAAW,OAAO;AACrE;AAEA,IAAM,eAA6C;CAC/C,KAAK;CACL,YAAY;CACZ,mBAAmB;CACnB,yBAAyB;CASzB,cAAc;CACd,kBAAkB;CAClB,WAAW;AACf;;AAGA,IAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmChB,SAAgB,cAAc,kBAA0B,aAA6B,UAAkB;CACnG,IAAI,eAAe,OAAO,OAAO;CAEjC,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,IAAI,gBAAgB;CAClC,QAAQ;EAGJ,OAAO;CACX;CACA,IAAI,IAAI,aAAa,eAAe,IAAI,aAAa,eAAe,OAAO;CAE3E,MAAM,WAAW,IAAI,aAAa,IAAI,SAAS;CAC/C,IAAI,YAAY,6BAA6B,KAAK,QAAQ,GAAG,OAAO;CAEpE,MAAM,OAAO,kBAAkB;CAC/B,IAAI,aAAa,IAAI,WAAW,WAAW,GA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