@rebasepro/server-postgres 0.12.1-canary.gf5f1d39 → 0.13.1-canary.g06dbe5b
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.
- package/dist/PostgresBackendDriver.d.ts +49 -2
- package/dist/PostgresBootstrapper.d.ts +25 -1
- package/dist/auth/services.d.ts +40 -0
- package/dist/{src-BbFOPJ1S.js → auth-users-columns-CBEOeYqa.js} +1118 -220
- package/dist/auth-users-columns-CBEOeYqa.js.map +1 -0
- package/dist/backup/backup-service.d.ts +10 -1
- package/dist/backup/pg-tools.d.ts +47 -0
- package/dist/backup-service-Bww-Lg0s.js +8999 -0
- package/dist/backup-service-Bww-Lg0s.js.map +1 -0
- package/dist/cli-helpers.d.ts +96 -1
- package/dist/connection-BuZ97wsr.js +250 -0
- package/dist/connection-BuZ97wsr.js.map +1 -0
- package/dist/connection.d.ts +42 -0
- package/dist/data-transformer.d.ts +7 -2
- package/dist/data_driver-ULAyJEi9.js +193 -0
- package/dist/data_driver-ULAyJEi9.js.map +1 -0
- package/dist/ensure-collection-policies-B_JMGa5K.js +57 -0
- package/dist/ensure-collection-policies-B_JMGa5K.js.map +1 -0
- package/dist/ensure-collection-tables-DzeTEvMv.js +800 -0
- package/dist/ensure-collection-tables-DzeTEvMv.js.map +1 -0
- package/dist/index.es.js +2460 -10233
- package/dist/index.es.js.map +1 -1
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js +244 -0
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +185 -144
- package/dist/schema/auth-users-columns.d.ts +97 -0
- package/dist/schema/doctor-policy-checks.d.ts +28 -0
- package/dist/schema/doctor.d.ts +23 -25
- package/dist/schema/ensure-collection-policies.d.ts +60 -0
- package/dist/schema/ensure-collection-tables.d.ts +99 -3
- package/dist/schema/generate-drizzle-schema-logic.d.ts +10 -2
- package/dist/schema/generate-postgres-ddl-logic.d.ts +185 -3
- package/dist/schema/generated-schema-staleness.d.ts +39 -0
- package/dist/schema/introspect-db-constraints.d.ts +57 -0
- package/dist/schema/introspect-db-logic.d.ts +94 -5
- package/dist/schema/introspect-db-queries.d.ts +119 -0
- package/dist/schema/introspect-db-structure.d.ts +263 -0
- package/dist/schema/introspect-db-types.d.ts +11 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +135 -0
- package/dist/schema/search-column.d.ts +248 -0
- package/dist/security/rls-enforcement.d.ts +61 -5
- package/dist/services/FetchService.d.ts +38 -8
- package/dist/services/RelationService.d.ts +54 -1
- package/dist/services/channel-bus/index.d.ts +1 -7
- package/dist/services/collection-helpers.d.ts +62 -2
- package/dist/services/dataService.d.ts +8 -1
- package/dist/services/realtimeService.d.ts +131 -21
- package/dist/services/row-pipeline.d.ts +1 -1
- package/dist/{src-Zqwaw3P5.js → src-C_wvdMnl.js} +78 -145
- package/dist/src-C_wvdMnl.js.map +1 -0
- package/dist/utils/connection-string.d.ts +29 -0
- package/dist/utils/drizzle-conditions.d.ts +129 -6
- package/dist/utils/pg-error-utils.d.ts +35 -0
- package/dist/websocket-D1qbmLZ2.js +587 -0
- package/dist/websocket-D1qbmLZ2.js.map +1 -0
- package/package.json +17 -16
- package/src/PostgresAdapter.ts +21 -2
- package/src/PostgresBackendDriver.ts +176 -6
- package/src/PostgresBootstrapper.ts +245 -37
- package/src/auth/ensure-tables.ts +357 -81
- package/src/auth/services.ts +93 -7
- package/src/backup/backup-cli.ts +41 -2
- package/src/backup/backup-service.ts +38 -5
- package/src/backup/pg-tools.ts +96 -3
- package/src/cli-helpers.ts +199 -10
- package/src/cli.ts +276 -56
- package/src/collections/validate-relations.ts +136 -14
- package/src/connection.ts +73 -0
- package/src/data-transformer.ts +129 -20
- package/src/databasePoolManager.ts +5 -2
- package/src/history/ensure-history-table.ts +7 -0
- package/src/schema/auth-schema.ts +46 -19
- package/src/schema/auth-users-columns.ts +131 -0
- package/src/schema/doctor-cli.ts +12 -63
- package/src/schema/doctor-policy-checks.ts +105 -0
- package/src/schema/doctor.ts +135 -76
- package/src/schema/ensure-collection-policies.ts +105 -0
- package/src/schema/ensure-collection-tables.test.ts +105 -9
- package/src/schema/ensure-collection-tables.ts +572 -42
- package/src/schema/generate-drizzle-schema-logic.ts +169 -43
- package/src/schema/generate-postgres-ddl-logic.ts +670 -29
- package/src/schema/generate-postgres-ddl.ts +25 -2
- package/src/schema/generated-schema-staleness.ts +169 -0
- package/src/schema/introspect-db-constraints.ts +385 -0
- package/src/schema/introspect-db-inference.ts +18 -8
- package/src/schema/introspect-db-logic.ts +446 -100
- package/src/schema/introspect-db-queries.ts +326 -0
- package/src/schema/introspect-db-structure.ts +670 -0
- package/src/schema/introspect-db-types.ts +56 -0
- package/src/schema/introspect-db.ts +37 -80
- package/src/schema/introspect-runtime.test.ts +56 -8
- package/src/schema/introspect-runtime.ts +31 -9
- package/src/schema/non-sql-collections.test.ts +131 -0
- package/src/schema/rls-bootstrap-sql.ts +288 -0
- package/src/schema/search-column.ts +643 -0
- package/src/security/anonymous-grants.test.ts +4 -2
- package/src/security/policy-drift.test.ts +11 -3
- package/src/security/rls-enforcement.ts +149 -6
- package/src/services/BranchService.ts +71 -28
- package/src/services/FetchService.ts +265 -122
- package/src/services/PersistService.ts +57 -7
- package/src/services/RelationService.ts +358 -114
- package/src/services/channel-bus/index.ts +0 -9
- package/src/services/channel-history.ts +14 -0
- package/src/services/channel-presence.ts +13 -0
- package/src/services/collection-helpers.ts +123 -4
- package/src/services/dataService.ts +8 -1
- package/src/services/realtimeService.ts +346 -81
- package/src/services/row-pipeline.ts +1 -1
- package/src/utils/connection-string.ts +58 -0
- package/src/utils/drizzle-conditions.ts +396 -29
- package/src/utils/pg-error-utils.ts +73 -3
- package/src/websocket.ts +130 -24
- package/dist/chunk-DSJWtz9O.js +0 -40
- package/dist/ensure-collection-tables-CNTcZGvn.js +0 -304
- package/dist/ensure-collection-tables-CNTcZGvn.js.map +0 -1
- package/dist/schema/auth-bootstrap-sql.d.ts +0 -24
- package/dist/src-BbFOPJ1S.js.map +0 -1
- package/dist/src-Zqwaw3P5.js.map +0 -1
- package/src/schema/auth-bootstrap-sql.ts +0 -47
package/dist/cli-helpers.d.ts
CHANGED
|
@@ -1,9 +1,89 @@
|
|
|
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
|
-
export declare function getTableIncludesFromCollections(
|
|
27
|
+
export declare function getTableIncludesFromCollections(allCollections: CollectionConfig[]): Promise<string[]>;
|
|
4
28
|
export declare function getTableIncludes(collectionsPath: string): Promise<string[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Load a project's collections the way the Atlas-facing commands need them.
|
|
31
|
+
*
|
|
32
|
+
* Deliberately forgiving — a file that fails to import is skipped rather than
|
|
33
|
+
* fatal — because the callers use this to *narrow* what Atlas may touch, and a
|
|
34
|
+
* hard failure here would block a push over an unrelated broken file. Callers
|
|
35
|
+
* that cannot tolerate a partial answer (the table excludes, which fail closed)
|
|
36
|
+
* check the result themselves.
|
|
37
|
+
*/
|
|
38
|
+
export declare function loadCollectionsForCli(collectionsPath: string): Promise<CollectionConfig[]>;
|
|
5
39
|
export declare function getDevDatabaseUrl(databaseUrl: string): string;
|
|
6
40
|
export declare function ensureDevDatabaseExists(databaseUrl: string, devDatabaseUrl: string): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* The generated SQL for the project's `search` blocks, if it has any.
|
|
43
|
+
*
|
|
44
|
+
* @param drizzleDir directory holding the generated SQL. Defaults to `drizzle`
|
|
45
|
+
* under the working directory.
|
|
46
|
+
*/
|
|
47
|
+
export declare function readSearchDdl(drizzleDir?: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Bring the search column, its index and their helpers up to date.
|
|
50
|
+
*
|
|
51
|
+
* Runs *after* Atlas, not before: the statements are `ALTER TABLE ... ADD
|
|
52
|
+
* COLUMN`, so the table has to exist. Atlas is told to ignore these objects
|
|
53
|
+
* entirely (`getSearchExcludes`) — it cannot manage them, and left to itself it
|
|
54
|
+
* would plan a `DROP COLUMN` for every one, since they are absent from the
|
|
55
|
+
* desired state it was given.
|
|
56
|
+
*
|
|
57
|
+
* A no-op when no collection declared `search`. A failure is *not* swallowed:
|
|
58
|
+
* silently pushing a schema whose search column never appeared is how a
|
|
59
|
+
* collection ends up with search configured, no error anywhere, and no results.
|
|
60
|
+
*/
|
|
61
|
+
export declare function applySearchDdl(databaseUrl: string, drizzleDir?: string): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Glob patterns keeping Atlas away from the search objects.
|
|
64
|
+
*
|
|
65
|
+
* Returns an empty list — and so changes nothing — for a project with no
|
|
66
|
+
* `search` block, which is every project that has not opted in.
|
|
67
|
+
*/
|
|
68
|
+
export declare function getSearchExcludes(collectionsPath: string): Promise<string[]>;
|
|
69
|
+
/**
|
|
70
|
+
* Give the dev database the search helper functions before Atlas plans.
|
|
71
|
+
*
|
|
72
|
+
* Excluding the search column keeps Atlas from *diffing* it, but not from
|
|
73
|
+
* materialising the inspected schema — column and all — in the dev database to
|
|
74
|
+
* analyse the plan against. That replay is where a push against an
|
|
75
|
+
* already-searchable database died with `function public.rebase_search_text
|
|
76
|
+
* (jsonb) does not exist`: the column came across, the function it calls did
|
|
77
|
+
* not, because Atlas will not carry a function at all.
|
|
78
|
+
*
|
|
79
|
+
* Only the extensions and functions, never the tables: the dev database holds
|
|
80
|
+
* whatever Atlas puts there and nothing of ours.
|
|
81
|
+
*
|
|
82
|
+
* Best-effort by design. Failing here would block a push for a project whose
|
|
83
|
+
* collections merely failed to import, and if the functions really are needed
|
|
84
|
+
* and really are missing, Atlas says so a moment later in its own words.
|
|
85
|
+
*/
|
|
86
|
+
export declare function seedDevDatabaseSearchHelpers(devDatabaseUrl: string, collectionsPath: string): Promise<void>;
|
|
7
87
|
/**
|
|
8
88
|
* Query the live database for every user table/view outside the system
|
|
9
89
|
* catalogs. Separated from {@link getTableExcludes} so its failure mode can
|
|
@@ -37,3 +117,18 @@ export declare function getTableExcludes(databaseUrl: string, collectionsPath: s
|
|
|
37
117
|
queryExistingTables?: (databaseUrl: string) => Promise<string[]>;
|
|
38
118
|
getIncludes?: (collectionsPath: string) => Promise<string[]>;
|
|
39
119
|
}): Promise<string[]>;
|
|
120
|
+
/**
|
|
121
|
+
* Ask a yes/no question on an interactive terminal.
|
|
122
|
+
*
|
|
123
|
+
* The `isTTY` guard is the contract, not an optimisation: non-interactive
|
|
124
|
+
* shells (CI, pipes, agents) can never answer, and `readline` on a
|
|
125
|
+
* non-TTY stdin resolves with whatever the pipe happens to contain — or never
|
|
126
|
+
* resolves at all. Returning false there is what makes an unattended
|
|
127
|
+
* `db push` abort instead of auto-confirming a destructive change. Callers
|
|
128
|
+
* should already have gone through {@link decidePushSafety}, which decides
|
|
129
|
+
* whether interactive confirmation is even possible; this is the backstop.
|
|
130
|
+
*
|
|
131
|
+
* Lives here rather than in cli.ts so it is reachable from a test — cli.ts uses
|
|
132
|
+
* `import.meta` and cannot be imported by the jest runner.
|
|
133
|
+
*/
|
|
134
|
+
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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"}
|
package/dist/connection.d.ts
CHANGED
|
@@ -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
|
*
|
|
@@ -42,9 +42,14 @@ export declare function sanitizeAndConvertDates(obj: unknown): unknown;
|
|
|
42
42
|
*/
|
|
43
43
|
export declare function serializeDataToServer<M extends Record<string, unknown>>(row: M, properties: Properties, collection?: CollectionConfig, registry?: PostgresCollectionRegistry): SerializedEntityData;
|
|
44
44
|
/**
|
|
45
|
-
* Serialize a single property value for database storage
|
|
45
|
+
* Serialize a single property value for database storage.
|
|
46
|
+
*
|
|
47
|
+
* `propertyKey` is only ever used to phrase errors and warnings. Without it the
|
|
48
|
+
* one trace a bad value left was `Expected array value for array property, got
|
|
49
|
+
* string` — no collection, no property, no value, which in the log of a
|
|
50
|
+
* thousand-row import names nothing at all.
|
|
46
51
|
*/
|
|
47
|
-
export declare function serializePropertyToServer(value: unknown, property: Property): unknown;
|
|
52
|
+
export declare function serializePropertyToServer(value: unknown, property: Property, propertyKey?: string): unknown;
|
|
48
53
|
/**
|
|
49
54
|
* Transform IDs back to relation objects for frontend
|
|
50
55
|
*/
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
import "process";
|
|
3
|
+
__createRequire(import.meta.url);
|
|
4
|
+
//#region ../types/src/errors.ts
|
|
5
|
+
/**
|
|
6
|
+
* The single error type thrown across the entire Rebase client surface —
|
|
7
|
+
* HTTP data/control-plane calls, realtime/WebSocket operations, and
|
|
8
|
+
* client-side logic errors (e.g. an unknown collection accessor). A `catch`
|
|
9
|
+
* block only ever needs to check for this one class:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { RebaseApiError } from "@rebasepro/client"; // re-exported
|
|
13
|
+
*
|
|
14
|
+
* try {
|
|
15
|
+
* await client.data.products.update(id, { price: 9 });
|
|
16
|
+
* } catch (e) {
|
|
17
|
+
* if (e instanceof RebaseApiError) {
|
|
18
|
+
* if (e.status === 404) { ... } // HTTP failures carry a status
|
|
19
|
+
* console.error(e.code, e.details);
|
|
20
|
+
* }
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* `status` is present for HTTP failures and `undefined` otherwise, so its
|
|
25
|
+
* presence distinguishes transport-level errors from realtime/logic errors.
|
|
26
|
+
*
|
|
27
|
+
* @group Errors
|
|
28
|
+
*/
|
|
29
|
+
var RebaseApiError = class extends Error {
|
|
30
|
+
/** HTTP status code, or `undefined` for non-HTTP errors. */
|
|
31
|
+
status;
|
|
32
|
+
/** Stable machine-readable error code, when the server supplied one. See {@link RebaseErrorCode}. */
|
|
33
|
+
code;
|
|
34
|
+
/** Structured error payload from the server, when present. */
|
|
35
|
+
details;
|
|
36
|
+
constructor(message, init = {}) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "RebaseApiError";
|
|
39
|
+
this.status = init.status;
|
|
40
|
+
this.code = init.code;
|
|
41
|
+
this.details = init.details;
|
|
42
|
+
if (init.cause !== void 0) this.cause = init.cause;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region ../types/src/types/policy.ts
|
|
47
|
+
/**
|
|
48
|
+
* The id a request without a logged-in user reports as `rebase.uid()`.
|
|
49
|
+
*
|
|
50
|
+
* A user-context request always sets `app.uid`: blank would read back as
|
|
51
|
+
* `NULL`, and `NULL` is how the trusted server context is recognised, so an
|
|
52
|
+
* anonymous visitor would be promoted to server privileges. The driver
|
|
53
|
+
* therefore substitutes this sentinel at the single chokepoint where the GUC
|
|
54
|
+
* is set.
|
|
55
|
+
*
|
|
56
|
+
* The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
|
|
57
|
+
* tautology on the user path** — it is true for anonymous visitors too. Use
|
|
58
|
+
* {@link policy.authenticated} to mean "signed in", and
|
|
59
|
+
* {@link policy.serverContext} to mean "the trusted server context". Do not
|
|
60
|
+
* hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
|
|
61
|
+
* literal is not enough.
|
|
62
|
+
*
|
|
63
|
+
* @group Models
|
|
64
|
+
*/
|
|
65
|
+
var ANONYMOUS_USER_ID = "anonymous";
|
|
66
|
+
/**
|
|
67
|
+
* Every uid that has ever meant "nobody is signed in" — newest first.
|
|
68
|
+
*
|
|
69
|
+
* There are two because there were two. The types, the policy compiler, the
|
|
70
|
+
* JavaScript evaluator and the linter were all built on
|
|
71
|
+
* {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
|
|
72
|
+
* callers as `'anon'` — so `policy.authenticated()`, which compiled to
|
|
73
|
+
* `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
|
|
74
|
+
* sanctioned way to write "signed in" granted to everyone, and the linter
|
|
75
|
+
* flagged the spelling that actually worked as a foreign convention.
|
|
76
|
+
*
|
|
77
|
+
* The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
|
|
78
|
+
* because policies outlive the server that generated them: a database still
|
|
79
|
+
* holding policies from before the fix, or a project whose server has not been
|
|
80
|
+
* upgraded yet, must not become a grant in either direction. Compile against
|
|
81
|
+
* this list, not against a single literal.
|
|
82
|
+
*
|
|
83
|
+
* No real user id is ever one of these, so a match is always "not signed in".
|
|
84
|
+
*
|
|
85
|
+
* @group Models
|
|
86
|
+
*/
|
|
87
|
+
var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
|
|
88
|
+
/** @group Models */
|
|
89
|
+
var policy = {
|
|
90
|
+
true: () => ({ kind: "true" }),
|
|
91
|
+
false: () => ({ kind: "false" }),
|
|
92
|
+
and: (...operands) => ({
|
|
93
|
+
kind: "and",
|
|
94
|
+
operands
|
|
95
|
+
}),
|
|
96
|
+
or: (...operands) => ({
|
|
97
|
+
kind: "or",
|
|
98
|
+
operands
|
|
99
|
+
}),
|
|
100
|
+
not: (operand) => ({
|
|
101
|
+
kind: "not",
|
|
102
|
+
operand
|
|
103
|
+
}),
|
|
104
|
+
compare: (left, op, right) => ({
|
|
105
|
+
kind: "compare",
|
|
106
|
+
op,
|
|
107
|
+
left,
|
|
108
|
+
right
|
|
109
|
+
}),
|
|
110
|
+
rolesOverlap: (roles) => ({
|
|
111
|
+
kind: "rolesOverlap",
|
|
112
|
+
roles
|
|
113
|
+
}),
|
|
114
|
+
rolesContain: (roles) => ({
|
|
115
|
+
kind: "rolesContain",
|
|
116
|
+
roles
|
|
117
|
+
}),
|
|
118
|
+
authenticated: () => ({ kind: "authenticated" }),
|
|
119
|
+
serverContext: () => ({ kind: "serverContext" }),
|
|
120
|
+
existsIn: (args) => ({
|
|
121
|
+
kind: "existsIn",
|
|
122
|
+
collection: args.collection,
|
|
123
|
+
where: args.where
|
|
124
|
+
}),
|
|
125
|
+
raw: (sql) => ({
|
|
126
|
+
kind: "raw",
|
|
127
|
+
sql
|
|
128
|
+
}),
|
|
129
|
+
field: (name) => ({
|
|
130
|
+
kind: "field",
|
|
131
|
+
name
|
|
132
|
+
}),
|
|
133
|
+
outerField: (name) => ({
|
|
134
|
+
kind: "outerField",
|
|
135
|
+
name
|
|
136
|
+
}),
|
|
137
|
+
literal: (value) => ({
|
|
138
|
+
kind: "literal",
|
|
139
|
+
value
|
|
140
|
+
}),
|
|
141
|
+
authUid: () => ({ kind: "authUid" }),
|
|
142
|
+
authRoles: () => ({ kind: "authRoles" })
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* Thrown by {@link resolveClientListLimit} for a `limit` the platform will not
|
|
146
|
+
* serve. Carries an HTTP status so an ingress that speaks HTTP can forward it
|
|
147
|
+
* verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.
|
|
148
|
+
*
|
|
149
|
+
* @group Errors
|
|
150
|
+
*/
|
|
151
|
+
var ListLimitError = class ListLimitError extends RebaseApiError {
|
|
152
|
+
/** The ceiling that was exceeded — what the caller should page by instead. */
|
|
153
|
+
maxLimit;
|
|
154
|
+
constructor(message, maxLimit) {
|
|
155
|
+
super(message, {
|
|
156
|
+
status: 400,
|
|
157
|
+
code: "INVALID_LIMIT"
|
|
158
|
+
});
|
|
159
|
+
this.name = "ListLimitError";
|
|
160
|
+
this.maxLimit = maxLimit;
|
|
161
|
+
Object.setPrototypeOf(this, ListLimitError.prototype);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Resolve a client-supplied list `limit` into a safe, always-defined value.
|
|
166
|
+
*
|
|
167
|
+
* - An absent / blank limit falls back to the mode default:
|
|
168
|
+
* `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.
|
|
169
|
+
* - A limit that is present must be an integer in `[1, maxLimit]`. Anything
|
|
170
|
+
* else — `0`, a negative, `1.5`, `abc`, `100000000` — throws
|
|
171
|
+
* {@link ListLimitError} rather than being coerced into range, because every
|
|
172
|
+
* coercion answers a question the caller did not ask with a page it cannot
|
|
173
|
+
* tell apart from the whole collection.
|
|
174
|
+
*
|
|
175
|
+
* The return is never `undefined` — no ingress that routes its client limit
|
|
176
|
+
* through this can produce an unbounded read.
|
|
177
|
+
*
|
|
178
|
+
* @throws {ListLimitError} when a present `limit` is not an integer in range.
|
|
179
|
+
*/
|
|
180
|
+
function resolveClientListLimit(rawLimit, opts = {}) {
|
|
181
|
+
const maxLimit = opts.maxLimit ?? 1e3;
|
|
182
|
+
if (rawLimit != null && String(rawLimit).trim() !== "") {
|
|
183
|
+
const parsed = typeof rawLimit === "number" ? rawLimit : Number(String(rawLimit).trim());
|
|
184
|
+
if (!Number.isInteger(parsed) || parsed < 1) throw new ListLimitError(`Invalid \`limit\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`, maxLimit);
|
|
185
|
+
if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\` — answering with a smaller page would be indistinguishable from there being no more rows.`, maxLimit);
|
|
186
|
+
return parsed;
|
|
187
|
+
}
|
|
188
|
+
return opts.vectorSearch ? opts.vectorDefaultLimit ?? 10 : opts.defaultLimit ?? 50;
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
export { policy as a, ANONYMOUS_USER_IDS as i, resolveClientListLimit as n, ANONYMOUS_USER_ID as r, ListLimitError as t };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=data_driver-ULAyJEi9.js.map
|