@venturekit/data 0.0.48 → 0.0.51
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/README.md +23 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +2 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/index.js +1 -0
- package/dist/migrations/index.js.map +1 -1
- package/dist/migrations/roles.d.ts +81 -0
- package/dist/migrations/roles.d.ts.map +1 -0
- package/dist/migrations/roles.js +281 -0
- package/dist/migrations/roles.js.map +1 -0
- package/dist/outbox/fingerprints.d.ts +82 -0
- package/dist/outbox/fingerprints.d.ts.map +1 -0
- package/dist/outbox/fingerprints.js +100 -0
- package/dist/outbox/fingerprints.js.map +1 -0
- package/dist/outbox/index.d.ts +3 -1
- package/dist/outbox/index.d.ts.map +1 -1
- package/dist/outbox/index.js +2 -1
- package/dist/outbox/index.js.map +1 -1
- package/dist/query/index.d.ts +1 -1
- package/dist/query/index.d.ts.map +1 -1
- package/dist/query/index.js +1 -1
- package/dist/query/index.js.map +1 -1
- package/dist/query/login.d.ts +16 -0
- package/dist/query/login.d.ts.map +1 -0
- package/dist/query/login.js +23 -0
- package/dist/query/login.js.map +1 -0
- package/dist/query/pool.d.ts.map +1 -1
- package/dist/query/pool.js +24 -0
- package/dist/query/pool.js.map +1 -1
- package/dist/query/tenant.d.ts +32 -0
- package/dist/query/tenant.d.ts.map +1 -1
- package/dist/query/tenant.js +69 -16
- package/dist/query/tenant.js.map +1 -1
- package/package.json +2 -2
- package/src/sql/0000_vk_data_outbox_fingerprints.sql +39 -0
package/README.md
CHANGED
|
@@ -164,6 +164,29 @@ const rows = q
|
|
|
164
164
|
: [];
|
|
165
165
|
```
|
|
166
166
|
|
|
167
|
+
## Publish on change
|
|
168
|
+
|
|
169
|
+
`@venturekit/data/outbox` — a fact measured on a schedule (a month's usage, a
|
|
170
|
+
readiness report) goes out only when it says something new. `publishIfChanged`
|
|
171
|
+
keeps one fingerprint per aggregate and key in `vk_outbox_fingerprints` and
|
|
172
|
+
calls `publish` only when the payload's differs, recording it first in the
|
|
173
|
+
caller's transaction, so a concurrent pass publishes nothing twice and a
|
|
174
|
+
`publish` that throws takes the fingerprint back with it.
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
import { publishIfChanged, appendToOutboxIfChanged } from '@venturekit/data/outbox';
|
|
178
|
+
|
|
179
|
+
await withTransaction(async (tx) => {
|
|
180
|
+
const report = await measureMonth(tx, tenantId, month);
|
|
181
|
+
await publishIfChanged(tx.query,
|
|
182
|
+
{ aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
|
|
183
|
+
() => recordEvent(tx, { type: 'usage.reported', payload: report })); // your outbox, or:
|
|
184
|
+
await appendToOutboxIfChanged(tx.query, event, { key: month, ignore: ['reportedAt'] }); // vk_outbox
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`initial: false` publishes only a change to something already published.
|
|
189
|
+
|
|
167
190
|
## API Reference
|
|
168
191
|
|
|
169
192
|
See the [API reference](https://venturekit.dev/api-reference/data) for full documentation.
|
package/dist/index.d.ts
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
export * from './types/index.js';
|
|
7
7
|
export { createRdsConfig, DEFAULT_RDS_CONFIG, buildRdsConfig, } from './rds/index.js';
|
|
8
8
|
export type { RdsOutputs, RdsInfraConfig } from './rds/index.js';
|
|
9
|
-
export { createMigrationConfig, DEFAULT_MIGRATION_CONFIG, getFlywayEnv, runMigrations, getMigrationStatus, runSeeds, getSeedStatus, MIGRATIONS_TRACKING_TABLE, SEEDS_TRACKING_TABLE, MigrationToolNotImplementedError, MigrationHashMismatchError, MigrationCollisionError, applyDatabaseUrlToEnv, } from './migrations/index.js';
|
|
10
|
-
export type { RunResult, StatusEntry, RunOptions, SeedRunOptions, } from './migrations/index.js';
|
|
11
|
-
export { query, getPool, mapResults, mapRow, configureMapper, getMapperConfig, beginTransaction, withTransaction, buildTransaction, applyDbSecretToEnv, TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, runWithTenant, runWithTenantScope, runWithoutTenant, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './query/index.js';
|
|
9
|
+
export { createMigrationConfig, DEFAULT_MIGRATION_CONFIG, getFlywayEnv, runMigrations, getMigrationStatus, runSeeds, getSeedStatus, MIGRATIONS_TRACKING_TABLE, SEEDS_TRACKING_TABLE, MigrationToolNotImplementedError, MigrationHashMismatchError, MigrationCollisionError, applyDatabaseUrlToEnv, provisionDatabaseRoles, databaseRolesFromEnv, DATABASE_ROLES_ENV, } from './migrations/index.js';
|
|
10
|
+
export type { RunResult, StatusEntry, RunOptions, SeedRunOptions, DatabaseRolesOptions, DatabaseLoginSpec, } from './migrations/index.js';
|
|
11
|
+
export { query, getPool, mapResults, mapRow, configureMapper, getMapperConfig, beginTransaction, withTransaction, buildTransaction, applyDbSecretToEnv, TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, DATABASE_LOGIN_ENV, databaseLogin, PlatformScopeUnavailableError, withDatabaseLogin, runWithTenant, runWithTenantScope, runWithoutTenant, runAsPlatform, isPlatformScope, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './query/index.js';
|
|
12
12
|
export type { Transaction, ResultsMapper, Querier, MapperOptions, } from './query/index.js';
|
|
13
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,cAAc,kBAAkB,CAAC;AAGjC,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAKjE,OAAO,EAEL,qBAAqB,EACrB,wBAAwB,EACxB,YAAY,EAEZ,aAAa,EACb,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACb,yBAAyB,EACzB,oBAAoB,EAEpB,gCAAgC,EAChC,0BAA0B,EAC1B,uBAAuB,EAGvB,qBAAqB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,cAAc,kBAAkB,CAAC;AAGjC,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAKjE,OAAO,EAEL,qBAAqB,EACrB,wBAAwB,EACxB,YAAY,EAEZ,aAAa,EACb,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACb,yBAAyB,EACzB,oBAAoB,EAEpB,gCAAgC,EAChC,0BAA0B,EAC1B,uBAAuB,EAGvB,qBAAqB,EAErB,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EACV,SAAS,EACT,WAAW,EACX,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,MAAM,EACN,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAKhB,kBAAkB,EAUlB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,aAAa,EACb,6BAA6B,EAC7B,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,WAAW,EACX,aAAa,EACb,OAAO,EACP,aAAa,GACd,MAAM,kBAAkB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -19,7 +19,9 @@ runMigrations, getMigrationStatus, runSeeds, getSeedStatus, MIGRATIONS_TRACKING_
|
|
|
19
19
|
MigrationToolNotImplementedError, MigrationHashMismatchError, MigrationCollisionError,
|
|
20
20
|
// env-var bridge: parses DATABASE_URL into the granular DB_* vars used
|
|
21
21
|
// by getPool(). Auto-applied at the top of runMigrations / runSeeds.
|
|
22
|
-
applyDatabaseUrlToEnv,
|
|
22
|
+
applyDatabaseUrlToEnv,
|
|
23
|
+
// least-privilege roles (app login + platform role), run after migrations
|
|
24
|
+
provisionDatabaseRoles, databaseRolesFromEnv, DATABASE_ROLES_ENV, } from './migrations/index.js';
|
|
23
25
|
// Query utility, result mapping, and transactions
|
|
24
26
|
export { query, getPool, mapResults, mapRow, configureMapper, getMapperConfig, beginTransaction, withTransaction, buildTransaction,
|
|
25
27
|
// Lambda cold-start helper: fetches DB user/password from
|
|
@@ -36,5 +38,5 @@ applyDbSecretToEnv,
|
|
|
36
38
|
// read several tenants.
|
|
37
39
|
// See ./query/tenant.ts for the required policy shape and the
|
|
38
40
|
// database-role split RLS depends on.
|
|
39
|
-
TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, runWithTenant, runWithTenantScope, runWithoutTenant, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './query/index.js';
|
|
41
|
+
TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, DATABASE_LOGIN_ENV, databaseLogin, PlatformScopeUnavailableError, withDatabaseLogin, runWithTenant, runWithTenantScope, runWithoutTenant, runAsPlatform, isPlatformScope, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './query/index.js';
|
|
40
42
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,QAAQ;AACR,cAAc,kBAAkB,CAAC;AAEjC,MAAM;AACN,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,GACf,MAAM,gBAAgB,CAAC;AAGxB,uEAAuE;AACvE,iEAAiE;AACjE,gDAAgD;AAChD,OAAO;AACL,4BAA4B;AAC5B,qBAAqB,EACrB,wBAAwB,EACxB,YAAY;AACZ,sEAAsE;AACtE,aAAa,EACb,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACb,yBAAyB,EACzB,oBAAoB;AACpB,SAAS;AACT,gCAAgC,EAChC,0BAA0B,EAC1B,uBAAuB;AACvB,uEAAuE;AACvE,qEAAqE;AACrE,qBAAqB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,QAAQ;AACR,cAAc,kBAAkB,CAAC;AAEjC,MAAM;AACN,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,GACf,MAAM,gBAAgB,CAAC;AAGxB,uEAAuE;AACvE,iEAAiE;AACjE,gDAAgD;AAChD,OAAO;AACL,4BAA4B;AAC5B,qBAAqB,EACrB,wBAAwB,EACxB,YAAY;AACZ,sEAAsE;AACtE,aAAa,EACb,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACb,yBAAyB,EACzB,oBAAoB;AACpB,SAAS;AACT,gCAAgC,EAChC,0BAA0B,EAC1B,uBAAuB;AACvB,uEAAuE;AACvE,qEAAqE;AACrE,qBAAqB;AACrB,0EAA0E;AAC1E,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAU/B,kDAAkD;AAClD,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,MAAM,EACN,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB;AAChB,0DAA0D;AAC1D,mEAAmE;AACnE,iEAAiE;AACjE,gCAAgC;AAChC,kBAAkB;AAClB,2DAA2D;AAC3D,gEAAgE;AAChE,mEAAmE;AACnE,4DAA4D;AAC5D,+DAA+D;AAC/D,mEAAmE;AACnE,wBAAwB;AACxB,8DAA8D;AAC9D,sCAAsC;AACtC,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,aAAa,EACb,6BAA6B,EAC7B,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,kBAAkB,CAAC"}
|
|
@@ -45,5 +45,7 @@ export { runMigrations, getMigrationStatus, MIGRATIONS_TRACKING_TABLE, } from '.
|
|
|
45
45
|
export { runSeeds, getSeedStatus, SEEDS_TRACKING_TABLE, } from './seeds.js';
|
|
46
46
|
export { MigrationToolNotImplementedError, MigrationHashMismatchError, MigrationCollisionError, } from './errors.js';
|
|
47
47
|
export { applyDatabaseUrlToEnv } from './env.js';
|
|
48
|
+
export { provisionDatabaseRoles, databaseRolesFromEnv, DATABASE_ROLES_ENV } from './roles.js';
|
|
49
|
+
export type { DatabaseRolesOptions, DatabaseLoginSpec } from './roles.js';
|
|
48
50
|
export type { RunResult, StatusEntry, RunOptions, SeedRunOptions, } from './types.js';
|
|
49
51
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAI/E;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,EAAE,eAGtC,CAAC;AAEF;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,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M,aAAa,CAAC;AAErB,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC9F,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE1E,YAAY,EACV,SAAS,EACT,WAAW,EACX,UAAU,EACV,cAAc,GACf,MAAM,YAAY,CAAC"}
|
package/dist/migrations/index.js
CHANGED
|
@@ -63,4 +63,5 @@ export { runMigrations, getMigrationStatus, MIGRATIONS_TRACKING_TABLE, } from '.
|
|
|
63
63
|
export { runSeeds, getSeedStatus, SEEDS_TRACKING_TABLE, } from './seeds.js';
|
|
64
64
|
export { MigrationToolNotImplementedError, MigrationHashMismatchError, MigrationCollisionError, } from './errors.js';
|
|
65
65
|
export { applyDatabaseUrlToEnv } from './env.js';
|
|
66
|
+
export { provisionDatabaseRoles, databaseRolesFromEnv, DATABASE_ROLES_ENV } from './roles.js';
|
|
66
67
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,2EAA2E;AAE3E;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAoB;IACvD,IAAI,EAAE,QAAQ;IACd,aAAa,EAAE,eAAe;CAC/B,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,KAA4B;IAChE,IAAI,CAAC,KAAK;QAAE,OAAO,wBAAwB,CAAC;IAE5C,OAAO;QACL,GAAG,wBAAwB;QAC3B,GAAG,KAAK;KACT,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAAC,MAAuB,EAAE,KAAa;IACjE,OAAO;QACL,UAAU,EAAE,KAAK;QACjB,gBAAgB,EAA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eAAe,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;KACnF,CAAC;AACJ,CAAC;AAED,4EAA4E;AAE5E,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACL,QAAQ,EACR,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database's two logins, provisioned by the migration runner (and by
|
|
3
|
+
* `vk dev` locally) — the model is documented on `databaseRoleNames` in
|
|
4
|
+
* `@venturekit/core`:
|
|
5
|
+
*
|
|
6
|
+
* - the OWNER — the migration runner's login; creates and alters schema.
|
|
7
|
+
* Never injected into a function or a task.
|
|
8
|
+
* - the APP login (`DB_APP_USER`) — what every function connects as by
|
|
9
|
+
* default. One tenant at a time: the only role it may `SET ROLE` to is
|
|
10
|
+
* the tenant role.
|
|
11
|
+
* - the SYSTEM login (`DB_SYSTEM_USER`) — only the functions declared in
|
|
12
|
+
* `databases[].logins.system.functions` get it; may reach every tenant.
|
|
13
|
+
*
|
|
14
|
+
* Both are created `LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB`
|
|
15
|
+
* and re-narrowed on every run, so a role widened by hand is narrowed again.
|
|
16
|
+
* Neither is a member of the other.
|
|
17
|
+
*
|
|
18
|
+
* Grants, per login (`DB_GRANTS` for both, `DB_SYSTEM_GRANTS` overriding it
|
|
19
|
+
* for the system login):
|
|
20
|
+
* - `framework` — DML on the application's schemas, and for the system
|
|
21
|
+
* login a `vk_system_access` policy admitting it to every row of every
|
|
22
|
+
* RLS table (RDS cannot grant `BYPASSRLS`; the policy also makes
|
|
23
|
+
* cross-tenant access visible in `pg_policies`).
|
|
24
|
+
* - `migrations` — nothing but memberships: the application's migrations
|
|
25
|
+
* own every privilege, through the login's `memberOf` roles. Whatever a
|
|
26
|
+
* `framework` run granted the login directly (and the system policy) is
|
|
27
|
+
* revoked, so switching a login to `migrations` takes effect.
|
|
28
|
+
*
|
|
29
|
+
* Memberships: the tenant role (`DB_TENANT_ROLE`) to both logins
|
|
30
|
+
* `WITH INHERIT FALSE, SET TRUE` — assumable inside a tenant scope, never
|
|
31
|
+
* inherited; each login's `memberOf` roles `WITH INHERIT TRUE, SET FALSE`.
|
|
32
|
+
* A declared role that does not exist, or a login that cannot `SET ROLE` to
|
|
33
|
+
* the tenant role afterwards, fails the run — and with it the deploy.
|
|
34
|
+
*
|
|
35
|
+
* Idempotent; runs after every migration batch so tables added since the
|
|
36
|
+
* last run get their grants and policy, and (re)sets both passwords from the
|
|
37
|
+
* deployment's secrets so a rotated secret takes effect on the next deploy.
|
|
38
|
+
*/
|
|
39
|
+
export interface DatabaseLoginSpec {
|
|
40
|
+
user: string;
|
|
41
|
+
password: string;
|
|
42
|
+
/** Roles inherited by this login (created by the migrations). */
|
|
43
|
+
memberOf?: string[];
|
|
44
|
+
}
|
|
45
|
+
export interface DatabaseRolesOptions {
|
|
46
|
+
app: DatabaseLoginSpec;
|
|
47
|
+
system: DatabaseLoginSpec;
|
|
48
|
+
/** Default `framework`. */
|
|
49
|
+
grants?: 'framework' | 'migrations';
|
|
50
|
+
/** The system login's mode, when it differs (default: {@link grants}). */
|
|
51
|
+
systemGrants?: 'framework' | 'migrations';
|
|
52
|
+
/** The role tenant-scoped statements assume (`DB_TENANT_ROLE`), created by the migrations. */
|
|
53
|
+
tenantRole?: string | null;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Create or update both logins, their memberships and (in `framework` mode)
|
|
57
|
+
* their grants and the system policy. Run as the table owner, after
|
|
58
|
+
* migrations.
|
|
59
|
+
*
|
|
60
|
+
* Uses the shared pool by default (the migration runner's owner login).
|
|
61
|
+
* With `connectionString`, a dedicated connection is opened and closed
|
|
62
|
+
* instead — for a process whose pool must stay on a login (`vk dev`).
|
|
63
|
+
*/
|
|
64
|
+
export declare function provisionDatabaseRoles(options: DatabaseRolesOptions & {
|
|
65
|
+
connectionString?: string;
|
|
66
|
+
}): Promise<void>;
|
|
67
|
+
/** The env vars the migration runner / `vk dev` pass to {@link provisionDatabaseRoles}. */
|
|
68
|
+
export declare const DATABASE_ROLES_ENV: {
|
|
69
|
+
readonly appUser: "DB_APP_USER";
|
|
70
|
+
readonly appPassword: "DB_APP_PASSWORD";
|
|
71
|
+
readonly appMemberOf: "DB_APP_MEMBER_OF";
|
|
72
|
+
readonly systemUser: "DB_SYSTEM_USER";
|
|
73
|
+
readonly systemPassword: "DB_SYSTEM_PASSWORD";
|
|
74
|
+
readonly systemMemberOf: "DB_SYSTEM_MEMBER_OF";
|
|
75
|
+
readonly grants: "DB_GRANTS";
|
|
76
|
+
readonly systemGrants: "DB_SYSTEM_GRANTS";
|
|
77
|
+
readonly tenantRole: "DB_TENANT_ROLE";
|
|
78
|
+
};
|
|
79
|
+
/** {@link DatabaseRolesOptions} from the environment, or `null` when the logins are not configured. */
|
|
80
|
+
export declare function databaseRolesFromEnv(env?: Record<string, string | undefined>): DatabaseRolesOptions | null;
|
|
81
|
+
//# sourceMappingURL=roles.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"roles.d.ts","sourceRoot":"","sources":["../../src/migrations/roles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAIH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,iEAAiE;IACjE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,iBAAiB,CAAC;IACvB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,2BAA2B;IAC3B,MAAM,CAAC,EAAE,WAAW,GAAG,YAAY,CAAC;IACpC,0EAA0E;IAC1E,YAAY,CAAC,EAAE,WAAW,GAAG,YAAY,CAAC;IAC1C,8FAA8F;IAC9F,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAyID;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,oBAAoB,GAAG;IAAE,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5D,OAAO,CAAC,IAAI,CAAC,CAgEf;AAED,2FAA2F;AAC3F,eAAO,MAAM,kBAAkB;;;;;;;;;;CAUrB,CAAC;AAKX,uGAAuG;AACvG,wBAAgB,oBAAoB,CAAC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GAAG,oBAAoB,GAAG,IAAI,CAiBvH"}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database's two logins, provisioned by the migration runner (and by
|
|
3
|
+
* `vk dev` locally) — the model is documented on `databaseRoleNames` in
|
|
4
|
+
* `@venturekit/core`:
|
|
5
|
+
*
|
|
6
|
+
* - the OWNER — the migration runner's login; creates and alters schema.
|
|
7
|
+
* Never injected into a function or a task.
|
|
8
|
+
* - the APP login (`DB_APP_USER`) — what every function connects as by
|
|
9
|
+
* default. One tenant at a time: the only role it may `SET ROLE` to is
|
|
10
|
+
* the tenant role.
|
|
11
|
+
* - the SYSTEM login (`DB_SYSTEM_USER`) — only the functions declared in
|
|
12
|
+
* `databases[].logins.system.functions` get it; may reach every tenant.
|
|
13
|
+
*
|
|
14
|
+
* Both are created `LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB`
|
|
15
|
+
* and re-narrowed on every run, so a role widened by hand is narrowed again.
|
|
16
|
+
* Neither is a member of the other.
|
|
17
|
+
*
|
|
18
|
+
* Grants, per login (`DB_GRANTS` for both, `DB_SYSTEM_GRANTS` overriding it
|
|
19
|
+
* for the system login):
|
|
20
|
+
* - `framework` — DML on the application's schemas, and for the system
|
|
21
|
+
* login a `vk_system_access` policy admitting it to every row of every
|
|
22
|
+
* RLS table (RDS cannot grant `BYPASSRLS`; the policy also makes
|
|
23
|
+
* cross-tenant access visible in `pg_policies`).
|
|
24
|
+
* - `migrations` — nothing but memberships: the application's migrations
|
|
25
|
+
* own every privilege, through the login's `memberOf` roles. Whatever a
|
|
26
|
+
* `framework` run granted the login directly (and the system policy) is
|
|
27
|
+
* revoked, so switching a login to `migrations` takes effect.
|
|
28
|
+
*
|
|
29
|
+
* Memberships: the tenant role (`DB_TENANT_ROLE`) to both logins
|
|
30
|
+
* `WITH INHERIT FALSE, SET TRUE` — assumable inside a tenant scope, never
|
|
31
|
+
* inherited; each login's `memberOf` roles `WITH INHERIT TRUE, SET FALSE`.
|
|
32
|
+
* A declared role that does not exist, or a login that cannot `SET ROLE` to
|
|
33
|
+
* the tenant role afterwards, fails the run — and with it the deploy.
|
|
34
|
+
*
|
|
35
|
+
* Idempotent; runs after every migration batch so tables added since the
|
|
36
|
+
* last run get their grants and policy, and (re)sets both passwords from the
|
|
37
|
+
* deployment's secrets so a rotated secret takes effect on the next deploy.
|
|
38
|
+
*/
|
|
39
|
+
import { beginTransaction, rollbackQuietly } from '../query/transaction.js';
|
|
40
|
+
/** Plain, unquoted Postgres identifiers only: they are interpolated (as `%I`). */
|
|
41
|
+
const ROLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
42
|
+
/**
|
|
43
|
+
* The provisioning block. Every value arrives through `current_setting`
|
|
44
|
+
* and is formatted with `%I` / `%L`, so nothing is spliced into SQL text.
|
|
45
|
+
* Lists are comma-separated role names (validated before they get here).
|
|
46
|
+
*/
|
|
47
|
+
const PROVISION_SQL = `
|
|
48
|
+
DO $vk$
|
|
49
|
+
DECLARE
|
|
50
|
+
app text := current_setting('vk.roles_app');
|
|
51
|
+
sys text := current_setting('vk.roles_system');
|
|
52
|
+
app_pass text := current_setting('vk.roles_app_password');
|
|
53
|
+
sys_pass text := current_setting('vk.roles_system_password');
|
|
54
|
+
tenant text := NULLIF(current_setting('vk.roles_tenant'), '');
|
|
55
|
+
grants_mode text := current_setting('vk.roles_grants');
|
|
56
|
+
sys_grants text := current_setting('vk.roles_system_grants');
|
|
57
|
+
fw_logins text[] := ARRAY[]::text[];
|
|
58
|
+
app_member text[] := string_to_array(NULLIF(current_setting('vk.roles_app_member_of'), ''), ',');
|
|
59
|
+
sys_member text[] := string_to_array(NULLIF(current_setting('vk.roles_system_member_of'), ''), ',');
|
|
60
|
+
login text;
|
|
61
|
+
pass text;
|
|
62
|
+
r text;
|
|
63
|
+
a record;
|
|
64
|
+
s record;
|
|
65
|
+
t record;
|
|
66
|
+
BEGIN
|
|
67
|
+
FOREACH login IN ARRAY ARRAY[app, sys] LOOP
|
|
68
|
+
pass := CASE WHEN login = app THEN app_pass ELSE sys_pass END;
|
|
69
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = login) THEN
|
|
70
|
+
EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', login, pass);
|
|
71
|
+
ELSE
|
|
72
|
+
EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', login, pass);
|
|
73
|
+
END IF;
|
|
74
|
+
-- Only what differs: PostgreSQL refuses a non-superuser (the RDS master)
|
|
75
|
+
-- any SUPERUSER / BYPASSRLS clause, even one that changes nothing.
|
|
76
|
+
SELECT rolsuper, rolbypassrls, rolcreatedb, rolcreaterole, rolinherit INTO a FROM pg_roles WHERE rolname = login;
|
|
77
|
+
IF a.rolsuper OR a.rolbypassrls THEN
|
|
78
|
+
RAISE EXCEPTION 'login % is SUPERUSER or BYPASSRLS: an administrator must remove that before it is used', login;
|
|
79
|
+
END IF;
|
|
80
|
+
IF a.rolcreatedb THEN EXECUTE format('ALTER ROLE %I NOCREATEDB', login); END IF;
|
|
81
|
+
IF a.rolcreaterole THEN EXECUTE format('ALTER ROLE %I NOCREATEROLE', login); END IF;
|
|
82
|
+
IF NOT a.rolinherit THEN EXECUTE format('ALTER ROLE %I INHERIT', login); END IF;
|
|
83
|
+
EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_database(), login);
|
|
84
|
+
END LOOP;
|
|
85
|
+
-- Neither login may become the other.
|
|
86
|
+
IF pg_has_role(app, sys, 'MEMBER') THEN EXECUTE format('REVOKE %I FROM %I', sys, app); END IF;
|
|
87
|
+
IF pg_has_role(sys, app, 'MEMBER') THEN EXECUTE format('REVOKE %I FROM %I', app, sys); END IF;
|
|
88
|
+
|
|
89
|
+
IF tenant IS NOT NULL THEN
|
|
90
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = tenant) THEN
|
|
91
|
+
RAISE EXCEPTION 'tenantRole % does not exist: create it in a migration', tenant;
|
|
92
|
+
END IF;
|
|
93
|
+
EXECUTE format('GRANT %I TO %I, %I WITH INHERIT FALSE, SET TRUE', tenant, app, sys);
|
|
94
|
+
IF NOT pg_has_role(app, tenant, 'SET') OR NOT pg_has_role(sys, tenant, 'SET') THEN
|
|
95
|
+
RAISE EXCEPTION 'a login cannot SET ROLE to the tenant role %', tenant;
|
|
96
|
+
END IF;
|
|
97
|
+
END IF;
|
|
98
|
+
FOREACH r IN ARRAY COALESCE(app_member, '{}') LOOP
|
|
99
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r) THEN
|
|
100
|
+
RAISE EXCEPTION 'logins.app.memberOf role % does not exist: create it in a migration', r;
|
|
101
|
+
END IF;
|
|
102
|
+
EXECUTE format('GRANT %I TO %I WITH INHERIT TRUE, SET FALSE', r, app);
|
|
103
|
+
END LOOP;
|
|
104
|
+
FOREACH r IN ARRAY COALESCE(sys_member, '{}') LOOP
|
|
105
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r) THEN
|
|
106
|
+
RAISE EXCEPTION 'logins.system.memberOf role % does not exist: create it in a migration', r;
|
|
107
|
+
END IF;
|
|
108
|
+
EXECUTE format('GRANT %I TO %I WITH INHERIT TRUE, SET FALSE', r, sys);
|
|
109
|
+
END LOOP;
|
|
110
|
+
|
|
111
|
+
IF grants_mode = 'framework' THEN fw_logins := fw_logins || app; END IF;
|
|
112
|
+
IF sys_grants = 'framework' THEN fw_logins := fw_logins || sys; END IF;
|
|
113
|
+
-- The application's schemas: every non-system schema the owner controls.
|
|
114
|
+
FOR s IN
|
|
115
|
+
SELECT n.nspname FROM pg_namespace n
|
|
116
|
+
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
117
|
+
AND n.nspname NOT LIKE 'pg\\_%'
|
|
118
|
+
AND pg_has_role(current_user, n.nspowner, 'USAGE')
|
|
119
|
+
LOOP
|
|
120
|
+
FOREACH login IN ARRAY ARRAY[app, sys] LOOP
|
|
121
|
+
IF login = ANY (fw_logins) THEN
|
|
122
|
+
EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', s.nspname, login);
|
|
123
|
+
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO %I', s.nspname, login);
|
|
124
|
+
EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', s.nspname, login);
|
|
125
|
+
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO %I', s.nspname, login);
|
|
126
|
+
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I', s.nspname, login);
|
|
127
|
+
ELSE
|
|
128
|
+
-- migrations mode: the login holds only what its memberOf roles hold.
|
|
129
|
+
EXECUTE format('REVOKE ALL ON ALL TABLES IN SCHEMA %I FROM %I', s.nspname, login);
|
|
130
|
+
EXECUTE format('REVOKE ALL ON ALL SEQUENCES IN SCHEMA %I FROM %I', s.nspname, login);
|
|
131
|
+
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I REVOKE ALL ON TABLES FROM %I', s.nspname, login);
|
|
132
|
+
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I REVOKE ALL ON SEQUENCES FROM %I', s.nspname, login);
|
|
133
|
+
EXECUTE format('REVOKE ALL ON SCHEMA %I FROM %I', s.nspname, login);
|
|
134
|
+
END IF;
|
|
135
|
+
END LOOP;
|
|
136
|
+
END LOOP;
|
|
137
|
+
-- Migration bookkeeping is the owner's alone.
|
|
138
|
+
IF to_regclass('public.__vk_migrations') IS NOT NULL THEN
|
|
139
|
+
EXECUTE format('REVOKE ALL ON public.__vk_migrations FROM %I, %I', app, sys);
|
|
140
|
+
END IF;
|
|
141
|
+
IF to_regclass('public.__vk_seeds') IS NOT NULL THEN
|
|
142
|
+
EXECUTE format('REVOKE ALL ON public.__vk_seeds FROM %I, %I', app, sys);
|
|
143
|
+
END IF;
|
|
144
|
+
-- The system login's explicit way through RLS (framework mode), on every
|
|
145
|
+
-- RLS table — and none at all in migrations mode, where the migrations'
|
|
146
|
+
-- policies for its memberOf roles are its only way.
|
|
147
|
+
FOR t IN
|
|
148
|
+
SELECT n.nspname, c.relname,
|
|
149
|
+
EXISTS (SELECT 1 FROM pg_policies p
|
|
150
|
+
WHERE p.schemaname = n.nspname AND p.tablename = c.relname AND p.policyname = 'vk_system_access') AS has_policy
|
|
151
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
152
|
+
WHERE c.relkind IN ('r', 'p') AND c.relrowsecurity
|
|
153
|
+
AND pg_has_role(current_user, c.relowner, 'USAGE')
|
|
154
|
+
LOOP
|
|
155
|
+
IF sys_grants = 'framework' AND NOT t.has_policy THEN
|
|
156
|
+
EXECUTE format(
|
|
157
|
+
'CREATE POLICY vk_system_access ON %I.%I AS PERMISSIVE FOR ALL TO %I USING (true) WITH CHECK (true)',
|
|
158
|
+
t.nspname, t.relname, sys
|
|
159
|
+
);
|
|
160
|
+
ELSIF sys_grants = 'migrations' AND t.has_policy THEN
|
|
161
|
+
EXECUTE format('DROP POLICY vk_system_access ON %I.%I', t.nspname, t.relname);
|
|
162
|
+
END IF;
|
|
163
|
+
END LOOP;
|
|
164
|
+
END
|
|
165
|
+
$vk$;
|
|
166
|
+
`;
|
|
167
|
+
function assertRole(label, value) {
|
|
168
|
+
if (!ROLE_NAME.test(value)) {
|
|
169
|
+
throw new Error(`[@venturekit/data] provisionDatabaseRoles: ${label} ${JSON.stringify(value)} is not a plain Postgres role name.`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Create or update both logins, their memberships and (in `framework` mode)
|
|
174
|
+
* their grants and the system policy. Run as the table owner, after
|
|
175
|
+
* migrations.
|
|
176
|
+
*
|
|
177
|
+
* Uses the shared pool by default (the migration runner's owner login).
|
|
178
|
+
* With `connectionString`, a dedicated connection is opened and closed
|
|
179
|
+
* instead — for a process whose pool must stay on a login (`vk dev`).
|
|
180
|
+
*/
|
|
181
|
+
export async function provisionDatabaseRoles(options) {
|
|
182
|
+
const tenant = options.tenantRole ?? '';
|
|
183
|
+
assertRole('app.user', options.app.user);
|
|
184
|
+
assertRole('system.user', options.system.user);
|
|
185
|
+
if (options.app.user === options.system.user) {
|
|
186
|
+
throw new Error('[@venturekit/data] provisionDatabaseRoles: the app and system logins must differ.');
|
|
187
|
+
}
|
|
188
|
+
if (tenant)
|
|
189
|
+
assertRole('tenantRole', tenant);
|
|
190
|
+
for (const r of [...(options.app.memberOf ?? []), ...(options.system.memberOf ?? [])])
|
|
191
|
+
assertRole('memberOf', r);
|
|
192
|
+
if (!options.app.password || !options.system.password) {
|
|
193
|
+
throw new Error('[@venturekit/data] provisionDatabaseRoles: both logins need a password.');
|
|
194
|
+
}
|
|
195
|
+
const grants = options.grants ?? 'framework';
|
|
196
|
+
const systemGrants = options.systemGrants ?? grants;
|
|
197
|
+
for (const mode of [grants, systemGrants]) {
|
|
198
|
+
if (mode !== 'framework' && mode !== 'migrations') {
|
|
199
|
+
throw new Error(`[@venturekit/data] provisionDatabaseRoles: grants must be 'framework' or 'migrations'.`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const settings = [
|
|
203
|
+
options.app.user,
|
|
204
|
+
options.system.user,
|
|
205
|
+
options.app.password,
|
|
206
|
+
options.system.password,
|
|
207
|
+
tenant,
|
|
208
|
+
grants,
|
|
209
|
+
(options.app.memberOf ?? []).join(','),
|
|
210
|
+
(options.system.memberOf ?? []).join(','),
|
|
211
|
+
systemGrants,
|
|
212
|
+
];
|
|
213
|
+
const SETTINGS_SQL = `SELECT set_config('vk.roles_app', $1, true), set_config('vk.roles_system', $2, true),
|
|
214
|
+
set_config('vk.roles_app_password', $3, true), set_config('vk.roles_system_password', $4, true),
|
|
215
|
+
set_config('vk.roles_tenant', $5, true), set_config('vk.roles_grants', $6, true),
|
|
216
|
+
set_config('vk.roles_app_member_of', $7, true), set_config('vk.roles_system_member_of', $8, true),
|
|
217
|
+
set_config('vk.roles_system_grants', $9, true)`;
|
|
218
|
+
if (options.connectionString) {
|
|
219
|
+
const { default: pg } = await import('pg');
|
|
220
|
+
const client = new pg.Client({ connectionString: options.connectionString });
|
|
221
|
+
await client.connect();
|
|
222
|
+
try {
|
|
223
|
+
await client.query('BEGIN');
|
|
224
|
+
await client.query(SETTINGS_SQL, settings);
|
|
225
|
+
await client.query(PROVISION_SQL);
|
|
226
|
+
await client.query('COMMIT');
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
await client.query('ROLLBACK').catch(() => undefined);
|
|
230
|
+
throw err;
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
await client.end();
|
|
234
|
+
}
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const tx = await beginTransaction({ statementTimeoutMs: 0 });
|
|
238
|
+
try {
|
|
239
|
+
await tx.query(SETTINGS_SQL, settings);
|
|
240
|
+
await tx.query(PROVISION_SQL);
|
|
241
|
+
await tx.commit();
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
await rollbackQuietly(tx);
|
|
245
|
+
throw err;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** The env vars the migration runner / `vk dev` pass to {@link provisionDatabaseRoles}. */
|
|
249
|
+
export const DATABASE_ROLES_ENV = {
|
|
250
|
+
appUser: 'DB_APP_USER',
|
|
251
|
+
appPassword: 'DB_APP_PASSWORD',
|
|
252
|
+
appMemberOf: 'DB_APP_MEMBER_OF',
|
|
253
|
+
systemUser: 'DB_SYSTEM_USER',
|
|
254
|
+
systemPassword: 'DB_SYSTEM_PASSWORD',
|
|
255
|
+
systemMemberOf: 'DB_SYSTEM_MEMBER_OF',
|
|
256
|
+
grants: 'DB_GRANTS',
|
|
257
|
+
systemGrants: 'DB_SYSTEM_GRANTS',
|
|
258
|
+
tenantRole: 'DB_TENANT_ROLE',
|
|
259
|
+
};
|
|
260
|
+
const list = (raw) => (raw ?? '').split(',').map((r) => r.trim()).filter(Boolean);
|
|
261
|
+
/** {@link DatabaseRolesOptions} from the environment, or `null` when the logins are not configured. */
|
|
262
|
+
export function databaseRolesFromEnv(env = process.env) {
|
|
263
|
+
const e = DATABASE_ROLES_ENV;
|
|
264
|
+
const appUser = env[e.appUser]?.trim();
|
|
265
|
+
const systemUser = env[e.systemUser]?.trim();
|
|
266
|
+
const appPassword = env[e.appPassword];
|
|
267
|
+
const systemPassword = env[e.systemPassword];
|
|
268
|
+
if (!appUser || !systemUser || !appPassword || !systemPassword)
|
|
269
|
+
return null;
|
|
270
|
+
const grants = env[e.grants]?.trim() === 'migrations' ? 'migrations' : 'framework';
|
|
271
|
+
const systemRaw = env[e.systemGrants]?.trim();
|
|
272
|
+
const systemGrants = systemRaw === 'migrations' || systemRaw === 'framework' ? systemRaw : grants;
|
|
273
|
+
return {
|
|
274
|
+
app: { user: appUser, password: appPassword, memberOf: list(env[e.appMemberOf]) },
|
|
275
|
+
system: { user: systemUser, password: systemPassword, memberOf: list(env[e.systemMemberOf]) },
|
|
276
|
+
grants,
|
|
277
|
+
systemGrants,
|
|
278
|
+
tenantRole: env[e.tenantRole]?.trim() || null,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
//# sourceMappingURL=roles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"roles.js","sourceRoot":"","sources":["../../src/migrations/roles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAoB5E,kFAAkF;AAClF,MAAM,SAAS,GAAG,yBAAyB,CAAC;AAE5C;;;;GAIG;AACH,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuHrB,CAAC;AAEF,SAAS,UAAU,CAAC,KAAa,EAAE,KAAa;IAC9C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,8CAA8C,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACrI,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAA6D;IAE7D,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;IACxC,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACzC,UAAU,CAAC,aAAa,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,CAA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C,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC;IACnF,MAAM,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC;IAC9C,MAAM,YAAY,GAAG,SAAS,KAAK,YAAY,IAAI,SAAS,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;IAClG,OAAO;QACL,GAAG,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,EAAE;QACjF,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,cAAc,EAAE,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,EAAE;QAC7F,MAAM;QACN,YAAY;QACZ,UAAU,EAAE,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,IAAI;KAC9C,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @venturekit/data — publish on change.
|
|
3
|
+
*
|
|
4
|
+
* A fact a service measures on a schedule — a tenant's month of usage, a readiness report
|
|
5
|
+
* recomputed every five minutes — is worth an event only when it says something new. Without
|
|
6
|
+
* a place to keep "what did we last say", every product grows its own: a hash column on a
|
|
7
|
+
* projection row here, a table keyed by month there, each comparing by hand, each with its own
|
|
8
|
+
* idea of what the payload's timestamp does to the comparison.
|
|
9
|
+
*
|
|
10
|
+
* {@link publishIfChanged} keeps one fingerprint per aggregate and key in
|
|
11
|
+
* `vk_outbox_fingerprints` (`0000_vk_data_outbox_fingerprints.sql`) and calls `publish` only
|
|
12
|
+
* when the payload's differs from the one last recorded. {@link appendToOutboxIfChanged} is the
|
|
13
|
+
* same over this package's own outbox.
|
|
14
|
+
*
|
|
15
|
+
* ### One transaction, record first
|
|
16
|
+
*
|
|
17
|
+
* The fingerprint is written with `INSERT … ON CONFLICT … DO UPDATE … WHERE … IS DISTINCT FROM
|
|
18
|
+
* … RETURNING`, which takes the row's lock until the transaction ends. A second pass for the
|
|
19
|
+
* same key running concurrently waits on it, then finds the fingerprint the first one committed
|
|
20
|
+
* and publishes nothing — the same change goes out once. That is why the record comes before
|
|
21
|
+
* `publish`, and why `querier` must be the transaction's: on the pool, a `publish` that failed
|
|
22
|
+
* would leave a change recorded and never sent. A `publish` that throws rolls both back.
|
|
23
|
+
*/
|
|
24
|
+
import type { Querier } from '../query/index.js';
|
|
25
|
+
import type { AppendOutboxInput } from './postgres.js';
|
|
26
|
+
/** Default table name, created by `0000_vk_data_outbox_fingerprints.sql`. */
|
|
27
|
+
export declare const DEFAULT_FINGERPRINT_TABLE = "vk_outbox_fingerprints";
|
|
28
|
+
/**
|
|
29
|
+
* What a payload says, as a sha-256 hex digest of its canonical JSON. `ignore` names top-level
|
|
30
|
+
* fields left out — the instant a report was made, which changes on every pass and says nothing.
|
|
31
|
+
*/
|
|
32
|
+
export declare function payloadFingerprint(payload: unknown, ignore?: readonly string[]): string;
|
|
33
|
+
export interface PublishIfChangedInput {
|
|
34
|
+
aggregateType: string;
|
|
35
|
+
aggregateId: string;
|
|
36
|
+
/** What is compared within the aggregate — a month, a report kind. Default `''`: the aggregate has one. */
|
|
37
|
+
key?: string;
|
|
38
|
+
/** Recorded with the fingerprint, for a tenant guard on the table. */
|
|
39
|
+
tenantId?: string | null;
|
|
40
|
+
payload: unknown;
|
|
41
|
+
/** Top-level payload fields left out of the comparison ({@link payloadFingerprint}). */
|
|
42
|
+
ignore?: readonly string[];
|
|
43
|
+
/**
|
|
44
|
+
* Whether a first payload — nothing recorded yet for this key — is published. Default `true`.
|
|
45
|
+
* `false` publishes only a change to something already published: a month nothing happened in
|
|
46
|
+
* is not worth a first report, but one that went quiet after a report is.
|
|
47
|
+
*/
|
|
48
|
+
initial?: boolean;
|
|
49
|
+
}
|
|
50
|
+
export interface FingerprintOptions {
|
|
51
|
+
/** Table name. Validated as an identifier, since it is interpolated. */
|
|
52
|
+
tableName?: string;
|
|
53
|
+
}
|
|
54
|
+
export interface PublishIfChangedResult {
|
|
55
|
+
published: boolean;
|
|
56
|
+
fingerprint: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Call `publish` when `payload` differs from the last one recorded for its aggregate and key,
|
|
60
|
+
* and record it — on the caller's transaction (see the module's notes).
|
|
61
|
+
*
|
|
62
|
+
* ```ts
|
|
63
|
+
* await withTransaction(async (tx) => {
|
|
64
|
+
* const report = await measure(tx);
|
|
65
|
+
* await publishIfChanged(tx.query, { aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
|
|
66
|
+
* () => recordEvent(tx, { type: 'usage.reported', payload: report, ... }));
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function publishIfChanged(querier: Querier, input: PublishIfChangedInput, publish: () => unknown, options?: FingerprintOptions): Promise<PublishIfChangedResult>;
|
|
71
|
+
export interface AppendIfChangedOptions extends Pick<PublishIfChangedInput, 'key' | 'ignore' | 'initial'> {
|
|
72
|
+
/** The outbox table ({@link appendToOutbox}'s `tableName`). */
|
|
73
|
+
tableName?: string;
|
|
74
|
+
/** The fingerprints table ({@link FingerprintOptions.tableName}). */
|
|
75
|
+
fingerprintTableName?: string;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* {@link appendToOutbox} when the event's payload differs from the last one appended for its
|
|
79
|
+
* aggregate and `key` — {@link publishIfChanged} over this package's outbox.
|
|
80
|
+
*/
|
|
81
|
+
export declare function appendToOutboxIfChanged(querier: Querier, event: AppendOutboxInput, options?: AppendIfChangedOptions): Promise<PublishIfChangedResult>;
|
|
82
|
+
//# sourceMappingURL=fingerprints.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AG,QAAQ,GAAG,SAAS,CAAC;IACvG,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qEAAqE;IACrE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,iBAAiB,EACxB,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,sBAAsB,CAAC,CAejC"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @venturekit/data — publish on change.
|
|
3
|
+
*
|
|
4
|
+
* A fact a service measures on a schedule — a tenant's month of usage, a readiness report
|
|
5
|
+
* recomputed every five minutes — is worth an event only when it says something new. Without
|
|
6
|
+
* a place to keep "what did we last say", every product grows its own: a hash column on a
|
|
7
|
+
* projection row here, a table keyed by month there, each comparing by hand, each with its own
|
|
8
|
+
* idea of what the payload's timestamp does to the comparison.
|
|
9
|
+
*
|
|
10
|
+
* {@link publishIfChanged} keeps one fingerprint per aggregate and key in
|
|
11
|
+
* `vk_outbox_fingerprints` (`0000_vk_data_outbox_fingerprints.sql`) and calls `publish` only
|
|
12
|
+
* when the payload's differs from the one last recorded. {@link appendToOutboxIfChanged} is the
|
|
13
|
+
* same over this package's own outbox.
|
|
14
|
+
*
|
|
15
|
+
* ### One transaction, record first
|
|
16
|
+
*
|
|
17
|
+
* The fingerprint is written with `INSERT … ON CONFLICT … DO UPDATE … WHERE … IS DISTINCT FROM
|
|
18
|
+
* … RETURNING`, which takes the row's lock until the transaction ends. A second pass for the
|
|
19
|
+
* same key running concurrently waits on it, then finds the fingerprint the first one committed
|
|
20
|
+
* and publishes nothing — the same change goes out once. That is why the record comes before
|
|
21
|
+
* `publish`, and why `querier` must be the transaction's: on the pool, a `publish` that failed
|
|
22
|
+
* would leave a change recorded and never sent. A `publish` that throws rolls both back.
|
|
23
|
+
*/
|
|
24
|
+
import { createHash } from 'node:crypto';
|
|
25
|
+
import { assertSqlIdentifier } from '../internal/identifier.js';
|
|
26
|
+
import { appendToOutbox } from './postgres.js';
|
|
27
|
+
/** Default table name, created by `0000_vk_data_outbox_fingerprints.sql`. */
|
|
28
|
+
export const DEFAULT_FINGERPRINT_TABLE = 'vk_outbox_fingerprints';
|
|
29
|
+
/** Object keys in order at every depth, so two payloads that say the same thing hash the same however they were built. */
|
|
30
|
+
function canonical(value) {
|
|
31
|
+
if (value !== null && typeof value === 'object' && typeof value.toJSON === 'function') {
|
|
32
|
+
return canonical(value.toJSON());
|
|
33
|
+
}
|
|
34
|
+
if (Array.isArray(value))
|
|
35
|
+
return value.map(canonical);
|
|
36
|
+
if (value !== null && typeof value === 'object') {
|
|
37
|
+
const source = value;
|
|
38
|
+
return Object.fromEntries(Object.keys(source).sort().map((k) => [k, canonical(source[k])]));
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* What a payload says, as a sha-256 hex digest of its canonical JSON. `ignore` names top-level
|
|
44
|
+
* fields left out — the instant a report was made, which changes on every pass and says nothing.
|
|
45
|
+
*/
|
|
46
|
+
export function payloadFingerprint(payload, ignore = []) {
|
|
47
|
+
let said = payload;
|
|
48
|
+
if (ignore.length > 0 && payload !== null && typeof payload === 'object' && !Array.isArray(payload)) {
|
|
49
|
+
said = Object.fromEntries(Object.entries(payload).filter(([k]) => !ignore.includes(k)));
|
|
50
|
+
}
|
|
51
|
+
return createHash('sha256').update(JSON.stringify(canonical(said)) ?? 'undefined').digest('hex');
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Call `publish` when `payload` differs from the last one recorded for its aggregate and key,
|
|
55
|
+
* and record it — on the caller's transaction (see the module's notes).
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* await withTransaction(async (tx) => {
|
|
59
|
+
* const report = await measure(tx);
|
|
60
|
+
* await publishIfChanged(tx.query, { aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
|
|
61
|
+
* () => recordEvent(tx, { type: 'usage.reported', payload: report, ... }));
|
|
62
|
+
* });
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export async function publishIfChanged(querier, input, publish, options = {}) {
|
|
66
|
+
const table = options.tableName ?? DEFAULT_FINGERPRINT_TABLE;
|
|
67
|
+
assertSqlIdentifier(table, 'publishIfChanged.tableName');
|
|
68
|
+
const fingerprint = payloadFingerprint(input.payload, input.ignore);
|
|
69
|
+
const key = input.key ?? '';
|
|
70
|
+
const changed = input.initial === false
|
|
71
|
+
? await querier(`UPDATE ${table} SET fingerprint = $4, published_at = now()
|
|
72
|
+
WHERE aggregate_type = $1 AND aggregate_id = $2 AND key = $3 AND fingerprint IS DISTINCT FROM $4
|
|
73
|
+
RETURNING 1 AS changed`, [input.aggregateType, input.aggregateId, key, fingerprint])
|
|
74
|
+
: await querier(`INSERT INTO ${table} (aggregate_type, aggregate_id, key, tenant_id, fingerprint)
|
|
75
|
+
VALUES ($1, $2, $3, $4, $5)
|
|
76
|
+
ON CONFLICT (aggregate_type, aggregate_id, key) DO UPDATE
|
|
77
|
+
SET fingerprint = EXCLUDED.fingerprint, tenant_id = EXCLUDED.tenant_id, published_at = now()
|
|
78
|
+
WHERE ${table}.fingerprint IS DISTINCT FROM EXCLUDED.fingerprint
|
|
79
|
+
RETURNING 1 AS changed`, [input.aggregateType, input.aggregateId, key, input.tenantId ?? null, fingerprint]);
|
|
80
|
+
if (changed.length === 0)
|
|
81
|
+
return { published: false, fingerprint };
|
|
82
|
+
await publish();
|
|
83
|
+
return { published: true, fingerprint };
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* {@link appendToOutbox} when the event's payload differs from the last one appended for its
|
|
87
|
+
* aggregate and `key` — {@link publishIfChanged} over this package's outbox.
|
|
88
|
+
*/
|
|
89
|
+
export async function appendToOutboxIfChanged(querier, event, options = {}) {
|
|
90
|
+
return publishIfChanged(querier, {
|
|
91
|
+
aggregateType: event.aggregateType,
|
|
92
|
+
aggregateId: event.aggregateId,
|
|
93
|
+
key: options.key,
|
|
94
|
+
tenantId: event.tenantId,
|
|
95
|
+
payload: event.payload,
|
|
96
|
+
ignore: options.ignore,
|
|
97
|
+
initial: options.initial,
|
|
98
|
+
}, () => appendToOutbox(querier, event, { tableName: options.tableName }), { tableName: options.fingerprintTableName });
|
|
99
|
+
}
|
|
100
|
+
//# sourceMappingURL=fingerprints.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fingerprints.js","sourceRoot":"","sources":["../../src/outbox/fingerprints.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAG/C,6EAA6E;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;AAElE,0HAA0H;AAC1H,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAQ,KAA8B,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAChH,OAAO,SAAS,CAAE,KAAmC,CAAC,MAAM,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACtD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,KAAgC,CAAC;QAChD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAA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gres outbox store.
|
|
3
3
|
*
|
|
4
4
|
* The storage half of `@venturekit/runtime/patterns`' transactional outbox. See
|
|
5
|
-
* `./postgres.ts`.
|
|
5
|
+
* `./postgres.ts`; publish-on-change is `./fingerprints.ts`.
|
|
6
6
|
*/
|
|
7
7
|
export { createPostgresOutboxStore, appendToOutbox, discardOutboxEvent, DEFAULT_OUTBOX_TABLE, } from './postgres.js';
|
|
8
8
|
export type { EventActor, OutboxRow, OutboxFailure, AppendOutboxInput, PostgresOutboxStore, PostgresOutboxStoreOptions, } from './postgres.js';
|
|
9
|
+
export { publishIfChanged, appendToOutboxIfChanged, payloadFingerprint, DEFAULT_FINGERPRINT_TABLE, } from './fingerprints.js';
|
|
10
|
+
export type { PublishIfChangedInput, PublishIfChangedResult, FingerprintOptions, AppendIfChangedOptions, } from './fingerprints.js';
|
|
9
11
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAE3B,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC"}
|
package/dist/outbox/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* @venturekit/data — Postgres outbox store.
|
|
3
3
|
*
|
|
4
4
|
* The storage half of `@venturekit/runtime/patterns`' transactional outbox. See
|
|
5
|
-
* `./postgres.ts`.
|
|
5
|
+
* `./postgres.ts`; publish-on-change is `./fingerprints.ts`.
|
|
6
6
|
*/
|
|
7
7
|
export { createPostgresOutboxStore, appendToOutbox, discardOutboxEvent, DEFAULT_OUTBOX_TABLE, } from './postgres.js';
|
|
8
|
+
export { publishIfChanged, appendToOutboxIfChanged, payloadFingerprint, DEFAULT_FINGERPRINT_TABLE, } from './fingerprints.js';
|
|
8
9
|
//# sourceMappingURL=index.js.map
|
package/dist/outbox/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAWvB,OAAO,EACL,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC"}
|
package/dist/query/index.d.ts
CHANGED
|
@@ -56,7 +56,7 @@ import type { ResultsMapper } from './transaction.js';
|
|
|
56
56
|
export declare const DEFAULT_SLOW_QUERY_THRESHOLD_MS = 1000;
|
|
57
57
|
export { getPool, applyDatabaseUrlToEnv } from './pool.js';
|
|
58
58
|
export { applyDbSecretToEnv } from './secret.js';
|
|
59
|
-
export { TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, runWithTenant, runWithTenantScope, runWithoutTenant, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './tenant.js';
|
|
59
|
+
export { TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, DATABASE_LOGIN_ENV, databaseLogin, PlatformScopeUnavailableError, withDatabaseLogin, runWithTenant, runWithTenantScope, runWithoutTenant, runAsPlatform, isPlatformScope, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './tenant.js';
|
|
60
60
|
export { mapResults, mapRow, configureMapper, getMapperConfig, } from './mapper.js';
|
|
61
61
|
export type { MapperOptions } from './mapper.js';
|
|
62
62
|
export { beginTransaction, withTransaction, buildTransaction, } from './transaction.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/query/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AAIH,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAKtD;;;;;;GAMG;AACH,eAAO,MAAM,+BAA+B,OAAQ,CAAC;AAqBrD,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,UAAU,EACV,M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AAC;AACrB,OAAO,EACL,UAAU,EACV,MAAM,EACN,eAAe,EACf,eAAe,GAChB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AA+B5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAsB,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACvD,QAAQ,EAAE,MAAM,EAChB,WAAW,CAAC,EAAE,OAAO,EAAE,EACvB,aAAa,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,EAChC,aAAa,CAAC,EAAE,aAAa,GAC5B,OAAO,CAAC,CAAC,CAAC,CA6CZ"}
|
package/dist/query/index.js
CHANGED
|
@@ -77,7 +77,7 @@ function previewSql(sql) {
|
|
|
77
77
|
}
|
|
78
78
|
export { getPool, applyDatabaseUrlToEnv } from './pool.js';
|
|
79
79
|
export { applyDbSecretToEnv } from './secret.js';
|
|
80
|
-
export { TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, runWithTenant, runWithTenantScope, runWithoutTenant, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './tenant.js';
|
|
80
|
+
export { TENANT_GUC, TENANT_SCOPE_GUC, TENANT_ROLE_ENV, tenantRole, DATABASE_LOGIN_ENV, databaseLogin, PlatformScopeUnavailableError, withDatabaseLogin, runWithTenant, runWithTenantScope, runWithoutTenant, runAsPlatform, isPlatformScope, getCurrentTenantId, getCurrentTenantScope, isTenancyEngaged, } from './tenant.js';
|
|
81
81
|
export { mapResults, mapRow, configureMapper, getMapperConfig, } from './mapper.js';
|
|
82
82
|
export { beginTransaction, withTransaction, buildTransaction, } from './transaction.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AK,CAAC,IAAI,CAAC,qBAAqB,EAAE;YAChC,UAAU;YACV,WAAW,EAAE,MAAM;YACnB,QAAQ,EAAE,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM;YACzC,UAAU,EAAE,UAAU,CAAC,QAAQ,CAAC;SACjC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;IACnD,OAAO,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAsB,CAAC;AACxE,CAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which login the current invocation runs as, when one process hosts
|
|
3
|
+
* functions of both kinds — `vk dev`, which serves every route, cron and
|
|
4
|
+
* WebSocket handler in a single process. A deployed function has exactly
|
|
5
|
+
* one login (`DB_LOGIN`, its own secret) and never needs this.
|
|
6
|
+
*
|
|
7
|
+
* The store lives on `globalThis` so the CLI's copy of this package and
|
|
8
|
+
* the project's own copy (two module instances in one `vk dev` process)
|
|
9
|
+
* see the same value.
|
|
10
|
+
*/
|
|
11
|
+
export type DatabaseLoginKind = 'app' | 'system';
|
|
12
|
+
/** Run `fn` as the given login (its pool, and its `runAsPlatform` rule). */
|
|
13
|
+
export declare function withDatabaseLogin<T>(kind: DatabaseLoginKind, fn: () => Promise<T>): Promise<T>;
|
|
14
|
+
/** The login set by {@link withDatabaseLogin} for this invocation, if any. */
|
|
15
|
+
export declare function databaseLoginOverride(): DatabaseLoginKind | undefined;
|
|
16
|
+
//# sourceMappingURL=login.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../src/query/login.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG,QAAQ,CAAC;AAMjD,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAE9F;AAED,8EAA8E;AAC9E,wBAAgB,qBAAqB,IAAI,iBAAiB,GAAG,SAAS,CAErE"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which login the current invocation runs as, when one process hosts
|
|
3
|
+
* functions of both kinds — `vk dev`, which serves every route, cron and
|
|
4
|
+
* WebSocket handler in a single process. A deployed function has exactly
|
|
5
|
+
* one login (`DB_LOGIN`, its own secret) and never needs this.
|
|
6
|
+
*
|
|
7
|
+
* The store lives on `globalThis` so the CLI's copy of this package and
|
|
8
|
+
* the project's own copy (two module instances in one `vk dev` process)
|
|
9
|
+
* see the same value.
|
|
10
|
+
*/
|
|
11
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
12
|
+
const KEY = Symbol.for('venturekit.data.login');
|
|
13
|
+
const store = (globalThis[KEY] ??=
|
|
14
|
+
new AsyncLocalStorage());
|
|
15
|
+
/** Run `fn` as the given login (its pool, and its `runAsPlatform` rule). */
|
|
16
|
+
export function withDatabaseLogin(kind, fn) {
|
|
17
|
+
return store.run(kind, fn);
|
|
18
|
+
}
|
|
19
|
+
/** The login set by {@link withDatabaseLogin} for this invocation, if any. */
|
|
20
|
+
export function databaseLoginOverride() {
|
|
21
|
+
return store.getStore();
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=login.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"login.js","sourceRoot":"","sources":["../../src/query/login.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAIrD,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;AAChD,MAAM,KAAK,GAAyC,CAAE,UAAsC,CAAC,GAAG,CAAC;IAC/F,IAAI,iBAAiB,EAAqB,CAAyC,CAAC;AAEtF,4EAA4E;AAC5E,MAAM,UAAU,iBAAiB,CAAI,IAAuB,EAAE,EAAoB;IAChF,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,qBAAqB;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AAC1B,CAAC"}
|
package/dist/query/pool.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.d.ts","sourceRoot":"","sources":["../../src/query/pool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;
|
|
1
|
+
{"version":3,"file":"pool.d.ts","sourceRoot":"","sources":["../../src/query/pool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,IAAI,EAAE,KAAK,UAAU,EAAE,MAAM,IAAI,CAAC;AAM3C;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAShD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAE1C;;;;GAIG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAK9C;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kCAAkC,QAAS,CAAC;AAEzD;;;GAGG;AACH,wBAAgB,8BAA8B,IAAI,MAAM,CAKvD;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,KAAK,CAAC;AAEnC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,uBAAuB,IAAI,CAAC;AAEzC;;;GAGG;AACH,wBAAgB,cAAc,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAO3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,IAAI,IAAI,CAoC5C;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAG3D;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,GAAG,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC;IACvB,IAAI,EAAE,KAAK,GAAG,UAAU,GAAG,oBAAoB,GAAG,qBAAqB,GAAG,oBAAoB,CAAC;CAChG,CAAC;AAEF,8DAA8D;AAC9D,wBAAgB,UAAU,IAAI,WAAW,CA8CxC;AASD,wBAAgB,OAAO,IAAI,IAAI,CAgB9B"}
|
package/dist/query/pool.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* surfaces as a clean `pg` error long before the Lambda is killed
|
|
25
25
|
* with no logs.
|
|
26
26
|
*/
|
|
27
|
+
import { databaseLoginOverride } from './login.js';
|
|
27
28
|
import { Pool } from 'pg';
|
|
28
29
|
import { dbLog } from '../internal/logger.js';
|
|
29
30
|
import { RDS_GLOBAL_CA_PEM } from '../internal/rds-global-ca.js';
|
|
@@ -233,7 +234,30 @@ export function resolveSsl() {
|
|
|
233
234
|
}
|
|
234
235
|
return { ssl: { rejectUnauthorized: true }, mode: 'verified-system-ca' };
|
|
235
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* The second pool `vk dev` keeps for system-login invocations
|
|
239
|
+
* (`withDatabaseLogin('system', …)`, `DB_SYSTEM_USER` / `DB_SYSTEM_PASSWORD`).
|
|
240
|
+
* A deployed function has one login and one pool.
|
|
241
|
+
*/
|
|
242
|
+
let systemPool = null;
|
|
236
243
|
export function getPool() {
|
|
244
|
+
if (databaseLoginOverride() === 'system' && process.env.DB_SYSTEM_USER && process.env.DB_SYSTEM_PASSWORD) {
|
|
245
|
+
if (!systemPool) {
|
|
246
|
+
const base = getAppPool();
|
|
247
|
+
systemPool = new Pool({
|
|
248
|
+
...base.options,
|
|
249
|
+
user: process.env.DB_SYSTEM_USER,
|
|
250
|
+
password: process.env.DB_SYSTEM_PASSWORD,
|
|
251
|
+
});
|
|
252
|
+
systemPool.on('error', (err) => {
|
|
253
|
+
dbLog.error('Postgres system pool emitted error event', { errorName: err.name, errorMessage: err.message });
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return systemPool;
|
|
257
|
+
}
|
|
258
|
+
return getAppPool();
|
|
259
|
+
}
|
|
260
|
+
function getAppPool() {
|
|
237
261
|
if (!pool) {
|
|
238
262
|
applyDatabaseUrlToEnv();
|
|
239
263
|
const { ssl, mode: sslMode } = resolveSsl();
|
package/dist/query/pool.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.js","sourceRoot":"","sources":["../../src/query/pool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,IAAI,EAAmB,MAAM,IAAI,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,IAAI,IAAI,GAAgB,IAAI,CAAC;AAE7B;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,SAAS,0BAA0B;IACjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;IAC9C,IAAI,CAAC,GAAG;QAAE,OAAO,0BAA0B,CAAC;IAC5C,MAAM,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACnC,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,0BAA0B,CAAC;AACvE,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,CAAC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AAG,IAAI,IAAI,CAAC;YACd,IAAI;YACJ,IAAI;YACJ,QAAQ;YACR,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,OAAO;YACzB,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW;YACjC,GAAG;YACH,GAAG;YACH,uBAAuB;YACvB,oEAAoE;YACpE,kEAAkE;YAClE,yDAAyD;YACzD,SAAS,EAAE,IAAI;YACf,2BAA2B;YAC3B,oEAAoE;YACpE,yDAAyD;YACzD,gEAAgE;YAChE,kEAAkE;YAClE,GAAG,CAAC,kBAAkB,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACzE,CAAC,CAAC;QAEH,oEAAoE;QACpE,oEAAoE;QACpE,0DAA0D;QAC1D,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAU,EAAE,EAAE;YAC9B,KAAK,CAAC,KAAK,CAAC,mCAAmC,EAAE;gBAC/C,SAAS,EAAE,GAAG,CAAC,IAAI;gBACnB,YAAY,EAAE,GAAG,CAAC,OAAO;aAC1B,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
|
package/dist/query/tenant.d.ts
CHANGED
|
@@ -187,6 +187,36 @@ export declare function runWithTenantScope<T>(tenantIds: string[], fn: () => Pro
|
|
|
187
187
|
* review.
|
|
188
188
|
*/
|
|
189
189
|
export declare function runWithoutTenant<T>(fn: () => Promise<T>): Promise<T>;
|
|
190
|
+
/**
|
|
191
|
+
* Run `fn` as the PLATFORM: deliberate cross-tenant work — operator
|
|
192
|
+
* consoles, crons sweeping every tenant, sign-ins that look an account up
|
|
193
|
+
* in every tenant, event consumers writing several tenants' rows.
|
|
194
|
+
*
|
|
195
|
+
* Cross-tenant reach is a property of the FUNCTION, not of a code path:
|
|
196
|
+
* VentureKit gives each database two logins, and only the functions listed
|
|
197
|
+
* in `databases[].logins.system.functions` connect as the SYSTEM login
|
|
198
|
+
* (`DB_LOGIN=system`). Every other function connects as the APP login
|
|
199
|
+
* (`DB_LOGIN=app`), which has no role to switch into — so neither a bug nor
|
|
200
|
+
* injected SQL on a request path can widen its reach. Under the system
|
|
201
|
+
* login, statements here run as the login itself with no tenant published;
|
|
202
|
+
* under the app login this rejects with {@link PlatformScopeUnavailableError}.
|
|
203
|
+
*
|
|
204
|
+
* Wrap entry points, not helpers: an operator route's whole request, a
|
|
205
|
+
* cron's whole run. A `runWithTenant` opened inside narrows again. Without
|
|
206
|
+
* `DB_LOGIN` (a local database, an owner login) the scope runs with the
|
|
207
|
+
* connection's own privileges.
|
|
208
|
+
*/
|
|
209
|
+
export declare function runAsPlatform<T>(fn: () => Promise<T>): Promise<T>;
|
|
210
|
+
/** The env var naming which of the database's two logins this process connects as. */
|
|
211
|
+
export declare const DATABASE_LOGIN_ENV = "DB_LOGIN";
|
|
212
|
+
/** `'app'` / `'system'` from `DB_LOGIN`, or `null` when unset (no split configured). */
|
|
213
|
+
export declare function databaseLogin(env?: NodeJS.ProcessEnv | Record<string, string | undefined>): 'app' | 'system' | null;
|
|
214
|
+
/** Thrown by {@link runAsPlatform} in a process connected as the app login. */
|
|
215
|
+
export declare class PlatformScopeUnavailableError extends Error {
|
|
216
|
+
constructor();
|
|
217
|
+
}
|
|
218
|
+
/** True inside a {@link runAsPlatform} scope. */
|
|
219
|
+
export declare function isPlatformScope(): boolean;
|
|
190
220
|
/** The env var naming the role tenant-scoped statements run as. */
|
|
191
221
|
export declare const TENANT_ROLE_ENV = "DB_TENANT_ROLE";
|
|
192
222
|
/**
|
|
@@ -223,4 +253,6 @@ export declare function applyTenantToTransaction(client: PoolClient): Promise<vo
|
|
|
223
253
|
* disengage tenancy once engaged.
|
|
224
254
|
*/
|
|
225
255
|
export declare function __resetTenancyForTests(): void;
|
|
256
|
+
export { withDatabaseLogin } from './login.js';
|
|
257
|
+
export type { DatabaseLoginKind } from './login.js';
|
|
226
258
|
//# sourceMappingURL=tenant.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../../src/query/tenant.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4GG;
|
|
1
|
+
{"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../../src/query/tenant.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4GG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAErC;;;;GAIG;AACH,eAAO,MAAM,UAAU,kBAAkB,CAAC;AAE1C;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,mBAAmB,CAAC;AA+CjD,6DAA6D;AAC7D,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,IAAI,CAElD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,EAAE,CAEhD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CASnF;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA2B3F;AAED;;;;;;;;;;;;GA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|
|
|
107
107
|
* module stays dormant until the first call, and `query()` keeps using
|
|
108
108
|
* `pool.query()` directly with no added statements.
|
|
109
109
|
*/
|
|
110
|
+
import { databaseLoginOverride } from './login.js';
|
|
110
111
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
111
112
|
/**
|
|
112
113
|
* The GUC that carries the current tenant into Postgres. `app.` is a
|
|
@@ -253,6 +254,55 @@ export function runWithoutTenant(fn) {
|
|
|
253
254
|
engaged = true;
|
|
254
255
|
return storage.run({ tenantId: null, tenantIds: [] }, fn);
|
|
255
256
|
}
|
|
257
|
+
/**
|
|
258
|
+
* Run `fn` as the PLATFORM: deliberate cross-tenant work — operator
|
|
259
|
+
* consoles, crons sweeping every tenant, sign-ins that look an account up
|
|
260
|
+
* in every tenant, event consumers writing several tenants' rows.
|
|
261
|
+
*
|
|
262
|
+
* Cross-tenant reach is a property of the FUNCTION, not of a code path:
|
|
263
|
+
* VentureKit gives each database two logins, and only the functions listed
|
|
264
|
+
* in `databases[].logins.system.functions` connect as the SYSTEM login
|
|
265
|
+
* (`DB_LOGIN=system`). Every other function connects as the APP login
|
|
266
|
+
* (`DB_LOGIN=app`), which has no role to switch into — so neither a bug nor
|
|
267
|
+
* injected SQL on a request path can widen its reach. Under the system
|
|
268
|
+
* login, statements here run as the login itself with no tenant published;
|
|
269
|
+
* under the app login this rejects with {@link PlatformScopeUnavailableError}.
|
|
270
|
+
*
|
|
271
|
+
* Wrap entry points, not helpers: an operator route's whole request, a
|
|
272
|
+
* cron's whole run. A `runWithTenant` opened inside narrows again. Without
|
|
273
|
+
* `DB_LOGIN` (a local database, an owner login) the scope runs with the
|
|
274
|
+
* connection's own privileges.
|
|
275
|
+
*/
|
|
276
|
+
export function runAsPlatform(fn) {
|
|
277
|
+
if (databaseLogin() === 'app')
|
|
278
|
+
return Promise.reject(new PlatformScopeUnavailableError());
|
|
279
|
+
engaged = true;
|
|
280
|
+
return storage.run({ tenantId: null, tenantIds: [], platform: true }, fn);
|
|
281
|
+
}
|
|
282
|
+
/** The env var naming which of the database's two logins this process connects as. */
|
|
283
|
+
export const DATABASE_LOGIN_ENV = 'DB_LOGIN';
|
|
284
|
+
/** `'app'` / `'system'` from `DB_LOGIN`, or `null` when unset (no split configured). */
|
|
285
|
+
export function databaseLogin(env = process.env) {
|
|
286
|
+
const raw = (env === process.env ? databaseLoginOverride() : undefined) ?? env[DATABASE_LOGIN_ENV]?.trim();
|
|
287
|
+
if (!raw)
|
|
288
|
+
return null;
|
|
289
|
+
if (raw !== 'app' && raw !== 'system') {
|
|
290
|
+
throw new Error(`[@venturekit/data] ${DATABASE_LOGIN_ENV}=${JSON.stringify(raw)} must be 'app' or 'system'.`);
|
|
291
|
+
}
|
|
292
|
+
return raw;
|
|
293
|
+
}
|
|
294
|
+
/** Thrown by {@link runAsPlatform} in a process connected as the app login. */
|
|
295
|
+
export class PlatformScopeUnavailableError extends Error {
|
|
296
|
+
constructor() {
|
|
297
|
+
super('[@venturekit/data] runAsPlatform: this function connects as the APP login, which cannot reach other ' +
|
|
298
|
+
'tenants. List it in databases[].logins.system.functions (vk.config.ts) to give it the system login.');
|
|
299
|
+
this.name = 'PlatformScopeUnavailableError';
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/** True inside a {@link runAsPlatform} scope. */
|
|
303
|
+
export function isPlatformScope() {
|
|
304
|
+
return storage.getStore()?.platform === true;
|
|
305
|
+
}
|
|
256
306
|
/**
|
|
257
307
|
* The pair of values to publish for the current scope. Both are written
|
|
258
308
|
* together so a connection can never carry one request's acting tenant
|
|
@@ -280,37 +330,39 @@ const ROLE_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
|
280
330
|
* a reconfigured process is honoured without a restart.
|
|
281
331
|
*/
|
|
282
332
|
export function tenantRole(env = process.env) {
|
|
283
|
-
|
|
333
|
+
return roleFromEnv(TENANT_ROLE_ENV, env);
|
|
334
|
+
}
|
|
335
|
+
function roleFromEnv(name, env) {
|
|
336
|
+
const raw = env[name]?.trim();
|
|
284
337
|
if (!raw)
|
|
285
338
|
return null;
|
|
286
339
|
if (!ROLE_NAME.test(raw)) {
|
|
287
|
-
throw new Error(`[@venturekit/data] ${
|
|
340
|
+
throw new Error(`[@venturekit/data] ${name}=${JSON.stringify(raw)} is not a plain Postgres role name ` +
|
|
288
341
|
`(lowercase letters, digits and underscores, not starting with a digit).`);
|
|
289
342
|
}
|
|
290
343
|
return raw;
|
|
291
344
|
}
|
|
292
345
|
/**
|
|
293
|
-
* Which role the current scope runs as
|
|
294
|
-
*
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
* when the feature is off.
|
|
346
|
+
* Which role the current scope runs as — `undefined` when `DB_TENANT_ROLE`
|
|
347
|
+
* is unset (no role statements at all), otherwise the tenant role inside a
|
|
348
|
+
* tenant scope ({@link runWithTenant} / {@link runWithTenantScope}) and
|
|
349
|
+
* `null` — the login itself, with the GUC empty — everywhere else. The app
|
|
350
|
+
* login has no role to switch into besides the tenant role, so returning to
|
|
351
|
+
* the login never widens its reach.
|
|
300
352
|
*/
|
|
301
353
|
function currentRole() {
|
|
302
|
-
const
|
|
303
|
-
if (!
|
|
304
|
-
return
|
|
305
|
-
return
|
|
354
|
+
const tenant = tenantRole();
|
|
355
|
+
if (!tenant)
|
|
356
|
+
return undefined;
|
|
357
|
+
return getCurrentTenantId() !== null ? tenant : null;
|
|
306
358
|
}
|
|
307
359
|
/** `SET [LOCAL] ROLE …` / `… ROLE NONE` for the current scope, or `null` when roles are not in play. */
|
|
308
360
|
function roleStatement(local) {
|
|
309
|
-
const
|
|
310
|
-
if (
|
|
361
|
+
const role = currentRole();
|
|
362
|
+
if (role === undefined)
|
|
311
363
|
return null;
|
|
312
364
|
const kw = local ? 'SET LOCAL ROLE' : 'SET ROLE';
|
|
313
|
-
return
|
|
365
|
+
return role ? `${kw} "${role}"` : `${kw} NONE`;
|
|
314
366
|
}
|
|
315
367
|
/**
|
|
316
368
|
* Last value applied to each physical connection.
|
|
@@ -398,4 +450,5 @@ export async function applyTenantToTransaction(client) {
|
|
|
398
450
|
export function __resetTenancyForTests() {
|
|
399
451
|
engaged = false;
|
|
400
452
|
}
|
|
453
|
+
export { withDatabaseLogin } from './login.js';
|
|
401
454
|
//# sourceMappingURL=tenant.js.map
|
package/dist/query/tenant.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tenant.js","sourceRoot":"","sources":["../../src/query/tenant.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4GG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAEjD;;;;GAIG;AACH,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B;;;;;;GAMG;AACH,MAAM,SAAS,GAAG,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"tenant.js","sourceRoot":"","sources":["../../src/query/tenant.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4GG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,eAAe,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAEjD;;;;GAIG;AACH,MA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,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venturekit/data",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.51",
|
|
4
4
|
"description": "Database and data layer for VentureKit",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@aws-sdk/client-secrets-manager": "^3.1126.0",
|
|
61
|
-
"@venturekit/core": "0.0.
|
|
61
|
+
"@venturekit/core": "0.0.51",
|
|
62
62
|
"pg": "^8.12.0"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
-- @venturekit/data — publish on change.
|
|
2
|
+
--
|
|
3
|
+
-- Table created by this migration:
|
|
4
|
+
-- vk_outbox_fingerprints — the fingerprint of the last payload published, per aggregate and key
|
|
5
|
+
--
|
|
6
|
+
-- Backs `publishIfChanged()` / `appendToOutboxIfChanged()` (`src/outbox/fingerprints.ts`). A
|
|
7
|
+
-- fact a service measures on a schedule — a month's usage, a readiness report — is worth an
|
|
8
|
+
-- event only when it says something new; this is where "what did we last say" is kept, so the
|
|
9
|
+
-- comparison and the event commit in the same transaction.
|
|
10
|
+
--
|
|
11
|
+
-- # Why the `0000_` filename prefix
|
|
12
|
+
--
|
|
13
|
+
-- A tenant-scoped product guards this table from its own migrations — a foreign key to its
|
|
14
|
+
-- tenants, `vk_install_tenant_guards()` — exactly as it does `vk_push_devices`, and for the
|
|
15
|
+
-- same reason `0000_vk_notify_push_devices.sql` takes the prefix: the runner applies every
|
|
16
|
+
-- directory's files in name order, so a `vk_data_006_*` name would sort after the consumer's
|
|
17
|
+
-- `0xxx_*` file that alters it. Sorting after `0000_vk_data_foundation.sql` is incidental;
|
|
18
|
+
-- nothing here calls its functions.
|
|
19
|
+
--
|
|
20
|
+
-- Additive: one new table, no existing file edited, and nothing writes to it until a project
|
|
21
|
+
-- calls `publishIfChanged()`. No RLS policy is installed — `vk_install_tenant_guards()` needs
|
|
22
|
+
-- your application role; call it if you scope by `tenant_id`.
|
|
23
|
+
|
|
24
|
+
CREATE TABLE IF NOT EXISTS vk_outbox_fingerprints (
|
|
25
|
+
aggregate_type text NOT NULL,
|
|
26
|
+
aggregate_id text NOT NULL,
|
|
27
|
+
-- What is compared within the aggregate — a month, a report kind. '' when it has one.
|
|
28
|
+
key text NOT NULL DEFAULT '',
|
|
29
|
+
-- NULL for platform-global facts. Not part of the key: aggregate ids are unique on their own,
|
|
30
|
+
-- and this is the column a tenant guard reads.
|
|
31
|
+
tenant_id uuid,
|
|
32
|
+
-- sha-256 (hex) of the payload's canonical JSON, the fields named in `ignore` left out.
|
|
33
|
+
fingerprint text NOT NULL,
|
|
34
|
+
published_at timestamptz NOT NULL DEFAULT now(),
|
|
35
|
+
PRIMARY KEY (aggregate_type, aggregate_id, key)
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
COMMENT ON TABLE vk_outbox_fingerprints IS
|
|
39
|
+
'The fingerprint of the last payload published per aggregate and key. publishIfChanged() publishes only when it differs, in the caller''s transaction.';
|