shutro 0.0.0-stage → 0.1.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 +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -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 +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -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 +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -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/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -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 +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -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 +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -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 +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -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 +60 -0
- package/dist/core/money/fx.js +109 -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/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -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 +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -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 +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -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 +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -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 +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -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 +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -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 +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,631 @@
|
|
|
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 { compile, sql as sqlTag } from '../../sql/index.js';
|
|
6
|
+
import { CompanyNotAllowedError, ConcurrentUpdateError, FlagNotAllowedError, InvalidIdentityError, NoEnvironmentError, NoRegistryError, TransactionScopeError, } from '../errors.js';
|
|
7
|
+
import { createFx } from '../money/fx.js';
|
|
8
|
+
import { trackSuperuser } from '../recordset/audit.js';
|
|
9
|
+
import { invalidateCached } from '../recordset/compute.js';
|
|
10
|
+
import { companyCurrencyId, createRecordCache, currencyById, flushAll, modelRef, } from '../recordset/recordset.js';
|
|
11
|
+
import { assertAccess, canAccess, canField } from '../recordset/security.js';
|
|
12
|
+
import { mapConstraintError } from '../recordset/sqlErrors.js';
|
|
13
|
+
import { assertLang, assertReason, resolveIdentity, } from './identity.js';
|
|
14
|
+
import { assertTimeZone, calendarDateIn } from './time.js';
|
|
15
|
+
const DEFAULT_FLAGS = Object.freeze({
|
|
16
|
+
activeTest: true,
|
|
17
|
+
tracking: true,
|
|
18
|
+
checkCompany: true,
|
|
19
|
+
});
|
|
20
|
+
const internals = new WeakMap();
|
|
21
|
+
/** @internal */
|
|
22
|
+
export function internalsOf(env) {
|
|
23
|
+
const get = internals.get(env);
|
|
24
|
+
if (get === undefined)
|
|
25
|
+
throw new NoEnvironmentError();
|
|
26
|
+
return get();
|
|
27
|
+
}
|
|
28
|
+
async function runHooks(hooks, runtime, phase) {
|
|
29
|
+
for (const hook of hooks) {
|
|
30
|
+
try {
|
|
31
|
+
await hook();
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
runtime.onHookError(error, phase);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The environment (RFC 0003): who is acting, for which company, how, and in which transaction. Immutable; the
|
|
40
|
+
* `with*` methods return derived environments that share the transaction scope. `S` is the schema view of the
|
|
41
|
+
* registry (model name → model), which types `model()`.
|
|
42
|
+
*/
|
|
43
|
+
export class Env {
|
|
44
|
+
/** Id of the acting user. */
|
|
45
|
+
uid;
|
|
46
|
+
/** Current company id. */
|
|
47
|
+
companyId;
|
|
48
|
+
/** Allowed company ids (record-rule scope). */
|
|
49
|
+
companyIds;
|
|
50
|
+
lang;
|
|
51
|
+
/** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
|
|
52
|
+
sourceLang;
|
|
53
|
+
tz;
|
|
54
|
+
/** Superuser mode: only inside {@link asSuperuser}. */
|
|
55
|
+
su;
|
|
56
|
+
/** Reason for a job or superuser scope, when given. */
|
|
57
|
+
reason;
|
|
58
|
+
/** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
|
|
59
|
+
groups;
|
|
60
|
+
/** @internal Encryption keys. */
|
|
61
|
+
keys;
|
|
62
|
+
flags;
|
|
63
|
+
/** 1 for the first attempt of `run()`, 2+ for retries after a serialization failure or deadlock. */
|
|
64
|
+
attempt;
|
|
65
|
+
readOnly;
|
|
66
|
+
#scope;
|
|
67
|
+
#runtime;
|
|
68
|
+
/** @internal */
|
|
69
|
+
constructor(identity, scope, runtime) {
|
|
70
|
+
this.uid = identity.uid;
|
|
71
|
+
this.companyId = identity.companyId;
|
|
72
|
+
this.companyIds = identity.companyIds;
|
|
73
|
+
this.lang = identity.lang;
|
|
74
|
+
this.sourceLang = runtime.sourceLang;
|
|
75
|
+
this.groups =
|
|
76
|
+
runtime.registry === undefined
|
|
77
|
+
? new Set(identity.groups)
|
|
78
|
+
: runtime.registry.security.closure(identity.groups);
|
|
79
|
+
this.keys = runtime.keys;
|
|
80
|
+
this.tz = identity.tz;
|
|
81
|
+
this.su = identity.su;
|
|
82
|
+
this.reason = identity.reason;
|
|
83
|
+
this.flags = identity.flags;
|
|
84
|
+
this.readOnly = identity.readOnly;
|
|
85
|
+
this.attempt = scope.root.attempt;
|
|
86
|
+
this.#scope = scope;
|
|
87
|
+
this.#runtime = runtime;
|
|
88
|
+
internals.set(this, () => {
|
|
89
|
+
this.#assertUsable();
|
|
90
|
+
const registry = runtime.registry;
|
|
91
|
+
if (registry === undefined)
|
|
92
|
+
throw new NoRegistryError();
|
|
93
|
+
return scopeInternals(this, scope, registry, (q) => this.#query(q), runtime.driver);
|
|
94
|
+
});
|
|
95
|
+
Object.freeze(this);
|
|
96
|
+
}
|
|
97
|
+
/** An empty recordset of `name`: `search()` / `browse()` / `create()` start here (RFC 0004). */
|
|
98
|
+
model(name) {
|
|
99
|
+
if (this.#runtime.registry === undefined)
|
|
100
|
+
throw new NoRegistryError();
|
|
101
|
+
this.#assertUsable();
|
|
102
|
+
// The runtime is untyped over S; widening here is safe because it never reads S.
|
|
103
|
+
return modelRef(this, name);
|
|
104
|
+
}
|
|
105
|
+
/** What this environment may do (RFC 0014): for Kosh menus, export / import buttons and API guards. */
|
|
106
|
+
get access() {
|
|
107
|
+
const scope = internalsOf(this);
|
|
108
|
+
return {
|
|
109
|
+
can: (model, perm) => canAccess(scope, scope.registry.get(model).model, perm),
|
|
110
|
+
check: (model, perm) => assertAccess(scope, scope.registry.get(model).model, perm),
|
|
111
|
+
canField: (model, field, kind) => canField(scope, scope.registry.get(model).model, field, kind),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
|
|
115
|
+
get fx() {
|
|
116
|
+
const scope = internalsOf(this);
|
|
117
|
+
return createFx({
|
|
118
|
+
internals: scope,
|
|
119
|
+
currency: (id) => currencyById(scope, id),
|
|
120
|
+
companyCurrency: async (company) => currencyById(scope, await companyCurrencyId(scope, company)),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** The transaction timestamp (PostgreSQL `now()`), stable within an attempt. Returns a fresh `Date` each call. */
|
|
124
|
+
now() {
|
|
125
|
+
return new Date(this.#scope.root.now.getTime());
|
|
126
|
+
}
|
|
127
|
+
/** Today's calendar date (`'YYYY-MM-DD'`) in the environment's time zone. */
|
|
128
|
+
today() {
|
|
129
|
+
return calendarDateIn(this.#scope.root.now, this.tz);
|
|
130
|
+
}
|
|
131
|
+
/** Today's calendar date in another time zone. */
|
|
132
|
+
todayIn(tz) {
|
|
133
|
+
return calendarDateIn(this.#scope.root.now, tz);
|
|
134
|
+
}
|
|
135
|
+
/** Writes every pending change of the unit of work to the database now (RFC 0004 §7.6). */
|
|
136
|
+
async flush() {
|
|
137
|
+
if (this.#runtime.registry === undefined)
|
|
138
|
+
return;
|
|
139
|
+
await flushAll(internalsOf(this));
|
|
140
|
+
}
|
|
141
|
+
/** Statistics of the current attempt (query counts for N+1 assertions, RFC 0004 §7.9). */
|
|
142
|
+
stats() {
|
|
143
|
+
return { queries: this.#scope.root.queries };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Raw SQL in this transaction (RFC 0005 §7.8): values become parameters, identifiers go through `sql.id()`.
|
|
147
|
+
* Pending writes are flushed first. Rejects with {@link TransactionScopeError} when the scope has ended or
|
|
148
|
+
* another scope is active.
|
|
149
|
+
*/
|
|
150
|
+
sql(strings, ...values) {
|
|
151
|
+
return (async () => {
|
|
152
|
+
this.#assertUsable();
|
|
153
|
+
await this.flush();
|
|
154
|
+
return this.#query(compile(sqlTag(strings, ...values)));
|
|
155
|
+
})();
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Runs `fn` in a savepoint: its database work and its cache changes are undone if it throws, kept otherwise.
|
|
159
|
+
* Pending writes are flushed before the savepoint is released.
|
|
160
|
+
*/
|
|
161
|
+
async transaction(fn) {
|
|
162
|
+
this.#assertUsable();
|
|
163
|
+
const parent = this.#scope;
|
|
164
|
+
const root = parent.root;
|
|
165
|
+
let child;
|
|
166
|
+
const auditMark = root.audit.length;
|
|
167
|
+
try {
|
|
168
|
+
const result = await parent.conn.savepoint(async (conn) => {
|
|
169
|
+
const scope = {
|
|
170
|
+
root,
|
|
171
|
+
parent,
|
|
172
|
+
conn,
|
|
173
|
+
status: 'open',
|
|
174
|
+
env: this,
|
|
175
|
+
afterCommit: [],
|
|
176
|
+
onRollback: [],
|
|
177
|
+
journal: [],
|
|
178
|
+
};
|
|
179
|
+
scope.env = this.#derive({}, scope);
|
|
180
|
+
child = scope;
|
|
181
|
+
root.top = scope;
|
|
182
|
+
return this.#runtime.als.run(scope, async () => {
|
|
183
|
+
const value = await fn(scope.env);
|
|
184
|
+
await scope.env.flush();
|
|
185
|
+
return value;
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
if (child !== undefined) {
|
|
189
|
+
child.status = 'committed';
|
|
190
|
+
parent.afterCommit.push(...child.afterCommit);
|
|
191
|
+
parent.onRollback.push(...child.onRollback);
|
|
192
|
+
if (parent.journal !== undefined && child.journal !== undefined)
|
|
193
|
+
parent.journal.push(...child.journal);
|
|
194
|
+
}
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
if (child !== undefined) {
|
|
199
|
+
child.status = 'rolled-back';
|
|
200
|
+
if (child.journal !== undefined)
|
|
201
|
+
undo(child.journal, root);
|
|
202
|
+
root.audit.length = auditMark; // rows of a rolled-back savepoint never reach the trail
|
|
203
|
+
await runHooks(child.onRollback, this.#runtime, 'onRollback');
|
|
204
|
+
}
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
root.top = parent;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Registers work to run only after the outermost transaction commits (emails, webhooks, queue messages). */
|
|
212
|
+
afterCommit(hook) {
|
|
213
|
+
this.#assertUsable();
|
|
214
|
+
this.#scope.afterCommit.push(hook);
|
|
215
|
+
}
|
|
216
|
+
/** Registers work to run if this scope rolls back (cleanup of external resources). */
|
|
217
|
+
onRollback(hook) {
|
|
218
|
+
this.#assertUsable();
|
|
219
|
+
this.#scope.onRollback.push(hook);
|
|
220
|
+
}
|
|
221
|
+
/** The same scope with another current company. Must be allowed unless `su`. @throws {CompanyNotAllowedError} */
|
|
222
|
+
withCompany(company) {
|
|
223
|
+
if (!this.su && !this.companyIds.includes(company))
|
|
224
|
+
throw new CompanyNotAllowedError(company, this.companyIds);
|
|
225
|
+
const companyIds = this.companyIds.includes(company)
|
|
226
|
+
? this.companyIds
|
|
227
|
+
: Object.freeze([...this.companyIds, company]);
|
|
228
|
+
return this.#derive({ companyId: company, companyIds });
|
|
229
|
+
}
|
|
230
|
+
/** The same scope with another language. */
|
|
231
|
+
withLang(lang) {
|
|
232
|
+
return this.#derive({ lang: assertLang(lang) });
|
|
233
|
+
}
|
|
234
|
+
/** The same scope with another time zone. */
|
|
235
|
+
withTz(tz) {
|
|
236
|
+
assertTimeZone(tz);
|
|
237
|
+
return this.#derive({ tz });
|
|
238
|
+
}
|
|
239
|
+
/** The same scope with some flags changed. `checkCompany: false` needs `su`. @throws {FlagNotAllowedError} */
|
|
240
|
+
withFlags(flags) {
|
|
241
|
+
if (flags.checkCompany === false && !this.su)
|
|
242
|
+
throw new FlagNotAllowedError('checkCompany');
|
|
243
|
+
return this.#derive({ flags: Object.freeze({ ...this.flags, ...flags }) });
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
|
|
247
|
+
* returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
|
|
248
|
+
*/
|
|
249
|
+
async asSuperuser(options, fn) {
|
|
250
|
+
const reason = assertReason(options.reason);
|
|
251
|
+
this.#assertUsable();
|
|
252
|
+
const su = this.#derive({ su: true, reason });
|
|
253
|
+
if (this.#runtime.registry !== undefined)
|
|
254
|
+
trackSuperuser(internalsOf(su), reason);
|
|
255
|
+
// RLS policies read shutro.su: the setting is scoped to the call (RFC 0014 §7.5).
|
|
256
|
+
const wasSu = this.su;
|
|
257
|
+
if (!wasSu)
|
|
258
|
+
await this.#query(compile(sqlTag `SELECT set_config(${'shutro.su'}, ${'1'}, true)`));
|
|
259
|
+
try {
|
|
260
|
+
return await fn(su);
|
|
261
|
+
}
|
|
262
|
+
finally {
|
|
263
|
+
if (!wasSu)
|
|
264
|
+
await this.#query(compile(sqlTag `SELECT set_config(${'shutro.su'}, ${'0'}, true)`));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
async #query(query) {
|
|
268
|
+
this.#scope.root.queries++;
|
|
269
|
+
const inspector = this.#runtime.inspector;
|
|
270
|
+
if (inspector === undefined)
|
|
271
|
+
return this.#scope.conn.query(query);
|
|
272
|
+
const started = performance.now();
|
|
273
|
+
const base = { sql: query.text, params: query.params, tx: this.#scope.root.tx, uid: this.uid };
|
|
274
|
+
try {
|
|
275
|
+
const rows = await this.#scope.conn.query(query);
|
|
276
|
+
inspector.record({ ...base, ms: performance.now() - started });
|
|
277
|
+
return rows;
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
inspector.record({
|
|
281
|
+
...base,
|
|
282
|
+
ms: performance.now() - started,
|
|
283
|
+
error: error instanceof Error ? error.message : String(error),
|
|
284
|
+
});
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
#derive(changes, scope = this.#scope) {
|
|
289
|
+
return new _a({
|
|
290
|
+
uid: this.uid,
|
|
291
|
+
companyId: this.companyId,
|
|
292
|
+
companyIds: this.companyIds,
|
|
293
|
+
lang: this.lang,
|
|
294
|
+
tz: this.tz,
|
|
295
|
+
reason: this.reason,
|
|
296
|
+
groups: [...this.groups],
|
|
297
|
+
su: this.su,
|
|
298
|
+
flags: this.flags,
|
|
299
|
+
readOnly: this.readOnly,
|
|
300
|
+
...changes,
|
|
301
|
+
}, scope, this.#runtime);
|
|
302
|
+
}
|
|
303
|
+
#assertUsable() {
|
|
304
|
+
const scope = this.#scope;
|
|
305
|
+
if (scope.status !== 'open') {
|
|
306
|
+
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.');
|
|
307
|
+
}
|
|
308
|
+
if (scope.root.top !== scope) {
|
|
309
|
+
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.');
|
|
310
|
+
}
|
|
311
|
+
const active = this.#runtime.als.getStore();
|
|
312
|
+
if (active !== undefined && active.root !== scope.root) {
|
|
313
|
+
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().');
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
_a = Env;
|
|
318
|
+
function scopeInternals(env, scope, registry, query, driver) {
|
|
319
|
+
const root = scope.root;
|
|
320
|
+
const dirtyOf = (model, id) => root.dirty.get(model)?.get(id);
|
|
321
|
+
const addIds = (sets, model, key, ids) => {
|
|
322
|
+
let byKey = sets.get(model);
|
|
323
|
+
if (byKey === undefined) {
|
|
324
|
+
byKey = new Map();
|
|
325
|
+
sets.set(model, byKey);
|
|
326
|
+
}
|
|
327
|
+
let set = byKey.get(key);
|
|
328
|
+
if (set === undefined) {
|
|
329
|
+
set = new Set();
|
|
330
|
+
byKey.set(key, set);
|
|
331
|
+
}
|
|
332
|
+
for (const id of ids)
|
|
333
|
+
set.add(id);
|
|
334
|
+
};
|
|
335
|
+
const self = {
|
|
336
|
+
env,
|
|
337
|
+
registry,
|
|
338
|
+
cache: root.cache,
|
|
339
|
+
uid: root.uid,
|
|
340
|
+
now: root.now,
|
|
341
|
+
query: async (q) => {
|
|
342
|
+
try {
|
|
343
|
+
return await query(q);
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
throw mapConstraintError(registry, error);
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
copyIn: async (q, lines) => {
|
|
350
|
+
root.queries++;
|
|
351
|
+
try {
|
|
352
|
+
return await scope.conn.copyIn(q, lines);
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
throw mapConstraintError(registry, error);
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
journal(entry) {
|
|
359
|
+
root.top.journal?.push(entry);
|
|
360
|
+
},
|
|
361
|
+
markDirty(model, id, key) {
|
|
362
|
+
let byId = root.dirty.get(model);
|
|
363
|
+
if (byId === undefined) {
|
|
364
|
+
byId = new Map();
|
|
365
|
+
root.dirty.set(model, byId);
|
|
366
|
+
}
|
|
367
|
+
let fields = byId.get(id);
|
|
368
|
+
if (fields === undefined) {
|
|
369
|
+
fields = new Set();
|
|
370
|
+
byId.set(id, fields);
|
|
371
|
+
}
|
|
372
|
+
fields.add(key);
|
|
373
|
+
},
|
|
374
|
+
isDirty: (model, id, key) => dirtyOf(model, id)?.has(key) ?? false,
|
|
375
|
+
dirtyFields: (model, id) => {
|
|
376
|
+
const fields = dirtyOf(model, id);
|
|
377
|
+
return fields === undefined ? undefined : new Set(fields);
|
|
378
|
+
},
|
|
379
|
+
dirtyModels: () => [...root.dirty.keys()],
|
|
380
|
+
takeDirty(model) {
|
|
381
|
+
const byId = root.dirty.get(model);
|
|
382
|
+
root.dirty.delete(model);
|
|
383
|
+
return byId;
|
|
384
|
+
},
|
|
385
|
+
forget(model, id) {
|
|
386
|
+
root.cache.records.get(model)?.delete(id);
|
|
387
|
+
root.dirty.get(model)?.delete(id);
|
|
388
|
+
for (const sets of [root.triggers, root.toCompute, root.toCheck])
|
|
389
|
+
for (const set of sets.get(model)?.values() ?? [])
|
|
390
|
+
set.delete(id);
|
|
391
|
+
},
|
|
392
|
+
cachedValues: (model) => root.cache.records.get(model)?.values() ?? [],
|
|
393
|
+
sourceLang: env.sourceLang,
|
|
394
|
+
driver,
|
|
395
|
+
keys: env.keys,
|
|
396
|
+
auditRows: root.audit,
|
|
397
|
+
tx: root.tx,
|
|
398
|
+
flush: (model) => flushAll(internalsOf(env), model),
|
|
399
|
+
trigger(model, key, ids) {
|
|
400
|
+
if (ids.length === 0)
|
|
401
|
+
return;
|
|
402
|
+
addIds(root.triggers, model, key, ids);
|
|
403
|
+
for (const c of registry.compute.constraints(model, key))
|
|
404
|
+
addIds(root.toCheck, model, c.key, ids);
|
|
405
|
+
invalidateCached(self, model, key, ids);
|
|
406
|
+
},
|
|
407
|
+
markToCompute: (model, key, ids) => addIds(root.toCompute, model, key, ids),
|
|
408
|
+
takeTriggers() {
|
|
409
|
+
const taken = new Map(root.triggers);
|
|
410
|
+
root.triggers.clear();
|
|
411
|
+
return taken;
|
|
412
|
+
},
|
|
413
|
+
takeToCompute() {
|
|
414
|
+
const taken = new Map(root.toCompute);
|
|
415
|
+
root.toCompute.clear();
|
|
416
|
+
return taken;
|
|
417
|
+
},
|
|
418
|
+
hasPending: () => root.triggers.size > 0 || root.toCompute.size > 0,
|
|
419
|
+
takeToCheck() {
|
|
420
|
+
const taken = new Map(root.toCheck);
|
|
421
|
+
root.toCheck.clear();
|
|
422
|
+
return taken;
|
|
423
|
+
},
|
|
424
|
+
hasChecks: () => root.toCheck.size > 0,
|
|
425
|
+
nextVirtualId: () => root.virtual--,
|
|
426
|
+
compute: root.compute,
|
|
427
|
+
};
|
|
428
|
+
return self;
|
|
429
|
+
}
|
|
430
|
+
/** Reverts a rolled-back savepoint's cache changes, newest first. */
|
|
431
|
+
function undo(journal, root) {
|
|
432
|
+
const valuesOf = (model, id) => {
|
|
433
|
+
let byId = root.cache.records.get(model);
|
|
434
|
+
if (byId === undefined) {
|
|
435
|
+
byId = new Map();
|
|
436
|
+
root.cache.records.set(model, byId);
|
|
437
|
+
}
|
|
438
|
+
let values = byId.get(id);
|
|
439
|
+
if (values === undefined) {
|
|
440
|
+
values = new Map();
|
|
441
|
+
byId.set(id, values);
|
|
442
|
+
}
|
|
443
|
+
return values;
|
|
444
|
+
};
|
|
445
|
+
const setDirty = (model, id, key, dirty) => {
|
|
446
|
+
const byId = root.dirty.get(model);
|
|
447
|
+
if (dirty) {
|
|
448
|
+
if (byId === undefined)
|
|
449
|
+
root.dirty.set(model, new Map([[id, new Set([key])]]));
|
|
450
|
+
else {
|
|
451
|
+
const fields = byId.get(id);
|
|
452
|
+
if (fields === undefined)
|
|
453
|
+
byId.set(id, new Set([key]));
|
|
454
|
+
else
|
|
455
|
+
fields.add(key);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
else {
|
|
459
|
+
byId?.get(id)?.delete(key);
|
|
460
|
+
if (byId?.get(id)?.size === 0)
|
|
461
|
+
byId.delete(id);
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
for (let i = journal.length - 1; i >= 0; i--) {
|
|
465
|
+
const entry = journal[i];
|
|
466
|
+
if (entry === undefined)
|
|
467
|
+
continue;
|
|
468
|
+
switch (entry.kind) {
|
|
469
|
+
case 'value': {
|
|
470
|
+
const values = valuesOf(entry.model, entry.id);
|
|
471
|
+
if (entry.had)
|
|
472
|
+
values.set(entry.key, entry.prev);
|
|
473
|
+
else
|
|
474
|
+
values.delete(entry.key);
|
|
475
|
+
setDirty(entry.model, entry.id, entry.key, entry.wasDirty);
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
case 'created':
|
|
479
|
+
root.cache.records.get(entry.model)?.delete(entry.id);
|
|
480
|
+
root.dirty.get(entry.model)?.delete(entry.id);
|
|
481
|
+
break;
|
|
482
|
+
case 'deleted': {
|
|
483
|
+
const byId = root.cache.records.get(entry.model) ?? new Map();
|
|
484
|
+
root.cache.records.set(entry.model, byId);
|
|
485
|
+
byId.set(entry.id, new Map(entry.values));
|
|
486
|
+
if (entry.dirty !== undefined && entry.dirty.size > 0) {
|
|
487
|
+
const dirtyById = root.dirty.get(entry.model) ?? new Map();
|
|
488
|
+
root.dirty.set(entry.model, dirtyById);
|
|
489
|
+
dirtyById.set(entry.id, new Set(entry.dirty));
|
|
490
|
+
}
|
|
491
|
+
break;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const defaultBackoff = (attempt) => Math.min(1_000, 25 * 2 ** attempt) * (0.5 + Math.random());
|
|
497
|
+
const defaultHookError = (error, phase) => {
|
|
498
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
499
|
+
process.emitWarning(`Shutro ${phase} hook failed: ${message}`, { code: 'SHUTRO_HOOK_FAILED' });
|
|
500
|
+
};
|
|
501
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
502
|
+
/** Creates a {@link Shutro} instance on a driver (and a registry). */
|
|
503
|
+
export function createShutro(options) {
|
|
504
|
+
const attempts = options.retry?.attempts ?? 5;
|
|
505
|
+
const backoff = options.retry?.backoffMs ?? defaultBackoff;
|
|
506
|
+
const runtime = {
|
|
507
|
+
als: new AsyncLocalStorage(),
|
|
508
|
+
onHookError: options.onHookError ?? defaultHookError,
|
|
509
|
+
registry: options.registry,
|
|
510
|
+
sourceLang: assertLang(options.sourceLang ?? 'en_US'),
|
|
511
|
+
driver: options.driver,
|
|
512
|
+
keys: options.keys,
|
|
513
|
+
inspector: options.inspector,
|
|
514
|
+
};
|
|
515
|
+
const NOW = compile(sqlTag `SELECT now() AS now`);
|
|
516
|
+
return {
|
|
517
|
+
async run(runOptions, fn) {
|
|
518
|
+
let identity = resolveIdentity(runOptions);
|
|
519
|
+
if (options.identity !== undefined) {
|
|
520
|
+
const verified = await options.identity(identity.uid);
|
|
521
|
+
if (verified === null) {
|
|
522
|
+
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.');
|
|
523
|
+
}
|
|
524
|
+
for (const company of identity.companyIds) {
|
|
525
|
+
if (!verified.companies.includes(company))
|
|
526
|
+
throw new CompanyNotAllowedError(company, verified.companies);
|
|
527
|
+
}
|
|
528
|
+
const asked = runOptions.groups;
|
|
529
|
+
if (asked !== undefined) {
|
|
530
|
+
const extra = asked.filter((g) => !verified.groups.includes(g));
|
|
531
|
+
if (extra.length > 0) {
|
|
532
|
+
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).');
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
identity = { ...identity, groups: Object.freeze([...(asked ?? verified.groups)]) };
|
|
536
|
+
}
|
|
537
|
+
const groups = options.registry === undefined
|
|
538
|
+
? new Set(identity.groups)
|
|
539
|
+
: options.registry.security.closure(identity.groups);
|
|
540
|
+
const maxAttempts = runOptions.retry === false ? 1 : attempts;
|
|
541
|
+
for (let attempt = 1;; attempt++) {
|
|
542
|
+
let scope;
|
|
543
|
+
try {
|
|
544
|
+
const result = await options.driver.transaction({
|
|
545
|
+
isolation: 'repeatable read',
|
|
546
|
+
readOnly: runOptions.readOnly ?? false,
|
|
547
|
+
settings: {
|
|
548
|
+
'shutro.user_id': String(identity.uid),
|
|
549
|
+
'shutro.company_id': String(identity.companyId),
|
|
550
|
+
'shutro.company_ids': `{${identity.companyIds.join(',')}}`,
|
|
551
|
+
'shutro.groups': [...groups].join(','),
|
|
552
|
+
'shutro.su': '0',
|
|
553
|
+
timezone: 'UTC',
|
|
554
|
+
},
|
|
555
|
+
}, async (conn) => {
|
|
556
|
+
const [row] = await conn.query(NOW);
|
|
557
|
+
const root = {
|
|
558
|
+
top: undefined,
|
|
559
|
+
attempt,
|
|
560
|
+
now: row?.now ?? new Date(),
|
|
561
|
+
queries: 0,
|
|
562
|
+
cache: createRecordCache(),
|
|
563
|
+
dirty: new Map(),
|
|
564
|
+
triggers: new Map(),
|
|
565
|
+
toCompute: new Map(),
|
|
566
|
+
toCheck: new Map(),
|
|
567
|
+
audit: [],
|
|
568
|
+
tx: randomUUID(),
|
|
569
|
+
virtual: -1,
|
|
570
|
+
compute: {
|
|
571
|
+
recomputing: false,
|
|
572
|
+
computing: new Set(),
|
|
573
|
+
protected: new Map(),
|
|
574
|
+
previous: new Map(),
|
|
575
|
+
},
|
|
576
|
+
uid: identity.uid,
|
|
577
|
+
};
|
|
578
|
+
const s = {
|
|
579
|
+
root,
|
|
580
|
+
parent: undefined,
|
|
581
|
+
conn,
|
|
582
|
+
status: 'open',
|
|
583
|
+
env: undefined,
|
|
584
|
+
afterCommit: [],
|
|
585
|
+
onRollback: [],
|
|
586
|
+
journal: undefined,
|
|
587
|
+
};
|
|
588
|
+
root.top = s;
|
|
589
|
+
s.env = new Env({
|
|
590
|
+
...identity,
|
|
591
|
+
su: false,
|
|
592
|
+
flags: DEFAULT_FLAGS,
|
|
593
|
+
readOnly: runOptions.readOnly ?? false,
|
|
594
|
+
}, s, runtime);
|
|
595
|
+
scope = s;
|
|
596
|
+
return runtime.als.run(s, async () => {
|
|
597
|
+
const value = await fn(s.env);
|
|
598
|
+
await s.env.flush(); // pre-commit: the unit of work reaches the database
|
|
599
|
+
return value;
|
|
600
|
+
});
|
|
601
|
+
});
|
|
602
|
+
if (scope !== undefined) {
|
|
603
|
+
scope.status = 'committed';
|
|
604
|
+
await runHooks(scope.afterCommit, runtime, 'afterCommit');
|
|
605
|
+
}
|
|
606
|
+
return result;
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
if (scope !== undefined) {
|
|
610
|
+
scope.status = 'rolled-back';
|
|
611
|
+
await runHooks(scope.onRollback, runtime, 'onRollback');
|
|
612
|
+
}
|
|
613
|
+
if (!isRetryable(error))
|
|
614
|
+
throw error;
|
|
615
|
+
if (attempt >= maxAttempts) {
|
|
616
|
+
if (maxAttempts === 1)
|
|
617
|
+
throw error;
|
|
618
|
+
throw new ConcurrentUpdateError(attempt, error);
|
|
619
|
+
}
|
|
620
|
+
await sleep(backoff(attempt + 1));
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
},
|
|
624
|
+
currentEnv() {
|
|
625
|
+
const scope = runtime.als.getStore();
|
|
626
|
+
if (scope === undefined)
|
|
627
|
+
throw new NoEnvironmentError();
|
|
628
|
+
return scope.env;
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Who is acting, for which company, and how (RFC 0003 §7.1). */
|
|
2
|
+
export interface Identity {
|
|
3
|
+
/** Id of the acting `res.users` record. */
|
|
4
|
+
readonly user: number;
|
|
5
|
+
/** Current company: defaults, sequences, currency. Must be one of `companies`. */
|
|
6
|
+
readonly company: number;
|
|
7
|
+
/** Allowed (selected) companies: the record-rule scope. Defaults to `[company]`. */
|
|
8
|
+
readonly companies?: readonly number[];
|
|
9
|
+
/** Language code such as `'bn_BD'`. Defaults to `'en_US'`. */
|
|
10
|
+
readonly lang?: string;
|
|
11
|
+
/** IANA time zone. Defaults to `'UTC'`. */
|
|
12
|
+
readonly tz?: string;
|
|
13
|
+
/** Why this unit of work runs, for jobs and system tasks (audited). */
|
|
14
|
+
readonly reason?: string;
|
|
15
|
+
/** Security group codes of the user (RFC 0014 §7.1); implied groups are added by the registry. */
|
|
16
|
+
readonly groups?: readonly string[];
|
|
17
|
+
}
|
|
18
|
+
/** A validated identity with defaults applied. */
|
|
19
|
+
export interface ResolvedIdentity {
|
|
20
|
+
readonly uid: number;
|
|
21
|
+
readonly companyId: number;
|
|
22
|
+
readonly companyIds: readonly number[];
|
|
23
|
+
readonly lang: string;
|
|
24
|
+
readonly tz: string;
|
|
25
|
+
readonly reason: string | undefined;
|
|
26
|
+
readonly groups: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
/** Validates a language code (`'en_US'`, `'bn_BD'`). @throws {InvalidIdentityError} */
|
|
29
|
+
export declare function assertLang(lang: string): string;
|
|
30
|
+
/** Validates `reason` for superuser scopes and jobs. @throws {InvalidIdentityError} */
|
|
31
|
+
export declare function assertReason(reason: string): string;
|
|
32
|
+
/** Applies defaults and validates. @throws {InvalidIdentityError} */
|
|
33
|
+
export declare function resolveIdentity(identity: Identity): ResolvedIdentity;
|