@fabrika/db 0.9.0-cloudflare.2 → 0.9.0-cloudflare.3

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
@@ -13,6 +13,7 @@ import { columnOf, type Compare, type Contains, parseCondition, type Primitive,
13
13
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
14
14
  import { answerFiles, type FileBinding } from './file-columns'
15
15
  import { databaseNow } from './job-leases'
16
+ import { rearmClaim } from './job-wakes'
16
17
  import { linksPredicate, linkValues } from './links'
17
18
  import {
18
19
  aggregateNode,
@@ -25,6 +26,7 @@ import {
25
26
  everything,
26
27
  inList,
27
28
  lockedSelectNode,
29
+ nextClaimNode,
28
30
  scopedWhere,
29
31
  selectNode,
30
32
  updateNode,
@@ -163,22 +165,19 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
163
165
  direct: () => parts.newSession(parts.runtime()),
164
166
  transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
165
167
  handles: (site: DataSite) => handlesOf(parts, site),
166
- sql: (site: SqlSite) =>
167
- sqlTag(
168
+ sql: (site: SqlSite) => {
169
+ const database = parts.runtime().database
170
+ return sqlTag(
168
171
  site,
169
- parts.runtime().database.schema,
170
- (capability, table, use, assigned) => {
172
+ database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
173
+ (capability, table, use) => {
171
174
  if (!hasOwn(parts.models, table)) {
172
175
  throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
173
176
  }
174
- return scopeTerms(parts.contextOf(table), capability, use, assigned)
177
+ return scopeTerms(parts.contextOf(table), capability, use)
175
178
  },
176
- (table) => {
177
- if (modelOf(parts.models, table)?.scope.mode === 'reference') {
178
- throw new QueryRefusedError('read_only', `ctx.sql: ${table} is a reference table, which no statement writes: its rows come from a migration`)
179
- }
180
- },
181
- ),
179
+ )
180
+ },
182
181
  })
183
182
  }
184
183
 
@@ -706,6 +705,8 @@ function publicApplicationRows(
706
705
  const DEFAULT_TICK_MS = 60_000
707
706
  /** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
708
707
  const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
708
+ /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
709
+ const CLAIM_REARM_MIN_MS = 1_000
709
710
 
710
711
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
711
712
  function backoffMs(tickMs: number, attempts: number): number {
@@ -716,6 +717,15 @@ function backoffMs(tickMs: number, attempts: number): number {
716
717
  return Math.min(backoff, MAX_BACKOFF_MS)
717
718
  }
718
719
 
720
+ /** A queue row's due time as the layer answers it. */
721
+ function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
722
+ const due = row[column]
723
+ if (!(due instanceof Date)) {
724
+ throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
725
+ }
726
+ return due
727
+ }
728
+
719
729
  /** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
720
730
  function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
721
731
  if (site.kind === 'query') {
@@ -766,17 +776,13 @@ async function claimRows(
766
776
  const chain = model.chain.map((link) => link.column)
767
777
  const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
768
778
  const tickMs = site.tickMs ?? DEFAULT_TICK_MS
769
- const order = [{ column: queue.due, direction: 'asc' as const }, { column: key, direction: 'asc' as const }]
770
- const leased = await parts.fenced(parts.runtime(), async (session) => {
779
+ const byDue = { column: queue.due, direction: 'asc' as const }
780
+ const order = [byDue, { column: key, direction: 'asc' as const }]
781
+ const runtime = parts.runtime()
782
+ const leased = await parts.fenced(runtime, async (session) => {
771
783
  const now = await databaseNow(session)
772
- const node = claimNode(
773
- rowState(table, conditions, order, limit),
774
- selected,
775
- { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts },
776
- scope,
777
- model.dates,
778
- dialect,
779
- )
784
+ const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
785
+ const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
780
786
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
781
787
  const byAttempts = new Map<number, string[]>()
782
788
  for (const row of rows) {
@@ -804,6 +810,23 @@ async function claimRows(
804
810
  claimed.set(id, { version: next, attempts: attempts + 1, due })
805
811
  }
806
812
  }
813
+ // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
814
+ const fence = runtime.capabilities.fence()
815
+ if (fence !== null && rows.length > 0) {
816
+ // A full claim left rows behind: due at once.
817
+ let rearm: Date | null = new Date(now.getTime() + 1)
818
+ if (rows.length < limit) {
819
+ const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
820
+ const [row] = answerRows(
821
+ dialect,
822
+ table,
823
+ rowColumnsOf(model),
824
+ await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
825
+ )
826
+ rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
827
+ }
828
+ await rearmClaim(runtime, session, fence, rearm)
829
+ }
807
830
  return { rows: await answerFiles(model, site.files, session, answerRows(dialect, table, rowColumnsOf(model), rows), grant.action), claimed }
808
831
  })
809
832
  return leased.rows.map((row) => {
package/src/registry.ts CHANGED
@@ -6,6 +6,7 @@ import type { Admissions } from './admissions'
6
6
  import type { Session } from './database'
7
7
  import type { WebhookTables } from './framework-tables'
8
8
  import type { JobLeases } from './job-leases'
9
+ import type { JobWakes } from './job-wakes'
9
10
  import type { DataAccess } from './orm'
10
11
  import type { DataLayerRuntime, TableContext, TableProbe } from './store'
11
12
  import type { StoredFiles } from './stored-files'
@@ -20,6 +21,8 @@ export type Locator = (dimension: string, id: string, using?: Session) => Promis
20
21
  export interface FrameworkTables {
21
22
  readonly webhooks: WebhookTables
22
23
  readonly jobs: JobLeases
24
+ /** A job's durable pending work (`fabrika_wakes`), which follows its lease, and the scheduler's next wake over both. */
25
+ readonly wakes: JobWakes
23
26
  /** A procedure's admission buckets, the challenge tokens it accepted and its byte budget. */
24
27
  readonly admissions: Admissions
25
28
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */