@fabrika/db 0.9.0-dev.12 → 0.9.0-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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, 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, 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
  )
@@ -766,6 +774,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
766
774
  return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
767
775
  }
768
776
 
777
+ /**
778
+ * How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
779
+ * compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
780
+ * statement's size. Every chunk runs in the claim's one fenced transaction.
781
+ */
782
+ const CLAIM_UPDATE_IDS = 50
783
+
769
784
  /**
770
785
  * Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
771
786
  * attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
@@ -808,7 +823,14 @@ async function claimRows(
808
823
  const now = await databaseNow(session)
809
824
  const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
810
825
  const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
811
- const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
826
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
827
+ root: 'SelectQueryNode',
828
+ table,
829
+ joins: {},
830
+ scope,
831
+ lock: 'claim',
832
+ subqueries: context.subqueries,
833
+ })
812
834
  const byAttempts = new Map<number, string[]>()
813
835
  for (const row of rows) {
814
836
  const attempts = row[queue.attempts]
@@ -822,17 +844,20 @@ async function claimRows(
822
844
  for (const [attempts, ids] of byAttempts) {
823
845
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
824
846
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
825
- const updated = await session.run<Readonly<Record<string, unknown>>>(
826
- updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
827
- { root: 'UpdateQueryNode', table, joins: {}, scope },
828
- )
829
- for (const row of updated) {
830
- const id = row['id']
831
- const next = row['version']
832
- if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
833
- throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
847
+ for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
848
+ const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
849
+ const updated = await session.run<Readonly<Record<string, unknown>>>(
850
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
851
+ { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
852
+ )
853
+ for (const row of updated) {
854
+ const id = row['id']
855
+ const next = row['version']
856
+ if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
857
+ throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
858
+ }
859
+ claimed.set(id, { version: next, attempts: attempts + 1, due })
834
860
  }
835
- claimed.set(id, { version: next, attempts: attempts + 1, due })
836
861
  }
837
862
  }
838
863
  // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
@@ -846,7 +871,13 @@ async function claimRows(
846
871
  dialect,
847
872
  table,
848
873
  rowColumnsOf(model),
849
- await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
874
+ await session.run<Readonly<Record<string, unknown>>>(later, {
875
+ root: 'SelectQueryNode',
876
+ table,
877
+ joins: {},
878
+ scope,
879
+ subqueries: context.subqueries,
880
+ }),
850
881
  )
851
882
  next = row === undefined ? null : dueOf(row, table, queue.due)
852
883
  }
@@ -1010,6 +1041,14 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
1010
1041
  if (model.view) {
1011
1042
  return refused(site, 'read_only', `${table} is a view, which no handler writes`)
1012
1043
  }
1044
+ // A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
1045
+ if (delegates(model) || context.writers.length > 0) {
1046
+ return refused(
1047
+ site,
1048
+ 'undeclared_reach',
1049
+ `${table} hands out access, so it is written through a capability only, never unscoped`,
1050
+ )
1051
+ }
1013
1052
  if (mode === 'read') {
1014
1053
  const verb = operation === 'remove' ? 'remove' : operation
1015
1054
  return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
@@ -1028,7 +1067,7 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
1028
1067
  const dialect = dialectOf(context)
1029
1068
  const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
1030
1069
  const session = await run.read()
1031
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1070
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
1032
1071
  const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
1033
1072
  if (row === undefined) {
1034
1073
  throw new NotFoundError(`${table} not found`)
@@ -1291,6 +1330,8 @@ async function listRows(
1291
1330
  table,
1292
1331
  joins: {},
1293
1332
  scope,
1333
+ subqueries: context.subqueries,
1334
+ through: context.through,
1294
1335
  })
1295
1336
  const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1296
1337
  const last = page[page.length - 1]
@@ -1315,7 +1356,14 @@ async function countRows(
1315
1356
  return 0
1316
1357
  }
1317
1358
  const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
1318
- const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1359
+ const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
1360
+ root: 'SelectQueryNode',
1361
+ table,
1362
+ joins: {},
1363
+ scope,
1364
+ subqueries: context.subqueries,
1365
+ through: context.through,
1366
+ })
1319
1367
  const count = row === undefined ? '0' : row['count']
1320
1368
  return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
1321
1369
  }