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,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base class of every error raised by `@shutro/core`. The message says what went wrong and ends with
|
|
3
|
+
* {@link ShutroError.hint}, which says how to fix it (`CLAUDE.md` coding rules).
|
|
4
|
+
*/
|
|
5
|
+
export class ShutroError extends Error {
|
|
6
|
+
/** Machine-readable reason. */
|
|
7
|
+
code;
|
|
8
|
+
/** How to fix the problem. Also included at the end of `message`. */
|
|
9
|
+
hint;
|
|
10
|
+
constructor(code, problem, hint, options) {
|
|
11
|
+
super(`${problem} ${hint}`, options?.cause === undefined ? undefined : { cause: options.cause });
|
|
12
|
+
this.name = new.target.name;
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.hint = hint;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** A JavaScript `number` that isn't a safe integer was used where an exact decimal is required. */
|
|
18
|
+
export class NonIntegerNumberError extends ShutroError {
|
|
19
|
+
constructor(problem, hint) {
|
|
20
|
+
super('NON_INTEGER_NUMBER', problem, hint);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** A string or Decimal that isn't a finite decimal number. */
|
|
24
|
+
export class InvalidDecimalError extends ShutroError {
|
|
25
|
+
constructor(problem, hint) {
|
|
26
|
+
super('INVALID_DECIMAL', problem, hint);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Division of a money amount or quantity by zero. */
|
|
30
|
+
export class DivisionByZeroError extends ShutroError {
|
|
31
|
+
constructor(problem, hint) {
|
|
32
|
+
super('DIVISION_BY_ZERO', problem, hint);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Invalid currency definition. */
|
|
36
|
+
export class InvalidCurrencyError extends ShutroError {
|
|
37
|
+
constructor(problem, hint) {
|
|
38
|
+
super('INVALID_CURRENCY', problem, hint);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Arithmetic or comparison between amounts in different currencies (RFC 0006 R4). */
|
|
42
|
+
export class CurrencyMismatchError extends ShutroError {
|
|
43
|
+
constructor(problem, hint) {
|
|
44
|
+
super('CURRENCY_MISMATCH', problem, hint);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Invalid ratios passed to `Money.allocate()`. */
|
|
48
|
+
export class InvalidAllocationError extends ShutroError {
|
|
49
|
+
constructor(problem, hint) {
|
|
50
|
+
super('INVALID_ALLOCATION', problem, hint);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** `Money.sum([])` without a currency. */
|
|
54
|
+
export class EmptyMoneySumError extends ShutroError {
|
|
55
|
+
constructor(problem, hint) {
|
|
56
|
+
super('MONEY_EMPTY_SUM', problem, hint);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Invalid unit-of-measure definition. */
|
|
60
|
+
export class InvalidUomError extends ShutroError {
|
|
61
|
+
constructor(problem, hint) {
|
|
62
|
+
super('INVALID_UOM', problem, hint);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Arithmetic or comparison between quantities in different units. */
|
|
66
|
+
export class UomMismatchError extends ShutroError {
|
|
67
|
+
constructor(problem, hint) {
|
|
68
|
+
super('UOM_MISMATCH', problem, hint);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Conversion between units of different categories (e.g. units to kilograms). */
|
|
72
|
+
export class IncompatibleUomCategoryError extends ShutroError {
|
|
73
|
+
constructor(problem, hint) {
|
|
74
|
+
super('UOM_CATEGORY_MISMATCH', problem, hint);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** No environment is active (code ran outside `shutro.run()`), RFC 0003 §7.7. */
|
|
78
|
+
export class NoEnvironmentError extends ShutroError {
|
|
79
|
+
constructor() {
|
|
80
|
+
super('NO_ENVIRONMENT', 'No Shutro environment is active.', 'Wrap the call in shutro.run({ user, company }, (env) => ...) or use the env of an existing recordset.');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** An environment was used outside its transaction scope (RFC 0003 §7.7). */
|
|
84
|
+
export class TransactionScopeError extends ShutroError {
|
|
85
|
+
constructor(problem, hint) {
|
|
86
|
+
super('TRANSACTION_SCOPE', problem, hint);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Every retry of a transaction hit a serialization failure or deadlock (RFC 0003 §7.5). */
|
|
90
|
+
export class ConcurrentUpdateError extends ShutroError {
|
|
91
|
+
constructor(attempts, cause) {
|
|
92
|
+
super('CONCURRENT_UPDATE', `The transaction conflicted with concurrent transactions on all ${attempts} attempts.`, 'Reduce contention: lock records in a consistent order, keep transactions short, or process the data in smaller chunks (shutro.forEachChunk).', { cause });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Invalid user, company, language, time zone or reason passed to `shutro.run()` or a derived environment. */
|
|
96
|
+
export class InvalidIdentityError extends ShutroError {
|
|
97
|
+
constructor(problem, hint) {
|
|
98
|
+
super('INVALID_IDENTITY', problem, hint);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** `withCompany()` outside the user's allowed companies (RFC 0003 §7.2). */
|
|
102
|
+
export class CompanyNotAllowedError extends ShutroError {
|
|
103
|
+
constructor(company, allowed) {
|
|
104
|
+
super('COMPANY_NOT_ALLOWED', `Company ${company} is not among the allowed companies [${allowed.join(', ')}] of this environment.`, 'Select the company in the session (allowed companies), or run the operation under env.asSuperuser({ reason }, ...) if it is a system task.');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** A field definition that can't be right (RFC 0001): bad size, scale, selection, transition, relation option, ... */
|
|
108
|
+
export class InvalidFieldError extends ShutroError {
|
|
109
|
+
constructor(problem, hint) {
|
|
110
|
+
super('INVALID_FIELD', problem, hint);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** A model definition that can't be right (RFC 0001): reserved keys, column collisions, bad sibling references, ... */
|
|
114
|
+
export class InvalidModelError extends ShutroError {
|
|
115
|
+
constructor(model, problem, hint) {
|
|
116
|
+
super('INVALID_MODEL', `Model '${model}': ${problem}`, hint);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** A module definition that can't be right (RFC 0002 §7.1). */
|
|
120
|
+
export class InvalidModuleError extends ShutroError {
|
|
121
|
+
constructor(problem, hint) {
|
|
122
|
+
super('INVALID_MODULE', problem, hint);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Two different module objects share a name (e.g. two copies of `base` from different package versions). */
|
|
126
|
+
export class DuplicateModuleError extends ShutroError {
|
|
127
|
+
constructor(name) {
|
|
128
|
+
super('DUPLICATE_MODULE', `Two different modules are named '${name}'.`, 'Modules are identified by name; dedupe the package (one version of each module) or rename one of them.');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** The same model name is defined twice (in one module or in two). */
|
|
132
|
+
export class DuplicateModelError extends ShutroError {
|
|
133
|
+
constructor(model, modules) {
|
|
134
|
+
super('DUPLICATE_MODEL', `Model '${model}' is defined more than once (in ${modules.map((m) => `'${m}'`).join(' and ')}).`, 'A model has exactly one owner; extend it from the other module with extendModel() instead of defining it again.');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** A module references a model owned by a module it doesn't depend on (RFC 0002 W2). */
|
|
138
|
+
export class UndeclaredDependencyError extends ShutroError {
|
|
139
|
+
constructor(module, model, owner, via) {
|
|
140
|
+
super('UNDECLARED_DEPENDENCY', `Module '${module}' references '${model}' (owned by '${owner}') in ${via}, but does not depend on '${owner}'.`, `Add the '${owner}' module to the depends of '${module}'. Only models of a module and its transitive dependencies may be referenced.`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** A model name that no loaded module defines. */
|
|
144
|
+
export class UnknownModelError extends ShutroError {
|
|
145
|
+
constructor(model, via) {
|
|
146
|
+
super('UNKNOWN_MODEL', via === undefined
|
|
147
|
+
? `No loaded module defines model '${model}'.`
|
|
148
|
+
: `${via} refers to model '${model}', which no loaded module defines.`, 'Check the model name, and make sure the module that defines it is loaded (directly or as a dependency).');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** A one2many whose inverse field doesn't point back, or another broken relation. */
|
|
152
|
+
export class InvalidRelationError extends ShutroError {
|
|
153
|
+
constructor(problem, hint) {
|
|
154
|
+
super('INVALID_RELATION', problem, hint);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** A `depends` path that doesn't resolve through real fields. */
|
|
158
|
+
export class InvalidDependsPathError extends ShutroError {
|
|
159
|
+
constructor(problem, hint) {
|
|
160
|
+
super('INVALID_DEPENDS_PATH', problem, hint);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** A field was read before it was loaded (RFC 0004 §7.1). */
|
|
164
|
+
export class FieldNotLoadedError extends ShutroError {
|
|
165
|
+
constructor(model, field, hint) {
|
|
166
|
+
super('FIELD_NOT_LOADED', `${model}.${field} is not loaded.`, hint);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** `first()` on an empty recordset, or `ensureOne()` on a recordset that isn't exactly one record. */
|
|
170
|
+
export class SingletonError extends ShutroError {
|
|
171
|
+
constructor(model, count, what) {
|
|
172
|
+
super('SINGLETON', `${what}() expected one ${model} record but the recordset has ${count}.`, what === 'first'
|
|
173
|
+
? 'Check isEmpty() first, or use a search that returns at least one record.'
|
|
174
|
+
: 'Narrow the search, or iterate the recordset when several records are expected.');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** A browsed id that doesn't exist (or isn't visible). */
|
|
178
|
+
export class MissingRecordError extends ShutroError {
|
|
179
|
+
constructor(model, ids) {
|
|
180
|
+
super('MISSING_RECORD', `${model} record(s) ${ids.join(', ')} do not exist or are not accessible.`, 'The id may come from stale data or another company; search for the record instead of browsing a remembered id.');
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* A compare-and-set write found records changed since they were read (lost-update protection, RFC 0018 §7.1):
|
|
185
|
+
* someone else saved first.
|
|
186
|
+
*/
|
|
187
|
+
export class StaleRecordError extends ShutroError {
|
|
188
|
+
model;
|
|
189
|
+
records;
|
|
190
|
+
fields;
|
|
191
|
+
constructor(model, records, fields) {
|
|
192
|
+
super('STALE_RECORD', `${model} record(s) ${records.join(', ')} changed since they were read (${fields.join(', ')}).`, 'Someone else saved first: reload the record, reapply the change, and save again.');
|
|
193
|
+
this.model = model;
|
|
194
|
+
this.records = Object.freeze([...records]);
|
|
195
|
+
this.fields = Object.freeze([...fields]);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** An external id (`module.name`, RFC 0017) that does not exist, or names a record of another model. */
|
|
199
|
+
export class UnknownExternalIdError extends ShutroError {
|
|
200
|
+
constructor(problem, hint) {
|
|
201
|
+
super('UNKNOWN_EXTERNAL_ID', problem, hint);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/** A search domain that can't be compiled (RFC 0005 §7.1). */
|
|
205
|
+
export class InvalidDomainError extends ShutroError {
|
|
206
|
+
constructor(problem, hint) {
|
|
207
|
+
super('INVALID_DOMAIN', problem, hint);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** `env.model()` on a Shutro instance created without a registry. */
|
|
211
|
+
export class NoRegistryError extends ShutroError {
|
|
212
|
+
constructor() {
|
|
213
|
+
super('NO_REGISTRY', 'This Shutro instance has no registry, so there are no models.', 'Pass registry: buildRegistry({ modules }) to createShutro().');
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Values rejected by `create()` / `write()`: missing required fields, unknown or readonly fields, wrong types (RFC 0001 §7.7). */
|
|
217
|
+
export class ValidationError extends ShutroError {
|
|
218
|
+
model;
|
|
219
|
+
/** The offending field keys. */
|
|
220
|
+
fields;
|
|
221
|
+
constructor(model, fields, problem, hint) {
|
|
222
|
+
super('VALIDATION', `${model}: ${problem}`, hint);
|
|
223
|
+
this.model = model;
|
|
224
|
+
this.fields = Object.freeze([...fields]);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** An extension that breaks a view-safety rule (RFC 0002 §7.5) or is malformed. */
|
|
228
|
+
export class InvalidExtensionError extends ShutroError {
|
|
229
|
+
constructor(problem, hint) {
|
|
230
|
+
super('INVALID_EXTENSION', problem, hint);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/** Two modules contribute the same field, method or constraint key (RFC 0002 §7.6). Never resolved silently. */
|
|
234
|
+
export class ExtensionConflictError extends ShutroError {
|
|
235
|
+
constructor(problem, hint) {
|
|
236
|
+
super('EXTENSION_CONFLICT', problem, hint);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** A flag that only a superuser environment may change (RFC 0003 §7.4). */
|
|
240
|
+
export class FlagNotAllowedError extends ShutroError {
|
|
241
|
+
constructor(flag) {
|
|
242
|
+
super('FLAG_NOT_ALLOWED', `The flag '${flag}' can only be changed in a superuser environment.`, 'Disable it inside env.asSuperuser({ reason }, (su) => su.withFlags({ ... })), and only for system tasks such as migrations.');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** Computed fields depend on each other in a cycle (RFC 0008 §7.1). */
|
|
246
|
+
export class ComputeCycleError extends ShutroError {
|
|
247
|
+
constructor(chain) {
|
|
248
|
+
super('COMPUTE_CYCLE', `Computed fields depend on each other in a cycle: ${chain.join(' → ')}.`, 'Break the cycle: one of these fields must be computed from stored data only, or become a method.');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** A computed field was assigned outside its compute (RFC 0008 §7.5). */
|
|
252
|
+
export class ComputeAssignmentError extends ShutroError {
|
|
253
|
+
constructor(model, key) {
|
|
254
|
+
super('COMPUTE_ASSIGNMENT', `${model}.${key} is computed and can only be assigned inside its compute function.`, 'Write the fields it depends on instead, or give the field an inverse and use write().');
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/** The recompute loop did not converge (RFC 0008 §7.3). */
|
|
258
|
+
export class RecomputeLimitError extends ShutroError {
|
|
259
|
+
constructor(rounds, pending) {
|
|
260
|
+
super('RECOMPUTE_LIMIT', `Recompute did not settle after ${rounds} rounds; still pending: ${pending.join(', ')}.`, 'A compute is probably writing one of its own dependencies. Computes must only assign their computed fields.');
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** A business constraint found failing records at a flush point (RFC 0009 §7.1). */
|
|
264
|
+
export class ConstraintError extends ShutroError {
|
|
265
|
+
model;
|
|
266
|
+
constraint;
|
|
267
|
+
/** The constraint's `depends`. */
|
|
268
|
+
fields;
|
|
269
|
+
/** Ids of the failing records. */
|
|
270
|
+
records;
|
|
271
|
+
constructor(model, constraint, fields, records, message) {
|
|
272
|
+
super('CONSTRAINT', `${model}: ${message}`, `Constraint '${constraint}' failed for record(s) ${records.join(', ')}.`);
|
|
273
|
+
this.model = model;
|
|
274
|
+
this.constraint = constraint;
|
|
275
|
+
this.fields = Object.freeze([...fields]);
|
|
276
|
+
this.records = Object.freeze([...records]);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** PostgreSQL rejected a statement because of a declared `sqlConstraints` entry or a foreign key (RFC 0009 §7.2). */
|
|
280
|
+
export class ConstraintViolationError extends ShutroError {
|
|
281
|
+
model;
|
|
282
|
+
/** The `sqlConstraints` key, or the many2one field for a foreign key. */
|
|
283
|
+
constraint;
|
|
284
|
+
kind;
|
|
285
|
+
fields;
|
|
286
|
+
constructor(model, constraint, kind, fields, message, hint, options) {
|
|
287
|
+
super('CONSTRAINT_VIOLATION', `${model}: ${message}`, hint, options);
|
|
288
|
+
this.model = model;
|
|
289
|
+
this.constraint = constraint;
|
|
290
|
+
this.kind = kind;
|
|
291
|
+
this.fields = Object.freeze([...fields]);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** A transition was requested from a state it does not start from (RFC 0010 §7.2). Nothing changed. */
|
|
295
|
+
export class InvalidTransitionError extends ShutroError {
|
|
296
|
+
model;
|
|
297
|
+
transition;
|
|
298
|
+
/** The offending records with their current state. */
|
|
299
|
+
records;
|
|
300
|
+
/** The states the transition starts from. */
|
|
301
|
+
from;
|
|
302
|
+
constructor(model, transition, records, from) {
|
|
303
|
+
super('INVALID_TRANSITION', `${model}: cannot '${transition}' ${records.map((r) => `#${r.id} (${r.state})`).join(', ') || 'these records'}.`, `'${transition}' starts from ${from.join(' | ') || 'no state'}. Check record.transitions() first, or leave the records out of the batch.`);
|
|
304
|
+
this.model = model;
|
|
305
|
+
this.transition = transition;
|
|
306
|
+
this.records = Object.freeze(records.map((r) => Object.freeze({ ...r })));
|
|
307
|
+
this.from = Object.freeze([...from]);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** A transition guard returned records that may not transition (RFC 0010 §7.2). Nothing changed. */
|
|
311
|
+
export class TransitionGuardError extends ShutroError {
|
|
312
|
+
model;
|
|
313
|
+
transition;
|
|
314
|
+
records;
|
|
315
|
+
constructor(model, transition, records, message) {
|
|
316
|
+
super('TRANSITION_GUARD', `${model}: ${message}`, `Guard of '${transition}' failed for record(s) ${records.join(', ')}.`);
|
|
317
|
+
this.model = model;
|
|
318
|
+
this.transition = transition;
|
|
319
|
+
this.records = Object.freeze([...records]);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** A record references a record of another company through a `checkCompany` many2one (RFC 0003 §7.4). */
|
|
323
|
+
export class CrossCompanyError extends ShutroError {
|
|
324
|
+
model;
|
|
325
|
+
records;
|
|
326
|
+
constructor(model, records) {
|
|
327
|
+
const first = records[0];
|
|
328
|
+
super('CROSS_COMPANY', `${model}: ${records.length} record(s) reference records of another company (e.g. #${first?.id ?? '?'}.${first?.field ?? '?'} belongs to company ${first?.targetCompany ?? '?'}, the record to ${first?.company ?? 'none'}).`, 'Reference a record of the same company or a shared one (no company), or switch the environment company with env.withCompany().');
|
|
329
|
+
this.model = model;
|
|
330
|
+
this.records = Object.freeze(records.map((r) => Object.freeze({ ...r })));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/** No exchange rate on or before the date (RFC 0006 §7.6), or the rate model is unusable. */
|
|
334
|
+
export class MissingRateError extends ShutroError {
|
|
335
|
+
constructor(problem, hint) {
|
|
336
|
+
super('MISSING_RATE', problem, hint);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/** A field references a sequence code no module declares (RFC 0012 §7.1). */
|
|
340
|
+
export class UnknownSequenceError extends ShutroError {
|
|
341
|
+
constructor(code, where) {
|
|
342
|
+
super('UNKNOWN_SEQUENCE', `${where} uses the sequence '${code}', which no module declares.`, `Add defineSequence({ code: '${code}', ... }) to the sequences of a module the field's module depends on.`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/** An operation the environment may not perform (RFC 0014): model ACL, record rules or field groups. */
|
|
346
|
+
export class AccessError extends ShutroError {
|
|
347
|
+
model;
|
|
348
|
+
perm;
|
|
349
|
+
/** The records out of scope, when the rules denied them. */
|
|
350
|
+
records;
|
|
351
|
+
/** The restricted field, when field groups denied it. */
|
|
352
|
+
field;
|
|
353
|
+
constructor(model, perm, details) {
|
|
354
|
+
super('ACCESS', `${model}: ${details.problem}`, details.hint);
|
|
355
|
+
this.model = model;
|
|
356
|
+
this.perm = perm;
|
|
357
|
+
this.records = Object.freeze([...(details.records ?? [])]);
|
|
358
|
+
this.field = details.field;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transactional events and jobs (RFC 0018 §7.2–§7.3). `env.emit` / `env.enqueue` insert in the business transaction,
|
|
3
|
+
* so events and jobs exist if and only if their transaction committed. Workers run each event or job inside a
|
|
4
|
+
* `run()` scope as the user who emitted / enqueued it; the subscription cursor advances, or the job is marked done,
|
|
5
|
+
* in that same transaction: database effects of a handler happen exactly once.
|
|
6
|
+
*/
|
|
7
|
+
import type { Driver } from '../../driver-pg/index.js';
|
|
8
|
+
export declare const OUTBOX_CHANNEL = "shutro_outbox";
|
|
9
|
+
export declare const JOB_CHANNEL = "shutro_job";
|
|
10
|
+
/** Statements creating the event and job tables (also created on first use). */
|
|
11
|
+
export declare function eventTableStatements(): readonly {
|
|
12
|
+
readonly text: string;
|
|
13
|
+
readonly params: readonly [];
|
|
14
|
+
}[];
|
|
15
|
+
type Query = <R extends Record<string, unknown>>(q: {
|
|
16
|
+
text: string;
|
|
17
|
+
params: readonly unknown[];
|
|
18
|
+
}) => Promise<readonly R[]>;
|
|
19
|
+
/** Creates the tables once per driver (or per query function). */
|
|
20
|
+
export declare function ensureEventTables(owner: object, query: Query): Promise<void>;
|
|
21
|
+
/** Who emitted / enqueued: handlers run as them. */
|
|
22
|
+
export interface Actor {
|
|
23
|
+
readonly uid: number;
|
|
24
|
+
readonly companyId: number;
|
|
25
|
+
readonly groups: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** `env.emit`: inserts the event in the current transaction. */
|
|
28
|
+
export declare function emitEvent(query: Query, actor: Actor, topic: string, payload: unknown): Promise<number>;
|
|
29
|
+
/** Options of `env.enqueue`. */
|
|
30
|
+
export interface EnqueueOptions {
|
|
31
|
+
/** Not before this instant. */
|
|
32
|
+
readonly runAt?: Date;
|
|
33
|
+
/** Deduplication: while a job with this key is pending or running, enqueueing it again does nothing. */
|
|
34
|
+
readonly key?: string;
|
|
35
|
+
/** Attempts before the job is marked `dead` (default 5). */
|
|
36
|
+
readonly attempts?: number;
|
|
37
|
+
}
|
|
38
|
+
/** `env.enqueue`: inserts the job in the current transaction. Returns its id, or `null` when deduplicated. */
|
|
39
|
+
export declare function enqueueJob(query: Query, actor: Actor, name: string, payload: unknown, options?: EnqueueOptions): Promise<number | null>;
|
|
40
|
+
/** Exponential backoff with a cap, in milliseconds (attempt 1 → 1 s, 2 → 2 s, … ≤ 10 min). */
|
|
41
|
+
export declare function backoffMs(attempt: number): number;
|
|
42
|
+
/** Releases jobs whose worker died while running them (locked longer than `staleMs`). */
|
|
43
|
+
export declare function releaseStale(driver: Driver, staleMs: number): Promise<number>;
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { compile, sql } from '../../sql/index.js';
|
|
2
|
+
export const OUTBOX_CHANNEL = 'shutro_outbox';
|
|
3
|
+
export const JOB_CHANNEL = 'shutro_job';
|
|
4
|
+
const DDL = [
|
|
5
|
+
'CREATE TABLE IF NOT EXISTS "shutro_outbox" ("id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, "topic" text NOT NULL, "payload" jsonb NOT NULL, "created_at" timestamp with time zone NOT NULL DEFAULT now(), "uid" bigint NOT NULL, "company_id" bigint NOT NULL, "groups" text[] NOT NULL DEFAULT \'{}\')',
|
|
6
|
+
'CREATE INDEX IF NOT EXISTS "shutro_outbox_topic_id_idx" ON "shutro_outbox" ("topic", "id")',
|
|
7
|
+
'CREATE TABLE IF NOT EXISTS "shutro_subscription" ("name" text PRIMARY KEY, "topic" text NOT NULL, "last_id" bigint NOT NULL DEFAULT 0, "attempts" integer NOT NULL DEFAULT 0, "retry_at" timestamp with time zone, "last_error" text)',
|
|
8
|
+
'CREATE TABLE IF NOT EXISTS "shutro_dead_event" ("subscription" text NOT NULL, "event_id" bigint NOT NULL, "error" text NOT NULL, "at" timestamp with time zone NOT NULL DEFAULT now(), PRIMARY KEY ("subscription", "event_id"))',
|
|
9
|
+
'CREATE TABLE IF NOT EXISTS "shutro_job" ("id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, "name" text NOT NULL, "payload" jsonb NOT NULL, "key" text, "state" text NOT NULL DEFAULT \'pending\', "run_at" timestamp with time zone NOT NULL DEFAULT now(), "attempts" integer NOT NULL DEFAULT 0, "max_attempts" integer NOT NULL DEFAULT 5, "locked_at" timestamp with time zone, "last_error" text, "created_at" timestamp with time zone NOT NULL DEFAULT now(), "done_at" timestamp with time zone, "uid" bigint NOT NULL, "company_id" bigint NOT NULL, "groups" text[] NOT NULL DEFAULT \'{}\')',
|
|
10
|
+
'CREATE INDEX IF NOT EXISTS "shutro_job_due_idx" ON "shutro_job" ("state", "run_at")',
|
|
11
|
+
'CREATE UNIQUE INDEX IF NOT EXISTS "shutro_job_key_idx" ON "shutro_job" ("key") WHERE "key" IS NOT NULL AND "state" IN (\'pending\', \'running\')',
|
|
12
|
+
];
|
|
13
|
+
/** Statements creating the event and job tables (also created on first use). */
|
|
14
|
+
export function eventTableStatements() {
|
|
15
|
+
return DDL.map((text) => ({ text, params: [] }));
|
|
16
|
+
}
|
|
17
|
+
const ensured = new WeakSet();
|
|
18
|
+
/** Creates the tables once per driver (or per query function). */
|
|
19
|
+
export async function ensureEventTables(owner, query) {
|
|
20
|
+
if (ensured.has(owner))
|
|
21
|
+
return;
|
|
22
|
+
for (const text of DDL)
|
|
23
|
+
await query({ text, params: [] });
|
|
24
|
+
ensured.add(owner);
|
|
25
|
+
}
|
|
26
|
+
const TOPIC = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$/;
|
|
27
|
+
function assertName(kind, name) {
|
|
28
|
+
if (!TOPIC.test(name))
|
|
29
|
+
throw new TypeError(`${JSON.stringify(name)} is not a valid ${kind} name. Use dotted snake_case, e.g. 'invoice.posted'.`);
|
|
30
|
+
}
|
|
31
|
+
/** `env.emit`: inserts the event in the current transaction. */
|
|
32
|
+
export async function emitEvent(query, actor, topic, payload) {
|
|
33
|
+
assertName('topic', topic);
|
|
34
|
+
const [row] = await query(compile(sql `INSERT INTO shutro_outbox (topic, payload, uid, company_id, groups) VALUES (${topic}, (${sql.param(JSON.stringify(payload ?? null), 'text')})::jsonb, ${actor.uid}, ${actor.companyId}, ${sql.array([...actor.groups], 'text')}) RETURNING id`));
|
|
35
|
+
await query(compile(sql `SELECT pg_notify(${OUTBOX_CHANNEL}, ${topic})`));
|
|
36
|
+
return Number(row?.id);
|
|
37
|
+
}
|
|
38
|
+
/** `env.enqueue`: inserts the job in the current transaction. Returns its id, or `null` when deduplicated. */
|
|
39
|
+
export async function enqueueJob(query, actor, name, payload, options = {}) {
|
|
40
|
+
assertName('job', name);
|
|
41
|
+
const attempts = options.attempts ?? 5;
|
|
42
|
+
if (!Number.isInteger(attempts) || attempts < 1)
|
|
43
|
+
throw new TypeError('attempts must be a positive integer.');
|
|
44
|
+
const rows = await query(compile(sql `INSERT INTO shutro_job (name, payload, key, run_at, max_attempts, uid, company_id, groups)
|
|
45
|
+
VALUES (${name}, (${sql.param(JSON.stringify(payload ?? null), 'text')})::jsonb, ${options.key ?? null}, ${options.runAt ?? new Date(0)}, ${attempts}, ${actor.uid}, ${actor.companyId}, ${sql.array([...actor.groups], 'text')})
|
|
46
|
+
ON CONFLICT ("key") WHERE "key" IS NOT NULL AND "state" IN ('pending', 'running') DO NOTHING RETURNING id`));
|
|
47
|
+
await query(compile(sql `SELECT pg_notify(${JOB_CHANNEL}, ${name})`));
|
|
48
|
+
return rows[0] === undefined ? null : Number(rows[0].id);
|
|
49
|
+
}
|
|
50
|
+
/** Exponential backoff with a cap, in milliseconds (attempt 1 → 1 s, 2 → 2 s, … ≤ 10 min). */
|
|
51
|
+
export function backoffMs(attempt) {
|
|
52
|
+
return Math.min(600_000, 1000 * 2 ** Math.max(0, attempt - 1));
|
|
53
|
+
}
|
|
54
|
+
/** Releases jobs whose worker died while running them (locked longer than `staleMs`). */
|
|
55
|
+
export async function releaseStale(driver, staleMs) {
|
|
56
|
+
const rows = await driver.query(compile(sql `UPDATE shutro_job SET state = 'pending', locked_at = NULL WHERE state = 'running' AND locked_at < now() - make_interval(secs => ${staleMs / 1000}) RETURNING id`));
|
|
57
|
+
return rows.length;
|
|
58
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Event subscribers and job workers (RFC 0018 §7.2–§7.3). Both claim work with row locks (`SKIP LOCKED`), run the
|
|
3
|
+
* handler in a `run()` scope as the emitting / enqueuing user, and record success in the handler's transaction.
|
|
4
|
+
* Failures are retried with exponential backoff; after the attempts run out, events go to `shutro_dead_event` and
|
|
5
|
+
* jobs to state `dead`.
|
|
6
|
+
*/
|
|
7
|
+
import type { Driver } from '../../driver-pg/index.js';
|
|
8
|
+
import type { Env, RunOptions } from '../env/env.js';
|
|
9
|
+
/** A committed event as subscribers receive it. */
|
|
10
|
+
export interface DeliveredEvent {
|
|
11
|
+
readonly id: number;
|
|
12
|
+
readonly topic: string;
|
|
13
|
+
readonly payload: unknown;
|
|
14
|
+
readonly createdAt: Date;
|
|
15
|
+
readonly uid: number;
|
|
16
|
+
readonly companyId: number;
|
|
17
|
+
}
|
|
18
|
+
/** A job as handlers receive it. */
|
|
19
|
+
export interface RunningJob {
|
|
20
|
+
readonly id: number;
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly attempt: number;
|
|
23
|
+
readonly maxAttempts: number;
|
|
24
|
+
}
|
|
25
|
+
/** A subscriber or worker: `drain()` processes what is due now; `start()` keeps processing until `stop()`. */
|
|
26
|
+
export interface Worker {
|
|
27
|
+
/** Processes everything due now; resolves with the number of events / jobs handled (successfully or not). */
|
|
28
|
+
drain(): Promise<number>;
|
|
29
|
+
/** Processes in the background: woken by NOTIFY, and polling every `pollMs` for retries and scheduled work. */
|
|
30
|
+
start(): void;
|
|
31
|
+
stop(): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
/** What workers need from a Shutro instance. */
|
|
34
|
+
export interface WorkerHost {
|
|
35
|
+
readonly driver: Driver;
|
|
36
|
+
run<T>(options: RunOptions, fn: (env: Env) => Promise<T>): Promise<T>;
|
|
37
|
+
bootstrap<T>(options: {
|
|
38
|
+
readonly reason: string;
|
|
39
|
+
readonly company?: number;
|
|
40
|
+
}, fn: (env: Env) => Promise<T>): Promise<T>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Delivers events of `topic` to `handler`, in id order, at least once; the cursor advances in the handler's
|
|
44
|
+
* transaction (exactly once for its database work). One active delivery per subscription name across processes.
|
|
45
|
+
*/
|
|
46
|
+
export declare function subscribe(host: WorkerHost, name: string, topic: string, handler: (event: DeliveredEvent, env: Env) => Promise<void>, options?: {
|
|
47
|
+
readonly attempts?: number;
|
|
48
|
+
readonly pollMs?: number;
|
|
49
|
+
}): Worker;
|
|
50
|
+
/**
|
|
51
|
+
* Runs due jobs with the given handlers (any number of workers and processes: `FOR UPDATE SKIP LOCKED`). A job is
|
|
52
|
+
* marked done in its handler's transaction; a failure is retried with backoff until its attempts run out (`dead`).
|
|
53
|
+
*/
|
|
54
|
+
export declare function work(host: WorkerHost, handlers: Readonly<Record<string, (payload: unknown, env: Env, job: RunningJob) => Promise<void>>>, options?: {
|
|
55
|
+
readonly pollMs?: number;
|
|
56
|
+
}): Worker;
|