@geonosis/document 0.1.1 → 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/CHANGELOG.md +113 -0
- package/README.md +144 -23
- package/dist/index.cjs +1206 -32
- package/dist/index.d.cts +387 -73
- package/dist/index.d.ts +387 -73
- package/dist/index.js +1199 -31
- package/migrations/0001_documents.sql +56 -0
- package/migrations/0002_documents_policies.sql +15 -0
- package/migrations/0003_document_revisions.sql +17 -0
- package/migrations/0004_document_revisions_policies.sql +23 -0
- package/package.json +8 -3
package/dist/index.js
CHANGED
|
@@ -27,35 +27,96 @@ var documentBodyVersioning = (definition) => ({
|
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
// src/core/document.ts
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
30
|
+
var fieldPatterns = {
|
|
31
|
+
calendarDate: /^\d{4}-\d{2}-\d{2}$/,
|
|
32
|
+
decimal: /^-?\d+(?:\.\d+)?$/
|
|
33
|
+
};
|
|
34
|
+
var FIELD_CHECKS = {
|
|
35
|
+
calendarDate: {
|
|
36
|
+
message: "a calendar date is `YYYY-MM-DD`, never prose",
|
|
37
|
+
test: (value) => typeof value === "string" && fieldPatterns.calendarDate.test(value)
|
|
38
|
+
},
|
|
39
|
+
decimal: {
|
|
40
|
+
message: "an amount is a decimal string, never a float",
|
|
41
|
+
test: (value) => typeof value === "string" && fieldPatterns.decimal.test(value)
|
|
42
|
+
},
|
|
43
|
+
int: {
|
|
44
|
+
message: "an integer",
|
|
45
|
+
test: (value) => typeof value === "number" && Number.isInteger(value)
|
|
46
|
+
},
|
|
47
|
+
positiveInt: {
|
|
48
|
+
message: "a positive integer",
|
|
49
|
+
test: (value) => typeof value === "number" && Number.isInteger(value) && value > 0
|
|
50
|
+
},
|
|
51
|
+
text: { message: "a string", test: (value) => typeof value === "string" }
|
|
52
|
+
};
|
|
53
|
+
var validatorOf = (fields, options) => {
|
|
54
|
+
const nullable = options?.nullable ?? false;
|
|
55
|
+
return {
|
|
56
|
+
"~standard": {
|
|
57
|
+
validate: (input) => {
|
|
58
|
+
if (input === null || typeof input !== "object") {
|
|
59
|
+
return { issues: [{ message: "expected an object" }] };
|
|
60
|
+
}
|
|
61
|
+
const record = input;
|
|
62
|
+
const issues = [];
|
|
63
|
+
const value = {};
|
|
64
|
+
for (const [key, kind] of Object.entries(fields)) {
|
|
65
|
+
const held = record[key];
|
|
66
|
+
value[key] = held;
|
|
67
|
+
if (nullable && held === null) continue;
|
|
68
|
+
if (!FIELD_CHECKS[kind].test(held)) {
|
|
69
|
+
issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return issues.length > 0 ? { issues } : { value };
|
|
73
|
+
},
|
|
74
|
+
vendor: "geonosis-document",
|
|
75
|
+
version: 1
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
var parseWith = (schema, input) => {
|
|
80
|
+
const result = schema["~standard"].validate(input);
|
|
81
|
+
if (result instanceof Promise) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
"Document.head and Document.record parse synchronously; an async Standard Schema cannot back them"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
if (result.issues !== void 0) {
|
|
87
|
+
throw new Error(result.issues.map((issue) => issue.message).join("; "));
|
|
88
|
+
}
|
|
89
|
+
return result.value;
|
|
90
|
+
};
|
|
91
|
+
var headFields = {
|
|
92
|
+
status: "text",
|
|
93
|
+
issueDate: "calendarDate",
|
|
94
|
+
dueDate: "calendarDate",
|
|
95
|
+
counterparty: "text",
|
|
96
|
+
externalRef: "text",
|
|
97
|
+
revision: "text",
|
|
98
|
+
total: "decimal"
|
|
99
|
+
};
|
|
100
|
+
var recordFields = {
|
|
101
|
+
version: "positiveInt",
|
|
102
|
+
createdAt: "int",
|
|
103
|
+
updatedAt: "int"
|
|
104
|
+
};
|
|
105
|
+
var headValidator = validatorOf(headFields, { nullable: true });
|
|
106
|
+
var recordValidator = validatorOf(recordFields);
|
|
47
107
|
var Document = {
|
|
48
|
-
head:
|
|
49
|
-
|
|
108
|
+
head: headValidator,
|
|
109
|
+
headFields,
|
|
110
|
+
record: recordValidator,
|
|
111
|
+
recordFields,
|
|
50
112
|
extend: (definition) => ({
|
|
51
113
|
...definition,
|
|
52
|
-
headOf: (body) =>
|
|
114
|
+
headOf: (body) => parseWith(headValidator, definition.headOf(body)),
|
|
53
115
|
is: (document) => document.entity === definition.name
|
|
54
116
|
})
|
|
55
117
|
};
|
|
56
118
|
|
|
57
119
|
// src/core/entities.ts
|
|
58
|
-
import { z as z2 } from "zod";
|
|
59
120
|
var documentEntities = (map) => {
|
|
60
121
|
for (const [key, entity] of Object.entries(map)) {
|
|
61
122
|
if (entity.name !== key) {
|
|
@@ -65,21 +126,38 @@ var documentEntities = (map) => {
|
|
|
65
126
|
}
|
|
66
127
|
}
|
|
67
128
|
const names = Object.keys(map);
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
const
|
|
71
|
-
|
|
129
|
+
const values = Object.values(map);
|
|
130
|
+
const fold = (pick) => values.map(pick);
|
|
131
|
+
const distinctBy = (pick) => [
|
|
132
|
+
...new Set(fold(pick))
|
|
133
|
+
];
|
|
72
134
|
return {
|
|
135
|
+
bodies: distinctBy((entity) => entity.body),
|
|
136
|
+
cards: distinctBy((entity) => entity.card.schema),
|
|
73
137
|
entities: map,
|
|
74
|
-
|
|
75
|
-
nameSchema,
|
|
76
|
-
bodySchema,
|
|
77
|
-
bodyDecoder,
|
|
138
|
+
fold,
|
|
78
139
|
instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
|
|
79
|
-
named: (name) => map[name]
|
|
140
|
+
named: (name) => map[name],
|
|
141
|
+
names
|
|
80
142
|
};
|
|
81
143
|
};
|
|
82
144
|
|
|
145
|
+
// src/core/actor.ts
|
|
146
|
+
var SYSTEM_PREFIX = "system:";
|
|
147
|
+
var systemActor = (name) => `${SYSTEM_PREFIX}${name}`;
|
|
148
|
+
var isSystemActor = (actor) => actor.startsWith(SYSTEM_PREFIX);
|
|
149
|
+
|
|
150
|
+
// src/core/hash.ts
|
|
151
|
+
import { createHash } from "crypto";
|
|
152
|
+
var canonicalOf = (input) => {
|
|
153
|
+
if (input === null || typeof input !== "object") return input;
|
|
154
|
+
if (Array.isArray(input)) return input.map(canonicalOf);
|
|
155
|
+
return Object.fromEntries(
|
|
156
|
+
Object.entries(input).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, held]) => [key, canonicalOf(held)])
|
|
157
|
+
);
|
|
158
|
+
};
|
|
159
|
+
var hashOf = (payload) => createHash("sha256").update(JSON.stringify(canonicalOf(payload))).digest("hex");
|
|
160
|
+
|
|
83
161
|
// src/core/naming.ts
|
|
84
162
|
var camelOf = (name) => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
85
163
|
var documentIdentifiers = (name) => {
|
|
@@ -97,14 +175,1104 @@ var documentIdentifiers = (name) => {
|
|
|
97
175
|
// src/core/status.ts
|
|
98
176
|
var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
|
|
99
177
|
var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
|
|
178
|
+
|
|
179
|
+
// src/store/ddl.ts
|
|
180
|
+
import {
|
|
181
|
+
DbRefusal,
|
|
182
|
+
ENTITY_PLACEHOLDERS,
|
|
183
|
+
entityMigrations
|
|
184
|
+
} from "@geonosis/db";
|
|
185
|
+
var DEFAULT_DOCUMENT_TABLE = "documents";
|
|
186
|
+
var DEFAULT_ENTITY_COLUMN = "entity";
|
|
187
|
+
var DEFAULT_VERSION_COLUMN = "version";
|
|
188
|
+
var DEFAULT_TOTAL_COLUMN = "total";
|
|
189
|
+
var DEFAULT_TENANT_COLUMN = "tenant_id";
|
|
190
|
+
var DEFAULT_REVISIONS_TABLE = "document_revisions";
|
|
191
|
+
var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
|
|
192
|
+
var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
|
|
193
|
+
var appendOnlyTables = (options = {}) => {
|
|
194
|
+
if (options.revisions === false) return [];
|
|
195
|
+
return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
|
|
196
|
+
};
|
|
197
|
+
var documentRoleStatements = (appRole, options = {}) => {
|
|
198
|
+
if (typeof appRole !== "string" || appRole === "") {
|
|
199
|
+
throw new DbRefusal(
|
|
200
|
+
"documentRoleStatements needs an `appRole` \u2014 the name a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s"
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
const role = quotedName(appRole);
|
|
204
|
+
const on = (table) => options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
|
|
205
|
+
return appendOnlyTables(options).flatMap((table) => [
|
|
206
|
+
`revoke update, delete on ${on(table)} from ${role}`,
|
|
207
|
+
`grant select, insert on ${on(table)} to ${role}`
|
|
208
|
+
]);
|
|
209
|
+
};
|
|
210
|
+
var DDL_TYPE_OF = { decimal: "numeric" };
|
|
211
|
+
var headIndexedColumns = (totalColumn) => Object.entries(headFields).map(([key, kind]) => {
|
|
212
|
+
const column = key === "total" ? totalColumn : key;
|
|
213
|
+
const type = DDL_TYPE_OF[kind];
|
|
214
|
+
return type === void 0 ? column : { column, type };
|
|
215
|
+
});
|
|
216
|
+
var quotedName = (name) => `"${name}"`;
|
|
217
|
+
var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
218
|
+
var settingDefault = (name) => `current_setting('${name}', true)`;
|
|
219
|
+
var immutableFunctionName = (table) => `${table}_immutable`;
|
|
220
|
+
var noUpdateOrDeleteTriggerName = (table) => `${table}_no_update_or_delete`;
|
|
221
|
+
var revisionsMigrations = (options, entityColumn, tenantColumn) => {
|
|
222
|
+
const revisions = options.revisions;
|
|
223
|
+
if (revisions === false) return [];
|
|
224
|
+
if (typeof options.appRole !== "string" || options.appRole === "") {
|
|
225
|
+
throw new DbRefusal(
|
|
226
|
+
"documentMigrations needs an `appRole` to render the log\u2019s wall \u2014 the role a consumer\u2019s application connects as belongs to whoever runs the database, and one baked in here would be another repo\u2019s. Pass it, or opt out of the log entirely with `revisions: false`"
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
const appRole = options.appRole;
|
|
230
|
+
const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
|
|
231
|
+
const table = revisions?.table ?? DEFAULT_REVISIONS_TABLE;
|
|
232
|
+
const on = options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
|
|
233
|
+
const [, policies] = entityMigrations({
|
|
234
|
+
columns: { tenant: tenantColumn },
|
|
235
|
+
...options.schema === void 0 ? {} : { schema: options.schema },
|
|
236
|
+
settings: options.settings,
|
|
237
|
+
table
|
|
238
|
+
});
|
|
239
|
+
if (policies === void 0) {
|
|
240
|
+
throw new Error(
|
|
241
|
+
"entityMigrations answered with no policies migration to borrow for the log\u2019s tenant wall"
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
const functionName = immutableFunctionName(table);
|
|
245
|
+
const triggerName = noUpdateOrDeleteTriggerName(table);
|
|
246
|
+
const qualifiedFunction = options.schema === void 0 ? quotedName(functionName) : `${quotedName(options.schema)}.${quotedName(functionName)}`;
|
|
247
|
+
return [
|
|
248
|
+
{
|
|
249
|
+
name: `0003_${table}.sql`,
|
|
250
|
+
statements: [
|
|
251
|
+
`create table if not exists ${on} (
|
|
252
|
+
${quotedName(tenantColumn)} text not null default ${settingDefault(options.settings.tenantSetting)},
|
|
253
|
+
${quotedName(entityColumn)} text not null,
|
|
254
|
+
${quotedName("ref")} text not null,
|
|
255
|
+
${quotedName("lineage")} integer not null,
|
|
256
|
+
${quotedName("version")} integer not null,
|
|
257
|
+
${quotedName(revisionKindColumn)} text not null,
|
|
258
|
+
${quotedName("body")} jsonb not null,
|
|
259
|
+
${quotedName("actor")} text not null,
|
|
260
|
+
${quotedName("reason")} text,
|
|
261
|
+
${quotedName("at")} bigint not null default (extract(epoch from clock_timestamp()) * 1000)::bigint,
|
|
262
|
+
${quotedName("prev_hash")} text,
|
|
263
|
+
${quotedName("hash")} text not null,
|
|
264
|
+
${quotedName("compensation_of")} integer,
|
|
265
|
+
constraint ${quotedName(`${table}_pkey`)} primary key (${quotedName(tenantColumn)}, ${quotedName(entityColumn)}, ${quotedName("ref")}, ${quotedName("lineage")}, ${quotedName("version")}),
|
|
266
|
+
constraint ${quotedName(`${table}_${revisionKindColumn}_check`)} check (${quotedName(revisionKindColumn)} in ('committed', 'retired', 'reinstated'))
|
|
267
|
+
)`
|
|
268
|
+
]
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
...policies,
|
|
272
|
+
name: `0004_${table}_policies.sql`,
|
|
273
|
+
statements: [
|
|
274
|
+
...policies.statements,
|
|
275
|
+
`create or replace function ${qualifiedFunction}() returns trigger language plpgsql as $$ begin raise exception 'this table is append-only: % is not permitted', tg_op; end; $$`,
|
|
276
|
+
`drop trigger if exists ${quotedName(triggerName)} on ${on}`,
|
|
277
|
+
`create trigger ${quotedName(triggerName)} before update or delete on ${on} for each row execute function ${qualifiedFunction}()`,
|
|
278
|
+
`do $$ begin if exists (select from pg_roles where rolname = ${literalName(appRole)}) then execute 'revoke update, delete on ${on} from ' || quote_ident(${literalName(appRole)}); end if; end $$`
|
|
279
|
+
]
|
|
280
|
+
}
|
|
281
|
+
];
|
|
282
|
+
};
|
|
283
|
+
var documentMigrations = (options) => {
|
|
284
|
+
const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
|
|
285
|
+
const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN;
|
|
286
|
+
const totalColumn = nameOf(options.columns?.total, DEFAULT_TOTAL_COLUMN);
|
|
287
|
+
const tenantColumn = nameOf(options.columns?.tenant, DEFAULT_TENANT_COLUMN);
|
|
288
|
+
const { entity: _entity, total: _total, version, ...restColumns } = options.columns ?? {};
|
|
289
|
+
const migrations = entityMigrations({
|
|
290
|
+
columns: { ...restColumns, version: version ?? DEFAULT_VERSION_COLUMN },
|
|
291
|
+
constants: { [entityColumn]: "" },
|
|
292
|
+
indexed: headIndexedColumns(totalColumn),
|
|
293
|
+
key: "number",
|
|
294
|
+
order: [{ column: "number" }],
|
|
295
|
+
...options.schema === void 0 ? {} : { schema: options.schema },
|
|
296
|
+
settings: options.settings,
|
|
297
|
+
sortable: Object.keys(headFields).map((key) => key === "total" ? totalColumn : key),
|
|
298
|
+
table
|
|
299
|
+
});
|
|
300
|
+
const [tableMigration, ...rest] = migrations;
|
|
301
|
+
if (tableMigration === void 0) {
|
|
302
|
+
throw new Error(
|
|
303
|
+
"entityMigrations answered with no table migration to append the listing index to"
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
const listingIndex = `create index if not exists ${quotedName(`${table}_${entityColumn}_issueDate_idx`)} on ${quotedName(table)} (${quotedName(entityColumn)}, ${quotedName("issueDate")})`;
|
|
307
|
+
const on = options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
|
|
308
|
+
const lineageAndHash = [
|
|
309
|
+
`alter table ${on} add column if not exists ${quotedName("lineage")} integer not null default 1`,
|
|
310
|
+
`alter table ${on} add column if not exists ${quotedName("hash")} text`
|
|
311
|
+
];
|
|
312
|
+
return [
|
|
313
|
+
{
|
|
314
|
+
...tableMigration,
|
|
315
|
+
statements: [...tableMigration.statements, listingIndex, ...lineageAndHash]
|
|
316
|
+
},
|
|
317
|
+
...rest,
|
|
318
|
+
...revisionsMigrations(options, entityColumn, tenantColumn)
|
|
319
|
+
];
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
// src/store/store.ts
|
|
323
|
+
import { rowsOf } from "@geonosis/conformance";
|
|
324
|
+
import {
|
|
325
|
+
DbRefusal as DbRefusal2,
|
|
326
|
+
defineEntity,
|
|
327
|
+
fragment
|
|
328
|
+
} from "@geonosis/db";
|
|
329
|
+
var DEFAULT_ENTITY_COLUMN2 = "entity";
|
|
330
|
+
var DEFAULT_VERSION_COLUMN2 = "version";
|
|
331
|
+
var DEFAULT_TOTAL_COLUMN2 = "total";
|
|
332
|
+
var DEFAULT_COLUMNS = { createdAt: "created_at", retiredAt: "retired_at", tenant: "tenant_id" };
|
|
333
|
+
var UNDO_ACTOR = systemActor("document.undo");
|
|
334
|
+
var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
|
|
335
|
+
var quote = (name) => `"${name}"`;
|
|
336
|
+
var chain = (before, after) => ({
|
|
337
|
+
chunks: [
|
|
338
|
+
...before.chunks.slice(0, -1),
|
|
339
|
+
`${before.chunks.at(-1) ?? ""}${after.chunks[0] ?? ""}`,
|
|
340
|
+
...after.chunks.slice(1)
|
|
341
|
+
],
|
|
342
|
+
values: [...before.values, ...after.values]
|
|
343
|
+
});
|
|
344
|
+
var chainAll = (pieces) => pieces.reduce((built, piece) => chain(built, piece), fragment([""]));
|
|
345
|
+
var text = (chunk) => fragment([chunk]);
|
|
346
|
+
var bound = (held) => fragment(["", ""], [held]);
|
|
347
|
+
var setList = (columns) => columns.flatMap((one, at) => [
|
|
348
|
+
text(`${at === 0 ? "" : ", "}${quote(one.column)} = `),
|
|
349
|
+
bound(one.held)
|
|
350
|
+
]);
|
|
351
|
+
var valuesList = (columns) => columns.flatMap((one, at) => [text(at === 0 ? "" : ", "), bound(one.held)]);
|
|
352
|
+
var readBody = (entity, entityName, ref, stored) => {
|
|
353
|
+
const migrated = migrateBody(entity, stored);
|
|
354
|
+
const result = entity.body["~standard"].validate(migrated);
|
|
355
|
+
if (result instanceof Promise) {
|
|
356
|
+
throw new Error(
|
|
357
|
+
`${entityName} ${ref}: this entity's body schema validates asynchronously, and a stored body can only be read synchronously here`
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
if (result.issues !== void 0) {
|
|
361
|
+
throw new Error(
|
|
362
|
+
`${entityName} ${ref}'s stored body no longer satisfies its own schema after migration: ${result.issues.map((issue) => issue.message).join("; ")}`
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
return result.value;
|
|
366
|
+
};
|
|
367
|
+
var bucketExpr = (unit, column) => `to_char(date_trunc('${unit}', ${quote(column)}::date), 'YYYY-MM-DD')`;
|
|
368
|
+
var byExpr = (by, columnOf) => by === "entity" ? quote(columnOf("entity")) : by === "status" ? quote(columnOf("status")) : bucketExpr(by.bucket, columnOf(by.of));
|
|
369
|
+
var documentStore = (options) => {
|
|
370
|
+
const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
|
|
371
|
+
const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN2;
|
|
372
|
+
const versionColumn = nameOf2(options.columns?.version, DEFAULT_VERSION_COLUMN2);
|
|
373
|
+
const tenantColumn = nameOf2(options.columns?.tenant, DEFAULT_COLUMNS.tenant);
|
|
374
|
+
const createdAtColumn = nameOf2(options.columns?.createdAt, DEFAULT_COLUMNS.createdAt);
|
|
375
|
+
const retiredAtColumn = nameOf2(options.columns?.retiredAt, DEFAULT_COLUMNS.retiredAt);
|
|
376
|
+
const totalColumn = nameOf2(options.columns?.total, DEFAULT_TOTAL_COLUMN2);
|
|
377
|
+
const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
|
|
378
|
+
const { archive, registry, schema, seam } = options;
|
|
379
|
+
const tenantKey = seam.tenantKey;
|
|
380
|
+
const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
|
|
381
|
+
const columnOf = (column) => column === "entity" ? entityColumn : column === "total" ? totalColumn : column;
|
|
382
|
+
const needsLog = () => {
|
|
383
|
+
if (revisionsTable === void 0) {
|
|
384
|
+
throw new DbRefusal2(
|
|
385
|
+
"this store has no log \u2014 `documentStore({ revisions: false })` opted out of the append-only record entirely, and the write model has no other door"
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
return revisionsTable;
|
|
389
|
+
};
|
|
390
|
+
const currentDbTime = async (tx) => {
|
|
391
|
+
const [row] = rowsOf(
|
|
392
|
+
await seam.send(
|
|
393
|
+
tx,
|
|
394
|
+
text('select (extract(epoch from clock_timestamp()) * 1000)::bigint as "now"')
|
|
395
|
+
)
|
|
396
|
+
);
|
|
397
|
+
return Number(row?.now ?? Date.now());
|
|
398
|
+
};
|
|
399
|
+
const lockedProjection = async (tx, tenantId, entityName, ref) => {
|
|
400
|
+
const [row] = rowsOf(
|
|
401
|
+
await seam.send(
|
|
402
|
+
tx,
|
|
403
|
+
chainAll([
|
|
404
|
+
text(
|
|
405
|
+
`select ${quote("body")} as "body", ${quote(versionColumn)} as "version", ${quote("lineage")} as "lineage", ${quote("hash")} as "hash", ${quote(retiredAtColumn)} as "retiredAt" from ${quote(table)} where ${quote(tenantColumn)} = `
|
|
406
|
+
),
|
|
407
|
+
bound(tenantId),
|
|
408
|
+
text(` and ${quote(entityColumn)} = `),
|
|
409
|
+
bound(entityName),
|
|
410
|
+
text(` and ${quote("number")} = `),
|
|
411
|
+
bound(ref),
|
|
412
|
+
text(" for update")
|
|
413
|
+
])
|
|
414
|
+
)
|
|
415
|
+
);
|
|
416
|
+
if (row === void 0) return void 0;
|
|
417
|
+
return {
|
|
418
|
+
body: row.body,
|
|
419
|
+
hash: row.hash ?? "",
|
|
420
|
+
lineage: row.lineage,
|
|
421
|
+
retiredAt: row.retiredAt === null ? null : Number(row.retiredAt),
|
|
422
|
+
version: row.version
|
|
423
|
+
};
|
|
424
|
+
};
|
|
425
|
+
const currentLineageOf = async (tx, tenantId, entityName, ref) => {
|
|
426
|
+
const [row] = rowsOf(
|
|
427
|
+
await seam.send(
|
|
428
|
+
tx,
|
|
429
|
+
chainAll([
|
|
430
|
+
text(
|
|
431
|
+
`select ${quote("lineage")} as "lineage" from ${quote(table)} where ${quote(tenantColumn)} = `
|
|
432
|
+
),
|
|
433
|
+
bound(tenantId),
|
|
434
|
+
text(` and ${quote(entityColumn)} = `),
|
|
435
|
+
bound(entityName),
|
|
436
|
+
text(` and ${quote("number")} = `),
|
|
437
|
+
bound(ref)
|
|
438
|
+
])
|
|
439
|
+
)
|
|
440
|
+
);
|
|
441
|
+
return row?.lineage ?? 1;
|
|
442
|
+
};
|
|
443
|
+
const insertRevisionRow = async (tx, write) => {
|
|
444
|
+
const log = needsLog();
|
|
445
|
+
const hash = hashOf({
|
|
446
|
+
actor: write.actor,
|
|
447
|
+
at: write.at,
|
|
448
|
+
body: write.body,
|
|
449
|
+
entity: write.entityName,
|
|
450
|
+
kind: write.kind,
|
|
451
|
+
lineage: write.lineage,
|
|
452
|
+
prevHash: write.prevHash,
|
|
453
|
+
reason: write.reason,
|
|
454
|
+
ref: write.ref,
|
|
455
|
+
tenant: write.tenantId,
|
|
456
|
+
version: write.version
|
|
457
|
+
});
|
|
458
|
+
await seam.send(
|
|
459
|
+
tx,
|
|
460
|
+
chainAll([
|
|
461
|
+
text(
|
|
462
|
+
`insert into ${quote(log)} (${quote(tenantColumn)}, ${quote(entityColumn)}, ${quote("ref")}, ${quote("lineage")}, ${quote("version")}, ${quote(revisionKindColumn)}, ${quote("body")}, ${quote("actor")}, ${quote("reason")}, ${quote("at")}, ${quote("prev_hash")}, ${quote("hash")}, ${quote("compensation_of")}) values (`
|
|
463
|
+
),
|
|
464
|
+
...valuesList([
|
|
465
|
+
{ column: tenantColumn, held: write.tenantId },
|
|
466
|
+
{ column: entityColumn, held: write.entityName },
|
|
467
|
+
{ column: "ref", held: write.ref },
|
|
468
|
+
{ column: "lineage", held: write.lineage },
|
|
469
|
+
{ column: "version", held: write.version },
|
|
470
|
+
{ column: revisionKindColumn, held: write.kind },
|
|
471
|
+
{ column: "body", held: write.body },
|
|
472
|
+
{ column: "actor", held: write.actor },
|
|
473
|
+
{ column: "reason", held: write.reason },
|
|
474
|
+
{ column: "at", held: write.at },
|
|
475
|
+
{ column: "prev_hash", held: write.prevHash },
|
|
476
|
+
{ column: "hash", held: hash },
|
|
477
|
+
{ column: "compensation_of", held: write.compensationOf }
|
|
478
|
+
]),
|
|
479
|
+
text(")")
|
|
480
|
+
])
|
|
481
|
+
);
|
|
482
|
+
return hash;
|
|
483
|
+
};
|
|
484
|
+
const writeProjection = async (tx, write) => {
|
|
485
|
+
const headColumns = Object.entries(write.head).map(([key, held]) => ({
|
|
486
|
+
column: columnOf(key),
|
|
487
|
+
held
|
|
488
|
+
}));
|
|
489
|
+
if (write.create) {
|
|
490
|
+
await seam.send(
|
|
491
|
+
tx,
|
|
492
|
+
chainAll([
|
|
493
|
+
text(
|
|
494
|
+
`insert into ${quote(table)} (${[
|
|
495
|
+
tenantColumn,
|
|
496
|
+
entityColumn,
|
|
497
|
+
"number",
|
|
498
|
+
createdAtColumn,
|
|
499
|
+
"updated_at",
|
|
500
|
+
retiredAtColumn,
|
|
501
|
+
versionColumn,
|
|
502
|
+
"lineage",
|
|
503
|
+
"hash",
|
|
504
|
+
"body",
|
|
505
|
+
...headColumns.map((one) => one.column)
|
|
506
|
+
].map(quote).join(", ")}) values (`
|
|
507
|
+
),
|
|
508
|
+
...valuesList([
|
|
509
|
+
{ column: tenantColumn, held: write.tenantId },
|
|
510
|
+
{ column: entityColumn, held: write.entityName },
|
|
511
|
+
{ column: "number", held: write.ref },
|
|
512
|
+
{ column: createdAtColumn, held: write.at },
|
|
513
|
+
{ column: "updated_at", held: write.at },
|
|
514
|
+
{ column: retiredAtColumn, held: write.retiredAt },
|
|
515
|
+
{ column: versionColumn, held: write.version },
|
|
516
|
+
{ column: "lineage", held: write.lineage },
|
|
517
|
+
{ column: "hash", held: write.hash },
|
|
518
|
+
{ column: "body", held: write.body },
|
|
519
|
+
...headColumns
|
|
520
|
+
]),
|
|
521
|
+
text(")")
|
|
522
|
+
])
|
|
523
|
+
);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
await seam.send(
|
|
527
|
+
tx,
|
|
528
|
+
chainAll([
|
|
529
|
+
text(`update ${quote(table)} set `),
|
|
530
|
+
...setList([
|
|
531
|
+
{ column: "updated_at", held: write.at },
|
|
532
|
+
{ column: retiredAtColumn, held: write.retiredAt },
|
|
533
|
+
{ column: versionColumn, held: write.version },
|
|
534
|
+
{ column: "lineage", held: write.lineage },
|
|
535
|
+
{ column: "hash", held: write.hash },
|
|
536
|
+
{ column: "body", held: write.body },
|
|
537
|
+
...headColumns
|
|
538
|
+
]),
|
|
539
|
+
text(` where ${quote(tenantColumn)} = `),
|
|
540
|
+
bound(write.tenantId),
|
|
541
|
+
text(` and ${quote(entityColumn)} = `),
|
|
542
|
+
bound(write.entityName),
|
|
543
|
+
text(` and ${quote("number")} = `),
|
|
544
|
+
bound(write.ref)
|
|
545
|
+
])
|
|
546
|
+
);
|
|
547
|
+
};
|
|
548
|
+
const upsertProjection = async (tx, write) => {
|
|
549
|
+
const headColumns = Object.entries(write.head).map(([key, held]) => ({
|
|
550
|
+
column: columnOf(key),
|
|
551
|
+
held
|
|
552
|
+
}));
|
|
553
|
+
const inserted = [
|
|
554
|
+
{ column: tenantColumn, held: write.tenantId },
|
|
555
|
+
{ column: entityColumn, held: write.entityName },
|
|
556
|
+
{ column: "number", held: write.ref },
|
|
557
|
+
{ column: createdAtColumn, held: write.at },
|
|
558
|
+
{ column: "updated_at", held: write.at },
|
|
559
|
+
{ column: retiredAtColumn, held: write.retiredAt },
|
|
560
|
+
{ column: versionColumn, held: write.version },
|
|
561
|
+
{ column: "lineage", held: write.lineage },
|
|
562
|
+
{ column: "hash", held: write.hash },
|
|
563
|
+
{ column: "body", held: write.body },
|
|
564
|
+
...headColumns
|
|
565
|
+
];
|
|
566
|
+
const conflictColumns = /* @__PURE__ */ new Set([tenantColumn, entityColumn, "number"]);
|
|
567
|
+
const conflict = [...conflictColumns].map(quote).join(", ");
|
|
568
|
+
const updated = inserted.filter((one) => !conflictColumns.has(one.column));
|
|
569
|
+
await seam.send(
|
|
570
|
+
tx,
|
|
571
|
+
chainAll([
|
|
572
|
+
text(
|
|
573
|
+
`insert into ${quote(table)} (${inserted.map((one) => quote(one.column)).join(", ")}) values (`
|
|
574
|
+
),
|
|
575
|
+
...valuesList(inserted),
|
|
576
|
+
text(`) on conflict (${conflict}) do update set `),
|
|
577
|
+
...setList(updated)
|
|
578
|
+
])
|
|
579
|
+
);
|
|
580
|
+
};
|
|
581
|
+
const revisionRowAt = async (tx, tenantId, entityName, ref, lineage, version) => {
|
|
582
|
+
const log = needsLog();
|
|
583
|
+
const [row] = rowsOf(
|
|
584
|
+
await seam.send(
|
|
585
|
+
tx,
|
|
586
|
+
chainAll([
|
|
587
|
+
text(
|
|
588
|
+
`select ${quote("version")} as "version", ${quote(revisionKindColumn)} as "kind", ${quote("body")} as "body", ${quote("actor")} as "actor", ${quote("reason")} as "reason", ${quote("at")} as "at", ${quote("prev_hash")} as "prevHash", ${quote("hash")} as "hash" from ${quote(log)} where ${quote(tenantColumn)} = `
|
|
589
|
+
),
|
|
590
|
+
bound(tenantId),
|
|
591
|
+
text(` and ${quote(entityColumn)} = `),
|
|
592
|
+
bound(entityName),
|
|
593
|
+
text(` and ${quote("ref")} = `),
|
|
594
|
+
bound(ref),
|
|
595
|
+
text(` and ${quote("lineage")} = `),
|
|
596
|
+
bound(lineage),
|
|
597
|
+
text(` and ${quote("version")} = `),
|
|
598
|
+
bound(version)
|
|
599
|
+
])
|
|
600
|
+
)
|
|
601
|
+
);
|
|
602
|
+
return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
|
|
603
|
+
};
|
|
604
|
+
const revisionRowAsOf = async (tx, tenantId, entityName, ref, lineage, at) => {
|
|
605
|
+
const log = needsLog();
|
|
606
|
+
const [row] = rowsOf(
|
|
607
|
+
await seam.send(
|
|
608
|
+
tx,
|
|
609
|
+
chainAll([
|
|
610
|
+
text(
|
|
611
|
+
`select ${quote("version")} as "version", ${quote(revisionKindColumn)} as "kind", ${quote("body")} as "body", ${quote("actor")} as "actor", ${quote("reason")} as "reason", ${quote("at")} as "at", ${quote("prev_hash")} as "prevHash", ${quote("hash")} as "hash" from ${quote(log)} where ${quote(tenantColumn)} = `
|
|
612
|
+
),
|
|
613
|
+
bound(tenantId),
|
|
614
|
+
text(` and ${quote(entityColumn)} = `),
|
|
615
|
+
bound(entityName),
|
|
616
|
+
text(` and ${quote("ref")} = `),
|
|
617
|
+
bound(ref),
|
|
618
|
+
text(` and ${quote("lineage")} = `),
|
|
619
|
+
bound(lineage),
|
|
620
|
+
text(` and ${quote("at")} <= `),
|
|
621
|
+
bound(at),
|
|
622
|
+
text(` order by ${quote("version")} desc limit 1`)
|
|
623
|
+
])
|
|
624
|
+
)
|
|
625
|
+
);
|
|
626
|
+
return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
|
|
627
|
+
};
|
|
628
|
+
const revisionRowsFor = async (tx, tenantId, entityName, ref, lineage) => {
|
|
629
|
+
const log = needsLog();
|
|
630
|
+
const rows = rowsOf(
|
|
631
|
+
await seam.send(
|
|
632
|
+
tx,
|
|
633
|
+
chainAll([
|
|
634
|
+
text(
|
|
635
|
+
`select ${quote("version")} as "version", ${quote(revisionKindColumn)} as "kind", ${quote("body")} as "body", ${quote("actor")} as "actor", ${quote("reason")} as "reason", ${quote("at")} as "at", ${quote("prev_hash")} as "prevHash", ${quote("hash")} as "hash" from ${quote(log)} where ${quote(tenantColumn)} = `
|
|
636
|
+
),
|
|
637
|
+
bound(tenantId),
|
|
638
|
+
text(` and ${quote(entityColumn)} = `),
|
|
639
|
+
bound(entityName),
|
|
640
|
+
text(` and ${quote("ref")} = `),
|
|
641
|
+
bound(ref),
|
|
642
|
+
text(` and ${quote("lineage")} = `),
|
|
643
|
+
bound(lineage),
|
|
644
|
+
text(` order by ${quote("version")} asc`)
|
|
645
|
+
])
|
|
646
|
+
)
|
|
647
|
+
);
|
|
648
|
+
return rows.map((row) => ({ ...row, at: Number(row.at), kind: row.kind }));
|
|
649
|
+
};
|
|
650
|
+
const entityStoreFor = (name) => {
|
|
651
|
+
const definition = registry.named(name);
|
|
652
|
+
const item = (row) => {
|
|
653
|
+
const body = readBody(definition, name, row.key, row.body);
|
|
654
|
+
const head = definition.headOf(body);
|
|
655
|
+
return registry.instance(name, {
|
|
656
|
+
...head,
|
|
657
|
+
body,
|
|
658
|
+
createdAt: row.createdAt,
|
|
659
|
+
number: row.key,
|
|
660
|
+
updatedAt: row.updatedAt,
|
|
661
|
+
version: row.version ?? 1
|
|
662
|
+
});
|
|
663
|
+
};
|
|
664
|
+
const instanceFromRevision = (ref, row) => {
|
|
665
|
+
const body = readBody(definition, name, ref, row.body);
|
|
666
|
+
const head = definition.headOf(body);
|
|
667
|
+
return registry.instance(name, {
|
|
668
|
+
...head,
|
|
669
|
+
body,
|
|
670
|
+
createdAt: row.at,
|
|
671
|
+
number: ref,
|
|
672
|
+
updatedAt: row.at,
|
|
673
|
+
version: row.version
|
|
674
|
+
});
|
|
675
|
+
};
|
|
676
|
+
const raw = defineEntity({
|
|
677
|
+
columns: { ...options.columns, version: versionColumn },
|
|
678
|
+
constants: { [entityColumn]: name },
|
|
679
|
+
filterable: Object.keys(headFields),
|
|
680
|
+
indexed: (body) => definition.headOf(body),
|
|
681
|
+
item,
|
|
682
|
+
key: { column: "number", param: "ref" },
|
|
683
|
+
order: [{ column: "number" }],
|
|
684
|
+
...schema === void 0 ? {} : { schema },
|
|
685
|
+
seam,
|
|
686
|
+
sortable: Object.keys(headFields),
|
|
687
|
+
table
|
|
688
|
+
});
|
|
689
|
+
const commitTx = seam.scoped(
|
|
690
|
+
async (tx, params) => {
|
|
691
|
+
const tenantId = params[tenantKey];
|
|
692
|
+
const prepared = definition.prepare(params.body);
|
|
693
|
+
const stamped = stampBody(definition, prepared);
|
|
694
|
+
const now = await currentDbTime(tx);
|
|
695
|
+
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
696
|
+
if (existing !== void 0 && existing.retiredAt !== null) {
|
|
697
|
+
throw new DbRefusal2(
|
|
698
|
+
`"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
const bodyChanged = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
|
|
702
|
+
if (existing !== void 0 && !bodyChanged) {
|
|
703
|
+
return {
|
|
704
|
+
committed: false,
|
|
705
|
+
lineage: existing.lineage,
|
|
706
|
+
ref: params.ref,
|
|
707
|
+
version: existing.version
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
const lineage = existing?.lineage ?? 1;
|
|
711
|
+
const version = existing === void 0 ? 1 : existing.version + 1;
|
|
712
|
+
const prevHash = existing?.hash ?? null;
|
|
713
|
+
const head = definition.headOf(prepared);
|
|
714
|
+
const hash = await insertRevisionRow(tx, {
|
|
715
|
+
actor: params.actor,
|
|
716
|
+
at: now,
|
|
717
|
+
body: stamped,
|
|
718
|
+
compensationOf: null,
|
|
719
|
+
entityName: name,
|
|
720
|
+
kind: "committed",
|
|
721
|
+
lineage,
|
|
722
|
+
prevHash,
|
|
723
|
+
ref: params.ref,
|
|
724
|
+
reason: params.reason ?? null,
|
|
725
|
+
tenantId,
|
|
726
|
+
version
|
|
727
|
+
});
|
|
728
|
+
await writeProjection(tx, {
|
|
729
|
+
at: now,
|
|
730
|
+
body: stamped,
|
|
731
|
+
create: existing === void 0,
|
|
732
|
+
entityName: name,
|
|
733
|
+
hash,
|
|
734
|
+
head,
|
|
735
|
+
lineage,
|
|
736
|
+
ref: params.ref,
|
|
737
|
+
retiredAt: null,
|
|
738
|
+
tenantId,
|
|
739
|
+
version
|
|
740
|
+
});
|
|
741
|
+
return {
|
|
742
|
+
archivable: {
|
|
743
|
+
actor: params.actor,
|
|
744
|
+
at: now,
|
|
745
|
+
body: stamped,
|
|
746
|
+
prevHash,
|
|
747
|
+
reason: params.reason ?? null
|
|
748
|
+
},
|
|
749
|
+
committed: true,
|
|
750
|
+
hash,
|
|
751
|
+
lineage,
|
|
752
|
+
previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
|
|
753
|
+
ref: params.ref,
|
|
754
|
+
version
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
);
|
|
758
|
+
const commit = async (handle, params) => {
|
|
759
|
+
const { archivable, ...answer } = await commitTx(handle, params);
|
|
760
|
+
if (archive === void 0 || !answer.committed || archivable === void 0) return answer;
|
|
761
|
+
const key = `${params[tenantKey]}/${name}/${answer.lineage}/${answer.version}.json`;
|
|
762
|
+
const payload = {
|
|
763
|
+
actor: archivable.actor,
|
|
764
|
+
at: archivable.at,
|
|
765
|
+
body: archivable.body,
|
|
766
|
+
entity: name,
|
|
767
|
+
hash: answer.hash,
|
|
768
|
+
kind: "committed",
|
|
769
|
+
lineage: answer.lineage,
|
|
770
|
+
prevHash: archivable.prevHash,
|
|
771
|
+
ref: params.ref,
|
|
772
|
+
reason: archivable.reason,
|
|
773
|
+
tenant: params[tenantKey],
|
|
774
|
+
version: answer.version
|
|
775
|
+
};
|
|
776
|
+
try {
|
|
777
|
+
await archive.put(key, new TextEncoder().encode(JSON.stringify(payload)), {
|
|
778
|
+
hash: answer.hash,
|
|
779
|
+
immutable: true
|
|
780
|
+
});
|
|
781
|
+
return { ...answer, archived: true };
|
|
782
|
+
} catch {
|
|
783
|
+
return { ...answer, archived: false };
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
const retire = seam.scoped(
|
|
787
|
+
async (tx, params) => {
|
|
788
|
+
const tenantId = params[tenantKey];
|
|
789
|
+
const now = await currentDbTime(tx);
|
|
790
|
+
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
791
|
+
if (existing === void 0) {
|
|
792
|
+
throw new DbRefusal2(`"${params.ref}" (${name}) has no document to retire`);
|
|
793
|
+
}
|
|
794
|
+
if (existing.retiredAt !== null) {
|
|
795
|
+
throw new DbRefusal2(`"${params.ref}" (${name}) is already retired`);
|
|
796
|
+
}
|
|
797
|
+
const version = existing.version + 1;
|
|
798
|
+
const head = definition.headOf(
|
|
799
|
+
readBody(definition, name, params.ref, existing.body)
|
|
800
|
+
);
|
|
801
|
+
const hash = await insertRevisionRow(tx, {
|
|
802
|
+
actor: params.actor,
|
|
803
|
+
at: now,
|
|
804
|
+
body: existing.body,
|
|
805
|
+
compensationOf: null,
|
|
806
|
+
entityName: name,
|
|
807
|
+
kind: "retired",
|
|
808
|
+
lineage: existing.lineage,
|
|
809
|
+
prevHash: existing.hash,
|
|
810
|
+
ref: params.ref,
|
|
811
|
+
reason: params.reason ?? null,
|
|
812
|
+
tenantId,
|
|
813
|
+
version
|
|
814
|
+
});
|
|
815
|
+
await writeProjection(tx, {
|
|
816
|
+
at: now,
|
|
817
|
+
body: existing.body,
|
|
818
|
+
create: false,
|
|
819
|
+
entityName: name,
|
|
820
|
+
hash,
|
|
821
|
+
head,
|
|
822
|
+
lineage: existing.lineage,
|
|
823
|
+
ref: params.ref,
|
|
824
|
+
retiredAt: now,
|
|
825
|
+
tenantId,
|
|
826
|
+
version
|
|
827
|
+
});
|
|
828
|
+
return { hash, lineage: existing.lineage, ref: params.ref, version };
|
|
829
|
+
}
|
|
830
|
+
);
|
|
831
|
+
const succeed = seam.scoped(
|
|
832
|
+
async (tx, params) => {
|
|
833
|
+
const tenantId = params[tenantKey];
|
|
834
|
+
const now = await currentDbTime(tx);
|
|
835
|
+
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
836
|
+
if (existing === void 0 || existing.retiredAt === null) {
|
|
837
|
+
throw new DbRefusal2(
|
|
838
|
+
`"${params.ref}" (${name}) is not retired: succeed opens a new lineage only for a retired document \u2014 commit is the door for a live one`
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
const prepared = definition.prepare(params.body);
|
|
842
|
+
const stamped = stampBody(definition, prepared);
|
|
843
|
+
const head = definition.headOf(prepared);
|
|
844
|
+
const lineage = existing.lineage + 1;
|
|
845
|
+
const hash = await insertRevisionRow(tx, {
|
|
846
|
+
actor: params.actor,
|
|
847
|
+
at: now,
|
|
848
|
+
body: stamped,
|
|
849
|
+
compensationOf: null,
|
|
850
|
+
entityName: name,
|
|
851
|
+
kind: "committed",
|
|
852
|
+
lineage,
|
|
853
|
+
prevHash: null,
|
|
854
|
+
ref: params.ref,
|
|
855
|
+
reason: params.reason ?? null,
|
|
856
|
+
tenantId,
|
|
857
|
+
version: 1
|
|
858
|
+
});
|
|
859
|
+
await writeProjection(tx, {
|
|
860
|
+
at: now,
|
|
861
|
+
body: stamped,
|
|
862
|
+
create: false,
|
|
863
|
+
entityName: name,
|
|
864
|
+
hash,
|
|
865
|
+
head,
|
|
866
|
+
lineage,
|
|
867
|
+
ref: params.ref,
|
|
868
|
+
retiredAt: null,
|
|
869
|
+
tenantId,
|
|
870
|
+
version: 1
|
|
871
|
+
});
|
|
872
|
+
return { committed: true, hash, lineage, previous: null, ref: params.ref, version: 1 };
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
const reinstate = seam.scoped(
|
|
876
|
+
async (tx, params) => {
|
|
877
|
+
const tenantId = params[tenantKey];
|
|
878
|
+
const now = await currentDbTime(tx);
|
|
879
|
+
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
880
|
+
if (existing === void 0 || existing.retiredAt === null) {
|
|
881
|
+
throw new DbRefusal2(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
|
|
882
|
+
}
|
|
883
|
+
const version = existing.version + 1;
|
|
884
|
+
const head = definition.headOf(
|
|
885
|
+
readBody(definition, name, params.ref, existing.body)
|
|
886
|
+
);
|
|
887
|
+
const hash = await insertRevisionRow(tx, {
|
|
888
|
+
actor: params.actor,
|
|
889
|
+
at: now,
|
|
890
|
+
body: existing.body,
|
|
891
|
+
compensationOf: null,
|
|
892
|
+
entityName: name,
|
|
893
|
+
kind: "reinstated",
|
|
894
|
+
lineage: existing.lineage,
|
|
895
|
+
prevHash: existing.hash,
|
|
896
|
+
ref: params.ref,
|
|
897
|
+
reason: params.reason ?? null,
|
|
898
|
+
tenantId,
|
|
899
|
+
version
|
|
900
|
+
});
|
|
901
|
+
await writeProjection(tx, {
|
|
902
|
+
at: now,
|
|
903
|
+
body: existing.body,
|
|
904
|
+
create: false,
|
|
905
|
+
entityName: name,
|
|
906
|
+
hash,
|
|
907
|
+
head,
|
|
908
|
+
lineage: existing.lineage,
|
|
909
|
+
ref: params.ref,
|
|
910
|
+
retiredAt: null,
|
|
911
|
+
tenantId,
|
|
912
|
+
version
|
|
913
|
+
});
|
|
914
|
+
return { hash, lineage: existing.lineage, ref: params.ref, version };
|
|
915
|
+
}
|
|
916
|
+
);
|
|
917
|
+
const at = seam.scoped(
|
|
918
|
+
async (tx, params) => {
|
|
919
|
+
const tenantId = params[tenantKey];
|
|
920
|
+
const lineage = await currentLineageOf(tx, tenantId, name, params.ref);
|
|
921
|
+
const row = await revisionRowAt(tx, tenantId, name, params.ref, lineage, params.version);
|
|
922
|
+
return row === void 0 ? null : instanceFromRevision(params.ref, row);
|
|
923
|
+
}
|
|
924
|
+
);
|
|
925
|
+
const asOf = seam.scoped(
|
|
926
|
+
async (tx, params) => {
|
|
927
|
+
const tenantId = params[tenantKey];
|
|
928
|
+
const lineage = await currentLineageOf(tx, tenantId, name, params.ref);
|
|
929
|
+
const row = await revisionRowAsOf(tx, tenantId, name, params.ref, lineage, params.at);
|
|
930
|
+
return row === void 0 ? null : instanceFromRevision(params.ref, row);
|
|
931
|
+
}
|
|
932
|
+
);
|
|
933
|
+
const history = seam.scoped(
|
|
934
|
+
async (tx, params) => {
|
|
935
|
+
const tenantId = params[tenantKey];
|
|
936
|
+
const lineage = params.lineage ?? await currentLineageOf(tx, tenantId, name, params.ref);
|
|
937
|
+
const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
|
|
938
|
+
return rows.map((row) => ({
|
|
939
|
+
actor: row.actor,
|
|
940
|
+
at: row.at,
|
|
941
|
+
body: readBody(definition, name, `${params.ref} version ${row.version}`, row.body),
|
|
942
|
+
hash: row.hash,
|
|
943
|
+
kind: row.kind,
|
|
944
|
+
reason: row.reason,
|
|
945
|
+
version: row.version
|
|
946
|
+
}));
|
|
947
|
+
}
|
|
948
|
+
);
|
|
949
|
+
const verify = seam.scoped(
|
|
950
|
+
async (tx, params) => {
|
|
951
|
+
const tenantId = params[tenantKey];
|
|
952
|
+
const lineage = params.lineage ?? await currentLineageOf(tx, tenantId, name, params.ref);
|
|
953
|
+
const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
|
|
954
|
+
let previousHash = null;
|
|
955
|
+
for (const row of rows) {
|
|
956
|
+
const expected = hashOf({
|
|
957
|
+
actor: row.actor,
|
|
958
|
+
at: row.at,
|
|
959
|
+
body: row.body,
|
|
960
|
+
entity: name,
|
|
961
|
+
kind: row.kind,
|
|
962
|
+
lineage,
|
|
963
|
+
prevHash: previousHash,
|
|
964
|
+
reason: row.reason,
|
|
965
|
+
ref: params.ref,
|
|
966
|
+
tenant: tenantId,
|
|
967
|
+
version: row.version
|
|
968
|
+
});
|
|
969
|
+
if (expected !== row.hash) {
|
|
970
|
+
return { brokenAt: row.version, expected, found: row.hash, ok: false };
|
|
971
|
+
}
|
|
972
|
+
previousHash = row.hash;
|
|
973
|
+
}
|
|
974
|
+
return { ok: true, versions: rows.length };
|
|
975
|
+
}
|
|
976
|
+
);
|
|
977
|
+
const undoRestoreOrRetire = async (scoped, output, tenantId) => {
|
|
978
|
+
if (!output.committed) return;
|
|
979
|
+
const now = await currentDbTime(scoped);
|
|
980
|
+
const existing = await lockedProjection(scoped, tenantId, name, output.ref);
|
|
981
|
+
if (existing === void 0) {
|
|
982
|
+
throw new DbRefusal2(
|
|
983
|
+
`"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
const version = existing.version + 1;
|
|
987
|
+
const reason = `undo of v${output.version}`;
|
|
988
|
+
if (output.previous === null) {
|
|
989
|
+
const head2 = definition.headOf(
|
|
990
|
+
readBody(definition, name, output.ref, existing.body)
|
|
991
|
+
);
|
|
992
|
+
const hash2 = await insertRevisionRow(scoped, {
|
|
993
|
+
actor: UNDO_ACTOR,
|
|
994
|
+
at: now,
|
|
995
|
+
body: existing.body,
|
|
996
|
+
compensationOf: output.version,
|
|
997
|
+
entityName: name,
|
|
998
|
+
kind: "retired",
|
|
999
|
+
lineage: output.lineage,
|
|
1000
|
+
prevHash: existing.hash,
|
|
1001
|
+
ref: output.ref,
|
|
1002
|
+
reason,
|
|
1003
|
+
tenantId,
|
|
1004
|
+
version
|
|
1005
|
+
});
|
|
1006
|
+
await writeProjection(scoped, {
|
|
1007
|
+
at: now,
|
|
1008
|
+
body: existing.body,
|
|
1009
|
+
create: false,
|
|
1010
|
+
entityName: name,
|
|
1011
|
+
hash: hash2,
|
|
1012
|
+
head: head2,
|
|
1013
|
+
lineage: output.lineage,
|
|
1014
|
+
ref: output.ref,
|
|
1015
|
+
retiredAt: now,
|
|
1016
|
+
tenantId,
|
|
1017
|
+
version
|
|
1018
|
+
});
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
const prior = await revisionRowAt(
|
|
1022
|
+
scoped,
|
|
1023
|
+
tenantId,
|
|
1024
|
+
name,
|
|
1025
|
+
output.ref,
|
|
1026
|
+
output.lineage,
|
|
1027
|
+
output.previous.version
|
|
1028
|
+
);
|
|
1029
|
+
if (prior === void 0) {
|
|
1030
|
+
throw new DbRefusal2(
|
|
1031
|
+
`"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
|
|
1032
|
+
);
|
|
1033
|
+
}
|
|
1034
|
+
const head = definition.headOf(readBody(definition, name, output.ref, prior.body));
|
|
1035
|
+
const hash = await insertRevisionRow(scoped, {
|
|
1036
|
+
actor: UNDO_ACTOR,
|
|
1037
|
+
at: now,
|
|
1038
|
+
body: prior.body,
|
|
1039
|
+
compensationOf: output.version,
|
|
1040
|
+
entityName: name,
|
|
1041
|
+
kind: "committed",
|
|
1042
|
+
lineage: output.lineage,
|
|
1043
|
+
prevHash: existing.hash,
|
|
1044
|
+
ref: output.ref,
|
|
1045
|
+
reason,
|
|
1046
|
+
tenantId,
|
|
1047
|
+
version
|
|
1048
|
+
});
|
|
1049
|
+
await writeProjection(scoped, {
|
|
1050
|
+
at: now,
|
|
1051
|
+
body: prior.body,
|
|
1052
|
+
create: false,
|
|
1053
|
+
entityName: name,
|
|
1054
|
+
hash,
|
|
1055
|
+
head,
|
|
1056
|
+
lineage: output.lineage,
|
|
1057
|
+
ref: output.ref,
|
|
1058
|
+
retiredAt: null,
|
|
1059
|
+
tenantId,
|
|
1060
|
+
version
|
|
1061
|
+
});
|
|
1062
|
+
};
|
|
1063
|
+
const undos = {
|
|
1064
|
+
commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, (scoped) => undoRestoreOrRetire(scoped, output, tenantId)),
|
|
1065
|
+
retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
|
|
1066
|
+
const now = await currentDbTime(scoped);
|
|
1067
|
+
const existing = await lockedProjection(scoped, tenantId, name, output.ref);
|
|
1068
|
+
if (existing === void 0) {
|
|
1069
|
+
throw new DbRefusal2(
|
|
1070
|
+
`"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
|
|
1071
|
+
);
|
|
1072
|
+
}
|
|
1073
|
+
const version = existing.version + 1;
|
|
1074
|
+
const head = definition.headOf(
|
|
1075
|
+
readBody(definition, name, output.ref, existing.body)
|
|
1076
|
+
);
|
|
1077
|
+
const hash = await insertRevisionRow(scoped, {
|
|
1078
|
+
actor: UNDO_ACTOR,
|
|
1079
|
+
at: now,
|
|
1080
|
+
body: existing.body,
|
|
1081
|
+
compensationOf: output.version,
|
|
1082
|
+
entityName: name,
|
|
1083
|
+
kind: "reinstated",
|
|
1084
|
+
lineage: output.lineage,
|
|
1085
|
+
prevHash: existing.hash,
|
|
1086
|
+
ref: output.ref,
|
|
1087
|
+
reason: `undo of v${output.version}`,
|
|
1088
|
+
tenantId,
|
|
1089
|
+
version
|
|
1090
|
+
});
|
|
1091
|
+
await writeProjection(scoped, {
|
|
1092
|
+
at: now,
|
|
1093
|
+
body: existing.body,
|
|
1094
|
+
create: false,
|
|
1095
|
+
entityName: name,
|
|
1096
|
+
hash,
|
|
1097
|
+
head,
|
|
1098
|
+
lineage: output.lineage,
|
|
1099
|
+
ref: output.ref,
|
|
1100
|
+
retiredAt: null,
|
|
1101
|
+
tenantId,
|
|
1102
|
+
version
|
|
1103
|
+
});
|
|
1104
|
+
})
|
|
1105
|
+
};
|
|
1106
|
+
return {
|
|
1107
|
+
asOf,
|
|
1108
|
+
at,
|
|
1109
|
+
commit,
|
|
1110
|
+
get: raw.get,
|
|
1111
|
+
history,
|
|
1112
|
+
list: raw.list,
|
|
1113
|
+
listAll: raw.listAll,
|
|
1114
|
+
reinstate,
|
|
1115
|
+
retire,
|
|
1116
|
+
succeed,
|
|
1117
|
+
undos,
|
|
1118
|
+
verify
|
|
1119
|
+
};
|
|
1120
|
+
};
|
|
1121
|
+
const rawEntities = Object.fromEntries(
|
|
1122
|
+
registry.names.map((name) => [name, entityStoreFor(name)])
|
|
1123
|
+
);
|
|
1124
|
+
const heads = seam.scoped(async (tx, params) => {
|
|
1125
|
+
const { columns, entity, order, where } = params;
|
|
1126
|
+
const tenantId = params[tenantKey];
|
|
1127
|
+
const selectList = columns.map((column) => `${quote(columnOf(column))} as ${quote(column)}`).join(", ");
|
|
1128
|
+
const predicates = [
|
|
1129
|
+
text(`select ${selectList} from ${quote(table)} where ${quote(tenantColumn)} = `),
|
|
1130
|
+
bound(tenantId),
|
|
1131
|
+
text(` and ${quote(retiredAtColumn)} is null`)
|
|
1132
|
+
];
|
|
1133
|
+
if (entity !== void 0) {
|
|
1134
|
+
predicates.push(
|
|
1135
|
+
Array.isArray(entity) ? chainAll([text(` and ${quote(entityColumn)} = any(`), bound(entity), text(")")]) : chainAll([text(` and ${quote(entityColumn)} = `), bound(entity)])
|
|
1136
|
+
);
|
|
1137
|
+
}
|
|
1138
|
+
if (where?.status !== void 0) {
|
|
1139
|
+
predicates.push(text(` and ${quote(columnOf("status"))} = `), bound(where.status));
|
|
1140
|
+
}
|
|
1141
|
+
if (where?.createdAt !== void 0) {
|
|
1142
|
+
predicates.push(
|
|
1143
|
+
text(` and ${quote(createdAtColumn)} between `),
|
|
1144
|
+
bound(where.createdAt[0]),
|
|
1145
|
+
text(" and "),
|
|
1146
|
+
bound(where.createdAt[1])
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
predicates.push(
|
|
1150
|
+
text(
|
|
1151
|
+
` order by ${order.map((one) => `${quote(columnOf(one.column))} ${one.direction === "desc" ? "desc" : "asc"}`).join(", ")}`
|
|
1152
|
+
)
|
|
1153
|
+
);
|
|
1154
|
+
return rowsOf(
|
|
1155
|
+
await seam.send(tx, chainAll(predicates))
|
|
1156
|
+
);
|
|
1157
|
+
});
|
|
1158
|
+
const aggregate = seam.scoped(async (tx, params) => {
|
|
1159
|
+
const { by, entities, entity, measures, where } = params;
|
|
1160
|
+
const tenantId = params[tenantKey];
|
|
1161
|
+
const wantsCount = measures.includes("count");
|
|
1162
|
+
const wantsSum = measures.includes("sum:total");
|
|
1163
|
+
const groupSelect = by === void 0 ? [] : [`${byExpr(by, columnOf)} as "by"`];
|
|
1164
|
+
const measureSelect = [
|
|
1165
|
+
...wantsCount ? ['count(*)::int as "count"'] : [],
|
|
1166
|
+
...wantsSum ? [`sum(${quote(columnOf("total"))})::text as "sum"`] : []
|
|
1167
|
+
];
|
|
1168
|
+
const predicates = [
|
|
1169
|
+
text(
|
|
1170
|
+
`select ${[...groupSelect, ...measureSelect].join(", ")} from ${quote(table)} where ${quote(tenantColumn)} = `
|
|
1171
|
+
),
|
|
1172
|
+
bound(tenantId),
|
|
1173
|
+
text(` and ${quote(retiredAtColumn)} is null`)
|
|
1174
|
+
];
|
|
1175
|
+
if (entity !== void 0)
|
|
1176
|
+
predicates.push(text(` and ${quote(entityColumn)} = `), bound(entity));
|
|
1177
|
+
if (entities !== void 0) {
|
|
1178
|
+
predicates.push(text(` and ${quote(entityColumn)} = any(`), bound(entities), text(")"));
|
|
1179
|
+
}
|
|
1180
|
+
if (where?.status !== void 0) {
|
|
1181
|
+
predicates.push(text(` and ${quote(columnOf("status"))} = `), bound(where.status));
|
|
1182
|
+
}
|
|
1183
|
+
if (where !== void 0 && "issueDate" in where) {
|
|
1184
|
+
predicates.push(
|
|
1185
|
+
text(` and ${quote(columnOf("issueDate"))} between `),
|
|
1186
|
+
bound(where.issueDate[0]),
|
|
1187
|
+
text(" and "),
|
|
1188
|
+
bound(where.issueDate[1])
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
if (where !== void 0 && "createdAt" in where) {
|
|
1192
|
+
predicates.push(
|
|
1193
|
+
text(` and ${quote(createdAtColumn)} between `),
|
|
1194
|
+
bound(where.createdAt[0]),
|
|
1195
|
+
text(" and "),
|
|
1196
|
+
bound(where.createdAt[1])
|
|
1197
|
+
);
|
|
1198
|
+
}
|
|
1199
|
+
if (by !== void 0) predicates.push(text(' group by "by" order by "by"'));
|
|
1200
|
+
const rows = rowsOf(
|
|
1201
|
+
await seam.send(tx, chainAll(predicates))
|
|
1202
|
+
);
|
|
1203
|
+
if (rows.length === 0 && by === void 0) {
|
|
1204
|
+
return [{ ...wantsCount ? { count: 0 } : {}, ...wantsSum ? { sum: "0" } : {} }];
|
|
1205
|
+
}
|
|
1206
|
+
return rows.map((row) => ({
|
|
1207
|
+
...by === void 0 ? {} : { by: row.by },
|
|
1208
|
+
...wantsCount ? { count: row.count ?? 0 } : {},
|
|
1209
|
+
...wantsSum ? { sum: row.sum ?? "0" } : {}
|
|
1210
|
+
}));
|
|
1211
|
+
});
|
|
1212
|
+
const rebuild = seam.scoped(
|
|
1213
|
+
async (tx, params) => {
|
|
1214
|
+
const log = needsLog();
|
|
1215
|
+
const tenantId = params[tenantKey];
|
|
1216
|
+
const predicates = [
|
|
1217
|
+
text(
|
|
1218
|
+
`select distinct on (${quote(entityColumn)}, ${quote("ref")}) ${quote(entityColumn)} as "entity", ${quote("ref")} as "ref", ${quote("lineage")} as "lineage", ${quote("version")} as "version", ${quote(revisionKindColumn)} as "kind", ${quote("body")} as "body", ${quote("hash")} as "hash", ${quote("at")} as "at", first_value(${quote("at")}) over (partition by ${quote(entityColumn)}, ${quote("ref")}, ${quote("lineage")} order by ${quote("version")}) as "createdAt" from ${quote(log)} where ${quote(tenantColumn)} = `
|
|
1219
|
+
),
|
|
1220
|
+
bound(tenantId)
|
|
1221
|
+
];
|
|
1222
|
+
if (params.entity !== void 0) {
|
|
1223
|
+
predicates.push(text(` and ${quote(entityColumn)} = `), bound(params.entity));
|
|
1224
|
+
}
|
|
1225
|
+
predicates.push(
|
|
1226
|
+
text(
|
|
1227
|
+
` order by ${quote(entityColumn)}, ${quote("ref")}, ${quote("lineage")} desc, ${quote("version")} desc`
|
|
1228
|
+
)
|
|
1229
|
+
);
|
|
1230
|
+
const rows = rowsOf(await seam.send(tx, chainAll(predicates)));
|
|
1231
|
+
for (const row of rows) {
|
|
1232
|
+
const definition = registry.named(row.entity);
|
|
1233
|
+
if (definition === void 0) continue;
|
|
1234
|
+
const clean = readBody(definition, row.entity, row.ref, row.body);
|
|
1235
|
+
const head = definition.headOf(clean);
|
|
1236
|
+
await upsertProjection(tx, {
|
|
1237
|
+
at: Number(row.createdAt),
|
|
1238
|
+
body: row.body,
|
|
1239
|
+
entityName: row.entity,
|
|
1240
|
+
hash: row.hash,
|
|
1241
|
+
head,
|
|
1242
|
+
lineage: row.lineage,
|
|
1243
|
+
ref: row.ref,
|
|
1244
|
+
retiredAt: row.kind === "retired" ? Number(row.at) : null,
|
|
1245
|
+
tenantId,
|
|
1246
|
+
version: row.version
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
return { rows: rows.length };
|
|
1250
|
+
}
|
|
1251
|
+
);
|
|
1252
|
+
return { ...rawEntities, aggregate, heads, rebuild };
|
|
1253
|
+
};
|
|
100
1254
|
export {
|
|
101
1255
|
BODY_VERSION_KEY,
|
|
1256
|
+
DEFAULT_DOCUMENT_TABLE,
|
|
1257
|
+
DEFAULT_REVISIONS_TABLE,
|
|
1258
|
+
DEFAULT_REVISION_KIND_COLUMN,
|
|
1259
|
+
ENTITY_PLACEHOLDERS as DOCUMENT_MIGRATION_PLACEHOLDERS,
|
|
102
1260
|
Document,
|
|
1261
|
+
appendOnlyTables,
|
|
103
1262
|
canTransition,
|
|
1263
|
+
canonicalOf,
|
|
104
1264
|
documentBodyVersioning,
|
|
105
1265
|
documentEntities,
|
|
106
1266
|
documentIdentifiers,
|
|
1267
|
+
documentMigrations,
|
|
1268
|
+
documentRoleStatements,
|
|
1269
|
+
documentStore,
|
|
1270
|
+
fieldPatterns,
|
|
1271
|
+
hashOf,
|
|
1272
|
+
isSystemActor,
|
|
107
1273
|
isTerminalStatus,
|
|
108
1274
|
migrateBody,
|
|
109
|
-
stampBody
|
|
1275
|
+
stampBody,
|
|
1276
|
+
systemActor,
|
|
1277
|
+
validatorOf
|
|
110
1278
|
};
|