shutro 0.1.0 → 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/README.md +12 -2
- package/dist/audit/index.d.ts +3 -1
- package/dist/audit/index.js +2 -0
- package/dist/cli/cli.js +17 -2
- package/dist/cli/config.js +2 -0
- package/dist/cli/generate/generate.js +2 -0
- package/dist/cli/generate/render.js +57 -8
- package/dist/cli/init.js +4 -4
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -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 +175 -2
- package/dist/core/env/env.js +304 -19
- package/dist/core/env/identity.d.ts +10 -0
- package/dist/core/env/identity.js +16 -0
- package/dist/core/errors.d.ts +15 -1
- package/dist/core/errors.js +21 -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 +17 -9
- package/dist/core/index.js +11 -3
- package/dist/core/model/field.d.ts +33 -0
- package/dist/core/model/field.js +64 -1
- package/dist/core/model/generated.d.ts +4 -2
- package/dist/core/model/model.d.ts +40 -0
- package/dist/core/model/model.js +28 -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/fx.d.ts +10 -2
- package/dist/core/money/fx.js +17 -2
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +9 -1
- package/dist/core/recordset/audit.js +59 -2
- package/dist/core/recordset/compute.d.ts +2 -0
- package/dist/core/recordset/compute.js +11 -2
- package/dist/core/recordset/domain.d.ts +4 -0
- package/dist/core/recordset/domain.js +74 -2
- package/dist/core/recordset/onchange.js +70 -37
- package/dist/core/recordset/recordset.d.ts +10 -1
- package/dist/core/recordset/recordset.js +80 -14
- package/dist/core/recordset/security.d.ts +15 -1
- package/dist/core/recordset/security.js +95 -10
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/transitions.js +4 -1
- package/dist/core/recordset/types.d.ts +131 -12
- package/dist/core/recordset/values.d.ts +6 -0
- package/dist/core/recordset/values.js +34 -4
- package/dist/core/recordset/writes.d.ts +6 -1
- package/dist/core/recordset/writes.js +217 -12
- package/dist/core/registry/ddl.d.ts +9 -0
- package/dist/core/registry/ddl.js +49 -2
- package/dist/core/registry/module.d.ts +10 -1
- package/dist/core/registry/module.js +2 -0
- package/dist/core/registry/registry.d.ts +29 -4
- package/dist/core/registry/registry.js +100 -5
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +2 -0
- package/dist/driver-pg/driver.js +1 -0
- package/dist/migrate/schema.js +40 -2
- package/dist/security/index.d.ts +24 -0
- package/dist/security/index.js +16 -0
- package/dist/sql/tag.d.ts +5 -0
- package/dist/sql/tag.js +29 -1
- package/package.json +1 -1
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loading module data and resolving external ids (RFC 0017 §4). Each module's data loads in one system transaction
|
|
3
|
+
* (`shutro.bootstrap`), in module load order, through the ORM: computes, sequences, constraints and the audit trail
|
|
4
|
+
* apply as for any create or write.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { compile, sql } from '../../sql/index.js';
|
|
8
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
9
|
+
import { internalsOf } from '../env/env.js';
|
|
10
|
+
import { UnknownExternalIdError } from '../errors.js';
|
|
11
|
+
import { fullId, isRef } from './data.js';
|
|
12
|
+
/** The external-id table (RFC 0017 §4). */
|
|
13
|
+
export const EXTERNAL_ID_TABLE = 'shutro_external_id';
|
|
14
|
+
const DDL = [
|
|
15
|
+
`CREATE TABLE IF NOT EXISTS "${EXTERNAL_ID_TABLE}" ("module" text NOT NULL, "name" text NOT NULL, "model" text NOT NULL, "res_id" bigint NOT NULL, "noupdate" boolean NOT NULL DEFAULT false, "checksum" text, "updated_at" timestamp with time zone NOT NULL DEFAULT now(), PRIMARY KEY ("module", "name"))`,
|
|
16
|
+
`CREATE INDEX IF NOT EXISTS "${EXTERNAL_ID_TABLE}_model_res_id_idx" ON "${EXTERNAL_ID_TABLE}" ("model", "res_id")`,
|
|
17
|
+
];
|
|
18
|
+
/** Statements that create the external-id table (for migrations or tests). */
|
|
19
|
+
export function externalIdTableStatements() {
|
|
20
|
+
return DDL.map((text) => ({ text, params: [] }));
|
|
21
|
+
}
|
|
22
|
+
async function tableExists(internals) {
|
|
23
|
+
const [row] = await internals.query(compile(sql `SELECT to_regclass(${EXTERNAL_ID_TABLE}) IS NOT NULL AS present`));
|
|
24
|
+
return row?.present === true;
|
|
25
|
+
}
|
|
26
|
+
const lookups = new WeakMap();
|
|
27
|
+
function split(id) {
|
|
28
|
+
const dot = id.indexOf('.');
|
|
29
|
+
return [id.slice(0, dot), id.slice(dot + 1)];
|
|
30
|
+
}
|
|
31
|
+
/** The record id of external id `id` (cached per transaction). @throws {UnknownExternalIdError} */
|
|
32
|
+
export async function resolveExternalId(internals, id, model) {
|
|
33
|
+
let cache = lookups.get(internals.cache);
|
|
34
|
+
if (cache === undefined) {
|
|
35
|
+
cache = new Map();
|
|
36
|
+
lookups.set(internals.cache, cache);
|
|
37
|
+
}
|
|
38
|
+
let found = cache.get(id);
|
|
39
|
+
if (found === undefined) {
|
|
40
|
+
const [module, name] = split(id);
|
|
41
|
+
const rows = name === '' || !(await tableExists(internals))
|
|
42
|
+
? []
|
|
43
|
+
: await internals.query(compile(sql `SELECT model, res_id FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module} AND name = ${name}`));
|
|
44
|
+
const row = rows[0];
|
|
45
|
+
if (row === undefined)
|
|
46
|
+
throw new UnknownExternalIdError(`The external id '${id}' does not exist.`, 'Check the spelling, and that the module shipping it is installed and its data loaded (shutro migrate apply).');
|
|
47
|
+
found = { model: row.model, id: Number(row.res_id) };
|
|
48
|
+
cache.set(id, found);
|
|
49
|
+
}
|
|
50
|
+
if (model !== undefined && found.model !== model)
|
|
51
|
+
throw new UnknownExternalIdError(`The external id '${id}' is a ${found.model}, not a ${model}.`, 'Use the model of the record.');
|
|
52
|
+
return found.id;
|
|
53
|
+
}
|
|
54
|
+
/** `env.refId(model, id)`. */
|
|
55
|
+
export async function refId(env, model, id) {
|
|
56
|
+
return (await resolveExternalId(internalsOf(env), id, model));
|
|
57
|
+
}
|
|
58
|
+
/** A stable text of declared values for checksums: refs by id, Decimals as strings, sorted keys. */
|
|
59
|
+
function stable(value) {
|
|
60
|
+
if (isRef(value))
|
|
61
|
+
return { $ref: value.id };
|
|
62
|
+
if (DecimalJs.isDecimal(value))
|
|
63
|
+
return { $decimal: value.toString() };
|
|
64
|
+
if (value instanceof Date)
|
|
65
|
+
return { $date: value.toISOString() };
|
|
66
|
+
if (Array.isArray(value))
|
|
67
|
+
return value.map(stable);
|
|
68
|
+
if (typeof value === 'object' && value !== null)
|
|
69
|
+
return Object.fromEntries(Object.keys(value)
|
|
70
|
+
.sort()
|
|
71
|
+
.map((k) => [k, stable(value[k])]));
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function checksumOf(record) {
|
|
75
|
+
return createHash('sha256')
|
|
76
|
+
.update(JSON.stringify(stable(record.values)))
|
|
77
|
+
.digest('hex')
|
|
78
|
+
.slice(0, 32);
|
|
79
|
+
}
|
|
80
|
+
async function resolveValues(internals, value) {
|
|
81
|
+
if (isRef(value))
|
|
82
|
+
return resolveExternalId(internals, value.id, value.model);
|
|
83
|
+
if (Array.isArray(value))
|
|
84
|
+
return Promise.all(value.map((v) => resolveValues(internals, v)));
|
|
85
|
+
if (typeof value === 'object' &&
|
|
86
|
+
value !== null &&
|
|
87
|
+
Object.getPrototypeOf(value) === Object.prototype) {
|
|
88
|
+
const out = {};
|
|
89
|
+
for (const [k, v] of Object.entries(value))
|
|
90
|
+
out[k] = await resolveValues(internals, v);
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
/** Values for an update: x2many `create` commands are left out (they would add children at every load). */
|
|
96
|
+
function forUpdate(values) {
|
|
97
|
+
const out = {};
|
|
98
|
+
for (const [k, v] of Object.entries(values)) {
|
|
99
|
+
if (typeof v === 'object' && v !== null && !Array.isArray(v) && 'create' in v) {
|
|
100
|
+
const { create: _create, ...rest } = v;
|
|
101
|
+
if (Object.keys(rest).length > 0)
|
|
102
|
+
out[k] = rest;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
out[k] = v;
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Loads the data of every installed module (RFC 0017 §4), idempotently: new ids are created, changed records
|
|
111
|
+
* updated, unchanged ones skipped (checksums), `noupdate` records left alone once they exist, and ids no longer
|
|
112
|
+
* declared deleted with their records. Run by `shutro migrate apply` after the schema.
|
|
113
|
+
*/
|
|
114
|
+
export async function loadData(shutro, options = {}) {
|
|
115
|
+
const results = [];
|
|
116
|
+
const registry = shutro.registry;
|
|
117
|
+
if (registry === undefined)
|
|
118
|
+
throw new UnknownExternalIdError('loadData() needs a Shutro instance with a registry.', 'Pass registry to createShutro.');
|
|
119
|
+
for (const module of registry.modules) {
|
|
120
|
+
if (options.modules !== undefined && !options.modules.includes(module.name))
|
|
121
|
+
continue;
|
|
122
|
+
// Modules without data still run: ids a previous version declared are deleted.
|
|
123
|
+
const result = await shutro.bootstrap({
|
|
124
|
+
reason: `data: ${module.name}`,
|
|
125
|
+
...(options.company === undefined ? {} : { company: options.company }),
|
|
126
|
+
}, async (env) => loadModule(env, module.name, module.data));
|
|
127
|
+
if (result.created.length +
|
|
128
|
+
result.updated.length +
|
|
129
|
+
result.deleted.length +
|
|
130
|
+
result.unchanged +
|
|
131
|
+
result.kept.length +
|
|
132
|
+
result.retained.length >
|
|
133
|
+
0)
|
|
134
|
+
results.push(result);
|
|
135
|
+
}
|
|
136
|
+
return results;
|
|
137
|
+
}
|
|
138
|
+
async function loadModule(scoped, module, data) {
|
|
139
|
+
const internals = internalsOf(scoped);
|
|
140
|
+
// Model names come from the data at runtime: an environment untyped over them.
|
|
141
|
+
const env = scoped;
|
|
142
|
+
for (const statement of DDL)
|
|
143
|
+
await internals.query({ text: statement, params: [] });
|
|
144
|
+
const rows = await internals.query(compile(sql `SELECT module, name, model, res_id, noupdate, checksum FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module}`));
|
|
145
|
+
const existing = new Map(rows.map((r) => [r.name, r]));
|
|
146
|
+
const out = {
|
|
147
|
+
module,
|
|
148
|
+
created: [],
|
|
149
|
+
updated: [],
|
|
150
|
+
unchanged: 0,
|
|
151
|
+
kept: [],
|
|
152
|
+
deleted: [],
|
|
153
|
+
retained: [],
|
|
154
|
+
};
|
|
155
|
+
const declared = new Set();
|
|
156
|
+
for (const rec of data) {
|
|
157
|
+
const id = fullId(module, rec);
|
|
158
|
+
const key = rec.kind === 'override' ? id : rec.name; // overrides are bookkept under the overriding module
|
|
159
|
+
declared.add(key);
|
|
160
|
+
const row = existing.get(key);
|
|
161
|
+
const checksum = checksumOf(rec);
|
|
162
|
+
const model = internals.registry.get(rec.model).model;
|
|
163
|
+
const target = rec.kind === 'override'
|
|
164
|
+
? await resolveExternalId(internals, id, rec.model)
|
|
165
|
+
: row === undefined
|
|
166
|
+
? undefined
|
|
167
|
+
: Number(row.res_id);
|
|
168
|
+
const alive = target !== undefined &&
|
|
169
|
+
(await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ${target}`))).length > 0;
|
|
170
|
+
// A noupdate record belongs to the users once created: kept as they left it, even deleted.
|
|
171
|
+
if (rec.noupdate && row !== undefined) {
|
|
172
|
+
out.kept.push(id);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const values = (await resolveValues(internals, rec.values));
|
|
176
|
+
if (rec.kind === 'record' && !alive) {
|
|
177
|
+
const created = await env.model(rec.model).create([values]);
|
|
178
|
+
const resId = created.ids[0];
|
|
179
|
+
await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate, checksum) VALUES (${module}, ${rec.name}, ${rec.model}, ${resId}, ${rec.noupdate}, ${checksum})
|
|
180
|
+
ON CONFLICT (module, name) DO UPDATE SET res_id = EXCLUDED.res_id, model = EXCLUDED.model, noupdate = EXCLUDED.noupdate, checksum = EXCLUDED.checksum, updated_at = now()`));
|
|
181
|
+
lookups.get(internals.cache)?.set(id, { model: rec.model, id: resId });
|
|
182
|
+
out.created.push(id);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (rec.kind === 'override' && !alive)
|
|
186
|
+
throw new UnknownExternalIdError(`'${id}' (overridden by ${module}) has no record.`, 'Load the owning module first.');
|
|
187
|
+
if (row?.checksum === checksum) {
|
|
188
|
+
out.unchanged++;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
await env
|
|
192
|
+
.model(rec.model)
|
|
193
|
+
.browse([target])
|
|
194
|
+
.write(forUpdate(values));
|
|
195
|
+
await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate, checksum) VALUES (${module}, ${key}, ${rec.model}, ${target}, ${false}, ${checksum})
|
|
196
|
+
ON CONFLICT (module, name) DO UPDATE SET checksum = EXCLUDED.checksum, updated_at = now()`));
|
|
197
|
+
out.updated.push(id);
|
|
198
|
+
}
|
|
199
|
+
// Ids this module no longer declares: delete their records (overrides only lose their bookkeeping).
|
|
200
|
+
for (const [name, row] of existing) {
|
|
201
|
+
if (declared.has(name))
|
|
202
|
+
continue;
|
|
203
|
+
const id = name.includes('.') ? name : `${module}.${name}`;
|
|
204
|
+
if (row.noupdate)
|
|
205
|
+
continue;
|
|
206
|
+
const forget = compile(sql `DELETE FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module} AND name = ${name}`);
|
|
207
|
+
if (name.includes('.')) {
|
|
208
|
+
await internals.query(forget);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const table = internals.registry.has(row.model)
|
|
212
|
+
? internals.registry.get(row.model).model.table
|
|
213
|
+
: undefined;
|
|
214
|
+
const present = table !== undefined &&
|
|
215
|
+
(await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(table)} WHERE ${sql.id('id')} = ${Number(row.res_id)}`))).length > 0;
|
|
216
|
+
if (!present) {
|
|
217
|
+
await internals.query(forget); // the record is already gone (or its model uninstalled)
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
await env.transaction(async (e) => {
|
|
222
|
+
await e
|
|
223
|
+
.model(row.model)
|
|
224
|
+
.browse([Number(row.res_id)])
|
|
225
|
+
.unlink();
|
|
226
|
+
});
|
|
227
|
+
await internals.query(forget);
|
|
228
|
+
out.deleted.push(id);
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
out.retained.push({ id, reason: error instanceof Error ? error.message : String(error) });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
await env.flush();
|
|
235
|
+
return out;
|
|
236
|
+
}
|
package/dist/core/env/env.d.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
2
|
import type { AuditRowInput } from '../../audit/index.js';
|
|
3
3
|
import { type Driver, type DriverConnection, type DriverQuery, type Row } from '../../driver-pg/index.js';
|
|
4
|
-
import type { KeyRing, Perm } from '../../security/index.js';
|
|
4
|
+
import type { KeyRing, Perm, RulePerm } from '../../security/index.js';
|
|
5
|
+
import { type EnqueueOptions } from '../events/events.js';
|
|
6
|
+
import { type DeliveredEvent, type RunningJob, type Worker } from '../events/workers.js';
|
|
7
|
+
import type { Id } from '../model/id.js';
|
|
5
8
|
import { type Fx } from '../money/fx.js';
|
|
6
9
|
import { type RecordCache } from '../recordset/recordset.js';
|
|
7
|
-
import type { ModelName, ModelRef } from '../recordset/types.js';
|
|
10
|
+
import type { ListLoaded, ModelName, ModelRef, RecordSet } from '../recordset/types.js';
|
|
8
11
|
import type { Registry } from '../registry/registry.js';
|
|
12
|
+
import { type RuntimeSecurity } from '../security/runtime.js';
|
|
9
13
|
import { type Identity, type ResolvedIdentity } from './identity.js';
|
|
10
14
|
import type { Inspector } from './inspector.js';
|
|
11
15
|
/** Typed context flags (RFC 0003 §7.4). Module-contributed flags arrive with the registry's second half. */
|
|
@@ -86,6 +90,8 @@ interface RootScope {
|
|
|
86
90
|
/** Next virtual id for drafts (negative, RFC 0009 §7.4). */
|
|
87
91
|
virtual: number;
|
|
88
92
|
readonly uid: number;
|
|
93
|
+
/** Set in `env.asOf` scopes: reads see the models with history as they were then; writes are refused. */
|
|
94
|
+
readonly asOf?: Date;
|
|
89
95
|
}
|
|
90
96
|
/** Compute-engine state of an attempt (RFC 0008 §7.3, §7.5). */
|
|
91
97
|
export interface ComputeState {
|
|
@@ -109,11 +115,21 @@ interface Runtime {
|
|
|
109
115
|
readonly keys: KeyRing | undefined;
|
|
110
116
|
/** The language translations fall back to (RFC 0011). */
|
|
111
117
|
readonly sourceLang: string;
|
|
118
|
+
/** Runtime security (RFC 0014 §7.10): the loaded overlay, when enabled. */
|
|
119
|
+
readonly security: {
|
|
120
|
+
enabled: boolean;
|
|
121
|
+
current: RuntimeSecurity | undefined;
|
|
122
|
+
loading: Promise<void> | undefined;
|
|
123
|
+
};
|
|
112
124
|
}
|
|
113
125
|
/** @internal What the recordset runtime needs from an environment. */
|
|
114
126
|
export interface ScopeInternals {
|
|
115
127
|
readonly env: Env;
|
|
116
128
|
readonly registry: Registry;
|
|
129
|
+
/** Runtime security additions (RFC 0014 §7.10), when enabled. */
|
|
130
|
+
readonly overlay: RuntimeSecurity | undefined;
|
|
131
|
+
/** The instant of an `env.asOf` scope (RFC 0018 §7.4). */
|
|
132
|
+
readonly asOf: Date | undefined;
|
|
117
133
|
readonly cache: RecordCache;
|
|
118
134
|
readonly uid: number;
|
|
119
135
|
readonly now: Date;
|
|
@@ -167,15 +183,26 @@ export declare class Env<S = unknown> {
|
|
|
167
183
|
/** Allowed company ids (record-rule scope). */
|
|
168
184
|
readonly companyIds: readonly number[];
|
|
169
185
|
readonly lang: string;
|
|
186
|
+
/** {@link uid} as a `res.users` id, for many2one defaults: `default: (env) => env.userId`. */
|
|
187
|
+
get userId(): Id<'res.users'>;
|
|
188
|
+
/** {@link companyId} as a `res.company` id. */
|
|
189
|
+
get companyRef(): Id<'res.company'>;
|
|
170
190
|
/** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
|
|
171
191
|
readonly sourceLang: string;
|
|
172
192
|
readonly tz: string;
|
|
173
193
|
/** Superuser mode: only inside {@link asSuperuser}. */
|
|
174
194
|
readonly su: boolean;
|
|
195
|
+
/**
|
|
196
|
+
* The user is in an administrator group (`defineGroup({ administrator: true })`): every ACL, record rule, field
|
|
197
|
+
* group and permission passes, without grants (RFC 0014 §7.9). Company scoping still applies.
|
|
198
|
+
*/
|
|
199
|
+
readonly administrator: boolean;
|
|
175
200
|
/** Reason for a job or superuser scope, when given. */
|
|
176
201
|
readonly reason: string | undefined;
|
|
177
202
|
/** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
|
|
178
203
|
readonly groups: ReadonlySet<string>;
|
|
204
|
+
/** Special permissions of this user on top of the roles (`'account.backdate'`, `'account.move:unlink'`). */
|
|
205
|
+
readonly grants: ReadonlySet<string>;
|
|
179
206
|
/** @internal Encryption keys. */
|
|
180
207
|
readonly keys: KeyRing | undefined;
|
|
181
208
|
readonly flags: Flags;
|
|
@@ -195,8 +222,45 @@ export declare class Env<S = unknown> {
|
|
|
195
222
|
can(model: ModelName<S>, perm: Perm): boolean;
|
|
196
223
|
/** @throws {AccessError} */
|
|
197
224
|
check(model: ModelName<S>, perm: Perm): void;
|
|
225
|
+
/**
|
|
226
|
+
* Checks model access and the record rules of `perm` for these ids without changing anything: may this user write
|
|
227
|
+
* (or unlink) these records? @throws {AccessError} out of scope, {@link MissingRecordError} for unknown ids
|
|
228
|
+
*/
|
|
229
|
+
checkRecords(model: ModelName<S>, ids: readonly number[], perm: RulePerm): Promise<void>;
|
|
198
230
|
canField(model: ModelName<S>, field: string, kind: 'read' | 'write'): boolean;
|
|
231
|
+
/** The feature permission `code` (`definePermission`): granted by a group, or administrator. */
|
|
232
|
+
has(code: string): boolean;
|
|
233
|
+
/** @throws {AccessError} unless {@link has}. */
|
|
234
|
+
require(code: string): void;
|
|
235
|
+
/**
|
|
236
|
+
* The group and role codes that make their holder an administrator (an administrator group, or implying one),
|
|
237
|
+
* from code and runtime roles: what sign-in, 2FA policy and "keep one administrator" checks look for.
|
|
238
|
+
*/
|
|
239
|
+
administratorGroups(): ReadonlySet<string>;
|
|
199
240
|
};
|
|
241
|
+
/**
|
|
242
|
+
* The record with external id `id` (`'base.main_company'`, RFC 0017), nothing loaded.
|
|
243
|
+
* @throws {UnknownExternalIdError} for an unknown id or a record of another model.
|
|
244
|
+
*/
|
|
245
|
+
ref<M extends ModelName<S>>(model: M, id: string): Promise<RecordSet<S, M, ListLoaded<never>>>;
|
|
246
|
+
/** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
|
|
247
|
+
refId<M extends ModelName<S>>(model: M, id: string): Promise<Id<M>>;
|
|
248
|
+
/**
|
|
249
|
+
* Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
|
|
250
|
+
* of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
|
|
251
|
+
* registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
|
|
252
|
+
*/
|
|
253
|
+
get securityAdmin(): SecurityAdmin;
|
|
254
|
+
/**
|
|
255
|
+
* Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
|
|
256
|
+
* subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
|
|
257
|
+
*/
|
|
258
|
+
emit(topic: string, payload: unknown): Promise<number>;
|
|
259
|
+
/**
|
|
260
|
+
* Enqueues a background job in this transaction (RFC 0018 §7.3), run by `shutro.work` as this user, with
|
|
261
|
+
* retries. With `key`, a job already pending or running under that key makes this a no-op (returns `null`).
|
|
262
|
+
*/
|
|
263
|
+
enqueue(name: string, payload: unknown, options?: EnqueueOptions): Promise<number | null>;
|
|
200
264
|
/** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
|
|
201
265
|
get fx(): Fx;
|
|
202
266
|
/** The transaction timestamp (PostgreSQL `now()`), stable within an attempt. Returns a fresh `Date` each call. */
|
|
@@ -226,12 +290,41 @@ export declare class Env<S = unknown> {
|
|
|
226
290
|
onRollback(hook: Hook): void;
|
|
227
291
|
/** The same scope with another current company. Must be allowed unless `su`. @throws {CompanyNotAllowedError} */
|
|
228
292
|
withCompany(company: number): Env<S>;
|
|
293
|
+
/**
|
|
294
|
+
* Drops clean records from this scope's cache (all models, or one): for long reads in one transaction, such as
|
|
295
|
+
* streaming an export of millions of rows page by page, so memory stays bounded. Records with unsaved changes or
|
|
296
|
+
* pending computes and checks are kept; dropped records are simply loaded again when read.
|
|
297
|
+
*/
|
|
298
|
+
releaseCache(model?: string): void;
|
|
229
299
|
/** The same scope with another language. */
|
|
230
300
|
withLang(lang: string): Env<S>;
|
|
231
301
|
/** The same scope with another time zone. */
|
|
232
302
|
withTz(tz: string): Env<S>;
|
|
233
303
|
/** The same scope with some flags changed. `checkCompany: false` needs `su`. @throws {FlagNotAllowedError} */
|
|
234
304
|
withFlags(flags: Partial<Flags>): Env<S>;
|
|
305
|
+
/**
|
|
306
|
+
* Runs `fn` reading the past (RFC 0018 §7.4): models with `history: true` are searched and loaded as they were at
|
|
307
|
+
* `instant` (rules, field groups and company scope apply as now); other models are read as they are now. The
|
|
308
|
+
* environment has its own cache and is read-only: writes are refused.
|
|
309
|
+
*
|
|
310
|
+
* ```ts
|
|
311
|
+
* 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'])));
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
314
|
+
asOf<T>(instant: Date, fn: (past: Env<S>) => Promise<T>): Promise<T>;
|
|
315
|
+
/**
|
|
316
|
+
* Runs `fn` with extra special grants in the same scope (RFC 0014 §7.9): a narrow, audited alternative to
|
|
317
|
+
* {@link asSuperuser} for code that must touch a model or feature its caller cannot. Record rules, field groups
|
|
318
|
+
* and company scoping still apply; only the named grants are added, and only inside `fn`.
|
|
319
|
+
*
|
|
320
|
+
* ```ts
|
|
321
|
+
* await env.withGrants({ grants: ['sale.order.line:read'], reason: 'invoice from orders' }, (e) => ...);
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
withGrants<T>(options: {
|
|
325
|
+
readonly grants: readonly string[];
|
|
326
|
+
readonly reason: string;
|
|
327
|
+
}, fn: (env: Env<S>) => Promise<T>): Promise<T>;
|
|
235
328
|
/**
|
|
236
329
|
* Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
|
|
237
330
|
* returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
|
|
@@ -257,6 +350,11 @@ export interface ShutroOptions<S> {
|
|
|
257
350
|
* outside the allowed set and groups the user does not have, and uses the loaded groups when none are given.
|
|
258
351
|
*/
|
|
259
352
|
readonly identity?: (uid: number) => Promise<VerifiedIdentity | null>;
|
|
353
|
+
/**
|
|
354
|
+
* Roles, access, record rules and permission grants edited at runtime (RFC 0014 §7.10), on top of the code's
|
|
355
|
+
* declarations. Loaded at the first run and reloaded whenever a change is committed (by any process).
|
|
356
|
+
*/
|
|
357
|
+
readonly runtimeSecurity?: boolean;
|
|
260
358
|
/** Retry policy for serialization failures and deadlocks. Default: 5 attempts with jittered exponential backoff. */
|
|
261
359
|
readonly retry?: {
|
|
262
360
|
readonly attempts?: number;
|
|
@@ -269,10 +367,53 @@ export interface ShutroOptions<S> {
|
|
|
269
367
|
*/
|
|
270
368
|
readonly onHookError?: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
|
|
271
369
|
}
|
|
370
|
+
/** Options of {@link Shutro.bootstrap}. */
|
|
371
|
+
export interface BootstrapOptions {
|
|
372
|
+
/** Why the system acts (audited), e.g. `'install'`. */
|
|
373
|
+
readonly reason: string;
|
|
374
|
+
/** Current company, once one exists; company-scoped defaults and sequences use it. */
|
|
375
|
+
readonly company?: number;
|
|
376
|
+
}
|
|
377
|
+
/** `env.securityAdmin` (RFC 0014 §7.10). */
|
|
378
|
+
export interface SecurityAdmin {
|
|
379
|
+
/** Creates or updates a runtime role. */
|
|
380
|
+
saveRole(role: {
|
|
381
|
+
readonly code: string;
|
|
382
|
+
readonly label?: string;
|
|
383
|
+
readonly implies?: readonly string[];
|
|
384
|
+
readonly administrator?: boolean;
|
|
385
|
+
}): Promise<void>;
|
|
386
|
+
/** Deletes a runtime role with its access, rules and grants. */
|
|
387
|
+
deleteRole(code: string): Promise<void>;
|
|
388
|
+
/** Sets what `role` may do on `model` (an empty list removes the runtime grant; code grants stay). */
|
|
389
|
+
setAccess(role: string, model: string, perms: readonly Perm[]): Promise<void>;
|
|
390
|
+
/** Creates or updates a record rule for `role` (the domain is compiled when saved). */
|
|
391
|
+
saveRule(rule: {
|
|
392
|
+
readonly name: string;
|
|
393
|
+
readonly role: string;
|
|
394
|
+
readonly model: string;
|
|
395
|
+
readonly perms: readonly RulePerm[];
|
|
396
|
+
readonly domain: Readonly<Record<string, unknown>>;
|
|
397
|
+
}): Promise<void>;
|
|
398
|
+
deleteRule(name: string): Promise<void>;
|
|
399
|
+
/** Grants a feature permission (declared by a module) to `role`. */
|
|
400
|
+
grantPermission(role: string, permission: string): Promise<void>;
|
|
401
|
+
revokePermission(role: string, permission: string): Promise<void>;
|
|
402
|
+
/**
|
|
403
|
+
* Field security at runtime: the roles that may read / write `model.field`, on top of its code groups (writers can
|
|
404
|
+
* read). A field without code groups becomes restricted to these roles; empty lists remove the runtime entry.
|
|
405
|
+
*/
|
|
406
|
+
setFieldGroups(model: string, field: string, groups: {
|
|
407
|
+
readonly read?: readonly string[];
|
|
408
|
+
readonly write?: readonly string[];
|
|
409
|
+
}): Promise<void>;
|
|
410
|
+
}
|
|
272
411
|
/** What an identity loader returns for a user. */
|
|
273
412
|
export interface VerifiedIdentity {
|
|
274
413
|
readonly companies: readonly number[];
|
|
275
414
|
readonly groups: readonly string[];
|
|
415
|
+
/** The user's special permissions (see `Identity.grants`). */
|
|
416
|
+
readonly grants?: readonly string[];
|
|
276
417
|
}
|
|
277
418
|
/** A Shutro instance: one driver, one registry, one AsyncLocalStorage. No global state (`CLAUDE.md`). */
|
|
278
419
|
export interface Shutro<S = unknown> {
|
|
@@ -287,8 +428,40 @@ export interface Shutro<S = unknown> {
|
|
|
287
428
|
* @throws {ConcurrentUpdateError} when every attempt conflicted.
|
|
288
429
|
*/
|
|
289
430
|
run<T>(options: RunOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
|
|
431
|
+
/**
|
|
432
|
+
* Runs `fn` as the system (uid {@link SYSTEM_UID}) in a superuser scope, for installing a database before any
|
|
433
|
+
* user exists (feedback #5): `created_by` / `updated_by` are written as `NULL`, the scope is audited with
|
|
434
|
+
* `reason`, and the identity loader is not consulted. Pass `company` once the first company exists, so
|
|
435
|
+
* company-scoped defaults have a value.
|
|
436
|
+
*
|
|
437
|
+
* ```ts
|
|
438
|
+
* await shutro.bootstrap({ reason: 'install' }, async (env) => {
|
|
439
|
+
* const [company] = await env.model('res.company').create([{ name: 'Acme', currency: bdt }]);
|
|
440
|
+
* await env.model('res.users').create([{ login: 'admin', name: 'Administrator' }]);
|
|
441
|
+
* });
|
|
442
|
+
* ```
|
|
443
|
+
*/
|
|
444
|
+
bootstrap<T>(options: BootstrapOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
|
|
290
445
|
/** The environment of the innermost active scope. @throws {NoEnvironmentError} outside `run()`. */
|
|
291
446
|
currentEnv(): Env<S>;
|
|
447
|
+
/** The registry this instance was created with. */
|
|
448
|
+
readonly registry: Registry | undefined;
|
|
449
|
+
/** The driver this instance was created with. */
|
|
450
|
+
readonly driver: Driver;
|
|
451
|
+
/** Reloads runtime security now (changes are also reloaded automatically after they commit). */
|
|
452
|
+
reloadSecurity(): Promise<void>;
|
|
453
|
+
/**
|
|
454
|
+
* A subscriber of `topic` named `name` (RFC 0018 §7.2): events in order, at least once, the cursor advancing in the
|
|
455
|
+
* handler's transaction. One delivery at a time per name, across processes.
|
|
456
|
+
*/
|
|
457
|
+
subscribe(name: string, topic: string, handler: (event: DeliveredEvent, env: Env<S>) => Promise<void>, options?: {
|
|
458
|
+
readonly attempts?: number;
|
|
459
|
+
readonly pollMs?: number;
|
|
460
|
+
}): Worker;
|
|
461
|
+
/** A job worker for these job names (RFC 0018 §7.3); start any number, in any processes. */
|
|
462
|
+
work(handlers: Readonly<Record<string, (payload: unknown, env: Env<S>, job: RunningJob) => Promise<void>>>, options?: {
|
|
463
|
+
readonly pollMs?: number;
|
|
464
|
+
}): Worker;
|
|
292
465
|
}
|
|
293
466
|
/** Creates a {@link Shutro} instance on a driver (and a registry). */
|
|
294
467
|
export declare function createShutro<S = unknown>(options: ShutroOptions<S>): Shutro<S>;
|