@geonosis/document 0.2.0 → 0.3.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 +39 -0
- package/README.md +63 -27
- package/dist/index.cjs +743 -727
- package/dist/index.d.cts +94 -76
- package/dist/index.d.ts +94 -76
- package/dist/index.js +746 -729
- package/migrations/0001_documents.sql +2 -2
- package/migrations/0003_document_revisions.sql +4 -5
- package/package.json +2 -3
package/dist/index.cjs
CHANGED
|
@@ -35,6 +35,7 @@ __export(index_exports, {
|
|
|
35
35
|
documentMigrations: () => documentMigrations,
|
|
36
36
|
documentRoleStatements: () => documentRoleStatements,
|
|
37
37
|
documentStore: () => documentStore,
|
|
38
|
+
documentSurface: () => documentSurface,
|
|
38
39
|
fieldPatterns: () => fieldPatterns,
|
|
39
40
|
hashOf: () => hashOf,
|
|
40
41
|
isSystemActor: () => isSystemActor,
|
|
@@ -99,7 +100,7 @@ var FIELD_CHECKS = {
|
|
|
99
100
|
text: { message: "a string", test: (value) => typeof value === "string" }
|
|
100
101
|
};
|
|
101
102
|
var validatorOf = (fields, options) => {
|
|
102
|
-
const
|
|
103
|
+
const nullable2 = options?.nullable ?? false;
|
|
103
104
|
return {
|
|
104
105
|
"~standard": {
|
|
105
106
|
validate: (input) => {
|
|
@@ -112,7 +113,7 @@ var validatorOf = (fields, options) => {
|
|
|
112
113
|
for (const [key, kind] of Object.entries(fields)) {
|
|
113
114
|
const held = record[key];
|
|
114
115
|
value[key] = held;
|
|
115
|
-
if (
|
|
116
|
+
if (nullable2 && held === null) continue;
|
|
116
117
|
if (!FIELD_CHECKS[kind].test(held)) {
|
|
117
118
|
issues.push({ message: FIELD_CHECKS[kind].message, path: [{ key }] });
|
|
118
119
|
}
|
|
@@ -160,7 +161,8 @@ var Document = {
|
|
|
160
161
|
extend: (definition) => ({
|
|
161
162
|
...definition,
|
|
162
163
|
headOf: (body) => parseWith(headValidator, definition.headOf(body)),
|
|
163
|
-
is: (document) => document.entity === definition.name
|
|
164
|
+
is: (document) => document.entity === definition.name,
|
|
165
|
+
view: definition.view ?? definition.body
|
|
164
166
|
})
|
|
165
167
|
};
|
|
166
168
|
|
|
@@ -186,7 +188,8 @@ var documentEntities = (map) => {
|
|
|
186
188
|
fold,
|
|
187
189
|
instance: (name, parts) => ({ ...parts, entity: name, body: parts.body }),
|
|
188
190
|
named: (name) => map[name],
|
|
189
|
-
names
|
|
191
|
+
names,
|
|
192
|
+
views: distinctBy((entity) => entity.view)
|
|
190
193
|
};
|
|
191
194
|
};
|
|
192
195
|
|
|
@@ -224,6 +227,396 @@ var documentIdentifiers = (name) => {
|
|
|
224
227
|
var canTransition = (machine, from, to) => machine.transitions[from].includes(to);
|
|
225
228
|
var isTerminalStatus = (machine, status) => machine.transitions[status].length === 0;
|
|
226
229
|
|
|
230
|
+
// src/surface/table.ts
|
|
231
|
+
var VENDOR = "geonosis-document-surface";
|
|
232
|
+
var isString = (value) => typeof value === "string";
|
|
233
|
+
var isNumber = (value) => typeof value === "number";
|
|
234
|
+
var scalar = (test, message) => ({
|
|
235
|
+
"~standard": {
|
|
236
|
+
validate: (input) => test(input) ? { value: input } : { issues: [{ message }] },
|
|
237
|
+
vendor: VENDOR,
|
|
238
|
+
version: 1
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
var stringSchema = scalar(isString, "expected a string");
|
|
242
|
+
var numberSchema = scalar(isNumber, "expected a number");
|
|
243
|
+
var booleanSchema = scalar(
|
|
244
|
+
(value) => typeof value === "boolean",
|
|
245
|
+
"expected a boolean"
|
|
246
|
+
);
|
|
247
|
+
var literalOf = (literal) => scalar(
|
|
248
|
+
(value) => value === literal,
|
|
249
|
+
`expected exactly ${JSON.stringify(literal)}`
|
|
250
|
+
);
|
|
251
|
+
var unknownSchema = {
|
|
252
|
+
"~standard": { validate: (input) => ({ value: input }), vendor: VENDOR, version: 1 }
|
|
253
|
+
};
|
|
254
|
+
var syncResult = (schema, input) => {
|
|
255
|
+
const result = schema["~standard"].validate(input);
|
|
256
|
+
if (result instanceof Promise) {
|
|
257
|
+
throw new Error(
|
|
258
|
+
"a document surface schema validates synchronously; an async Standard Schema cannot back a row"
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return result;
|
|
262
|
+
};
|
|
263
|
+
var optional = (inner) => ({
|
|
264
|
+
"~standard": {
|
|
265
|
+
validate: (input) => input === void 0 ? { value: void 0 } : syncResult(inner, input),
|
|
266
|
+
vendor: VENDOR,
|
|
267
|
+
version: 1
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
var nullable = (inner) => ({
|
|
271
|
+
"~standard": {
|
|
272
|
+
validate: (input) => input === null ? { value: null } : syncResult(inner, input),
|
|
273
|
+
vendor: VENDOR,
|
|
274
|
+
version: 1
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
var arrayOf = (item) => ({
|
|
278
|
+
"~standard": {
|
|
279
|
+
validate: (input) => {
|
|
280
|
+
if (!Array.isArray(input)) return { issues: [{ message: "expected an array" }] };
|
|
281
|
+
const value = [];
|
|
282
|
+
const issues = [];
|
|
283
|
+
input.forEach((one, at) => {
|
|
284
|
+
const result = syncResult(item, one);
|
|
285
|
+
if (result.issues !== void 0) {
|
|
286
|
+
issues.push(
|
|
287
|
+
...result.issues.map((issue) => ({ ...issue, path: [at, ...issue.path ?? []] }))
|
|
288
|
+
);
|
|
289
|
+
} else {
|
|
290
|
+
value.push(result.value);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
return issues.length > 0 ? { issues } : { value };
|
|
294
|
+
},
|
|
295
|
+
vendor: VENDOR,
|
|
296
|
+
version: 1
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
var merge = (schemas) => ({
|
|
300
|
+
"~standard": {
|
|
301
|
+
validate: (input) => {
|
|
302
|
+
let value = {};
|
|
303
|
+
const issues = [];
|
|
304
|
+
for (const schema of schemas) {
|
|
305
|
+
const result = syncResult(schema, input);
|
|
306
|
+
if (result.issues !== void 0) issues.push(...result.issues);
|
|
307
|
+
else value = { ...value, ...result.value };
|
|
308
|
+
}
|
|
309
|
+
return issues.length > 0 ? { issues } : { value };
|
|
310
|
+
},
|
|
311
|
+
vendor: VENDOR,
|
|
312
|
+
version: 1
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
var doorFor = (store, name) => {
|
|
316
|
+
const door = store[name];
|
|
317
|
+
if (door === void 0) {
|
|
318
|
+
throw new Error(
|
|
319
|
+
`"${name}" names no store this table's registry can find \u2014 the table and the store must share one registry`
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
return door;
|
|
323
|
+
};
|
|
324
|
+
var HEAD_COLUMNS = Object.keys(Document.headFields);
|
|
325
|
+
var rowsFor = (definition, store, schema) => {
|
|
326
|
+
const { name } = definition;
|
|
327
|
+
const door = doorFor(store, name);
|
|
328
|
+
const basePath = `/${definition.basePath}`;
|
|
329
|
+
const instanceSchema = merge([
|
|
330
|
+
Document.head,
|
|
331
|
+
Document.record,
|
|
332
|
+
schema.object({ body: definition.view, entity: schema.enum([name]), number: stringSchema })
|
|
333
|
+
]);
|
|
334
|
+
const commitOutput = schema.union([
|
|
335
|
+
schema.object({
|
|
336
|
+
committed: literalOf(false),
|
|
337
|
+
lineage: numberSchema,
|
|
338
|
+
ref: stringSchema,
|
|
339
|
+
version: numberSchema
|
|
340
|
+
}),
|
|
341
|
+
schema.object({
|
|
342
|
+
archived: optional(booleanSchema),
|
|
343
|
+
committed: literalOf(true),
|
|
344
|
+
hash: stringSchema,
|
|
345
|
+
lineage: numberSchema,
|
|
346
|
+
previous: nullable(schema.object({ hash: stringSchema, version: numberSchema })),
|
|
347
|
+
ref: stringSchema,
|
|
348
|
+
version: numberSchema
|
|
349
|
+
})
|
|
350
|
+
]);
|
|
351
|
+
const retireLikeOutput = schema.object({
|
|
352
|
+
hash: stringSchema,
|
|
353
|
+
lineage: numberSchema,
|
|
354
|
+
ref: stringSchema,
|
|
355
|
+
version: numberSchema
|
|
356
|
+
});
|
|
357
|
+
const verifyOutput = schema.union([
|
|
358
|
+
schema.object({ ok: literalOf(true), versions: numberSchema }),
|
|
359
|
+
schema.object({
|
|
360
|
+
brokenAt: numberSchema,
|
|
361
|
+
expected: stringSchema,
|
|
362
|
+
found: stringSchema,
|
|
363
|
+
ok: literalOf(false)
|
|
364
|
+
})
|
|
365
|
+
]);
|
|
366
|
+
const historyOutput = arrayOf(
|
|
367
|
+
schema.object({
|
|
368
|
+
actor: stringSchema,
|
|
369
|
+
at: numberSchema,
|
|
370
|
+
body: unknownSchema,
|
|
371
|
+
hash: stringSchema,
|
|
372
|
+
kind: schema.enum(["committed", "retired", "reinstated"]),
|
|
373
|
+
reason: nullable(stringSchema),
|
|
374
|
+
version: numberSchema
|
|
375
|
+
})
|
|
376
|
+
);
|
|
377
|
+
const listInput = schema.object({
|
|
378
|
+
cursor: optional(nullable(stringSchema)),
|
|
379
|
+
filter: optional(
|
|
380
|
+
schema.object(
|
|
381
|
+
Object.fromEntries(HEAD_COLUMNS.map((column) => [column, optional(stringSchema)]))
|
|
382
|
+
)
|
|
383
|
+
),
|
|
384
|
+
limit: optional(numberSchema),
|
|
385
|
+
order: optional(
|
|
386
|
+
schema.object({
|
|
387
|
+
column: schema.enum(HEAD_COLUMNS),
|
|
388
|
+
direction: optional(schema.enum(["asc", "desc"]))
|
|
389
|
+
})
|
|
390
|
+
)
|
|
391
|
+
});
|
|
392
|
+
const listOutput = schema.object({
|
|
393
|
+
items: arrayOf(merge([instanceSchema, schema.object({ card: definition.card.schema })])),
|
|
394
|
+
nextCursor: nullable(stringSchema)
|
|
395
|
+
});
|
|
396
|
+
const ackOutput = schema.object({ ref: stringSchema });
|
|
397
|
+
return [
|
|
398
|
+
{
|
|
399
|
+
call: (handle, params) => door.get(handle, params),
|
|
400
|
+
input: schema.object({ ref: stringSchema }),
|
|
401
|
+
name: `${name}.get`,
|
|
402
|
+
output: nullable(instanceSchema),
|
|
403
|
+
path: `${basePath}/:ref`,
|
|
404
|
+
scope: "org",
|
|
405
|
+
verb: "query"
|
|
406
|
+
},
|
|
407
|
+
{
|
|
408
|
+
call: async (handle, params) => {
|
|
409
|
+
const page = await door.list(handle, params);
|
|
410
|
+
return {
|
|
411
|
+
items: page.items.map((item) => ({
|
|
412
|
+
...item,
|
|
413
|
+
card: definition.card.of(item, { counterpartyName: "" })
|
|
414
|
+
})),
|
|
415
|
+
nextCursor: page.nextCursor
|
|
416
|
+
};
|
|
417
|
+
},
|
|
418
|
+
input: listInput,
|
|
419
|
+
name: `${name}.list`,
|
|
420
|
+
output: listOutput,
|
|
421
|
+
path: basePath,
|
|
422
|
+
scope: "org",
|
|
423
|
+
verb: "query"
|
|
424
|
+
},
|
|
425
|
+
{
|
|
426
|
+
call: (handle, params) => door.history(handle, params),
|
|
427
|
+
input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
|
|
428
|
+
name: `${name}.history`,
|
|
429
|
+
output: historyOutput,
|
|
430
|
+
path: `${basePath}/:ref/history`,
|
|
431
|
+
scope: "org",
|
|
432
|
+
verb: "query"
|
|
433
|
+
},
|
|
434
|
+
{
|
|
435
|
+
call: (handle, params) => door.verify(handle, params),
|
|
436
|
+
input: schema.object({ lineage: optional(numberSchema), ref: stringSchema }),
|
|
437
|
+
name: `${name}.verify`,
|
|
438
|
+
output: verifyOutput,
|
|
439
|
+
path: `${basePath}/:ref/verify`,
|
|
440
|
+
scope: "org",
|
|
441
|
+
verb: "query"
|
|
442
|
+
},
|
|
443
|
+
{
|
|
444
|
+
call: (handle, params) => door.commit(handle, params),
|
|
445
|
+
input: schema.object({
|
|
446
|
+
actor: stringSchema,
|
|
447
|
+
body: definition.body,
|
|
448
|
+
reason: optional(stringSchema),
|
|
449
|
+
ref: stringSchema
|
|
450
|
+
}),
|
|
451
|
+
name: `${name}.commit`,
|
|
452
|
+
output: commitOutput,
|
|
453
|
+
path: basePath,
|
|
454
|
+
scope: "org",
|
|
455
|
+
verb: "mutation"
|
|
456
|
+
},
|
|
457
|
+
{
|
|
458
|
+
call: (handle, params) => door.retire(handle, params),
|
|
459
|
+
input: schema.object({
|
|
460
|
+
actor: stringSchema,
|
|
461
|
+
reason: optional(stringSchema),
|
|
462
|
+
ref: stringSchema
|
|
463
|
+
}),
|
|
464
|
+
name: `${name}.retire`,
|
|
465
|
+
output: retireLikeOutput,
|
|
466
|
+
path: `${basePath}/:ref/retire`,
|
|
467
|
+
scope: "org",
|
|
468
|
+
verb: "mutation"
|
|
469
|
+
},
|
|
470
|
+
{
|
|
471
|
+
call: (handle, params) => door.reinstate(handle, params),
|
|
472
|
+
input: schema.object({
|
|
473
|
+
actor: stringSchema,
|
|
474
|
+
reason: optional(stringSchema),
|
|
475
|
+
ref: stringSchema
|
|
476
|
+
}),
|
|
477
|
+
name: `${name}.reinstate`,
|
|
478
|
+
output: retireLikeOutput,
|
|
479
|
+
path: `${basePath}/:ref/reinstate`,
|
|
480
|
+
scope: "org",
|
|
481
|
+
verb: "mutation"
|
|
482
|
+
},
|
|
483
|
+
{
|
|
484
|
+
call: async (handle, params) => {
|
|
485
|
+
const asked = params;
|
|
486
|
+
const current = await door.get(handle, params);
|
|
487
|
+
if (current === null) {
|
|
488
|
+
throw new Error(`"${asked.ref}" (${name}) has no document to set a status on`);
|
|
489
|
+
}
|
|
490
|
+
const from = definition.statusOf(current.body);
|
|
491
|
+
if (!canTransition(definition.statuses, from, asked.status)) {
|
|
492
|
+
throw new Error(
|
|
493
|
+
`"${name}" cannot move "${asked.ref}" from "${from}" to "${asked.status}": the status machine declares no such transition`
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
const body = definition.withStatus(
|
|
497
|
+
current.body,
|
|
498
|
+
asked.status,
|
|
499
|
+
(/* @__PURE__ */ new Date()).toISOString()
|
|
500
|
+
);
|
|
501
|
+
return door.commit(handle, { ...asked, body });
|
|
502
|
+
},
|
|
503
|
+
input: schema.object({
|
|
504
|
+
actor: stringSchema,
|
|
505
|
+
reason: optional(stringSchema),
|
|
506
|
+
ref: stringSchema,
|
|
507
|
+
status: schema.enum(definition.statuses.statuses)
|
|
508
|
+
}),
|
|
509
|
+
name: `${name}.setStatus`,
|
|
510
|
+
output: commitOutput,
|
|
511
|
+
path: `${basePath}/:ref/status`,
|
|
512
|
+
scope: "org",
|
|
513
|
+
verb: "mutation"
|
|
514
|
+
},
|
|
515
|
+
{
|
|
516
|
+
call: { pending: "T3", workflow: `${name}.create` },
|
|
517
|
+
input: schema.object({ draft: definition.draft }),
|
|
518
|
+
name: `${name}.create`,
|
|
519
|
+
output: commitOutput,
|
|
520
|
+
path: basePath,
|
|
521
|
+
scope: "org",
|
|
522
|
+
verb: "mutation"
|
|
523
|
+
},
|
|
524
|
+
{
|
|
525
|
+
call: { pending: "T3", workflow: `${name}.send` },
|
|
526
|
+
input: schema.object({ ref: stringSchema }),
|
|
527
|
+
name: `${name}.send`,
|
|
528
|
+
output: ackOutput,
|
|
529
|
+
path: `${basePath}/:ref/send`,
|
|
530
|
+
scope: "org",
|
|
531
|
+
verb: "mutation"
|
|
532
|
+
},
|
|
533
|
+
{
|
|
534
|
+
call: { pending: "T3", workflow: `${name}.duplicate` },
|
|
535
|
+
input: schema.object({ ref: stringSchema }),
|
|
536
|
+
name: `${name}.duplicate`,
|
|
537
|
+
output: commitOutput,
|
|
538
|
+
path: `${basePath}/:ref/duplicate`,
|
|
539
|
+
scope: "org",
|
|
540
|
+
verb: "mutation"
|
|
541
|
+
},
|
|
542
|
+
{
|
|
543
|
+
call: { pending: "T3", workflow: `${name}.runStarted` },
|
|
544
|
+
input: schema.object({ ref: stringSchema }),
|
|
545
|
+
name: `${name}.runStarted`,
|
|
546
|
+
output: ackOutput,
|
|
547
|
+
path: `${basePath}/:ref/run-started`,
|
|
548
|
+
scope: "org",
|
|
549
|
+
verb: "mutation"
|
|
550
|
+
}
|
|
551
|
+
];
|
|
552
|
+
};
|
|
553
|
+
var documentSurface = (options) => {
|
|
554
|
+
const { registry, schema, store } = options;
|
|
555
|
+
const headsColumns = [...HEAD_COLUMNS, "entity", "number"];
|
|
556
|
+
const headsInput = schema.object({
|
|
557
|
+
columns: arrayOf(schema.enum(headsColumns)),
|
|
558
|
+
entity: optional(schema.union([stringSchema, arrayOf(stringSchema)])),
|
|
559
|
+
order: arrayOf(
|
|
560
|
+
schema.object({
|
|
561
|
+
column: schema.enum(headsColumns),
|
|
562
|
+
direction: optional(schema.enum(["asc", "desc"]))
|
|
563
|
+
})
|
|
564
|
+
),
|
|
565
|
+
where: optional(
|
|
566
|
+
schema.object({ createdAt: optional(arrayOf(numberSchema)), status: optional(stringSchema) })
|
|
567
|
+
)
|
|
568
|
+
});
|
|
569
|
+
const aggregateInput = schema.object({
|
|
570
|
+
by: optional(unknownSchema),
|
|
571
|
+
entities: optional(arrayOf(stringSchema)),
|
|
572
|
+
entity: optional(stringSchema),
|
|
573
|
+
measures: arrayOf(schema.enum(["count", "sum:total"])),
|
|
574
|
+
where: optional(unknownSchema)
|
|
575
|
+
});
|
|
576
|
+
const aggregateOutput = arrayOf(
|
|
577
|
+
schema.object({
|
|
578
|
+
by: optional(stringSchema),
|
|
579
|
+
count: optional(numberSchema),
|
|
580
|
+
sum: optional(stringSchema)
|
|
581
|
+
})
|
|
582
|
+
);
|
|
583
|
+
const sharedOutput = schema.union(
|
|
584
|
+
registry.fold(
|
|
585
|
+
(entity) => schema.object({ entity: schema.enum([entity.name]), view: entity.view })
|
|
586
|
+
)
|
|
587
|
+
);
|
|
588
|
+
return [
|
|
589
|
+
...registry.fold((entity) => rowsFor(entity, store, schema)).flat(),
|
|
590
|
+
{
|
|
591
|
+
call: (handle, params) => store.heads(handle, params),
|
|
592
|
+
input: headsInput,
|
|
593
|
+
name: "heads",
|
|
594
|
+
output: arrayOf(unknownSchema),
|
|
595
|
+
path: "/documents/heads",
|
|
596
|
+
scope: "org",
|
|
597
|
+
verb: "query"
|
|
598
|
+
},
|
|
599
|
+
{
|
|
600
|
+
call: (handle, params) => store.aggregate(handle, params),
|
|
601
|
+
input: aggregateInput,
|
|
602
|
+
name: "aggregate",
|
|
603
|
+
output: aggregateOutput,
|
|
604
|
+
path: "/documents/aggregate",
|
|
605
|
+
scope: "org",
|
|
606
|
+
verb: "query"
|
|
607
|
+
},
|
|
608
|
+
{
|
|
609
|
+
call: { pending: "T3", workflow: "document.shared" },
|
|
610
|
+
input: schema.object({ token: stringSchema }),
|
|
611
|
+
name: "shared",
|
|
612
|
+
output: sharedOutput,
|
|
613
|
+
path: "/documents/shared",
|
|
614
|
+
scope: "token",
|
|
615
|
+
verb: "query"
|
|
616
|
+
}
|
|
617
|
+
];
|
|
618
|
+
};
|
|
619
|
+
|
|
227
620
|
// src/store/ddl.ts
|
|
228
621
|
var import_db = require("@geonosis/db");
|
|
229
622
|
var DEFAULT_DOCUMENT_TABLE = "documents";
|
|
@@ -233,11 +626,14 @@ var DEFAULT_TOTAL_COLUMN = "total";
|
|
|
233
626
|
var DEFAULT_TENANT_COLUMN = "tenant_id";
|
|
234
627
|
var DEFAULT_REVISIONS_TABLE = "document_revisions";
|
|
235
628
|
var DEFAULT_REVISION_KIND_COLUMN = "revision_kind";
|
|
629
|
+
var REVISION_KINDS = ["committed", "retired", "reinstated"];
|
|
236
630
|
var nameOf = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
|
|
237
631
|
var appendOnlyTables = (options = {}) => {
|
|
238
632
|
if (options.revisions === false) return [];
|
|
239
633
|
return [options.revisions?.table ?? options.table ?? DEFAULT_REVISIONS_TABLE];
|
|
240
634
|
};
|
|
635
|
+
var quotedName = (name) => `"${name}"`;
|
|
636
|
+
var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
241
637
|
var documentRoleStatements = (appRole, options = {}) => {
|
|
242
638
|
if (typeof appRole !== "string" || appRole === "") {
|
|
243
639
|
throw new import_db.DbRefusal(
|
|
@@ -257,71 +653,31 @@ var headIndexedColumns = (totalColumn) => Object.entries(headFields).map(([key,
|
|
|
257
653
|
const type = DDL_TYPE_OF[kind];
|
|
258
654
|
return type === void 0 ? column : { column, type };
|
|
259
655
|
});
|
|
260
|
-
var
|
|
261
|
-
var literalName = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
262
|
-
var settingDefault = (name) => `current_setting('${name}', true)`;
|
|
263
|
-
var immutableFunctionName = (table) => `${table}_immutable`;
|
|
264
|
-
var noUpdateOrDeleteTriggerName = (table) => `${table}_no_update_or_delete`;
|
|
656
|
+
var revisionKindType = (column) => `text check (${quotedName(column)} in (${REVISION_KINDS.map(literalName).join(", ")}))`;
|
|
265
657
|
var revisionsMigrations = (options, entityColumn, tenantColumn) => {
|
|
266
|
-
|
|
267
|
-
if (revisions === false) return [];
|
|
658
|
+
if (options.revisions === false) return [];
|
|
268
659
|
if (typeof options.appRole !== "string" || options.appRole === "") {
|
|
269
660
|
throw new import_db.DbRefusal(
|
|
270
661
|
"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`"
|
|
271
662
|
);
|
|
272
663
|
}
|
|
273
|
-
const appRole = options.appRole;
|
|
274
664
|
const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
|
|
275
|
-
const table = revisions?.table ?? DEFAULT_REVISIONS_TABLE;
|
|
276
|
-
const
|
|
277
|
-
|
|
665
|
+
const table = options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
|
|
666
|
+
const [tableMigration, policies] = (0, import_db.logMigrations)({
|
|
667
|
+
appRole: options.appRole,
|
|
278
668
|
columns: { tenant: tenantColumn },
|
|
669
|
+
extra: [{ column: revisionKindColumn, type: revisionKindType(revisionKindColumn) }],
|
|
670
|
+
key: [entityColumn, "ref", { column: "lineage", type: "integer" }],
|
|
279
671
|
...options.schema === void 0 ? {} : { schema: options.schema },
|
|
280
672
|
settings: options.settings,
|
|
281
673
|
table
|
|
282
674
|
});
|
|
283
|
-
if (policies === void 0) {
|
|
284
|
-
throw new Error(
|
|
285
|
-
"entityMigrations answered with no policies migration to borrow for the log\u2019s tenant wall"
|
|
286
|
-
);
|
|
675
|
+
if (tableMigration === void 0 || policies === void 0) {
|
|
676
|
+
throw new Error("logMigrations answered with fewer than the two migrations a log renders");
|
|
287
677
|
}
|
|
288
|
-
const functionName = immutableFunctionName(table);
|
|
289
|
-
const triggerName = noUpdateOrDeleteTriggerName(table);
|
|
290
|
-
const qualifiedFunction = options.schema === void 0 ? quotedName(functionName) : `${quotedName(options.schema)}.${quotedName(functionName)}`;
|
|
291
678
|
return [
|
|
292
|
-
{
|
|
293
|
-
|
|
294
|
-
statements: [
|
|
295
|
-
`create table if not exists ${on} (
|
|
296
|
-
${quotedName(tenantColumn)} text not null default ${settingDefault(options.settings.tenantSetting)},
|
|
297
|
-
${quotedName(entityColumn)} text not null,
|
|
298
|
-
${quotedName("ref")} text not null,
|
|
299
|
-
${quotedName("lineage")} integer not null,
|
|
300
|
-
${quotedName("version")} integer not null,
|
|
301
|
-
${quotedName(revisionKindColumn)} text not null,
|
|
302
|
-
${quotedName("body")} jsonb not null,
|
|
303
|
-
${quotedName("actor")} text not null,
|
|
304
|
-
${quotedName("reason")} text,
|
|
305
|
-
${quotedName("at")} bigint not null default (extract(epoch from clock_timestamp()) * 1000)::bigint,
|
|
306
|
-
${quotedName("prev_hash")} text,
|
|
307
|
-
${quotedName("hash")} text not null,
|
|
308
|
-
${quotedName("compensation_of")} integer,
|
|
309
|
-
constraint ${quotedName(`${table}_pkey`)} primary key (${quotedName(tenantColumn)}, ${quotedName(entityColumn)}, ${quotedName("ref")}, ${quotedName("lineage")}, ${quotedName("version")}),
|
|
310
|
-
constraint ${quotedName(`${table}_${revisionKindColumn}_check`)} check (${quotedName(revisionKindColumn)} in ('committed', 'retired', 'reinstated'))
|
|
311
|
-
)`
|
|
312
|
-
]
|
|
313
|
-
},
|
|
314
|
-
{
|
|
315
|
-
...policies,
|
|
316
|
-
name: `0004_${table}_policies.sql`,
|
|
317
|
-
statements: [
|
|
318
|
-
...policies.statements,
|
|
319
|
-
`create or replace function ${qualifiedFunction}() returns trigger language plpgsql as $$ begin raise exception 'this table is append-only: % is not permitted', tg_op; end; $$`,
|
|
320
|
-
`drop trigger if exists ${quotedName(triggerName)} on ${on}`,
|
|
321
|
-
`create trigger ${quotedName(triggerName)} before update or delete on ${on} for each row execute function ${qualifiedFunction}()`,
|
|
322
|
-
`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 $$`
|
|
323
|
-
]
|
|
324
|
-
}
|
|
679
|
+
{ ...tableMigration, name: `0003_${table}.sql` },
|
|
680
|
+
{ ...policies, name: `0004_${table}_policies.sql` }
|
|
325
681
|
];
|
|
326
682
|
};
|
|
327
683
|
var documentMigrations = (options) => {
|
|
@@ -329,9 +685,16 @@ var documentMigrations = (options) => {
|
|
|
329
685
|
const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN;
|
|
330
686
|
const totalColumn = nameOf(options.columns?.total, DEFAULT_TOTAL_COLUMN);
|
|
331
687
|
const tenantColumn = nameOf(options.columns?.tenant, DEFAULT_TENANT_COLUMN);
|
|
332
|
-
const {
|
|
333
|
-
|
|
334
|
-
|
|
688
|
+
const {
|
|
689
|
+
entity: _entity,
|
|
690
|
+
revisionKind: _revisionKind,
|
|
691
|
+
total: _total,
|
|
692
|
+
version,
|
|
693
|
+
...restColumns
|
|
694
|
+
} = options.columns ?? {};
|
|
695
|
+
const [tableMigration, ...rest] = (0, import_db.projectionMigrations)({
|
|
696
|
+
carried: [{ column: "lineage", type: "integer not null default 1" }],
|
|
697
|
+
columns: { ...restColumns, sequence: version ?? DEFAULT_VERSION_COLUMN },
|
|
335
698
|
constants: { [entityColumn]: "" },
|
|
336
699
|
indexed: headIndexedColumns(totalColumn),
|
|
337
700
|
key: "number",
|
|
@@ -341,54 +704,28 @@ var documentMigrations = (options) => {
|
|
|
341
704
|
sortable: Object.keys(headFields).map((key) => key === "total" ? totalColumn : key),
|
|
342
705
|
table
|
|
343
706
|
});
|
|
344
|
-
const [tableMigration, ...rest] = migrations;
|
|
345
707
|
if (tableMigration === void 0) {
|
|
346
708
|
throw new Error(
|
|
347
|
-
"
|
|
709
|
+
"projectionMigrations answered with no table migration to append the listing index to"
|
|
348
710
|
);
|
|
349
711
|
}
|
|
350
712
|
const listingIndex = `create index if not exists ${quotedName(`${table}_${entityColumn}_issueDate_idx`)} on ${quotedName(table)} (${quotedName(entityColumn)}, ${quotedName("issueDate")})`;
|
|
351
|
-
const on = options.schema === void 0 ? quotedName(table) : `${quotedName(options.schema)}.${quotedName(table)}`;
|
|
352
|
-
const lineageAndHash = [
|
|
353
|
-
`alter table ${on} add column if not exists ${quotedName("lineage")} integer not null default 1`,
|
|
354
|
-
`alter table ${on} add column if not exists ${quotedName("hash")} text`
|
|
355
|
-
];
|
|
356
713
|
return [
|
|
357
|
-
{
|
|
358
|
-
...tableMigration,
|
|
359
|
-
statements: [...tableMigration.statements, listingIndex, ...lineageAndHash]
|
|
360
|
-
},
|
|
714
|
+
{ ...tableMigration, statements: [...tableMigration.statements, listingIndex] },
|
|
361
715
|
...rest,
|
|
362
716
|
...revisionsMigrations(options, entityColumn, tenantColumn)
|
|
363
717
|
];
|
|
364
718
|
};
|
|
365
719
|
|
|
366
720
|
// src/store/store.ts
|
|
367
|
-
var import_conformance = require("@geonosis/conformance");
|
|
368
721
|
var import_db2 = require("@geonosis/db");
|
|
369
722
|
var DEFAULT_ENTITY_COLUMN2 = "entity";
|
|
370
723
|
var DEFAULT_VERSION_COLUMN2 = "version";
|
|
371
724
|
var DEFAULT_TOTAL_COLUMN2 = "total";
|
|
372
|
-
var
|
|
725
|
+
var DEFAULT_TENANT_COLUMN2 = "tenant_id";
|
|
726
|
+
var DEFAULT_CREATED_AT_COLUMN = "created_at";
|
|
373
727
|
var UNDO_ACTOR = systemActor("document.undo");
|
|
374
728
|
var nameOf2 = (value, fallback) => value === void 0 ? fallback : typeof value === "string" ? value : value.name;
|
|
375
|
-
var quote = (name) => `"${name}"`;
|
|
376
|
-
var chain = (before, after) => ({
|
|
377
|
-
chunks: [
|
|
378
|
-
...before.chunks.slice(0, -1),
|
|
379
|
-
`${before.chunks.at(-1) ?? ""}${after.chunks[0] ?? ""}`,
|
|
380
|
-
...after.chunks.slice(1)
|
|
381
|
-
],
|
|
382
|
-
values: [...before.values, ...after.values]
|
|
383
|
-
});
|
|
384
|
-
var chainAll = (pieces) => pieces.reduce((built, piece) => chain(built, piece), (0, import_db2.fragment)([""]));
|
|
385
|
-
var text = (chunk) => (0, import_db2.fragment)([chunk]);
|
|
386
|
-
var bound = (held) => (0, import_db2.fragment)(["", ""], [held]);
|
|
387
|
-
var setList = (columns) => columns.flatMap((one, at) => [
|
|
388
|
-
text(`${at === 0 ? "" : ", "}${quote(one.column)} = `),
|
|
389
|
-
bound(one.held)
|
|
390
|
-
]);
|
|
391
|
-
var valuesList = (columns) => columns.flatMap((one, at) => [text(at === 0 ? "" : ", "), bound(one.held)]);
|
|
392
729
|
var readBody = (entity, entityName, ref, stored) => {
|
|
393
730
|
const migrated = migrateBody(entity, stored);
|
|
394
731
|
const result = entity.body["~standard"].validate(migrated);
|
|
@@ -404,289 +741,80 @@ var readBody = (entity, entityName, ref, stored) => {
|
|
|
404
741
|
}
|
|
405
742
|
return result.value;
|
|
406
743
|
};
|
|
407
|
-
var
|
|
408
|
-
var
|
|
744
|
+
var HEAD_COLUMNS2 = Object.keys(headFields);
|
|
745
|
+
var headFrom = (found) => found === void 0 ? void 0 : {
|
|
746
|
+
body: found.body,
|
|
747
|
+
hash: found.hash,
|
|
748
|
+
lineage: Number(found.carried.lineage ?? 1),
|
|
749
|
+
retiredAt: found.retiredAt,
|
|
750
|
+
version: found.sequence
|
|
751
|
+
};
|
|
409
752
|
var documentStore = (options) => {
|
|
410
753
|
const table = options.table ?? DEFAULT_DOCUMENT_TABLE;
|
|
411
754
|
const entityColumn = options.columns?.entity ?? DEFAULT_ENTITY_COLUMN2;
|
|
412
|
-
const versionColumn = nameOf2(options.columns?.version, DEFAULT_VERSION_COLUMN2);
|
|
413
|
-
const tenantColumn = nameOf2(options.columns?.tenant, DEFAULT_COLUMNS.tenant);
|
|
414
|
-
const createdAtColumn = nameOf2(options.columns?.createdAt, DEFAULT_COLUMNS.createdAt);
|
|
415
|
-
const retiredAtColumn = nameOf2(options.columns?.retiredAt, DEFAULT_COLUMNS.retiredAt);
|
|
416
|
-
const totalColumn = nameOf2(options.columns?.total, DEFAULT_TOTAL_COLUMN2);
|
|
417
755
|
const revisionKindColumn = options.columns?.revisionKind ?? DEFAULT_REVISION_KIND_COLUMN;
|
|
756
|
+
const {
|
|
757
|
+
entity: _entity,
|
|
758
|
+
revisionKind: _revisionKind,
|
|
759
|
+
total,
|
|
760
|
+
version,
|
|
761
|
+
...entityColumns
|
|
762
|
+
} = options.columns ?? {};
|
|
763
|
+
const versionColumn = nameOf2(version, DEFAULT_VERSION_COLUMN2);
|
|
764
|
+
const totalColumn = nameOf2(total, DEFAULT_TOTAL_COLUMN2);
|
|
765
|
+
const tenantColumn = nameOf2(entityColumns.tenant, DEFAULT_TENANT_COLUMN2);
|
|
766
|
+
const createdAtColumn = nameOf2(entityColumns.createdAt, DEFAULT_CREATED_AT_COLUMN);
|
|
418
767
|
const { archive, registry, schema, seam } = options;
|
|
419
768
|
const tenantKey = seam.tenantKey;
|
|
769
|
+
const placed = schema === void 0 ? {} : { schema };
|
|
420
770
|
const revisionsTable = options.revisions === false ? void 0 : options.revisions?.table ?? DEFAULT_REVISIONS_TABLE;
|
|
771
|
+
const tenanted = (tenantId) => ({ [tenantKey]: tenantId });
|
|
421
772
|
const columnOf = (column) => column === "entity" ? entityColumn : column === "total" ? totalColumn : column;
|
|
773
|
+
const physicalHeads = HEAD_COLUMNS2.map(columnOf);
|
|
774
|
+
const revisions = revisionsTable === void 0 ? void 0 : (0, import_db2.defineLog)({
|
|
775
|
+
columns: { tenant: tenantColumn },
|
|
776
|
+
extra: [{ column: revisionKindColumn, param: "kind" }],
|
|
777
|
+
hash: (row) => hashOf({
|
|
778
|
+
actor: row.actor,
|
|
779
|
+
at: row.at,
|
|
780
|
+
body: row.body,
|
|
781
|
+
entity: row.entity,
|
|
782
|
+
kind: row.kind,
|
|
783
|
+
lineage: row.lineage,
|
|
784
|
+
prevHash: row.prevHash,
|
|
785
|
+
reason: row.reason,
|
|
786
|
+
ref: row.ref,
|
|
787
|
+
tenant: row.tenant,
|
|
788
|
+
version: row.sequence
|
|
789
|
+
}),
|
|
790
|
+
key: [
|
|
791
|
+
{ column: entityColumn, param: "entity" },
|
|
792
|
+
{ column: "ref", param: "ref" },
|
|
793
|
+
{ column: "lineage", param: "lineage" }
|
|
794
|
+
],
|
|
795
|
+
...placed,
|
|
796
|
+
seam,
|
|
797
|
+
table: revisionsTable
|
|
798
|
+
});
|
|
422
799
|
const needsLog = () => {
|
|
423
|
-
if (
|
|
800
|
+
if (revisions === void 0) {
|
|
424
801
|
throw new import_db2.DbRefusal(
|
|
425
802
|
"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"
|
|
426
803
|
);
|
|
427
804
|
}
|
|
428
|
-
return
|
|
429
|
-
};
|
|
430
|
-
const currentDbTime = async (tx) => {
|
|
431
|
-
const [row] = (0, import_conformance.rowsOf)(
|
|
432
|
-
await seam.send(
|
|
433
|
-
tx,
|
|
434
|
-
text('select (extract(epoch from clock_timestamp()) * 1000)::bigint as "now"')
|
|
435
|
-
)
|
|
436
|
-
);
|
|
437
|
-
return Number(row?.now ?? Date.now());
|
|
438
|
-
};
|
|
439
|
-
const lockedProjection = async (tx, tenantId, entityName, ref) => {
|
|
440
|
-
const [row] = (0, import_conformance.rowsOf)(
|
|
441
|
-
await seam.send(
|
|
442
|
-
tx,
|
|
443
|
-
chainAll([
|
|
444
|
-
text(
|
|
445
|
-
`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)} = `
|
|
446
|
-
),
|
|
447
|
-
bound(tenantId),
|
|
448
|
-
text(` and ${quote(entityColumn)} = `),
|
|
449
|
-
bound(entityName),
|
|
450
|
-
text(` and ${quote("number")} = `),
|
|
451
|
-
bound(ref),
|
|
452
|
-
text(" for update")
|
|
453
|
-
])
|
|
454
|
-
)
|
|
455
|
-
);
|
|
456
|
-
if (row === void 0) return void 0;
|
|
457
|
-
return {
|
|
458
|
-
body: row.body,
|
|
459
|
-
hash: row.hash ?? "",
|
|
460
|
-
lineage: row.lineage,
|
|
461
|
-
retiredAt: row.retiredAt === null ? null : Number(row.retiredAt),
|
|
462
|
-
version: row.version
|
|
463
|
-
};
|
|
464
|
-
};
|
|
465
|
-
const currentLineageOf = async (tx, tenantId, entityName, ref) => {
|
|
466
|
-
const [row] = (0, import_conformance.rowsOf)(
|
|
467
|
-
await seam.send(
|
|
468
|
-
tx,
|
|
469
|
-
chainAll([
|
|
470
|
-
text(
|
|
471
|
-
`select ${quote("lineage")} as "lineage" from ${quote(table)} where ${quote(tenantColumn)} = `
|
|
472
|
-
),
|
|
473
|
-
bound(tenantId),
|
|
474
|
-
text(` and ${quote(entityColumn)} = `),
|
|
475
|
-
bound(entityName),
|
|
476
|
-
text(` and ${quote("number")} = `),
|
|
477
|
-
bound(ref)
|
|
478
|
-
])
|
|
479
|
-
)
|
|
480
|
-
);
|
|
481
|
-
return row?.lineage ?? 1;
|
|
482
|
-
};
|
|
483
|
-
const insertRevisionRow = async (tx, write) => {
|
|
484
|
-
const log = needsLog();
|
|
485
|
-
const hash = hashOf({
|
|
486
|
-
actor: write.actor,
|
|
487
|
-
at: write.at,
|
|
488
|
-
body: write.body,
|
|
489
|
-
entity: write.entityName,
|
|
490
|
-
kind: write.kind,
|
|
491
|
-
lineage: write.lineage,
|
|
492
|
-
prevHash: write.prevHash,
|
|
493
|
-
reason: write.reason,
|
|
494
|
-
ref: write.ref,
|
|
495
|
-
tenant: write.tenantId,
|
|
496
|
-
version: write.version
|
|
497
|
-
});
|
|
498
|
-
await seam.send(
|
|
499
|
-
tx,
|
|
500
|
-
chainAll([
|
|
501
|
-
text(
|
|
502
|
-
`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 (`
|
|
503
|
-
),
|
|
504
|
-
...valuesList([
|
|
505
|
-
{ column: tenantColumn, held: write.tenantId },
|
|
506
|
-
{ column: entityColumn, held: write.entityName },
|
|
507
|
-
{ column: "ref", held: write.ref },
|
|
508
|
-
{ column: "lineage", held: write.lineage },
|
|
509
|
-
{ column: "version", held: write.version },
|
|
510
|
-
{ column: revisionKindColumn, held: write.kind },
|
|
511
|
-
{ column: "body", held: write.body },
|
|
512
|
-
{ column: "actor", held: write.actor },
|
|
513
|
-
{ column: "reason", held: write.reason },
|
|
514
|
-
{ column: "at", held: write.at },
|
|
515
|
-
{ column: "prev_hash", held: write.prevHash },
|
|
516
|
-
{ column: "hash", held: hash },
|
|
517
|
-
{ column: "compensation_of", held: write.compensationOf }
|
|
518
|
-
]),
|
|
519
|
-
text(")")
|
|
520
|
-
])
|
|
521
|
-
);
|
|
522
|
-
return hash;
|
|
523
|
-
};
|
|
524
|
-
const writeProjection = async (tx, write) => {
|
|
525
|
-
const headColumns = Object.entries(write.head).map(([key, held]) => ({
|
|
526
|
-
column: columnOf(key),
|
|
527
|
-
held
|
|
528
|
-
}));
|
|
529
|
-
if (write.create) {
|
|
530
|
-
await seam.send(
|
|
531
|
-
tx,
|
|
532
|
-
chainAll([
|
|
533
|
-
text(
|
|
534
|
-
`insert into ${quote(table)} (${[
|
|
535
|
-
tenantColumn,
|
|
536
|
-
entityColumn,
|
|
537
|
-
"number",
|
|
538
|
-
createdAtColumn,
|
|
539
|
-
"updated_at",
|
|
540
|
-
retiredAtColumn,
|
|
541
|
-
versionColumn,
|
|
542
|
-
"lineage",
|
|
543
|
-
"hash",
|
|
544
|
-
"body",
|
|
545
|
-
...headColumns.map((one) => one.column)
|
|
546
|
-
].map(quote).join(", ")}) values (`
|
|
547
|
-
),
|
|
548
|
-
...valuesList([
|
|
549
|
-
{ column: tenantColumn, held: write.tenantId },
|
|
550
|
-
{ column: entityColumn, held: write.entityName },
|
|
551
|
-
{ column: "number", held: write.ref },
|
|
552
|
-
{ column: createdAtColumn, held: write.at },
|
|
553
|
-
{ column: "updated_at", held: write.at },
|
|
554
|
-
{ column: retiredAtColumn, held: write.retiredAt },
|
|
555
|
-
{ column: versionColumn, held: write.version },
|
|
556
|
-
{ column: "lineage", held: write.lineage },
|
|
557
|
-
{ column: "hash", held: write.hash },
|
|
558
|
-
{ column: "body", held: write.body },
|
|
559
|
-
...headColumns
|
|
560
|
-
]),
|
|
561
|
-
text(")")
|
|
562
|
-
])
|
|
563
|
-
);
|
|
564
|
-
return;
|
|
565
|
-
}
|
|
566
|
-
await seam.send(
|
|
567
|
-
tx,
|
|
568
|
-
chainAll([
|
|
569
|
-
text(`update ${quote(table)} set `),
|
|
570
|
-
...setList([
|
|
571
|
-
{ column: "updated_at", held: write.at },
|
|
572
|
-
{ column: retiredAtColumn, held: write.retiredAt },
|
|
573
|
-
{ column: versionColumn, held: write.version },
|
|
574
|
-
{ column: "lineage", held: write.lineage },
|
|
575
|
-
{ column: "hash", held: write.hash },
|
|
576
|
-
{ column: "body", held: write.body },
|
|
577
|
-
...headColumns
|
|
578
|
-
]),
|
|
579
|
-
text(` where ${quote(tenantColumn)} = `),
|
|
580
|
-
bound(write.tenantId),
|
|
581
|
-
text(` and ${quote(entityColumn)} = `),
|
|
582
|
-
bound(write.entityName),
|
|
583
|
-
text(` and ${quote("number")} = `),
|
|
584
|
-
bound(write.ref)
|
|
585
|
-
])
|
|
586
|
-
);
|
|
587
|
-
};
|
|
588
|
-
const upsertProjection = async (tx, write) => {
|
|
589
|
-
const headColumns = Object.entries(write.head).map(([key, held]) => ({
|
|
590
|
-
column: columnOf(key),
|
|
591
|
-
held
|
|
592
|
-
}));
|
|
593
|
-
const inserted = [
|
|
594
|
-
{ column: tenantColumn, held: write.tenantId },
|
|
595
|
-
{ column: entityColumn, held: write.entityName },
|
|
596
|
-
{ column: "number", held: write.ref },
|
|
597
|
-
{ column: createdAtColumn, held: write.at },
|
|
598
|
-
{ column: "updated_at", held: write.at },
|
|
599
|
-
{ column: retiredAtColumn, held: write.retiredAt },
|
|
600
|
-
{ column: versionColumn, held: write.version },
|
|
601
|
-
{ column: "lineage", held: write.lineage },
|
|
602
|
-
{ column: "hash", held: write.hash },
|
|
603
|
-
{ column: "body", held: write.body },
|
|
604
|
-
...headColumns
|
|
605
|
-
];
|
|
606
|
-
const conflictColumns = /* @__PURE__ */ new Set([tenantColumn, entityColumn, "number"]);
|
|
607
|
-
const conflict = [...conflictColumns].map(quote).join(", ");
|
|
608
|
-
const updated = inserted.filter((one) => !conflictColumns.has(one.column));
|
|
609
|
-
await seam.send(
|
|
610
|
-
tx,
|
|
611
|
-
chainAll([
|
|
612
|
-
text(
|
|
613
|
-
`insert into ${quote(table)} (${inserted.map((one) => quote(one.column)).join(", ")}) values (`
|
|
614
|
-
),
|
|
615
|
-
...valuesList(inserted),
|
|
616
|
-
text(`) on conflict (${conflict}) do update set `),
|
|
617
|
-
...setList(updated)
|
|
618
|
-
])
|
|
619
|
-
);
|
|
620
|
-
};
|
|
621
|
-
const revisionRowAt = async (tx, tenantId, entityName, ref, lineage, version) => {
|
|
622
|
-
const log = needsLog();
|
|
623
|
-
const [row] = (0, import_conformance.rowsOf)(
|
|
624
|
-
await seam.send(
|
|
625
|
-
tx,
|
|
626
|
-
chainAll([
|
|
627
|
-
text(
|
|
628
|
-
`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)} = `
|
|
629
|
-
),
|
|
630
|
-
bound(tenantId),
|
|
631
|
-
text(` and ${quote(entityColumn)} = `),
|
|
632
|
-
bound(entityName),
|
|
633
|
-
text(` and ${quote("ref")} = `),
|
|
634
|
-
bound(ref),
|
|
635
|
-
text(` and ${quote("lineage")} = `),
|
|
636
|
-
bound(lineage),
|
|
637
|
-
text(` and ${quote("version")} = `),
|
|
638
|
-
bound(version)
|
|
639
|
-
])
|
|
640
|
-
)
|
|
641
|
-
);
|
|
642
|
-
return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
|
|
643
|
-
};
|
|
644
|
-
const revisionRowAsOf = async (tx, tenantId, entityName, ref, lineage, at) => {
|
|
645
|
-
const log = needsLog();
|
|
646
|
-
const [row] = (0, import_conformance.rowsOf)(
|
|
647
|
-
await seam.send(
|
|
648
|
-
tx,
|
|
649
|
-
chainAll([
|
|
650
|
-
text(
|
|
651
|
-
`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)} = `
|
|
652
|
-
),
|
|
653
|
-
bound(tenantId),
|
|
654
|
-
text(` and ${quote(entityColumn)} = `),
|
|
655
|
-
bound(entityName),
|
|
656
|
-
text(` and ${quote("ref")} = `),
|
|
657
|
-
bound(ref),
|
|
658
|
-
text(` and ${quote("lineage")} = `),
|
|
659
|
-
bound(lineage),
|
|
660
|
-
text(` and ${quote("at")} <= `),
|
|
661
|
-
bound(at),
|
|
662
|
-
text(` order by ${quote("version")} desc limit 1`)
|
|
663
|
-
])
|
|
664
|
-
)
|
|
665
|
-
);
|
|
666
|
-
return row === void 0 ? void 0 : { ...row, at: Number(row.at), kind: row.kind };
|
|
667
|
-
};
|
|
668
|
-
const revisionRowsFor = async (tx, tenantId, entityName, ref, lineage) => {
|
|
669
|
-
const log = needsLog();
|
|
670
|
-
const rows = (0, import_conformance.rowsOf)(
|
|
671
|
-
await seam.send(
|
|
672
|
-
tx,
|
|
673
|
-
chainAll([
|
|
674
|
-
text(
|
|
675
|
-
`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)} = `
|
|
676
|
-
),
|
|
677
|
-
bound(tenantId),
|
|
678
|
-
text(` and ${quote(entityColumn)} = `),
|
|
679
|
-
bound(entityName),
|
|
680
|
-
text(` and ${quote("ref")} = `),
|
|
681
|
-
bound(ref),
|
|
682
|
-
text(` and ${quote("lineage")} = `),
|
|
683
|
-
bound(lineage),
|
|
684
|
-
text(` order by ${quote("version")} asc`)
|
|
685
|
-
])
|
|
686
|
-
)
|
|
687
|
-
);
|
|
688
|
-
return rows.map((row) => ({ ...row, at: Number(row.at), kind: row.kind }));
|
|
805
|
+
return revisions;
|
|
689
806
|
};
|
|
807
|
+
const readers = (0, import_db2.defineEntity)({
|
|
808
|
+
columns: { ...entityColumns, version: versionColumn },
|
|
809
|
+
filterable: [...physicalHeads, entityColumn, createdAtColumn],
|
|
810
|
+
item: (row) => row,
|
|
811
|
+
key: { column: "number", param: "ref" },
|
|
812
|
+
order: [{ column: "number" }],
|
|
813
|
+
...placed,
|
|
814
|
+
seam,
|
|
815
|
+
sortable: [...physicalHeads, entityColumn, "number"],
|
|
816
|
+
table
|
|
817
|
+
});
|
|
690
818
|
const entityStoreFor = (name) => {
|
|
691
819
|
const definition = registry.named(name);
|
|
692
820
|
const item = (row) => {
|
|
@@ -710,36 +838,76 @@ var documentStore = (options) => {
|
|
|
710
838
|
createdAt: row.at,
|
|
711
839
|
number: ref,
|
|
712
840
|
updatedAt: row.at,
|
|
713
|
-
version: row.
|
|
841
|
+
version: row.sequence
|
|
714
842
|
});
|
|
715
843
|
};
|
|
716
|
-
const
|
|
717
|
-
|
|
844
|
+
const projection = (0, import_db2.projectionOf)({
|
|
845
|
+
carried: ["lineage"],
|
|
846
|
+
columns: { ...entityColumns, hash: "hash", sequence: versionColumn },
|
|
718
847
|
constants: { [entityColumn]: name },
|
|
719
|
-
filterable:
|
|
720
|
-
indexed: (body) => definition.headOf(body),
|
|
848
|
+
filterable: HEAD_COLUMNS2,
|
|
721
849
|
item,
|
|
722
850
|
key: { column: "number", param: "ref" },
|
|
723
851
|
order: [{ column: "number" }],
|
|
724
|
-
...
|
|
852
|
+
...placed,
|
|
725
853
|
seam,
|
|
726
|
-
sortable:
|
|
854
|
+
sortable: HEAD_COLUMNS2,
|
|
727
855
|
table
|
|
728
856
|
});
|
|
857
|
+
const locked = async (tx, params) => headFrom(await projection.lockLatest(tx, params));
|
|
858
|
+
const currentLineageOf = async (tx, params) => headFrom(await projection.head(tx, params))?.lineage ?? 1;
|
|
859
|
+
const stream = (params, lineage) => ({
|
|
860
|
+
...tenanted(params[tenantKey]),
|
|
861
|
+
entity: name,
|
|
862
|
+
lineage,
|
|
863
|
+
ref: params.ref
|
|
864
|
+
});
|
|
865
|
+
const headColumnsOf = (body) => Object.fromEntries(
|
|
866
|
+
Object.entries(definition.headOf(body)).map(([key, held]) => [
|
|
867
|
+
columnOf(key),
|
|
868
|
+
held
|
|
869
|
+
])
|
|
870
|
+
);
|
|
871
|
+
const storedHead = (ref, body) => headColumnsOf(readBody(definition, name, ref, body));
|
|
872
|
+
const append = async (tx, write) => {
|
|
873
|
+
const log = needsLog();
|
|
874
|
+
const params = {
|
|
875
|
+
...tenanted(write.tenantId),
|
|
876
|
+
actor: write.actor,
|
|
877
|
+
body: write.body,
|
|
878
|
+
entity: name,
|
|
879
|
+
kind: write.kind,
|
|
880
|
+
lineage: write.lineage,
|
|
881
|
+
ref: write.ref,
|
|
882
|
+
...write.reason === null ? {} : { reason: write.reason }
|
|
883
|
+
};
|
|
884
|
+
const out = write.compensationOf === null ? await log.append(tx, params) : await log.appendCompensation(tx, { ...params, compensationOf: write.compensationOf });
|
|
885
|
+
return { at: out.at, hash: out.hash, prevHash: out.prevHash, version: out.sequence };
|
|
886
|
+
};
|
|
887
|
+
const project = async (tx, write) => projection.write(tx, {
|
|
888
|
+
...tenanted(write.tenantId),
|
|
889
|
+
at: write.at,
|
|
890
|
+
body: write.body,
|
|
891
|
+
carried: { lineage: write.lineage },
|
|
892
|
+
derived: write.head,
|
|
893
|
+
hash: write.hash,
|
|
894
|
+
ref: write.ref,
|
|
895
|
+
retiredAt: write.retiredAt,
|
|
896
|
+
sequence: write.version
|
|
897
|
+
});
|
|
729
898
|
const commitTx = seam.scoped(
|
|
730
899
|
async (tx, params) => {
|
|
731
900
|
const tenantId = params[tenantKey];
|
|
732
901
|
const prepared = definition.prepare(params.body);
|
|
733
902
|
const stamped = stampBody(definition, prepared);
|
|
734
|
-
const
|
|
735
|
-
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
903
|
+
const existing = await locked(tx, params);
|
|
736
904
|
if (existing !== void 0 && existing.retiredAt !== null) {
|
|
737
905
|
throw new import_db2.DbRefusal(
|
|
738
906
|
`"${params.ref}" (${name}) is retired: commit refuses a retired document \u2014 succeed opens a new lineage for it`
|
|
739
907
|
);
|
|
740
908
|
}
|
|
741
|
-
const
|
|
742
|
-
if (existing !== void 0 && !
|
|
909
|
+
const changed = existing === void 0 || JSON.stringify(canonicalOf(existing.body)) !== JSON.stringify(canonicalOf(stamped));
|
|
910
|
+
if (existing !== void 0 && !changed) {
|
|
743
911
|
return {
|
|
744
912
|
committed: false,
|
|
745
913
|
lineage: existing.lineage,
|
|
@@ -748,50 +916,42 @@ var documentStore = (options) => {
|
|
|
748
916
|
};
|
|
749
917
|
}
|
|
750
918
|
const lineage = existing?.lineage ?? 1;
|
|
751
|
-
const
|
|
752
|
-
const
|
|
753
|
-
const head = definition.headOf(prepared);
|
|
754
|
-
const hash = await insertRevisionRow(tx, {
|
|
919
|
+
const reason = params.reason ?? null;
|
|
920
|
+
const appended = await append(tx, {
|
|
755
921
|
actor: params.actor,
|
|
756
|
-
at: now,
|
|
757
922
|
body: stamped,
|
|
758
923
|
compensationOf: null,
|
|
759
|
-
entityName: name,
|
|
760
924
|
kind: "committed",
|
|
761
925
|
lineage,
|
|
762
|
-
|
|
926
|
+
reason,
|
|
763
927
|
ref: params.ref,
|
|
764
|
-
|
|
765
|
-
tenantId,
|
|
766
|
-
version
|
|
928
|
+
tenantId
|
|
767
929
|
});
|
|
768
|
-
await
|
|
769
|
-
at:
|
|
930
|
+
await project(tx, {
|
|
931
|
+
at: appended.at,
|
|
770
932
|
body: stamped,
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
hash,
|
|
774
|
-
head,
|
|
933
|
+
hash: appended.hash,
|
|
934
|
+
head: headColumnsOf(prepared),
|
|
775
935
|
lineage,
|
|
776
936
|
ref: params.ref,
|
|
777
937
|
retiredAt: null,
|
|
778
938
|
tenantId,
|
|
779
|
-
version
|
|
939
|
+
version: appended.version
|
|
780
940
|
});
|
|
781
941
|
return {
|
|
782
942
|
archivable: {
|
|
783
943
|
actor: params.actor,
|
|
784
|
-
at:
|
|
944
|
+
at: appended.at,
|
|
785
945
|
body: stamped,
|
|
786
|
-
prevHash,
|
|
787
|
-
reason
|
|
946
|
+
prevHash: appended.prevHash,
|
|
947
|
+
reason
|
|
788
948
|
},
|
|
789
949
|
committed: true,
|
|
790
|
-
hash,
|
|
950
|
+
hash: appended.hash,
|
|
791
951
|
lineage,
|
|
792
952
|
previous: existing === void 0 ? null : { hash: existing.hash, version: existing.version },
|
|
793
953
|
ref: params.ref,
|
|
794
|
-
version
|
|
954
|
+
version: appended.version
|
|
795
955
|
};
|
|
796
956
|
}
|
|
797
957
|
);
|
|
@@ -826,53 +986,46 @@ var documentStore = (options) => {
|
|
|
826
986
|
const retire = seam.scoped(
|
|
827
987
|
async (tx, params) => {
|
|
828
988
|
const tenantId = params[tenantKey];
|
|
829
|
-
const
|
|
830
|
-
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
989
|
+
const existing = await locked(tx, params);
|
|
831
990
|
if (existing === void 0) {
|
|
832
991
|
throw new import_db2.DbRefusal(`"${params.ref}" (${name}) has no document to retire`);
|
|
833
992
|
}
|
|
834
993
|
if (existing.retiredAt !== null) {
|
|
835
994
|
throw new import_db2.DbRefusal(`"${params.ref}" (${name}) is already retired`);
|
|
836
995
|
}
|
|
837
|
-
const
|
|
838
|
-
const head = definition.headOf(
|
|
839
|
-
readBody(definition, name, params.ref, existing.body)
|
|
840
|
-
);
|
|
841
|
-
const hash = await insertRevisionRow(tx, {
|
|
996
|
+
const appended = await append(tx, {
|
|
842
997
|
actor: params.actor,
|
|
843
|
-
at: now,
|
|
844
998
|
body: existing.body,
|
|
845
999
|
compensationOf: null,
|
|
846
|
-
entityName: name,
|
|
847
1000
|
kind: "retired",
|
|
848
1001
|
lineage: existing.lineage,
|
|
849
|
-
prevHash: existing.hash,
|
|
850
|
-
ref: params.ref,
|
|
851
1002
|
reason: params.reason ?? null,
|
|
852
|
-
|
|
853
|
-
|
|
1003
|
+
ref: params.ref,
|
|
1004
|
+
tenantId
|
|
854
1005
|
});
|
|
855
|
-
await
|
|
856
|
-
at:
|
|
1006
|
+
await project(tx, {
|
|
1007
|
+
at: appended.at,
|
|
857
1008
|
body: existing.body,
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
hash,
|
|
861
|
-
head,
|
|
1009
|
+
hash: appended.hash,
|
|
1010
|
+
head: storedHead(params.ref, existing.body),
|
|
862
1011
|
lineage: existing.lineage,
|
|
863
1012
|
ref: params.ref,
|
|
864
|
-
retiredAt:
|
|
1013
|
+
retiredAt: appended.at,
|
|
865
1014
|
tenantId,
|
|
866
|
-
version
|
|
1015
|
+
version: appended.version
|
|
867
1016
|
});
|
|
868
|
-
return {
|
|
1017
|
+
return {
|
|
1018
|
+
hash: appended.hash,
|
|
1019
|
+
lineage: existing.lineage,
|
|
1020
|
+
ref: params.ref,
|
|
1021
|
+
version: appended.version
|
|
1022
|
+
};
|
|
869
1023
|
}
|
|
870
1024
|
);
|
|
871
1025
|
const succeed = seam.scoped(
|
|
872
1026
|
async (tx, params) => {
|
|
873
1027
|
const tenantId = params[tenantKey];
|
|
874
|
-
const
|
|
875
|
-
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
1028
|
+
const existing = await locked(tx, params);
|
|
876
1029
|
if (existing === void 0 || existing.retiredAt === null) {
|
|
877
1030
|
throw new import_db2.DbRefusal(
|
|
878
1031
|
`"${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`
|
|
@@ -880,413 +1033,275 @@ var documentStore = (options) => {
|
|
|
880
1033
|
}
|
|
881
1034
|
const prepared = definition.prepare(params.body);
|
|
882
1035
|
const stamped = stampBody(definition, prepared);
|
|
883
|
-
const head = definition.headOf(prepared);
|
|
884
1036
|
const lineage = existing.lineage + 1;
|
|
885
|
-
const
|
|
1037
|
+
const appended = await append(tx, {
|
|
886
1038
|
actor: params.actor,
|
|
887
|
-
at: now,
|
|
888
1039
|
body: stamped,
|
|
889
1040
|
compensationOf: null,
|
|
890
|
-
entityName: name,
|
|
891
1041
|
kind: "committed",
|
|
892
1042
|
lineage,
|
|
893
|
-
prevHash: null,
|
|
894
|
-
ref: params.ref,
|
|
895
1043
|
reason: params.reason ?? null,
|
|
896
|
-
|
|
897
|
-
|
|
1044
|
+
ref: params.ref,
|
|
1045
|
+
tenantId
|
|
898
1046
|
});
|
|
899
|
-
await
|
|
900
|
-
at:
|
|
1047
|
+
await project(tx, {
|
|
1048
|
+
at: appended.at,
|
|
901
1049
|
body: stamped,
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
hash,
|
|
905
|
-
head,
|
|
1050
|
+
hash: appended.hash,
|
|
1051
|
+
head: headColumnsOf(prepared),
|
|
906
1052
|
lineage,
|
|
907
1053
|
ref: params.ref,
|
|
908
1054
|
retiredAt: null,
|
|
909
1055
|
tenantId,
|
|
910
|
-
version:
|
|
1056
|
+
version: appended.version
|
|
911
1057
|
});
|
|
912
|
-
return {
|
|
1058
|
+
return {
|
|
1059
|
+
committed: true,
|
|
1060
|
+
hash: appended.hash,
|
|
1061
|
+
lineage,
|
|
1062
|
+
previous: null,
|
|
1063
|
+
ref: params.ref,
|
|
1064
|
+
version: appended.version
|
|
1065
|
+
};
|
|
913
1066
|
}
|
|
914
1067
|
);
|
|
915
1068
|
const reinstate = seam.scoped(
|
|
916
1069
|
async (tx, params) => {
|
|
917
1070
|
const tenantId = params[tenantKey];
|
|
918
|
-
const
|
|
919
|
-
const existing = await lockedProjection(tx, tenantId, name, params.ref);
|
|
1071
|
+
const existing = await locked(tx, params);
|
|
920
1072
|
if (existing === void 0 || existing.retiredAt === null) {
|
|
921
1073
|
throw new import_db2.DbRefusal(`"${params.ref}" (${name}) is not retired: nothing to reinstate`);
|
|
922
1074
|
}
|
|
923
|
-
const
|
|
924
|
-
const head = definition.headOf(
|
|
925
|
-
readBody(definition, name, params.ref, existing.body)
|
|
926
|
-
);
|
|
927
|
-
const hash = await insertRevisionRow(tx, {
|
|
1075
|
+
const appended = await append(tx, {
|
|
928
1076
|
actor: params.actor,
|
|
929
|
-
at: now,
|
|
930
1077
|
body: existing.body,
|
|
931
1078
|
compensationOf: null,
|
|
932
|
-
entityName: name,
|
|
933
1079
|
kind: "reinstated",
|
|
934
1080
|
lineage: existing.lineage,
|
|
935
|
-
prevHash: existing.hash,
|
|
936
|
-
ref: params.ref,
|
|
937
1081
|
reason: params.reason ?? null,
|
|
938
|
-
|
|
939
|
-
|
|
1082
|
+
ref: params.ref,
|
|
1083
|
+
tenantId
|
|
940
1084
|
});
|
|
941
|
-
await
|
|
942
|
-
at:
|
|
1085
|
+
await project(tx, {
|
|
1086
|
+
at: appended.at,
|
|
943
1087
|
body: existing.body,
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
hash,
|
|
947
|
-
head,
|
|
1088
|
+
hash: appended.hash,
|
|
1089
|
+
head: storedHead(params.ref, existing.body),
|
|
948
1090
|
lineage: existing.lineage,
|
|
949
1091
|
ref: params.ref,
|
|
950
1092
|
retiredAt: null,
|
|
951
1093
|
tenantId,
|
|
952
|
-
version
|
|
1094
|
+
version: appended.version
|
|
953
1095
|
});
|
|
954
|
-
return {
|
|
1096
|
+
return {
|
|
1097
|
+
hash: appended.hash,
|
|
1098
|
+
lineage: existing.lineage,
|
|
1099
|
+
ref: params.ref,
|
|
1100
|
+
version: appended.version
|
|
1101
|
+
};
|
|
955
1102
|
}
|
|
956
1103
|
);
|
|
957
1104
|
const at = seam.scoped(
|
|
958
1105
|
async (tx, params) => {
|
|
959
|
-
const
|
|
960
|
-
const
|
|
961
|
-
|
|
962
|
-
|
|
1106
|
+
const lineage = await currentLineageOf(tx, params);
|
|
1107
|
+
const row = await needsLog().at(tx, {
|
|
1108
|
+
...stream(params, lineage),
|
|
1109
|
+
sequence: params.version
|
|
1110
|
+
});
|
|
1111
|
+
return row === null ? null : instanceFromRevision(params.ref, row);
|
|
963
1112
|
}
|
|
964
1113
|
);
|
|
965
1114
|
const asOf = seam.scoped(
|
|
966
1115
|
async (tx, params) => {
|
|
967
|
-
const
|
|
968
|
-
const
|
|
969
|
-
|
|
970
|
-
return row === void 0 ? null : instanceFromRevision(params.ref, row);
|
|
1116
|
+
const lineage = await currentLineageOf(tx, params);
|
|
1117
|
+
const row = await needsLog().asOf(tx, { ...stream(params, lineage), at: params.at });
|
|
1118
|
+
return row === null ? null : instanceFromRevision(params.ref, row);
|
|
971
1119
|
}
|
|
972
1120
|
);
|
|
973
1121
|
const history = seam.scoped(
|
|
974
1122
|
async (tx, params) => {
|
|
975
|
-
const
|
|
976
|
-
const
|
|
977
|
-
const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
|
|
1123
|
+
const lineage = params.lineage ?? await currentLineageOf(tx, params);
|
|
1124
|
+
const rows = await needsLog().history(tx, stream(params, lineage));
|
|
978
1125
|
return rows.map((row) => ({
|
|
979
1126
|
actor: row.actor,
|
|
980
1127
|
at: row.at,
|
|
981
|
-
body: readBody(definition, name, `${params.ref} version ${row.
|
|
1128
|
+
body: readBody(definition, name, `${params.ref} version ${row.sequence}`, row.body),
|
|
982
1129
|
hash: row.hash,
|
|
983
1130
|
kind: row.kind,
|
|
984
1131
|
reason: row.reason,
|
|
985
|
-
version: row.
|
|
1132
|
+
version: row.sequence
|
|
986
1133
|
}));
|
|
987
1134
|
}
|
|
988
1135
|
);
|
|
989
1136
|
const verify = seam.scoped(
|
|
990
1137
|
async (tx, params) => {
|
|
991
|
-
const
|
|
992
|
-
|
|
993
|
-
const rows = await revisionRowsFor(tx, tenantId, name, params.ref, lineage);
|
|
994
|
-
let previousHash = null;
|
|
995
|
-
for (const row of rows) {
|
|
996
|
-
const expected = hashOf({
|
|
997
|
-
actor: row.actor,
|
|
998
|
-
at: row.at,
|
|
999
|
-
body: row.body,
|
|
1000
|
-
entity: name,
|
|
1001
|
-
kind: row.kind,
|
|
1002
|
-
lineage,
|
|
1003
|
-
prevHash: previousHash,
|
|
1004
|
-
reason: row.reason,
|
|
1005
|
-
ref: params.ref,
|
|
1006
|
-
tenant: tenantId,
|
|
1007
|
-
version: row.version
|
|
1008
|
-
});
|
|
1009
|
-
if (expected !== row.hash) {
|
|
1010
|
-
return { brokenAt: row.version, expected, found: row.hash, ok: false };
|
|
1011
|
-
}
|
|
1012
|
-
previousHash = row.hash;
|
|
1013
|
-
}
|
|
1014
|
-
return { ok: true, versions: rows.length };
|
|
1138
|
+
const lineage = params.lineage ?? await currentLineageOf(tx, params);
|
|
1139
|
+
return needsLog().verify(tx, stream(params, lineage));
|
|
1015
1140
|
}
|
|
1016
1141
|
);
|
|
1017
|
-
const
|
|
1018
|
-
|
|
1019
|
-
const now = await currentDbTime(scoped);
|
|
1020
|
-
const existing = await lockedProjection(scoped, tenantId, name, output.ref);
|
|
1021
|
-
if (existing === void 0) {
|
|
1022
|
-
throw new import_db2.DbRefusal(
|
|
1023
|
-
`"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
|
|
1024
|
-
);
|
|
1025
|
-
}
|
|
1026
|
-
const version = existing.version + 1;
|
|
1027
|
-
const reason = `undo of v${output.version}`;
|
|
1028
|
-
if (output.previous === null) {
|
|
1029
|
-
const head2 = definition.headOf(
|
|
1030
|
-
readBody(definition, name, output.ref, existing.body)
|
|
1031
|
-
);
|
|
1032
|
-
const hash2 = await insertRevisionRow(scoped, {
|
|
1033
|
-
actor: UNDO_ACTOR,
|
|
1034
|
-
at: now,
|
|
1035
|
-
body: existing.body,
|
|
1036
|
-
compensationOf: output.version,
|
|
1037
|
-
entityName: name,
|
|
1038
|
-
kind: "retired",
|
|
1039
|
-
lineage: output.lineage,
|
|
1040
|
-
prevHash: existing.hash,
|
|
1041
|
-
ref: output.ref,
|
|
1042
|
-
reason,
|
|
1043
|
-
tenantId,
|
|
1044
|
-
version
|
|
1045
|
-
});
|
|
1046
|
-
await writeProjection(scoped, {
|
|
1047
|
-
at: now,
|
|
1048
|
-
body: existing.body,
|
|
1049
|
-
create: false,
|
|
1050
|
-
entityName: name,
|
|
1051
|
-
hash: hash2,
|
|
1052
|
-
head: head2,
|
|
1053
|
-
lineage: output.lineage,
|
|
1054
|
-
ref: output.ref,
|
|
1055
|
-
retiredAt: now,
|
|
1056
|
-
tenantId,
|
|
1057
|
-
version
|
|
1058
|
-
});
|
|
1059
|
-
return;
|
|
1060
|
-
}
|
|
1061
|
-
const prior = await revisionRowAt(
|
|
1062
|
-
scoped,
|
|
1063
|
-
tenantId,
|
|
1064
|
-
name,
|
|
1065
|
-
output.ref,
|
|
1066
|
-
output.lineage,
|
|
1067
|
-
output.previous.version
|
|
1068
|
-
);
|
|
1069
|
-
if (prior === void 0) {
|
|
1070
|
-
throw new import_db2.DbRefusal(
|
|
1071
|
-
`"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
|
|
1072
|
-
);
|
|
1073
|
-
}
|
|
1074
|
-
const head = definition.headOf(readBody(definition, name, output.ref, prior.body));
|
|
1075
|
-
const hash = await insertRevisionRow(scoped, {
|
|
1142
|
+
const compensate = async (scoped, tenantId, output, kind, body, retired) => {
|
|
1143
|
+
const appended = await append(scoped, {
|
|
1076
1144
|
actor: UNDO_ACTOR,
|
|
1077
|
-
|
|
1078
|
-
body: prior.body,
|
|
1145
|
+
body,
|
|
1079
1146
|
compensationOf: output.version,
|
|
1080
|
-
|
|
1081
|
-
kind: "committed",
|
|
1147
|
+
kind,
|
|
1082
1148
|
lineage: output.lineage,
|
|
1083
|
-
|
|
1149
|
+
reason: `undo of v${output.version}`,
|
|
1084
1150
|
ref: output.ref,
|
|
1085
|
-
|
|
1086
|
-
tenantId,
|
|
1087
|
-
version
|
|
1151
|
+
tenantId
|
|
1088
1152
|
});
|
|
1089
|
-
await
|
|
1090
|
-
at:
|
|
1091
|
-
body
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
hash,
|
|
1095
|
-
head,
|
|
1153
|
+
await project(scoped, {
|
|
1154
|
+
at: appended.at,
|
|
1155
|
+
body,
|
|
1156
|
+
hash: appended.hash,
|
|
1157
|
+
head: storedHead(output.ref, body),
|
|
1096
1158
|
lineage: output.lineage,
|
|
1097
1159
|
ref: output.ref,
|
|
1098
|
-
retiredAt: null,
|
|
1160
|
+
retiredAt: retired ? appended.at : null,
|
|
1099
1161
|
tenantId,
|
|
1100
|
-
version
|
|
1162
|
+
version: appended.version
|
|
1101
1163
|
});
|
|
1102
1164
|
};
|
|
1165
|
+
const lockedForUndo = async (scoped, tenantId, output) => {
|
|
1166
|
+
const existing = await locked(scoped, { ...tenanted(tenantId), ref: output.ref });
|
|
1167
|
+
if (existing === void 0) {
|
|
1168
|
+
throw new import_db2.DbRefusal(
|
|
1169
|
+
`"${output.ref}" (${name}) has nothing to undo \u2014 the row v${output.version} wrote is gone`
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
return existing;
|
|
1173
|
+
};
|
|
1103
1174
|
const undos = {
|
|
1104
|
-
commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, (scoped) =>
|
|
1105
|
-
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1175
|
+
commit: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
|
|
1176
|
+
if (!output.committed) return;
|
|
1177
|
+
const existing = await lockedForUndo(scoped, tenantId, output);
|
|
1178
|
+
if (output.previous === null) {
|
|
1179
|
+
await compensate(scoped, tenantId, output, "retired", existing.body, true);
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
const prior = await needsLog().at(scoped, {
|
|
1183
|
+
...stream({ ...tenanted(tenantId), ref: output.ref }, output.lineage),
|
|
1184
|
+
sequence: output.previous.version
|
|
1185
|
+
});
|
|
1186
|
+
if (prior === null) {
|
|
1109
1187
|
throw new import_db2.DbRefusal(
|
|
1110
|
-
`"${output.ref}" (${name})
|
|
1188
|
+
`"${output.ref}" (${name}) version ${output.previous.version} is gone \u2014 cannot undo v${output.version} without it`
|
|
1111
1189
|
);
|
|
1112
1190
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
);
|
|
1117
|
-
|
|
1118
|
-
actor: UNDO_ACTOR,
|
|
1119
|
-
at: now,
|
|
1120
|
-
body: existing.body,
|
|
1121
|
-
compensationOf: output.version,
|
|
1122
|
-
entityName: name,
|
|
1123
|
-
kind: "reinstated",
|
|
1124
|
-
lineage: output.lineage,
|
|
1125
|
-
prevHash: existing.hash,
|
|
1126
|
-
ref: output.ref,
|
|
1127
|
-
reason: `undo of v${output.version}`,
|
|
1128
|
-
tenantId,
|
|
1129
|
-
version
|
|
1130
|
-
});
|
|
1131
|
-
await writeProjection(scoped, {
|
|
1132
|
-
at: now,
|
|
1133
|
-
body: existing.body,
|
|
1134
|
-
create: false,
|
|
1135
|
-
entityName: name,
|
|
1136
|
-
hash,
|
|
1137
|
-
head,
|
|
1138
|
-
lineage: output.lineage,
|
|
1139
|
-
ref: output.ref,
|
|
1140
|
-
retiredAt: null,
|
|
1141
|
-
tenantId,
|
|
1142
|
-
version
|
|
1143
|
-
});
|
|
1191
|
+
await compensate(scoped, tenantId, output, "committed", prior.body, false);
|
|
1192
|
+
}),
|
|
1193
|
+
retire: (tx, { output, tenantId }) => seam.inTenant(tx, tenantId, async (scoped) => {
|
|
1194
|
+
const existing = await lockedForUndo(scoped, tenantId, output);
|
|
1195
|
+
await compensate(scoped, tenantId, output, "reinstated", existing.body, false);
|
|
1144
1196
|
})
|
|
1145
1197
|
};
|
|
1198
|
+
const restore = async (tx, row, createdAt) => {
|
|
1199
|
+
const ref = String(row.ref);
|
|
1200
|
+
await project(tx, {
|
|
1201
|
+
at: createdAt,
|
|
1202
|
+
body: row.body,
|
|
1203
|
+
hash: row.hash,
|
|
1204
|
+
head: storedHead(ref, row.body),
|
|
1205
|
+
lineage: Number(row.lineage),
|
|
1206
|
+
ref,
|
|
1207
|
+
retiredAt: row.kind === "retired" ? row.at : null,
|
|
1208
|
+
tenantId: row.tenant,
|
|
1209
|
+
version: row.sequence
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1146
1212
|
return {
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1213
|
+
door: {
|
|
1214
|
+
asOf,
|
|
1215
|
+
at,
|
|
1216
|
+
commit,
|
|
1217
|
+
get: projection.get,
|
|
1218
|
+
history,
|
|
1219
|
+
list: projection.list,
|
|
1220
|
+
listAll: projection.listAll,
|
|
1221
|
+
reinstate,
|
|
1222
|
+
retire,
|
|
1223
|
+
succeed,
|
|
1224
|
+
undos,
|
|
1225
|
+
verify
|
|
1226
|
+
},
|
|
1227
|
+
restore
|
|
1159
1228
|
};
|
|
1160
1229
|
};
|
|
1161
|
-
const
|
|
1162
|
-
|
|
1230
|
+
const built = registry.names.map((name) => [name, entityStoreFor(name)]);
|
|
1231
|
+
const rawEntities = Object.fromEntries(built.map(([name, one]) => [name, one.door]));
|
|
1232
|
+
const restorers = Object.fromEntries(
|
|
1233
|
+
built.map(([name, one]) => [name, one.restore])
|
|
1163
1234
|
);
|
|
1164
1235
|
const heads = seam.scoped(async (tx, params) => {
|
|
1165
1236
|
const { columns, entity, order, where } = params;
|
|
1166
|
-
const
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
predicates.push(
|
|
1183
|
-
text(` and ${quote(createdAtColumn)} between `),
|
|
1184
|
-
bound(where.createdAt[0]),
|
|
1185
|
-
text(" and "),
|
|
1186
|
-
bound(where.createdAt[1])
|
|
1187
|
-
);
|
|
1188
|
-
}
|
|
1189
|
-
predicates.push(
|
|
1190
|
-
text(
|
|
1191
|
-
` order by ${order.map((one) => `${quote(columnOf(one.column))} ${one.direction === "desc" ? "desc" : "asc"}`).join(", ")}`
|
|
1237
|
+
const rows = await readers.project(tx, {
|
|
1238
|
+
...tenanted(params[tenantKey]),
|
|
1239
|
+
columns: columns.filter((column) => column !== "number").map(columnOf),
|
|
1240
|
+
order: order.map((one) => ({
|
|
1241
|
+
column: columnOf(one.column),
|
|
1242
|
+
...one.direction === void 0 ? {} : { direction: one.direction }
|
|
1243
|
+
})),
|
|
1244
|
+
where: {
|
|
1245
|
+
...entity === void 0 ? {} : { [entityColumn]: entity },
|
|
1246
|
+
...where?.status === void 0 ? {} : { status: where.status },
|
|
1247
|
+
...where?.createdAt === void 0 ? {} : { [createdAtColumn]: { from: where.createdAt[0], to: where.createdAt[1] } }
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
return rows.map(
|
|
1251
|
+
(row) => Object.fromEntries(
|
|
1252
|
+
columns.map((column) => [column, column === "number" ? row.key : row[columnOf(column)]])
|
|
1192
1253
|
)
|
|
1193
1254
|
);
|
|
1194
|
-
return (0, import_conformance.rowsOf)(
|
|
1195
|
-
await seam.send(tx, chainAll(predicates))
|
|
1196
|
-
);
|
|
1197
1255
|
});
|
|
1198
|
-
const aggregate = seam.scoped(
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
if (entities !== void 0) {
|
|
1218
|
-
predicates.push(text(` and ${quote(entityColumn)} = any(`), bound(entities), text(")"));
|
|
1219
|
-
}
|
|
1220
|
-
if (where?.status !== void 0) {
|
|
1221
|
-
predicates.push(text(` and ${quote(columnOf("status"))} = `), bound(where.status));
|
|
1222
|
-
}
|
|
1223
|
-
if (where !== void 0 && "issueDate" in where) {
|
|
1224
|
-
predicates.push(
|
|
1225
|
-
text(` and ${quote(columnOf("issueDate"))} between `),
|
|
1226
|
-
bound(where.issueDate[0]),
|
|
1227
|
-
text(" and "),
|
|
1228
|
-
bound(where.issueDate[1])
|
|
1229
|
-
);
|
|
1230
|
-
}
|
|
1231
|
-
if (where !== void 0 && "createdAt" in where) {
|
|
1232
|
-
predicates.push(
|
|
1233
|
-
text(` and ${quote(createdAtColumn)} between `),
|
|
1234
|
-
bound(where.createdAt[0]),
|
|
1235
|
-
text(" and "),
|
|
1236
|
-
bound(where.createdAt[1])
|
|
1237
|
-
);
|
|
1238
|
-
}
|
|
1239
|
-
if (by !== void 0) predicates.push(text(' group by "by" order by "by"'));
|
|
1240
|
-
const rows = (0, import_conformance.rowsOf)(
|
|
1241
|
-
await seam.send(tx, chainAll(predicates))
|
|
1242
|
-
);
|
|
1243
|
-
if (rows.length === 0 && by === void 0) {
|
|
1244
|
-
return [{ ...wantsCount ? { count: 0 } : {}, ...wantsSum ? { sum: "0" } : {} }];
|
|
1256
|
+
const aggregate = seam.scoped(
|
|
1257
|
+
(tx, params) => {
|
|
1258
|
+
const { by, entities, entity, measures, where } = params;
|
|
1259
|
+
return readers.aggregate(tx, {
|
|
1260
|
+
...tenanted(params[tenantKey]),
|
|
1261
|
+
...by === void 0 ? {} : {
|
|
1262
|
+
by: by === "entity" ? entityColumn : by === "status" ? "status" : { bucket: by.bucket, of: by.of }
|
|
1263
|
+
},
|
|
1264
|
+
measures: measures.map(
|
|
1265
|
+
(one) => one === "sum:total" ? `sum:${totalColumn}` : one
|
|
1266
|
+
),
|
|
1267
|
+
where: {
|
|
1268
|
+
...entity === void 0 ? {} : { [entityColumn]: entity },
|
|
1269
|
+
...entities === void 0 ? {} : { [entityColumn]: entities },
|
|
1270
|
+
...where?.status === void 0 ? {} : { status: where.status },
|
|
1271
|
+
...where !== void 0 && "issueDate" in where ? { issueDate: { from: where.issueDate[0], to: where.issueDate[1] } } : {},
|
|
1272
|
+
...where !== void 0 && "createdAt" in where ? { [createdAtColumn]: { from: where.createdAt[0], to: where.createdAt[1] } } : {}
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
1245
1275
|
}
|
|
1246
|
-
|
|
1247
|
-
...by === void 0 ? {} : { by: row.by },
|
|
1248
|
-
...wantsCount ? { count: row.count ?? 0 } : {},
|
|
1249
|
-
...wantsSum ? { sum: row.sum ?? "0" } : {}
|
|
1250
|
-
}));
|
|
1251
|
-
});
|
|
1276
|
+
);
|
|
1252
1277
|
const rebuild = seam.scoped(
|
|
1253
1278
|
async (tx, params) => {
|
|
1254
1279
|
const log = needsLog();
|
|
1255
|
-
const
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
)
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1280
|
+
const tenant = tenanted(params[tenantKey]);
|
|
1281
|
+
const latest = /* @__PURE__ */ new Map();
|
|
1282
|
+
for (const row of await log.latestPerStream(tx, tenant)) {
|
|
1283
|
+
if (params.entity !== void 0 && row.entity !== params.entity) continue;
|
|
1284
|
+
const address = `${String(row.entity)} ${String(row.ref)}`;
|
|
1285
|
+
const held = latest.get(address);
|
|
1286
|
+
if (held === void 0 || Number(row.lineage) > Number(held.lineage)) {
|
|
1287
|
+
latest.set(address, row);
|
|
1288
|
+
}
|
|
1264
1289
|
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
)
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
const definition = registry.named(row.entity);
|
|
1273
|
-
if (definition === void 0) continue;
|
|
1274
|
-
const clean = readBody(definition, row.entity, row.ref, row.body);
|
|
1275
|
-
const head = definition.headOf(clean);
|
|
1276
|
-
await upsertProjection(tx, {
|
|
1277
|
-
at: Number(row.createdAt),
|
|
1278
|
-
body: row.body,
|
|
1279
|
-
entityName: row.entity,
|
|
1280
|
-
hash: row.hash,
|
|
1281
|
-
head,
|
|
1290
|
+
let rows = 0;
|
|
1291
|
+
for (const row of latest.values()) {
|
|
1292
|
+
const restore = restorers[String(row.entity)];
|
|
1293
|
+
if (restore === void 0) continue;
|
|
1294
|
+
const first = await log.at(tx, {
|
|
1295
|
+
...tenant,
|
|
1296
|
+
entity: row.entity,
|
|
1282
1297
|
lineage: row.lineage,
|
|
1283
1298
|
ref: row.ref,
|
|
1284
|
-
|
|
1285
|
-
tenantId,
|
|
1286
|
-
version: row.version
|
|
1299
|
+
sequence: 1
|
|
1287
1300
|
});
|
|
1301
|
+
await restore(tx, row, first?.at ?? row.at);
|
|
1302
|
+
rows += 1;
|
|
1288
1303
|
}
|
|
1289
|
-
return { rows
|
|
1304
|
+
return { rows };
|
|
1290
1305
|
}
|
|
1291
1306
|
);
|
|
1292
1307
|
return { ...rawEntities, aggregate, heads, rebuild };
|
|
@@ -1308,6 +1323,7 @@ var documentStore = (options) => {
|
|
|
1308
1323
|
documentMigrations,
|
|
1309
1324
|
documentRoleStatements,
|
|
1310
1325
|
documentStore,
|
|
1326
|
+
documentSurface,
|
|
1311
1327
|
fieldPatterns,
|
|
1312
1328
|
hashOf,
|
|
1313
1329
|
isSystemActor,
|