shutro 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/dist/audit/index.d.ts +59 -0
- package/dist/audit/index.js +96 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +164 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +49 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +84 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +249 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +468 -0
- package/dist/core/env/env.js +916 -0
- package/dist/core/env/identity.d.ts +43 -0
- package/dist/core/env/identity.js +65 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +256 -0
- package/dist/core/errors.js +360 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +51 -0
- package/dist/core/index.js +42 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +479 -0
- package/dist/core/model/field.js +461 -0
- package/dist/core/model/generated.d.ts +77 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +387 -0
- package/dist/core/model/model.js +566 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +68 -0
- package/dist/core/money/fx.js +124 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +33 -0
- package/dist/core/recordset/audit.js +262 -0
- package/dist/core/recordset/compute.d.ts +36 -0
- package/dist/core/recordset/compute.js +414 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +31 -0
- package/dist/core/recordset/domain.js +300 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +240 -0
- package/dist/core/recordset/recordset.d.ts +110 -0
- package/dist/core/recordset/recordset.js +789 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +56 -0
- package/dist/core/recordset/security.js +269 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +80 -0
- package/dist/core/recordset/types.d.ts +415 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +33 -0
- package/dist/core/recordset/values.js +177 -0
- package/dist/core/recordset/writes.d.ts +42 -0
- package/dist/core/recordset/writes.js +786 -0
- package/dist/core/registry/ddl.d.ts +31 -0
- package/dist/core/registry/ddl.js +174 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +89 -0
- package/dist/core/registry/module.js +98 -0
- package/dist/core/registry/registry.d.ts +130 -0
- package/dist/core/registry/registry.js +591 -0
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +88 -0
- package/dist/driver-pg/driver.js +177 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +233 -0
- package/dist/security/index.d.ts +147 -0
- package/dist/security/index.js +278 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +47 -0
- package/dist/sql/tag.js +123 -0
- package/package.json +82 -4
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime security (RFC 0014 §7.10): roles, model access, record rules and feature-permission grants stored in the
|
|
3
|
+
* database and edited while the system runs. Code declarations are the reviewed baseline; the database extends it
|
|
4
|
+
* (it never removes a grant the code makes). Every change is validated against the registry when saved, audited,
|
|
5
|
+
* and announced with NOTIFY so every process reloads.
|
|
6
|
+
*/
|
|
7
|
+
import type { Driver } from '../../driver-pg/index.js';
|
|
8
|
+
import { type FieldGroups, type Perm, type RulePerm, type RuleSpec } from '../../security/index.js';
|
|
9
|
+
import { compile } from '../../sql/index.js';
|
|
10
|
+
import type { Registry } from '../registry/registry.js';
|
|
11
|
+
/** The NOTIFY channel runtime security changes are announced on. */
|
|
12
|
+
export declare const SECURITY_CHANNEL = "shutro_security";
|
|
13
|
+
/** A role defined at runtime. */
|
|
14
|
+
export interface RuntimeRole {
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly label: string;
|
|
17
|
+
readonly implies: readonly string[];
|
|
18
|
+
readonly administrator: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** A record rule defined at runtime, for one role. */
|
|
21
|
+
export interface RuntimeRule {
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly role: string;
|
|
24
|
+
readonly model: string;
|
|
25
|
+
readonly perms: readonly RulePerm[];
|
|
26
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
27
|
+
}
|
|
28
|
+
/** The runtime additions, as loaded. */
|
|
29
|
+
export interface RuntimeSecurity {
|
|
30
|
+
readonly roles: ReadonlyMap<string, RuntimeRole>;
|
|
31
|
+
/** model → role → permissions. */
|
|
32
|
+
readonly access: ReadonlyMap<string, ReadonlyMap<string, ReadonlySet<Perm>>>;
|
|
33
|
+
/** model → rules (as rule specs for that role). */
|
|
34
|
+
readonly rules: ReadonlyMap<string, Readonly<Record<string, RuleSpec>>>;
|
|
35
|
+
/** feature permission → roles granted it. */
|
|
36
|
+
readonly permissions: ReadonlyMap<string, ReadonlySet<string>>;
|
|
37
|
+
/** model → field → the roles that may read / write it (in addition to the field's code groups). */
|
|
38
|
+
readonly fields: ReadonlyMap<string, ReadonlyMap<string, FieldGroups>>;
|
|
39
|
+
}
|
|
40
|
+
/** Statements creating the runtime security tables. */
|
|
41
|
+
export declare function runtimeSecurityStatements(): readonly {
|
|
42
|
+
readonly text: string;
|
|
43
|
+
readonly params: readonly [];
|
|
44
|
+
}[];
|
|
45
|
+
/** Loads the runtime additions (creating the tables on first use). */
|
|
46
|
+
export declare function loadRuntimeSecurity(driver: Pick<Driver, 'query'>): Promise<RuntimeSecurity>;
|
|
47
|
+
/**
|
|
48
|
+
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
49
|
+
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
|
50
|
+
* overlay allows, so administrators can hide or lock a field without code.
|
|
51
|
+
*/
|
|
52
|
+
export declare function effectiveFieldGroups(overlay: RuntimeSecurity | undefined, model: string, field: string, code: FieldGroups): FieldGroups;
|
|
53
|
+
/** The codes (code groups and runtime roles) whose closure includes an administrator group. */
|
|
54
|
+
export declare function administratorCodes(registry: Registry, overlay: RuntimeSecurity | undefined): ReadonlySet<string>;
|
|
55
|
+
/** The closure of `codes` over `implies`, code groups and runtime roles together. */
|
|
56
|
+
export declare function closureWith(registry: Registry, overlay: RuntimeSecurity | undefined, codes: Iterable<string>): Set<string>;
|
|
57
|
+
/** True when the groups include an administrator group, from code or from a runtime role. */
|
|
58
|
+
export declare function isAdministratorWith(registry: Registry, overlay: RuntimeSecurity | undefined, groups: ReadonlySet<string>): boolean;
|
|
59
|
+
/** Validates a change against the registry and the current overlay (RFC 0014 §7.10). @throws {InvalidModuleError} */
|
|
60
|
+
export declare function validateChange(registry: Registry, overlay: RuntimeSecurity, change: SecurityChange): void;
|
|
61
|
+
/** One change to runtime security. */
|
|
62
|
+
export type SecurityChange = {
|
|
63
|
+
readonly kind: 'role';
|
|
64
|
+
readonly code: string;
|
|
65
|
+
readonly label?: string;
|
|
66
|
+
readonly implies?: readonly string[];
|
|
67
|
+
readonly administrator?: boolean;
|
|
68
|
+
} | {
|
|
69
|
+
readonly kind: 'deleteRole';
|
|
70
|
+
readonly code: string;
|
|
71
|
+
} | {
|
|
72
|
+
readonly kind: 'access';
|
|
73
|
+
readonly role: string;
|
|
74
|
+
readonly model: string;
|
|
75
|
+
readonly perms: readonly Perm[];
|
|
76
|
+
} | {
|
|
77
|
+
readonly kind: 'rule';
|
|
78
|
+
readonly name: string;
|
|
79
|
+
readonly role: string;
|
|
80
|
+
readonly model: string;
|
|
81
|
+
readonly perms: readonly RulePerm[];
|
|
82
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
83
|
+
} | {
|
|
84
|
+
readonly kind: 'deleteRule';
|
|
85
|
+
readonly name: string;
|
|
86
|
+
} | {
|
|
87
|
+
readonly kind: 'permission';
|
|
88
|
+
readonly role: string;
|
|
89
|
+
readonly permission: string;
|
|
90
|
+
} | {
|
|
91
|
+
readonly kind: 'revokePermission';
|
|
92
|
+
readonly role: string;
|
|
93
|
+
readonly permission: string;
|
|
94
|
+
} | {
|
|
95
|
+
readonly kind: 'fields';
|
|
96
|
+
readonly model: string;
|
|
97
|
+
readonly field: string;
|
|
98
|
+
readonly read: readonly string[];
|
|
99
|
+
readonly write: readonly string[];
|
|
100
|
+
};
|
|
101
|
+
/** The statement that applies a validated change. */
|
|
102
|
+
export declare function changeStatement(change: SecurityChange): ReturnType<typeof compile>;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { GROUP_CODE, resolvePlaceholders, } from '../../security/index.js';
|
|
2
|
+
import { compile, sql } from '../../sql/index.js';
|
|
3
|
+
import { InvalidModuleError } from '../errors.js';
|
|
4
|
+
import { compileDomain } from '../recordset/domain.js';
|
|
5
|
+
/** The NOTIFY channel runtime security changes are announced on. */
|
|
6
|
+
export const SECURITY_CHANNEL = 'shutro_security';
|
|
7
|
+
const PERMS = ['read', 'write', 'create', 'unlink', 'export', 'import'];
|
|
8
|
+
const RULE_PERMS = ['read', 'write', 'create', 'unlink'];
|
|
9
|
+
const DDL = [
|
|
10
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role" ("code" text PRIMARY KEY, "label" text NOT NULL, "implies" text[] NOT NULL DEFAULT \'{}\', "administrator" boolean NOT NULL DEFAULT false)',
|
|
11
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_access" ("role" text NOT NULL, "model" text NOT NULL, "perms" text[] NOT NULL, PRIMARY KEY ("role", "model"))',
|
|
12
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_rule" ("name" text PRIMARY KEY, "role" text NOT NULL, "model" text NOT NULL, "perms" text[] NOT NULL, "domain" jsonb NOT NULL)',
|
|
13
|
+
'CREATE TABLE IF NOT EXISTS "shutro_role_permission" ("role" text NOT NULL, "permission" text NOT NULL, PRIMARY KEY ("role", "permission"))',
|
|
14
|
+
`CREATE TABLE IF NOT EXISTS "shutro_role_field" ("model" text NOT NULL, "field" text NOT NULL, "read" text[] NOT NULL DEFAULT '{}', "write" text[] NOT NULL DEFAULT '{}', PRIMARY KEY ("model", "field"))`,
|
|
15
|
+
];
|
|
16
|
+
/** Statements creating the runtime security tables. */
|
|
17
|
+
export function runtimeSecurityStatements() {
|
|
18
|
+
return DDL.map((text) => ({ text, params: [] }));
|
|
19
|
+
}
|
|
20
|
+
/** Loads the runtime additions (creating the tables on first use). */
|
|
21
|
+
export async function loadRuntimeSecurity(driver) {
|
|
22
|
+
for (const text of DDL)
|
|
23
|
+
await driver.query({ text, params: [] });
|
|
24
|
+
const roles = await driver.query({
|
|
25
|
+
text: 'SELECT code, label, implies, administrator FROM shutro_role',
|
|
26
|
+
params: [],
|
|
27
|
+
});
|
|
28
|
+
const access = await driver.query({
|
|
29
|
+
text: 'SELECT role, model, perms FROM shutro_role_access',
|
|
30
|
+
params: [],
|
|
31
|
+
});
|
|
32
|
+
const rules = await driver.query({
|
|
33
|
+
text: 'SELECT name, role, model, perms, domain FROM shutro_role_rule ORDER BY name',
|
|
34
|
+
params: [],
|
|
35
|
+
});
|
|
36
|
+
const grants = await driver.query({
|
|
37
|
+
text: 'SELECT role, permission FROM shutro_role_permission',
|
|
38
|
+
params: [],
|
|
39
|
+
});
|
|
40
|
+
const fieldRows = await driver.query({
|
|
41
|
+
text: 'SELECT model, field, read, write FROM shutro_role_field',
|
|
42
|
+
params: [],
|
|
43
|
+
});
|
|
44
|
+
const fieldMap = new Map();
|
|
45
|
+
for (const f of fieldRows) {
|
|
46
|
+
const byField = fieldMap.get(f.model) ?? new Map();
|
|
47
|
+
// Writers can read: when reading is restricted, the roles allowed to write are allowed to read. An empty read
|
|
48
|
+
// list leaves reading open (`{ write: [...] }` makes the field read-only for everyone else).
|
|
49
|
+
const read = Object.freeze(f.read.length === 0 ? [] : [...new Set([...f.read, ...f.write])]);
|
|
50
|
+
byField.set(f.field, Object.freeze({ read, write: Object.freeze([...f.write]) }));
|
|
51
|
+
fieldMap.set(f.model, byField);
|
|
52
|
+
}
|
|
53
|
+
const accessMap = new Map();
|
|
54
|
+
for (const a of access) {
|
|
55
|
+
const byRole = accessMap.get(a.model) ?? new Map();
|
|
56
|
+
byRole.set(a.role, new Set(a.perms));
|
|
57
|
+
accessMap.set(a.model, byRole);
|
|
58
|
+
}
|
|
59
|
+
const ruleMap = new Map();
|
|
60
|
+
for (const r of rules) {
|
|
61
|
+
const byName = ruleMap.get(r.model) ?? {};
|
|
62
|
+
byName[`runtime:${r.name}`] = Object.freeze({
|
|
63
|
+
groups: [r.role],
|
|
64
|
+
perms: r.perms,
|
|
65
|
+
domain: r.domain,
|
|
66
|
+
});
|
|
67
|
+
ruleMap.set(r.model, byName);
|
|
68
|
+
}
|
|
69
|
+
const permissionMap = new Map();
|
|
70
|
+
for (const g of grants)
|
|
71
|
+
permissionMap.set(g.permission, (permissionMap.get(g.permission) ?? new Set()).add(g.role));
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
roles: new Map(roles.map((r) => [r.code, Object.freeze({ ...r, implies: Object.freeze([...r.implies]) })])),
|
|
74
|
+
access: accessMap,
|
|
75
|
+
rules: ruleMap,
|
|
76
|
+
permissions: permissionMap,
|
|
77
|
+
fields: fieldMap,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The groups of a field with the runtime overlay (RFC 0014 §7.10): the code groups plus the roles given in the
|
|
82
|
+
* overlay. A field without code groups that gets runtime roles becomes restricted to them: the one narrowing the
|
|
83
|
+
* overlay allows, so administrators can hide or lock a field without code.
|
|
84
|
+
*/
|
|
85
|
+
export function effectiveFieldGroups(overlay, model, field, code) {
|
|
86
|
+
const extra = overlay?.fields.get(model)?.get(field);
|
|
87
|
+
if (extra === undefined)
|
|
88
|
+
return code;
|
|
89
|
+
const merge = (a, b) => b.length === 0 ? a : Object.freeze([...new Set([...a, ...b])]);
|
|
90
|
+
return Object.freeze({
|
|
91
|
+
read: merge(code.read, extra.read),
|
|
92
|
+
write: merge(code.write, extra.write),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** The codes (code groups and runtime roles) whose closure includes an administrator group. */
|
|
96
|
+
export function administratorCodes(registry, overlay) {
|
|
97
|
+
const codes = [...registry.security.groups.keys(), ...(overlay?.roles.keys() ?? [])];
|
|
98
|
+
return new Set(codes.filter((code) => isAdministratorWith(registry, overlay, closureWith(registry, overlay, [code]))));
|
|
99
|
+
}
|
|
100
|
+
/** The closure of `codes` over `implies`, code groups and runtime roles together. */
|
|
101
|
+
export function closureWith(registry, overlay, codes) {
|
|
102
|
+
if (overlay === undefined || overlay.roles.size === 0)
|
|
103
|
+
return registry.security.closure(codes);
|
|
104
|
+
const out = new Set();
|
|
105
|
+
const stack = [...codes];
|
|
106
|
+
while (stack.length > 0) {
|
|
107
|
+
const code = stack.pop();
|
|
108
|
+
if (out.has(code))
|
|
109
|
+
continue;
|
|
110
|
+
out.add(code);
|
|
111
|
+
for (const implied of registry.security.groups.get(code)?.implies ?? [])
|
|
112
|
+
stack.push(implied);
|
|
113
|
+
for (const implied of overlay.roles.get(code)?.implies ?? [])
|
|
114
|
+
stack.push(implied);
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
/** True when the groups include an administrator group, from code or from a runtime role. */
|
|
119
|
+
export function isAdministratorWith(registry, overlay, groups) {
|
|
120
|
+
if (registry.security.isAdministrator(groups))
|
|
121
|
+
return true;
|
|
122
|
+
for (const role of overlay?.roles.values() ?? [])
|
|
123
|
+
if (role.administrator && groups.has(role.code))
|
|
124
|
+
return true;
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
function invalid(problem, hint) {
|
|
128
|
+
throw new InvalidModuleError(problem, hint);
|
|
129
|
+
}
|
|
130
|
+
function knownRole(registry, overlay, role) {
|
|
131
|
+
if (!registry.security.groups.has(role) && !overlay.roles.has(role))
|
|
132
|
+
invalid(`The role '${role}' does not exist.`, 'Create it with saveRole(), or use a group a module declares.');
|
|
133
|
+
}
|
|
134
|
+
/** Validates a change against the registry and the current overlay (RFC 0014 §7.10). @throws {InvalidModuleError} */
|
|
135
|
+
export function validateChange(registry, overlay, change) {
|
|
136
|
+
switch (change.kind) {
|
|
137
|
+
case 'role': {
|
|
138
|
+
if (!GROUP_CODE.test(change.code))
|
|
139
|
+
invalid(`'${change.code}' is not a role code.`, "Use 'module.name', e.g. 'sale.team_lead'.");
|
|
140
|
+
if (registry.security.groups.has(change.code))
|
|
141
|
+
invalid(`'${change.code}' is declared in code.`, 'Code groups are changed in their module; create a new role instead.');
|
|
142
|
+
for (const code of change.implies ?? [])
|
|
143
|
+
if (code !== change.code)
|
|
144
|
+
knownRole(registry, overlay, code);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
case 'access': {
|
|
148
|
+
knownRole(registry, overlay, change.role);
|
|
149
|
+
if (!registry.has(change.model))
|
|
150
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
151
|
+
for (const p of change.perms)
|
|
152
|
+
if (!PERMS.includes(p))
|
|
153
|
+
invalid(`'${p}' is not a permission.`, `Use ${PERMS.join(', ')}.`);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
case 'rule': {
|
|
157
|
+
knownRole(registry, overlay, change.role);
|
|
158
|
+
if (!registry.has(change.model))
|
|
159
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
160
|
+
if (change.perms.length === 0)
|
|
161
|
+
invalid(`Rule '${change.name}' applies to no operation.`, `Give perms among ${RULE_PERMS.join(', ')}.`);
|
|
162
|
+
for (const p of change.perms)
|
|
163
|
+
if (!RULE_PERMS.includes(p))
|
|
164
|
+
invalid(`'${p}' is not a rule permission.`, `Use ${RULE_PERMS.join(', ')}.`);
|
|
165
|
+
// Compiled now, with placeholder values: a broken domain is refused when saved, not when users hit it.
|
|
166
|
+
const resolved = resolvePlaceholders(change.domain, {
|
|
167
|
+
uid: 0,
|
|
168
|
+
companyId: 0,
|
|
169
|
+
companyIds: [0],
|
|
170
|
+
});
|
|
171
|
+
compileDomain(registry.get(change.model).model, resolved, undefined, (n) => registry.get(n).model);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
case 'deleteRole': {
|
|
175
|
+
for (const [model, byField] of overlay.fields)
|
|
176
|
+
for (const [field, groups] of byField)
|
|
177
|
+
if (groups.read.includes(change.code) || groups.write.includes(change.code))
|
|
178
|
+
invalid(`The role '${change.code}' is used by the field security of ${model}.${field}.`, 'Remove it from that field first (setFieldGroups): deleting it would change who sees the field.');
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
case 'fields': {
|
|
182
|
+
if (!registry.has(change.model))
|
|
183
|
+
invalid(`The model '${change.model}' is not installed.`, 'Check the model name.');
|
|
184
|
+
const field = registry.get(change.model).model.fields[change.field];
|
|
185
|
+
if (field === undefined)
|
|
186
|
+
invalid(`${change.model} has no field '${change.field}'.`, 'Check the field name.');
|
|
187
|
+
if (change.field === 'id')
|
|
188
|
+
invalid('The id field cannot be restricted.', 'Restrict other fields, or the model access.');
|
|
189
|
+
for (const role of [...change.read, ...change.write])
|
|
190
|
+
knownRole(registry, overlay, role);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
case 'permission': {
|
|
194
|
+
knownRole(registry, overlay, change.role);
|
|
195
|
+
if (!registry.security.permissions.has(change.permission))
|
|
196
|
+
invalid(`The permission '${change.permission}' is not declared by any module.`, 'Grant a permission a module declares with definePermission().');
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
default:
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** The statement that applies a validated change. */
|
|
204
|
+
export function changeStatement(change) {
|
|
205
|
+
switch (change.kind) {
|
|
206
|
+
case 'role':
|
|
207
|
+
return compile(sql `INSERT INTO shutro_role (code, label, implies, administrator) VALUES (${change.code}, ${change.label ?? change.code}, ${sql.array([...(change.implies ?? [])], 'text')}, ${change.administrator === true})
|
|
208
|
+
ON CONFLICT (code) DO UPDATE SET label = EXCLUDED.label, implies = EXCLUDED.implies, administrator = EXCLUDED.administrator`);
|
|
209
|
+
case 'deleteRole':
|
|
210
|
+
return compile(sql `WITH a AS (DELETE FROM shutro_role_access WHERE role = ${change.code}), r AS (DELETE FROM shutro_role_rule WHERE role = ${change.code}), p AS (DELETE FROM shutro_role_permission WHERE role = ${change.code})
|
|
211
|
+
DELETE FROM shutro_role WHERE code = ${change.code}`);
|
|
212
|
+
case 'access':
|
|
213
|
+
return change.perms.length === 0
|
|
214
|
+
? compile(sql `DELETE FROM shutro_role_access WHERE role = ${change.role} AND model = ${change.model}`)
|
|
215
|
+
: compile(sql `INSERT INTO shutro_role_access (role, model, perms) VALUES (${change.role}, ${change.model}, ${sql.array([...change.perms], 'text')})
|
|
216
|
+
ON CONFLICT (role, model) DO UPDATE SET perms = EXCLUDED.perms`);
|
|
217
|
+
case 'rule':
|
|
218
|
+
return compile(sql `INSERT INTO shutro_role_rule (name, role, model, perms, domain) VALUES (${change.name}, ${change.role}, ${change.model}, ${sql.array([...change.perms], 'text')}, (${sql.param(JSON.stringify(change.domain), 'text')})::jsonb)
|
|
219
|
+
ON CONFLICT (name) DO UPDATE SET role = EXCLUDED.role, model = EXCLUDED.model, perms = EXCLUDED.perms, domain = EXCLUDED.domain`);
|
|
220
|
+
case 'deleteRule':
|
|
221
|
+
return compile(sql `DELETE FROM shutro_role_rule WHERE name = ${change.name}`);
|
|
222
|
+
case 'permission':
|
|
223
|
+
return compile(sql `INSERT INTO shutro_role_permission (role, permission) VALUES (${change.role}, ${change.permission}) ON CONFLICT DO NOTHING`);
|
|
224
|
+
case 'revokePermission':
|
|
225
|
+
return compile(sql `DELETE FROM shutro_role_permission WHERE role = ${change.role} AND permission = ${change.permission}`);
|
|
226
|
+
case 'fields':
|
|
227
|
+
return change.read.length === 0 && change.write.length === 0
|
|
228
|
+
? compile(sql `DELETE FROM shutro_role_field WHERE model = ${change.model} AND field = ${change.field}`)
|
|
229
|
+
: compile(sql `INSERT INTO shutro_role_field (model, field, read, write) VALUES (${change.model}, ${change.field}, ${sql.array([...change.read], 'text')}, ${sql.array([...change.write], 'text')})
|
|
230
|
+
ON CONFLICT (model, field) DO UPDATE SET read = EXCLUDED.read, write = EXCLUDED.write`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** SQL ready to execute. `CompiledSql` from `@shutro/sql` satisfies this structurally. */
|
|
2
|
+
export interface DriverQuery {
|
|
3
|
+
readonly text: string;
|
|
4
|
+
readonly params: readonly unknown[];
|
|
5
|
+
}
|
|
6
|
+
/** A result row. */
|
|
7
|
+
export type Row = Record<string, unknown>;
|
|
8
|
+
/** Transaction isolation level. */
|
|
9
|
+
export type Isolation = 'read committed' | 'repeatable read' | 'serializable';
|
|
10
|
+
/** Options for {@link Driver.transaction}. */
|
|
11
|
+
export interface TxOptions {
|
|
12
|
+
/** Defaults to `repeatable read` (RFC 0003 §7.5). */
|
|
13
|
+
readonly isolation?: Isolation;
|
|
14
|
+
/** `BEGIN … READ ONLY`. Writes fail with `ReadOnlyTransactionError`. */
|
|
15
|
+
readonly readOnly?: boolean;
|
|
16
|
+
/** Session settings for this transaction only (`set_config(name, value, true)`), e.g. `{ 'shutro.user_id': '42' }`. */
|
|
17
|
+
readonly settings?: Readonly<Record<string, string>>;
|
|
18
|
+
/** `statement_timeout` for this transaction. */
|
|
19
|
+
readonly statementTimeoutMs?: number;
|
|
20
|
+
/** `lock_timeout` for this transaction. */
|
|
21
|
+
readonly lockTimeoutMs?: number;
|
|
22
|
+
}
|
|
23
|
+
/** A connection inside a transaction (or savepoint). */
|
|
24
|
+
export interface DriverConnection {
|
|
25
|
+
/** Runs one statement. */
|
|
26
|
+
query<R extends Row = Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
27
|
+
/** Runs a query through a server-side cursor, yielding batches of at most `batchSize` rows (RFC 0004 §7.7). */
|
|
28
|
+
stream<R extends Row = Row>(query: DriverQuery, batchSize: number): AsyncIterable<readonly R[]>;
|
|
29
|
+
/** Runs `fn` in a savepoint: rolled back if `fn` throws (and the error rethrown), released otherwise. */
|
|
30
|
+
savepoint<T>(fn: (conn: DriverConnection) => Promise<T>): Promise<T>;
|
|
31
|
+
/** `COPY … FROM STDIN` with one text-format line per item (tab-separated). Returns the number of lines written. */
|
|
32
|
+
copyIn(query: DriverQuery, lines: Iterable<string> | AsyncIterable<string>): Promise<number>;
|
|
33
|
+
}
|
|
34
|
+
/** The connection pool. */
|
|
35
|
+
export interface Driver {
|
|
36
|
+
/** Pool size (`max`), when known: Shutro checks it against features that need a second connection. */
|
|
37
|
+
readonly max?: number;
|
|
38
|
+
/** Runs one statement in its own implicit transaction (DDL, maintenance). Business code uses `transaction()`. */
|
|
39
|
+
query<R extends Row = Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
40
|
+
/**
|
|
41
|
+
* Runs `fn` in a transaction: committed when `fn` resolves, rolled back when it throws. PostgreSQL errors are
|
|
42
|
+
* mapped to typed `DriverError`s. Retrying is the caller's job (`isRetryable()`), because only the caller knows
|
|
43
|
+
* that `fn` is safe to repeat.
|
|
44
|
+
*/
|
|
45
|
+
transaction<T>(options: TxOptions, fn: (conn: DriverConnection) => Promise<T>): Promise<T>;
|
|
46
|
+
/** `LISTEN` on a dedicated connection. Returns a function that stops listening. */
|
|
47
|
+
listen(channel: string, onMessage: (payload: string) => void): Promise<() => Promise<void>>;
|
|
48
|
+
/** Closes all connections, waiting up to `timeoutSeconds` (default 5) for running queries. */
|
|
49
|
+
end(options?: {
|
|
50
|
+
readonly timeoutSeconds?: number;
|
|
51
|
+
}): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** Options for {@link createDriver}. */
|
|
54
|
+
export interface DriverOptions {
|
|
55
|
+
/** `postgres://user:password@host:port/database`. */
|
|
56
|
+
readonly url: string;
|
|
57
|
+
/** Pool size. Defaults to 10. */
|
|
58
|
+
readonly max?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Parses `numeric` values (OID 1700) from their exact text form. `@shutro/core` passes `toDecimal`. Defaults to
|
|
61
|
+
* returning the string unchanged, which is lossless.
|
|
62
|
+
*/
|
|
63
|
+
readonly parseNumeric?: (text: string) => unknown;
|
|
64
|
+
/** Named prepared statements (default `true`). Behind PgBouncer this needs `max_prepared_statements > 0` (≥ 1.21). */
|
|
65
|
+
readonly prepare?: boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Development guard (RFC 0007 §7.3): reject a query when a string parameter (8+ characters) also appears in its text,
|
|
68
|
+
* which means the text was built by concatenation. Defaults to `true` unless `NODE_ENV === 'production'`.
|
|
69
|
+
*/
|
|
70
|
+
readonly checkParamsInText?: boolean;
|
|
71
|
+
/** Receives server NOTICE messages. Defaults to ignoring them (never `console`). */
|
|
72
|
+
readonly onNotice?: (notice: Readonly<Record<string, unknown>>) => void;
|
|
73
|
+
/** `application_name`, visible in `pg_stat_activity`. Defaults to `'shutro'`. */
|
|
74
|
+
readonly applicationName?: string;
|
|
75
|
+
readonly connectTimeoutSeconds?: number;
|
|
76
|
+
readonly idleTimeoutSeconds?: number;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Creates the PostgreSQL connection pool (postgres.js, RFC 0007). All type handling is configured on this instance;
|
|
80
|
+
* no global state is touched.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const driver = createDriver({ url: process.env.DATABASE_URL, parseNumeric: toDecimal });
|
|
85
|
+
* await driver.transaction({ settings: { 'shutro.user_id': '42' } }, (conn) => conn.query(compile(q)));
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
export declare function createDriver(options: DriverOptions): Driver;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { pipeline } from 'node:stream/promises';
|
|
3
|
+
import postgres from 'postgres';
|
|
4
|
+
import { DriverError, mapPostgresError } from './errors.js';
|
|
5
|
+
const SETTING_NAME = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/;
|
|
6
|
+
const MIN_GUARDED_LENGTH = 8;
|
|
7
|
+
/** bigint → number, refusing values that a JS number can't hold exactly (RFC 0001: ids are branded numbers). */
|
|
8
|
+
function parseBigint(text) {
|
|
9
|
+
const n = Number(text);
|
|
10
|
+
if (!Number.isSafeInteger(n)) {
|
|
11
|
+
throw new DriverError('BIGINT_OUT_OF_RANGE', `The bigint ${text} is beyond Number.MAX_SAFE_INTEGER and would lose precision as a JavaScript number.`, 'Cast it to text or numeric in the query (e.g. col::text) if the column really holds such values.');
|
|
12
|
+
}
|
|
13
|
+
return n;
|
|
14
|
+
}
|
|
15
|
+
function collectStrings(value, out) {
|
|
16
|
+
if (typeof value === 'string') {
|
|
17
|
+
if (value.length >= MIN_GUARDED_LENGTH)
|
|
18
|
+
out.push(value);
|
|
19
|
+
}
|
|
20
|
+
else if (Array.isArray(value)) {
|
|
21
|
+
for (const item of value)
|
|
22
|
+
collectStrings(item, out);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function guardParamsInText(query) {
|
|
26
|
+
const strings = [];
|
|
27
|
+
for (const p of query.params)
|
|
28
|
+
collectStrings(p, strings);
|
|
29
|
+
const leaked = strings.find((s) => query.text.includes(s));
|
|
30
|
+
if (leaked !== undefined) {
|
|
31
|
+
throw new DriverError('PARAM_IN_TEXT', `A parameter value (${JSON.stringify(leaked.slice(0, 40))}) also appears in the SQL text, so the text was probably built by string concatenation.`, 'Build queries with sql`...` from @shutro/sql so values only travel as parameters; set checkParamsInText: false only if the overlap is intentional.');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function settingsFor(options) {
|
|
35
|
+
const entries = Object.entries(options.settings ?? {});
|
|
36
|
+
if (options.statementTimeoutMs !== undefined)
|
|
37
|
+
entries.push(['statement_timeout', String(options.statementTimeoutMs)]);
|
|
38
|
+
if (options.lockTimeoutMs !== undefined)
|
|
39
|
+
entries.push(['lock_timeout', String(options.lockTimeoutMs)]);
|
|
40
|
+
for (const [name, value] of entries) {
|
|
41
|
+
if (!SETTING_NAME.test(name) || typeof value !== 'string') {
|
|
42
|
+
throw new DriverError('INVALID_SETTING', `${JSON.stringify(name)} is not a valid transaction setting.`, "Use lower-case names like 'statement_timeout' or a custom 'namespace.name' (e.g. 'shutro.user_id') with string values.");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return entries;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Creates the PostgreSQL connection pool (postgres.js, RFC 0007). All type handling is configured on this instance;
|
|
49
|
+
* no global state is touched.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* const driver = createDriver({ url: process.env.DATABASE_URL, parseNumeric: toDecimal });
|
|
54
|
+
* await driver.transaction({ settings: { 'shutro.user_id': '42' } }, (conn) => conn.query(compile(q)));
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export function createDriver(options) {
|
|
58
|
+
const prepare = options.prepare ?? true;
|
|
59
|
+
const guard = options.checkParamsInText ?? process.env['NODE_ENV'] !== 'production';
|
|
60
|
+
const parseNumeric = options.parseNumeric ?? ((text) => text);
|
|
61
|
+
const sql = postgres(options.url, {
|
|
62
|
+
max: options.max ?? 10,
|
|
63
|
+
prepare,
|
|
64
|
+
onnotice: options.onNotice ?? (() => { }),
|
|
65
|
+
connection: { application_name: options.applicationName ?? 'shutro' },
|
|
66
|
+
...(options.connectTimeoutSeconds === undefined
|
|
67
|
+
? {}
|
|
68
|
+
: { connect_timeout: options.connectTimeoutSeconds }),
|
|
69
|
+
...(options.idleTimeoutSeconds === undefined
|
|
70
|
+
? {}
|
|
71
|
+
: { idle_timeout: options.idleTimeoutSeconds }),
|
|
72
|
+
types: {
|
|
73
|
+
numeric: {
|
|
74
|
+
to: 1700,
|
|
75
|
+
from: [1700],
|
|
76
|
+
serialize: (v) => String(v),
|
|
77
|
+
parse: parseNumeric,
|
|
78
|
+
},
|
|
79
|
+
bigint: { to: 20, from: [20], serialize: (v) => String(v), parse: parseBigint },
|
|
80
|
+
// Calendar dates stay 'YYYY-MM-DD' strings: a JS Date would shift them by the time zone (RFC 0001 W7).
|
|
81
|
+
calendar_date: {
|
|
82
|
+
to: 1082,
|
|
83
|
+
from: [1082],
|
|
84
|
+
serialize: (v) => String(v),
|
|
85
|
+
parse: (s) => s,
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
/**
|
|
90
|
+
* postgres.js infers an array parameter's type from its first element, so an array of booleans is sent as a scalar
|
|
91
|
+
* boolean (and a text array that the server resolves to boolean[] is serialized with the boolean serializer, giving
|
|
92
|
+
* 'f' for anything but the value true). Declaring boolean arrays as boolean[] (OID 1000) avoids both.
|
|
93
|
+
*/
|
|
94
|
+
const typed = (params) => params.map((p) => Array.isArray(p) && p.some((v) => typeof v === 'boolean') ? sql.typed(p, 1000) : p);
|
|
95
|
+
const run = async (s, query) => {
|
|
96
|
+
if (guard)
|
|
97
|
+
guardParamsInText(query);
|
|
98
|
+
try {
|
|
99
|
+
return [...(await s.unsafe(query.text, typed(query.params), { prepare }))];
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
throw mapPostgresError(e);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const connection = (s) => ({
|
|
106
|
+
query: (query) => run(s, query),
|
|
107
|
+
async *stream(query, batchSize) {
|
|
108
|
+
if (guard)
|
|
109
|
+
guardParamsInText(query);
|
|
110
|
+
try {
|
|
111
|
+
for await (const rows of s
|
|
112
|
+
.unsafe(query.text, query.params, { prepare })
|
|
113
|
+
.cursor(batchSize)) {
|
|
114
|
+
yield [...rows];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
throw mapPostgresError(e);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
async savepoint(fn) {
|
|
122
|
+
return (await s.savepoint((sp) => fn(connection(sp))));
|
|
123
|
+
},
|
|
124
|
+
async copyIn(query, lines) {
|
|
125
|
+
let count = 0;
|
|
126
|
+
async function* withNewlines() {
|
|
127
|
+
for await (const line of lines) {
|
|
128
|
+
count++;
|
|
129
|
+
yield `${line}\n`;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const writable = await s.unsafe(query.text, typed(query.params)).writable();
|
|
134
|
+
await pipeline(Readable.from(withNewlines()), writable);
|
|
135
|
+
}
|
|
136
|
+
catch (e) {
|
|
137
|
+
throw mapPostgresError(e);
|
|
138
|
+
}
|
|
139
|
+
return count;
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
return {
|
|
143
|
+
max: options.max ?? 10,
|
|
144
|
+
query: (query) => run(sql, query),
|
|
145
|
+
async transaction(txOptions, fn) {
|
|
146
|
+
const settings = settingsFor(txOptions);
|
|
147
|
+
const mode = `isolation level ${txOptions.isolation ?? 'repeatable read'}${txOptions.readOnly ? ' read only' : ''}`;
|
|
148
|
+
try {
|
|
149
|
+
return (await sql.begin(mode, async (tx) => {
|
|
150
|
+
if (settings.length > 0) {
|
|
151
|
+
// One round-trip for all settings: SELECT set_config($1, $2, true), set_config($3, $4, true), …
|
|
152
|
+
const calls = settings
|
|
153
|
+
.map((_, i) => `set_config($${2 * i + 1}, $${2 * i + 2}, true)`)
|
|
154
|
+
.join(', ');
|
|
155
|
+
await tx.unsafe(`SELECT ${calls}`, settings.flat(), { prepare });
|
|
156
|
+
}
|
|
157
|
+
return fn(connection(tx));
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
throw mapPostgresError(e);
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
async listen(channel, onMessage) {
|
|
165
|
+
try {
|
|
166
|
+
const subscription = await sql.listen(channel, onMessage);
|
|
167
|
+
return async () => {
|
|
168
|
+
await subscription.unlisten();
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
throw mapPostgresError(e);
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
end: (endOptions) => sql.end({ timeout: endOptions?.timeoutSeconds ?? 5 }),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Machine-readable reason for a {@link DriverError}. */
|
|
2
|
+
export type DriverErrorCode = 'QUERY_FAILED' | 'CONSTRAINT_VIOLATION' | 'SERIALIZATION_FAILURE' | 'DEADLOCK' | 'STATEMENT_TIMEOUT' | 'LOCK_TIMEOUT' | 'READ_ONLY_TRANSACTION' | 'CONNECTION_FAILED' | 'BIGINT_OUT_OF_RANGE' | 'PARAM_IN_TEXT' | 'INVALID_SETTING';
|
|
3
|
+
/** Server-side details carried by a {@link DriverError}. */
|
|
4
|
+
export interface DriverErrorDetails {
|
|
5
|
+
/** SQLSTATE, e.g. `'23505'`. */
|
|
6
|
+
readonly sqlState?: string | undefined;
|
|
7
|
+
readonly constraint?: string | undefined;
|
|
8
|
+
readonly table?: string | undefined;
|
|
9
|
+
readonly column?: string | undefined;
|
|
10
|
+
/** PostgreSQL's DETAIL line, e.g. `Key (name)=(SO001) already exists.` */
|
|
11
|
+
readonly detail?: string | undefined;
|
|
12
|
+
/** The original error. */
|
|
13
|
+
readonly cause?: unknown;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Base class of every error raised by `@shutro/driver-pg`. Same convention as `ShutroError` in `@shutro/core`: the
|
|
17
|
+
* message says what went wrong and ends with {@link DriverError.hint}, which says how to fix it.
|
|
18
|
+
*/
|
|
19
|
+
export declare class DriverError extends Error {
|
|
20
|
+
readonly code: DriverErrorCode;
|
|
21
|
+
readonly hint: string;
|
|
22
|
+
/** True when re-running the whole transaction may succeed (serialization failure, deadlock). */
|
|
23
|
+
readonly retryable: boolean;
|
|
24
|
+
readonly sqlState: string | undefined;
|
|
25
|
+
readonly constraint: string | undefined;
|
|
26
|
+
readonly table: string | undefined;
|
|
27
|
+
readonly column: string | undefined;
|
|
28
|
+
readonly detail: string | undefined;
|
|
29
|
+
constructor(code: DriverErrorCode, problem: string, hint: string, details?: DriverErrorDetails, retryable?: boolean);
|
|
30
|
+
}
|
|
31
|
+
/** Which kind of constraint was violated. */
|
|
32
|
+
export type ConstraintKind = 'unique' | 'foreign_key' | 'not_null' | 'check' | 'exclusion';
|
|
33
|
+
/** A unique, foreign-key, not-null, check or exclusion constraint was violated (SQLSTATE class 23). */
|
|
34
|
+
export declare class ConstraintViolationError extends DriverError {
|
|
35
|
+
readonly kind: ConstraintKind;
|
|
36
|
+
constructor(kind: ConstraintKind, problem: string, hint: string, details: DriverErrorDetails);
|
|
37
|
+
}
|
|
38
|
+
/** 40001: the transaction conflicted with a concurrent one. Retry the whole transaction. */
|
|
39
|
+
export declare class SerializationFailureError extends DriverError {
|
|
40
|
+
constructor(details: DriverErrorDetails);
|
|
41
|
+
}
|
|
42
|
+
/** 40P01: deadlock detected. Retry the whole transaction. */
|
|
43
|
+
export declare class DeadlockError extends DriverError {
|
|
44
|
+
constructor(details: DriverErrorDetails);
|
|
45
|
+
}
|
|
46
|
+
/** 57014: the statement exceeded `statement_timeout`. */
|
|
47
|
+
export declare class StatementTimeoutError extends DriverError {
|
|
48
|
+
constructor(details: DriverErrorDetails);
|
|
49
|
+
}
|
|
50
|
+
/** 55P03: waiting for a lock exceeded `lock_timeout`. */
|
|
51
|
+
export declare class LockTimeoutError extends DriverError {
|
|
52
|
+
constructor(details: DriverErrorDetails);
|
|
53
|
+
}
|
|
54
|
+
/** 25006: a write in a read-only transaction. */
|
|
55
|
+
export declare class ReadOnlyTransactionError extends DriverError {
|
|
56
|
+
constructor(details: DriverErrorDetails);
|
|
57
|
+
}
|
|
58
|
+
/** The server could not be reached, the connection broke, or authentication failed. */
|
|
59
|
+
export declare class ConnectionError extends DriverError {
|
|
60
|
+
constructor(problem: string, hint: string, details: DriverErrorDetails);
|
|
61
|
+
}
|
|
62
|
+
/** Any other PostgreSQL error. */
|
|
63
|
+
export declare class QueryError extends DriverError {
|
|
64
|
+
constructor(problem: string, hint: string, details: DriverErrorDetails);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Maps a postgres.js error to a typed {@link DriverError}. Anything else (including errors thrown by business
|
|
68
|
+
* code and already-mapped errors) is returned unchanged.
|
|
69
|
+
*/
|
|
70
|
+
export declare function mapPostgresError(error: unknown): unknown;
|
|
71
|
+
/** True when `error` is a {@link DriverError} worth retrying as a whole transaction. */
|
|
72
|
+
export declare function isRetryable(error: unknown): boolean;
|