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,916 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { isRetryable, } from '../../driver-pg/index.js';
|
|
5
|
+
import { InvalidSequenceError } from '../../sequence/index.js';
|
|
6
|
+
import { compile, sql as sqlTag } from '../../sql/index.js';
|
|
7
|
+
import { refId } from '../data/load.js';
|
|
8
|
+
import { AccessError, CompanyNotAllowedError, ConcurrentUpdateError, FlagNotAllowedError, InvalidIdentityError, NoEnvironmentError, NoRegistryError, TransactionScopeError, } from '../errors.js';
|
|
9
|
+
import { emitEvent, enqueueJob, ensureEventTables } from '../events/events.js';
|
|
10
|
+
import { subscribe, work, } from '../events/workers.js';
|
|
11
|
+
import { createFx } from '../money/fx.js';
|
|
12
|
+
import { trackElevation, trackSecurityChange, trackSuperuser } from '../recordset/audit.js';
|
|
13
|
+
import { invalidateCached } from '../recordset/compute.js';
|
|
14
|
+
import { companyCurrencyId, createRecordCache, currencyById, flushAll, modelRef, } from '../recordset/recordset.js';
|
|
15
|
+
import { assertAccess, assertPermission, assertRecords, canAccess, canField, hasPermission, } from '../recordset/security.js';
|
|
16
|
+
import { mapConstraintError } from '../recordset/sqlErrors.js';
|
|
17
|
+
import { administratorCodes, changeStatement, closureWith, isAdministratorWith, loadRuntimeSecurity, SECURITY_CHANNEL, validateChange, } from '../security/runtime.js';
|
|
18
|
+
import { assertGrants, assertLang, assertReason, resolveIdentity, SYSTEM_UID, } from './identity.js';
|
|
19
|
+
import { assertTimeZone, calendarDateIn } from './time.js';
|
|
20
|
+
const DEFAULT_FLAGS = Object.freeze({
|
|
21
|
+
activeTest: true,
|
|
22
|
+
tracking: true,
|
|
23
|
+
checkCompany: true,
|
|
24
|
+
});
|
|
25
|
+
const internals = new WeakMap();
|
|
26
|
+
/** @internal */
|
|
27
|
+
export function internalsOf(env) {
|
|
28
|
+
const get = internals.get(env);
|
|
29
|
+
if (get === undefined)
|
|
30
|
+
throw new NoEnvironmentError();
|
|
31
|
+
return get();
|
|
32
|
+
}
|
|
33
|
+
async function runHooks(hooks, runtime, phase) {
|
|
34
|
+
for (const hook of hooks) {
|
|
35
|
+
try {
|
|
36
|
+
await hook();
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
runtime.onHookError(error, phase);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The environment (RFC 0003): who is acting, for which company, how, and in which transaction. Immutable; the
|
|
45
|
+
* `with*` methods return derived environments that share the transaction scope. `S` is the schema view of the
|
|
46
|
+
* registry (model name → model), which types `model()`.
|
|
47
|
+
*/
|
|
48
|
+
export class Env {
|
|
49
|
+
/** Id of the acting user. */
|
|
50
|
+
uid;
|
|
51
|
+
/** Current company id. */
|
|
52
|
+
companyId;
|
|
53
|
+
/** Allowed company ids (record-rule scope). */
|
|
54
|
+
companyIds;
|
|
55
|
+
lang;
|
|
56
|
+
/** {@link uid} as a `res.users` id, for many2one defaults: `default: (env) => env.userId`. */
|
|
57
|
+
get userId() {
|
|
58
|
+
return this.uid;
|
|
59
|
+
}
|
|
60
|
+
/** {@link companyId} as a `res.company` id. */
|
|
61
|
+
get companyRef() {
|
|
62
|
+
return this.companyId;
|
|
63
|
+
}
|
|
64
|
+
/** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
|
|
65
|
+
sourceLang;
|
|
66
|
+
tz;
|
|
67
|
+
/** Superuser mode: only inside {@link asSuperuser}. */
|
|
68
|
+
su;
|
|
69
|
+
/**
|
|
70
|
+
* The user is in an administrator group (`defineGroup({ administrator: true })`): every ACL, record rule, field
|
|
71
|
+
* group and permission passes, without grants (RFC 0014 §7.9). Company scoping still applies.
|
|
72
|
+
*/
|
|
73
|
+
administrator;
|
|
74
|
+
/** Reason for a job or superuser scope, when given. */
|
|
75
|
+
reason;
|
|
76
|
+
/** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
|
|
77
|
+
groups;
|
|
78
|
+
/** Special permissions of this user on top of the roles (`'account.backdate'`, `'account.move:unlink'`). */
|
|
79
|
+
grants;
|
|
80
|
+
/** @internal Encryption keys. */
|
|
81
|
+
keys;
|
|
82
|
+
flags;
|
|
83
|
+
/** 1 for the first attempt of `run()`, 2+ for retries after a serialization failure or deadlock. */
|
|
84
|
+
attempt;
|
|
85
|
+
readOnly;
|
|
86
|
+
#scope;
|
|
87
|
+
#runtime;
|
|
88
|
+
/** @internal */
|
|
89
|
+
constructor(identity, scope, runtime) {
|
|
90
|
+
this.uid = identity.uid;
|
|
91
|
+
this.companyId = identity.companyId;
|
|
92
|
+
this.companyIds = identity.companyIds;
|
|
93
|
+
this.lang = identity.lang;
|
|
94
|
+
this.sourceLang = runtime.sourceLang;
|
|
95
|
+
this.groups =
|
|
96
|
+
runtime.registry === undefined
|
|
97
|
+
? new Set(identity.groups)
|
|
98
|
+
: closureWith(runtime.registry, runtime.security.current, identity.groups);
|
|
99
|
+
this.administrator =
|
|
100
|
+
runtime.registry !== undefined &&
|
|
101
|
+
isAdministratorWith(runtime.registry, runtime.security.current, this.groups);
|
|
102
|
+
this.grants = new Set(identity.grants);
|
|
103
|
+
this.keys = runtime.keys;
|
|
104
|
+
this.tz = identity.tz;
|
|
105
|
+
this.su = identity.su;
|
|
106
|
+
this.reason = identity.reason;
|
|
107
|
+
this.flags = identity.flags;
|
|
108
|
+
this.readOnly = identity.readOnly;
|
|
109
|
+
this.attempt = scope.root.attempt;
|
|
110
|
+
this.#scope = scope;
|
|
111
|
+
this.#runtime = runtime;
|
|
112
|
+
internals.set(this, () => {
|
|
113
|
+
this.#assertUsable();
|
|
114
|
+
const registry = runtime.registry;
|
|
115
|
+
if (registry === undefined)
|
|
116
|
+
throw new NoRegistryError();
|
|
117
|
+
return scopeInternals(this, scope, registry, (q) => this.#query(q), runtime.driver, runtime.security.current);
|
|
118
|
+
});
|
|
119
|
+
Object.freeze(this);
|
|
120
|
+
}
|
|
121
|
+
/** An empty recordset of `name`: `search()` / `browse()` / `create()` start here (RFC 0004). */
|
|
122
|
+
model(name) {
|
|
123
|
+
if (this.#runtime.registry === undefined)
|
|
124
|
+
throw new NoRegistryError();
|
|
125
|
+
this.#assertUsable();
|
|
126
|
+
// The runtime is untyped over S; widening here is safe because it never reads S.
|
|
127
|
+
return modelRef(this, name);
|
|
128
|
+
}
|
|
129
|
+
/** What this environment may do (RFC 0014): for Kosh menus, export / import buttons and API guards. */
|
|
130
|
+
get access() {
|
|
131
|
+
const scope = internalsOf(this);
|
|
132
|
+
return {
|
|
133
|
+
can: (model, perm) => canAccess(scope, scope.registry.get(model).model, perm),
|
|
134
|
+
check: (model, perm) => assertAccess(scope, scope.registry.get(model).model, perm),
|
|
135
|
+
checkRecords: async (model, ids, perm) => {
|
|
136
|
+
const target = scope.registry.get(model).model;
|
|
137
|
+
assertAccess(scope, target, perm);
|
|
138
|
+
await assertRecords(scope, target, ids, perm);
|
|
139
|
+
},
|
|
140
|
+
canField: (model, field, kind) => canField(scope, scope.registry.get(model).model, field, kind),
|
|
141
|
+
has: (code) => hasPermission(scope, code),
|
|
142
|
+
require: (code) => {
|
|
143
|
+
assertPermission(scope, code);
|
|
144
|
+
},
|
|
145
|
+
administratorGroups: () => administratorCodes(scope.registry, scope.overlay),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The record with external id `id` (`'base.main_company'`, RFC 0017), nothing loaded.
|
|
150
|
+
* @throws {UnknownExternalIdError} for an unknown id or a record of another model.
|
|
151
|
+
*/
|
|
152
|
+
async ref(model, id) {
|
|
153
|
+
const resId = await refId(this, model, id);
|
|
154
|
+
return this.model(model).browse([resId]);
|
|
155
|
+
}
|
|
156
|
+
/** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
|
|
157
|
+
async refId(model, id) {
|
|
158
|
+
return refId(this, model, id);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
|
|
162
|
+
* of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
|
|
163
|
+
* registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
|
|
164
|
+
*/
|
|
165
|
+
get securityAdmin() {
|
|
166
|
+
const apply = async (change) => {
|
|
167
|
+
const scope = internalsOf(this);
|
|
168
|
+
if (!this.#runtime.security.enabled)
|
|
169
|
+
throw new InvalidIdentityError('Runtime security is not enabled.', 'Pass runtimeSecurity: true to createShutro.');
|
|
170
|
+
if (!this.su && !this.administrator)
|
|
171
|
+
throw new AccessError('security', 'manage', {
|
|
172
|
+
problem: 'only administrators can change roles, access and rules.',
|
|
173
|
+
hint: 'Use an administrator account (defineGroup({ administrator: true })).',
|
|
174
|
+
});
|
|
175
|
+
// Read through this transaction: roles saved earlier in it count.
|
|
176
|
+
const overlay = await loadRuntimeSecurity({
|
|
177
|
+
query: (q) => scope.query(q),
|
|
178
|
+
});
|
|
179
|
+
validateChange(scope.registry, overlay, change);
|
|
180
|
+
await scope.query(changeStatement(change));
|
|
181
|
+
await scope.query(compile(sqlTag `SELECT pg_notify(${SECURITY_CHANNEL}, '')`));
|
|
182
|
+
trackSecurityChange(scope, change);
|
|
183
|
+
this.afterCommit(async () => {
|
|
184
|
+
this.#runtime.security.current = await loadRuntimeSecurity(this.#runtime.driver);
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
saveRole: (role) => apply({ kind: 'role', ...role }),
|
|
189
|
+
deleteRole: (code) => apply({ kind: 'deleteRole', code }),
|
|
190
|
+
setAccess: (role, model, perms) => apply({ kind: 'access', role, model, perms }),
|
|
191
|
+
saveRule: (rule) => apply({ kind: 'rule', ...rule }),
|
|
192
|
+
deleteRule: (name) => apply({ kind: 'deleteRule', name }),
|
|
193
|
+
grantPermission: (role, permission) => apply({ kind: 'permission', role, permission }),
|
|
194
|
+
revokePermission: (role, permission) => apply({ kind: 'revokePermission', role, permission }),
|
|
195
|
+
setFieldGroups: (model, field, groups) => apply({
|
|
196
|
+
kind: 'fields',
|
|
197
|
+
model,
|
|
198
|
+
field,
|
|
199
|
+
read: [...(groups.read ?? [])],
|
|
200
|
+
write: [...(groups.write ?? [])],
|
|
201
|
+
}),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
|
|
206
|
+
* subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
|
|
207
|
+
*/
|
|
208
|
+
async emit(topic, payload) {
|
|
209
|
+
const scope = internalsOf(this);
|
|
210
|
+
const query = (q) => scope.query(q);
|
|
211
|
+
await ensureEventTables(this.#runtime.driver, query);
|
|
212
|
+
return emitEvent(query, this.#actor(), topic, payload);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Enqueues a background job in this transaction (RFC 0018 §7.3), run by `shutro.work` as this user, with
|
|
216
|
+
* retries. With `key`, a job already pending or running under that key makes this a no-op (returns `null`).
|
|
217
|
+
*/
|
|
218
|
+
async enqueue(name, payload, options) {
|
|
219
|
+
const scope = internalsOf(this);
|
|
220
|
+
const query = (q) => scope.query(q);
|
|
221
|
+
await ensureEventTables(this.#runtime.driver, query);
|
|
222
|
+
return enqueueJob(query, this.#actor(), name, payload, options);
|
|
223
|
+
}
|
|
224
|
+
#actor() {
|
|
225
|
+
return { uid: this.uid, companyId: this.companyId, groups: [...this.groups] };
|
|
226
|
+
}
|
|
227
|
+
/** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
|
|
228
|
+
get fx() {
|
|
229
|
+
const scope = internalsOf(this);
|
|
230
|
+
return createFx({
|
|
231
|
+
internals: scope,
|
|
232
|
+
currency: (id) => currencyById(scope, id),
|
|
233
|
+
companyCurrency: async (company) => currencyById(scope, await companyCurrencyId(scope, company)),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/** The transaction timestamp (PostgreSQL `now()`), stable within an attempt. Returns a fresh `Date` each call. */
|
|
237
|
+
now() {
|
|
238
|
+
return new Date(this.#scope.root.now.getTime());
|
|
239
|
+
}
|
|
240
|
+
/** Today's calendar date (`'YYYY-MM-DD'`) in the environment's time zone. */
|
|
241
|
+
today() {
|
|
242
|
+
return calendarDateIn(this.#scope.root.now, this.tz);
|
|
243
|
+
}
|
|
244
|
+
/** Today's calendar date in another time zone. */
|
|
245
|
+
todayIn(tz) {
|
|
246
|
+
return calendarDateIn(this.#scope.root.now, tz);
|
|
247
|
+
}
|
|
248
|
+
/** Writes every pending change of the unit of work to the database now (RFC 0004 §7.6). */
|
|
249
|
+
async flush() {
|
|
250
|
+
if (this.#runtime.registry === undefined)
|
|
251
|
+
return;
|
|
252
|
+
await flushAll(internalsOf(this));
|
|
253
|
+
}
|
|
254
|
+
/** Statistics of the current attempt (query counts for N+1 assertions, RFC 0004 §7.9). */
|
|
255
|
+
stats() {
|
|
256
|
+
return { queries: this.#scope.root.queries };
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Raw SQL in this transaction (RFC 0005 §7.8): values become parameters, identifiers go through `sql.id()`.
|
|
260
|
+
* Pending writes are flushed first. Rejects with {@link TransactionScopeError} when the scope has ended or
|
|
261
|
+
* another scope is active.
|
|
262
|
+
*/
|
|
263
|
+
sql(strings, ...values) {
|
|
264
|
+
return (async () => {
|
|
265
|
+
this.#assertUsable();
|
|
266
|
+
await this.flush();
|
|
267
|
+
return this.#query(compile(sqlTag(strings, ...values)));
|
|
268
|
+
})();
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Runs `fn` in a savepoint: its database work and its cache changes are undone if it throws, kept otherwise.
|
|
272
|
+
* Pending writes are flushed before the savepoint is released.
|
|
273
|
+
*/
|
|
274
|
+
async transaction(fn) {
|
|
275
|
+
this.#assertUsable();
|
|
276
|
+
const parent = this.#scope;
|
|
277
|
+
const root = parent.root;
|
|
278
|
+
let child;
|
|
279
|
+
const auditMark = root.audit.length;
|
|
280
|
+
try {
|
|
281
|
+
const result = await parent.conn.savepoint(async (conn) => {
|
|
282
|
+
const scope = {
|
|
283
|
+
root,
|
|
284
|
+
parent,
|
|
285
|
+
conn,
|
|
286
|
+
status: 'open',
|
|
287
|
+
env: this,
|
|
288
|
+
afterCommit: [],
|
|
289
|
+
onRollback: [],
|
|
290
|
+
journal: [],
|
|
291
|
+
};
|
|
292
|
+
scope.env = this.#derive({}, scope);
|
|
293
|
+
child = scope;
|
|
294
|
+
root.top = scope;
|
|
295
|
+
return this.#runtime.als.run(scope, async () => {
|
|
296
|
+
const value = await fn(scope.env);
|
|
297
|
+
await scope.env.flush();
|
|
298
|
+
return value;
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
if (child !== undefined) {
|
|
302
|
+
child.status = 'committed';
|
|
303
|
+
parent.afterCommit.push(...child.afterCommit);
|
|
304
|
+
parent.onRollback.push(...child.onRollback);
|
|
305
|
+
if (parent.journal !== undefined && child.journal !== undefined)
|
|
306
|
+
parent.journal.push(...child.journal);
|
|
307
|
+
}
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
if (child !== undefined) {
|
|
312
|
+
child.status = 'rolled-back';
|
|
313
|
+
if (child.journal !== undefined)
|
|
314
|
+
undo(child.journal, root);
|
|
315
|
+
root.audit.length = auditMark; // rows of a rolled-back savepoint never reach the trail
|
|
316
|
+
await runHooks(child.onRollback, this.#runtime, 'onRollback');
|
|
317
|
+
}
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
root.top = parent;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/** Registers work to run only after the outermost transaction commits (emails, webhooks, queue messages). */
|
|
325
|
+
afterCommit(hook) {
|
|
326
|
+
this.#assertUsable();
|
|
327
|
+
this.#scope.afterCommit.push(hook);
|
|
328
|
+
}
|
|
329
|
+
/** Registers work to run if this scope rolls back (cleanup of external resources). */
|
|
330
|
+
onRollback(hook) {
|
|
331
|
+
this.#assertUsable();
|
|
332
|
+
this.#scope.onRollback.push(hook);
|
|
333
|
+
}
|
|
334
|
+
/** The same scope with another current company. Must be allowed unless `su`. @throws {CompanyNotAllowedError} */
|
|
335
|
+
withCompany(company) {
|
|
336
|
+
if (!this.su && !this.companyIds.includes(company))
|
|
337
|
+
throw new CompanyNotAllowedError(company, this.companyIds);
|
|
338
|
+
const companyIds = this.companyIds.includes(company)
|
|
339
|
+
? this.companyIds
|
|
340
|
+
: Object.freeze([...this.companyIds, company]);
|
|
341
|
+
return this.#derive({ companyId: company, companyIds });
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Drops clean records from this scope's cache (all models, or one): for long reads in one transaction, such as
|
|
345
|
+
* streaming an export of millions of rows page by page, so memory stays bounded. Records with unsaved changes or
|
|
346
|
+
* pending computes and checks are kept; dropped records are simply loaded again when read.
|
|
347
|
+
*/
|
|
348
|
+
releaseCache(model) {
|
|
349
|
+
const scope = internalsOf(this);
|
|
350
|
+
const root = this.#scope.root;
|
|
351
|
+
for (const name of model === undefined ? [...root.cache.records.keys()] : [model]) {
|
|
352
|
+
const byId = root.cache.records.get(name);
|
|
353
|
+
if (byId === undefined)
|
|
354
|
+
continue;
|
|
355
|
+
const pending = (sets) => [...(sets.get(name)?.values() ?? [])].flatMap((set) => [...set]);
|
|
356
|
+
const keep = new Set([
|
|
357
|
+
...(root.dirty.get(name)?.keys() ?? []),
|
|
358
|
+
...pending(root.triggers),
|
|
359
|
+
...pending(root.toCompute),
|
|
360
|
+
...pending(root.toCheck),
|
|
361
|
+
]);
|
|
362
|
+
for (const id of [...byId.keys()])
|
|
363
|
+
if (!keep.has(id))
|
|
364
|
+
scope.forget(name, id);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/** The same scope with another language. */
|
|
368
|
+
withLang(lang) {
|
|
369
|
+
return this.#derive({ lang: assertLang(lang) });
|
|
370
|
+
}
|
|
371
|
+
/** The same scope with another time zone. */
|
|
372
|
+
withTz(tz) {
|
|
373
|
+
assertTimeZone(tz);
|
|
374
|
+
return this.#derive({ tz });
|
|
375
|
+
}
|
|
376
|
+
/** The same scope with some flags changed. `checkCompany: false` needs `su`. @throws {FlagNotAllowedError} */
|
|
377
|
+
withFlags(flags) {
|
|
378
|
+
if (flags.checkCompany === false && !this.su)
|
|
379
|
+
throw new FlagNotAllowedError('checkCompany');
|
|
380
|
+
return this.#derive({ flags: Object.freeze({ ...this.flags, ...flags }) });
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Runs `fn` reading the past (RFC 0018 §7.4): models with `history: true` are searched and loaded as they were at
|
|
384
|
+
* `instant` (rules, field groups and company scope apply as now); other models are read as they are now. The
|
|
385
|
+
* environment has its own cache and is read-only: writes are refused.
|
|
386
|
+
*
|
|
387
|
+
* ```ts
|
|
388
|
+
* const atClose = await env.asOf(new Date('2026-09-30T23:59:59Z'), (past) => past.model('account.move').search({ where: { state: 'posted' } }).then((m) => m.read(['name', 'amountTotal'])));
|
|
389
|
+
* ```
|
|
390
|
+
*/
|
|
391
|
+
async asOf(instant, fn) {
|
|
392
|
+
this.#assertUsable();
|
|
393
|
+
if (!(instant instanceof Date) || Number.isNaN(instant.getTime()))
|
|
394
|
+
throw new InvalidIdentityError('asOf() needs a valid Date.', "Pass the instant to read, e.g. new Date('2026-09-30T23:59:59Z').");
|
|
395
|
+
const parent = this.#scope;
|
|
396
|
+
const root = {
|
|
397
|
+
...parent.root,
|
|
398
|
+
top: undefined,
|
|
399
|
+
cache: createRecordCache(),
|
|
400
|
+
dirty: new Map(),
|
|
401
|
+
triggers: new Map(),
|
|
402
|
+
toCompute: new Map(),
|
|
403
|
+
toCheck: new Map(),
|
|
404
|
+
audit: [],
|
|
405
|
+
compute: {
|
|
406
|
+
recomputing: false,
|
|
407
|
+
computing: new Set(),
|
|
408
|
+
protected: new Map(),
|
|
409
|
+
previous: new Map(),
|
|
410
|
+
},
|
|
411
|
+
asOf: instant,
|
|
412
|
+
};
|
|
413
|
+
const scope = { ...parent, root, afterCommit: [], onRollback: [], journal: undefined };
|
|
414
|
+
root.top = scope;
|
|
415
|
+
const past = this.#derive({ readOnly: true }, scope);
|
|
416
|
+
scope.env = past;
|
|
417
|
+
try {
|
|
418
|
+
return await this.#runtime.als.run(scope, () => fn(past));
|
|
419
|
+
}
|
|
420
|
+
finally {
|
|
421
|
+
parent.root.queries += root.queries;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Runs `fn` with extra special grants in the same scope (RFC 0014 §7.9): a narrow, audited alternative to
|
|
426
|
+
* {@link asSuperuser} for code that must touch a model or feature its caller cannot. Record rules, field groups
|
|
427
|
+
* and company scoping still apply; only the named grants are added, and only inside `fn`.
|
|
428
|
+
*
|
|
429
|
+
* ```ts
|
|
430
|
+
* await env.withGrants({ grants: ['sale.order.line:read'], reason: 'invoice from orders' }, (e) => ...);
|
|
431
|
+
* ```
|
|
432
|
+
*/
|
|
433
|
+
async withGrants(options, fn) {
|
|
434
|
+
const reason = assertReason(options.reason);
|
|
435
|
+
const grants = assertGrants(options.grants);
|
|
436
|
+
this.#assertUsable();
|
|
437
|
+
const elevated = this.#derive({
|
|
438
|
+
grants: Object.freeze([...new Set([...this.grants, ...grants])]),
|
|
439
|
+
});
|
|
440
|
+
if (this.#runtime.registry !== undefined)
|
|
441
|
+
trackElevation(internalsOf(elevated), grants, reason);
|
|
442
|
+
return fn(elevated);
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
|
|
446
|
+
* returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
|
|
447
|
+
*/
|
|
448
|
+
async asSuperuser(options, fn) {
|
|
449
|
+
const reason = assertReason(options.reason);
|
|
450
|
+
this.#assertUsable();
|
|
451
|
+
const su = this.#derive({ su: true, reason });
|
|
452
|
+
if (this.#runtime.registry !== undefined)
|
|
453
|
+
trackSuperuser(internalsOf(su), reason);
|
|
454
|
+
// RLS policies read shutro.su: the setting is scoped to the call (RFC 0014 §7.5).
|
|
455
|
+
const wasSu = this.su || this.administrator; // administrators already pass RLS (shutro.su = 1)
|
|
456
|
+
if (!wasSu)
|
|
457
|
+
await this.#query(compile(sqlTag `SELECT set_config(${'shutro.su'}, ${'1'}, true)`));
|
|
458
|
+
try {
|
|
459
|
+
return await fn(su);
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
if (!wasSu)
|
|
463
|
+
await this.#query(compile(sqlTag `SELECT set_config(${'shutro.su'}, ${'0'}, true)`));
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
async #query(query) {
|
|
467
|
+
this.#scope.root.queries++;
|
|
468
|
+
const inspector = this.#runtime.inspector;
|
|
469
|
+
if (inspector === undefined)
|
|
470
|
+
return this.#scope.conn.query(query);
|
|
471
|
+
const started = performance.now();
|
|
472
|
+
const base = { sql: query.text, params: query.params, tx: this.#scope.root.tx, uid: this.uid };
|
|
473
|
+
try {
|
|
474
|
+
const rows = await this.#scope.conn.query(query);
|
|
475
|
+
inspector.record({ ...base, ms: performance.now() - started });
|
|
476
|
+
return rows;
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
inspector.record({
|
|
480
|
+
...base,
|
|
481
|
+
ms: performance.now() - started,
|
|
482
|
+
error: error instanceof Error ? error.message : String(error),
|
|
483
|
+
});
|
|
484
|
+
throw error;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
#derive(changes, scope = this.#scope) {
|
|
488
|
+
return new _a({
|
|
489
|
+
uid: this.uid,
|
|
490
|
+
companyId: this.companyId,
|
|
491
|
+
companyIds: this.companyIds,
|
|
492
|
+
lang: this.lang,
|
|
493
|
+
tz: this.tz,
|
|
494
|
+
reason: this.reason,
|
|
495
|
+
groups: [...this.groups],
|
|
496
|
+
grants: [...this.grants],
|
|
497
|
+
su: this.su,
|
|
498
|
+
flags: this.flags,
|
|
499
|
+
readOnly: this.readOnly,
|
|
500
|
+
...changes,
|
|
501
|
+
}, scope, this.#runtime);
|
|
502
|
+
}
|
|
503
|
+
#assertUsable() {
|
|
504
|
+
const scope = this.#scope;
|
|
505
|
+
if (scope.status !== 'open') {
|
|
506
|
+
throw new TransactionScopeError(`This environment belongs to a transaction that already ${scope.status === 'committed' ? 'committed' : 'rolled back'}.`, 'Do not keep environments or records across requests; start a new shutro.run() and re-browse the records inside it.');
|
|
507
|
+
}
|
|
508
|
+
if (scope.root.top !== scope) {
|
|
509
|
+
throw new TransactionScopeError('A nested transaction (savepoint) is active on this connection.', 'Use the env passed to env.transaction(fn) inside the callback; the outer env becomes usable again when it ends.');
|
|
510
|
+
}
|
|
511
|
+
const active = this.#runtime.als.getStore();
|
|
512
|
+
if (active !== undefined && active.root !== scope.root) {
|
|
513
|
+
throw new TransactionScopeError('This environment belongs to a different transaction than the one running here.', 'Pass data, not environments or records, between transactions; re-browse records in the current shutro.run().');
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
_a = Env;
|
|
518
|
+
function scopeInternals(env, scope, registry, query, driver, overlay) {
|
|
519
|
+
const root = scope.root;
|
|
520
|
+
const dirtyOf = (model, id) => root.dirty.get(model)?.get(id);
|
|
521
|
+
const addIds = (sets, model, key, ids) => {
|
|
522
|
+
let byKey = sets.get(model);
|
|
523
|
+
if (byKey === undefined) {
|
|
524
|
+
byKey = new Map();
|
|
525
|
+
sets.set(model, byKey);
|
|
526
|
+
}
|
|
527
|
+
let set = byKey.get(key);
|
|
528
|
+
if (set === undefined) {
|
|
529
|
+
set = new Set();
|
|
530
|
+
byKey.set(key, set);
|
|
531
|
+
}
|
|
532
|
+
for (const id of ids)
|
|
533
|
+
set.add(id);
|
|
534
|
+
};
|
|
535
|
+
const self = {
|
|
536
|
+
env,
|
|
537
|
+
registry,
|
|
538
|
+
overlay,
|
|
539
|
+
asOf: root.asOf,
|
|
540
|
+
cache: root.cache,
|
|
541
|
+
uid: root.uid,
|
|
542
|
+
now: root.now,
|
|
543
|
+
query: async (q) => {
|
|
544
|
+
try {
|
|
545
|
+
return await query(q);
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
throw mapConstraintError(registry, error);
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
copyIn: async (q, lines) => {
|
|
552
|
+
root.queries++;
|
|
553
|
+
try {
|
|
554
|
+
return await scope.conn.copyIn(q, lines);
|
|
555
|
+
}
|
|
556
|
+
catch (error) {
|
|
557
|
+
throw mapConstraintError(registry, error);
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
journal(entry) {
|
|
561
|
+
root.top.journal?.push(entry);
|
|
562
|
+
},
|
|
563
|
+
markDirty(model, id, key) {
|
|
564
|
+
let byId = root.dirty.get(model);
|
|
565
|
+
if (byId === undefined) {
|
|
566
|
+
byId = new Map();
|
|
567
|
+
root.dirty.set(model, byId);
|
|
568
|
+
}
|
|
569
|
+
let fields = byId.get(id);
|
|
570
|
+
if (fields === undefined) {
|
|
571
|
+
fields = new Set();
|
|
572
|
+
byId.set(id, fields);
|
|
573
|
+
}
|
|
574
|
+
fields.add(key);
|
|
575
|
+
},
|
|
576
|
+
isDirty: (model, id, key) => dirtyOf(model, id)?.has(key) ?? false,
|
|
577
|
+
dirtyFields: (model, id) => {
|
|
578
|
+
const fields = dirtyOf(model, id);
|
|
579
|
+
return fields === undefined ? undefined : new Set(fields);
|
|
580
|
+
},
|
|
581
|
+
dirtyModels: () => [...root.dirty.keys()],
|
|
582
|
+
takeDirty(model) {
|
|
583
|
+
const byId = root.dirty.get(model);
|
|
584
|
+
root.dirty.delete(model);
|
|
585
|
+
return byId;
|
|
586
|
+
},
|
|
587
|
+
forget(model, id) {
|
|
588
|
+
root.cache.records.get(model)?.delete(id);
|
|
589
|
+
root.dirty.get(model)?.delete(id);
|
|
590
|
+
for (const sets of [root.triggers, root.toCompute, root.toCheck])
|
|
591
|
+
for (const set of sets.get(model)?.values() ?? [])
|
|
592
|
+
set.delete(id);
|
|
593
|
+
},
|
|
594
|
+
cachedValues: (model) => root.cache.records.get(model)?.values() ?? [],
|
|
595
|
+
sourceLang: env.sourceLang,
|
|
596
|
+
driver,
|
|
597
|
+
keys: env.keys,
|
|
598
|
+
auditRows: root.audit,
|
|
599
|
+
tx: root.tx,
|
|
600
|
+
flush: (model) => flushAll(internalsOf(env), model),
|
|
601
|
+
trigger(model, key, ids) {
|
|
602
|
+
if (ids.length === 0)
|
|
603
|
+
return;
|
|
604
|
+
addIds(root.triggers, model, key, ids);
|
|
605
|
+
for (const c of registry.compute.constraints(model, key))
|
|
606
|
+
addIds(root.toCheck, model, c.key, ids);
|
|
607
|
+
invalidateCached(self, model, key, ids);
|
|
608
|
+
},
|
|
609
|
+
markToCompute: (model, key, ids) => addIds(root.toCompute, model, key, ids),
|
|
610
|
+
takeTriggers() {
|
|
611
|
+
const taken = new Map(root.triggers);
|
|
612
|
+
root.triggers.clear();
|
|
613
|
+
return taken;
|
|
614
|
+
},
|
|
615
|
+
takeToCompute() {
|
|
616
|
+
const taken = new Map(root.toCompute);
|
|
617
|
+
root.toCompute.clear();
|
|
618
|
+
return taken;
|
|
619
|
+
},
|
|
620
|
+
hasPending: () => root.triggers.size > 0 || root.toCompute.size > 0,
|
|
621
|
+
takeToCheck() {
|
|
622
|
+
const taken = new Map(root.toCheck);
|
|
623
|
+
root.toCheck.clear();
|
|
624
|
+
return taken;
|
|
625
|
+
},
|
|
626
|
+
hasChecks: () => root.toCheck.size > 0,
|
|
627
|
+
nextVirtualId: () => root.virtual--,
|
|
628
|
+
compute: root.compute,
|
|
629
|
+
};
|
|
630
|
+
return self;
|
|
631
|
+
}
|
|
632
|
+
/** Reverts a rolled-back savepoint's cache changes, newest first. */
|
|
633
|
+
function undo(journal, root) {
|
|
634
|
+
const valuesOf = (model, id) => {
|
|
635
|
+
let byId = root.cache.records.get(model);
|
|
636
|
+
if (byId === undefined) {
|
|
637
|
+
byId = new Map();
|
|
638
|
+
root.cache.records.set(model, byId);
|
|
639
|
+
}
|
|
640
|
+
let values = byId.get(id);
|
|
641
|
+
if (values === undefined) {
|
|
642
|
+
values = new Map();
|
|
643
|
+
byId.set(id, values);
|
|
644
|
+
}
|
|
645
|
+
return values;
|
|
646
|
+
};
|
|
647
|
+
const setDirty = (model, id, key, dirty) => {
|
|
648
|
+
const byId = root.dirty.get(model);
|
|
649
|
+
if (dirty) {
|
|
650
|
+
if (byId === undefined)
|
|
651
|
+
root.dirty.set(model, new Map([[id, new Set([key])]]));
|
|
652
|
+
else {
|
|
653
|
+
const fields = byId.get(id);
|
|
654
|
+
if (fields === undefined)
|
|
655
|
+
byId.set(id, new Set([key]));
|
|
656
|
+
else
|
|
657
|
+
fields.add(key);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
byId?.get(id)?.delete(key);
|
|
662
|
+
if (byId?.get(id)?.size === 0)
|
|
663
|
+
byId.delete(id);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
for (let i = journal.length - 1; i >= 0; i--) {
|
|
667
|
+
const entry = journal[i];
|
|
668
|
+
if (entry === undefined)
|
|
669
|
+
continue;
|
|
670
|
+
switch (entry.kind) {
|
|
671
|
+
case 'value': {
|
|
672
|
+
const values = valuesOf(entry.model, entry.id);
|
|
673
|
+
if (entry.had)
|
|
674
|
+
values.set(entry.key, entry.prev);
|
|
675
|
+
else
|
|
676
|
+
values.delete(entry.key);
|
|
677
|
+
setDirty(entry.model, entry.id, entry.key, entry.wasDirty);
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
case 'created':
|
|
681
|
+
root.cache.records.get(entry.model)?.delete(entry.id);
|
|
682
|
+
root.dirty.get(entry.model)?.delete(entry.id);
|
|
683
|
+
break;
|
|
684
|
+
case 'deleted': {
|
|
685
|
+
const byId = root.cache.records.get(entry.model) ?? new Map();
|
|
686
|
+
root.cache.records.set(entry.model, byId);
|
|
687
|
+
byId.set(entry.id, new Map(entry.values));
|
|
688
|
+
if (entry.dirty !== undefined && entry.dirty.size > 0) {
|
|
689
|
+
const dirtyById = root.dirty.get(entry.model) ?? new Map();
|
|
690
|
+
root.dirty.set(entry.model, dirtyById);
|
|
691
|
+
dirtyById.set(entry.id, new Set(entry.dirty));
|
|
692
|
+
}
|
|
693
|
+
break;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
const defaultBackoff = (attempt) => Math.min(1_000, 25 * 2 ** attempt) * (0.5 + Math.random());
|
|
699
|
+
const defaultHookError = (error, phase) => {
|
|
700
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
701
|
+
process.emitWarning(`Shutro ${phase} hook failed: ${message}`, { code: 'SHUTRO_HOOK_FAILED' });
|
|
702
|
+
};
|
|
703
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
704
|
+
/**
|
|
705
|
+
* Standard sequences allocate in a short autonomous transaction on a second connection (RFC 0012 §7.3): with a pool
|
|
706
|
+
* of one, that waits forever for the connection the business transaction holds (feedback #21).
|
|
707
|
+
*/
|
|
708
|
+
function assertPoolFits(options) {
|
|
709
|
+
if (options.driver.max === undefined || options.driver.max > 1)
|
|
710
|
+
return;
|
|
711
|
+
const registry = options.registry;
|
|
712
|
+
const standard = [...(registry?.sequences.values() ?? [])]
|
|
713
|
+
.filter((d) => !d.gapless)
|
|
714
|
+
.map((d) => d.code);
|
|
715
|
+
if (standard.length === 0)
|
|
716
|
+
return;
|
|
717
|
+
throw new InvalidSequenceError(`Sequence(s) ${standard.join(', ')} need a pool of at least 2 connections; the driver has max: 1.`, 'Raise the driver max, or declare the sequences gapless: true (allocated inside the business transaction).');
|
|
718
|
+
}
|
|
719
|
+
function workerHost(shutro) {
|
|
720
|
+
return {
|
|
721
|
+
driver: shutro.driver,
|
|
722
|
+
run: (o, fn) => shutro.run(o, fn),
|
|
723
|
+
bootstrap: (o, fn) => shutro.bootstrap(o, fn),
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
/** Creates a {@link Shutro} instance on a driver (and a registry). */
|
|
727
|
+
export function createShutro(options) {
|
|
728
|
+
const attempts = options.retry?.attempts ?? 5;
|
|
729
|
+
const backoff = options.retry?.backoffMs ?? defaultBackoff;
|
|
730
|
+
assertPoolFits(options);
|
|
731
|
+
const runtime = {
|
|
732
|
+
als: new AsyncLocalStorage(),
|
|
733
|
+
onHookError: options.onHookError ?? defaultHookError,
|
|
734
|
+
registry: options.registry,
|
|
735
|
+
sourceLang: assertLang(options.sourceLang ?? 'en_US'),
|
|
736
|
+
driver: options.driver,
|
|
737
|
+
keys: options.keys,
|
|
738
|
+
inspector: options.inspector,
|
|
739
|
+
security: { enabled: options.runtimeSecurity === true, current: undefined, loading: undefined },
|
|
740
|
+
};
|
|
741
|
+
const NOW = compile(sqlTag `SELECT now() AS now`);
|
|
742
|
+
const reload = async () => {
|
|
743
|
+
runtime.security.current = await loadRuntimeSecurity(options.driver);
|
|
744
|
+
};
|
|
745
|
+
const ensureSecurity = async () => {
|
|
746
|
+
if (!runtime.security.enabled || runtime.security.current !== undefined)
|
|
747
|
+
return;
|
|
748
|
+
runtime.security.loading ??= (async () => {
|
|
749
|
+
await reload();
|
|
750
|
+
// Every process reloads when any of them commits a change.
|
|
751
|
+
await options.driver.listen(SECURITY_CHANNEL, () => {
|
|
752
|
+
reload().catch((error) => runtime.onHookError(error, 'afterCommit'));
|
|
753
|
+
});
|
|
754
|
+
})();
|
|
755
|
+
await runtime.security.loading;
|
|
756
|
+
};
|
|
757
|
+
return {
|
|
758
|
+
async run(runOptions, fn) {
|
|
759
|
+
await ensureSecurity();
|
|
760
|
+
let identity = resolveIdentity(runOptions);
|
|
761
|
+
if (options.identity !== undefined) {
|
|
762
|
+
const verified = await options.identity(identity.uid);
|
|
763
|
+
if (verified === null) {
|
|
764
|
+
throw new InvalidIdentityError(`User ${identity.uid} is unknown or disabled.`, 'The identity loader returned no record for this user: check the session, or reactivate the user.');
|
|
765
|
+
}
|
|
766
|
+
for (const company of identity.companyIds) {
|
|
767
|
+
if (!verified.companies.includes(company))
|
|
768
|
+
throw new CompanyNotAllowedError(company, verified.companies);
|
|
769
|
+
}
|
|
770
|
+
const asked = runOptions.groups;
|
|
771
|
+
if (asked !== undefined) {
|
|
772
|
+
const extra = asked.filter((g) => !verified.groups.includes(g));
|
|
773
|
+
if (extra.length > 0) {
|
|
774
|
+
throw new InvalidIdentityError(`User ${identity.uid} is not in group(s) ${extra.join(', ')}.`, 'Pass only groups the user has (or omit groups to use the loaded ones).');
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const askedGrants = runOptions.grants;
|
|
778
|
+
const extraGrants = (askedGrants ?? []).filter((g) => !(verified.grants ?? []).includes(g));
|
|
779
|
+
if (extraGrants.length > 0) {
|
|
780
|
+
throw new InvalidIdentityError(`User ${identity.uid} does not have the grant(s) ${extraGrants.join(', ')}.`, 'Pass only grants the user has (or omit grants to use the loaded ones).');
|
|
781
|
+
}
|
|
782
|
+
identity = {
|
|
783
|
+
...identity,
|
|
784
|
+
groups: Object.freeze([...(asked ?? verified.groups)]),
|
|
785
|
+
grants: Object.freeze([...(askedGrants ?? verified.grants ?? [])]),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
return execute(identity, runOptions, fn);
|
|
789
|
+
},
|
|
790
|
+
async bootstrap(bootstrapOptions, fn) {
|
|
791
|
+
const reason = assertReason(bootstrapOptions.reason);
|
|
792
|
+
const company = bootstrapOptions.company === undefined
|
|
793
|
+
? SYSTEM_UID
|
|
794
|
+
: resolveIdentity({ user: 1, company: bootstrapOptions.company }).companyId;
|
|
795
|
+
const identity = {
|
|
796
|
+
uid: SYSTEM_UID,
|
|
797
|
+
companyId: company,
|
|
798
|
+
companyIds: Object.freeze([company]),
|
|
799
|
+
lang: 'en_US',
|
|
800
|
+
tz: 'UTC',
|
|
801
|
+
reason,
|
|
802
|
+
groups: Object.freeze([]),
|
|
803
|
+
grants: Object.freeze([]),
|
|
804
|
+
};
|
|
805
|
+
return execute(identity, { user: 1, company: 1 }, (env) => env.asSuperuser({ reason }, fn));
|
|
806
|
+
},
|
|
807
|
+
registry: options.registry,
|
|
808
|
+
driver: options.driver,
|
|
809
|
+
reloadSecurity: reload,
|
|
810
|
+
subscribe(name, topic, handler, subscribeOptions) {
|
|
811
|
+
return subscribe(workerHost(this), name, topic, handler, subscribeOptions);
|
|
812
|
+
},
|
|
813
|
+
work(handlers, workOptions) {
|
|
814
|
+
return work(workerHost(this), handlers, workOptions);
|
|
815
|
+
},
|
|
816
|
+
currentEnv() {
|
|
817
|
+
const scope = runtime.als.getStore();
|
|
818
|
+
if (scope === undefined)
|
|
819
|
+
throw new NoEnvironmentError();
|
|
820
|
+
return scope.env;
|
|
821
|
+
},
|
|
822
|
+
};
|
|
823
|
+
async function execute(identity, runOptions, fn) {
|
|
824
|
+
{
|
|
825
|
+
const groups = options.registry === undefined
|
|
826
|
+
? new Set(identity.groups)
|
|
827
|
+
: closureWith(options.registry, runtime.security.current, identity.groups);
|
|
828
|
+
const administrator = options.registry !== undefined &&
|
|
829
|
+
isAdministratorWith(options.registry, runtime.security.current, groups);
|
|
830
|
+
const maxAttempts = runOptions.retry === false ? 1 : attempts;
|
|
831
|
+
for (let attempt = 1;; attempt++) {
|
|
832
|
+
let scope;
|
|
833
|
+
try {
|
|
834
|
+
const result = await options.driver.transaction({
|
|
835
|
+
isolation: 'repeatable read',
|
|
836
|
+
readOnly: runOptions.readOnly ?? false,
|
|
837
|
+
settings: {
|
|
838
|
+
'shutro.user_id': String(identity.uid),
|
|
839
|
+
'shutro.company_id': String(identity.companyId),
|
|
840
|
+
'shutro.company_ids': `{${identity.companyIds.join(',')}}`,
|
|
841
|
+
'shutro.groups': [...groups].join(','),
|
|
842
|
+
// Administrators pass every RLS policy, like superuser scopes (RFC 0014 §7.9).
|
|
843
|
+
'shutro.su': administrator ? '1' : '0',
|
|
844
|
+
timezone: 'UTC',
|
|
845
|
+
},
|
|
846
|
+
}, async (conn) => {
|
|
847
|
+
const [row] = await conn.query(NOW);
|
|
848
|
+
const root = {
|
|
849
|
+
top: undefined,
|
|
850
|
+
attempt,
|
|
851
|
+
now: row?.now ?? new Date(),
|
|
852
|
+
queries: 0,
|
|
853
|
+
cache: createRecordCache(),
|
|
854
|
+
dirty: new Map(),
|
|
855
|
+
triggers: new Map(),
|
|
856
|
+
toCompute: new Map(),
|
|
857
|
+
toCheck: new Map(),
|
|
858
|
+
audit: [],
|
|
859
|
+
tx: randomUUID(),
|
|
860
|
+
virtual: -1,
|
|
861
|
+
compute: {
|
|
862
|
+
recomputing: false,
|
|
863
|
+
computing: new Set(),
|
|
864
|
+
protected: new Map(),
|
|
865
|
+
previous: new Map(),
|
|
866
|
+
},
|
|
867
|
+
uid: identity.uid,
|
|
868
|
+
};
|
|
869
|
+
const s = {
|
|
870
|
+
root,
|
|
871
|
+
parent: undefined,
|
|
872
|
+
conn,
|
|
873
|
+
status: 'open',
|
|
874
|
+
env: undefined,
|
|
875
|
+
afterCommit: [],
|
|
876
|
+
onRollback: [],
|
|
877
|
+
journal: undefined,
|
|
878
|
+
};
|
|
879
|
+
root.top = s;
|
|
880
|
+
s.env = new Env({
|
|
881
|
+
...identity,
|
|
882
|
+
su: false,
|
|
883
|
+
flags: DEFAULT_FLAGS,
|
|
884
|
+
readOnly: runOptions.readOnly ?? false,
|
|
885
|
+
}, s, runtime);
|
|
886
|
+
scope = s;
|
|
887
|
+
return runtime.als.run(s, async () => {
|
|
888
|
+
const value = await fn(s.env);
|
|
889
|
+
await s.env.flush(); // pre-commit: the unit of work reaches the database
|
|
890
|
+
return value;
|
|
891
|
+
});
|
|
892
|
+
});
|
|
893
|
+
if (scope !== undefined) {
|
|
894
|
+
scope.status = 'committed';
|
|
895
|
+
await runHooks(scope.afterCommit, runtime, 'afterCommit');
|
|
896
|
+
}
|
|
897
|
+
return result;
|
|
898
|
+
}
|
|
899
|
+
catch (error) {
|
|
900
|
+
if (scope !== undefined) {
|
|
901
|
+
scope.status = 'rolled-back';
|
|
902
|
+
await runHooks(scope.onRollback, runtime, 'onRollback');
|
|
903
|
+
}
|
|
904
|
+
if (!isRetryable(error))
|
|
905
|
+
throw error;
|
|
906
|
+
if (attempt >= maxAttempts) {
|
|
907
|
+
if (maxAttempts === 1)
|
|
908
|
+
throw error;
|
|
909
|
+
throw new ConcurrentUpdateError(attempt, error);
|
|
910
|
+
}
|
|
911
|
+
await sleep(backoff(attempt + 1));
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|