@fabrika/db 0.9.0-dev.12 → 0.9.0-dev.14
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 +539 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +43 -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 +365 -15
- package/src/index.ts +1 -0
- package/src/job-leases.ts +3 -2
- package/src/nodes.ts +21 -6
- package/src/orm-types.ts +13 -2
- package/src/orm.ts +85 -37
- package/src/policy.ts +1596 -39
- package/src/registry.ts +40 -0
- package/src/sql.ts +23 -5
- package/src/sqlite.ts +46 -1
- package/src/store.ts +1529 -69
- package/src/tables.ts +143 -2
- package/src/vocabulary-tables.ts +35 -1
- package/types/src/authority.d.ts +141 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +42 -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 +24 -0
- package/types/src/index.d.ts +1 -1
- package/types/src/job-leases.d.ts +2 -1
- package/types/src/nodes.d.ts +4 -0
- package/types/src/orm-types.d.ts +17 -2
- package/types/src/policy.d.ts +264 -0
- package/types/src/registry.d.ts +26 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/store.d.ts +74 -11
- package/types/src/tables.d.ts +6 -0
- package/types/src/vocabulary-tables.d.ts +60 -2
package/src/store.ts
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
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
|
+
accessReach,
|
|
6
|
+
type AccessRelation,
|
|
7
|
+
activeRow,
|
|
8
|
+
conditioned,
|
|
9
|
+
everyPath,
|
|
10
|
+
gateTerms,
|
|
11
|
+
heldThrough,
|
|
12
|
+
holdsBesides,
|
|
13
|
+
isIn,
|
|
14
|
+
knownRelation,
|
|
15
|
+
type LayerRelation,
|
|
16
|
+
type MemberReveals,
|
|
17
|
+
memberTerms,
|
|
18
|
+
namesPrincipal,
|
|
19
|
+
noPath,
|
|
20
|
+
type PathRule,
|
|
21
|
+
pathTerms,
|
|
22
|
+
refScope,
|
|
23
|
+
relationCondition,
|
|
24
|
+
relationGate,
|
|
25
|
+
relationSource,
|
|
26
|
+
type RelationSources,
|
|
27
|
+
relationTerms,
|
|
28
|
+
revealedNodes,
|
|
29
|
+
type SplitReach,
|
|
30
|
+
throughPath,
|
|
31
|
+
viewScope,
|
|
32
|
+
} from './authority'
|
|
4
33
|
import {
|
|
5
34
|
defineValue,
|
|
6
35
|
freeze,
|
|
@@ -25,13 +54,17 @@ import {
|
|
|
25
54
|
type AppGrant,
|
|
26
55
|
type CapabilityAuthority,
|
|
27
56
|
type CapabilityGrant,
|
|
57
|
+
type ContainerGrant,
|
|
28
58
|
describeGrant,
|
|
29
59
|
MAX_WITHIN_VALUES,
|
|
30
60
|
type Ref,
|
|
31
61
|
type RefGrant,
|
|
62
|
+
type RelationHold,
|
|
32
63
|
type Within,
|
|
33
64
|
type WithinGrant,
|
|
34
65
|
} from './capability'
|
|
66
|
+
import { conditionNode, subquery } from './condition-nodes'
|
|
67
|
+
import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
|
|
35
68
|
import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
|
|
36
69
|
import {
|
|
37
70
|
type ComparableColumn,
|
|
@@ -42,6 +75,7 @@ import {
|
|
|
42
75
|
finishSelect,
|
|
43
76
|
isPrimitive,
|
|
44
77
|
type JoinShape,
|
|
78
|
+
type JoinState,
|
|
45
79
|
type NoColumns,
|
|
46
80
|
type Primitive,
|
|
47
81
|
type ScopedSelect,
|
|
@@ -53,7 +87,7 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
|
|
|
53
87
|
import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
|
|
54
88
|
import { fileReference } from './file-references'
|
|
55
89
|
import { webhookTables } from './framework-tables'
|
|
56
|
-
import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
|
|
90
|
+
import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
|
|
57
91
|
import { fencedTransaction, jobLeases } from './job-leases'
|
|
58
92
|
import { jobWakes, leaseProjection } from './job-wakes'
|
|
59
93
|
import { jsonInput } from './json'
|
|
@@ -77,6 +111,8 @@ import {
|
|
|
77
111
|
scopedWhere,
|
|
78
112
|
selectNode,
|
|
79
113
|
updateNode,
|
|
114
|
+
valueList,
|
|
115
|
+
valuesNode,
|
|
80
116
|
} from './nodes'
|
|
81
117
|
import { dataAccess } from './orm'
|
|
82
118
|
import {
|
|
@@ -85,18 +121,25 @@ import {
|
|
|
85
121
|
type ChildTableName,
|
|
86
122
|
type Container,
|
|
87
123
|
type ContainerOf,
|
|
124
|
+
delegates,
|
|
88
125
|
type DimensionOf,
|
|
89
126
|
type DimensionTableName,
|
|
90
127
|
includes,
|
|
91
128
|
type InsertValues,
|
|
92
129
|
type JoinableChildren,
|
|
93
130
|
type ListDimensionOf,
|
|
131
|
+
type MemberRevealModel,
|
|
94
132
|
modelOf,
|
|
95
133
|
type MoveAcknowledgement,
|
|
96
134
|
namesAction,
|
|
135
|
+
nodeColumnOf,
|
|
97
136
|
type Operation,
|
|
98
137
|
type ParentOf,
|
|
138
|
+
type PathWriter,
|
|
139
|
+
pathWriters,
|
|
99
140
|
type PolicyRow,
|
|
141
|
+
type RevealModel,
|
|
142
|
+
type SecondaryPath,
|
|
100
143
|
type TableModel,
|
|
101
144
|
type TableModels,
|
|
102
145
|
tableModels,
|
|
@@ -139,6 +182,36 @@ export interface TableContext {
|
|
|
139
182
|
/** The model of each child a select may join, by its table name. */
|
|
140
183
|
readonly children: Readonly<Record<string, TableModel>>
|
|
141
184
|
readonly connection: Connection
|
|
185
|
+
/** Every relation of the layer with its source table: what a relation term of any table reads. */
|
|
186
|
+
readonly relations: RelationSources
|
|
187
|
+
/** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
|
|
188
|
+
readonly members: MemberReveals
|
|
189
|
+
/** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
|
|
190
|
+
readonly subqueries: Readonly<Record<string, readonly string[]>>
|
|
191
|
+
/** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
|
|
192
|
+
readonly through: ViewParent | undefined
|
|
193
|
+
/** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
|
|
194
|
+
readonly writers: readonly PathBound[]
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A path column an insert writes under its bound, and the table that owns the dimension it names. */
|
|
198
|
+
export interface PathBound extends PathWriter {
|
|
199
|
+
readonly owner: TableModel
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
|
|
203
|
+
export interface ViewParent extends ViewParentLink {
|
|
204
|
+
readonly context: TableContext
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A child view's access views, as the guard admits them on its statements: its key in each view's row column. */
|
|
208
|
+
function viewAccessLinks(model: TableModel, key: string): readonly ViewAccessLink[] {
|
|
209
|
+
const links: ViewAccessLink[] = []
|
|
210
|
+
for (let index = 0; index < model.access.length; index++) {
|
|
211
|
+
const access = model.access[index]
|
|
212
|
+
if (access !== undefined) links[links.length] = freeze({ key, view: access.view, row: access.row })
|
|
213
|
+
}
|
|
214
|
+
return freeze(links)
|
|
142
215
|
}
|
|
143
216
|
|
|
144
217
|
/** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
|
|
@@ -299,13 +372,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
|
|
|
299
372
|
return grant
|
|
300
373
|
}
|
|
301
374
|
|
|
302
|
-
/**
|
|
375
|
+
/**
|
|
376
|
+
* The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
|
|
377
|
+
* table's own dimension counts, so its containers lie above a `Within` of it.
|
|
378
|
+
*/
|
|
303
379
|
function linksAbove(model: TableModel, dimension: string): readonly Container[] {
|
|
304
|
-
|
|
305
|
-
|
|
380
|
+
const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
|
|
381
|
+
for (let index = 0; index < links.length; index++) {
|
|
382
|
+
if (links[index]?.dimension === dimension) {
|
|
306
383
|
const above: Container[] = []
|
|
307
|
-
for (let position = index + 1; position <
|
|
308
|
-
const link =
|
|
384
|
+
for (let position = index + 1; position < links.length; position++) {
|
|
385
|
+
const link = links[position]
|
|
309
386
|
if (link !== undefined) {
|
|
310
387
|
above[above.length] = link
|
|
311
388
|
}
|
|
@@ -383,6 +460,9 @@ function withinCount(grant: WithinGrant): number {
|
|
|
383
460
|
for (let index = 0; index < grant.contained.length; index++) {
|
|
384
461
|
count += grant.contained[index]?.values.length ?? 0
|
|
385
462
|
}
|
|
463
|
+
for (let index = 0; index < grant.revealing.length; index++) {
|
|
464
|
+
count += grant.revealing[index]?.values.length ?? 0
|
|
465
|
+
}
|
|
386
466
|
return count
|
|
387
467
|
}
|
|
388
468
|
|
|
@@ -391,9 +471,11 @@ function withinCount(grant: WithinGrant): number {
|
|
|
391
471
|
* the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
|
|
392
472
|
* answers `[]` without a query.
|
|
393
473
|
*/
|
|
394
|
-
function withinPredicate(
|
|
474
|
+
function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
|
|
475
|
+
const model = context.model
|
|
476
|
+
const now = new Date()
|
|
395
477
|
if (grant.values === 'all') {
|
|
396
|
-
return
|
|
478
|
+
return conditioned(model, grant.action, 'all', now)
|
|
397
479
|
}
|
|
398
480
|
const above = linksAbove(model, grant.dimension)
|
|
399
481
|
const predicates: OperationNode[] = []
|
|
@@ -427,7 +509,80 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
|
|
|
427
509
|
if (count > MAX_WITHIN_VALUES) {
|
|
428
510
|
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
|
|
429
511
|
}
|
|
430
|
-
|
|
512
|
+
addRelationTerms(context, grant, operation === 'read', predicates, now)
|
|
513
|
+
if (operation === 'read') addMemberTerms(context, grant, predicates, now)
|
|
514
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
|
|
518
|
+
function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
|
|
519
|
+
const terms = memberTerms(context.members, context.model, grant, now)
|
|
520
|
+
for (let index = 0; index < terms.length; index++) {
|
|
521
|
+
const term = terms[index]
|
|
522
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
|
|
527
|
+
function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
|
|
528
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
529
|
+
const hold = grant.relations[index]
|
|
530
|
+
if (hold === undefined) continue
|
|
531
|
+
const terms = relationTerms(
|
|
532
|
+
context.relations,
|
|
533
|
+
context.model,
|
|
534
|
+
hold,
|
|
535
|
+
grant.principal,
|
|
536
|
+
grant.action,
|
|
537
|
+
now,
|
|
538
|
+
reads ? everyPath : noPath,
|
|
539
|
+
)
|
|
540
|
+
for (let position = 0; position < terms.length; position++) {
|
|
541
|
+
const term = terms[position]
|
|
542
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
|
|
549
|
+
* `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
|
|
550
|
+
* (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
|
|
551
|
+
* Within's lies at no node the column holds, so it reaches no row here.
|
|
552
|
+
*/
|
|
553
|
+
function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
|
|
554
|
+
const model = context.model
|
|
555
|
+
const now = new Date()
|
|
556
|
+
if (grant.values === 'all') {
|
|
557
|
+
return conditioned(model, grant.action, 'all', now)
|
|
558
|
+
}
|
|
559
|
+
if (withinCount(grant) > MAX_WITHIN_VALUES) {
|
|
560
|
+
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
|
|
561
|
+
}
|
|
562
|
+
const predicates: OperationNode[] = []
|
|
563
|
+
for (let index = 0; index < paths.length; index++) {
|
|
564
|
+
const path = paths[index]
|
|
565
|
+
if (path === undefined) continue
|
|
566
|
+
if (grant.values.length > 0) {
|
|
567
|
+
const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
|
|
568
|
+
if (own !== undefined) predicates[predicates.length] = own
|
|
569
|
+
}
|
|
570
|
+
for (let position = 0; position < grant.containers.length; position++) {
|
|
571
|
+
const container = grant.containers[position]
|
|
572
|
+
if (container === undefined || container.values.length === 0) continue
|
|
573
|
+
const above = throughPath(model.name, path, container.dimension, valueList(container.values))
|
|
574
|
+
if (above === undefined) {
|
|
575
|
+
throw new CapabilityError(
|
|
576
|
+
'unenforceable',
|
|
577
|
+
`the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
|
|
578
|
+
)
|
|
579
|
+
}
|
|
580
|
+
predicates[predicates.length] = above
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
addRelationTerms(context, grant, true, predicates, now)
|
|
584
|
+
addMemberTerms(context, grant, predicates, now)
|
|
585
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
431
586
|
}
|
|
432
587
|
|
|
433
588
|
/** The object a Ref of the model's own dimension names, with every link of its chain. */
|
|
@@ -443,23 +598,126 @@ export function selfLinks(model: TableModel): readonly Container[] {
|
|
|
443
598
|
return links
|
|
444
599
|
}
|
|
445
600
|
|
|
446
|
-
/** This object, over the whole chain the Ref carries. */
|
|
447
|
-
export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
|
|
601
|
+
/** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
|
|
602
|
+
export function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode {
|
|
448
603
|
const scope = dimensionScope(context.model)
|
|
449
604
|
const grant = refGrant(context, capability, scope.dimension, operation)
|
|
450
|
-
return
|
|
605
|
+
return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
|
|
451
606
|
}
|
|
452
607
|
|
|
453
608
|
/** Rows of a dimension table within the scope values of its list dimension. */
|
|
454
609
|
export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
455
610
|
const scope = dimensionScope(context.model)
|
|
456
611
|
const grant = withinGrant(context, capability, listDimension(scope), operation)
|
|
457
|
-
return withinPredicate(context
|
|
612
|
+
return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
|
|
617
|
+
* of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
|
|
618
|
+
*/
|
|
619
|
+
export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
|
|
620
|
+
const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
|
|
621
|
+
const through = context.through
|
|
622
|
+
if (through !== undefined) {
|
|
623
|
+
const parent = through.context
|
|
624
|
+
const now = new Date()
|
|
625
|
+
const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
|
|
626
|
+
const reached = narrowed.length === 0
|
|
627
|
+
? refScope(parent, parent.model, selfLinks(parent.model), grant, now)
|
|
628
|
+
: splitRefReach(context.model, parent, grant, narrowed, now)
|
|
629
|
+
return viewScope(context.model, through, grant.action, reached, now, row)
|
|
630
|
+
}
|
|
631
|
+
return refScope(context, context.model, context.model.chain, grant, new Date(), row)
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Of `holds`, the relations a child view's `relationWhen` narrows for `action`: each reads the parent through a part of its own. */
|
|
635
|
+
function viewNarrowed(view: TableModel, holds: readonly RelationHold[], action: string): readonly string[] {
|
|
636
|
+
const narrowed: string[] = []
|
|
637
|
+
for (let index = 0; index < holds.length; index++) {
|
|
638
|
+
const relation = holds[index]?.relation ?? ''
|
|
639
|
+
if (relationCondition(view, relation, action) !== undefined && !includes(narrowed, relation)) narrowed[narrowed.length] = relation
|
|
640
|
+
}
|
|
641
|
+
return narrowed
|
|
458
642
|
}
|
|
459
643
|
|
|
460
|
-
/**
|
|
461
|
-
|
|
462
|
-
|
|
644
|
+
/**
|
|
645
|
+
* A Ref's reach of a view's parent, split by the relations the view narrows: the chain with the terms of its other
|
|
646
|
+
* relations, member reveals and paths, and the chain with each narrowed relation's own terms. A part that reaches no
|
|
647
|
+
* parent row adds nothing; none left is unenforceable, never unconditioned.
|
|
648
|
+
*/
|
|
649
|
+
function splitRefReach(view: TableModel, parent: TableContext, grant: RefGrant, narrowed: readonly string[], now: Date): SplitReach {
|
|
650
|
+
const model = parent.model
|
|
651
|
+
const chain = linksPredicate(model.name, linkValues(model.name, selfLinks(model), grant))
|
|
652
|
+
const paths = heldThrough(grant.action)
|
|
653
|
+
const others = holdsBesides(grant.relations, narrowed)
|
|
654
|
+
const rest: RefGrant = { ...grant, relations: others }
|
|
655
|
+
const restTerms = others.length === 0 && rest.revealing.length === 0 && rest.paths.length === 0 ? [] : gateTerms(parent, model, rest, now, paths)
|
|
656
|
+
const relations: { reached: OperationNode; condition: ConditionModel }[] = []
|
|
657
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
658
|
+
const hold = grant.relations[index]
|
|
659
|
+
const condition = hold === undefined || !includes(narrowed, hold.relation) ? undefined : relationCondition(view, hold.relation, grant.action)
|
|
660
|
+
const terms = hold === undefined || condition === undefined
|
|
661
|
+
? []
|
|
662
|
+
: relationTerms(parent.relations, model, hold, grant.principal, grant.action, now, paths)
|
|
663
|
+
if (condition !== undefined && terms.length > 0) relations[relations.length] = { reached: allOf([chain, anyOf(terms)]), condition }
|
|
664
|
+
}
|
|
665
|
+
if (restTerms.length === 0 && relations.length === 0) {
|
|
666
|
+
throw new CapabilityError(
|
|
667
|
+
'unenforceable',
|
|
668
|
+
`the Ref of ${grant.dimension} is held through relations, member reveals or secondary paths, none of which reaches a row of ${model.name} for ${grant.action}`,
|
|
669
|
+
)
|
|
670
|
+
}
|
|
671
|
+
return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
|
|
676
|
+
* those whose parent row exists. A relation the view narrows (`relationWhen`) reaches the parent through a part of its
|
|
677
|
+
* own, ANDed with the view's condition. The view's own access views list rows beside them. Undefined where nothing is
|
|
678
|
+
* reached: the empty `Within`.
|
|
679
|
+
*/
|
|
680
|
+
function throughParent(
|
|
681
|
+
context: TableContext,
|
|
682
|
+
through: ViewParent,
|
|
683
|
+
grant: WithinGrant,
|
|
684
|
+
reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
|
|
685
|
+
): OperationNode | undefined {
|
|
686
|
+
const now = new Date()
|
|
687
|
+
if (grant.values === 'all') {
|
|
688
|
+
return viewScope(context.model, through, grant.action, 'all', now)
|
|
689
|
+
}
|
|
690
|
+
const own: OperationNode[] = []
|
|
691
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
692
|
+
const hold = grant.relations[index]
|
|
693
|
+
const terms = hold === undefined ? [] : accessReach(context.model, hold, grant.principal, grant.action, now)
|
|
694
|
+
for (let position = 0; position < terms.length; position++) {
|
|
695
|
+
const term = terms[position]
|
|
696
|
+
if (term !== undefined) own[own.length] = term
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
|
|
700
|
+
if (narrowed.length === 0) {
|
|
701
|
+
const reached = reach(through.context, grant)
|
|
702
|
+
return reached === undefined && own.length === 0 ? undefined : viewScope(context.model, through, grant.action, reached, now, undefined, own)
|
|
703
|
+
}
|
|
704
|
+
const rest = reach(through.context, { ...grant, relations: holdsBesides(grant.relations, narrowed) })
|
|
705
|
+
const relations: { reached: OperationNode; condition: ConditionModel }[] = []
|
|
706
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
707
|
+
const hold = grant.relations[index]
|
|
708
|
+
const condition = hold === undefined || !includes(narrowed, hold.relation)
|
|
709
|
+
? undefined
|
|
710
|
+
: relationCondition(context.model, hold.relation, grant.action)
|
|
711
|
+
const alone: WithinGrant | undefined = hold === undefined
|
|
712
|
+
? undefined
|
|
713
|
+
: { ...grant, values: [], containers: [], contained: [], revealing: [], relations: [hold] }
|
|
714
|
+
const reached = condition === undefined || alone === undefined ? undefined : reach(through.context, alone)
|
|
715
|
+
if (condition !== undefined && reached !== undefined) relations[relations.length] = { reached, condition }
|
|
716
|
+
}
|
|
717
|
+
if (rest === undefined && relations.length === 0 && own.length === 0) {
|
|
718
|
+
return undefined
|
|
719
|
+
}
|
|
720
|
+
return viewScope(context.model, through, grant.action, { rest, relations }, now, undefined, own)
|
|
463
721
|
}
|
|
464
722
|
|
|
465
723
|
export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
@@ -473,7 +731,11 @@ export function childListPredicate(context: TableContext, capability: unknown, o
|
|
|
473
731
|
throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
|
|
474
732
|
}
|
|
475
733
|
checkGrant(context, grant, listDimension(scope.parent), operation)
|
|
476
|
-
|
|
734
|
+
if (context.through !== undefined) {
|
|
735
|
+
const column = scope.parent.container?.column ?? scope.parent.key
|
|
736
|
+
return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
|
|
737
|
+
}
|
|
738
|
+
return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
|
|
477
739
|
}
|
|
478
740
|
|
|
479
741
|
/**
|
|
@@ -493,9 +755,39 @@ export function reachColumn(model: TableModel, dimension: string): string | unde
|
|
|
493
755
|
return undefined
|
|
494
756
|
}
|
|
495
757
|
|
|
758
|
+
/**
|
|
759
|
+
* Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
|
|
760
|
+
* view through its parent's, its parent's own dimension included.
|
|
761
|
+
*/
|
|
762
|
+
export function reachedBy(context: TableContext, dimension: string): boolean {
|
|
763
|
+
const model = context.through?.context.model ?? context.model
|
|
764
|
+
return parentColumn(model, context.through !== undefined, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** The column that places a row of `model` in `dimension`, a view's parent's own key among them (`own`). */
|
|
768
|
+
function parentColumn(model: TableModel, own: boolean, dimension: string): string | undefined {
|
|
769
|
+
if (own && model.scope.mode === 'dimension' && model.scope.dimension === dimension) {
|
|
770
|
+
return model.scope.key
|
|
771
|
+
}
|
|
772
|
+
return reachColumn(model, dimension)
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
|
|
776
|
+
export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
|
|
777
|
+
const paths: SecondaryPath[] = []
|
|
778
|
+
for (let index = 0; index < model.readThrough.length; index++) {
|
|
779
|
+
const path = model.readThrough[index]
|
|
780
|
+
if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
|
|
781
|
+
paths[paths.length] = path
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return paths
|
|
785
|
+
}
|
|
786
|
+
|
|
496
787
|
/**
|
|
497
788
|
* 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
|
|
789
|
+
* `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
|
|
790
|
+
* table reaches through a secondary path, through that path's column.
|
|
499
791
|
*/
|
|
500
792
|
export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
|
|
501
793
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
@@ -504,14 +796,25 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
|
|
|
504
796
|
throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
|
|
505
797
|
}
|
|
506
798
|
checkAction(context, 'read', grant.action)
|
|
507
|
-
|
|
508
|
-
if (column === undefined) {
|
|
799
|
+
if (!reachedBy(context, grant.dimension)) {
|
|
509
800
|
throw new CapabilityError(
|
|
510
801
|
'out_of_reach',
|
|
511
|
-
`a Within of ${grant.dimension} does not reach ${table}: its containment chain
|
|
802
|
+
`a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
|
|
512
803
|
)
|
|
513
804
|
}
|
|
514
|
-
|
|
805
|
+
if (context.through !== undefined) {
|
|
806
|
+
return throughParent(context, context.through, grant, (parent, part) => withinReach(parent, part, true))
|
|
807
|
+
}
|
|
808
|
+
return withinReach(context, grant, false)
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
|
|
812
|
+
function withinReach(context: TableContext, grant: WithinGrant, own: boolean): OperationNode | undefined {
|
|
813
|
+
const column = parentColumn(context.model, own, grant.dimension)
|
|
814
|
+
if (column !== undefined) {
|
|
815
|
+
return withinPredicate(context, column, grant, 'read')
|
|
816
|
+
}
|
|
817
|
+
return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
|
|
515
818
|
}
|
|
516
819
|
|
|
517
820
|
/**
|
|
@@ -568,6 +871,22 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
|
|
|
568
871
|
if (use !== 'read') {
|
|
569
872
|
checkWriteTarget(context, grant, use)
|
|
570
873
|
}
|
|
874
|
+
// The fragment renders column tests only; a relation's, a member reveal's or a path's subquery, or an action's condition, would be left out.
|
|
875
|
+
const held = grant.kind !== 'app'
|
|
876
|
+
&& (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
|
|
877
|
+
if (held || hasOwn(model.when, grant.action)) {
|
|
878
|
+
throw new CapabilityError(
|
|
879
|
+
'unenforceable',
|
|
880
|
+
`ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${grant.action} on ${model.name}: read it through ctx.db`,
|
|
881
|
+
)
|
|
882
|
+
}
|
|
883
|
+
// Nor the subquery through the parent row, which alone places a child view's rows.
|
|
884
|
+
if (grant.kind !== 'app' && context.through !== undefined) {
|
|
885
|
+
throw new CapabilityError(
|
|
886
|
+
'unenforceable',
|
|
887
|
+
`ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
|
|
888
|
+
)
|
|
889
|
+
}
|
|
571
890
|
if (grant.kind === 'app') {
|
|
572
891
|
if (use === 'read') {
|
|
573
892
|
// The action is held as a global grant, so its scope is every row of a table it reaches.
|
|
@@ -762,7 +1081,7 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
|
|
|
762
1081
|
throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
|
|
763
1082
|
}
|
|
764
1083
|
checkRecordReach(context, grant, reach)
|
|
765
|
-
return
|
|
1084
|
+
return conditioned(model, grant.action, 'all', new Date())
|
|
766
1085
|
}
|
|
767
1086
|
|
|
768
1087
|
/** An `app` capability addresses a row by its key, and writes, only in an application table. */
|
|
@@ -795,15 +1114,15 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
|
|
|
795
1114
|
|
|
796
1115
|
/** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
|
|
797
1116
|
export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
|
|
798
|
-
appGrant(context, capability, 'read')
|
|
799
|
-
return
|
|
1117
|
+
const grant = appGrant(context, capability, 'read')
|
|
1118
|
+
return conditioned(context.model, grant.action, 'all', new Date())
|
|
800
1119
|
}
|
|
801
1120
|
|
|
802
1121
|
/**
|
|
803
1122
|
* 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
1123
|
* or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
|
|
805
1124
|
*/
|
|
806
|
-
export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
|
|
1125
|
+
export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
|
|
807
1126
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
808
1127
|
const model = context.model
|
|
809
1128
|
if (model.scope.mode !== 'app') {
|
|
@@ -819,14 +1138,14 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
|
|
|
819
1138
|
`a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
|
|
820
1139
|
)
|
|
821
1140
|
}
|
|
822
|
-
return
|
|
1141
|
+
return conditioned(model, grant.action, branch, new Date())
|
|
823
1142
|
}
|
|
824
1143
|
|
|
825
1144
|
/** One row of an application table by its key, for an `app` capability of `operation`'s action. */
|
|
826
1145
|
export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
|
|
827
1146
|
checkApplicationTable(context, operation)
|
|
828
|
-
appGrant(context, capability, operation)
|
|
829
|
-
return appKeyPredicate(context.model, key)
|
|
1147
|
+
const grant = appGrant(context, capability, operation)
|
|
1148
|
+
return conditioned(context.model, grant.action, appKeyPredicate(context.model, key), new Date())
|
|
830
1149
|
}
|
|
831
1150
|
|
|
832
1151
|
/**
|
|
@@ -843,7 +1162,8 @@ export function claimScope(
|
|
|
843
1162
|
throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
|
|
844
1163
|
}
|
|
845
1164
|
if (grant.kind === 'app') {
|
|
846
|
-
|
|
1165
|
+
const held = appGrant(context, capability, 'update')
|
|
1166
|
+
return { grant: held, scope: conditioned(model, held.action, 'all', new Date()) }
|
|
847
1167
|
}
|
|
848
1168
|
if (grant.kind !== 'within') {
|
|
849
1169
|
throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
|
|
@@ -859,7 +1179,7 @@ export function claimScope(
|
|
|
859
1179
|
`a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
|
|
860
1180
|
)
|
|
861
1181
|
}
|
|
862
|
-
return { grant, scope: withinPredicate(
|
|
1182
|
+
return { grant, scope: withinPredicate(context, column, grant, 'update') }
|
|
863
1183
|
}
|
|
864
1184
|
|
|
865
1185
|
/**
|
|
@@ -882,7 +1202,12 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
|
|
|
882
1202
|
}
|
|
883
1203
|
terms[terms.length] = equals(model.name, link.column, value)
|
|
884
1204
|
}
|
|
885
|
-
return allOf(terms)
|
|
1205
|
+
return conditioned(model, grant.action, allOf(terms), new Date())
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/** The row of an application table `key` names, as `action` reaches it: within the action's condition. */
|
|
1209
|
+
export function appKeyScope(model: TableModel, action: string, key: unknown): OperationNode {
|
|
1210
|
+
return conditioned(model, action, appKeyPredicate(model, key), new Date())
|
|
886
1211
|
}
|
|
887
1212
|
|
|
888
1213
|
/** The row of an application table `key` names. */
|
|
@@ -922,7 +1247,7 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
|
|
|
922
1247
|
throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
|
|
923
1248
|
}
|
|
924
1249
|
const grant = refGrant(context, parent, scope.parent.dimension, operation)
|
|
925
|
-
return
|
|
1250
|
+
return parentPredicate(context, grant, key)
|
|
926
1251
|
}
|
|
927
1252
|
|
|
928
1253
|
export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
|
|
@@ -930,7 +1255,14 @@ export function guard(context: TableContext, root: RootKind, scope: OperationNod
|
|
|
930
1255
|
if (context.model.view && root !== 'SelectQueryNode') {
|
|
931
1256
|
throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
|
|
932
1257
|
}
|
|
933
|
-
return {
|
|
1258
|
+
return {
|
|
1259
|
+
root,
|
|
1260
|
+
table: context.model.name,
|
|
1261
|
+
joins: root === 'SelectQueryNode' ? context.joins : {},
|
|
1262
|
+
scope,
|
|
1263
|
+
subqueries: context.subqueries,
|
|
1264
|
+
through: context.through,
|
|
1265
|
+
}
|
|
934
1266
|
}
|
|
935
1267
|
|
|
936
1268
|
/**
|
|
@@ -1067,24 +1399,54 @@ async function selectRows<S>(
|
|
|
1067
1399
|
visible: readonly string[] = context.model.visible,
|
|
1068
1400
|
): Promise<S[]> {
|
|
1069
1401
|
const run = storeRunner(context)
|
|
1402
|
+
const now = new Date()
|
|
1403
|
+
const joins: JoinState[] = []
|
|
1070
1404
|
for (let index = 0; index < state.joins.length; index++) {
|
|
1071
1405
|
const join = state.joins[index]
|
|
1072
|
-
if (join
|
|
1406
|
+
if (join === undefined) continue
|
|
1407
|
+
if (!includes(join.join.readActions, action)) {
|
|
1073
1408
|
throw new CapabilityError(
|
|
1074
1409
|
'wrong_action',
|
|
1075
1410
|
`joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
|
|
1076
1411
|
)
|
|
1077
1412
|
}
|
|
1413
|
+
joins[joins.length] = heldJoin(context, join, action, now)
|
|
1078
1414
|
}
|
|
1079
1415
|
if (scope === undefined) {
|
|
1080
1416
|
return []
|
|
1081
1417
|
}
|
|
1082
1418
|
const dialect = dialectOf(context)
|
|
1083
|
-
const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
|
|
1419
|
+
const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
|
|
1084
1420
|
const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
|
|
1085
1421
|
return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
|
|
1086
1422
|
}
|
|
1087
1423
|
|
|
1424
|
+
/**
|
|
1425
|
+
* `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
|
|
1426
|
+
* subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
|
|
1427
|
+
*/
|
|
1428
|
+
function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
|
|
1429
|
+
const child = ownEntry(context.children, join.join.shape.table)
|
|
1430
|
+
if (child === undefined) {
|
|
1431
|
+
throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
|
|
1432
|
+
}
|
|
1433
|
+
const condition = ownEntry(child.when, action)
|
|
1434
|
+
if (condition === undefined) {
|
|
1435
|
+
return join
|
|
1436
|
+
}
|
|
1437
|
+
let reads = false
|
|
1438
|
+
conditionReach(condition, () => {
|
|
1439
|
+
reads = true
|
|
1440
|
+
})
|
|
1441
|
+
if (reads) {
|
|
1442
|
+
throw new CapabilityError(
|
|
1443
|
+
'unenforceable',
|
|
1444
|
+
`joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
|
|
1445
|
+
)
|
|
1446
|
+
}
|
|
1447
|
+
return { ...join, condition: conditionNode(child.name, condition, now) }
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1088
1450
|
/** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
|
|
1089
1451
|
function joinedColumns(context: TableContext, state: SelectState): RowColumns {
|
|
1090
1452
|
const own = rowColumnsOf(context.model)
|
|
@@ -1207,29 +1569,55 @@ export function keyOf(model: TableModel): string {
|
|
|
1207
1569
|
* Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
|
|
1208
1570
|
* Ref minted before its object moved would insert into, or move rows into, the object's new container.
|
|
1209
1571
|
*/
|
|
1210
|
-
async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
|
|
1572
|
+
async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<void> {
|
|
1573
|
+
if (!(await destinationHeld(transaction, context, grant, paths))) {
|
|
1574
|
+
throw context.destination === undefined
|
|
1575
|
+
? new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
|
|
1576
|
+
: new NotFoundError(`${context.destination.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/** Whether the destination still lies where `grant`'s chain says and still holds it, locked `for share` (`lockDestination`). */
|
|
1581
|
+
async function destinationHeld(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
|
|
1211
1582
|
const owner = context.destination
|
|
1212
1583
|
if (owner === undefined) {
|
|
1213
|
-
|
|
1584
|
+
// No table owns the destination, so a Ref held through relations or member reveals is checked on the rows that hold it.
|
|
1585
|
+
return grant.relations.length === 0 && grant.revealing.length === 0 ? true : await holdingRowLocked(transaction, context, grant)
|
|
1214
1586
|
}
|
|
1215
|
-
const
|
|
1587
|
+
const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
|
|
1588
|
+
// A Ref held through a relation or a member reveal inserts only while a row of it still holds the destination.
|
|
1589
|
+
const gate = relationGate(context, owner, grant, new Date(), paths ?? heldThrough(grant.action))
|
|
1590
|
+
const scope = gate === undefined ? chain : allOf([chain, gate])
|
|
1216
1591
|
const node = lockNode(owner.name, keyOf(owner), scope)
|
|
1217
|
-
const rows = await transaction.run(node, {
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1592
|
+
const rows = await transaction.run(node, {
|
|
1593
|
+
root: 'SelectQueryNode',
|
|
1594
|
+
table: owner.name,
|
|
1595
|
+
joins: {},
|
|
1596
|
+
scope,
|
|
1597
|
+
lock: 'share',
|
|
1598
|
+
subqueries: context.subqueries,
|
|
1599
|
+
})
|
|
1600
|
+
return rows.length > 0
|
|
1221
1601
|
}
|
|
1222
1602
|
|
|
1603
|
+
/** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
|
|
1223
1604
|
export async function insertRow<O>(
|
|
1224
1605
|
context: TableContext,
|
|
1225
1606
|
run: Runner,
|
|
1226
1607
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1227
|
-
|
|
1608
|
+
prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
|
|
1228
1609
|
): Promise<O> {
|
|
1229
1610
|
const values = boundValues(context, given)
|
|
1230
1611
|
return run.write(async (transaction) => {
|
|
1231
|
-
if (destination !== undefined) {
|
|
1232
|
-
await lockDestination(transaction, context, destination)
|
|
1612
|
+
if (prepared?.destination !== undefined) {
|
|
1613
|
+
await lockDestination(transaction, context, prepared.destination)
|
|
1614
|
+
}
|
|
1615
|
+
const before = await narrowedHolds(transaction, context, prepared)
|
|
1616
|
+
if (prepared !== undefined) {
|
|
1617
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, given)
|
|
1618
|
+
await checkRevealAssign(transaction, context, prepared.writer, given)
|
|
1619
|
+
await checkMemberRevealAssign(transaction, context, prepared.writer, given)
|
|
1620
|
+
await checkPathWriters(transaction, context, prepared.writer, given)
|
|
1233
1621
|
}
|
|
1234
1622
|
const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
|
|
1235
1623
|
if (row === undefined) {
|
|
@@ -1237,6 +1625,8 @@ export async function insertRow<O>(
|
|
|
1237
1625
|
}
|
|
1238
1626
|
checkVersion(context, row)
|
|
1239
1627
|
await referenceInserted(context, run, transaction, values)
|
|
1628
|
+
await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
|
|
1629
|
+
await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
|
|
1240
1630
|
return row
|
|
1241
1631
|
})
|
|
1242
1632
|
}
|
|
@@ -1250,6 +1640,8 @@ export interface OnConflict {
|
|
|
1250
1640
|
readonly mode: 'nothing' | 'update'
|
|
1251
1641
|
/** The values given for the table's update columns: what `update` sets on the conflicting row. */
|
|
1252
1642
|
readonly updates: ReadonlyMap<string, Primitive | null>
|
|
1643
|
+
/** The capability's action, whose condition the conflicting row must satisfy to be updated. */
|
|
1644
|
+
readonly action: string
|
|
1253
1645
|
}
|
|
1254
1646
|
|
|
1255
1647
|
const CONFLICT_FIELDS = nameSet(['columns', 'do'])
|
|
@@ -1310,7 +1702,7 @@ export function onConflictOf(
|
|
|
1310
1702
|
}
|
|
1311
1703
|
}
|
|
1312
1704
|
}
|
|
1313
|
-
return freeze({ columns: freeze(columns), mode, updates })
|
|
1705
|
+
return freeze({ columns: freeze(columns), mode, updates, action })
|
|
1314
1706
|
}
|
|
1315
1707
|
|
|
1316
1708
|
/** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
|
|
@@ -1365,8 +1757,8 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
|
|
|
1365
1757
|
|
|
1366
1758
|
/**
|
|
1367
1759
|
* `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:
|
|
1760
|
+
* within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
|
|
1761
|
+
* 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
1762
|
* false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
|
|
1371
1763
|
*/
|
|
1372
1764
|
async function insertOnConflict(
|
|
@@ -1388,7 +1780,7 @@ async function insertOnConflict(
|
|
|
1388
1780
|
}
|
|
1389
1781
|
matches[matches.length] = equals(model.name, name, value)
|
|
1390
1782
|
}
|
|
1391
|
-
const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
|
|
1783
|
+
const scope = conflict.mode === 'update' ? conditioned(model, conflict.action, insertedScope(context, values), new Date()) : undefined
|
|
1392
1784
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1393
1785
|
const node = insertNode(model.name, values, answer(context), conflict.columns)
|
|
1394
1786
|
const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
|
|
@@ -1469,7 +1861,7 @@ export async function updateRow<O>(
|
|
|
1469
1861
|
target: Addressed,
|
|
1470
1862
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1471
1863
|
expectedVersion: OperationNode | undefined,
|
|
1472
|
-
|
|
1864
|
+
moved?: MovedRow,
|
|
1473
1865
|
): Promise<O> {
|
|
1474
1866
|
const { name: table, version } = context.model
|
|
1475
1867
|
const changes = boundValues(context, given)
|
|
@@ -1479,19 +1871,42 @@ export async function updateRow<O>(
|
|
|
1479
1871
|
? acknowledgementNode(table, keyOf(context.model), version, where)
|
|
1480
1872
|
: updateNode(table, changes, version, where, answer(context))
|
|
1481
1873
|
return run.write(async (transaction) => {
|
|
1482
|
-
|
|
1483
|
-
|
|
1874
|
+
// A move follows containment, so a path never holds its destination.
|
|
1875
|
+
if (moved !== undefined) {
|
|
1876
|
+
await lockDestination(transaction, context, moved.destination, noPath)
|
|
1484
1877
|
}
|
|
1878
|
+
const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
|
|
1485
1879
|
const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
|
|
1486
1880
|
if (row !== undefined) {
|
|
1487
1881
|
checkVersion(context, row)
|
|
1488
1882
|
await referenceUpdated(context, run, transaction, changes, row)
|
|
1883
|
+
if (moved !== undefined) {
|
|
1884
|
+
await judgeInserted(transaction, context, moved.judged, rowKey(context, row))
|
|
1885
|
+
await judgeNarrowed(transaction, context, moved, before, rowKey(context, row))
|
|
1886
|
+
}
|
|
1489
1887
|
return row
|
|
1490
1888
|
}
|
|
1491
1889
|
return missingOrChanged(context, transaction, target, expectedVersion)
|
|
1492
1890
|
})
|
|
1493
1891
|
}
|
|
1494
1892
|
|
|
1893
|
+
/**
|
|
1894
|
+
* A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
|
|
1895
|
+
* after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
|
|
1896
|
+
* `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
|
|
1897
|
+
*/
|
|
1898
|
+
export interface MovedRow {
|
|
1899
|
+
readonly destination: RefGrant
|
|
1900
|
+
readonly judged: JudgedInsert | undefined
|
|
1901
|
+
readonly narrowed: readonly NarrowedInsert[]
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
/** The key `row`, a write's acknowledgement, answers; `undefined` when it answers none as text. */
|
|
1905
|
+
function rowKey(context: TableContext, row: unknown): string | undefined {
|
|
1906
|
+
const value: unknown = typeof row === 'object' && row !== null ? ownDescriptor(row, keyOf(context.model))?.value : undefined
|
|
1907
|
+
return typeof value === 'string' ? value : undefined
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1495
1910
|
/** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
|
|
1496
1911
|
export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
|
|
1497
1912
|
const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
|
|
@@ -1658,8 +2073,25 @@ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]
|
|
|
1658
2073
|
/** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
|
|
1659
2074
|
export interface PreparedInsert {
|
|
1660
2075
|
readonly row: Map<string, Primitive | null>
|
|
2076
|
+
/** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
|
|
2077
|
+
readonly writer: string
|
|
1661
2078
|
readonly destination: RefGrant | undefined
|
|
1662
2079
|
readonly conflict: OnConflict | undefined
|
|
2080
|
+
/** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
|
|
2081
|
+
readonly judged: JudgedInsert | undefined
|
|
2082
|
+
/** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
|
|
2083
|
+
readonly narrowed: readonly NarrowedInsert[]
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
export interface JudgedInsert {
|
|
2087
|
+
readonly action: string
|
|
2088
|
+
readonly condition: ConditionModel
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
/** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
|
|
2092
|
+
export interface NarrowedInsert {
|
|
2093
|
+
readonly relation: string
|
|
2094
|
+
readonly condition: ConditionModel
|
|
1663
2095
|
}
|
|
1664
2096
|
|
|
1665
2097
|
/**
|
|
@@ -1675,11 +2107,16 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
|
|
|
1675
2107
|
// The object does not exist yet; this only refuses a chain the table has no column for.
|
|
1676
2108
|
linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
|
|
1677
2109
|
stampInsert(context, grant, row, scope.key, grant.id)
|
|
1678
|
-
|
|
2110
|
+
const judged = checkInserted(context, grant, row)
|
|
2111
|
+
// No destination to check again after the write, so a condition with a path holds nothing here.
|
|
2112
|
+
narrowedDestination(context, grant, row, false)
|
|
2113
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
|
|
1679
2114
|
}
|
|
1680
2115
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1681
2116
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1682
|
-
|
|
2117
|
+
const judged = checkInserted(context, grant, row)
|
|
2118
|
+
const held = narrowedDestination(context, grant, row, true)
|
|
2119
|
+
return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
|
|
1683
2120
|
}
|
|
1684
2121
|
|
|
1685
2122
|
/** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
|
|
@@ -1688,7 +2125,8 @@ export function prepareApplicationInsert(context: TableContext, capability: unkn
|
|
|
1688
2125
|
const row = readValues(values, context.model.insert, 'insert', context.model)
|
|
1689
2126
|
const conflict = onConflictOf(context, options, grant.action, row)
|
|
1690
2127
|
stampInsert(context, grant, row, keyOf(context.model), uuidv7())
|
|
1691
|
-
|
|
2128
|
+
const judged = checkInserted(context, grant, row)
|
|
2129
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
|
|
1692
2130
|
}
|
|
1693
2131
|
|
|
1694
2132
|
/** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
|
|
@@ -1699,7 +2137,269 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
|
|
|
1699
2137
|
const conflict = onConflictOf(context, options, grant.action, row)
|
|
1700
2138
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1701
2139
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1702
|
-
|
|
2140
|
+
const judged = checkInserted(context, grant, row)
|
|
2141
|
+
const held = narrowedDestination(context, grant, row, true)
|
|
2142
|
+
return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
const DAY_MS = 86_400_000
|
|
2146
|
+
|
|
2147
|
+
/**
|
|
2148
|
+
* An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
|
|
2149
|
+
* its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
|
|
2150
|
+
* ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
|
|
2151
|
+
* that follows a path is answered for the transaction to judge.
|
|
2152
|
+
*/
|
|
2153
|
+
function checkInserted(
|
|
2154
|
+
context: TableContext,
|
|
2155
|
+
grant: { readonly action: string; readonly principal: string },
|
|
2156
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2157
|
+
): JudgedInsert | undefined {
|
|
2158
|
+
const model = context.model
|
|
2159
|
+
const now = new Date()
|
|
2160
|
+
const condition = ownEntry(model.when, grant.action)
|
|
2161
|
+
const judged = condition === undefined || readPaths(condition).length === 0 ? undefined : { action: grant.action, condition }
|
|
2162
|
+
if (condition !== undefined && judged === undefined && !rowSatisfies(condition, row, now)) {
|
|
2163
|
+
throw new ConflictError(`the row is outside what ${grant.action} inserts into ${model.name}`)
|
|
2164
|
+
}
|
|
2165
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
2166
|
+
const source = model.confers[index]
|
|
2167
|
+
if (source === undefined) {
|
|
2168
|
+
continue
|
|
2169
|
+
}
|
|
2170
|
+
const assign = source.assign
|
|
2171
|
+
if (assign === undefined) {
|
|
2172
|
+
throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
|
|
2173
|
+
}
|
|
2174
|
+
// A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
|
|
2175
|
+
if (!assign.self && source.principalPath === undefined && row.get(source.principal) === grant.principal) {
|
|
2176
|
+
throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
|
|
2177
|
+
}
|
|
2178
|
+
if (assign.maxDays !== undefined && source.expires !== undefined) {
|
|
2179
|
+
const value = row.get(source.expires)
|
|
2180
|
+
const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
|
|
2181
|
+
if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
|
|
2182
|
+
throw new ConflictError(
|
|
2183
|
+
`a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
|
|
2184
|
+
)
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
return judged
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
/**
|
|
2192
|
+
* The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
|
|
2193
|
+
* and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
|
|
2194
|
+
* the transaction to judge (`judgeNarrowed`), or, without a destination to check again (`defer` false), held to fail. A Ref held by nothing else then is refused (409): the relation's membership
|
|
2195
|
+
* is never judged on the written row, so the row never counts towards its own insert.
|
|
2196
|
+
*/
|
|
2197
|
+
function narrowedDestination(
|
|
2198
|
+
context: TableContext,
|
|
2199
|
+
grant: RefGrant,
|
|
2200
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2201
|
+
defer: boolean,
|
|
2202
|
+
): { readonly destination: RefGrant; readonly narrowed: readonly NarrowedInsert[] } {
|
|
2203
|
+
const now = new Date()
|
|
2204
|
+
const kept: RelationHold[] = []
|
|
2205
|
+
const narrowed: NarrowedInsert[] = []
|
|
2206
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
2207
|
+
const hold = grant.relations[index]
|
|
2208
|
+
if (hold === undefined) continue
|
|
2209
|
+
const relation = hold.relation
|
|
2210
|
+
const condition = relationCondition(context.model, relation, grant.action)
|
|
2211
|
+
const pathed = condition !== undefined && readPaths(condition).length > 0
|
|
2212
|
+
if (condition !== undefined && pathed && defer && !judgesRelation(narrowed, relation)) {
|
|
2213
|
+
narrowed[narrowed.length] = { relation, condition }
|
|
2214
|
+
}
|
|
2215
|
+
if (condition === undefined || (pathed ? defer : rowSatisfies(condition, row, now))) {
|
|
2216
|
+
kept[kept.length] = hold
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
if (kept.length === grant.relations.length) {
|
|
2220
|
+
return { destination: grant, narrowed }
|
|
2221
|
+
}
|
|
2222
|
+
if (kept.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
|
|
2223
|
+
throw new ConflictError(`the row is outside what ${grant.action} inserts into ${context.model.name} through its relations`)
|
|
2224
|
+
}
|
|
2225
|
+
return { destination: { ...grant, relations: kept }, narrowed }
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
/** Whether `narrowed` already judges `relation`: two holds of one relation are judged once. */
|
|
2229
|
+
function judgesRelation(narrowed: readonly NarrowedInsert[], relation: string): boolean {
|
|
2230
|
+
for (let index = 0; index < narrowed.length; index++) {
|
|
2231
|
+
if (narrowed[index]?.relation === relation) return true
|
|
2232
|
+
}
|
|
2233
|
+
return false
|
|
2234
|
+
}
|
|
2235
|
+
|
|
2236
|
+
/**
|
|
2237
|
+
* What held an insert's destination before the write, apart from the relations narrowed by a path: the rest of the
|
|
2238
|
+
* `Ref`, and, with several such relations, each of them alone. Decided before the row exists, so it never counts it.
|
|
2239
|
+
*/
|
|
2240
|
+
interface NarrowedHolds {
|
|
2241
|
+
readonly rest: boolean
|
|
2242
|
+
readonly alone: readonly string[]
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
/** `NarrowedHolds` of a prepared insert, locked `for share` in its transaction before the write; `undefined` with nothing narrowed. */
|
|
2246
|
+
async function narrowedHolds(
|
|
2247
|
+
transaction: Session,
|
|
2248
|
+
context: TableContext,
|
|
2249
|
+
prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
|
|
2250
|
+
paths?: PathRule,
|
|
2251
|
+
): Promise<NarrowedHolds | undefined> {
|
|
2252
|
+
const destination = prepared?.destination
|
|
2253
|
+
if (prepared === undefined || destination === undefined || prepared.narrowed.length === 0) {
|
|
2254
|
+
return undefined
|
|
2255
|
+
}
|
|
2256
|
+
const relations: string[] = []
|
|
2257
|
+
for (let index = 0; index < prepared.narrowed.length; index++) {
|
|
2258
|
+
const entry = prepared.narrowed[index]
|
|
2259
|
+
if (entry !== undefined) relations[relations.length] = entry.relation
|
|
2260
|
+
}
|
|
2261
|
+
const rest = await heldBy(transaction, context, { ...destination, relations: holdsBesides(destination.relations, relations) }, paths)
|
|
2262
|
+
const alone: string[] = []
|
|
2263
|
+
// One narrowed relation that passes leaves the destination as `lockDestination` found it; only with several may it be another's.
|
|
2264
|
+
for (let index = 0; relations.length > 1 && index < relations.length; index++) {
|
|
2265
|
+
const relation = relations[index] ?? ''
|
|
2266
|
+
const holds: RelationHold[] = []
|
|
2267
|
+
for (let position = 0; position < destination.relations.length; position++) {
|
|
2268
|
+
const hold = destination.relations[position]
|
|
2269
|
+
if (hold !== undefined && hold.relation === relation) holds[holds.length] = hold
|
|
2270
|
+
}
|
|
2271
|
+
if (await heldBy(transaction, context, { ...destination, relations: holds, revealing: [], paths: [] }, paths)) alone[alone.length] = relation
|
|
2272
|
+
}
|
|
2273
|
+
return { rest, alone }
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/** Whether `grant` holds the destination: with no part left, never. */
|
|
2277
|
+
async function heldBy(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
|
|
2278
|
+
if (grant.relations.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
|
|
2279
|
+
return false
|
|
2280
|
+
}
|
|
2281
|
+
return await destinationHeld(transaction, context, grant, paths)
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
/**
|
|
2285
|
+
* The destination's relations whose condition for the insert follows a path, judged on the row just written as
|
|
2286
|
+
* `judgeInserted` judges `when`. When the row fails one, the insert stands only on what held the destination before the
|
|
2287
|
+
* write without it (`before`): the rest of the `Ref`, or a narrowed relation the row meets that held it alone. Otherwise
|
|
2288
|
+
* the transaction fails with a 409.
|
|
2289
|
+
*/
|
|
2290
|
+
async function judgeNarrowed(
|
|
2291
|
+
transaction: Session,
|
|
2292
|
+
context: TableContext,
|
|
2293
|
+
prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
|
|
2294
|
+
before: NarrowedHolds | undefined,
|
|
2295
|
+
key: Primitive | null | undefined,
|
|
2296
|
+
): Promise<void> {
|
|
2297
|
+
const destination = prepared?.destination
|
|
2298
|
+
if (prepared === undefined || destination === undefined || before === undefined) {
|
|
2299
|
+
return
|
|
2300
|
+
}
|
|
2301
|
+
let failed = false
|
|
2302
|
+
let held = before.rest
|
|
2303
|
+
for (let index = 0; index < prepared.narrowed.length; index++) {
|
|
2304
|
+
const entry = prepared.narrowed[index]
|
|
2305
|
+
if (entry === undefined) continue
|
|
2306
|
+
if (!(await rowMeets(transaction, context, destination.action, entry.condition, key))) {
|
|
2307
|
+
failed = true
|
|
2308
|
+
} else if (includes(before.alone, entry.relation)) {
|
|
2309
|
+
held = true
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
if (failed && !held) {
|
|
2313
|
+
transaction.fail()
|
|
2314
|
+
throw new ConflictError(`the row is outside what ${destination.action} inserts into ${context.model.name} through its relations`)
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
/**
|
|
2319
|
+
* An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
|
|
2320
|
+
* 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
|
|
2321
|
+
* reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
|
|
2322
|
+
* before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
|
|
2323
|
+
* so it commits nothing even when the handler catches the refusal.
|
|
2324
|
+
*/
|
|
2325
|
+
async function judgeInserted(
|
|
2326
|
+
transaction: Session,
|
|
2327
|
+
context: TableContext,
|
|
2328
|
+
judged: JudgedInsert | undefined,
|
|
2329
|
+
key: Primitive | null | undefined,
|
|
2330
|
+
): Promise<void> {
|
|
2331
|
+
if (judged === undefined) {
|
|
2332
|
+
return
|
|
2333
|
+
}
|
|
2334
|
+
if (!(await rowMeets(transaction, context, judged.action, judged.condition, key))) {
|
|
2335
|
+
transaction.fail()
|
|
2336
|
+
throw new ConflictError(`the row is outside what ${judged.action} inserts into ${context.model.name}`)
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
/**
|
|
2341
|
+
* Whether the row just written meets `condition`, in the insert's transaction: every row each of its paths reaches is
|
|
2342
|
+
* locked `FOR SHARE` first, then the condition is judged as a read of the row judges it.
|
|
2343
|
+
*/
|
|
2344
|
+
async function rowMeets(
|
|
2345
|
+
transaction: Session,
|
|
2346
|
+
context: TableContext,
|
|
2347
|
+
action: string,
|
|
2348
|
+
condition: ConditionModel,
|
|
2349
|
+
key: Primitive | null | undefined,
|
|
2350
|
+
): Promise<boolean> {
|
|
2351
|
+
const model = context.model
|
|
2352
|
+
if (key === undefined || key === null) {
|
|
2353
|
+
throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
|
|
2354
|
+
}
|
|
2355
|
+
const paths = readPaths(condition)
|
|
2356
|
+
for (let index = 0; index < paths.length; index++) {
|
|
2357
|
+
const steps = paths[index] ?? []
|
|
2358
|
+
// The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
|
|
2359
|
+
let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
|
|
2360
|
+
const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
|
|
2361
|
+
for (let position = 0; position < steps.length; position++) {
|
|
2362
|
+
const step = steps[position]
|
|
2363
|
+
if (step === undefined) continue
|
|
2364
|
+
const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
|
|
2365
|
+
await transaction.run(lockNode(step.table, step.to, scope), {
|
|
2366
|
+
root: 'SelectQueryNode',
|
|
2367
|
+
table: step.table,
|
|
2368
|
+
joins: {},
|
|
2369
|
+
scope,
|
|
2370
|
+
lock: 'share',
|
|
2371
|
+
subqueries: withColumns(context.subqueries, walked),
|
|
2372
|
+
})
|
|
2373
|
+
const next = steps[position + 1]
|
|
2374
|
+
if (next !== undefined) {
|
|
2375
|
+
reached = subquery(step.table, next.from, scope)
|
|
2376
|
+
walked[step.table] = [...(walked[step.table] ?? []), next.from]
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
|
|
2381
|
+
const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
|
|
2382
|
+
root: 'SelectQueryNode',
|
|
2383
|
+
table: model.name,
|
|
2384
|
+
joins: {},
|
|
2385
|
+
scope,
|
|
2386
|
+
subqueries: context.subqueries,
|
|
2387
|
+
})
|
|
2388
|
+
return rows.length > 0
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
/** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
|
|
2392
|
+
function withColumns(
|
|
2393
|
+
admitted: Readonly<Record<string, readonly string[]>>,
|
|
2394
|
+
more: Readonly<Record<string, readonly string[]>>,
|
|
2395
|
+
): Readonly<Record<string, readonly string[]>> {
|
|
2396
|
+
const merged: Record<string, readonly string[]> = { ...admitted }
|
|
2397
|
+
const tables = ownKeys(more)
|
|
2398
|
+
for (let index = 0; index < tables.length; index++) {
|
|
2399
|
+
const table = tables[index] ?? ''
|
|
2400
|
+
setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
|
|
2401
|
+
}
|
|
2402
|
+
return merged
|
|
1703
2403
|
}
|
|
1704
2404
|
|
|
1705
2405
|
/** Writes each chain column the destination `Ref` settles into an insert's row. */
|
|
@@ -1716,32 +2416,255 @@ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkVal
|
|
|
1716
2416
|
export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
|
|
1717
2417
|
const conflict = prepared.conflict
|
|
1718
2418
|
if (conflict === undefined) {
|
|
1719
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2419
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1720
2420
|
}
|
|
1721
2421
|
return run.write(async (transaction) => {
|
|
1722
2422
|
if (prepared.destination !== undefined) {
|
|
1723
2423
|
await lockDestination(transaction, context, prepared.destination)
|
|
1724
2424
|
}
|
|
1725
|
-
|
|
2425
|
+
const before = await narrowedHolds(transaction, context, prepared)
|
|
2426
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
|
|
2427
|
+
await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
|
|
2428
|
+
await checkMemberRevealAssign(transaction, context, prepared.writer, prepared.row)
|
|
2429
|
+
await checkPathWriters(transaction, context, prepared.writer, prepared.row)
|
|
2430
|
+
const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
|
|
2431
|
+
// A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
|
|
2432
|
+
if (written['inserted'] === true) {
|
|
2433
|
+
await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
|
|
2434
|
+
await judgeNarrowed(transaction, context, prepared, before, prepared.row.get(keyOf(context.model)))
|
|
2435
|
+
}
|
|
2436
|
+
return written
|
|
1726
2437
|
})
|
|
1727
2438
|
}
|
|
1728
2439
|
|
|
2440
|
+
/**
|
|
2441
|
+
* A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
|
|
2442
|
+
* row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
|
|
2443
|
+
* stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
|
|
2444
|
+
*/
|
|
2445
|
+
async function checkPrincipalAssign(
|
|
2446
|
+
transaction: Session,
|
|
2447
|
+
context: TableContext,
|
|
2448
|
+
writer: string,
|
|
2449
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2450
|
+
): Promise<void> {
|
|
2451
|
+
const model = context.model
|
|
2452
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
2453
|
+
const source = model.confers[index]
|
|
2454
|
+
const path = source?.principalPath
|
|
2455
|
+
const value = source === undefined ? undefined : row.get(source.principal)
|
|
2456
|
+
if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
|
|
2457
|
+
continue
|
|
2458
|
+
}
|
|
2459
|
+
const keyed = equals(path.table, path.key, value)
|
|
2460
|
+
await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
|
|
2461
|
+
const named = allOf([keyed, equals(path.table, path.column, writer)])
|
|
2462
|
+
const rows = await transaction.run(locateNode(path.table, [path.key], named), {
|
|
2463
|
+
root: 'SelectQueryNode',
|
|
2464
|
+
table: path.table,
|
|
2465
|
+
joins: {},
|
|
2466
|
+
scope: named,
|
|
2467
|
+
})
|
|
2468
|
+
if (rows.length > 0) {
|
|
2469
|
+
throw new ConflictError(
|
|
2470
|
+
`a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
|
|
2471
|
+
)
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
/**
|
|
2477
|
+
* An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
|
|
2478
|
+
* insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
|
|
2479
|
+
* the relation is at. One guarded select per such reveal, in the insert's transaction.
|
|
2480
|
+
*/
|
|
2481
|
+
async function checkRevealAssign(
|
|
2482
|
+
transaction: Session,
|
|
2483
|
+
context: TableContext,
|
|
2484
|
+
writer: string,
|
|
2485
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2486
|
+
): Promise<void> {
|
|
2487
|
+
const model = context.model
|
|
2488
|
+
const now = new Date()
|
|
2489
|
+
for (let index = 0; index < model.reveals.length; index++) {
|
|
2490
|
+
const reveal = model.reveals[index]
|
|
2491
|
+
const path = reveal?.path
|
|
2492
|
+
const value = path === undefined ? undefined : row.get(path.column)
|
|
2493
|
+
if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
|
|
2494
|
+
const source = relationSource(context.relations, reveal.relation)
|
|
2495
|
+
const tests: OperationNode[] = []
|
|
2496
|
+
const rest: OperationNode[] = [...activeRow(source, now)]
|
|
2497
|
+
if (source.dimension === path.dimension) {
|
|
2498
|
+
tests[tests.length] = equals(source.table, source.node, value)
|
|
2499
|
+
} else {
|
|
2500
|
+
const link = linkOf(path.chain, source.dimension)
|
|
2501
|
+
if (link === undefined) continue
|
|
2502
|
+
const above = subquery(path.table, link.column, equals(path.table, path.key, value))
|
|
2503
|
+
rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
|
|
2504
|
+
}
|
|
2505
|
+
// The principal test comes last: an equality, or a path's membership after the node's equality.
|
|
2506
|
+
tests[tests.length] = namesPrincipal(source, writer)
|
|
2507
|
+
const address = allOf(tests)
|
|
2508
|
+
const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
|
|
2509
|
+
const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
|
|
2510
|
+
root: 'SelectQueryNode',
|
|
2511
|
+
table: source.table,
|
|
2512
|
+
joins: {},
|
|
2513
|
+
scope,
|
|
2514
|
+
subqueries: context.subqueries,
|
|
2515
|
+
})
|
|
2516
|
+
if (rows.length > 0) {
|
|
2517
|
+
throw new ConflictError(
|
|
2518
|
+
`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`,
|
|
2519
|
+
)
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
/**
|
|
2525
|
+
* An inserted row whose path column a member reveal matches through, under the reveal's `assign`: without `self`, the
|
|
2526
|
+
* insert is refused while its writer holds a grant the reveal counts (one of its actions, at the node itself) at the
|
|
2527
|
+
* node the column names. The grants are the request's own; the database compares them with the node's key, so every
|
|
2528
|
+
* spelling of a key it reads as one (a `uuid`) is that node. Work with no request caller has none to judge, and is
|
|
2529
|
+
* refused.
|
|
2530
|
+
*/
|
|
2531
|
+
async function checkMemberRevealAssign(
|
|
2532
|
+
transaction: Session,
|
|
2533
|
+
context: TableContext,
|
|
2534
|
+
writer: string,
|
|
2535
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2536
|
+
): Promise<void> {
|
|
2537
|
+
const model = context.model
|
|
2538
|
+
const authority = runtimeOf(context.connection).capabilities
|
|
2539
|
+
for (let index = 0; index < model.memberReveals.length; index++) {
|
|
2540
|
+
const reveal = model.memberReveals[index]
|
|
2541
|
+
const path = reveal?.path
|
|
2542
|
+
const value = path === undefined ? undefined : row.get(path.column)
|
|
2543
|
+
if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || value === undefined || value === null) {
|
|
2544
|
+
continue
|
|
2545
|
+
}
|
|
2546
|
+
for (let position = 0; position < reveal.actions.length; position++) {
|
|
2547
|
+
const action = reveal.actions[position] ?? ''
|
|
2548
|
+
const standing = authority.standing?.(path.dimension, action)
|
|
2549
|
+
if (standing === undefined || standing.principal !== writer) {
|
|
2550
|
+
throw new ConflictError(
|
|
2551
|
+
`a row of ${model.name} names in ${path.column} a ${path.dimension} its member reveal reveals to, and its writer's grants cannot be judged under assign without self: work with no request caller`,
|
|
2552
|
+
)
|
|
2553
|
+
}
|
|
2554
|
+
if (standing.values === 'all' || standing.values.length === 0) continue
|
|
2555
|
+
const scope = AndNode.create(equals(path.table, path.key, value), inList(path.table, path.key, standing.values))
|
|
2556
|
+
const rows = await transaction.run(locateNode(path.table, [path.key], scope), {
|
|
2557
|
+
root: 'SelectQueryNode',
|
|
2558
|
+
table: path.table,
|
|
2559
|
+
joins: {},
|
|
2560
|
+
scope,
|
|
2561
|
+
})
|
|
2562
|
+
if (rows.length > 0) {
|
|
2563
|
+
throw new ConflictError(
|
|
2564
|
+
`a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer holds a grant the member reveal counts, which the reveal's assign.self does not allow`,
|
|
2565
|
+
)
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
|
|
2571
|
+
/**
|
|
2572
|
+
* An inserted row's path column that hands out actions (`writeThrough`): its writer must hold every one of them at the
|
|
2573
|
+
* node the column names, as a grant there or above it, a relation row naming it there (of a relation no `relationWhen`
|
|
2574
|
+
* narrows for the action), or a revealing row. The node's
|
|
2575
|
+
* row is locked `FOR SHARE` first, so it stays where it lies until the commit, and so is each row the writer holds it
|
|
2576
|
+
* through; IAM grants are the request's own. Judged before the insert, so the inserted row never counts. A writer
|
|
2577
|
+
* outside the bound, or work with no caller, is a 409 and nothing is written.
|
|
2578
|
+
*/
|
|
2579
|
+
async function checkPathWriters(
|
|
2580
|
+
transaction: Session,
|
|
2581
|
+
context: TableContext,
|
|
2582
|
+
writer: string,
|
|
2583
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2584
|
+
): Promise<void> {
|
|
2585
|
+
const model = context.model
|
|
2586
|
+
const authority = runtimeOf(context.connection).capabilities
|
|
2587
|
+
for (let index = 0; index < context.writers.length; index++) {
|
|
2588
|
+
const bound = context.writers[index]
|
|
2589
|
+
const value = bound === undefined ? undefined : row.get(bound.path.column)
|
|
2590
|
+
if (bound === undefined || value === undefined || value === null) continue
|
|
2591
|
+
const { path, owner } = bound
|
|
2592
|
+
const refused = (action: string) =>
|
|
2593
|
+
new ConflictError(
|
|
2594
|
+
`a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer does not hold ${action}, which the path hands out (writeThrough)`,
|
|
2595
|
+
)
|
|
2596
|
+
const keyed = equals(owner.name, keyOf(owner), value)
|
|
2597
|
+
const locked = await transaction.run(lockNode(owner.name, keyOf(owner), keyed), {
|
|
2598
|
+
root: 'SelectQueryNode',
|
|
2599
|
+
table: owner.name,
|
|
2600
|
+
joins: {},
|
|
2601
|
+
scope: keyed,
|
|
2602
|
+
lock: 'share',
|
|
2603
|
+
})
|
|
2604
|
+
const chain = locked.length === 0 ? null : await chainOf(owner, transaction, String(value))
|
|
2605
|
+
for (let position = 0; position < bound.actions.length; position++) {
|
|
2606
|
+
const action = bound.actions[position] ?? ''
|
|
2607
|
+
const standing = authority.standing?.(path.dimension, action)
|
|
2608
|
+
if (chain === null || standing === undefined || standing.principal !== writer) throw refused(action)
|
|
2609
|
+
if (holdsByGrant(standing, String(value), chain)) continue
|
|
2610
|
+
const holding: RefGrant = {
|
|
2611
|
+
kind: 'ref',
|
|
2612
|
+
dimension: path.dimension,
|
|
2613
|
+
action,
|
|
2614
|
+
principal: writer,
|
|
2615
|
+
id: String(value),
|
|
2616
|
+
chain,
|
|
2617
|
+
relations: unnarrowed(context.relations, standing.relations, action),
|
|
2618
|
+
revealing: standing.revealing,
|
|
2619
|
+
paths: [],
|
|
2620
|
+
}
|
|
2621
|
+
if (!(await holdingRowLocked(transaction, context, holding))) throw refused(action)
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
/**
|
|
2627
|
+
* Of `relations`, those no table's `relationWhen` narrows for `action`: a relation that holds the action on some rows only
|
|
2628
|
+
* does not bound a writer who hands it out at a node.
|
|
2629
|
+
*/
|
|
2630
|
+
function unnarrowed(relations: RelationSources, held: readonly RelationHold[], action: string): readonly RelationHold[] {
|
|
2631
|
+
const kept: RelationHold[] = []
|
|
2632
|
+
for (let index = 0; index < held.length; index++) {
|
|
2633
|
+
const hold = held[index]
|
|
2634
|
+
if (hold !== undefined && !includes(knownRelation(relations, hold.relation).narrowed, action)) kept[kept.length] = hold
|
|
2635
|
+
}
|
|
2636
|
+
return kept
|
|
2637
|
+
}
|
|
2638
|
+
|
|
2639
|
+
/** Whether `standing`'s grants hold its action at `node`: everywhere, there, or at a container `chain` places it in. */
|
|
2640
|
+
function holdsByGrant(standing: WithinGrant, node: string, chain: ReadonlyMap<string, string>): boolean {
|
|
2641
|
+
if (standing.values === 'all' || includes(standing.values, node)) {
|
|
2642
|
+
return true
|
|
2643
|
+
}
|
|
2644
|
+
for (let index = 0; index < standing.containers.length; index++) {
|
|
2645
|
+
const container = standing.containers[index]
|
|
2646
|
+
const at = container === undefined ? undefined : chain.get(container.dimension)
|
|
2647
|
+
if (container !== undefined && at !== undefined && includes(container.values, at)) return true
|
|
2648
|
+
}
|
|
2649
|
+
return false
|
|
2650
|
+
}
|
|
2651
|
+
|
|
1729
2652
|
/** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
|
|
1730
2653
|
export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
|
|
1731
2654
|
const prepared = prepareDimensionInsert(context, target, values)
|
|
1732
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2655
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1733
2656
|
}
|
|
1734
2657
|
|
|
1735
2658
|
/** An application table's insert, for an `app` capability of its insert action. */
|
|
1736
2659
|
export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
|
|
1737
2660
|
const prepared = prepareApplicationInsert(context, capability, values)
|
|
1738
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2661
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1739
2662
|
}
|
|
1740
2663
|
|
|
1741
2664
|
/** `ChildTable.insert` over a capability nobody type-checked. */
|
|
1742
2665
|
export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
|
|
1743
2666
|
const prepared = prepareChildInsert(context, parent, values)
|
|
1744
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2667
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1745
2668
|
}
|
|
1746
2669
|
|
|
1747
2670
|
type ReadAction<P, T> = ActionOf<P, T, 'read'>
|
|
@@ -1801,7 +2724,9 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1801
2724
|
/**
|
|
1802
2725
|
* Moves the object to another container: the delete action at the source, the insert action at the target,
|
|
1803
2726
|
* whose chain is checked against the database. Every chain column changes; children that copy them follow
|
|
1804
|
-
* through `ON UPDATE CASCADE` on their composite foreign key.
|
|
2727
|
+
* through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
|
|
2728
|
+
* condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
|
|
2729
|
+
* Answers the acknowledgement and the new chain.
|
|
1805
2730
|
*/
|
|
1806
2731
|
async move(
|
|
1807
2732
|
ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
|
|
@@ -1812,8 +2737,21 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1812
2737
|
if (container === undefined) {
|
|
1813
2738
|
throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
|
|
1814
2739
|
}
|
|
1815
|
-
|
|
2740
|
+
if (delegates(context.model)) {
|
|
2741
|
+
throw new CapabilityError(
|
|
2742
|
+
'table_kind',
|
|
2743
|
+
`${context.model.name} hands out access, so a row is never moved: insert a new one`,
|
|
2744
|
+
)
|
|
2745
|
+
}
|
|
2746
|
+
// A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
|
|
1816
2747
|
const target = refGrant(context, to, container.dimension, 'insert')
|
|
2748
|
+
if (refGrant(context, ref, dimensionScope(context.model).dimension, 'delete').paths.length > 0 || target.paths.length > 0) {
|
|
2749
|
+
throw new CapabilityError(
|
|
2750
|
+
'unenforceable',
|
|
2751
|
+
`a Ref held through a secondary path never moves a row of ${context.model.name}: a move follows containment`,
|
|
2752
|
+
)
|
|
2753
|
+
}
|
|
2754
|
+
const scope = objectPredicate(context, ref, 'delete', noPath)
|
|
1817
2755
|
const values = linkValues(context.model.name, context.model.chain, target)
|
|
1818
2756
|
const changes = new Map<string, Primitive | null>()
|
|
1819
2757
|
stampChain(changes, values)
|
|
@@ -1824,7 +2762,16 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1824
2762
|
setOwn(chain, entry.link.dimension, entry.value)
|
|
1825
2763
|
}
|
|
1826
2764
|
}
|
|
1827
|
-
const
|
|
2765
|
+
const condition = ownEntry(context.model.when, target.action)
|
|
2766
|
+
const narrowed: NarrowedInsert[] = []
|
|
2767
|
+
for (let index = 0; index < target.relations.length; index++) {
|
|
2768
|
+
const relation = target.relations[index]?.relation ?? ''
|
|
2769
|
+
const narrowing = relationCondition(context.model, relation, target.action)
|
|
2770
|
+
if (narrowing !== undefined && !judgesRelation(narrowed, relation)) narrowed[narrowed.length] = { relation, condition: narrowing }
|
|
2771
|
+
}
|
|
2772
|
+
const judged = condition === undefined ? undefined : { action: target.action, condition }
|
|
2773
|
+
const moved: MovedRow = { destination: target, judged, narrowed }
|
|
2774
|
+
const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, moved)
|
|
1828
2775
|
return { ...acknowledged, chain }
|
|
1829
2776
|
}
|
|
1830
2777
|
|
|
@@ -2035,8 +2982,7 @@ function appProbeOf(context: TableContext): TableProbe {
|
|
|
2035
2982
|
mode: 'app',
|
|
2036
2983
|
get: async (capability: unknown, key?: string) => {
|
|
2037
2984
|
if (scoped(capability)) {
|
|
2038
|
-
scopedApplicationRead(context, capability)
|
|
2039
|
-
return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
|
|
2985
|
+
return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
|
|
2040
2986
|
}
|
|
2041
2987
|
return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
|
|
2042
2988
|
},
|
|
@@ -2137,6 +3083,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
|
|
|
2137
3083
|
export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
2138
3084
|
const models = tableModels(tables)
|
|
2139
3085
|
const connection: Connection = { runtime: undefined }
|
|
3086
|
+
const layer = layerReach(models)
|
|
3087
|
+
const { relations, members, subqueries } = layer
|
|
2140
3088
|
|
|
2141
3089
|
function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
|
|
2142
3090
|
const model = typeof table === 'string' ? modelOf(models, table) : undefined
|
|
@@ -2148,6 +3096,15 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2148
3096
|
|
|
2149
3097
|
function contextOf(model: TableModel): TableContext {
|
|
2150
3098
|
const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
|
|
3099
|
+
const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
|
|
3100
|
+
? freeze({
|
|
3101
|
+
column: model.scope.column,
|
|
3102
|
+
table: parent.name,
|
|
3103
|
+
key: parent.scope.key,
|
|
3104
|
+
access: viewAccessLinks(model, model.scope.key),
|
|
3105
|
+
context: contextOf(freeze({ ...parent, when: freeze({}), relationWhen: freeze({}) })),
|
|
3106
|
+
})
|
|
3107
|
+
: undefined
|
|
2151
3108
|
const joinable = joinShapes(models, model)
|
|
2152
3109
|
const joins: Record<string, readonly ForeignKeyPair[]> = {}
|
|
2153
3110
|
const children = ownKeys(joinable)
|
|
@@ -2166,6 +3123,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2166
3123
|
}
|
|
2167
3124
|
}
|
|
2168
3125
|
const shape = shapeOf(model, joinable)
|
|
3126
|
+
const writers: PathBound[] = []
|
|
3127
|
+
const declared = pathWriters(models, model)
|
|
3128
|
+
for (let index = 0; index < declared.length; index++) {
|
|
3129
|
+
const writer = declared[index]
|
|
3130
|
+
const owner = writer === undefined ? undefined : modelOf(models, writer.path.table)
|
|
3131
|
+
if (writer !== undefined && owner !== undefined) writers[writers.length] = freeze({ ...writer, owner })
|
|
3132
|
+
}
|
|
2169
3133
|
return freeze({
|
|
2170
3134
|
model,
|
|
2171
3135
|
parent,
|
|
@@ -2174,6 +3138,11 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2174
3138
|
joins: freeze(joins),
|
|
2175
3139
|
children: freeze(childModels),
|
|
2176
3140
|
connection,
|
|
3141
|
+
relations,
|
|
3142
|
+
members,
|
|
3143
|
+
subqueries,
|
|
3144
|
+
through,
|
|
3145
|
+
writers: freeze(writers),
|
|
2177
3146
|
})
|
|
2178
3147
|
}
|
|
2179
3148
|
|
|
@@ -2203,6 +3172,20 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2203
3172
|
connection.runtime = bound
|
|
2204
3173
|
return freeze({
|
|
2205
3174
|
locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
|
|
3175
|
+
relates: async (relation: string, node: string, principal: string) =>
|
|
3176
|
+
relationHolds(models, relations, subqueries, bound, relation, node, principal),
|
|
3177
|
+
reveals: async (relation: string, dimension: string, node: string, principal: string, action: string) =>
|
|
3178
|
+
revealHolds(relations, subqueries, bound, relation, dimension, node, principal, action),
|
|
3179
|
+
holdsThrough: async (
|
|
3180
|
+
dimension: string,
|
|
3181
|
+
id: string,
|
|
3182
|
+
action: string,
|
|
3183
|
+
principal: string,
|
|
3184
|
+
relations: readonly RelationHold[],
|
|
3185
|
+
paths: readonly ContainerGrant[],
|
|
3186
|
+
) => heldThroughPaths(models, layer, bound, dimension, id, action, principal, relations, paths),
|
|
3187
|
+
revealsToMembers: async (revealing: string, values: readonly string[], dimension: string, node: string, action: string) =>
|
|
3188
|
+
membersRevealed(members, subqueries, bound, revealing, values, dimension, node, action),
|
|
2206
3189
|
release() {
|
|
2207
3190
|
if (connection.runtime === bound) {
|
|
2208
3191
|
connection.runtime = undefined
|
|
@@ -2235,6 +3218,150 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2235
3218
|
return database
|
|
2236
3219
|
}
|
|
2237
3220
|
|
|
3221
|
+
/**
|
|
3222
|
+
* Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
|
|
3223
|
+
* node column, a condition path's target by its key), which the guard admits and nothing else.
|
|
3224
|
+
*/
|
|
3225
|
+
function layerReach(
|
|
3226
|
+
models: TableModels,
|
|
3227
|
+
): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
|
|
3228
|
+
const relations: Record<string, LayerRelation | AccessRelation> = {}
|
|
3229
|
+
const members: Record<string, MemberRevealModel[]> = {}
|
|
3230
|
+
const selected: Record<string, string[]> = {}
|
|
3231
|
+
const select = (table: string, column: string): void => {
|
|
3232
|
+
const columns = ownEntry(selected, table) ?? []
|
|
3233
|
+
if (!includes(columns, column)) columns[columns.length] = column
|
|
3234
|
+
setOwn(selected, table, columns)
|
|
3235
|
+
}
|
|
3236
|
+
const names = ownKeys(models)
|
|
3237
|
+
const reveals: Record<string, RevealModel[]> = {}
|
|
3238
|
+
const narrowed: Record<string, string[]> = {}
|
|
3239
|
+
for (let index = 0; index < names.length; index++) {
|
|
3240
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3241
|
+
const conditioned = model === undefined ? [] : ownKeys(model.relationWhen)
|
|
3242
|
+
for (let position = 0; model !== undefined && position < conditioned.length; position++) {
|
|
3243
|
+
const relation = conditioned[position] ?? ''
|
|
3244
|
+
const conditions = ownEntry(model.relationWhen, relation) ?? {}
|
|
3245
|
+
const actions = ownKeys(conditions)
|
|
3246
|
+
const listed = ownEntry(narrowed, relation) ?? []
|
|
3247
|
+
for (let next = 0; next < actions.length; next++) {
|
|
3248
|
+
const action = actions[next] ?? ''
|
|
3249
|
+
if (!includes(listed, action)) listed[listed.length] = action
|
|
3250
|
+
const condition = ownEntry(conditions, action)
|
|
3251
|
+
if (condition !== undefined) addReach(condition, select)
|
|
3252
|
+
}
|
|
3253
|
+
setOwn(narrowed, relation, listed)
|
|
3254
|
+
}
|
|
3255
|
+
for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
|
|
3256
|
+
const reveal = model.reveals[position]
|
|
3257
|
+
if (reveal === undefined) continue
|
|
3258
|
+
const listed = ownEntry(reveals, reveal.relation) ?? []
|
|
3259
|
+
listed[listed.length] = reveal
|
|
3260
|
+
setOwn(reveals, reveal.relation, listed)
|
|
3261
|
+
select(reveal.table, reveal.column)
|
|
3262
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
3263
|
+
}
|
|
3264
|
+
for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
|
|
3265
|
+
const reveal = model.memberReveals[position]
|
|
3266
|
+
if (reveal === undefined) continue
|
|
3267
|
+
const listed = ownEntry(members, reveal.source) ?? []
|
|
3268
|
+
listed[listed.length] = reveal
|
|
3269
|
+
setOwn(members, reveal.source, listed)
|
|
3270
|
+
select(reveal.table, reveal.column)
|
|
3271
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
for (let index = 0; index < names.length; index++) {
|
|
3275
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3276
|
+
if (model === undefined) continue
|
|
3277
|
+
for (let position = 0; position < model.confers.length; position++) {
|
|
3278
|
+
const source = model.confers[position]
|
|
3279
|
+
if (source === undefined) continue
|
|
3280
|
+
const revealed = ownEntry(reveals, source.relation) ?? []
|
|
3281
|
+
const placed: Record<string, Readonly<Record<string, string>>> = {}
|
|
3282
|
+
setOwn(placed, model.name, placementOf(model))
|
|
3283
|
+
for (let next = 0; next < revealed.length; next++) {
|
|
3284
|
+
const table = revealed[next]?.table ?? ''
|
|
3285
|
+
const at = modelOf(models, table)
|
|
3286
|
+
if (at !== undefined) setOwn(placed, table, placementOf(at))
|
|
3287
|
+
}
|
|
3288
|
+
setOwn(
|
|
3289
|
+
relations,
|
|
3290
|
+
source.relation,
|
|
3291
|
+
freeze({
|
|
3292
|
+
...source,
|
|
3293
|
+
kind: 'source',
|
|
3294
|
+
reveals: freeze(revealed),
|
|
3295
|
+
narrowed: freeze(ownEntry(narrowed, source.relation) ?? []),
|
|
3296
|
+
placed: freeze(placed),
|
|
3297
|
+
}),
|
|
3298
|
+
)
|
|
3299
|
+
select(source.table, source.node)
|
|
3300
|
+
if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
|
|
3301
|
+
if (source.when !== undefined) addReach(source.when, select)
|
|
3302
|
+
}
|
|
3303
|
+
for (let position = 0; position < model.access.length; position++) {
|
|
3304
|
+
const access = model.access[position]
|
|
3305
|
+
if (access === undefined) continue
|
|
3306
|
+
select(access.view, access.row)
|
|
3307
|
+
}
|
|
3308
|
+
for (let position = 0; position < model.readThrough.length; position++) {
|
|
3309
|
+
const path = model.readThrough[position]
|
|
3310
|
+
if (path === undefined) continue
|
|
3311
|
+
select(path.table, path.key)
|
|
3312
|
+
if (path.via !== undefined) select(path.via.table, path.via.key)
|
|
3313
|
+
for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
|
|
3314
|
+
}
|
|
3315
|
+
const actions = ownKeys(model.when)
|
|
3316
|
+
for (let position = 0; position < actions.length; position++) {
|
|
3317
|
+
const condition = ownEntry(model.when, actions[position] ?? '')
|
|
3318
|
+
if (condition !== undefined) addReach(condition, select)
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
// A relation no table confers is served by the access views alone; a table that confers it adds them to its source.
|
|
3322
|
+
for (let index = 0; index < names.length; index++) {
|
|
3323
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3324
|
+
for (let position = 0; model !== undefined && position < model.access.length; position++) {
|
|
3325
|
+
const access = model.access[position]
|
|
3326
|
+
if (access === undefined || ownEntry(relations, access.relation) !== undefined) continue
|
|
3327
|
+
const relation = access.relation
|
|
3328
|
+
setOwn(
|
|
3329
|
+
relations,
|
|
3330
|
+
relation,
|
|
3331
|
+
freeze({ kind: 'access', relation, dimension: access.dimension, narrowed: freeze(ownEntry(narrowed, relation) ?? []) }),
|
|
3332
|
+
)
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
const subqueries: Record<string, readonly string[]> = {}
|
|
3336
|
+
const tablesRead = ownKeys(selected)
|
|
3337
|
+
for (let index = 0; index < tablesRead.length; index++) {
|
|
3338
|
+
const table = tablesRead[index] ?? ''
|
|
3339
|
+
setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
|
|
3340
|
+
}
|
|
3341
|
+
const revealing: Record<string, readonly MemberRevealModel[]> = {}
|
|
3342
|
+
const sources = ownKeys(members)
|
|
3343
|
+
for (let index = 0; index < sources.length; index++) {
|
|
3344
|
+
const source = sources[index] ?? ''
|
|
3345
|
+
setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
|
|
3346
|
+
}
|
|
3347
|
+
return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
/** `model`'s column for each dimension a row of it lies at: its key at its own dimension, then each link of its chain. */
|
|
3351
|
+
function placementOf(model: TableModel): Readonly<Record<string, string>> {
|
|
3352
|
+
const placed: Record<string, string> = {}
|
|
3353
|
+
if (model.scope.mode === 'dimension') setOwn(placed, model.scope.dimension, model.scope.key)
|
|
3354
|
+
for (let index = 0; index < model.chain.length; index++) {
|
|
3355
|
+
const link = model.chain[index]
|
|
3356
|
+
if (link !== undefined && ownEntry(placed, link.dimension) === undefined) setOwn(placed, link.dimension, link.column)
|
|
3357
|
+
}
|
|
3358
|
+
return freeze(placed)
|
|
3359
|
+
}
|
|
3360
|
+
|
|
3361
|
+
function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
|
|
3362
|
+
conditionReach(condition, select)
|
|
3363
|
+
}
|
|
3364
|
+
|
|
2238
3365
|
/** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
|
|
2239
3366
|
function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
|
|
2240
3367
|
const side = frameworkSideOf(database)
|
|
@@ -2277,6 +3404,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
|
|
|
2277
3404
|
return undefined
|
|
2278
3405
|
}
|
|
2279
3406
|
|
|
3407
|
+
/**
|
|
3408
|
+
* Whether an access view of `relation` lists `node` for `principal`: a guarded select of the row of the table that owns
|
|
3409
|
+
* the relation's dimension, by its key, under the access term. Only a principal-bound view answers; one bound to a
|
|
3410
|
+
* member node lists nothing for a hold anywhere, which is all `relates` asks about.
|
|
3411
|
+
*/
|
|
3412
|
+
async function accessHolds(
|
|
3413
|
+
models: TableModels,
|
|
3414
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3415
|
+
runtime: DataLayerRuntime,
|
|
3416
|
+
relation: string,
|
|
3417
|
+
dimension: string,
|
|
3418
|
+
node: string,
|
|
3419
|
+
principal: string,
|
|
3420
|
+
): Promise<boolean> {
|
|
3421
|
+
const names = ownKeys(models)
|
|
3422
|
+
for (let index = 0; index < names.length; index++) {
|
|
3423
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3424
|
+
if (model === undefined || model.scope.mode !== 'dimension' || model.scope.dimension !== dimension) continue
|
|
3425
|
+
const terms = relationTerms(
|
|
3426
|
+
{ [relation]: freeze({ kind: 'access', relation, dimension, narrowed: freeze([]) }) },
|
|
3427
|
+
model,
|
|
3428
|
+
{ relation, inside: null },
|
|
3429
|
+
principal,
|
|
3430
|
+
'',
|
|
3431
|
+
new Date(),
|
|
3432
|
+
noPath,
|
|
3433
|
+
)
|
|
3434
|
+
if (terms.length === 0) continue
|
|
3435
|
+
const scope = AndNode.create(equals(model.name, keyOf(model), node), anyOf(terms))
|
|
3436
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: model.name, joins: {}, scope, subqueries }
|
|
3437
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(model.name, [keyOf(model)], scope), context)
|
|
3438
|
+
if (rows.length > 0) return true
|
|
3439
|
+
}
|
|
3440
|
+
return false
|
|
3441
|
+
}
|
|
3442
|
+
|
|
2280
3443
|
/** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
|
|
2281
3444
|
function locatedOwner(models: TableModels, dimension: unknown): TableModel {
|
|
2282
3445
|
const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
|
|
@@ -2286,6 +3449,298 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
|
|
|
2286
3449
|
return owner
|
|
2287
3450
|
}
|
|
2288
3451
|
|
|
3452
|
+
/** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
|
|
3453
|
+
async function relationHolds(
|
|
3454
|
+
models: TableModels,
|
|
3455
|
+
relations: RelationSources,
|
|
3456
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3457
|
+
runtime: DataLayerRuntime,
|
|
3458
|
+
relation: string,
|
|
3459
|
+
node: string,
|
|
3460
|
+
principal: string,
|
|
3461
|
+
): Promise<boolean> {
|
|
3462
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
3463
|
+
throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
|
|
3464
|
+
}
|
|
3465
|
+
const known = knownRelation(relations, relation)
|
|
3466
|
+
if (known.kind === 'access') {
|
|
3467
|
+
return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
|
|
3468
|
+
}
|
|
3469
|
+
const source = relationSource(relations, relation)
|
|
3470
|
+
const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
|
|
3471
|
+
const active = activeRow(source, new Date())
|
|
3472
|
+
const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
|
|
3473
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
|
|
3474
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
|
|
3475
|
+
// A relation with a source table may also name access views: the same term answers through them.
|
|
3476
|
+
return rows.length > 0 || accessHolds(models, subqueries, runtime, relation, source.dimension, node, principal)
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3479
|
+
/**
|
|
3480
|
+
* Locks the first row that holds `grant`'s action for its principal at its object or a container on its chain, if any:
|
|
3481
|
+
* a source row naming it there, a row the relation reaches that reveals that node, or a row at a node the Ref's
|
|
3482
|
+
* revealing grants name that reveals it to its members.
|
|
3483
|
+
*/
|
|
3484
|
+
async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
|
|
3485
|
+
const now = new Date()
|
|
3486
|
+
const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
|
|
3487
|
+
const candidates: { table: string; column: string; scope: OperationNode }[] = []
|
|
3488
|
+
for (let index = 0; index < grant.revealing.length; index++) {
|
|
3489
|
+
const revealing = grant.revealing[index]
|
|
3490
|
+
const reveals = revealing === undefined ? [] : ownEntry(context.members, revealing.dimension) ?? []
|
|
3491
|
+
for (let position = 0; revealing !== undefined && position < reveals.length; position++) {
|
|
3492
|
+
const reveal = reveals[position]
|
|
3493
|
+
const held = reveal !== undefined && includes(reveal.actions, grant.action)
|
|
3494
|
+
&& (reveal.path === undefined || includes(reveal.path.writes, grant.action))
|
|
3495
|
+
const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
|
|
3496
|
+
if (reveal === undefined || revealed === undefined || revealing.values.length === 0) continue
|
|
3497
|
+
candidates[candidates.length] = { table: reveal.table, column: reveal.key, scope: memberAddress(reveal, revealing.values, revealed, now) }
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
3501
|
+
const hold = grant.relations[index]
|
|
3502
|
+
// An access view's base rows are not the data layer's to lock (ADR-0076): such a hold holds no destination here.
|
|
3503
|
+
if (hold === undefined || knownRelation(context.relations, hold.relation).kind === 'access') continue
|
|
3504
|
+
const source = relationSource(context.relations, hold.relation)
|
|
3505
|
+
const node = nodeOf(source.dimension)
|
|
3506
|
+
const sourceInside = insideRow(source, source.table, hold)
|
|
3507
|
+
if (node !== undefined && sourceInside !== null) {
|
|
3508
|
+
const parts = [equals(source.table, source.node, node), namesPrincipal(source, grant.principal)]
|
|
3509
|
+
if (sourceInside !== undefined) parts[parts.length] = sourceInside
|
|
3510
|
+
const address = allOf(parts)
|
|
3511
|
+
const active = activeRow(source, now)
|
|
3512
|
+
candidates[candidates.length] = {
|
|
3513
|
+
table: source.table,
|
|
3514
|
+
column: source.node,
|
|
3515
|
+
scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
for (let position = 0; position < source.reveals.length; position++) {
|
|
3519
|
+
const reveal = source.reveals[position]
|
|
3520
|
+
const held = reveal !== undefined && includes(reveal.actions, grant.action)
|
|
3521
|
+
&& (reveal.path === undefined || includes(reveal.path.writes, grant.action))
|
|
3522
|
+
const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
|
|
3523
|
+
const revealInside = reveal === undefined ? null : insideRow(source, reveal.table, hold)
|
|
3524
|
+
if (reveal !== undefined && revealed !== undefined && revealInside !== null) {
|
|
3525
|
+
const address = revealAddress(source, reveal, revealed, grant.principal, now)
|
|
3526
|
+
candidates[candidates.length] = {
|
|
3527
|
+
table: reveal.table,
|
|
3528
|
+
column: reveal.column,
|
|
3529
|
+
scope: revealInside === undefined ? address : allOf([address, revealInside]),
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
for (let position = 0; position < candidates.length; position++) {
|
|
3535
|
+
const candidate = candidates[position]
|
|
3536
|
+
if (candidate === undefined) continue
|
|
3537
|
+
const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
|
|
3538
|
+
root: 'SelectQueryNode',
|
|
3539
|
+
table: candidate.table,
|
|
3540
|
+
joins: {},
|
|
3541
|
+
scope: candidate.scope,
|
|
3542
|
+
lock: 'share',
|
|
3543
|
+
subqueries: context.subqueries,
|
|
3544
|
+
})
|
|
3545
|
+
if (rows.length > 0) return true
|
|
3546
|
+
}
|
|
3547
|
+
return false
|
|
3548
|
+
}
|
|
3549
|
+
|
|
3550
|
+
/**
|
|
3551
|
+
* What a row of `table` (the relation's source or a reveal's table) must meet to hold under `hold`: nothing
|
|
3552
|
+
* (`undefined`) for a hold anywhere, its column for the hold's dimension among the hold's values for one inside a node,
|
|
3553
|
+
* and null when it has no such column, so it is not inside and holds nothing.
|
|
3554
|
+
*/
|
|
3555
|
+
function insideRow(source: LayerRelation, table: string, hold: RelationHold): OperationNode | undefined | null {
|
|
3556
|
+
if (hold.inside === null) {
|
|
3557
|
+
return undefined
|
|
3558
|
+
}
|
|
3559
|
+
const placed = ownEntry(source.placed, table)
|
|
3560
|
+
const column = placed === undefined ? undefined : ownEntry(placed, hold.inside.dimension)
|
|
3561
|
+
return column === undefined || hold.inside.values.length === 0 ? null : isIn(table, column, valueList(hold.inside.values))
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
/** `R.<ancestor> = $node and (R.<key> in (values) and <when>)`: a row at a node `values` name that reveals `node` now. */
|
|
3565
|
+
function memberAddress(reveal: MemberRevealModel, values: readonly string[], node: string, now: Date): OperationNode {
|
|
3566
|
+
const named = inList(reveal.table, reveal.key, values)
|
|
3567
|
+
const held = reveal.when === undefined ? named : allOf([named, conditionNode(reveal.table, reveal.when, now)])
|
|
3568
|
+
return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(held))
|
|
3569
|
+
}
|
|
3570
|
+
|
|
3571
|
+
/** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
|
|
3572
|
+
function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
|
|
3573
|
+
const revealed = BinaryOperationNode.create(
|
|
3574
|
+
column(reveal.table, reveal.column),
|
|
3575
|
+
OperatorNode.create('in'),
|
|
3576
|
+
revealedNodes(source, reveal, principal, now),
|
|
3577
|
+
)
|
|
3578
|
+
return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
|
|
3579
|
+
}
|
|
3580
|
+
|
|
3581
|
+
/** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
|
|
3582
|
+
async function revealHolds(
|
|
3583
|
+
relations: RelationSources,
|
|
3584
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3585
|
+
runtime: DataLayerRuntime,
|
|
3586
|
+
relation: string,
|
|
3587
|
+
dimension: string,
|
|
3588
|
+
node: string,
|
|
3589
|
+
principal: string,
|
|
3590
|
+
action: string,
|
|
3591
|
+
): Promise<boolean> {
|
|
3592
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
3593
|
+
throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
|
|
3594
|
+
}
|
|
3595
|
+
const source = relationSource(relations, relation)
|
|
3596
|
+
for (let index = 0; index < source.reveals.length; index++) {
|
|
3597
|
+
const reveal = source.reveals[index]
|
|
3598
|
+
// A reveal matched through a secondary path holds a Ref's action only where the path holds it (`writeThrough`).
|
|
3599
|
+
if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
|
|
3600
|
+
if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
|
|
3601
|
+
const address = revealAddress(source, reveal, node, principal, new Date())
|
|
3602
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
|
|
3603
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
|
|
3604
|
+
if (rows.length > 0) return true
|
|
3605
|
+
}
|
|
3606
|
+
return false
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
/**
|
|
3610
|
+
* Of `values`, nodes of `revealing` at which the caller holds `action`, the ones whose row reveals `node` of `dimension`
|
|
3611
|
+
* for it now: one guarded select per member reveal of `revealing` to `dimension` that lists `action`.
|
|
3612
|
+
*/
|
|
3613
|
+
async function membersRevealed(
|
|
3614
|
+
members: MemberReveals,
|
|
3615
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3616
|
+
runtime: DataLayerRuntime,
|
|
3617
|
+
revealing: string,
|
|
3618
|
+
values: readonly string[],
|
|
3619
|
+
dimension: string,
|
|
3620
|
+
node: string,
|
|
3621
|
+
action: string,
|
|
3622
|
+
): Promise<readonly string[]> {
|
|
3623
|
+
if (typeof node !== 'string' || node.length === 0 || !isArray(values) || values.length > MAX_WITHIN_VALUES) {
|
|
3624
|
+
throw new QueryRefusedError('row_address', `a node ${revealing} reveals is addressed by its node and at most ${MAX_WITHIN_VALUES} grants`)
|
|
3625
|
+
}
|
|
3626
|
+
for (let index = 0; index < values.length; index++) {
|
|
3627
|
+
if (typeof values[index] !== 'string' || values[index] === '') {
|
|
3628
|
+
throw new QueryRefusedError('row_address', `a grant at ${revealing} names its node, a non-empty string`)
|
|
3629
|
+
}
|
|
3630
|
+
}
|
|
3631
|
+
const reveals = ownEntry(members, revealing) ?? []
|
|
3632
|
+
const found: string[] = []
|
|
3633
|
+
for (let index = 0; values.length > 0 && index < reveals.length; index++) {
|
|
3634
|
+
const reveal = reveals[index]
|
|
3635
|
+
if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
|
|
3636
|
+
if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
|
|
3637
|
+
const scope = memberAddress(reveal, values, node, new Date())
|
|
3638
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope, subqueries }
|
|
3639
|
+
// Grouped, not limited: through a path many rows name one grant's node, and every grant matched is carried.
|
|
3640
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(valuesNode(reveal.table, reveal.key, scope), context)
|
|
3641
|
+
for (let position = 0; position < rows.length; position++) {
|
|
3642
|
+
const key = ownEntry(rows[position] ?? {}, reveal.key)
|
|
3643
|
+
if (typeof key === 'string' && !includes(found, key)) found[found.length] = key
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
return freeze(found)
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
/**
|
|
3650
|
+
* Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
|
|
3651
|
+
* through a relation row, a reveal or a secondary path that holds the action for a `Ref` (`writeThrough`): one guarded
|
|
3652
|
+
* select per candidate. What `on` and `in` mint a `Ref` held through a path with, and through a relation held inside a
|
|
3653
|
+
* node: the statement compares the object's column for the node's dimension with the held values, and the relation
|
|
3654
|
+
* comes back held inside the node that column stores, so every spelling the database equates is one node.
|
|
3655
|
+
*/
|
|
3656
|
+
async function heldThroughPaths(
|
|
3657
|
+
models: TableModels,
|
|
3658
|
+
layer: ReturnType<typeof layerReach>,
|
|
3659
|
+
runtime: DataLayerRuntime,
|
|
3660
|
+
dimension: string,
|
|
3661
|
+
id: string,
|
|
3662
|
+
action: string,
|
|
3663
|
+
principal: string,
|
|
3664
|
+
relations: readonly RelationHold[],
|
|
3665
|
+
paths: readonly ContainerGrant[],
|
|
3666
|
+
): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }> {
|
|
3667
|
+
const owner = locatedOwner(models, dimension)
|
|
3668
|
+
if (typeof id !== 'string' || id.length === 0 || typeof principal !== 'string' || principal.length === 0 || typeof action !== 'string') {
|
|
3669
|
+
throw new QueryRefusedError('row_address', `a ${dimension} held through a path is addressed by its key, the principal and the action`)
|
|
3670
|
+
}
|
|
3671
|
+
let count = 0
|
|
3672
|
+
const grantOf = (grant: unknown, what: string): ContainerGrant => {
|
|
3673
|
+
const at: unknown = typeof grant === 'object' && grant !== null ? ownDescriptor(grant, 'dimension')?.value : undefined
|
|
3674
|
+
const values = typeof grant === 'object' && grant !== null
|
|
3675
|
+
? parseList(ownDescriptor(grant, 'values')?.value, (value) => {
|
|
3676
|
+
if (typeof value !== 'string' || value === '') throw new QueryRefusedError('row_address', 'a grant names its node, a non-empty string')
|
|
3677
|
+
return value
|
|
3678
|
+
})
|
|
3679
|
+
: undefined
|
|
3680
|
+
if (typeof at !== 'string' || values === undefined) {
|
|
3681
|
+
throw new QueryRefusedError('row_address', `${what} names its dimension and its nodes`)
|
|
3682
|
+
}
|
|
3683
|
+
count += values.length
|
|
3684
|
+
return freeze({ dimension: at, values: freeze(values) })
|
|
3685
|
+
}
|
|
3686
|
+
const named = parseList(relations, (hold): RelationHold => {
|
|
3687
|
+
const relation: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'relation')?.value : undefined
|
|
3688
|
+
const inside: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'inside')?.value : undefined
|
|
3689
|
+
if (typeof relation !== 'string') throw new QueryRefusedError('row_address', 'a relation is named by its name')
|
|
3690
|
+
return freeze({ relation, inside: inside === null ? null : grantOf(inside, 'a relation held inside a node') })
|
|
3691
|
+
})
|
|
3692
|
+
const grants = parseList(paths, (grant): ContainerGrant => grantOf(grant, 'a grant of a path'))
|
|
3693
|
+
if (named === undefined || grants === undefined) {
|
|
3694
|
+
throw new QueryRefusedError('row_address', 'the candidates of a path are plain arrays')
|
|
3695
|
+
}
|
|
3696
|
+
if (count > MAX_WITHIN_VALUES) {
|
|
3697
|
+
throw new QueryRefusedError('row_address', `the grants of a path carry at most ${MAX_WITHIN_VALUES} nodes`)
|
|
3698
|
+
}
|
|
3699
|
+
const now = new Date()
|
|
3700
|
+
const session = sessionOf(runtime)
|
|
3701
|
+
const reached = async (
|
|
3702
|
+
terms: readonly OperationNode[],
|
|
3703
|
+
column: string,
|
|
3704
|
+
inside?: readonly string[],
|
|
3705
|
+
): Promise<Readonly<Record<string, unknown>> | undefined> => {
|
|
3706
|
+
if (terms.length === 0) return undefined
|
|
3707
|
+
const found = AndNode.create(equals(owner.name, keyOf(owner), id), anyOf(terms))
|
|
3708
|
+
// A member-bound access term is not narrowed to the node (ADR-0076): the object's own column is, as the database compares it.
|
|
3709
|
+
const scope = inside === undefined ? found : AndNode.create(found, ParensNode.create(isIn(owner.name, column, valueList(inside))))
|
|
3710
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, subqueries: layer.subqueries }
|
|
3711
|
+
const columns = column === keyOf(owner) ? [column] : [keyOf(owner), column]
|
|
3712
|
+
const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
|
|
3713
|
+
return row
|
|
3714
|
+
}
|
|
3715
|
+
const held: RelationHold[] = []
|
|
3716
|
+
for (let index = 0; index < named.length; index++) {
|
|
3717
|
+
const hold = named[index]
|
|
3718
|
+
if (hold === undefined) continue
|
|
3719
|
+
const column = hold.inside === null ? keyOf(owner) : nodeColumnOf(owner, hold.inside.dimension)
|
|
3720
|
+
const row = column === undefined
|
|
3721
|
+
? undefined
|
|
3722
|
+
: await reached(relationTerms(layer.relations, owner, hold, principal, action, now, heldThrough(action)), column, hold.inside?.values)
|
|
3723
|
+
if (row === undefined || column === undefined) continue
|
|
3724
|
+
if (hold.inside === null) {
|
|
3725
|
+
held[held.length] = hold
|
|
3726
|
+
continue
|
|
3727
|
+
}
|
|
3728
|
+
const node = ownEntry(row, column)
|
|
3729
|
+
if (typeof node !== 'string') {
|
|
3730
|
+
throw new PolicyError(`${owner.name}.${column} came back as ${typeof node}; a containment column holds its scope value as text`)
|
|
3731
|
+
}
|
|
3732
|
+
held[held.length] = freeze({ relation: hold.relation, inside: freeze({ dimension: hold.inside.dimension, values: freeze([node]) }) })
|
|
3733
|
+
}
|
|
3734
|
+
const through: ContainerGrant[] = []
|
|
3735
|
+
for (let index = 0; index < grants.length; index++) {
|
|
3736
|
+
const grant = grants[index]
|
|
3737
|
+
if (grant !== undefined && (await reached(pathTerms(owner, [grant], heldThrough(action)), keyOf(owner))) !== undefined) {
|
|
3738
|
+
through[through.length] = grant
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
3741
|
+
return freeze({ relations: freeze(held), paths: freeze(through) })
|
|
3742
|
+
}
|
|
3743
|
+
|
|
2289
3744
|
/** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
|
|
2290
3745
|
async function locateObject(
|
|
2291
3746
|
models: TableModels,
|
|
@@ -2298,6 +3753,11 @@ async function locateObject(
|
|
|
2298
3753
|
if (typeof id !== 'string' || id.length === 0) {
|
|
2299
3754
|
throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
|
|
2300
3755
|
}
|
|
3756
|
+
return chainOf(owner, using ?? sessionOf(runtime), id)
|
|
3757
|
+
}
|
|
3758
|
+
|
|
3759
|
+
/** The containers of `owner`'s row keyed `id`, by dimension, read in `session`; `null` for no such row. */
|
|
3760
|
+
async function chainOf(owner: TableModel, session: Session, id: string): Promise<ReadonlyMap<string, string> | null> {
|
|
2301
3761
|
const key = keyOf(owner)
|
|
2302
3762
|
const scope = equals(owner.name, key, id)
|
|
2303
3763
|
const columns: string[] = [key]
|
|
@@ -2305,7 +3765,7 @@ async function locateObject(
|
|
|
2305
3765
|
columns[columns.length] = owner.chain[index]?.column ?? ''
|
|
2306
3766
|
}
|
|
2307
3767
|
const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
|
|
2308
|
-
const [row] = await
|
|
3768
|
+
const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
|
|
2309
3769
|
if (row === undefined) {
|
|
2310
3770
|
return null
|
|
2311
3771
|
}
|