@rebasepro/server-postgres 0.12.1-canary.gf5f1d39 → 0.13.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 (92) hide show
  1. package/dist/PostgresBackendDriver.d.ts +1 -1
  2. package/dist/PostgresBootstrapper.d.ts +25 -1
  3. package/dist/auth/services.d.ts +21 -0
  4. package/dist/backup/backup-service.d.ts +10 -1
  5. package/dist/backup/pg-tools.d.ts +47 -0
  6. package/dist/backup-service-CD8o_1Sl.js +8999 -0
  7. package/dist/backup-service-CD8o_1Sl.js.map +1 -0
  8. package/dist/cli-helpers.d.ts +39 -0
  9. package/dist/connection-BuZ97wsr.js +250 -0
  10. package/dist/connection-BuZ97wsr.js.map +1 -0
  11. package/dist/connection.d.ts +42 -0
  12. package/dist/ensure-collection-policies-ViG8XiPn.js +57 -0
  13. package/dist/ensure-collection-policies-ViG8XiPn.js.map +1 -0
  14. package/dist/ensure-collection-tables-CBQdOETu.js +650 -0
  15. package/dist/ensure-collection-tables-CBQdOETu.js.map +1 -0
  16. package/dist/index.es.js +1231 -10031
  17. package/dist/index.es.js.map +1 -1
  18. package/dist/policy-CeA1JcxP.js +105 -0
  19. package/dist/policy-CeA1JcxP.js.map +1 -0
  20. package/dist/schema/auth-schema.d.ts +83 -144
  21. package/dist/schema/ensure-collection-policies.d.ts +60 -0
  22. package/dist/schema/ensure-collection-tables.d.ts +44 -2
  23. package/dist/schema/generate-postgres-ddl-logic.d.ts +135 -1
  24. package/dist/schema/introspect-db-constraints.d.ts +57 -0
  25. package/dist/schema/introspect-db-logic.d.ts +94 -5
  26. package/dist/schema/introspect-db-queries.d.ts +119 -0
  27. package/dist/schema/introspect-db-structure.d.ts +263 -0
  28. package/dist/schema/introspect-db-types.d.ts +11 -0
  29. package/dist/services/FetchService.d.ts +4 -1
  30. package/dist/services/RelationService.d.ts +24 -1
  31. package/dist/services/channel-bus/index.d.ts +1 -7
  32. package/dist/services/collection-helpers.d.ts +36 -2
  33. package/dist/services/dataService.d.ts +3 -1
  34. package/dist/services/row-pipeline.d.ts +1 -1
  35. package/dist/{src-BbFOPJ1S.js → src-DlPBctw_.js} +299 -173
  36. package/dist/src-DlPBctw_.js.map +1 -0
  37. package/dist/{src-Zqwaw3P5.js → src-DoU9yPqq.js} +3 -159
  38. package/dist/src-DoU9yPqq.js.map +1 -0
  39. package/dist/utils/connection-string.d.ts +29 -0
  40. package/dist/utils/drizzle-conditions.d.ts +5 -4
  41. package/dist/utils/pg-error-utils.d.ts +35 -0
  42. package/dist/websocket-B2LsrINK.js +530 -0
  43. package/dist/websocket-B2LsrINK.js.map +1 -0
  44. package/package.json +14 -14
  45. package/src/PostgresAdapter.ts +21 -2
  46. package/src/PostgresBackendDriver.ts +4 -0
  47. package/src/PostgresBootstrapper.ts +192 -33
  48. package/src/auth/ensure-tables.ts +164 -9
  49. package/src/auth/services.ts +24 -2
  50. package/src/backup/backup-cli.ts +41 -2
  51. package/src/backup/backup-service.ts +38 -5
  52. package/src/backup/pg-tools.ts +96 -3
  53. package/src/cli-helpers.ts +70 -0
  54. package/src/cli.ts +44 -26
  55. package/src/collections/validate-relations.ts +15 -0
  56. package/src/connection.ts +73 -0
  57. package/src/data-transformer.ts +9 -3
  58. package/src/databasePoolManager.ts +5 -2
  59. package/src/schema/auth-schema.ts +30 -19
  60. package/src/schema/ensure-collection-policies.ts +105 -0
  61. package/src/schema/ensure-collection-tables.test.ts +105 -9
  62. package/src/schema/ensure-collection-tables.ts +220 -32
  63. package/src/schema/generate-drizzle-schema-logic.ts +42 -6
  64. package/src/schema/generate-postgres-ddl-logic.ts +382 -19
  65. package/src/schema/introspect-db-constraints.ts +385 -0
  66. package/src/schema/introspect-db-inference.ts +18 -8
  67. package/src/schema/introspect-db-logic.ts +385 -71
  68. package/src/schema/introspect-db-queries.ts +326 -0
  69. package/src/schema/introspect-db-structure.ts +670 -0
  70. package/src/schema/introspect-db-types.ts +56 -0
  71. package/src/schema/introspect-db.ts +37 -80
  72. package/src/schema/introspect-runtime.test.ts +56 -8
  73. package/src/schema/introspect-runtime.ts +31 -9
  74. package/src/security/policy-drift.test.ts +11 -3
  75. package/src/services/BranchService.ts +66 -28
  76. package/src/services/FetchService.ts +90 -14
  77. package/src/services/PersistService.ts +20 -6
  78. package/src/services/RelationService.ts +249 -48
  79. package/src/services/channel-bus/index.ts +0 -9
  80. package/src/services/collection-helpers.ts +69 -3
  81. package/src/services/dataService.ts +3 -1
  82. package/src/services/realtimeService.ts +3 -3
  83. package/src/services/row-pipeline.ts +1 -1
  84. package/src/utils/connection-string.ts +58 -0
  85. package/src/utils/drizzle-conditions.ts +31 -6
  86. package/src/utils/pg-error-utils.ts +65 -0
  87. package/src/websocket.ts +18 -9
  88. package/dist/chunk-DSJWtz9O.js +0 -40
  89. package/dist/ensure-collection-tables-CNTcZGvn.js +0 -304
  90. package/dist/ensure-collection-tables-CNTcZGvn.js.map +0 -1
  91. package/dist/src-BbFOPJ1S.js.map +0 -1
  92. package/dist/src-Zqwaw3P5.js.map +0 -1
@@ -1,4 +1,28 @@
1
1
  import type { CollectionConfig } from "@rebasepro/types";
2
+ /**
3
+ * Why is a dependency's binary missing — never installed, or installed with its
4
+ * build script blocked?
5
+ *
6
+ * These need opposite advice, and getting it wrong is not a cosmetic miss. pnpm
7
+ * 10+ refuses to run a dependency's lifecycle scripts unless it is allowlisted
8
+ * (`pnpm.onlyBuiltDependencies`, or `allowBuilds` in `pnpm-workspace.yaml`).
9
+ * `@ariga/atlas` downloads its platform binary in `preinstall`, so a blocked
10
+ * script leaves a state that looks like a successful install: the package is on
11
+ * disk with its `install.js` and `package.json`, `node_modules/.bin` is empty,
12
+ * the install exits 0, and the only signal is `ERR_PNPM_IGNORED_BUILDS` several
13
+ * screens up.
14
+ *
15
+ * Telling somebody in that state to install the package again sends them round
16
+ * the same loop forever — the add succeeds, the script is blocked again,
17
+ * nothing changes. Verified by doing it: `pnpm add @ariga/atlas` into a bare
18
+ * project yields exactly this, three "Failed to create bin … ENOENT" warnings
19
+ * and no binary.
20
+ *
21
+ * Resolution is attempted from the user's project first and this package
22
+ * second, matching the order {@link resolveLocalBin} searches — the driver may
23
+ * be installed a level up from where the command runs.
24
+ */
25
+ export declare function diagnoseMissingBin(packageName: string): "not-installed" | "build-script-blocked";
2
26
  export declare function resolveLocalBin(binName: string): string | null;
3
27
  export declare function getTableIncludesFromCollections(collections: CollectionConfig[]): Promise<string[]>;
4
28
  export declare function getTableIncludes(collectionsPath: string): Promise<string[]>;
@@ -37,3 +61,18 @@ export declare function getTableExcludes(databaseUrl: string, collectionsPath: s
37
61
  queryExistingTables?: (databaseUrl: string) => Promise<string[]>;
38
62
  getIncludes?: (collectionsPath: string) => Promise<string[]>;
39
63
  }): Promise<string[]>;
64
+ /**
65
+ * Ask a yes/no question on an interactive terminal.
66
+ *
67
+ * The `isTTY` guard is the contract, not an optimisation: non-interactive
68
+ * shells (CI, pipes, agents) can never answer, and `readline` on a
69
+ * non-TTY stdin resolves with whatever the pipe happens to contain — or never
70
+ * resolves at all. Returning false there is what makes an unattended
71
+ * `db push` abort instead of auto-confirming a destructive change. Callers
72
+ * should already have gone through {@link decidePushSafety}, which decides
73
+ * whether interactive confirmation is even possible; this is the backstop.
74
+ *
75
+ * Lives here rather than in cli.ts so it is reachable from a test — cli.ts uses
76
+ * `import.meta` and cannot be imported by the jest runner.
77
+ */
78
+ export declare function promptConfirm(question: string): Promise<boolean>;
@@ -0,0 +1,250 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "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
+ createDirectDatabaseConnection: () => createDirectDatabaseConnection,
46
+ createPostgresDatabaseConnection: () => createPostgresDatabaseConnection,
47
+ createReadReplicaConnection: () => createReadReplicaConnection,
48
+ guardPoolAgainstDirtyRelease: () => guardPoolAgainstDirtyRelease,
49
+ pinSearchPath: () => pinSearchPath
50
+ });
51
+ var DEFAULT_POOL = {
52
+ max: 20,
53
+ searchPath: "public",
54
+ idleTimeoutMillis: 3e4,
55
+ connectionTimeoutMillis: 1e4,
56
+ queryTimeout: 6e4,
57
+ statementTimeout: 3e4,
58
+ keepAlive: true
59
+ };
60
+ /** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
61
+ var TX_IDLE = "I";
62
+ /**
63
+ * Pin `search_path` into a connection string, so unqualified SQL resolves to a
64
+ * schema this framework chose rather than to one Postgres inferred.
65
+ *
66
+ * Postgres defaults `search_path` to `"$user", public`: the *first* candidate
67
+ * is a schema named after the connecting role. Rebase creates a schema called
68
+ * `rebase` (auth, history, api keys), and every template, compose file and
69
+ * deployment doc names the database role `rebase` too — so `$user` resolves to
70
+ * a schema that exists, and every unqualified statement lands there instead of
71
+ * in `public`. The generated Drizzle schema emits bare `pgTable("posts", …)`
72
+ * for any collection without an explicit `schema`, which makes the *runtime's*
73
+ * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the
74
+ * Studio SQL editor and any hand-written migration are unqualified too. The
75
+ * result is collection tables created in, and served from, `rebase`.
76
+ *
77
+ * Drizzle cannot express the fix on its side: `pgSchema("public")` throws by
78
+ * design ("just use pgTable() instead"), so there is no way to emit a
79
+ * public-qualified table from the generator. The pin has to live on the
80
+ * connection.
81
+ *
82
+ * Precedence is deliberate and verified against node-postgres: `options` in
83
+ * the connection string wins over the `options` field passed to `Pool`, so
84
+ * rewriting the URL — rather than setting the field — is what makes this
85
+ * authoritative. Two escape hatches survive it:
86
+ *
87
+ * - an `options` that already mentions `search_path` is left untouched, so a
88
+ * deployment that deliberately pins something else keeps it;
89
+ * - `searchPath: false` (or an unparseable, non-URL connection string) sends
90
+ * nothing and inherits the server default.
91
+ *
92
+ * Anything else in `options` (a `statement_timeout`, say) is preserved and the
93
+ * `search_path` flag is appended to it.
94
+ */
95
+ function pinSearchPath(connectionString, searchPath = "public") {
96
+ if (searchPath === false) return connectionString;
97
+ let url;
98
+ try {
99
+ url = new URL(connectionString);
100
+ } catch {
101
+ return connectionString;
102
+ }
103
+ if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return connectionString;
104
+ const existing = url.searchParams.get("options");
105
+ if (existing && /(^|\s)-c\s*search_path\s*=/.test(existing)) return connectionString;
106
+ const flag = `-c search_path=${searchPath}`;
107
+ url.searchParams.set("options", existing ? `${existing} ${flag}` : flag);
108
+ url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
109
+ return url.toString();
110
+ }
111
+ /**
112
+ * Destroy pool clients that are released while still inside a transaction.
113
+ *
114
+ * pg-pool returns a client to the idle list whenever `release()` is called
115
+ * without an error — even if the connection is still mid-transaction (status
116
+ * `T`/`E`). That happens in practice: drizzle's pool transaction releases in
117
+ * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails
118
+ * (e.g. it was queued behind a statement that hit the client-side
119
+ * query_timeout), the client goes back dirty. The next checkout then runs
120
+ * its statements inside the zombie transaction — with the previous request's
121
+ * `app.*` RLS GUCs still applied, which turns unrelated queries into
122
+ * RLS-scoped ones (observed in production as registration failing with
123
+ * SQLSTATE 42501 under a leaked anonymous context).
124
+ *
125
+ * pg-pool emits `release` before it consults its private `_expired` set, so
126
+ * marking the client expired here makes `_release()` destroy it instead of
127
+ * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are
128
+ * private APIs — feature-detect and fall back to loud logging so an upstream
129
+ * change degrades to observability, never to silent corruption.
130
+ */
131
+ function guardPoolAgainstDirtyRelease(pool, label) {
132
+ pool.on("release", (err, client) => {
133
+ if (err) return;
134
+ const txStatus = client?._txStatus;
135
+ if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
136
+ const expired = pool._expired;
137
+ if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
138
+ expired.add(client);
139
+ 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.`);
140
+ } 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.`);
141
+ });
142
+ }
143
+ /**
144
+ * Create a Drizzle-backed Postgres connection with a production-grade
145
+ * connection pool.
146
+ *
147
+ * @param connectionString Postgres connection URL
148
+ * @param schema Optional Drizzle schema for the relational API
149
+ * @param poolConfig Optional pool tuning (merged over defaults)
150
+ *
151
+ * @returns `{ db, pool, connectionString }` — the `pool` is exposed so
152
+ * callers can register shutdown hooks (`pool.end()`) or monitor
153
+ * pool metrics.
154
+ */
155
+ function createPostgresDatabaseConnection(connectionString, schema, poolConfig) {
156
+ const opts = {
157
+ ...DEFAULT_POOL,
158
+ ...poolConfig
159
+ };
160
+ connectionString = pinSearchPath(connectionString, opts.searchPath);
161
+ const pool = new Pool({
162
+ connectionString,
163
+ max: opts.max,
164
+ idleTimeoutMillis: opts.idleTimeoutMillis,
165
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
166
+ query_timeout: opts.queryTimeout,
167
+ statement_timeout: opts.statementTimeout,
168
+ keepAlive: opts.keepAlive,
169
+ keepAliveInitialDelayMillis: 0
170
+ });
171
+ pool.on("error", (err) => {
172
+ logger.error("[pg-pool] Unexpected pool error", { detail: err.message });
173
+ if (err.message.includes("ETIMEDOUT")) logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
174
+ });
175
+ guardPoolAgainstDirtyRelease(pool, "pg-pool");
176
+ return {
177
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
178
+ pool,
179
+ connectionString
180
+ };
181
+ }
182
+ /**
183
+ * Create a direct (non-pooled) connection for operations that require
184
+ * session-level features incompatible with PgBouncer transaction mode,
185
+ * such as LISTEN/NOTIFY, prepared statements, or advisory locks.
186
+ *
187
+ * Uses a smaller pool since this is only for specific use cases.
188
+ */
189
+ function createDirectDatabaseConnection(connectionString, schema, poolConfig) {
190
+ const opts = {
191
+ ...DEFAULT_POOL,
192
+ max: 5,
193
+ ...poolConfig
194
+ };
195
+ connectionString = pinSearchPath(connectionString, opts.searchPath);
196
+ const pool = new Pool({
197
+ connectionString,
198
+ max: opts.max,
199
+ idleTimeoutMillis: opts.idleTimeoutMillis,
200
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
201
+ query_timeout: opts.queryTimeout,
202
+ statement_timeout: opts.statementTimeout,
203
+ keepAlive: opts.keepAlive,
204
+ keepAliveInitialDelayMillis: 0
205
+ });
206
+ pool.on("error", (err) => {
207
+ logger.error("[pg-direct-pool] Unexpected pool error", { detail: err.message });
208
+ });
209
+ guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
210
+ return {
211
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
212
+ pool,
213
+ connectionString
214
+ };
215
+ }
216
+ /**
217
+ * Create a read-only connection for routing read queries to replicas.
218
+ * Uses a moderate pool size since reads are distributed across replicas.
219
+ */
220
+ function createReadReplicaConnection(connectionString, schema, poolConfig) {
221
+ const opts = {
222
+ ...DEFAULT_POOL,
223
+ max: 10,
224
+ ...poolConfig
225
+ };
226
+ connectionString = pinSearchPath(connectionString, opts.searchPath);
227
+ const pool = new Pool({
228
+ connectionString,
229
+ max: opts.max,
230
+ idleTimeoutMillis: opts.idleTimeoutMillis,
231
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
232
+ query_timeout: opts.queryTimeout,
233
+ statement_timeout: opts.statementTimeout,
234
+ keepAlive: opts.keepAlive,
235
+ keepAliveInitialDelayMillis: 0
236
+ });
237
+ pool.on("error", (err) => {
238
+ logger.error("[pg-replica-pool] Unexpected pool error", { detail: err.message });
239
+ });
240
+ guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
241
+ return {
242
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
243
+ pool,
244
+ connectionString
245
+ };
246
+ }
247
+ //#endregion
248
+ export { guardPoolAgainstDirtyRelease as a, __exportAll as c, createReadReplicaConnection as i, __require as l, createDirectDatabaseConnection as n, pinSearchPath as o, createPostgresDatabaseConnection as r, __commonJSMin as s, connection_exports as t, __toESM as u };
249
+
250
+ //# sourceMappingURL=connection-BuZ97wsr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-BuZ97wsr.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\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: 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: 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: 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":"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"}
@@ -18,7 +18,49 @@ export interface PostgresPoolConfig {
18
18
  statementTimeout?: number;
19
19
  /** Enable TCP keep-alive (default: true) */
20
20
  keepAlive?: boolean;
21
+ /**
22
+ * `search_path` pinned on every connection (default: `"public"`).
23
+ *
24
+ * Pass `false` to send no `search_path` at all and inherit whatever the
25
+ * server/role defaults to. See {@link pinSearchPath} for why the default
26
+ * is not "inherit".
27
+ */
28
+ searchPath?: string | false;
21
29
  }
30
+ /**
31
+ * Pin `search_path` into a connection string, so unqualified SQL resolves to a
32
+ * schema this framework chose rather than to one Postgres inferred.
33
+ *
34
+ * Postgres defaults `search_path` to `"$user", public`: the *first* candidate
35
+ * is a schema named after the connecting role. Rebase creates a schema called
36
+ * `rebase` (auth, history, api keys), and every template, compose file and
37
+ * deployment doc names the database role `rebase` too — so `$user` resolves to
38
+ * a schema that exists, and every unqualified statement lands there instead of
39
+ * in `public`. The generated Drizzle schema emits bare `pgTable("posts", …)`
40
+ * for any collection without an explicit `schema`, which makes the *runtime's*
41
+ * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the
42
+ * Studio SQL editor and any hand-written migration are unqualified too. The
43
+ * result is collection tables created in, and served from, `rebase`.
44
+ *
45
+ * Drizzle cannot express the fix on its side: `pgSchema("public")` throws by
46
+ * design ("just use pgTable() instead"), so there is no way to emit a
47
+ * public-qualified table from the generator. The pin has to live on the
48
+ * connection.
49
+ *
50
+ * Precedence is deliberate and verified against node-postgres: `options` in
51
+ * the connection string wins over the `options` field passed to `Pool`, so
52
+ * rewriting the URL — rather than setting the field — is what makes this
53
+ * authoritative. Two escape hatches survive it:
54
+ *
55
+ * - an `options` that already mentions `search_path` is left untouched, so a
56
+ * deployment that deliberately pins something else keeps it;
57
+ * - `searchPath: false` (or an unparseable, non-URL connection string) sends
58
+ * nothing and inherits the server default.
59
+ *
60
+ * Anything else in `options` (a `statement_timeout`, say) is preserved and the
61
+ * `search_path` flag is appended to it.
62
+ */
63
+ export declare function pinSearchPath(connectionString: string, searchPath?: string | false): string;
22
64
  /**
23
65
  * Destroy pool clients that are released while still inside a transaction.
24
66
  *
@@ -0,0 +1,57 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "process";
3
+ __createRequire(import.meta.url);
4
+ import { readExistingSchema, t as planCollectionPolicies } from "./ensure-collection-tables-CBQdOETu.js";
5
+ //#region src/schema/ensure-collection-policies.ts
6
+ var isCreatePolicy = (statement) => /^\s*CREATE POLICY/i.test(statement);
7
+ /**
8
+ * Bring the declared collections' RLS policies up to date. Returns what it did.
9
+ *
10
+ * Only tables that already exist are touched: the boot-time table creator runs
11
+ * first, so anything still missing is a table this additive path is not allowed
12
+ * to create (a junction, or a relation left to a migration). Enabling RLS on a
13
+ * non-existent table would error, so those are recorded as skipped, not failed.
14
+ */
15
+ async function ensureCollectionPolicies(client, collections, log) {
16
+ const result = {
17
+ policiesApplied: 0,
18
+ tablesSecured: 0,
19
+ skipped: [],
20
+ failures: []
21
+ };
22
+ const plans = planCollectionPolicies(collections);
23
+ if (plans.length === 0) return result;
24
+ const existing = await readExistingSchema(client, Array.from(new Set(plans.map((p) => p.schema))));
25
+ for (const plan of plans) {
26
+ if (!existing.tables.has(plan.qualified)) {
27
+ result.skipped.push({
28
+ table: plan.qualified,
29
+ reason: "table is not present in the database; create it with `rebase db push` / `rebase db migrate`"
30
+ });
31
+ continue;
32
+ }
33
+ try {
34
+ await client.query(plan.enableRls);
35
+ result.tablesSecured++;
36
+ let created = 0;
37
+ for (const statement of plan.policyStatements) {
38
+ await client.query(statement);
39
+ if (isCreatePolicy(statement)) {
40
+ result.policiesApplied++;
41
+ created++;
42
+ }
43
+ }
44
+ log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied`);
45
+ } catch (err) {
46
+ result.failures.push({
47
+ table: plan.qualified,
48
+ error: err instanceof Error ? err.message : String(err)
49
+ });
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ //#endregion
55
+ export { ensureCollectionPolicies };
56
+
57
+ //# sourceMappingURL=ensure-collection-policies-ViG8XiPn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensure-collection-policies-ViG8XiPn.js","names":[],"sources":["../src/schema/ensure-collection-policies.ts"],"sourcesContent":["/**\n * Applying a bundle's RLS policies to a database at boot, idempotently.\n *\n * ## Why this exists\n *\n * {@link ensureCollectionTables} creates the collection *tables* a managed\n * runtime boots against, but a table with row-level security disabled and no\n * policies is not servable: authenticated requests run as the restricted\n * `rebase_user` role, so a read with no `SELECT` policy returns nothing (a\n * public collection answered 401) and a write with no `INSERT`/`UPDATE` policy\n * is denied. The policies live in the collections' `securityRules`; nothing at\n * boot applied them. `rebase db push` does — but it drives Atlas against a\n * local `DATABASE_URL`, and a managed tenant's database is reachable only from\n * inside the cluster, by the runtime that is already connected to it. So the\n * runtime is the only thing that *can* apply them, and this is where it does.\n *\n * ## Why this is safe to run on every boot\n *\n * Every statement is idempotent: `ENABLE ROW LEVEL SECURITY` is a no-op once\n * enabled, and each policy is a `DROP POLICY IF EXISTS` immediately followed by\n * a `CREATE POLICY`, so re-applying asserts exactly the declared state. It adds\n * and replaces; it never drops data. (It does not *reconcile* — a policy a\n * previous push left behind under an old name is not removed here; that stays a\n * `db push` / `db migrate` concern, alongside destructive schema changes.)\n *\n * Unlike table creation, a failure here is not fatal: RLS stays enabled, so a\n * table whose policies could not be applied fails **closed** (denies) rather\n * than leaking rows. One collection's policy failing (e.g. a rule that\n * references a table a real migration has not created yet) must not crash-loop\n * the whole deployment and take the other collections' working routes down with\n * it. Failures are reported loudly and per-table so the operator can see\n * exactly which collection is not yet servable and why.\n */\nimport { type CollectionConfig } from \"@rebasepro/types\";\nimport { planCollectionPolicies } from \"./generate-postgres-ddl-logic\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-tables\";\n\nexport interface PolicyEnsureResult {\n /** `CREATE POLICY` statements that ran successfully. */\n policiesApplied: number;\n /** Tables that had RLS enabled. */\n tablesSecured: number;\n /** Declared tables absent from the database — left to a real migration. */\n skipped: { table: string; reason: string }[];\n /** Tables whose RLS could not be fully applied (fail closed). */\n failures: { table: string; error: string }[];\n}\n\nconst isCreatePolicy = (statement: string): boolean => /^\\s*CREATE POLICY/i.test(statement);\n\n/**\n * Bring the declared collections' RLS policies up to date. Returns what it did.\n *\n * Only tables that already exist are touched: the boot-time table creator runs\n * first, so anything still missing is a table this additive path is not allowed\n * to create (a junction, or a relation left to a migration). Enabling RLS on a\n * non-existent table would error, so those are recorded as skipped, not failed.\n */\nexport async function ensureCollectionPolicies(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void\n): Promise<PolicyEnsureResult> {\n const result: PolicyEnsureResult = { policiesApplied: 0, tablesSecured: 0, skipped: [], failures: [] };\n\n const plans = planCollectionPolicies(collections);\n if (plans.length === 0) return result;\n\n const schemas = Array.from(new Set(plans.map(p => p.schema)));\n const existing = await readExistingSchema(client, schemas);\n\n for (const plan of plans) {\n if (!existing.tables.has(plan.qualified)) {\n result.skipped.push({\n table: plan.qualified,\n reason: \"table is not present in the database; create it with `rebase db push` / `rebase db migrate`\"\n });\n continue;\n }\n\n try {\n // Enable first: if a later policy statement fails, the table is left\n // locked (deny-all for the user role) rather than open.\n await client.query(plan.enableRls);\n result.tablesSecured++;\n\n let created = 0;\n for (const statement of plan.policyStatements) {\n await client.query(statement);\n if (isCreatePolicy(statement)) {\n result.policiesApplied++;\n created++;\n }\n }\n log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied`);\n } catch (err) {\n result.failures.push({\n table: plan.qualified,\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;AAgDA,IAAM,kBAAkB,cAA+B,qBAAqB,KAAK,SAAS;;;;;;;;;AAU1F,eAAsB,yBAClB,QACA,aACA,KAC2B;CAC3B,MAAM,SAA6B;EAAE,iBAAiB;EAAG,eAAe;EAAG,SAAS,CAAC;EAAG,UAAU,CAAC;CAAE;CAErG,MAAM,QAAQ,uBAAuB,WAAW;CAChD,IAAI,MAAM,WAAW,GAAG,OAAO;CAG/B,MAAM,WAAW,MAAM,mBAAmB,QAD1B,MAAM,KAAK,IAAI,IAAI,MAAM,KAAI,MAAK,EAAE,MAAM,CAAC,CACT,CAAO;CAEzD,KAAK,MAAM,QAAQ,OAAO;EACtB,IAAI,CAAC,SAAS,OAAO,IAAI,KAAK,SAAS,GAAG;GACtC,OAAO,QAAQ,KAAK;IAChB,OAAO,KAAK;IACZ,QAAQ;GACZ,CAAC;GACD;EACJ;EAEA,IAAI;GAGA,MAAM,OAAO,MAAM,KAAK,SAAS;GACjC,OAAO;GAEP,IAAI,UAAU;GACd,KAAK,MAAM,aAAa,KAAK,kBAAkB;IAC3C,MAAM,OAAO,MAAM,SAAS;IAC5B,IAAI,eAAe,SAAS,GAAG;KAC3B,OAAO;KACP;IACJ;GACJ;GACA,MAAM,GAAG,KAAK,UAAU,iBAAiB,QAAQ,qBAAqB;EAC1E,SAAS,KAAK;GACV,OAAO,SAAS,KAAK;IACjB,OAAO,KAAK;IACZ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GAC1D,CAAC;EACL;CACJ;CAEA,OAAO;AACX"}