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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/orm.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { uuidv7 } from '@fabrika/platform'
7
7
  import type { OperationNode } from 'kysely'
8
8
  import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
+ import { refScope } from './authority'
9
10
  import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
10
11
  import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
11
12
  import type { InvocationTransaction, Session } from './database'
@@ -23,7 +24,6 @@ import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError }
23
24
  import { answerFiles, type FileBinding } from './file-columns'
24
25
  import { databaseNow } from './job-leases'
25
26
  import { rearmClaim } from './job-wakes'
26
- import { linksPredicate, linkValues } from './links'
27
27
  import {
28
28
  aggregateNode,
29
29
  allOf,
@@ -42,7 +42,7 @@ import {
42
42
  withCursorColumns,
43
43
  } from './nodes'
44
44
  import type { DataKind, TargetForm, UnscopedMode } from './orm-types'
45
- import { modelOf, namesAction, type TableModels, updatableBy, visibleFor } from './policy'
45
+ import { accessTablesOf, delegates, modelOf, namesAction, type TableModels, updatableBy, visibleFor } from './policy'
46
46
  import { type SqlSite, type SqlTag, sqlTag } from './sql'
47
47
  import {
48
48
  actionShape,
@@ -50,6 +50,7 @@ import {
50
50
  type AggregateSpec,
51
51
  answer,
52
52
  appKeyPredicate,
53
+ appKeyScope,
53
54
  appListPredicate,
54
55
  appRecordPredicate,
55
56
  appRowPredicate,
@@ -71,7 +72,7 @@ import {
71
72
  prepareApplicationInsert,
72
73
  prepareChildInsert,
73
74
  prepareDimensionInsert,
74
- reachColumn,
75
+ reachedBy,
75
76
  reachPredicate,
76
77
  readValues,
77
78
  removeRow,
@@ -190,6 +191,7 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
190
191
  }
191
192
  return scopeTerms(parts.contextOf(table), capability, use)
192
193
  },
194
+ accessTablesOf(parts.models),
193
195
  )
194
196
  },
195
197
  })
@@ -327,7 +329,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
327
329
 
328
330
  /** The predicate of the target object, over the whole chain its `Ref` carries. */
329
331
  function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
330
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
332
+ return refScope(context.relations, context.model, selfLinks(context.model), grant, new Date())
331
333
  }
332
334
 
333
335
  function targetRow(
@@ -348,7 +350,14 @@ function targetRow(
348
350
  const scope = targetPredicate(context, grant)
349
351
  const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
350
352
  const session = await run.read()
351
- const rows = await session.run(node, { root: 'SelectQueryNode', table: context.model.name, joins: {}, scope, lock: 'update' })
353
+ const rows = await session.run(node, {
354
+ root: 'SelectQueryNode',
355
+ table: context.model.name,
356
+ joins: {},
357
+ scope,
358
+ lock: 'update',
359
+ subqueries: context.subqueries,
360
+ })
352
361
  const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
353
362
  if (row === undefined) {
354
363
  throw new NotFoundError(`${context.model.name} not found`)
@@ -393,8 +402,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
393
402
  if (typeof id !== 'string' || id.length === 0) {
394
403
  throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its ${key}, a non-empty string`)
395
404
  }
396
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
397
- return selectOne(context, run, scope, visibleFor(context.model, grant.action), grant.action)
405
+ return selectOne(context, run, parentPredicate(context, grant, id), visibleFor(context.model, grant.action), grant.action)
398
406
  }),
399
407
  insert: writing(
400
408
  site,
@@ -407,8 +415,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
407
415
  }
408
416
  const grant = updatingRef(context, capability, parent)
409
417
  const changes = readValues(values, updatableBy(context.model, grant.action), 'update', context.model)
410
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
411
- return updateRow(context, run, { scope }, changes, versionArgument(context, options))
418
+ return updateRow(context, run, { scope: parentPredicate(context, grant, id) }, changes, versionArgument(context, options))
412
419
  }),
413
420
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
414
421
  await removeRow(context, run, { scope: childObjectPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -421,7 +428,7 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
421
428
  return freeze({
422
429
  list: bound(site, async (options?: unknown) => {
423
430
  const grant = namedRef(context, capability, dimension)
424
- const scope = linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
431
+ const scope = refScope(context.relations, context.model, context.model.chain, grant, new Date())
425
432
  return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
426
433
  }),
427
434
  insert: writing(
@@ -453,9 +460,9 @@ function withinTables(parts: DataLayerParts, site: DataSite, run: Runner, capabi
453
460
  for (let index = 0; index < tables.length; index++) {
454
461
  const model = modelOf(parts.models, tables[index] ?? '')
455
462
  const listable = model?.scope.mode === 'dimension' || model?.scope.mode === 'child'
456
- if (model !== undefined && listable && reachColumn(model, grant.dimension) !== undefined) {
457
- const context = parts.contextOf(model.name)
458
- setOwn(handle, model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
463
+ const context = model !== undefined && listable ? parts.contextOf(model.name) : undefined
464
+ if (context !== undefined && reachedBy(context, grant.dimension)) {
465
+ setOwn(handle, context.model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
459
466
  }
460
467
  }
461
468
  return freeze(handle)
@@ -560,10 +567,11 @@ function scopedApplicationRows(context: TableContext, site: DataSite, run: Runne
560
567
  list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, heldAction(context, capability))),
561
568
  count: bound(site, async (options?: unknown) => countRows(context, run, scope(), visible, options)),
562
569
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, scope(), context.shape, spec)),
563
- get: bound(site, async (id: unknown) => {
564
- scope()
565
- return selectOne(context, run, appKeyPredicate(model, id), visible, heldAction(context, capability))
566
- }),
570
+ get: bound(
571
+ site,
572
+ async (id: unknown) =>
573
+ selectOne(context, run, scopedApplicationRead(context, capability, appKeyPredicate(model, id)), visible, heldAction(context, capability)),
574
+ ),
567
575
  })
568
576
  }
569
577
 
@@ -603,11 +611,11 @@ function applicationRows(
603
611
  : site.kind === 'query'
604
612
  ? refused(site, 'read_only', 'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation')
605
613
  : bound(site, async (id: unknown) => {
606
- const scope = appKeyPredicate(model, id)
607
614
  const action = namedApp(context, capability)
615
+ const scope = appKeyScope(model, action, id)
608
616
  const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
609
617
  const session = await run.read()
610
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
618
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update', subqueries: context.subqueries })
611
619
  const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
612
620
  if (row === undefined) {
613
621
  throw new NotFoundError(`${table} not found`)
@@ -628,7 +636,7 @@ function applicationRows(
628
636
  ),
629
637
  get: bound(site, async (id: unknown) => {
630
638
  const action = namedApp(context, capability)
631
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
639
+ return selectOne(context, run, appKeyScope(model, action, id), visibleFor(model, action), action)
632
640
  }),
633
641
  getForUpdate,
634
642
  claim: claiming(parts, context, site, capability),
@@ -640,7 +648,7 @@ function applicationRows(
640
648
  update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
641
649
  const grant = updatingApp(context, capability)
642
650
  const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
643
- return updateRow(context, run, { scope: appKeyPredicate(model, id) }, changes, versionArgument(context, options))
651
+ return updateRow(context, run, { scope: appKeyScope(model, grant.action, id) }, changes, versionArgument(context, options))
644
652
  }),
645
653
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
646
654
  await removeRow(context, run, { scope: appRowPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -682,7 +690,7 @@ function publicApplicationRows(
682
690
  get: bound(site, async (id: unknown) => {
683
691
  appListPredicate(context, capability)
684
692
  const action = heldAction(context, capability)
685
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
693
+ return selectOne(context, run, appKeyScope(model, action, id), visibleFor(model, action), action)
686
694
  }),
687
695
  getForUpdate: refusal('lock'),
688
696
  claim: refusal('claim'),
@@ -693,7 +701,7 @@ function publicApplicationRows(
693
701
  const saved = await updateRow<Readonly<Record<string, unknown>>>(
694
702
  context,
695
703
  run,
696
- { scope: appKeyPredicate(model, id) },
704
+ { scope: appKeyScope(model, grant.action, id) },
697
705
  changes,
698
706
  versionArgument(context, options),
699
707
  )
@@ -722,6 +730,17 @@ const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
722
730
  /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
723
731
  const CLAIM_REARM_MIN_MS = 1_000
724
732
 
733
+ /**
734
+ * When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
735
+ * at the next due row it would take but no sooner than a second after it, or never when it would take none.
736
+ */
737
+ export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
738
+ if (full) {
739
+ return new Date(now.getTime() + 1)
740
+ }
741
+ return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
742
+ }
743
+
725
744
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
726
745
  function backoffMs(tickMs: number, attempts: number): number {
727
746
  let backoff = tickMs
@@ -797,7 +816,14 @@ async function claimRows(
797
816
  const now = await databaseNow(session)
798
817
  const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
799
818
  const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
800
- const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
819
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
820
+ root: 'SelectQueryNode',
821
+ table,
822
+ joins: {},
823
+ scope,
824
+ lock: 'claim',
825
+ subqueries: context.subqueries,
826
+ })
801
827
  const byAttempts = new Map<number, string[]>()
802
828
  for (const row of rows) {
803
829
  const attempts = row[queue.attempts]
@@ -813,7 +839,7 @@ async function claimRows(
813
839
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
814
840
  const updated = await session.run<Readonly<Record<string, unknown>>>(
815
841
  updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
816
- { root: 'UpdateQueryNode', table, joins: {}, scope },
842
+ { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
817
843
  )
818
844
  for (const row of updated) {
819
845
  const id = row['id']
@@ -827,19 +853,25 @@ async function claimRows(
827
853
  // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
828
854
  const fence = runtime.capabilities.fence()
829
855
  if (fence !== null && rows.length > 0) {
830
- // A full claim left rows behind: due at once.
831
- let rearm: Date | null = new Date(now.getTime() + 1)
832
- if (rows.length < limit) {
856
+ const full = rows.length >= limit
857
+ let next: Date | null = null
858
+ if (!full) {
833
859
  const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
834
860
  const [row] = answerRows(
835
861
  dialect,
836
862
  table,
837
863
  rowColumnsOf(model),
838
- await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
864
+ await session.run<Readonly<Record<string, unknown>>>(later, {
865
+ root: 'SelectQueryNode',
866
+ table,
867
+ joins: {},
868
+ scope,
869
+ subqueries: context.subqueries,
870
+ }),
839
871
  )
840
- rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
872
+ next = row === undefined ? null : dueOf(row, table, queue.due)
841
873
  }
842
- await rearmClaim(runtime, session, fence, rearm)
874
+ await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
843
875
  }
844
876
  return {
845
877
  rows: await answerFiles(
@@ -996,6 +1028,17 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
996
1028
  return equals(table, keyOf(model), id)
997
1029
  }
998
1030
  const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
1031
+ if (model.view) {
1032
+ return refused(site, 'read_only', `${table} is a view, which no handler writes`)
1033
+ }
1034
+ // A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
1035
+ if (delegates(model)) {
1036
+ return refused(
1037
+ site,
1038
+ 'undeclared_reach',
1039
+ `${table} hands out access, so it is written through a capability only, never unscoped`,
1040
+ )
1041
+ }
999
1042
  if (mode === 'read') {
1000
1043
  const verb = operation === 'remove' ? 'remove' : operation
1001
1044
  return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
@@ -1014,7 +1057,7 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
1014
1057
  const dialect = dialectOf(context)
1015
1058
  const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
1016
1059
  const session = await run.read()
1017
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1060
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
1018
1061
  const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
1019
1062
  if (row === undefined) {
1020
1063
  throw new NotFoundError(`${table} not found`)
@@ -1277,6 +1320,8 @@ async function listRows(
1277
1320
  table,
1278
1321
  joins: {},
1279
1322
  scope,
1323
+ subqueries: context.subqueries,
1324
+ through: context.through,
1280
1325
  })
1281
1326
  const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1282
1327
  const last = page[page.length - 1]
@@ -1301,7 +1346,14 @@ async function countRows(
1301
1346
  return 0
1302
1347
  }
1303
1348
  const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
1304
- const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1349
+ const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
1350
+ root: 'SelectQueryNode',
1351
+ table,
1352
+ joins: {},
1353
+ scope,
1354
+ subqueries: context.subqueries,
1355
+ through: context.through,
1356
+ })
1305
1357
  const count = row === undefined ? '0' : row['count']
1306
1358
  return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
1307
1359
  }