@fabrika/db 0.9.0-dev.12 → 0.9.0-dev.13
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/package.json +4 -4
- package/src/authority.ts +254 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +15 -0
- package/src/codegen.ts +11 -1
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/description.ts +3 -0
- package/src/framework.ts +1 -1
- package/src/guard.ts +302 -15
- package/src/nodes.ts +9 -6
- package/src/orm-types.ts +13 -2
- package/src/orm.ts +66 -28
- package/src/policy.ts +1197 -39
- package/src/registry.ts +11 -0
- package/src/sql.ts +22 -3
- package/src/store.ts +740 -55
- package/src/tables.ts +101 -2
- package/src/vocabulary-tables.ts +23 -1
- package/types/src/authority.d.ts +66 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +15 -0
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/description.d.ts +3 -0
- package/types/src/framework.d.ts +1 -1
- package/types/src/guard.d.ts +16 -0
- package/types/src/nodes.d.ts +2 -0
- package/types/src/orm-types.d.ts +17 -2
- package/types/src/policy.d.ts +191 -0
- package/types/src/registry.d.ts +9 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/store.d.ts +45 -7
- package/types/src/tables.d.ts +6 -0
- package/types/src/vocabulary-tables.d.ts +37 -2
package/src/store.ts
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { uuidv7 } from '@fabrika/platform'
|
|
2
|
-
import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
|
|
2
|
+
import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
|
|
3
3
|
import { admissions } from './admissions'
|
|
4
|
+
import {
|
|
5
|
+
activeRow,
|
|
6
|
+
conditioned,
|
|
7
|
+
type LayerRelation,
|
|
8
|
+
type MemberReveals,
|
|
9
|
+
memberTerms,
|
|
10
|
+
namesPrincipal,
|
|
11
|
+
refScope,
|
|
12
|
+
relationGate,
|
|
13
|
+
relationSource,
|
|
14
|
+
type RelationSources,
|
|
15
|
+
relationTerms,
|
|
16
|
+
revealedNodes,
|
|
17
|
+
throughPath,
|
|
18
|
+
viewScope,
|
|
19
|
+
} from './authority'
|
|
4
20
|
import {
|
|
5
21
|
defineValue,
|
|
6
22
|
freeze,
|
|
@@ -32,6 +48,8 @@ import {
|
|
|
32
48
|
type Within,
|
|
33
49
|
type WithinGrant,
|
|
34
50
|
} from './capability'
|
|
51
|
+
import { conditionNode, subquery } from './condition-nodes'
|
|
52
|
+
import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
|
|
35
53
|
import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
|
|
36
54
|
import {
|
|
37
55
|
type ComparableColumn,
|
|
@@ -42,6 +60,7 @@ import {
|
|
|
42
60
|
finishSelect,
|
|
43
61
|
isPrimitive,
|
|
44
62
|
type JoinShape,
|
|
63
|
+
type JoinState,
|
|
45
64
|
type NoColumns,
|
|
46
65
|
type Primitive,
|
|
47
66
|
type ScopedSelect,
|
|
@@ -53,7 +72,7 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
|
|
|
53
72
|
import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
|
|
54
73
|
import { fileReference } from './file-references'
|
|
55
74
|
import { webhookTables } from './framework-tables'
|
|
56
|
-
import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
|
|
75
|
+
import type { ForeignKeyPair, GuardContext, RootKind, ViewParentLink } from './guard'
|
|
57
76
|
import { fencedTransaction, jobLeases } from './job-leases'
|
|
58
77
|
import { jobWakes, leaseProjection } from './job-wakes'
|
|
59
78
|
import { jsonInput } from './json'
|
|
@@ -77,6 +96,7 @@ import {
|
|
|
77
96
|
scopedWhere,
|
|
78
97
|
selectNode,
|
|
79
98
|
updateNode,
|
|
99
|
+
valueList,
|
|
80
100
|
} from './nodes'
|
|
81
101
|
import { dataAccess } from './orm'
|
|
82
102
|
import {
|
|
@@ -85,18 +105,22 @@ import {
|
|
|
85
105
|
type ChildTableName,
|
|
86
106
|
type Container,
|
|
87
107
|
type ContainerOf,
|
|
108
|
+
delegates,
|
|
88
109
|
type DimensionOf,
|
|
89
110
|
type DimensionTableName,
|
|
90
111
|
includes,
|
|
91
112
|
type InsertValues,
|
|
92
113
|
type JoinableChildren,
|
|
93
114
|
type ListDimensionOf,
|
|
115
|
+
type MemberRevealModel,
|
|
94
116
|
modelOf,
|
|
95
117
|
type MoveAcknowledgement,
|
|
96
118
|
namesAction,
|
|
97
119
|
type Operation,
|
|
98
120
|
type ParentOf,
|
|
99
121
|
type PolicyRow,
|
|
122
|
+
type RevealModel,
|
|
123
|
+
type SecondaryPath,
|
|
100
124
|
type TableModel,
|
|
101
125
|
type TableModels,
|
|
102
126
|
tableModels,
|
|
@@ -139,6 +163,19 @@ export interface TableContext {
|
|
|
139
163
|
/** The model of each child a select may join, by its table name. */
|
|
140
164
|
readonly children: Readonly<Record<string, TableModel>>
|
|
141
165
|
readonly connection: Connection
|
|
166
|
+
/** Every relation of the layer with its source table: what a relation term of any table reads. */
|
|
167
|
+
readonly relations: RelationSources
|
|
168
|
+
/** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
|
|
169
|
+
readonly members: MemberReveals
|
|
170
|
+
/** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
|
|
171
|
+
readonly subqueries: Readonly<Record<string, readonly string[]>>
|
|
172
|
+
/** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
|
|
173
|
+
readonly through: ViewParent | undefined
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
|
|
177
|
+
export interface ViewParent extends ViewParentLink {
|
|
178
|
+
readonly context: TableContext
|
|
142
179
|
}
|
|
143
180
|
|
|
144
181
|
/** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
|
|
@@ -299,13 +336,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
|
|
|
299
336
|
return grant
|
|
300
337
|
}
|
|
301
338
|
|
|
302
|
-
/**
|
|
339
|
+
/**
|
|
340
|
+
* The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
|
|
341
|
+
* table's own dimension counts, so its containers lie above a `Within` of it.
|
|
342
|
+
*/
|
|
303
343
|
function linksAbove(model: TableModel, dimension: string): readonly Container[] {
|
|
304
|
-
|
|
305
|
-
|
|
344
|
+
const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
|
|
345
|
+
for (let index = 0; index < links.length; index++) {
|
|
346
|
+
if (links[index]?.dimension === dimension) {
|
|
306
347
|
const above: Container[] = []
|
|
307
|
-
for (let position = index + 1; position <
|
|
308
|
-
const link =
|
|
348
|
+
for (let position = index + 1; position < links.length; position++) {
|
|
349
|
+
const link = links[position]
|
|
309
350
|
if (link !== undefined) {
|
|
310
351
|
above[above.length] = link
|
|
311
352
|
}
|
|
@@ -383,6 +424,9 @@ function withinCount(grant: WithinGrant): number {
|
|
|
383
424
|
for (let index = 0; index < grant.contained.length; index++) {
|
|
384
425
|
count += grant.contained[index]?.values.length ?? 0
|
|
385
426
|
}
|
|
427
|
+
for (let index = 0; index < grant.revealing.length; index++) {
|
|
428
|
+
count += grant.revealing[index]?.values.length ?? 0
|
|
429
|
+
}
|
|
386
430
|
return count
|
|
387
431
|
}
|
|
388
432
|
|
|
@@ -391,9 +435,11 @@ function withinCount(grant: WithinGrant): number {
|
|
|
391
435
|
* the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
|
|
392
436
|
* answers `[]` without a query.
|
|
393
437
|
*/
|
|
394
|
-
function withinPredicate(
|
|
438
|
+
function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
|
|
439
|
+
const model = context.model
|
|
440
|
+
const now = new Date()
|
|
395
441
|
if (grant.values === 'all') {
|
|
396
|
-
return
|
|
442
|
+
return conditioned(model, grant.action, 'all', now)
|
|
397
443
|
}
|
|
398
444
|
const above = linksAbove(model, grant.dimension)
|
|
399
445
|
const predicates: OperationNode[] = []
|
|
@@ -427,7 +473,70 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
|
|
|
427
473
|
if (count > MAX_WITHIN_VALUES) {
|
|
428
474
|
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
|
|
429
475
|
}
|
|
430
|
-
|
|
476
|
+
addRelationTerms(context, grant, operation === 'read', predicates, now)
|
|
477
|
+
if (operation === 'read') addMemberTerms(context, grant, predicates, now)
|
|
478
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
|
|
482
|
+
function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
|
|
483
|
+
const terms = memberTerms(context.members, context.model, grant, now)
|
|
484
|
+
for (let index = 0; index < terms.length; index++) {
|
|
485
|
+
const term = terms[index]
|
|
486
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
|
|
491
|
+
function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
|
|
492
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
493
|
+
const terms = relationTerms(context.relations, context.model, grant.relations[index] ?? '', grant.principal, grant.action, now, reads)
|
|
494
|
+
for (let position = 0; position < terms.length; position++) {
|
|
495
|
+
const term = terms[position]
|
|
496
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
|
|
503
|
+
* `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
|
|
504
|
+
* (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
|
|
505
|
+
* Within's lies at no node the column holds, so it reaches no row here.
|
|
506
|
+
*/
|
|
507
|
+
function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
|
|
508
|
+
const model = context.model
|
|
509
|
+
const now = new Date()
|
|
510
|
+
if (grant.values === 'all') {
|
|
511
|
+
return conditioned(model, grant.action, 'all', now)
|
|
512
|
+
}
|
|
513
|
+
if (withinCount(grant) > MAX_WITHIN_VALUES) {
|
|
514
|
+
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
|
|
515
|
+
}
|
|
516
|
+
const predicates: OperationNode[] = []
|
|
517
|
+
for (let index = 0; index < paths.length; index++) {
|
|
518
|
+
const path = paths[index]
|
|
519
|
+
if (path === undefined) continue
|
|
520
|
+
if (grant.values.length > 0) {
|
|
521
|
+
const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
|
|
522
|
+
if (own !== undefined) predicates[predicates.length] = own
|
|
523
|
+
}
|
|
524
|
+
for (let position = 0; position < grant.containers.length; position++) {
|
|
525
|
+
const container = grant.containers[position]
|
|
526
|
+
if (container === undefined || container.values.length === 0) continue
|
|
527
|
+
const above = throughPath(model.name, path, container.dimension, valueList(container.values))
|
|
528
|
+
if (above === undefined) {
|
|
529
|
+
throw new CapabilityError(
|
|
530
|
+
'unenforceable',
|
|
531
|
+
`the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
|
|
532
|
+
)
|
|
533
|
+
}
|
|
534
|
+
predicates[predicates.length] = above
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
addRelationTerms(context, grant, true, predicates, now)
|
|
538
|
+
addMemberTerms(context, grant, predicates, now)
|
|
539
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
431
540
|
}
|
|
432
541
|
|
|
433
542
|
/** The object a Ref of the model's own dimension names, with every link of its chain. */
|
|
@@ -447,19 +556,47 @@ export function selfLinks(model: TableModel): readonly Container[] {
|
|
|
447
556
|
export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
|
|
448
557
|
const scope = dimensionScope(context.model)
|
|
449
558
|
const grant = refGrant(context, capability, scope.dimension, operation)
|
|
450
|
-
return
|
|
559
|
+
return refScope(context.relations, context.model, selfLinks(context.model), grant, new Date())
|
|
451
560
|
}
|
|
452
561
|
|
|
453
562
|
/** Rows of a dimension table within the scope values of its list dimension. */
|
|
454
563
|
export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
455
564
|
const scope = dimensionScope(context.model)
|
|
456
565
|
const grant = withinGrant(context, capability, listDimension(scope), operation)
|
|
457
|
-
return withinPredicate(context
|
|
566
|
+
return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
|
|
458
567
|
}
|
|
459
568
|
|
|
460
|
-
/**
|
|
461
|
-
|
|
462
|
-
|
|
569
|
+
/**
|
|
570
|
+
* Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
|
|
571
|
+
* of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
|
|
572
|
+
*/
|
|
573
|
+
export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
|
|
574
|
+
const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
|
|
575
|
+
const through = context.through
|
|
576
|
+
if (through !== undefined) {
|
|
577
|
+
const parent = through.context
|
|
578
|
+
const now = new Date()
|
|
579
|
+
return viewScope(context.model, through, grant.action, refScope(parent.relations, parent.model, selfLinks(parent.model), grant, now), now, row)
|
|
580
|
+
}
|
|
581
|
+
return refScope(context.relations, context.model, context.model.chain, grant, new Date(), row)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
|
|
586
|
+
* those whose parent row exists. Undefined where `reach` is: the empty `Within`.
|
|
587
|
+
*/
|
|
588
|
+
function throughParent(
|
|
589
|
+
context: TableContext,
|
|
590
|
+
through: ViewParent,
|
|
591
|
+
grant: WithinGrant,
|
|
592
|
+
reach: (parent: TableContext) => OperationNode | undefined,
|
|
593
|
+
): OperationNode | undefined {
|
|
594
|
+
const now = new Date()
|
|
595
|
+
if (grant.values === 'all') {
|
|
596
|
+
return viewScope(context.model, through, grant.action, 'all', now)
|
|
597
|
+
}
|
|
598
|
+
const reached = reach(through.context)
|
|
599
|
+
return reached === undefined ? undefined : viewScope(context.model, through, grant.action, reached, now)
|
|
463
600
|
}
|
|
464
601
|
|
|
465
602
|
export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
@@ -473,7 +610,11 @@ export function childListPredicate(context: TableContext, capability: unknown, o
|
|
|
473
610
|
throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
|
|
474
611
|
}
|
|
475
612
|
checkGrant(context, grant, listDimension(scope.parent), operation)
|
|
476
|
-
|
|
613
|
+
if (context.through !== undefined) {
|
|
614
|
+
const column = scope.parent.container?.column ?? scope.parent.key
|
|
615
|
+
return throughParent(context, context.through, grant, (parent) => withinPredicate(parent, column, grant, operation))
|
|
616
|
+
}
|
|
617
|
+
return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
|
|
477
618
|
}
|
|
478
619
|
|
|
479
620
|
/**
|
|
@@ -493,9 +634,39 @@ export function reachColumn(model: TableModel, dimension: string): string | unde
|
|
|
493
634
|
return undefined
|
|
494
635
|
}
|
|
495
636
|
|
|
637
|
+
/**
|
|
638
|
+
* Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
|
|
639
|
+
* view through its parent's, its parent's own dimension included.
|
|
640
|
+
*/
|
|
641
|
+
export function reachedBy(context: TableContext, dimension: string): boolean {
|
|
642
|
+
const model = context.through?.context.model ?? context.model
|
|
643
|
+
return parentColumn(model, context.through !== undefined, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** The column that places a row of `model` in `dimension`, a view's parent's own key among them (`own`). */
|
|
647
|
+
function parentColumn(model: TableModel, own: boolean, dimension: string): string | undefined {
|
|
648
|
+
if (own && model.scope.mode === 'dimension' && model.scope.dimension === dimension) {
|
|
649
|
+
return model.scope.key
|
|
650
|
+
}
|
|
651
|
+
return reachColumn(model, dimension)
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
|
|
655
|
+
export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
|
|
656
|
+
const paths: SecondaryPath[] = []
|
|
657
|
+
for (let index = 0; index < model.readThrough.length; index++) {
|
|
658
|
+
const path = model.readThrough[index]
|
|
659
|
+
if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
|
|
660
|
+
paths[paths.length] = path
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
return paths
|
|
664
|
+
}
|
|
665
|
+
|
|
496
666
|
/**
|
|
497
667
|
* Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
|
|
498
|
-
* `org` through their stamped `org_id`, as under one of `project` through `project_id
|
|
668
|
+
* `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
|
|
669
|
+
* table reaches through a secondary path, through that path's column.
|
|
499
670
|
*/
|
|
500
671
|
export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
|
|
501
672
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
@@ -504,14 +675,25 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
|
|
|
504
675
|
throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
|
|
505
676
|
}
|
|
506
677
|
checkAction(context, 'read', grant.action)
|
|
507
|
-
|
|
508
|
-
if (column === undefined) {
|
|
678
|
+
if (!reachedBy(context, grant.dimension)) {
|
|
509
679
|
throw new CapabilityError(
|
|
510
680
|
'out_of_reach',
|
|
511
|
-
`a Within of ${grant.dimension} does not reach ${table}: its containment chain
|
|
681
|
+
`a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
|
|
512
682
|
)
|
|
513
683
|
}
|
|
514
|
-
|
|
684
|
+
if (context.through !== undefined) {
|
|
685
|
+
return throughParent(context, context.through, grant, (parent) => withinReach(parent, grant, true))
|
|
686
|
+
}
|
|
687
|
+
return withinReach(context, grant, false)
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
|
|
691
|
+
function withinReach(context: TableContext, grant: WithinGrant, own: boolean): OperationNode | undefined {
|
|
692
|
+
const column = parentColumn(context.model, own, grant.dimension)
|
|
693
|
+
if (column !== undefined) {
|
|
694
|
+
return withinPredicate(context, column, grant, 'read')
|
|
695
|
+
}
|
|
696
|
+
return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
|
|
515
697
|
}
|
|
516
698
|
|
|
517
699
|
/**
|
|
@@ -568,6 +750,20 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
|
|
|
568
750
|
if (use !== 'read') {
|
|
569
751
|
checkWriteTarget(context, grant, use)
|
|
570
752
|
}
|
|
753
|
+
// The fragment renders column tests only; a relation's subquery or an action's condition would be left out.
|
|
754
|
+
if ((grant.kind !== 'app' && grant.relations.length > 0) || hasOwn(model.when, grant.action)) {
|
|
755
|
+
throw new CapabilityError(
|
|
756
|
+
'unenforceable',
|
|
757
|
+
`ctx.sql.scope cannot render a relation or a condition of ${grant.action} on ${model.name}: read it through ctx.db`,
|
|
758
|
+
)
|
|
759
|
+
}
|
|
760
|
+
// Nor the subquery through the parent row, which alone places a child view's rows.
|
|
761
|
+
if (grant.kind !== 'app' && context.through !== undefined) {
|
|
762
|
+
throw new CapabilityError(
|
|
763
|
+
'unenforceable',
|
|
764
|
+
`ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
|
|
765
|
+
)
|
|
766
|
+
}
|
|
571
767
|
if (grant.kind === 'app') {
|
|
572
768
|
if (use === 'read') {
|
|
573
769
|
// The action is held as a global grant, so its scope is every row of a table it reaches.
|
|
@@ -762,7 +958,7 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
|
|
|
762
958
|
throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
|
|
763
959
|
}
|
|
764
960
|
checkRecordReach(context, grant, reach)
|
|
765
|
-
return
|
|
961
|
+
return conditioned(model, grant.action, 'all', new Date())
|
|
766
962
|
}
|
|
767
963
|
|
|
768
964
|
/** An `app` capability addresses a row by its key, and writes, only in an application table. */
|
|
@@ -795,15 +991,15 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
|
|
|
795
991
|
|
|
796
992
|
/** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
|
|
797
993
|
export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
|
|
798
|
-
appGrant(context, capability, 'read')
|
|
799
|
-
return
|
|
994
|
+
const grant = appGrant(context, capability, 'read')
|
|
995
|
+
return conditioned(context.model, grant.action, 'all', new Date())
|
|
800
996
|
}
|
|
801
997
|
|
|
802
998
|
/**
|
|
803
999
|
* Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
|
|
804
1000
|
* or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
|
|
805
1001
|
*/
|
|
806
|
-
export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
|
|
1002
|
+
export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
|
|
807
1003
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
808
1004
|
const model = context.model
|
|
809
1005
|
if (model.scope.mode !== 'app') {
|
|
@@ -819,14 +1015,14 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
|
|
|
819
1015
|
`a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
|
|
820
1016
|
)
|
|
821
1017
|
}
|
|
822
|
-
return
|
|
1018
|
+
return conditioned(model, grant.action, branch, new Date())
|
|
823
1019
|
}
|
|
824
1020
|
|
|
825
1021
|
/** One row of an application table by its key, for an `app` capability of `operation`'s action. */
|
|
826
1022
|
export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
|
|
827
1023
|
checkApplicationTable(context, operation)
|
|
828
|
-
appGrant(context, capability, operation)
|
|
829
|
-
return appKeyPredicate(context.model, key)
|
|
1024
|
+
const grant = appGrant(context, capability, operation)
|
|
1025
|
+
return conditioned(context.model, grant.action, appKeyPredicate(context.model, key), new Date())
|
|
830
1026
|
}
|
|
831
1027
|
|
|
832
1028
|
/**
|
|
@@ -843,7 +1039,8 @@ export function claimScope(
|
|
|
843
1039
|
throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
|
|
844
1040
|
}
|
|
845
1041
|
if (grant.kind === 'app') {
|
|
846
|
-
|
|
1042
|
+
const held = appGrant(context, capability, 'update')
|
|
1043
|
+
return { grant: held, scope: conditioned(model, held.action, 'all', new Date()) }
|
|
847
1044
|
}
|
|
848
1045
|
if (grant.kind !== 'within') {
|
|
849
1046
|
throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
|
|
@@ -859,7 +1056,7 @@ export function claimScope(
|
|
|
859
1056
|
`a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
|
|
860
1057
|
)
|
|
861
1058
|
}
|
|
862
|
-
return { grant, scope: withinPredicate(
|
|
1059
|
+
return { grant, scope: withinPredicate(context, column, grant, 'update') }
|
|
863
1060
|
}
|
|
864
1061
|
|
|
865
1062
|
/**
|
|
@@ -882,7 +1079,12 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
|
|
|
882
1079
|
}
|
|
883
1080
|
terms[terms.length] = equals(model.name, link.column, value)
|
|
884
1081
|
}
|
|
885
|
-
return allOf(terms)
|
|
1082
|
+
return conditioned(model, grant.action, allOf(terms), new Date())
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** The row of an application table `key` names, as `action` reaches it: within the action's condition. */
|
|
1086
|
+
export function appKeyScope(model: TableModel, action: string, key: unknown): OperationNode {
|
|
1087
|
+
return conditioned(model, action, appKeyPredicate(model, key), new Date())
|
|
886
1088
|
}
|
|
887
1089
|
|
|
888
1090
|
/** The row of an application table `key` names. */
|
|
@@ -922,7 +1124,7 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
|
|
|
922
1124
|
throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
|
|
923
1125
|
}
|
|
924
1126
|
const grant = refGrant(context, parent, scope.parent.dimension, operation)
|
|
925
|
-
return
|
|
1127
|
+
return parentPredicate(context, grant, key)
|
|
926
1128
|
}
|
|
927
1129
|
|
|
928
1130
|
export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
|
|
@@ -930,7 +1132,14 @@ export function guard(context: TableContext, root: RootKind, scope: OperationNod
|
|
|
930
1132
|
if (context.model.view && root !== 'SelectQueryNode') {
|
|
931
1133
|
throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
|
|
932
1134
|
}
|
|
933
|
-
return {
|
|
1135
|
+
return {
|
|
1136
|
+
root,
|
|
1137
|
+
table: context.model.name,
|
|
1138
|
+
joins: root === 'SelectQueryNode' ? context.joins : {},
|
|
1139
|
+
scope,
|
|
1140
|
+
subqueries: context.subqueries,
|
|
1141
|
+
through: context.through,
|
|
1142
|
+
}
|
|
934
1143
|
}
|
|
935
1144
|
|
|
936
1145
|
/**
|
|
@@ -1067,24 +1276,54 @@ async function selectRows<S>(
|
|
|
1067
1276
|
visible: readonly string[] = context.model.visible,
|
|
1068
1277
|
): Promise<S[]> {
|
|
1069
1278
|
const run = storeRunner(context)
|
|
1279
|
+
const now = new Date()
|
|
1280
|
+
const joins: JoinState[] = []
|
|
1070
1281
|
for (let index = 0; index < state.joins.length; index++) {
|
|
1071
1282
|
const join = state.joins[index]
|
|
1072
|
-
if (join
|
|
1283
|
+
if (join === undefined) continue
|
|
1284
|
+
if (!includes(join.join.readActions, action)) {
|
|
1073
1285
|
throw new CapabilityError(
|
|
1074
1286
|
'wrong_action',
|
|
1075
1287
|
`joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
|
|
1076
1288
|
)
|
|
1077
1289
|
}
|
|
1290
|
+
joins[joins.length] = heldJoin(context, join, action, now)
|
|
1078
1291
|
}
|
|
1079
1292
|
if (scope === undefined) {
|
|
1080
1293
|
return []
|
|
1081
1294
|
}
|
|
1082
1295
|
const dialect = dialectOf(context)
|
|
1083
|
-
const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
|
|
1296
|
+
const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
|
|
1084
1297
|
const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
|
|
1085
1298
|
return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
|
|
1086
1299
|
}
|
|
1087
1300
|
|
|
1301
|
+
/**
|
|
1302
|
+
* `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
|
|
1303
|
+
* subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
|
|
1304
|
+
*/
|
|
1305
|
+
function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
|
|
1306
|
+
const child = ownEntry(context.children, join.join.shape.table)
|
|
1307
|
+
if (child === undefined) {
|
|
1308
|
+
throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
|
|
1309
|
+
}
|
|
1310
|
+
const condition = ownEntry(child.when, action)
|
|
1311
|
+
if (condition === undefined) {
|
|
1312
|
+
return join
|
|
1313
|
+
}
|
|
1314
|
+
let reads = false
|
|
1315
|
+
conditionReach(condition, () => {
|
|
1316
|
+
reads = true
|
|
1317
|
+
})
|
|
1318
|
+
if (reads) {
|
|
1319
|
+
throw new CapabilityError(
|
|
1320
|
+
'unenforceable',
|
|
1321
|
+
`joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
|
|
1322
|
+
)
|
|
1323
|
+
}
|
|
1324
|
+
return { ...join, condition: conditionNode(child.name, condition, now) }
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1088
1327
|
/** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
|
|
1089
1328
|
function joinedColumns(context: TableContext, state: SelectState): RowColumns {
|
|
1090
1329
|
const own = rowColumnsOf(context.model)
|
|
@@ -1210,26 +1449,43 @@ export function keyOf(model: TableModel): string {
|
|
|
1210
1449
|
async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
|
|
1211
1450
|
const owner = context.destination
|
|
1212
1451
|
if (owner === undefined) {
|
|
1452
|
+
// No table owns the destination, so a Ref held through relations is checked on the rows that hold it.
|
|
1453
|
+
if (grant.relations.length > 0) await lockRelationRow(transaction, context, grant)
|
|
1213
1454
|
return
|
|
1214
1455
|
}
|
|
1215
|
-
const
|
|
1456
|
+
const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
|
|
1457
|
+
// A Ref held through a relation inserts only while a row of it still names the caller at the destination.
|
|
1458
|
+
const gate = relationGate(context.relations, owner, grant, new Date())
|
|
1459
|
+
const scope = gate === undefined ? chain : allOf([chain, gate])
|
|
1216
1460
|
const node = lockNode(owner.name, keyOf(owner), scope)
|
|
1217
|
-
const rows = await transaction.run(node, {
|
|
1461
|
+
const rows = await transaction.run(node, {
|
|
1462
|
+
root: 'SelectQueryNode',
|
|
1463
|
+
table: owner.name,
|
|
1464
|
+
joins: {},
|
|
1465
|
+
scope,
|
|
1466
|
+
lock: 'share',
|
|
1467
|
+
subqueries: context.subqueries,
|
|
1468
|
+
})
|
|
1218
1469
|
if (rows.length === 0) {
|
|
1219
1470
|
throw new NotFoundError(`${owner.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
|
|
1220
1471
|
}
|
|
1221
1472
|
}
|
|
1222
1473
|
|
|
1474
|
+
/** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
|
|
1223
1475
|
export async function insertRow<O>(
|
|
1224
1476
|
context: TableContext,
|
|
1225
1477
|
run: Runner,
|
|
1226
1478
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1227
|
-
|
|
1479
|
+
prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged'> | undefined,
|
|
1228
1480
|
): Promise<O> {
|
|
1229
1481
|
const values = boundValues(context, given)
|
|
1230
1482
|
return run.write(async (transaction) => {
|
|
1231
|
-
if (destination !== undefined) {
|
|
1232
|
-
await lockDestination(transaction, context, destination)
|
|
1483
|
+
if (prepared?.destination !== undefined) {
|
|
1484
|
+
await lockDestination(transaction, context, prepared.destination)
|
|
1485
|
+
}
|
|
1486
|
+
if (prepared !== undefined) {
|
|
1487
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, given)
|
|
1488
|
+
await checkRevealAssign(transaction, context, prepared.writer, given)
|
|
1233
1489
|
}
|
|
1234
1490
|
const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
|
|
1235
1491
|
if (row === undefined) {
|
|
@@ -1237,6 +1493,7 @@ export async function insertRow<O>(
|
|
|
1237
1493
|
}
|
|
1238
1494
|
checkVersion(context, row)
|
|
1239
1495
|
await referenceInserted(context, run, transaction, values)
|
|
1496
|
+
await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
|
|
1240
1497
|
return row
|
|
1241
1498
|
})
|
|
1242
1499
|
}
|
|
@@ -1250,6 +1507,8 @@ export interface OnConflict {
|
|
|
1250
1507
|
readonly mode: 'nothing' | 'update'
|
|
1251
1508
|
/** The values given for the table's update columns: what `update` sets on the conflicting row. */
|
|
1252
1509
|
readonly updates: ReadonlyMap<string, Primitive | null>
|
|
1510
|
+
/** The capability's action, whose condition the conflicting row must satisfy to be updated. */
|
|
1511
|
+
readonly action: string
|
|
1253
1512
|
}
|
|
1254
1513
|
|
|
1255
1514
|
const CONFLICT_FIELDS = nameSet(['columns', 'do'])
|
|
@@ -1310,7 +1569,7 @@ export function onConflictOf(
|
|
|
1310
1569
|
}
|
|
1311
1570
|
}
|
|
1312
1571
|
}
|
|
1313
|
-
return freeze({ columns: freeze(columns), mode, updates })
|
|
1572
|
+
return freeze({ columns: freeze(columns), mode, updates, action })
|
|
1314
1573
|
}
|
|
1315
1574
|
|
|
1316
1575
|
/** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
|
|
@@ -1365,8 +1624,8 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
|
|
|
1365
1624
|
|
|
1366
1625
|
/**
|
|
1367
1626
|
* `insert … on conflict (columns) do nothing`, and for `update` the conflicting row's update in the same transaction,
|
|
1368
|
-
* within the insert's own containment. A row deleted between the two is
|
|
1369
|
-
* the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
|
|
1627
|
+
* within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
|
|
1628
|
+
* inserted on the second try; a conflicting row the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
|
|
1370
1629
|
* false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
|
|
1371
1630
|
*/
|
|
1372
1631
|
async function insertOnConflict(
|
|
@@ -1388,7 +1647,7 @@ async function insertOnConflict(
|
|
|
1388
1647
|
}
|
|
1389
1648
|
matches[matches.length] = equals(model.name, name, value)
|
|
1390
1649
|
}
|
|
1391
|
-
const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
|
|
1650
|
+
const scope = conflict.mode === 'update' ? conditioned(model, conflict.action, insertedScope(context, values), new Date()) : undefined
|
|
1392
1651
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1393
1652
|
const node = insertNode(model.name, values, answer(context), conflict.columns)
|
|
1394
1653
|
const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
|
|
@@ -1658,8 +1917,17 @@ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]
|
|
|
1658
1917
|
/** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
|
|
1659
1918
|
export interface PreparedInsert {
|
|
1660
1919
|
readonly row: Map<string, Primitive | null>
|
|
1920
|
+
/** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
|
|
1921
|
+
readonly writer: string
|
|
1661
1922
|
readonly destination: RefGrant | undefined
|
|
1662
1923
|
readonly conflict: OnConflict | undefined
|
|
1924
|
+
/** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
|
|
1925
|
+
readonly judged: JudgedInsert | undefined
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
export interface JudgedInsert {
|
|
1929
|
+
readonly action: string
|
|
1930
|
+
readonly condition: ConditionModel
|
|
1663
1931
|
}
|
|
1664
1932
|
|
|
1665
1933
|
/**
|
|
@@ -1675,11 +1943,13 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
|
|
|
1675
1943
|
// The object does not exist yet; this only refuses a chain the table has no column for.
|
|
1676
1944
|
linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
|
|
1677
1945
|
stampInsert(context, grant, row, scope.key, grant.id)
|
|
1678
|
-
|
|
1946
|
+
const judged = checkInserted(context, grant, row)
|
|
1947
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged }
|
|
1679
1948
|
}
|
|
1680
1949
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1681
1950
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1682
|
-
|
|
1951
|
+
const judged = checkInserted(context, grant, row)
|
|
1952
|
+
return { row, writer: grant.principal, destination: grant, conflict, judged }
|
|
1683
1953
|
}
|
|
1684
1954
|
|
|
1685
1955
|
/** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
|
|
@@ -1688,7 +1958,8 @@ export function prepareApplicationInsert(context: TableContext, capability: unkn
|
|
|
1688
1958
|
const row = readValues(values, context.model.insert, 'insert', context.model)
|
|
1689
1959
|
const conflict = onConflictOf(context, options, grant.action, row)
|
|
1690
1960
|
stampInsert(context, grant, row, keyOf(context.model), uuidv7())
|
|
1691
|
-
|
|
1961
|
+
const judged = checkInserted(context, grant, row)
|
|
1962
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged }
|
|
1692
1963
|
}
|
|
1693
1964
|
|
|
1694
1965
|
/** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
|
|
@@ -1699,7 +1970,127 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
|
|
|
1699
1970
|
const conflict = onConflictOf(context, options, grant.action, row)
|
|
1700
1971
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1701
1972
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1702
|
-
|
|
1973
|
+
const judged = checkInserted(context, grant, row)
|
|
1974
|
+
return { row, writer: grant.principal, destination: grant, conflict, judged }
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
const DAY_MS = 86_400_000
|
|
1978
|
+
|
|
1979
|
+
/**
|
|
1980
|
+
* An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
|
|
1981
|
+
* its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
|
|
1982
|
+
* ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
|
|
1983
|
+
* that follows a path is answered for the transaction to judge.
|
|
1984
|
+
*/
|
|
1985
|
+
function checkInserted(
|
|
1986
|
+
context: TableContext,
|
|
1987
|
+
grant: { readonly action: string; readonly principal: string },
|
|
1988
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
1989
|
+
): JudgedInsert | undefined {
|
|
1990
|
+
const model = context.model
|
|
1991
|
+
const now = new Date()
|
|
1992
|
+
const condition = ownEntry(model.when, grant.action)
|
|
1993
|
+
const judged = condition === undefined || readPaths(condition).length === 0 ? undefined : { action: grant.action, condition }
|
|
1994
|
+
if (condition !== undefined && judged === undefined && !rowSatisfies(condition, row, now)) {
|
|
1995
|
+
throw new ConflictError(`the row is outside what ${grant.action} inserts into ${model.name}`)
|
|
1996
|
+
}
|
|
1997
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
1998
|
+
const source = model.confers[index]
|
|
1999
|
+
if (source === undefined) {
|
|
2000
|
+
continue
|
|
2001
|
+
}
|
|
2002
|
+
const assign = source.assign
|
|
2003
|
+
if (assign === undefined) {
|
|
2004
|
+
throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
|
|
2005
|
+
}
|
|
2006
|
+
// A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
|
|
2007
|
+
if (!assign.self && source.principalPath === undefined && row.get(source.principal) === grant.principal) {
|
|
2008
|
+
throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
|
|
2009
|
+
}
|
|
2010
|
+
if (assign.maxDays !== undefined && source.expires !== undefined) {
|
|
2011
|
+
const value = row.get(source.expires)
|
|
2012
|
+
const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
|
|
2013
|
+
if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
|
|
2014
|
+
throw new ConflictError(
|
|
2015
|
+
`a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
|
|
2016
|
+
)
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
return judged
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
/**
|
|
2024
|
+
* An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
|
|
2025
|
+
* held the row's foreign keys, so a path reads only the rows they name in the row's tenant. Every row each read path
|
|
2026
|
+
* reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
|
|
2027
|
+
* before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
|
|
2028
|
+
* so it commits nothing even when the handler catches the refusal.
|
|
2029
|
+
*/
|
|
2030
|
+
async function judgeInserted(
|
|
2031
|
+
transaction: Session,
|
|
2032
|
+
context: TableContext,
|
|
2033
|
+
judged: JudgedInsert | undefined,
|
|
2034
|
+
key: Primitive | null | undefined,
|
|
2035
|
+
): Promise<void> {
|
|
2036
|
+
if (judged === undefined) {
|
|
2037
|
+
return
|
|
2038
|
+
}
|
|
2039
|
+
const model = context.model
|
|
2040
|
+
if (key === undefined || key === null) {
|
|
2041
|
+
throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${judged.action} has no key`)
|
|
2042
|
+
}
|
|
2043
|
+
const paths = readPaths(judged.condition)
|
|
2044
|
+
for (let index = 0; index < paths.length; index++) {
|
|
2045
|
+
const steps = paths[index] ?? []
|
|
2046
|
+
// The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
|
|
2047
|
+
let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
|
|
2048
|
+
const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
|
|
2049
|
+
for (let position = 0; position < steps.length; position++) {
|
|
2050
|
+
const step = steps[position]
|
|
2051
|
+
if (step === undefined) continue
|
|
2052
|
+
const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
|
|
2053
|
+
await transaction.run(lockNode(step.table, step.to, scope), {
|
|
2054
|
+
root: 'SelectQueryNode',
|
|
2055
|
+
table: step.table,
|
|
2056
|
+
joins: {},
|
|
2057
|
+
scope,
|
|
2058
|
+
lock: 'share',
|
|
2059
|
+
subqueries: withColumns(context.subqueries, walked),
|
|
2060
|
+
})
|
|
2061
|
+
const next = steps[position + 1]
|
|
2062
|
+
if (next !== undefined) {
|
|
2063
|
+
reached = subquery(step.table, next.from, scope)
|
|
2064
|
+
walked[step.table] = [...(walked[step.table] ?? []), next.from]
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, judged.condition, new Date())))
|
|
2069
|
+
const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
|
|
2070
|
+
root: 'SelectQueryNode',
|
|
2071
|
+
table: model.name,
|
|
2072
|
+
joins: {},
|
|
2073
|
+
scope,
|
|
2074
|
+
subqueries: context.subqueries,
|
|
2075
|
+
})
|
|
2076
|
+
if (rows.length === 0) {
|
|
2077
|
+
transaction.fail()
|
|
2078
|
+
throw new ConflictError(`the row is outside what ${judged.action} inserts into ${model.name}`)
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
/** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
|
|
2083
|
+
function withColumns(
|
|
2084
|
+
admitted: Readonly<Record<string, readonly string[]>>,
|
|
2085
|
+
more: Readonly<Record<string, readonly string[]>>,
|
|
2086
|
+
): Readonly<Record<string, readonly string[]>> {
|
|
2087
|
+
const merged: Record<string, readonly string[]> = { ...admitted }
|
|
2088
|
+
const tables = ownKeys(more)
|
|
2089
|
+
for (let index = 0; index < tables.length; index++) {
|
|
2090
|
+
const table = tables[index] ?? ''
|
|
2091
|
+
setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
|
|
2092
|
+
}
|
|
2093
|
+
return merged
|
|
1703
2094
|
}
|
|
1704
2095
|
|
|
1705
2096
|
/** Writes each chain column the destination `Ref` settles into an insert's row. */
|
|
@@ -1716,32 +2107,123 @@ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkVal
|
|
|
1716
2107
|
export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
|
|
1717
2108
|
const conflict = prepared.conflict
|
|
1718
2109
|
if (conflict === undefined) {
|
|
1719
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2110
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1720
2111
|
}
|
|
1721
2112
|
return run.write(async (transaction) => {
|
|
1722
2113
|
if (prepared.destination !== undefined) {
|
|
1723
2114
|
await lockDestination(transaction, context, prepared.destination)
|
|
1724
2115
|
}
|
|
1725
|
-
|
|
2116
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
|
|
2117
|
+
await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
|
|
2118
|
+
const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
|
|
2119
|
+
// A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
|
|
2120
|
+
if (written['inserted'] === true) {
|
|
2121
|
+
await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
|
|
2122
|
+
}
|
|
2123
|
+
return written
|
|
1726
2124
|
})
|
|
1727
2125
|
}
|
|
1728
2126
|
|
|
2127
|
+
/**
|
|
2128
|
+
* A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
|
|
2129
|
+
* row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
|
|
2130
|
+
* stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
|
|
2131
|
+
*/
|
|
2132
|
+
async function checkPrincipalAssign(
|
|
2133
|
+
transaction: Session,
|
|
2134
|
+
context: TableContext,
|
|
2135
|
+
writer: string,
|
|
2136
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2137
|
+
): Promise<void> {
|
|
2138
|
+
const model = context.model
|
|
2139
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
2140
|
+
const source = model.confers[index]
|
|
2141
|
+
const path = source?.principalPath
|
|
2142
|
+
const value = source === undefined ? undefined : row.get(source.principal)
|
|
2143
|
+
if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
|
|
2144
|
+
continue
|
|
2145
|
+
}
|
|
2146
|
+
const keyed = equals(path.table, path.key, value)
|
|
2147
|
+
await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
|
|
2148
|
+
const named = allOf([keyed, equals(path.table, path.column, writer)])
|
|
2149
|
+
const rows = await transaction.run(locateNode(path.table, [path.key], named), {
|
|
2150
|
+
root: 'SelectQueryNode',
|
|
2151
|
+
table: path.table,
|
|
2152
|
+
joins: {},
|
|
2153
|
+
scope: named,
|
|
2154
|
+
})
|
|
2155
|
+
if (rows.length > 0) {
|
|
2156
|
+
throw new ConflictError(
|
|
2157
|
+
`a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
|
|
2158
|
+
)
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
/**
|
|
2164
|
+
* An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
|
|
2165
|
+
* insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
|
|
2166
|
+
* the relation is at. One guarded select per such reveal, in the insert's transaction.
|
|
2167
|
+
*/
|
|
2168
|
+
async function checkRevealAssign(
|
|
2169
|
+
transaction: Session,
|
|
2170
|
+
context: TableContext,
|
|
2171
|
+
writer: string,
|
|
2172
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2173
|
+
): Promise<void> {
|
|
2174
|
+
const model = context.model
|
|
2175
|
+
const now = new Date()
|
|
2176
|
+
for (let index = 0; index < model.reveals.length; index++) {
|
|
2177
|
+
const reveal = model.reveals[index]
|
|
2178
|
+
const path = reveal?.path
|
|
2179
|
+
const value = path === undefined ? undefined : row.get(path.column)
|
|
2180
|
+
if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
|
|
2181
|
+
const source = relationSource(context.relations, reveal.relation)
|
|
2182
|
+
const tests: OperationNode[] = []
|
|
2183
|
+
const rest: OperationNode[] = [...activeRow(source, now)]
|
|
2184
|
+
if (source.dimension === path.dimension) {
|
|
2185
|
+
tests[tests.length] = equals(source.table, source.node, value)
|
|
2186
|
+
} else {
|
|
2187
|
+
const link = linkOf(path.chain, source.dimension)
|
|
2188
|
+
if (link === undefined) continue
|
|
2189
|
+
const above = subquery(path.table, link.column, equals(path.table, path.key, value))
|
|
2190
|
+
rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
|
|
2191
|
+
}
|
|
2192
|
+
// The principal test comes last: an equality, or a path's membership after the node's equality.
|
|
2193
|
+
tests[tests.length] = namesPrincipal(source, writer)
|
|
2194
|
+
const address = allOf(tests)
|
|
2195
|
+
const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
|
|
2196
|
+
const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
|
|
2197
|
+
root: 'SelectQueryNode',
|
|
2198
|
+
table: source.table,
|
|
2199
|
+
joins: {},
|
|
2200
|
+
scope,
|
|
2201
|
+
subqueries: context.subqueries,
|
|
2202
|
+
})
|
|
2203
|
+
if (rows.length > 0) {
|
|
2204
|
+
throw new ConflictError(
|
|
2205
|
+
`a row of ${model.name} names in ${path.column} a node where its writer holds ${reveal.relation}, which the reveal's assign.self does not allow`,
|
|
2206
|
+
)
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
|
|
1729
2211
|
/** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
|
|
1730
2212
|
export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
|
|
1731
2213
|
const prepared = prepareDimensionInsert(context, target, values)
|
|
1732
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2214
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1733
2215
|
}
|
|
1734
2216
|
|
|
1735
2217
|
/** An application table's insert, for an `app` capability of its insert action. */
|
|
1736
2218
|
export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
|
|
1737
2219
|
const prepared = prepareApplicationInsert(context, capability, values)
|
|
1738
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2220
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1739
2221
|
}
|
|
1740
2222
|
|
|
1741
2223
|
/** `ChildTable.insert` over a capability nobody type-checked. */
|
|
1742
2224
|
export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
|
|
1743
2225
|
const prepared = prepareChildInsert(context, parent, values)
|
|
1744
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2226
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1745
2227
|
}
|
|
1746
2228
|
|
|
1747
2229
|
type ReadAction<P, T> = ActionOf<P, T, 'read'>
|
|
@@ -1812,6 +2294,12 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1812
2294
|
if (container === undefined) {
|
|
1813
2295
|
throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
|
|
1814
2296
|
}
|
|
2297
|
+
if (delegates(context.model)) {
|
|
2298
|
+
throw new CapabilityError(
|
|
2299
|
+
'table_kind',
|
|
2300
|
+
`${context.model.name} hands out access, so a row is never moved: insert a new one`,
|
|
2301
|
+
)
|
|
2302
|
+
}
|
|
1815
2303
|
const scope = objectPredicate(context, ref, 'delete')
|
|
1816
2304
|
const target = refGrant(context, to, container.dimension, 'insert')
|
|
1817
2305
|
const values = linkValues(context.model.name, context.model.chain, target)
|
|
@@ -2035,8 +2523,7 @@ function appProbeOf(context: TableContext): TableProbe {
|
|
|
2035
2523
|
mode: 'app',
|
|
2036
2524
|
get: async (capability: unknown, key?: string) => {
|
|
2037
2525
|
if (scoped(capability)) {
|
|
2038
|
-
scopedApplicationRead(context, capability)
|
|
2039
|
-
return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
|
|
2526
|
+
return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
|
|
2040
2527
|
}
|
|
2041
2528
|
return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
|
|
2042
2529
|
},
|
|
@@ -2137,6 +2624,7 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
|
|
|
2137
2624
|
export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
2138
2625
|
const models = tableModels(tables)
|
|
2139
2626
|
const connection: Connection = { runtime: undefined }
|
|
2627
|
+
const { relations, members, subqueries } = layerReach(models)
|
|
2140
2628
|
|
|
2141
2629
|
function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
|
|
2142
2630
|
const model = typeof table === 'string' ? modelOf(models, table) : undefined
|
|
@@ -2148,6 +2636,9 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2148
2636
|
|
|
2149
2637
|
function contextOf(model: TableModel): TableContext {
|
|
2150
2638
|
const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
|
|
2639
|
+
const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
|
|
2640
|
+
? freeze({ column: model.scope.column, table: parent.name, key: parent.scope.key, context: contextOf(freeze({ ...parent, when: freeze({}) })) })
|
|
2641
|
+
: undefined
|
|
2151
2642
|
const joinable = joinShapes(models, model)
|
|
2152
2643
|
const joins: Record<string, readonly ForeignKeyPair[]> = {}
|
|
2153
2644
|
const children = ownKeys(joinable)
|
|
@@ -2174,6 +2665,10 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2174
2665
|
joins: freeze(joins),
|
|
2175
2666
|
children: freeze(childModels),
|
|
2176
2667
|
connection,
|
|
2668
|
+
relations,
|
|
2669
|
+
members,
|
|
2670
|
+
subqueries,
|
|
2671
|
+
through,
|
|
2177
2672
|
})
|
|
2178
2673
|
}
|
|
2179
2674
|
|
|
@@ -2203,6 +2698,9 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2203
2698
|
connection.runtime = bound
|
|
2204
2699
|
return freeze({
|
|
2205
2700
|
locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
|
|
2701
|
+
relates: async (relation: string, node: string, principal: string) => relationHolds(relations, subqueries, bound, relation, node, principal),
|
|
2702
|
+
reveals: async (relation: string, dimension: string, node: string, principal: string) =>
|
|
2703
|
+
revealHolds(relations, subqueries, bound, relation, dimension, node, principal),
|
|
2206
2704
|
release() {
|
|
2207
2705
|
if (connection.runtime === bound) {
|
|
2208
2706
|
connection.runtime = undefined
|
|
@@ -2235,6 +2733,87 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2235
2733
|
return database
|
|
2236
2734
|
}
|
|
2237
2735
|
|
|
2736
|
+
/**
|
|
2737
|
+
* Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
|
|
2738
|
+
* node column, a condition path's target by its key), which the guard admits and nothing else.
|
|
2739
|
+
*/
|
|
2740
|
+
function layerReach(
|
|
2741
|
+
models: TableModels,
|
|
2742
|
+
): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
|
|
2743
|
+
const relations: Record<string, LayerRelation> = {}
|
|
2744
|
+
const members: Record<string, MemberRevealModel[]> = {}
|
|
2745
|
+
const selected: Record<string, string[]> = {}
|
|
2746
|
+
const select = (table: string, column: string): void => {
|
|
2747
|
+
const columns = ownEntry(selected, table) ?? []
|
|
2748
|
+
if (!includes(columns, column)) columns[columns.length] = column
|
|
2749
|
+
setOwn(selected, table, columns)
|
|
2750
|
+
}
|
|
2751
|
+
const names = ownKeys(models)
|
|
2752
|
+
const reveals: Record<string, RevealModel[]> = {}
|
|
2753
|
+
for (let index = 0; index < names.length; index++) {
|
|
2754
|
+
const model = modelOf(models, names[index] ?? '')
|
|
2755
|
+
for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
|
|
2756
|
+
const reveal = model.reveals[position]
|
|
2757
|
+
if (reveal === undefined) continue
|
|
2758
|
+
const listed = ownEntry(reveals, reveal.relation) ?? []
|
|
2759
|
+
listed[listed.length] = reveal
|
|
2760
|
+
setOwn(reveals, reveal.relation, listed)
|
|
2761
|
+
select(reveal.table, reveal.column)
|
|
2762
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
2763
|
+
}
|
|
2764
|
+
for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
|
|
2765
|
+
const reveal = model.memberReveals[position]
|
|
2766
|
+
if (reveal === undefined) continue
|
|
2767
|
+
const listed = ownEntry(members, reveal.source) ?? []
|
|
2768
|
+
listed[listed.length] = reveal
|
|
2769
|
+
setOwn(members, reveal.source, listed)
|
|
2770
|
+
select(reveal.table, reveal.column)
|
|
2771
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
for (let index = 0; index < names.length; index++) {
|
|
2775
|
+
const model = modelOf(models, names[index] ?? '')
|
|
2776
|
+
if (model === undefined) continue
|
|
2777
|
+
for (let position = 0; position < model.confers.length; position++) {
|
|
2778
|
+
const source = model.confers[position]
|
|
2779
|
+
if (source === undefined) continue
|
|
2780
|
+
setOwn(relations, source.relation, freeze({ ...source, reveals: freeze(ownEntry(reveals, source.relation) ?? []) }))
|
|
2781
|
+
select(source.table, source.node)
|
|
2782
|
+
if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
|
|
2783
|
+
if (source.when !== undefined) addReach(source.when, select)
|
|
2784
|
+
}
|
|
2785
|
+
for (let position = 0; position < model.readThrough.length; position++) {
|
|
2786
|
+
const path = model.readThrough[position]
|
|
2787
|
+
if (path === undefined) continue
|
|
2788
|
+
select(path.table, path.key)
|
|
2789
|
+
if (path.via !== undefined) select(path.via.table, path.via.key)
|
|
2790
|
+
for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
|
|
2791
|
+
}
|
|
2792
|
+
const actions = ownKeys(model.when)
|
|
2793
|
+
for (let position = 0; position < actions.length; position++) {
|
|
2794
|
+
const condition = ownEntry(model.when, actions[position] ?? '')
|
|
2795
|
+
if (condition !== undefined) addReach(condition, select)
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
const subqueries: Record<string, readonly string[]> = {}
|
|
2799
|
+
const tablesRead = ownKeys(selected)
|
|
2800
|
+
for (let index = 0; index < tablesRead.length; index++) {
|
|
2801
|
+
const table = tablesRead[index] ?? ''
|
|
2802
|
+
setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
|
|
2803
|
+
}
|
|
2804
|
+
const revealing: Record<string, readonly MemberRevealModel[]> = {}
|
|
2805
|
+
const sources = ownKeys(members)
|
|
2806
|
+
for (let index = 0; index < sources.length; index++) {
|
|
2807
|
+
const source = sources[index] ?? ''
|
|
2808
|
+
setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
|
|
2809
|
+
}
|
|
2810
|
+
return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
|
|
2811
|
+
}
|
|
2812
|
+
|
|
2813
|
+
function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
|
|
2814
|
+
conditionReach(condition, select)
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2238
2817
|
/** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
|
|
2239
2818
|
function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
|
|
2240
2819
|
const side = frameworkSideOf(database)
|
|
@@ -2286,6 +2865,112 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
|
|
|
2286
2865
|
return owner
|
|
2287
2866
|
}
|
|
2288
2867
|
|
|
2868
|
+
/** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
|
|
2869
|
+
async function relationHolds(
|
|
2870
|
+
relations: RelationSources,
|
|
2871
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
2872
|
+
runtime: DataLayerRuntime,
|
|
2873
|
+
relation: string,
|
|
2874
|
+
node: string,
|
|
2875
|
+
principal: string,
|
|
2876
|
+
): Promise<boolean> {
|
|
2877
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
2878
|
+
throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
|
|
2879
|
+
}
|
|
2880
|
+
const source = relationSource(relations, relation)
|
|
2881
|
+
const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
|
|
2882
|
+
const active = activeRow(source, new Date())
|
|
2883
|
+
const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
|
|
2884
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
|
|
2885
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
|
|
2886
|
+
return rows.length > 0
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
/**
|
|
2890
|
+
* Locks a row that still holds the Ref's action for its principal at the Ref's object or a container on its chain: a
|
|
2891
|
+
* source row naming it there, or a row the relation reaches that reveals that node. None is 404, and nothing is written.
|
|
2892
|
+
*/
|
|
2893
|
+
async function lockRelationRow(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
|
|
2894
|
+
const now = new Date()
|
|
2895
|
+
const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
|
|
2896
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
2897
|
+
const source = relationSource(context.relations, grant.relations[index] ?? '')
|
|
2898
|
+
const candidates: { table: string; column: string; scope: OperationNode }[] = []
|
|
2899
|
+
const node = nodeOf(source.dimension)
|
|
2900
|
+
if (node !== undefined) {
|
|
2901
|
+
const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, grant.principal)])
|
|
2902
|
+
const active = activeRow(source, now)
|
|
2903
|
+
candidates[candidates.length] = {
|
|
2904
|
+
table: source.table,
|
|
2905
|
+
column: source.node,
|
|
2906
|
+
scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
for (let position = 0; position < source.reveals.length; position++) {
|
|
2910
|
+
const reveal = source.reveals[position]
|
|
2911
|
+
const held = reveal !== undefined && reveal.path === undefined && includes(reveal.actions, grant.action)
|
|
2912
|
+
const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
|
|
2913
|
+
if (reveal !== undefined && revealed !== undefined) {
|
|
2914
|
+
candidates[candidates.length] = {
|
|
2915
|
+
table: reveal.table,
|
|
2916
|
+
column: reveal.column,
|
|
2917
|
+
scope: revealAddress(source, reveal, revealed, grant.principal, now),
|
|
2918
|
+
}
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
for (let position = 0; position < candidates.length; position++) {
|
|
2922
|
+
const candidate = candidates[position]
|
|
2923
|
+
if (candidate === undefined) continue
|
|
2924
|
+
const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
|
|
2925
|
+
root: 'SelectQueryNode',
|
|
2926
|
+
table: candidate.table,
|
|
2927
|
+
joins: {},
|
|
2928
|
+
scope: candidate.scope,
|
|
2929
|
+
lock: 'share',
|
|
2930
|
+
subqueries: context.subqueries,
|
|
2931
|
+
})
|
|
2932
|
+
if (rows.length > 0) return
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
throw new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
/** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
|
|
2939
|
+
function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
|
|
2940
|
+
const revealed = BinaryOperationNode.create(
|
|
2941
|
+
column(reveal.table, reveal.column),
|
|
2942
|
+
OperatorNode.create('in'),
|
|
2943
|
+
revealedNodes(source, reveal, principal, now),
|
|
2944
|
+
)
|
|
2945
|
+
return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
/** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
|
|
2949
|
+
async function revealHolds(
|
|
2950
|
+
relations: RelationSources,
|
|
2951
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
2952
|
+
runtime: DataLayerRuntime,
|
|
2953
|
+
relation: string,
|
|
2954
|
+
dimension: string,
|
|
2955
|
+
node: string,
|
|
2956
|
+
principal: string,
|
|
2957
|
+
): Promise<boolean> {
|
|
2958
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
2959
|
+
throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
|
|
2960
|
+
}
|
|
2961
|
+
const source = relationSource(relations, relation)
|
|
2962
|
+
for (let index = 0; index < source.reveals.length; index++) {
|
|
2963
|
+
const reveal = source.reveals[index]
|
|
2964
|
+
// A reveal matched through a secondary path holds reads under a Within only; no Ref is minted through it.
|
|
2965
|
+
if (reveal === undefined || reveal.path !== undefined || reveal.dimension !== dimension) continue
|
|
2966
|
+
const address = revealAddress(source, reveal, node, principal, new Date())
|
|
2967
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
|
|
2968
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
|
|
2969
|
+
if (rows.length > 0) return true
|
|
2970
|
+
}
|
|
2971
|
+
return false
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2289
2974
|
/** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
|
|
2290
2975
|
async function locateObject(
|
|
2291
2976
|
models: TableModels,
|