@fabrika/db 0.9.0-dev.13 → 0.9.0-dev.15

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/src/store.ts CHANGED
@@ -2,18 +2,31 @@ import { uuidv7 } from '@fabrika/platform'
2
2
  import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
3
3
  import { admissions } from './admissions'
4
4
  import {
5
+ accessReach,
6
+ type AccessRelation,
5
7
  activeRow,
6
8
  conditioned,
9
+ everyPath,
10
+ gateTerms,
11
+ heldThrough,
12
+ holdsBesides,
13
+ isIn,
14
+ knownRelation,
7
15
  type LayerRelation,
8
16
  type MemberReveals,
9
17
  memberTerms,
10
18
  namesPrincipal,
19
+ noPath,
20
+ type PathRule,
21
+ pathTerms,
11
22
  refScope,
23
+ relationCondition,
12
24
  relationGate,
13
25
  relationSource,
14
26
  type RelationSources,
15
27
  relationTerms,
16
28
  revealedNodes,
29
+ type SplitReach,
17
30
  throughPath,
18
31
  viewScope,
19
32
  } from './authority'
@@ -41,10 +54,12 @@ import {
41
54
  type AppGrant,
42
55
  type CapabilityAuthority,
43
56
  type CapabilityGrant,
57
+ type ContainerGrant,
44
58
  describeGrant,
45
59
  MAX_WITHIN_VALUES,
46
60
  type Ref,
47
61
  type RefGrant,
62
+ type RelationHold,
48
63
  type Within,
49
64
  type WithinGrant,
50
65
  } from './capability'
@@ -72,7 +87,7 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
72
87
  import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
73
88
  import { fileReference } from './file-references'
74
89
  import { webhookTables } from './framework-tables'
75
- import type { ForeignKeyPair, GuardContext, RootKind, ViewParentLink } from './guard'
90
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
76
91
  import { fencedTransaction, jobLeases } from './job-leases'
77
92
  import { jobWakes, leaseProjection } from './job-wakes'
78
93
  import { jsonInput } from './json'
@@ -97,6 +112,7 @@ import {
97
112
  selectNode,
98
113
  updateNode,
99
114
  valueList,
115
+ valuesNode,
100
116
  } from './nodes'
101
117
  import { dataAccess } from './orm'
102
118
  import {
@@ -116,8 +132,11 @@ import {
116
132
  modelOf,
117
133
  type MoveAcknowledgement,
118
134
  namesAction,
135
+ nodeColumnOf,
119
136
  type Operation,
120
137
  type ParentOf,
138
+ type PathWriter,
139
+ pathWriters,
121
140
  type PolicyRow,
122
141
  type RevealModel,
123
142
  type SecondaryPath,
@@ -171,6 +190,13 @@ export interface TableContext {
171
190
  readonly subqueries: Readonly<Record<string, readonly string[]>>
172
191
  /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
173
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
174
200
  }
175
201
 
176
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. */
@@ -178,6 +204,16 @@ export interface ViewParent extends ViewParentLink {
178
204
  readonly context: TableContext
179
205
  }
180
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)
215
+ }
216
+
181
217
  /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
182
218
  export function dialectOf(context: TableContext): SqlDialect {
183
219
  return runtimeOf(context.connection).database.dialect
@@ -490,7 +526,17 @@ function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: O
490
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. */
491
527
  function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
492
528
  for (let index = 0; index < grant.relations.length; index++) {
493
- const terms = relationTerms(context.relations, context.model, grant.relations[index] ?? '', grant.principal, grant.action, now, reads)
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
+ )
494
540
  for (let position = 0; position < terms.length; position++) {
495
541
  const term = terms[position]
496
542
  if (term !== undefined) predicates[predicates.length] = term
@@ -552,11 +598,11 @@ export function selfLinks(model: TableModel): readonly Container[] {
552
598
  return links
553
599
  }
554
600
 
555
- /** This object, over the whole chain the Ref carries. */
556
- 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 {
557
603
  const scope = dimensionScope(context.model)
558
604
  const grant = refGrant(context, capability, scope.dimension, operation)
559
- return refScope(context.relations, context.model, selfLinks(context.model), grant, new Date())
605
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
560
606
  }
561
607
 
562
608
  /** Rows of a dimension table within the scope values of its list dimension. */
@@ -576,27 +622,102 @@ export function parentPredicate(context: TableContext, grant: RefGrant, key?: st
576
622
  if (through !== undefined) {
577
623
  const parent = through.context
578
624
  const now = new Date()
579
- return viewScope(context.model, through, grant.action, refScope(parent.relations, parent.model, selfLinks(parent.model), grant, now), now, row)
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
642
+ }
643
+
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
+ )
580
670
  }
581
- return refScope(context.relations, context.model, context.model.chain, grant, new Date(), row)
671
+ return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
582
672
  }
583
673
 
584
674
  /**
585
675
  * A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
586
- * those whose parent row exists. Undefined where `reach` is: the empty `Within`.
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`.
587
679
  */
588
680
  function throughParent(
589
681
  context: TableContext,
590
682
  through: ViewParent,
591
683
  grant: WithinGrant,
592
- reach: (parent: TableContext) => OperationNode | undefined,
684
+ reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
593
685
  ): OperationNode | undefined {
594
686
  const now = new Date()
595
687
  if (grant.values === 'all') {
596
688
  return viewScope(context.model, through, grant.action, 'all', now)
597
689
  }
598
- const reached = reach(through.context)
599
- return reached === undefined ? undefined : viewScope(context.model, through, grant.action, reached, now)
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)
600
721
  }
601
722
 
602
723
  export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
@@ -612,7 +733,7 @@ export function childListPredicate(context: TableContext, capability: unknown, o
612
733
  checkGrant(context, grant, listDimension(scope.parent), operation)
613
734
  if (context.through !== undefined) {
614
735
  const column = scope.parent.container?.column ?? scope.parent.key
615
- return throughParent(context, context.through, grant, (parent) => withinPredicate(parent, column, grant, operation))
736
+ return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
616
737
  }
617
738
  return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
618
739
  }
@@ -682,7 +803,7 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
682
803
  )
683
804
  }
684
805
  if (context.through !== undefined) {
685
- return throughParent(context, context.through, grant, (parent) => withinReach(parent, grant, true))
806
+ return throughParent(context, context.through, grant, (parent, part) => withinReach(parent, part, true))
686
807
  }
687
808
  return withinReach(context, grant, false)
688
809
  }
@@ -750,11 +871,13 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
750
871
  if (use !== 'read') {
751
872
  checkWriteTarget(context, grant, use)
752
873
  }
753
- // The fragment renders column tests only; a relation's subquery or an action's condition would be left out.
754
- if ((grant.kind !== 'app' && grant.relations.length > 0) || hasOwn(model.when, grant.action)) {
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)) {
755
878
  throw new CapabilityError(
756
879
  'unenforceable',
757
- `ctx.sql.scope cannot render a relation or a condition of ${grant.action} on ${model.name}: read it through ctx.db`,
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`,
758
881
  )
759
882
  }
760
883
  // Nor the subquery through the parent row, which alone places a child view's rows.
@@ -1446,16 +1569,24 @@ export function keyOf(model: TableModel): string {
1446
1569
  * Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
1447
1570
  * Ref minted before its object moved would insert into, or move rows into, the object's new container.
1448
1571
  */
1449
- 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> {
1450
1582
  const owner = context.destination
1451
1583
  if (owner === undefined) {
1452
- // No table owns the destination, so a Ref held through relations is checked on the rows that hold it.
1453
- if (grant.relations.length > 0) await lockRelationRow(transaction, context, grant)
1454
- return
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)
1455
1586
  }
1456
1587
  const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1457
- // A Ref held through a relation inserts only while a row of it still names the caller at the destination.
1458
- const gate = relationGate(context.relations, owner, grant, new Date())
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))
1459
1590
  const scope = gate === undefined ? chain : allOf([chain, gate])
1460
1591
  const node = lockNode(owner.name, keyOf(owner), scope)
1461
1592
  const rows = await transaction.run(node, {
@@ -1466,9 +1597,7 @@ async function lockDestination(transaction: Session, context: TableContext, gran
1466
1597
  lock: 'share',
1467
1598
  subqueries: context.subqueries,
1468
1599
  })
1469
- if (rows.length === 0) {
1470
- throw new NotFoundError(`${owner.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1471
- }
1600
+ return rows.length > 0
1472
1601
  }
1473
1602
 
1474
1603
  /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
@@ -1476,16 +1605,19 @@ export async function insertRow<O>(
1476
1605
  context: TableContext,
1477
1606
  run: Runner,
1478
1607
  given: ReadonlyMap<string, Primitive | null>,
1479
- prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged'> | undefined,
1608
+ prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
1480
1609
  ): Promise<O> {
1481
1610
  const values = boundValues(context, given)
1482
1611
  return run.write(async (transaction) => {
1483
1612
  if (prepared?.destination !== undefined) {
1484
1613
  await lockDestination(transaction, context, prepared.destination)
1485
1614
  }
1615
+ const before = await narrowedHolds(transaction, context, prepared)
1486
1616
  if (prepared !== undefined) {
1487
1617
  await checkPrincipalAssign(transaction, context, prepared.writer, given)
1488
1618
  await checkRevealAssign(transaction, context, prepared.writer, given)
1619
+ await checkMemberRevealAssign(transaction, context, prepared.writer, given)
1620
+ await checkPathWriters(transaction, context, prepared.writer, given)
1489
1621
  }
1490
1622
  const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
1491
1623
  if (row === undefined) {
@@ -1494,6 +1626,7 @@ export async function insertRow<O>(
1494
1626
  checkVersion(context, row)
1495
1627
  await referenceInserted(context, run, transaction, values)
1496
1628
  await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
1629
+ await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
1497
1630
  return row
1498
1631
  })
1499
1632
  }
@@ -1728,7 +1861,7 @@ export async function updateRow<O>(
1728
1861
  target: Addressed,
1729
1862
  given: ReadonlyMap<string, Primitive | null>,
1730
1863
  expectedVersion: OperationNode | undefined,
1731
- destination?: RefGrant,
1864
+ moved?: MovedRow,
1732
1865
  ): Promise<O> {
1733
1866
  const { name: table, version } = context.model
1734
1867
  const changes = boundValues(context, given)
@@ -1738,19 +1871,42 @@ export async function updateRow<O>(
1738
1871
  ? acknowledgementNode(table, keyOf(context.model), version, where)
1739
1872
  : updateNode(table, changes, version, where, answer(context))
1740
1873
  return run.write(async (transaction) => {
1741
- if (destination !== undefined) {
1742
- await lockDestination(transaction, context, destination)
1874
+ // A move follows containment, so a path never holds its destination.
1875
+ if (moved !== undefined) {
1876
+ await lockDestination(transaction, context, moved.destination, noPath)
1743
1877
  }
1878
+ const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
1744
1879
  const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
1745
1880
  if (row !== undefined) {
1746
1881
  checkVersion(context, row)
1747
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
+ }
1748
1887
  return row
1749
1888
  }
1750
1889
  return missingOrChanged(context, transaction, target, expectedVersion)
1751
1890
  })
1752
1891
  }
1753
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
+
1754
1910
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
1755
1911
  export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
1756
1912
  const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
@@ -1923,6 +2079,8 @@ export interface PreparedInsert {
1923
2079
  readonly conflict: OnConflict | undefined
1924
2080
  /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
1925
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[]
1926
2084
  }
1927
2085
 
1928
2086
  export interface JudgedInsert {
@@ -1930,6 +2088,12 @@ export interface JudgedInsert {
1930
2088
  readonly condition: ConditionModel
1931
2089
  }
1932
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
2095
+ }
2096
+
1933
2097
  /**
1934
2098
  * A dimension table's insert over a capability nobody type-checked: into a container (a new UUIDv7 key, the chain from
1935
2099
  * the container's `Ref`), or for a top-level table the object the `Ref` names.
@@ -1944,12 +2108,15 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
1944
2108
  linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
1945
2109
  stampInsert(context, grant, row, scope.key, grant.id)
1946
2110
  const judged = checkInserted(context, grant, row)
1947
- return { row, writer: grant.principal, destination: undefined, conflict, judged }
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: [] }
1948
2114
  }
1949
2115
  stampInsert(context, grant, row, scope.key, uuidv7())
1950
2116
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1951
2117
  const judged = checkInserted(context, grant, row)
1952
- return { row, writer: grant.principal, destination: grant, conflict, judged }
2118
+ const held = narrowedDestination(context, grant, row, true)
2119
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1953
2120
  }
1954
2121
 
1955
2122
  /** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
@@ -1959,7 +2126,7 @@ export function prepareApplicationInsert(context: TableContext, capability: unkn
1959
2126
  const conflict = onConflictOf(context, options, grant.action, row)
1960
2127
  stampInsert(context, grant, row, keyOf(context.model), uuidv7())
1961
2128
  const judged = checkInserted(context, grant, row)
1962
- return { row, writer: grant.principal, destination: undefined, conflict, judged }
2129
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
1963
2130
  }
1964
2131
 
1965
2132
  /** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
@@ -1971,7 +2138,8 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
1971
2138
  stampInsert(context, grant, row, scope.key, uuidv7())
1972
2139
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1973
2140
  const judged = checkInserted(context, grant, row)
1974
- return { row, writer: grant.principal, destination: grant, conflict, judged }
2141
+ const held = narrowedDestination(context, grant, row, true)
2142
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1975
2143
  }
1976
2144
 
1977
2145
  const DAY_MS = 86_400_000
@@ -2020,6 +2188,133 @@ function checkInserted(
2020
2188
  return judged
2021
2189
  }
2022
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
+
2023
2318
  /**
2024
2319
  * An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
2025
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
@@ -2036,11 +2331,28 @@ async function judgeInserted(
2036
2331
  if (judged === undefined) {
2037
2332
  return
2038
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> {
2039
2351
  const model = context.model
2040
2352
  if (key === undefined || key === null) {
2041
- throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${judged.action} has no key`)
2353
+ throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
2042
2354
  }
2043
- const paths = readPaths(judged.condition)
2355
+ const paths = readPaths(condition)
2044
2356
  for (let index = 0; index < paths.length; index++) {
2045
2357
  const steps = paths[index] ?? []
2046
2358
  // The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
@@ -2065,7 +2377,7 @@ async function judgeInserted(
2065
2377
  }
2066
2378
  }
2067
2379
  }
2068
- const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, judged.condition, new Date())))
2380
+ const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
2069
2381
  const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
2070
2382
  root: 'SelectQueryNode',
2071
2383
  table: model.name,
@@ -2073,10 +2385,7 @@ async function judgeInserted(
2073
2385
  scope,
2074
2386
  subqueries: context.subqueries,
2075
2387
  })
2076
- if (rows.length === 0) {
2077
- transaction.fail()
2078
- throw new ConflictError(`the row is outside what ${judged.action} inserts into ${model.name}`)
2079
- }
2388
+ return rows.length > 0
2080
2389
  }
2081
2390
 
2082
2391
  /** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
@@ -2113,12 +2422,16 @@ export function insertPrepared(context: TableContext, run: Runner, prepared: Pre
2113
2422
  if (prepared.destination !== undefined) {
2114
2423
  await lockDestination(transaction, context, prepared.destination)
2115
2424
  }
2425
+ const before = await narrowedHolds(transaction, context, prepared)
2116
2426
  await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
2117
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)
2118
2430
  const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
2119
2431
  // A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
2120
2432
  if (written['inserted'] === true) {
2121
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)))
2122
2435
  }
2123
2436
  return written
2124
2437
  })
@@ -2208,6 +2521,134 @@ async function checkRevealAssign(
2208
2521
  }
2209
2522
  }
2210
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
+
2211
2652
  /** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
2212
2653
  export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
2213
2654
  const prepared = prepareDimensionInsert(context, target, values)
@@ -2283,7 +2724,9 @@ export class DimensionTable<DB, P, T extends string> {
2283
2724
  /**
2284
2725
  * Moves the object to another container: the delete action at the source, the insert action at the target,
2285
2726
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
2286
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
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.
2287
2730
  */
2288
2731
  async move(
2289
2732
  ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
@@ -2300,8 +2743,15 @@ export class DimensionTable<DB, P, T extends string> {
2300
2743
  `${context.model.name} hands out access, so a row is never moved: insert a new one`,
2301
2744
  )
2302
2745
  }
2303
- const scope = objectPredicate(context, ref, 'delete')
2746
+ // A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
2304
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)
2305
2755
  const values = linkValues(context.model.name, context.model.chain, target)
2306
2756
  const changes = new Map<string, Primitive | null>()
2307
2757
  stampChain(changes, values)
@@ -2312,7 +2762,16 @@ export class DimensionTable<DB, P, T extends string> {
2312
2762
  setOwn(chain, entry.link.dimension, entry.value)
2313
2763
  }
2314
2764
  }
2315
- const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, target)
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)
2316
2775
  return { ...acknowledged, chain }
2317
2776
  }
2318
2777
 
@@ -2624,7 +3083,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
2624
3083
  export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2625
3084
  const models = tableModels(tables)
2626
3085
  const connection: Connection = { runtime: undefined }
2627
- const { relations, members, subqueries } = layerReach(models)
3086
+ const layer = layerReach(models)
3087
+ const { relations, members, subqueries } = layer
2628
3088
 
2629
3089
  function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
2630
3090
  const model = typeof table === 'string' ? modelOf(models, table) : undefined
@@ -2637,7 +3097,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2637
3097
  function contextOf(model: TableModel): TableContext {
2638
3098
  const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
2639
3099
  const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
2640
- ? freeze({ column: model.scope.column, table: parent.name, key: parent.scope.key, context: contextOf(freeze({ ...parent, when: freeze({}) })) })
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
+ })
2641
3107
  : undefined
2642
3108
  const joinable = joinShapes(models, model)
2643
3109
  const joins: Record<string, readonly ForeignKeyPair[]> = {}
@@ -2657,6 +3123,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2657
3123
  }
2658
3124
  }
2659
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
+ }
2660
3133
  return freeze({
2661
3134
  model,
2662
3135
  parent,
@@ -2669,6 +3142,7 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2669
3142
  members,
2670
3143
  subqueries,
2671
3144
  through,
3145
+ writers: freeze(writers),
2672
3146
  })
2673
3147
  }
2674
3148
 
@@ -2698,9 +3172,20 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2698
3172
  connection.runtime = bound
2699
3173
  return freeze({
2700
3174
  locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
2701
- relates: async (relation: string, node: string, principal: string) => relationHolds(relations, subqueries, bound, relation, node, principal),
2702
- reveals: async (relation: string, dimension: string, node: string, principal: string) =>
2703
- revealHolds(relations, subqueries, bound, relation, dimension, node, principal),
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),
2704
3189
  release() {
2705
3190
  if (connection.runtime === bound) {
2706
3191
  connection.runtime = undefined
@@ -2740,7 +3225,7 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
2740
3225
  function layerReach(
2741
3226
  models: TableModels,
2742
3227
  ): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
2743
- const relations: Record<string, LayerRelation> = {}
3228
+ const relations: Record<string, LayerRelation | AccessRelation> = {}
2744
3229
  const members: Record<string, MemberRevealModel[]> = {}
2745
3230
  const selected: Record<string, string[]> = {}
2746
3231
  const select = (table: string, column: string): void => {
@@ -2750,8 +3235,23 @@ function layerReach(
2750
3235
  }
2751
3236
  const names = ownKeys(models)
2752
3237
  const reveals: Record<string, RevealModel[]> = {}
3238
+ const narrowed: Record<string, string[]> = {}
2753
3239
  for (let index = 0; index < names.length; index++) {
2754
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
+ }
2755
3255
  for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
2756
3256
  const reveal = model.reveals[position]
2757
3257
  if (reveal === undefined) continue
@@ -2777,11 +3277,34 @@ function layerReach(
2777
3277
  for (let position = 0; position < model.confers.length; position++) {
2778
3278
  const source = model.confers[position]
2779
3279
  if (source === undefined) continue
2780
- setOwn(relations, source.relation, freeze({ ...source, reveals: freeze(ownEntry(reveals, source.relation) ?? []) }))
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
+ )
2781
3299
  select(source.table, source.node)
2782
3300
  if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
2783
3301
  if (source.when !== undefined) addReach(source.when, select)
2784
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
+ }
2785
3308
  for (let position = 0; position < model.readThrough.length; position++) {
2786
3309
  const path = model.readThrough[position]
2787
3310
  if (path === undefined) continue
@@ -2795,6 +3318,20 @@ function layerReach(
2795
3318
  if (condition !== undefined) addReach(condition, select)
2796
3319
  }
2797
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
+ }
2798
3335
  const subqueries: Record<string, readonly string[]> = {}
2799
3336
  const tablesRead = ownKeys(selected)
2800
3337
  for (let index = 0; index < tablesRead.length; index++) {
@@ -2810,6 +3347,17 @@ function layerReach(
2810
3347
  return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
2811
3348
  }
2812
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
+
2813
3361
  function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
2814
3362
  conditionReach(condition, select)
2815
3363
  }
@@ -2856,6 +3404,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
2856
3404
  return undefined
2857
3405
  }
2858
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
+
2859
3443
  /** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
2860
3444
  function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2861
3445
  const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
@@ -2867,6 +3451,7 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2867
3451
 
2868
3452
  /** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
2869
3453
  async function relationHolds(
3454
+ models: TableModels,
2870
3455
  relations: RelationSources,
2871
3456
  subqueries: Readonly<Record<string, readonly string[]>>,
2872
3457
  runtime: DataLayerRuntime,
@@ -2877,28 +3462,52 @@ async function relationHolds(
2877
3462
  if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
2878
3463
  throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
2879
3464
  }
3465
+ const known = knownRelation(relations, relation)
3466
+ if (known.kind === 'access') {
3467
+ return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
3468
+ }
2880
3469
  const source = relationSource(relations, relation)
2881
3470
  const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
2882
3471
  const active = activeRow(source, new Date())
2883
3472
  const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
2884
3473
  const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
2885
3474
  const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
2886
- return rows.length > 0
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)
2887
3477
  }
2888
3478
 
2889
3479
  /**
2890
- * Locks a row that still holds the Ref's action for its principal at the Ref's object or a container on its chain: a
2891
- * source row naming it there, or a row the relation reaches that reveals that node. None is 404, and nothing is written.
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.
2892
3483
  */
2893
- async function lockRelationRow(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
3484
+ async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
2894
3485
  const now = new Date()
2895
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
+ }
2896
3500
  for (let index = 0; index < grant.relations.length; index++) {
2897
- const source = relationSource(context.relations, grant.relations[index] ?? '')
2898
- const candidates: { table: string; column: string; scope: OperationNode }[] = []
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)
2899
3505
  const node = nodeOf(source.dimension)
2900
- if (node !== undefined) {
2901
- const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, grant.principal)])
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)
2902
3511
  const active = activeRow(source, now)
2903
3512
  candidates[candidates.length] = {
2904
3513
  table: source.table,
@@ -2908,31 +3517,55 @@ async function lockRelationRow(transaction: Session, context: TableContext, gran
2908
3517
  }
2909
3518
  for (let position = 0; position < source.reveals.length; position++) {
2910
3519
  const reveal = source.reveals[position]
2911
- const held = reveal !== undefined && reveal.path === undefined && includes(reveal.actions, grant.action)
3520
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3521
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
2912
3522
  const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
2913
- if (reveal !== undefined && revealed !== undefined) {
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)
2914
3526
  candidates[candidates.length] = {
2915
3527
  table: reveal.table,
2916
3528
  column: reveal.column,
2917
- scope: revealAddress(source, reveal, revealed, grant.principal, now),
3529
+ scope: revealInside === undefined ? address : allOf([address, revealInside]),
2918
3530
  }
2919
3531
  }
2920
3532
  }
2921
- for (let position = 0; position < candidates.length; position++) {
2922
- const candidate = candidates[position]
2923
- if (candidate === undefined) continue
2924
- const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
2925
- root: 'SelectQueryNode',
2926
- table: candidate.table,
2927
- joins: {},
2928
- scope: candidate.scope,
2929
- lock: 'share',
2930
- subqueries: context.subqueries,
2931
- })
2932
- if (rows.length > 0) return
2933
- }
2934
3533
  }
2935
- throw new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
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))
2936
3569
  }
2937
3570
 
2938
3571
  /** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
@@ -2954,6 +3587,7 @@ async function revealHolds(
2954
3587
  dimension: string,
2955
3588
  node: string,
2956
3589
  principal: string,
3590
+ action: string,
2957
3591
  ): Promise<boolean> {
2958
3592
  if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
2959
3593
  throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
@@ -2961,8 +3595,9 @@ async function revealHolds(
2961
3595
  const source = relationSource(relations, relation)
2962
3596
  for (let index = 0; index < source.reveals.length; index++) {
2963
3597
  const reveal = source.reveals[index]
2964
- // A reveal matched through a secondary path holds reads under a Within only; no Ref is minted through it.
2965
- if (reveal === undefined || reveal.path !== undefined || reveal.dimension !== dimension) continue
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
2966
3601
  const address = revealAddress(source, reveal, node, principal, new Date())
2967
3602
  const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
2968
3603
  const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
@@ -2971,6 +3606,141 @@ async function revealHolds(
2971
3606
  return false
2972
3607
  }
2973
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
+
2974
3744
  /** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
2975
3745
  async function locateObject(
2976
3746
  models: TableModels,
@@ -2983,6 +3753,11 @@ async function locateObject(
2983
3753
  if (typeof id !== 'string' || id.length === 0) {
2984
3754
  throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
2985
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> {
2986
3761
  const key = keyOf(owner)
2987
3762
  const scope = equals(owner.name, key, id)
2988
3763
  const columns: string[] = [key]
@@ -2990,7 +3765,7 @@ async function locateObject(
2990
3765
  columns[columns.length] = owner.chain[index]?.column ?? ''
2991
3766
  }
2992
3767
  const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
2993
- const [row] = await (using ?? sessionOf(runtime)).run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
3768
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
2994
3769
  if (row === undefined) {
2995
3770
  return null
2996
3771
  }