@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +39 -4
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +56 -2
- package/src/codegen-sqlite.ts +194 -0
- package/src/codegen.ts +230 -41
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/database.ts +227 -61
- package/src/description.ts +37 -8
- package/src/errors.ts +10 -6
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +15 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +17 -1
- package/src/job-leases.ts +228 -55
- package/src/job-wakes.ts +600 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +210 -0
- package/src/migrations.ts +73 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +206 -71
- package/src/orm.ts +425 -170
- package/src/policy.ts +1979 -141
- package/src/postgres.ts +26 -0
- package/src/registry.ts +55 -3
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +247 -476
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +269 -0
- package/src/store.ts +2292 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +172 -6
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1351 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +55 -2
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +79 -5
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/description.d.ts +26 -8
- package/types/src/errors.d.ts +9 -6
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +12 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +5 -4
- package/types/src/job-leases.d.ts +40 -5
- package/types/src/job-wakes.d.ts +124 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +4 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +163 -71
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +351 -23
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +40 -3
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +143 -34
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +18 -2
- package/types/src/temporal.d.ts +24 -0
- package/types/src/testing-shared.d.ts +290 -0
- package/types/src/testing-sqlite.d.ts +37 -0
- package/types/src/testing.d.ts +2 -93
- package/types/src/vocabulary-tables.d.ts +169 -22
package/src/orm.ts
CHANGED
|
@@ -3,16 +3,28 @@
|
|
|
3
3
|
// is that invocation, then refuses what the site may not do with the message its types give, then runs the store's
|
|
4
4
|
// own checks of kind, dimension and action against the capability.
|
|
5
5
|
|
|
6
|
+
import { uuidv7 } from '@fabrika/platform'
|
|
6
7
|
import type { OperationNode } from 'kysely'
|
|
7
8
|
import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
|
|
9
|
+
import { refScope } from './authority'
|
|
8
10
|
import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
|
|
9
11
|
import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
|
|
10
12
|
import type { InvocationTransaction, Session } from './database'
|
|
11
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
columnOf,
|
|
15
|
+
comparableColumnOf,
|
|
16
|
+
type Compare,
|
|
17
|
+
type Contains,
|
|
18
|
+
parseCondition,
|
|
19
|
+
type Primitive,
|
|
20
|
+
type SelectState,
|
|
21
|
+
type TableShape,
|
|
22
|
+
} from './description'
|
|
12
23
|
import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
|
|
13
24
|
import { answerFiles, type FileBinding } from './file-columns'
|
|
14
25
|
import { databaseNow } from './job-leases'
|
|
15
|
-
import {
|
|
26
|
+
import { rearmClaim } from './job-wakes'
|
|
27
|
+
import { cursorKey, type CursorValue, openCursor, signCursor } from './list-cursor'
|
|
16
28
|
import {
|
|
17
29
|
aggregateNode,
|
|
18
30
|
allOf,
|
|
@@ -24,28 +36,48 @@ import {
|
|
|
24
36
|
everything,
|
|
25
37
|
inList,
|
|
26
38
|
lockedSelectNode,
|
|
39
|
+
nextClaimNode,
|
|
27
40
|
scopedWhere,
|
|
28
41
|
selectNode,
|
|
29
42
|
updateNode,
|
|
30
43
|
withCursorColumns,
|
|
31
44
|
} from './nodes'
|
|
32
45
|
import type { DataKind, TargetForm, UnscopedMode } from './orm-types'
|
|
33
|
-
import {
|
|
46
|
+
import {
|
|
47
|
+
accessTablesOf,
|
|
48
|
+
delegates,
|
|
49
|
+
modelOf,
|
|
50
|
+
namesAction,
|
|
51
|
+
type ReadReach,
|
|
52
|
+
soleReach,
|
|
53
|
+
type TableModels,
|
|
54
|
+
updatableBy,
|
|
55
|
+
visibleFor,
|
|
56
|
+
visibleThrough,
|
|
57
|
+
} from './policy'
|
|
34
58
|
import { type SqlSite, type SqlTag, sqlTag } from './sql'
|
|
35
59
|
import {
|
|
36
60
|
actionShape,
|
|
37
61
|
aggregateRows,
|
|
38
62
|
type AggregateSpec,
|
|
39
63
|
answer,
|
|
64
|
+
appGetScope,
|
|
40
65
|
appKeyPredicate,
|
|
66
|
+
appKeyScope,
|
|
41
67
|
appListPredicate,
|
|
42
|
-
|
|
68
|
+
appListRead,
|
|
69
|
+
type AppRead,
|
|
70
|
+
appRecordRead,
|
|
43
71
|
appRowPredicate,
|
|
72
|
+
appUpdate,
|
|
73
|
+
boundTerms,
|
|
74
|
+
boundValues,
|
|
44
75
|
childObjectPredicate,
|
|
45
76
|
childScope,
|
|
46
77
|
claimedRowPredicate,
|
|
47
78
|
claimScope,
|
|
48
79
|
type DataLayerRuntime,
|
|
80
|
+
dialectOf,
|
|
49
81
|
heldAction,
|
|
50
82
|
insertPrepared,
|
|
51
83
|
insertRow,
|
|
@@ -56,10 +88,11 @@ import {
|
|
|
56
88
|
prepareApplicationInsert,
|
|
57
89
|
prepareChildInsert,
|
|
58
90
|
prepareDimensionInsert,
|
|
59
|
-
|
|
91
|
+
reachedBy,
|
|
60
92
|
reachPredicate,
|
|
61
93
|
readValues,
|
|
62
94
|
removeRow,
|
|
95
|
+
rowColumnsOf,
|
|
63
96
|
type Runner,
|
|
64
97
|
runtimeOf,
|
|
65
98
|
scopedApplicationRead,
|
|
@@ -68,15 +101,20 @@ import {
|
|
|
68
101
|
selfLinks,
|
|
69
102
|
type TableContext,
|
|
70
103
|
updateRow,
|
|
71
|
-
updatingApp,
|
|
72
104
|
updatingRef,
|
|
73
105
|
versionArgument,
|
|
74
106
|
} from './store'
|
|
75
|
-
import {
|
|
107
|
+
import { answerRows, timestampInput } from './temporal'
|
|
76
108
|
|
|
77
109
|
/** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
|
|
78
110
|
export const DEFAULT_LIST_LIMIT = 50
|
|
79
111
|
export const MAX_LIST_LIMIT = 500
|
|
112
|
+
/**
|
|
113
|
+
* The most rows `all()` answers; past it, it refuses instead of truncating. It bounds rows, not bytes: 10 000 rows of
|
|
114
|
+
* ~1 KB, held two or three times over (driver, answer, response), is tens of MB of the one 128 MB Durable Object
|
|
115
|
+
* isolate every concurrent invocation of the environment shares. Wide rows or a growing set page with `list`.
|
|
116
|
+
*/
|
|
117
|
+
export const MAX_ALL_ROWS = 10_000
|
|
80
118
|
|
|
81
119
|
/** The framework's own tables; no declaration reaches one. */
|
|
82
120
|
const FRAMEWORK_PREFIX = 'fabrika_'
|
|
@@ -102,6 +140,11 @@ export interface DataSite {
|
|
|
102
140
|
* only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
|
|
103
141
|
*/
|
|
104
142
|
readonly files?: FileBinding
|
|
143
|
+
/**
|
|
144
|
+
* The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
|
|
145
|
+
* answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
|
|
146
|
+
*/
|
|
147
|
+
readonly holds?: readonly string[]
|
|
105
148
|
/** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
|
|
106
149
|
readonly carried?: ReadonlySet<string>
|
|
107
150
|
/** Throws unless the work running now is the invocation these handles were made for. */
|
|
@@ -126,6 +169,11 @@ export interface DataHandles {
|
|
|
126
169
|
readonly reference: object
|
|
127
170
|
/** `ctx.db.unscoped`, or `undefined` for a site that declares none. */
|
|
128
171
|
readonly unscoped: object | undefined
|
|
172
|
+
/**
|
|
173
|
+
* At most two rows of `table` whose `column` holds `value`, as an unscoped read answers them: the framework's read of
|
|
174
|
+
* the caller's own row (`ctx.caller` of `@fabrika/app`). No handle of an application reaches it.
|
|
175
|
+
*/
|
|
176
|
+
rowsNaming(table: string, column: string, value: string): Promise<readonly Readonly<Record<string, unknown>>[]>
|
|
129
177
|
}
|
|
130
178
|
|
|
131
179
|
/** The data side of one bound layer, which only the framework reaches (`@fabrika/db/framework`). */
|
|
@@ -158,22 +206,20 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
|
|
|
158
206
|
direct: () => parts.newSession(parts.runtime()),
|
|
159
207
|
transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
|
|
160
208
|
handles: (site: DataSite) => handlesOf(parts, site),
|
|
161
|
-
sql: (site: SqlSite) =>
|
|
162
|
-
|
|
209
|
+
sql: (site: SqlSite) => {
|
|
210
|
+
const database = parts.runtime().database
|
|
211
|
+
return sqlTag(
|
|
163
212
|
site,
|
|
164
|
-
|
|
165
|
-
(capability, table, use
|
|
213
|
+
database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
|
|
214
|
+
(capability, table, use) => {
|
|
166
215
|
if (!hasOwn(parts.models, table)) {
|
|
167
216
|
throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
|
|
168
217
|
}
|
|
169
|
-
return scopeTerms(parts.contextOf(table), capability, use
|
|
170
|
-
},
|
|
171
|
-
(table) => {
|
|
172
|
-
if (modelOf(parts.models, table)?.scope.mode === 'reference') {
|
|
173
|
-
throw new QueryRefusedError('read_only', `ctx.sql: ${table} is a reference table, which no statement writes: its rows come from a migration`)
|
|
174
|
-
}
|
|
218
|
+
return scopeTerms(parts.contextOf(table), capability, use)
|
|
175
219
|
},
|
|
176
|
-
|
|
220
|
+
accessTablesOf(parts.models),
|
|
221
|
+
)
|
|
222
|
+
},
|
|
177
223
|
})
|
|
178
224
|
}
|
|
179
225
|
|
|
@@ -259,6 +305,24 @@ function handlesOf(parts: DataLayerParts, site: DataSite): DataHandles {
|
|
|
259
305
|
},
|
|
260
306
|
reference: referenceTables(parts, site, run),
|
|
261
307
|
unscoped,
|
|
308
|
+
rowsNaming: async (table: string, column: string, value: string) => {
|
|
309
|
+
site.check()
|
|
310
|
+
const model = table.startsWith(FRAMEWORK_PREFIX) ? undefined : modelOf(parts.models, table)
|
|
311
|
+
if (model === undefined) {
|
|
312
|
+
throw new QueryRefusedError('unknown_table', `the caller's table ${table} is not a table of src/db/tables.ts`)
|
|
313
|
+
}
|
|
314
|
+
const keyed = model.scope.mode === 'dimension' || model.scope.mode === 'child' || model.scope.mode === 'app'
|
|
315
|
+
const page = await listRows(
|
|
316
|
+
parts.contextOf(table),
|
|
317
|
+
run,
|
|
318
|
+
everything(),
|
|
319
|
+
model.visible,
|
|
320
|
+
{ where: [[column, '=', value]], limit: 2 },
|
|
321
|
+
keyed ? [keyOf(model)] : model.visible,
|
|
322
|
+
soleReach(model.actions.read[0] ?? ''),
|
|
323
|
+
)
|
|
324
|
+
return page.items
|
|
325
|
+
},
|
|
262
326
|
})
|
|
263
327
|
}
|
|
264
328
|
|
|
@@ -309,7 +373,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
|
|
|
309
373
|
|
|
310
374
|
/** The predicate of the target object, over the whole chain its `Ref` carries. */
|
|
311
375
|
function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
|
|
312
|
-
return
|
|
376
|
+
return refScope(context, context.model, selfLinks(context.model), grant, new Date())
|
|
313
377
|
}
|
|
314
378
|
|
|
315
379
|
function targetRow(
|
|
@@ -323,19 +387,26 @@ function targetRow(
|
|
|
323
387
|
const onOnly = (operation: string) => `${operation} acts on one object: declare access with on`
|
|
324
388
|
const get = bound(site, async () => {
|
|
325
389
|
const grant = namedRef(context, capability, dimension)
|
|
326
|
-
return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), grant.action)
|
|
390
|
+
return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), soleReach(grant.action))
|
|
327
391
|
})
|
|
328
392
|
const lock = bound(site, async () => {
|
|
329
393
|
const grant = namedRef(context, capability, dimension)
|
|
330
394
|
const scope = targetPredicate(context, grant)
|
|
331
395
|
const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
|
|
332
396
|
const session = await run.read()
|
|
333
|
-
const rows = await session.run(node, {
|
|
334
|
-
|
|
397
|
+
const rows = await session.run(node, {
|
|
398
|
+
root: 'SelectQueryNode',
|
|
399
|
+
table: context.model.name,
|
|
400
|
+
joins: {},
|
|
401
|
+
scope,
|
|
402
|
+
lock: 'update',
|
|
403
|
+
subqueries: context.subqueries,
|
|
404
|
+
})
|
|
405
|
+
const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
|
|
335
406
|
if (row === undefined) {
|
|
336
407
|
throw new NotFoundError(`${context.model.name} not found`)
|
|
337
408
|
}
|
|
338
|
-
await answerFiles(context.model, run.files, session, [row], grant.action)
|
|
409
|
+
await answerFiles(context.model, run.files, session, [row], soleReach(grant.action))
|
|
339
410
|
return row
|
|
340
411
|
})
|
|
341
412
|
const getForUpdate = site.kind === 'job'
|
|
@@ -368,15 +439,18 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
|
|
|
368
439
|
return freeze({
|
|
369
440
|
list: bound(site, async (options?: unknown) => {
|
|
370
441
|
const grant = namedRef(context, capability, parent)
|
|
371
|
-
return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], grant.action)
|
|
442
|
+
return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
|
|
443
|
+
}),
|
|
444
|
+
all: bound(site, async (options?: unknown) => {
|
|
445
|
+
const grant = namedRef(context, capability, parent)
|
|
446
|
+
return allRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
|
|
372
447
|
}),
|
|
373
448
|
get: bound(site, async (id: unknown) => {
|
|
374
449
|
const grant = namedRef(context, capability, parent)
|
|
375
450
|
if (typeof id !== 'string' || id.length === 0) {
|
|
376
451
|
throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its ${key}, a non-empty string`)
|
|
377
452
|
}
|
|
378
|
-
|
|
379
|
-
return selectOne(context, run, scope, visibleFor(context.model, grant.action), grant.action)
|
|
453
|
+
return selectOne(context, run, parentPredicate(context, grant, id), visibleFor(context.model, grant.action), soleReach(grant.action))
|
|
380
454
|
}),
|
|
381
455
|
insert: writing(
|
|
382
456
|
site,
|
|
@@ -389,8 +463,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
|
|
|
389
463
|
}
|
|
390
464
|
const grant = updatingRef(context, capability, parent)
|
|
391
465
|
const changes = readValues(values, updatableBy(context.model, grant.action), 'update', context.model)
|
|
392
|
-
|
|
393
|
-
return updateRow(context, run, { scope }, changes, versionArgument(context, options))
|
|
466
|
+
return updateRow(context, run, { scope: parentPredicate(context, grant, id) }, changes, versionArgument(context, options))
|
|
394
467
|
}),
|
|
395
468
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
396
469
|
await removeRow(context, run, { scope: childObjectPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
|
|
@@ -403,8 +476,13 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
|
|
|
403
476
|
return freeze({
|
|
404
477
|
list: bound(site, async (options?: unknown) => {
|
|
405
478
|
const grant = namedRef(context, capability, dimension)
|
|
406
|
-
const scope =
|
|
407
|
-
return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
|
|
479
|
+
const scope = refScope(context, context.model, context.model.chain, grant, new Date())
|
|
480
|
+
return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
|
|
481
|
+
}),
|
|
482
|
+
all: bound(site, async (options?: unknown) => {
|
|
483
|
+
const grant = namedRef(context, capability, dimension)
|
|
484
|
+
const scope = refScope(context, context.model, context.model.chain, grant, new Date())
|
|
485
|
+
return allRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
|
|
408
486
|
}),
|
|
409
487
|
insert: writing(
|
|
410
488
|
site,
|
|
@@ -435,9 +513,9 @@ function withinTables(parts: DataLayerParts, site: DataSite, run: Runner, capabi
|
|
|
435
513
|
for (let index = 0; index < tables.length; index++) {
|
|
436
514
|
const model = modelOf(parts.models, tables[index] ?? '')
|
|
437
515
|
const listable = model?.scope.mode === 'dimension' || model?.scope.mode === 'child'
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
setOwn(handle, model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
|
|
516
|
+
const context = model !== undefined && listable ? parts.contextOf(model.name) : undefined
|
|
517
|
+
if (context !== undefined && reachedBy(context, grant.dimension)) {
|
|
518
|
+
setOwn(handle, context.model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
|
|
441
519
|
}
|
|
442
520
|
}
|
|
443
521
|
return freeze(handle)
|
|
@@ -461,7 +539,11 @@ function listedRows(
|
|
|
461
539
|
claim: claiming(parts, context, site, capability),
|
|
462
540
|
list: bound(site, async (options?: unknown) => {
|
|
463
541
|
const predicate = scope()
|
|
464
|
-
return listRows(context, run, predicate, visible(), options, key, heldAction(context, capability))
|
|
542
|
+
return listRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
|
|
543
|
+
}),
|
|
544
|
+
all: bound(site, async (options?: unknown) => {
|
|
545
|
+
const predicate = scope()
|
|
546
|
+
return allRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
|
|
465
547
|
}),
|
|
466
548
|
count: bound(site, async (options?: unknown) => {
|
|
467
549
|
const predicate = scope()
|
|
@@ -491,31 +573,37 @@ function applicationTables(parts: DataLayerParts, site: DataSite, run: Runner, c
|
|
|
491
573
|
const rows = applicationRows(parts, context, site, run, capability)
|
|
492
574
|
setOwn(handle, model.name, site.public === true ? publicApplicationRows(context, site, run, capability, rows) : freeze(rows))
|
|
493
575
|
} else if (site.public !== true && (model.scope.mode === 'dimension' || model.scope.mode === 'child')) {
|
|
494
|
-
setOwn(handle, model.name, appRecordRows(context, site, run, capability
|
|
576
|
+
setOwn(handle, model.name, appRecordRows(context, site, run, capability))
|
|
495
577
|
}
|
|
496
578
|
}
|
|
497
579
|
return freeze(handle)
|
|
498
580
|
}
|
|
499
581
|
|
|
500
582
|
/**
|
|
501
|
-
* A dimension or child table under an `app` capability
|
|
502
|
-
*
|
|
583
|
+
* A dimension or child table under an `app` capability, read-only and every row, with the columns its reaching actions
|
|
584
|
+
* read alone (`visibleThrough`): listed and aggregated with its read action or an action of its `appRead`, counted with
|
|
503
585
|
* those or an action of its `appCount`.
|
|
504
586
|
*/
|
|
505
|
-
function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown
|
|
506
|
-
const
|
|
507
|
-
const
|
|
508
|
-
const key = [keyOf(context.model)]
|
|
587
|
+
function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown): object {
|
|
588
|
+
const model = context.model
|
|
589
|
+
const key = [keyOf(model)]
|
|
509
590
|
return freeze({
|
|
510
|
-
list: bound(
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
),
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
)
|
|
591
|
+
list: bound(site, async (options?: unknown) => {
|
|
592
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
593
|
+
return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
594
|
+
}),
|
|
595
|
+
all: bound(site, async (options?: unknown) => {
|
|
596
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
597
|
+
return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
598
|
+
}),
|
|
599
|
+
count: bound(site, async (options?: unknown) => {
|
|
600
|
+
const { predicate, reach } = appRecordRead(context, capability, 'counts')
|
|
601
|
+
return countRows(context, run, predicate, visibleThrough(model, reach), options)
|
|
602
|
+
}),
|
|
603
|
+
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
|
|
604
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
605
|
+
return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
|
|
606
|
+
}),
|
|
519
607
|
})
|
|
520
608
|
}
|
|
521
609
|
|
|
@@ -539,30 +627,55 @@ function scopedApplicationRows(context: TableContext, site: DataSite, run: Runne
|
|
|
539
627
|
const key = [keyOf(model)]
|
|
540
628
|
const scope = () => scopedApplicationRead(context, capability)
|
|
541
629
|
return freeze({
|
|
542
|
-
list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, heldAction(context, capability))),
|
|
630
|
+
list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
|
|
631
|
+
all: bound(site, async (options?: unknown) => allRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
|
|
543
632
|
count: bound(site, async (options?: unknown) => countRows(context, run, scope(), visible, options)),
|
|
544
633
|
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, scope(), context.shape, spec)),
|
|
545
|
-
get: bound(
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
634
|
+
get: bound(
|
|
635
|
+
site,
|
|
636
|
+
async (id: unknown) =>
|
|
637
|
+
selectOne(
|
|
638
|
+
context,
|
|
639
|
+
run,
|
|
640
|
+
scopedApplicationRead(context, capability, appKeyPredicate(model, id)),
|
|
641
|
+
visible,
|
|
642
|
+
soleReach(heldAction(context, capability)),
|
|
643
|
+
),
|
|
644
|
+
),
|
|
549
645
|
})
|
|
550
646
|
}
|
|
551
647
|
|
|
552
|
-
/**
|
|
553
|
-
|
|
648
|
+
/**
|
|
649
|
+
* The row `key` names, for an `app` capability with an action the application table names, or any but a public
|
|
650
|
+
* procedure's on a table read with `'any'`: within the conditions of the actions it holds that the table names, any one
|
|
651
|
+
* admitting the row, and with the columns they read alone (`visibleThrough`).
|
|
652
|
+
*/
|
|
653
|
+
function namedAppRead(context: TableContext, capability: unknown, key: unknown): AppRead {
|
|
554
654
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
555
|
-
const
|
|
655
|
+
const model = context.model
|
|
656
|
+
const table = model.name
|
|
556
657
|
if (grant.kind !== 'app') {
|
|
557
658
|
throw new CapabilityError('wrong_capability', `a read of ${table} here needs the capability of an app endpoint, got ${describeGrant(grant)}`)
|
|
558
659
|
}
|
|
559
|
-
if (
|
|
660
|
+
if (model.actions.readAny) {
|
|
661
|
+
// Refuses a public procedure's grant, which reads no table read with 'any'.
|
|
662
|
+
appListPredicate(context, capability)
|
|
663
|
+
return { predicate: appGetScope(model, grant.actions, key), reach: freeze({ actions: grant.actions, narrowed: false }) }
|
|
664
|
+
}
|
|
665
|
+
const named: string[] = []
|
|
666
|
+
for (let index = 0; index < grant.actions.length; index++) {
|
|
667
|
+
const action = grant.actions[index]
|
|
668
|
+
if (action !== undefined && namesAction(model, action)) {
|
|
669
|
+
named[named.length] = action
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (named.length === 0) {
|
|
560
673
|
throw new CapabilityError(
|
|
561
674
|
'wrong_action',
|
|
562
|
-
`${table} does not name the action '${grant.
|
|
675
|
+
`${table} does not name the action '${grant.actions.join("', '")}': read it from an app endpoint whose action ${table} names`,
|
|
563
676
|
)
|
|
564
677
|
}
|
|
565
|
-
return
|
|
678
|
+
return { predicate: appGetScope(model, named, key), reach: freeze({ actions: named, narrowed: true }) }
|
|
566
679
|
}
|
|
567
680
|
|
|
568
681
|
/**
|
|
@@ -578,39 +691,43 @@ function applicationRows(
|
|
|
578
691
|
): Readonly<Record<string, unknown>> {
|
|
579
692
|
const model = context.model
|
|
580
693
|
const table = model.name
|
|
581
|
-
const visible = () => visibleFor(model, heldAction(context, capability))
|
|
582
694
|
const key = [keyOf(model)]
|
|
583
695
|
const getForUpdate = site.kind === 'job'
|
|
584
696
|
? refused(site, 'read_only', 'a job writes inside ctx.transaction((tx) => …): use tx.db there')
|
|
585
697
|
: site.kind === 'query'
|
|
586
698
|
? refused(site, 'read_only', 'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation')
|
|
587
699
|
: bound(site, async (id: unknown) => {
|
|
588
|
-
const scope =
|
|
589
|
-
const
|
|
590
|
-
const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
|
|
700
|
+
const { predicate: scope, reach } = namedAppRead(context, capability, id)
|
|
701
|
+
const node = lockedSelectNode(table, visibleThrough(model, reach), scope, model.dates)
|
|
591
702
|
const session = await run.read()
|
|
592
|
-
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
|
|
593
|
-
const [row] =
|
|
703
|
+
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update', subqueries: context.subqueries })
|
|
704
|
+
const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
|
|
594
705
|
if (row === undefined) {
|
|
595
706
|
throw new NotFoundError(`${table} not found`)
|
|
596
707
|
}
|
|
597
|
-
await answerFiles(model, run.files, session, [row],
|
|
708
|
+
await answerFiles(model, run.files, session, [row], reach)
|
|
598
709
|
return row
|
|
599
710
|
})
|
|
600
711
|
return {
|
|
601
|
-
list: bound(
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
)
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
712
|
+
list: bound(site, async (options?: unknown) => {
|
|
713
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
714
|
+
return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
715
|
+
}),
|
|
716
|
+
all: bound(site, async (options?: unknown) => {
|
|
717
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
718
|
+
return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
719
|
+
}),
|
|
720
|
+
count: bound(site, async (options?: unknown) => {
|
|
721
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
722
|
+
return countRows(context, run, predicate, visibleThrough(model, reach), options)
|
|
723
|
+
}),
|
|
724
|
+
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
|
|
725
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
726
|
+
return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
|
|
727
|
+
}),
|
|
611
728
|
get: bound(site, async (id: unknown) => {
|
|
612
|
-
const
|
|
613
|
-
return selectOne(context, run,
|
|
729
|
+
const { predicate, reach } = namedAppRead(context, capability, id)
|
|
730
|
+
return selectOne(context, run, predicate, visibleThrough(model, reach), reach)
|
|
614
731
|
}),
|
|
615
732
|
getForUpdate,
|
|
616
733
|
claim: claiming(parts, context, site, capability),
|
|
@@ -620,9 +737,8 @@ function applicationRows(
|
|
|
620
737
|
async (values: unknown, options?: unknown) => insertPrepared(context, run, prepareApplicationInsert(context, capability, values, options)),
|
|
621
738
|
),
|
|
622
739
|
update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
|
|
623
|
-
const
|
|
624
|
-
|
|
625
|
-
return updateRow(context, run, { scope: appKeyPredicate(model, id) }, changes, versionArgument(context, options))
|
|
740
|
+
const { scope, changes } = appUpdate(context, capability, id, values)
|
|
741
|
+
return updateRow(context, run, { scope }, changes, versionArgument(context, options))
|
|
626
742
|
}),
|
|
627
743
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
628
744
|
await removeRow(context, run, { scope: appRowPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
|
|
@@ -659,26 +775,24 @@ function publicApplicationRows(
|
|
|
659
775
|
}
|
|
660
776
|
return freeze({
|
|
661
777
|
list: rows['list'],
|
|
778
|
+
all: bound(site, async () => {
|
|
779
|
+
// The table's own read refusal first, as list answers it, so the message never points to a list it refuses too.
|
|
780
|
+
appListPredicate(context, capability)
|
|
781
|
+
throw new QueryRefusedError('public_reach', 'a public procedure pages its reads: read the table with list')
|
|
782
|
+
}),
|
|
662
783
|
count: rows['count'],
|
|
663
784
|
aggregate: rows['aggregate'],
|
|
664
785
|
get: bound(site, async (id: unknown) => {
|
|
665
786
|
appListPredicate(context, capability)
|
|
666
787
|
const action = heldAction(context, capability)
|
|
667
|
-
return selectOne(context, run,
|
|
788
|
+
return selectOne(context, run, appKeyScope(model, [action], id), visibleFor(model, action), soleReach(action))
|
|
668
789
|
}),
|
|
669
790
|
getForUpdate: refusal('lock'),
|
|
670
791
|
claim: refusal('claim'),
|
|
671
792
|
update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
|
|
672
793
|
tokenRow('update', id)
|
|
673
|
-
const
|
|
674
|
-
const
|
|
675
|
-
const saved = await updateRow<Readonly<Record<string, unknown>>>(
|
|
676
|
-
context,
|
|
677
|
-
run,
|
|
678
|
-
{ scope: appKeyPredicate(model, id) },
|
|
679
|
-
changes,
|
|
680
|
-
versionArgument(context, options),
|
|
681
|
-
)
|
|
794
|
+
const { scope, changes } = appUpdate(context, capability, id, values)
|
|
795
|
+
const saved = await updateRow<Readonly<Record<string, unknown>>>(context, run, { scope }, changes, versionArgument(context, options))
|
|
682
796
|
return freeze({ version: saved['version'] })
|
|
683
797
|
}),
|
|
684
798
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
@@ -701,6 +815,19 @@ function publicApplicationRows(
|
|
|
701
815
|
const DEFAULT_TICK_MS = 60_000
|
|
702
816
|
/** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
|
|
703
817
|
const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
|
|
818
|
+
/** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
|
|
819
|
+
const CLAIM_REARM_MIN_MS = 1_000
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
|
|
823
|
+
* at the next due row it would take but no sooner than a second after it, or never when it would take none.
|
|
824
|
+
*/
|
|
825
|
+
export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
|
|
826
|
+
if (full) {
|
|
827
|
+
return new Date(now.getTime() + 1)
|
|
828
|
+
}
|
|
829
|
+
return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
|
|
830
|
+
}
|
|
704
831
|
|
|
705
832
|
/** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
|
|
706
833
|
function backoffMs(tickMs: number, attempts: number): number {
|
|
@@ -711,6 +838,15 @@ function backoffMs(tickMs: number, attempts: number): number {
|
|
|
711
838
|
return Math.min(backoff, MAX_BACKOFF_MS)
|
|
712
839
|
}
|
|
713
840
|
|
|
841
|
+
/** A queue row's due time as the layer answers it. */
|
|
842
|
+
function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
|
|
843
|
+
const due = row[column]
|
|
844
|
+
if (!(due instanceof Date)) {
|
|
845
|
+
throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
|
|
846
|
+
}
|
|
847
|
+
return due
|
|
848
|
+
}
|
|
849
|
+
|
|
714
850
|
/** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
|
|
715
851
|
function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
|
|
716
852
|
if (site.kind === 'query') {
|
|
@@ -726,6 +862,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
|
|
|
726
862
|
return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
|
|
727
863
|
}
|
|
728
864
|
|
|
865
|
+
/**
|
|
866
|
+
* How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
|
|
867
|
+
* compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
|
|
868
|
+
* statement's size. Every chunk runs in the claim's one fenced transaction.
|
|
869
|
+
*/
|
|
870
|
+
const CLAIM_UPDATE_IDS = 50
|
|
871
|
+
|
|
729
872
|
/**
|
|
730
873
|
* Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
|
|
731
874
|
* attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
|
|
@@ -740,7 +883,7 @@ async function claimRows(
|
|
|
740
883
|
): Promise<readonly Readonly<Record<string, unknown>>[]> {
|
|
741
884
|
const model = context.model
|
|
742
885
|
const table = model.name
|
|
743
|
-
const { grant, scope } = claimScope(context, capability)
|
|
886
|
+
const { grant, action, scope } = claimScope(context, capability)
|
|
744
887
|
const queue = model.queue
|
|
745
888
|
const version = model.version
|
|
746
889
|
if (queue === undefined || version === undefined) {
|
|
@@ -751,26 +894,31 @@ async function claimRows(
|
|
|
751
894
|
throw new QueryRefusedError('list_page', 'claim takes { limit }: attempts count claims, so claim only what the run will reach')
|
|
752
895
|
}
|
|
753
896
|
const limit = limitOf(options['limit'])
|
|
754
|
-
const visible = visibleFor(model,
|
|
755
|
-
const conditions = conditionsOf(actionShape(model, visible), options['where'])
|
|
756
|
-
if (scope === undefined) {
|
|
897
|
+
const visible = visibleFor(model, action)
|
|
898
|
+
const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
|
|
899
|
+
if (scope === undefined || conditions === undefined) {
|
|
757
900
|
return []
|
|
758
901
|
}
|
|
902
|
+
const dialect = dialectOf(context)
|
|
759
903
|
const key = keyOf(model)
|
|
760
904
|
const chain = model.chain.map((link) => link.column)
|
|
761
905
|
const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
|
|
762
906
|
const tickMs = site.tickMs ?? DEFAULT_TICK_MS
|
|
763
|
-
const
|
|
764
|
-
const
|
|
907
|
+
const byDue = { column: queue.due, direction: 'asc' as const }
|
|
908
|
+
const order = [byDue, { column: key, direction: 'asc' as const }]
|
|
909
|
+
const runtime = parts.runtime()
|
|
910
|
+
const leased = await parts.fenced(runtime, async (session) => {
|
|
765
911
|
const now = await databaseNow(session)
|
|
766
|
-
const
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
912
|
+
const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
|
|
913
|
+
const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
|
|
914
|
+
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
915
|
+
root: 'SelectQueryNode',
|
|
916
|
+
table,
|
|
917
|
+
joins: {},
|
|
770
918
|
scope,
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
919
|
+
lock: 'claim',
|
|
920
|
+
subqueries: context.subqueries,
|
|
921
|
+
})
|
|
774
922
|
const byAttempts = new Map<number, string[]>()
|
|
775
923
|
for (const row of rows) {
|
|
776
924
|
const attempts = row[queue.attempts]
|
|
@@ -784,20 +932,56 @@ async function claimRows(
|
|
|
784
932
|
for (const [attempts, ids] of byAttempts) {
|
|
785
933
|
const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
|
|
786
934
|
const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
const
|
|
794
|
-
|
|
795
|
-
|
|
935
|
+
for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
|
|
936
|
+
const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
|
|
937
|
+
const updated = await session.run<Readonly<Record<string, unknown>>>(
|
|
938
|
+
updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
|
|
939
|
+
{ root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
|
|
940
|
+
)
|
|
941
|
+
for (const row of updated) {
|
|
942
|
+
const id = row['id']
|
|
943
|
+
const next = row['version']
|
|
944
|
+
if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
|
|
945
|
+
throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
|
|
946
|
+
}
|
|
947
|
+
claimed.set(id, { version: next, attempts: attempts + 1, due })
|
|
796
948
|
}
|
|
797
|
-
claimed.set(id, { version: next, attempts: attempts + 1, due })
|
|
798
949
|
}
|
|
799
950
|
}
|
|
800
|
-
|
|
951
|
+
// The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
|
|
952
|
+
const fence = runtime.capabilities.fence()
|
|
953
|
+
if (fence !== null && rows.length > 0) {
|
|
954
|
+
const full = rows.length >= limit
|
|
955
|
+
let next: Date | null = null
|
|
956
|
+
if (!full) {
|
|
957
|
+
const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
|
|
958
|
+
const [row] = answerRows(
|
|
959
|
+
dialect,
|
|
960
|
+
table,
|
|
961
|
+
rowColumnsOf(model),
|
|
962
|
+
await session.run<Readonly<Record<string, unknown>>>(later, {
|
|
963
|
+
root: 'SelectQueryNode',
|
|
964
|
+
table,
|
|
965
|
+
joins: {},
|
|
966
|
+
scope,
|
|
967
|
+
subqueries: context.subqueries,
|
|
968
|
+
}),
|
|
969
|
+
)
|
|
970
|
+
next = row === undefined ? null : dueOf(row, table, queue.due)
|
|
971
|
+
}
|
|
972
|
+
await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
|
|
973
|
+
}
|
|
974
|
+
return {
|
|
975
|
+
rows: await answerFiles(
|
|
976
|
+
model,
|
|
977
|
+
site.files,
|
|
978
|
+
session,
|
|
979
|
+
answerRows(dialect, table, rowColumnsOf(model), rows),
|
|
980
|
+
soleReach(action),
|
|
981
|
+
nameSet(site.holds ?? []),
|
|
982
|
+
),
|
|
983
|
+
claimed,
|
|
984
|
+
}
|
|
801
985
|
})
|
|
802
986
|
return leased.rows.map((row) => {
|
|
803
987
|
const id = String(row[key])
|
|
@@ -809,7 +993,7 @@ async function claimRows(
|
|
|
809
993
|
for (const name of chain) {
|
|
810
994
|
links.set(name, String(row[name]))
|
|
811
995
|
}
|
|
812
|
-
const ref = runtimeOf(context.connection).capabilities.row({ table, action
|
|
996
|
+
const ref = runtimeOf(context.connection).capabilities.row({ table, action, principal: grant.principal, id, chain: links })
|
|
813
997
|
const answered: Record<string, unknown> = {}
|
|
814
998
|
for (const name of visible) {
|
|
815
999
|
setOwn(answered, name, row[name])
|
|
@@ -893,6 +1077,7 @@ function referenceTables(parts: DataLayerParts, site: DataSite, run: Runner): ob
|
|
|
893
1077
|
model.name,
|
|
894
1078
|
freeze({
|
|
895
1079
|
list: bound(site, async (options?: unknown) => listRows(context, run, everything(), model.visible, options, model.visible)),
|
|
1080
|
+
all: bound(site, async (options?: unknown) => allRows(context, run, everything(), model.visible, options, model.visible)),
|
|
896
1081
|
count: bound(site, async (options?: unknown) => countRows(context, run, everything(), model.visible, options)),
|
|
897
1082
|
}),
|
|
898
1083
|
)
|
|
@@ -942,6 +1127,17 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
942
1127
|
return equals(table, keyOf(model), id)
|
|
943
1128
|
}
|
|
944
1129
|
const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
|
|
1130
|
+
if (model.view) {
|
|
1131
|
+
return refused(site, 'read_only', `${table} is a view, which no handler writes`)
|
|
1132
|
+
}
|
|
1133
|
+
// A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
|
|
1134
|
+
if (delegates(model) || context.writers.length > 0) {
|
|
1135
|
+
return refused(
|
|
1136
|
+
site,
|
|
1137
|
+
'undeclared_reach',
|
|
1138
|
+
`${table} hands out access, so it is written through a capability only, never unscoped`,
|
|
1139
|
+
)
|
|
1140
|
+
}
|
|
945
1141
|
if (mode === 'read') {
|
|
946
1142
|
const verb = operation === 'remove' ? 'remove' : operation
|
|
947
1143
|
return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
|
|
@@ -951,20 +1147,25 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
951
1147
|
return freeze({
|
|
952
1148
|
list: bound(
|
|
953
1149
|
site,
|
|
954
|
-
async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, unscopedRead),
|
|
1150
|
+
async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
|
|
1151
|
+
),
|
|
1152
|
+
all: bound(
|
|
1153
|
+
site,
|
|
1154
|
+
async (options?: unknown) => allRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
|
|
955
1155
|
),
|
|
956
1156
|
count: bound(site, async (options?: unknown) => countRows(context, run, everything(), visible, options)),
|
|
957
1157
|
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
|
|
958
1158
|
get: bound(site, async (id: unknown) => {
|
|
959
1159
|
const scope = everything()
|
|
960
|
-
const
|
|
1160
|
+
const dialect = dialectOf(context)
|
|
1161
|
+
const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
|
|
961
1162
|
const session = await run.read()
|
|
962
|
-
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
|
|
963
|
-
const [row] =
|
|
1163
|
+
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
|
|
1164
|
+
const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
|
|
964
1165
|
if (row === undefined) {
|
|
965
1166
|
throw new NotFoundError(`${table} not found`)
|
|
966
1167
|
}
|
|
967
|
-
await answerFiles(model, run.files, session, [row], unscopedRead)
|
|
1168
|
+
await answerFiles(model, run.files, session, [row], soleReach(unscopedRead))
|
|
968
1169
|
return row
|
|
969
1170
|
}),
|
|
970
1171
|
insert: write('insert', async (values: unknown) => insertUnscoped(context, run, site.principal, values)),
|
|
@@ -1003,7 +1204,7 @@ async function insertUnscoped(context: TableContext, run: Runner, principal: str
|
|
|
1003
1204
|
)
|
|
1004
1205
|
}
|
|
1005
1206
|
}
|
|
1006
|
-
row.set(keyOf(model),
|
|
1207
|
+
row.set(keyOf(model), uuidv7())
|
|
1007
1208
|
if (model.version !== undefined) {
|
|
1008
1209
|
row.set(model.version, 1)
|
|
1009
1210
|
}
|
|
@@ -1045,21 +1246,38 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
|
|
|
1045
1246
|
return read
|
|
1046
1247
|
}
|
|
1047
1248
|
|
|
1048
|
-
|
|
1249
|
+
/**
|
|
1250
|
+
* A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). Undefined when a condition is an
|
|
1251
|
+
* `in` with an empty list: it matches no row, so the read answers nothing and sends no statement, as an empty `Within`.
|
|
1252
|
+
*/
|
|
1253
|
+
function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] | undefined {
|
|
1049
1254
|
if (where === undefined) {
|
|
1050
1255
|
return []
|
|
1051
1256
|
}
|
|
1052
|
-
const
|
|
1257
|
+
const parsed = parseList(where, (condition): Compare | Contains | undefined => {
|
|
1053
1258
|
const parts = parseList(condition, (part) => part)
|
|
1054
1259
|
if (parts === undefined || parts.length !== 3) {
|
|
1055
1260
|
throw new QueryRefusedError('invalid_argument', 'where takes [column, operator, value] conditions, each a plain array')
|
|
1056
1261
|
}
|
|
1262
|
+
if (parts[1] === 'in' && parseList(parts[2], (item) => item)?.length === 0) {
|
|
1263
|
+
// The column is still held to the capability's columns: an empty list does not make a hidden one nameable.
|
|
1264
|
+
comparableColumnOf(shape, parts[0], 'compares')
|
|
1265
|
+
return undefined
|
|
1266
|
+
}
|
|
1057
1267
|
return parseCondition(shape, parts[0], parts[1], parts[2])
|
|
1058
1268
|
})
|
|
1059
|
-
if (
|
|
1269
|
+
if (parsed === undefined) {
|
|
1060
1270
|
throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
|
|
1061
1271
|
}
|
|
1062
|
-
|
|
1272
|
+
const conditions: (Compare | Contains)[] = []
|
|
1273
|
+
for (let index = 0; index < parsed.length; index++) {
|
|
1274
|
+
const condition = parsed[index]
|
|
1275
|
+
if (condition === undefined) {
|
|
1276
|
+
return undefined
|
|
1277
|
+
}
|
|
1278
|
+
conditions[index] = condition
|
|
1279
|
+
}
|
|
1280
|
+
return boundTerms(context, context.model, conditions)
|
|
1063
1281
|
}
|
|
1064
1282
|
|
|
1065
1283
|
function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[]): OrderColumn[] {
|
|
@@ -1069,7 +1287,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
|
|
|
1069
1287
|
if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
|
|
1070
1288
|
throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
|
|
1071
1289
|
}
|
|
1072
|
-
return { column:
|
|
1290
|
+
return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
|
|
1073
1291
|
})
|
|
1074
1292
|
if (terms === undefined) {
|
|
1075
1293
|
throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
|
|
@@ -1100,11 +1318,18 @@ function rowState(table: string, conditions: readonly (Compare | Contains)[], or
|
|
|
1100
1318
|
return { origin: freeze({}), table, columns: undefined, conditions, orderBy: order, limit, offset: undefined, joins: [] }
|
|
1101
1319
|
}
|
|
1102
1320
|
|
|
1103
|
-
/**
|
|
1104
|
-
|
|
1321
|
+
/** The list a cursor belongs to, as its signature covers it: its table and its whole order, the tiebreak included. */
|
|
1322
|
+
function cursorList(table: string, order: readonly OrderColumn[]): string {
|
|
1323
|
+
return JSON.stringify([table, order.map((term) => [term.column, term.direction])])
|
|
1324
|
+
}
|
|
1105
1325
|
|
|
1106
|
-
/** A page's position: the text of its last row's order columns (`keyset.c<n>`),
|
|
1107
|
-
function encodeCursor(
|
|
1326
|
+
/** A page's position: the text of its last row's order columns (`keyset.c<n>`), signed for its list. */
|
|
1327
|
+
async function encodeCursor(
|
|
1328
|
+
key: () => Promise<CryptoKey>,
|
|
1329
|
+
table: string,
|
|
1330
|
+
row: Readonly<Record<string, unknown>>,
|
|
1331
|
+
order: readonly OrderColumn[],
|
|
1332
|
+
): Promise<string> {
|
|
1108
1333
|
const values: CursorValue[] = order.map(({ column: name }, index) => {
|
|
1109
1334
|
const value = hasOwn(row, cursorAlias(index)) ? row[cursorAlias(index)] : null
|
|
1110
1335
|
if (typeof value === 'string' || value === null) {
|
|
@@ -1112,7 +1337,7 @@ function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly Or
|
|
|
1112
1337
|
}
|
|
1113
1338
|
throw new QueryRefusedError('list_page', `${name} came back as ${typeof value} text, which a list cannot page by`)
|
|
1114
1339
|
})
|
|
1115
|
-
return
|
|
1340
|
+
return await signCursor(key, cursorList(table, order), values)
|
|
1116
1341
|
}
|
|
1117
1342
|
|
|
1118
1343
|
/** A row as the caller sees it: the position columns stay the layer's. */
|
|
@@ -1129,30 +1354,6 @@ function withoutCursor(row: Readonly<Record<string, unknown>>, order: readonly O
|
|
|
1129
1354
|
return item
|
|
1130
1355
|
}
|
|
1131
1356
|
|
|
1132
|
-
/** The cursor `after` names, parsed at the boundary: one plain value per order column. */
|
|
1133
|
-
function decodeCursor(after: unknown, order: readonly OrderColumn[]): readonly CursorValue[] {
|
|
1134
|
-
const refused = () => new QueryRefusedError('list_page', 'after takes the next cursor of a page of this same list')
|
|
1135
|
-
if (typeof after !== 'string' || after.length === 0) {
|
|
1136
|
-
throw refused()
|
|
1137
|
-
}
|
|
1138
|
-
let parsed: unknown
|
|
1139
|
-
try {
|
|
1140
|
-
parsed = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'))
|
|
1141
|
-
} catch {
|
|
1142
|
-
throw refused()
|
|
1143
|
-
}
|
|
1144
|
-
const values = parseList(parsed, (value): CursorValue => {
|
|
1145
|
-
if (typeof value === 'string' || value === null) {
|
|
1146
|
-
return value
|
|
1147
|
-
}
|
|
1148
|
-
throw refused()
|
|
1149
|
-
})
|
|
1150
|
-
if (values === undefined || values.length !== order.length) {
|
|
1151
|
-
throw refused()
|
|
1152
|
-
}
|
|
1153
|
-
return values
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
1357
|
function compare(table: string, name: string, operator: '>' | '<' | '=', value: Primitive): OperationNode {
|
|
1157
1358
|
return BinaryOperationNode.create(column(table, name), OperatorNode.create(operator), ValueNode.create(value))
|
|
1158
1359
|
}
|
|
@@ -1197,37 +1398,84 @@ async function listRows(
|
|
|
1197
1398
|
visible: readonly string[],
|
|
1198
1399
|
input: unknown,
|
|
1199
1400
|
tiebreak: readonly string[],
|
|
1200
|
-
|
|
1401
|
+
reach?: ReadReach,
|
|
1201
1402
|
): Promise<{ readonly items: Readonly<Record<string, unknown>>[]; readonly next: string | null }> {
|
|
1202
1403
|
const table = context.model.name
|
|
1203
1404
|
const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
|
|
1204
1405
|
const shape = actionShape(context.model, visible)
|
|
1205
|
-
const conditions = conditionsOf(shape, options['where'])
|
|
1406
|
+
const conditions = conditionsOf(context, shape, options['where'])
|
|
1206
1407
|
const order = orderOf(shape, options['orderBy'], tiebreak)
|
|
1207
1408
|
const limit = limitOf(options['limit'])
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1409
|
+
const session = await run.read()
|
|
1410
|
+
// Read once per page, whether the page verifies `after`, signs `next` or both.
|
|
1411
|
+
let read: Promise<CryptoKey> | undefined
|
|
1412
|
+
const key = (): Promise<CryptoKey> => (read ??= cursorKey(session))
|
|
1413
|
+
const position = options['after'] === undefined
|
|
1414
|
+
? undefined
|
|
1415
|
+
: keysetAfter(table, order, await openCursor(key, cursorList(table, order), options['after'], order.length))
|
|
1416
|
+
if (scope === undefined || conditions === undefined) {
|
|
1210
1417
|
return { items: [], next: null }
|
|
1211
1418
|
}
|
|
1419
|
+
const dialect = dialectOf(context)
|
|
1212
1420
|
const node = withCursorColumns(
|
|
1213
|
-
selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates),
|
|
1421
|
+
selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
|
|
1214
1422
|
table,
|
|
1215
1423
|
order.map((term) => term.column),
|
|
1216
1424
|
)
|
|
1217
|
-
const session = await run.read()
|
|
1218
1425
|
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
1219
1426
|
root: 'SelectQueryNode',
|
|
1220
1427
|
table,
|
|
1221
1428
|
joins: {},
|
|
1222
1429
|
scope,
|
|
1430
|
+
subqueries: context.subqueries,
|
|
1431
|
+
through: context.through,
|
|
1223
1432
|
})
|
|
1224
|
-
const page =
|
|
1433
|
+
const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
|
|
1225
1434
|
const last = page[page.length - 1]
|
|
1226
1435
|
const items = page.map((row) => withoutCursor(row, order))
|
|
1227
1436
|
return {
|
|
1228
|
-
items:
|
|
1229
|
-
next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
|
|
1437
|
+
items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
|
|
1438
|
+
next: rows.length > limit && last !== undefined ? await encodeCursor(key, table, last, order) : null,
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* Every row of a read in one statement, in the order asked with the tiebreak last, or a refusal when more than
|
|
1444
|
+
* `MAX_ALL_ROWS` match: it never answers a truncated set.
|
|
1445
|
+
*/
|
|
1446
|
+
async function allRows(
|
|
1447
|
+
context: TableContext,
|
|
1448
|
+
run: Runner,
|
|
1449
|
+
scope: OperationNode | undefined,
|
|
1450
|
+
visible: readonly string[],
|
|
1451
|
+
input: unknown,
|
|
1452
|
+
tiebreak: readonly string[],
|
|
1453
|
+
reach?: ReadReach,
|
|
1454
|
+
): Promise<Readonly<Record<string, unknown>>[]> {
|
|
1455
|
+
const table = context.model.name
|
|
1456
|
+
const options = readOptions(input, ['where', 'orderBy'], 'all')
|
|
1457
|
+
const shape = actionShape(context.model, visible)
|
|
1458
|
+
const conditions = conditionsOf(context, shape, options['where'])
|
|
1459
|
+
const order = orderOf(shape, options['orderBy'], tiebreak)
|
|
1460
|
+
if (scope === undefined || conditions === undefined) {
|
|
1461
|
+
return []
|
|
1462
|
+
}
|
|
1463
|
+
const dialect = dialectOf(context)
|
|
1464
|
+
const node = selectNode(rowState(table, conditions, order, MAX_ALL_ROWS + 1), visible, scope, undefined, context.model.dates, dialect)
|
|
1465
|
+
const session = await run.read()
|
|
1466
|
+
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
1467
|
+
root: 'SelectQueryNode',
|
|
1468
|
+
table,
|
|
1469
|
+
joins: {},
|
|
1470
|
+
scope,
|
|
1471
|
+
subqueries: context.subqueries,
|
|
1472
|
+
through: context.through,
|
|
1473
|
+
})
|
|
1474
|
+
if (rows.length > MAX_ALL_ROWS) {
|
|
1475
|
+
throw new QueryRefusedError('too_many_rows', `all() of ${table} matches more than ${MAX_ALL_ROWS} rows: narrow it with where, or page it with list`)
|
|
1230
1476
|
}
|
|
1477
|
+
const items = answerRows(dialect, table, rowColumnsOf(context.model), rows)
|
|
1478
|
+
return reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach)
|
|
1231
1479
|
}
|
|
1232
1480
|
|
|
1233
1481
|
async function countRows(
|
|
@@ -1239,12 +1487,19 @@ async function countRows(
|
|
|
1239
1487
|
): Promise<number> {
|
|
1240
1488
|
const table = context.model.name
|
|
1241
1489
|
const options = readOptions(input, ['where'], 'count')
|
|
1242
|
-
const conditions = conditionsOf(actionShape(context.model, visible), options['where'])
|
|
1243
|
-
if (scope === undefined) {
|
|
1490
|
+
const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
|
|
1491
|
+
if (scope === undefined || conditions === undefined) {
|
|
1244
1492
|
return 0
|
|
1245
1493
|
}
|
|
1246
1494
|
const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
|
|
1247
|
-
const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
|
|
1495
|
+
const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
|
|
1496
|
+
root: 'SelectQueryNode',
|
|
1497
|
+
table,
|
|
1498
|
+
joins: {},
|
|
1499
|
+
scope,
|
|
1500
|
+
subqueries: context.subqueries,
|
|
1501
|
+
through: context.through,
|
|
1502
|
+
})
|
|
1248
1503
|
const count = row === undefined ? '0' : row['count']
|
|
1249
1504
|
return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
|
|
1250
1505
|
}
|