@lunora/codegen 1.0.0-alpha.26 → 1.0.0-alpha.261
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/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +3851 -1254
- package/dist/index.d.ts +3851 -1254
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-UhIaG4BZ.mjs +1 -0
- package/dist/packem_shared/CAPABILITY_PROBES-DFsutD7g.mjs +25 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-DhUL5rDc.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-7sHexLjO.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-BINQ51Zq.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-dFyrHgQ0.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-D1Q6EUII.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-bbHHFQ_t.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-CGu1_YK7.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-CSLmXUQA.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BVhRHIbS.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-DuR5hLW1.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-IqUyMQgM.mjs +1 -0
- package/dist/packem_shared/attribution-sW_DHmLO.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-DOsv1HEF.mjs +3 -0
- package/dist/packem_shared/capabilitiesUsedBy-CzqyN9dX.mjs +1 -0
- package/dist/packem_shared/chain-BTbLDrrU.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-OnJoKgqu.mjs +1 -0
- package/dist/packem_shared/context-property-calls-BEBjylgc.mjs +1 -0
- package/dist/packem_shared/context-root-KWXRWlv6.mjs +1 -0
- package/dist/packem_shared/database-calls-rLPCL3-U.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-CNj9-Jch.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BqTY53L5.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-DPH4drkg.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-MRFziTCb.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-BcVkR6nw.mjs +1 -0
- package/dist/packem_shared/discoverInserts-Duz40u-s.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-DYJhbHF3.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-D2P2n7JE.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-Cxf6T2Oi.mjs +1 -0
- package/dist/packem_shared/discoverQueries-CWmNPVHm.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-DnKwop5c.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-BXXEFXjf.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-Des596JU.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-Bjl8A_hj.mjs +1 -0
- package/dist/packem_shared/discoverSchema-Cd3iH6q5.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-DGFonj0I.mjs +1 -0
- package/dist/packem_shared/emitAgents-Dotqck8w.mjs +1 -0
- package/dist/packem_shared/emitApi-xDIHPRPH.mjs +154 -0
- package/dist/packem_shared/emitApp-RNU41dtm.mjs +860 -0
- package/dist/packem_shared/emitCrons-DsXsg1uG.mjs +83 -0
- package/dist/packem_shared/emitDataModel-DSk9AkJe.mjs +113 -0
- package/dist/packem_shared/emitDrizzleSchema-DohtnI8c.mjs +15 -0
- package/dist/packem_shared/emitFunctions-evl8Mx1a.mjs +249 -0
- package/dist/packem_shared/emitServer-DymRagL2.mjs +368 -0
- package/dist/packem_shared/emitShard-DHMYSP4m.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-58yS9zc8.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-BzFVnBfa.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/handler-reference-C1oBljnl.mjs +1 -0
- package/dist/packem_shared/index-BusOvbeQ.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/listLunoraSourceFiles-DRes9d5p.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-CuGQsqYS.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-CsA-QVJ6.mjs +1 -0
- package/dist/packem_shared/parse-validator-B4mFs19C.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/qualifiers-Cw8dEDbh.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-CnvEGOir.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/reserved-words-CW1QFbTd.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/shard-WXSIZRpD.mjs +1438 -0
- package/dist/packem_shared/shard-runtime-B1nU9CRa.mjs +321 -0
- package/dist/packem_shared/shared-BXUKWh7t.mjs +9 -0
- package/dist/packem_shared/unwrap-handler-return-D7E2TKkS.mjs +1 -0
- package/package.json +16 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-CYaSI_qY.mjs +0 -3268
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-CRe5l79E.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-cgOjZTVY.mjs +0 -1137
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-BlpXQe2K.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-C38fHt_1.mjs +0 -675
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,1438 @@
|
|
|
1
|
+
import{LunoraError as vt}from"@lunora/errors";import{serializeSchemaSnapshot as kt,hashSchemaSnapshot as St}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Rt,isD1GlobalTable as xt}from"./isD1GlobalTable-udvHAAzD.mjs";import{p as At,i as Dt}from"./ir-DBSvhNa-.mjs";import{r as h}from"./json-data-Chfs2Cz5.mjs";import{r as C,e as Tt,a as Ot,b as Et,c as Ct,d as Lt,f as It,g as _t,h as Mt,i as Pt,j as qt,k as Nt,l as $t,m as Ft,n as Ut,o as Bt,p as Wt,q as jt}from"./shard-runtime-B1nU9CRa.mjs";import{u as K,i as Ht,G as Vt,d as Kt}from"./shared-BXUKWh7t.mjs";const Gt=` /**
|
|
2
|
+
* The bare writer every admin/maintenance entry point writes through.
|
|
3
|
+
*
|
|
4
|
+
* Admin and maintenance writes go through the SAME reactive-cache hooks as a
|
|
5
|
+
* user mutation. Without this, a studio row edit, a TTL sweep, an admin
|
|
6
|
+
* import, a CDC apply or a data-migration backfill writes without
|
|
7
|
+
* invalidating, and the next query answers from the pre-write snapshot.
|
|
8
|
+
*
|
|
9
|
+
* \`headroom\` meters the transaction. An admin \`/rpc\` caller passes nothing
|
|
10
|
+
* and falls back to \`this.transactionHeadroom()\`, which for an admin RPC is
|
|
11
|
+
* \`undefined\` — \`handleAdminRpc\` answers before \`beginDispatch\`, so no
|
|
12
|
+
* per-dispatch meter is in flight and a bulk loop is bounded by its per-call
|
|
13
|
+
* row cap alone. The TTL sweep (an alarm work item, no dispatch) passes its
|
|
14
|
+
* own by-value tracker explicitly instead.
|
|
15
|
+
*/
|
|
16
|
+
private adminWriter(headroom?: TransactionHeadroomTracker): DatabaseWriterLike {
|
|
17
|
+
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
18
|
+
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
19
|
+
|
|
20
|
+
return createShardCtxDb({
|
|
21
|
+
...this.ctxDbTuning(),
|
|
22
|
+
broadcast: (delta) => {
|
|
23
|
+
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
24
|
+
},
|
|
25
|
+
cdc: config.cdc ?? false,
|
|
26
|
+
headroom,
|
|
27
|
+
// Live predicate, same as the user-facing ctx — see \`databaseOptions\`.
|
|
28
|
+
inTransaction: () => this.isInTransaction(),
|
|
29
|
+
scheduler,
|
|
30
|
+
schema: schema as unknown as SchemaLike,
|
|
31
|
+
sql: this.sql as SqlExec,
|
|
32
|
+
});
|
|
33
|
+
}`,p=(a="")=>` const writer = this.adminWriter(${a});`,Qt=`${Gt}
|
|
34
|
+
|
|
35
|
+
protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise<MigrationRunResult> {
|
|
36
|
+
this.ensureMigrated();
|
|
37
|
+
|
|
38
|
+
// Falls back to the framework's reserved re-projection backfill
|
|
39
|
+
// (\`__lunora_reproject__<table>\`), which rewrites rows whose
|
|
40
|
+
// v.bigint()/v.bytes() columns are still stored in the pre-projection
|
|
41
|
+
// tagged form. Built here rather than at module scope because it
|
|
42
|
+
// needs this shard's \`sql\` handle to tell a legacy row from a
|
|
43
|
+
// current one.
|
|
44
|
+
const migration = LUNORA_MIGRATIONS[args.id] ?? buildReprojectionMigration(args.id, schema as unknown as SchemaLike, this.sql as SqlExec);
|
|
45
|
+
|
|
46
|
+
if (!migration) {
|
|
47
|
+
throw new LunoraError("MIGRATION_NOT_FOUND", \`data migration "\${args.id}" is not registered\`, { status: 404 });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
${p()}
|
|
51
|
+
|
|
52
|
+
return runDataMigration({
|
|
53
|
+
batchSize: args.batchSize,
|
|
54
|
+
direction: args.direction,
|
|
55
|
+
dryRun: args.dryRun,
|
|
56
|
+
maxBatches: args.maxBatches,
|
|
57
|
+
migration: migration as unknown as DataMigrationLike,
|
|
58
|
+
// Flush after each batch so live migrationStatus subscribers see
|
|
59
|
+
// progress mid-run (the base method records the reserved state
|
|
60
|
+
// table the raw-SQL progress write is invisible to the tracker).
|
|
61
|
+
onBatch: () => this.flushMigrationProgress(),
|
|
62
|
+
sql: this.sql as SqlExec,
|
|
63
|
+
writer,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
protected override async runShardWrite(args: RunShardWriteArgs, headroom?: TransactionHeadroomTracker): Promise<RunShardWriteResult> {
|
|
68
|
+
const definition = (schema as unknown as SchemaLike).tables[args.table];
|
|
69
|
+
|
|
70
|
+
if (!definition) {
|
|
71
|
+
throw new LunoraError("UNKNOWN_TABLE", \`unknown table: \${args.table}\`, { status: 404 });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// \`.global()\` tables live in D1, not this DO's SQLite — editing them
|
|
75
|
+
// here would corrupt nothing but would fail confusingly, so reject up
|
|
76
|
+
// front with a clear code the studio can surface.
|
|
77
|
+
if (definition.shardMode?.kind === "global") {
|
|
78
|
+
throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", \`table "\${args.table}" is global; edit it through D1, not the shard\`, { status: 400 });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
this.ensureMigrated();
|
|
82
|
+
|
|
83
|
+
${p("headroom ?? this.transactionHeadroom()")}
|
|
84
|
+
|
|
85
|
+
if (args.op === "insert") {
|
|
86
|
+
const id = await writer.insert(args.table, args.doc ?? {});
|
|
87
|
+
|
|
88
|
+
return { id, op: "insert" };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Every by-id op PINS \`args.table\`. Unpinned, \`locateRowById\` probes
|
|
92
|
+
// every non-global table for the id, so a request naming table A with an
|
|
93
|
+
// id belonging to table B locates and mutates B's row — the by-id IDOR
|
|
94
|
+
// the per-table \`ctx.db.<table>\` facade pins against. Pinning also stops
|
|
95
|
+
// an absent row falling through to the \`.global()\` D1 twin, though that
|
|
96
|
+
// branch is already unreachable here: \`adminWriter\` is built without a
|
|
97
|
+
// \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
|
|
98
|
+
// \`hard\` is set only by the BULK delete arm, which needs the row gone
|
|
99
|
+
// from the physical table for its next batch's scan to make progress.
|
|
100
|
+
// A single-row \`writeRow\` delete never carries it, so it keeps the
|
|
101
|
+
// table's declared \`.softDelete()\` behaviour.
|
|
102
|
+
if (args.op === "delete") {
|
|
103
|
+
await writer.delete(args.id ?? "", args.table, { hard: args.hard === true });
|
|
104
|
+
|
|
105
|
+
return { id: args.id ?? null, op: "delete" };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (args.op === "replace") {
|
|
109
|
+
await writer.replace(args.id ?? "", args.doc ?? {}, args.table);
|
|
110
|
+
|
|
111
|
+
return { id: args.id ?? null, op: "replace" };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
await writer.patch(args.id ?? "", args.doc ?? {}, args.table);
|
|
115
|
+
|
|
116
|
+
return { id: args.id ?? null, op: "patch" };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// The base \`ShardDO\` cannot build a schema-aware writer, so its
|
|
120
|
+
// \`runShardExport\`/\`runShardImport\` return \`[]\` and \`{inserted:{}}\`.
|
|
121
|
+
// Those are success-shaped: an empty export is what a correct export of
|
|
122
|
+
// an empty shard looks like, so a backup of a populated sharded schema
|
|
123
|
+
// reported success and wrote nothing, and an import reported success and
|
|
124
|
+
// dropped every row. Overriding both here is what makes the two admin
|
|
125
|
+
// RPCs real for a \`.shardBy()\` table.
|
|
126
|
+
//
|
|
127
|
+
// NOTE: the admin export RPC is not paginated — \`parseExportShardArgs\`
|
|
128
|
+
// takes \`tables\`/\`batchSize\` but no cursor, and the coordinator issues
|
|
129
|
+
// one call per shard — so the rows are collected into a single response.
|
|
130
|
+
// \`batchSize\` bounds the SQLite scan page, not the reply. A shard holding
|
|
131
|
+
// more rows than fit in the DO's memory budget will therefore fail the
|
|
132
|
+
// export rather than stream it. That is a loud failure where the bug this
|
|
133
|
+
// replaces was a silent empty one, but a cursor on the RPC is what makes
|
|
134
|
+
// this a complete backup path for large shards.
|
|
135
|
+
protected override async runShardExport(args: RunShardExportArgs): Promise<ExportRow[]> {
|
|
136
|
+
this.ensureMigrated();
|
|
137
|
+
|
|
138
|
+
${p()}
|
|
139
|
+
|
|
140
|
+
const rows: ExportRow[] = [];
|
|
141
|
+
|
|
142
|
+
// \`exportShardRows\` walks in keyset batches so a large table does not
|
|
143
|
+
// materialize at once inside the generator; the admin RPC's response
|
|
144
|
+
// is a single array, so it is collected here rather than streamed.
|
|
145
|
+
for await (const row of exportShardRows(writer, schema as unknown as SchemaLike, { batchSize: args.batchSize, tables: args.tables })) {
|
|
146
|
+
rows.push(row);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return rows;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
protected override async runShardImport(args: RunShardImportArgs): Promise<ImportShardResult> {
|
|
153
|
+
this.ensureMigrated();
|
|
154
|
+
|
|
155
|
+
${p()}
|
|
156
|
+
|
|
157
|
+
// \`importShardRows\` inserts with \`allowExplicitId\`, so a source
|
|
158
|
+
// database's \`_id\`s carry across verbatim and every foreign key
|
|
159
|
+
// referencing them stays valid without a second remapping pass.
|
|
160
|
+
return importShardRows(writer, schema as unknown as SchemaLike, { rows: args.rows, startLine: args.startLine });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> {
|
|
164
|
+
this.ensureMigrated();
|
|
165
|
+
|
|
166
|
+
${p()}
|
|
167
|
+
|
|
168
|
+
// \`rankBefore\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
169
|
+
// but the shard writer from \`createShardCtxDb\` always defines it.
|
|
170
|
+
if (!writer.rankBefore) {
|
|
171
|
+
throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return writer.rankBefore(args.table, args.index, {
|
|
175
|
+
partitionKey: args.partitionKey,
|
|
176
|
+
rowId: args.rowId,
|
|
177
|
+
sortValues: args.sortValues,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
protected override async runShardFindRelated(args: RunShardFindRelatedArgs): Promise<RelatedPage> {
|
|
182
|
+
this.ensureMigrated();
|
|
183
|
+
|
|
184
|
+
${p()}
|
|
185
|
+
|
|
186
|
+
// \`related\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
187
|
+
// but the shard writer from \`createShardCtxDb\` always defines it — it
|
|
188
|
+
// derives the edge set from this app's schema.
|
|
189
|
+
if (!writer.related) {
|
|
190
|
+
throw new LunoraError("NOT_IMPLEMENTED", "findRelated is unavailable on the shard writer", { status: 500 });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return writer.related(
|
|
194
|
+
{ id: args.id, table: args.table },
|
|
195
|
+
{ cursor: args.cursor, depth: args.depth, direction: args.direction, edges: args.edges, limit: args.limit },
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
protected override async runShardRankPage(args: RunShardRankPageArgs): Promise<ShardRankPageResult> {
|
|
200
|
+
this.ensureMigrated();
|
|
201
|
+
|
|
202
|
+
${p()}
|
|
203
|
+
|
|
204
|
+
// \`rankPageRows\` is optional on \`DatabaseWriterLike\` (the D1 twin omits it),
|
|
205
|
+
// but the shard writer from \`createShardCtxDb\` always defines it. The sort
|
|
206
|
+
// directions live in the schema's rankIndex, so the shard reads them itself;
|
|
207
|
+
// \`args.directions\` is only the coordinator's comparator hint and isn't forwarded.
|
|
208
|
+
if (!writer.rankPageRows) {
|
|
209
|
+
throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return writer.rankPageRows(args.table, args.index, {
|
|
213
|
+
after: args.after,
|
|
214
|
+
cursor: args.cursor,
|
|
215
|
+
partitionKey: args.partitionKey,
|
|
216
|
+
take: args.take,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> {
|
|
221
|
+
this.ensureMigrated();
|
|
222
|
+
|
|
223
|
+
${p()}
|
|
224
|
+
|
|
225
|
+
await applyCdcChanges(writer, args.changes);
|
|
226
|
+
|
|
227
|
+
return { applied: args.changes.length };
|
|
228
|
+
}`,zt=({actionOnlyBuild:a,actionOnlyFields:r,agentsBuild:e,agentsContextField:n,containersBuild:t,containersContextField:o,databaseOptions:d,everyContextBuild:m,everyContextField:f,facadeBlock:c,globalDatabaseLine:w,notifyBuild:S,ormContextField:y,paymentsBuild:L,paymentsContextField:i,queuesBuild:g,queuesContextField:I,topicsBuild:_,topicsContextField:M,vectorsBuild:A,vectorsContextField:P,workflowsBuild:q,workflowsContextField:R})=>{const l=r.length>0,D=l?`
|
|
229
|
+
// ActionCtx-only helpers (external, non-deterministic I/O): constructed
|
|
230
|
+
// and attached only for an \`action\` so query/mutation ctx never carry them.
|
|
231
|
+
if (isAction) {
|
|
232
|
+
${a.replaceAll(/^(?=.)/gmu," ")}${r.map(k=>` ctx.${k} = ${k};`).join(`
|
|
233
|
+
`)}
|
|
234
|
+
}
|
|
235
|
+
`:"";return` private buildCtx(options: { bookmarks?: DispatchBookmark; functionPath?: string; headroom?: TransactionHeadroomTracker; identity?: SubscriptionIdentity; kind?: "query"; onRead?: (table: string, idOrScan?: string) => void; onReadRange?: (range: KeyRange) => void; scope?: QueryReadScope; trusted?: boolean } = {}): unknown {
|
|
236
|
+
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
237
|
+
// The caller context this ctx runs under, resolved ONCE on one
|
|
238
|
+
// discriminant. When the caller threads an explicit identity
|
|
239
|
+
// (subscription seed / refresh / stream pull / shape resolve — all
|
|
240
|
+
// deferred or interleaved), it is used by value and the shared
|
|
241
|
+
// per-request fields are never read, because a concurrent RPC owns
|
|
242
|
+
// them: a refresh in particular runs inside the writing dispatch's
|
|
243
|
+
// \`flushChangedTables\`, BEFORE its \`endDispatch\`, so \`getCurrentIp()\`
|
|
244
|
+
// there is the MUTATING caller's address. Otherwise (the synchronous
|
|
245
|
+
// RPC dispatch path) it falls back to those fields as before.
|
|
246
|
+
//
|
|
247
|
+
// One expression, not one per field: three parallel ternaries on the
|
|
248
|
+
// same discriminant is how \`ip\` came to be the only one still reading
|
|
249
|
+
// the shared field.
|
|
250
|
+
const caller: SubscriptionIdentity = options.identity ?? {
|
|
251
|
+
identity: this.getCurrentIdentity(),
|
|
252
|
+
ip: this.getCurrentIp(),
|
|
253
|
+
userId: this.getCurrentUserId(),
|
|
254
|
+
};
|
|
255
|
+
const { identity, ip, userId } = caller;
|
|
256
|
+
${A}${m}${t}${q}${g}${_}${e}
|
|
257
|
+
// Which dispatch this ctx belongs to. Drives the two deferral facades
|
|
258
|
+
// below and the \`ctx.run*\` caller guard; a ctx built for an
|
|
259
|
+
// admin/lifecycle path has no registered function, and so no kind. An
|
|
260
|
+
// untracked \`ctx.runQuery\` overrides it with \`"query"\`: the sub-query
|
|
261
|
+
// keeps the caller's \`functionPath\` for attribution but runs as a query.
|
|
262
|
+
const contextKind = options.kind ?? LUNORA_FUNCTIONS[options.functionPath ?? ""]?.kind;
|
|
263
|
+
// \`list\`/\`get\` are the two methods \`ctx.db.system.query("_scheduled_functions")\`
|
|
264
|
+
// reaches through, and pending jobs live in the SchedulerDO — nothing the
|
|
265
|
+
// CDC changelog records — so reading them must forfeit a delta resume.
|
|
266
|
+
// The scheduler's own \`runAfter\`/\`runAt\`/\`cancel\` are writes and stay unstamped.
|
|
267
|
+
const schedulerBase = markUnvouchableReads((config.scheduler?.(env) ?? schedulerStub) as SchedulerLike, options.onRead, ["get", "list"]);
|
|
268
|
+
// \`ctx.scheduler.runAfter(0, ...)\` is documented as the deterministic
|
|
269
|
+
// equivalent of an \`afterCommit\` hook, and the SchedulerDO persists the
|
|
270
|
+
// job the moment it is called — so inside a mutation the call is BUFFERED
|
|
271
|
+
// and replayed after the transaction commits (a rollback drops it).
|
|
272
|
+
// Wrapped on the same dispatches as the deferred-delete queue and for the
|
|
273
|
+
// same reason: \`ctx.runMutation\` hands the CALLER's ctx to the callee, so
|
|
274
|
+
// a mutation reached from an action schedules through the action's ctx.
|
|
275
|
+
// An action's own schedules stay immediate — the window is only open
|
|
276
|
+
// while a transaction is (see \`runMutationTransaction\`).
|
|
277
|
+
//
|
|
278
|
+
// Every kind but \`query\` is wrapped, because \`runMutationTransaction\`
|
|
279
|
+
// is installed on \`ctx.runMutation\` for every kind but \`query\`: a
|
|
280
|
+
// STREAM ctx, and an admin/lifecycle ctx with no registered kind at all,
|
|
281
|
+
// both get the BEGIN/COMMIT span for a mutation they compose, and used
|
|
282
|
+
// to get it with the deferral missing — so that mutation's job reached
|
|
283
|
+
// the SchedulerDO while its transaction was still open, and survived the
|
|
284
|
+
// rollback. A query cannot host a mutation handler (\`dispatchRun\`
|
|
285
|
+
// refuses it) and its ctx is built on the hot subscription path, so it
|
|
286
|
+
// stays unwrapped.
|
|
287
|
+
//
|
|
288
|
+
// Wrapped OUTSIDE the read-stamping facade so \`get\`/\`list\` stay stamped.
|
|
289
|
+
//
|
|
290
|
+
// \`this.scheduleOutbox()\` is what keeps the buffer honest. Everything
|
|
291
|
+
// between the COMMIT and the scheduler's acknowledgement is outside the
|
|
292
|
+
// transaction, so a failure there leaves writes that are durable and a
|
|
293
|
+
// job that exists nowhere — and the mutation's replay-dedup row committed
|
|
294
|
+
// inside the span, so the client's retry is answered from cache and told
|
|
295
|
+
// it succeeded. The outbox takes custody of each buffered call inside the
|
|
296
|
+
// transaction and releases it once the scheduler has the job; what
|
|
297
|
+
// survives is retried by \`pollScheduleOutbox\` on the shared poll alarm.
|
|
298
|
+
const scheduler = contextKind === "query" ? schedulerBase : withDeferredSchedules(schedulerBase, this.scheduleOutbox());
|
|
299
|
+
// Build the storage adapter once and share it between \`ctx.storage\`
|
|
300
|
+
// and \`ctx.db.system._storage\` so both read the same R2 binding. The
|
|
301
|
+
// \`storageStub\` fallback satisfies SystemReaderStorageLike structurally
|
|
302
|
+
// (its \`list\`/\`getMetadata\` throw the "no storage configured" error).
|
|
303
|
+
//
|
|
304
|
+
// Wrapped BEFORE the split so both consumers share one stamping facade.
|
|
305
|
+
// Only the methods that actually reach R2 are stamped: \`getUrl\` and
|
|
306
|
+
// \`getSignedUrl\` build a URL from the configured base (and an HMAC) and
|
|
307
|
+
// read nothing, and they are what handlers overwhelmingly call — stamping
|
|
308
|
+
// them would forfeit resumes for a dependency that cannot move the result.
|
|
309
|
+
// \`bucket\` IS stamped: it hands back a sub-facade this wrapper does not
|
|
310
|
+
// reach, so the selection is the last point at which the read can be seen.
|
|
311
|
+
//
|
|
312
|
+
// The request origin is the storage base fallback for mutations and
|
|
313
|
+
// actions on the synchronous dispatch only. A deferred caller
|
|
314
|
+
// (\`options.identity\` set) runs outside the dispatch that owns the
|
|
315
|
+
// field, the same hazard \`getCurrentIp\` has. A query never gets it: a
|
|
316
|
+
// live query re-runs with no request behind it, and the reactive
|
|
317
|
+
// cache does not key on the host, so a query that signs URLs needs a
|
|
318
|
+
// declared \`publicBaseUrl\` either way.
|
|
319
|
+
const requestOrigin = contextKind !== "query" && options.identity === undefined ? this.getCurrentOrigin() : undefined;
|
|
320
|
+
const makeStorage = (origin?: string): SystemReaderStorageLike =>
|
|
321
|
+
markUnvouchableReads(asBucketStorage(config.storage?.(env, origin) ?? storageStub) as SystemReaderStorageLike, options.onRead, [
|
|
322
|
+
"bucket",
|
|
323
|
+
"download",
|
|
324
|
+
"getMetadata",
|
|
325
|
+
"list",
|
|
326
|
+
]);
|
|
327
|
+
const storage = makeStorage(requestOrigin);
|
|
328
|
+
// \`ctx.storage.deleteAfterCommit(key)\`, on every dispatch that can host
|
|
329
|
+
// a MUTATION handler — which is not only a mutation dispatch:
|
|
330
|
+
// \`ctx.runMutation\` hands the CALLER's ctx to the callee, so a mutation
|
|
331
|
+
// reached from an action runs on the action's ctx. Wrapping mutations
|
|
332
|
+
// alone made that composition throw a bare TypeError on a method the
|
|
333
|
+
// handler's own type promises. Queries stay unwrapped: they cannot host
|
|
334
|
+
// one, and their ctx is built on the hot subscription path.
|
|
335
|
+
//
|
|
336
|
+
// Every dispatch wrapped here also flushes (see \`handleRpc\` and
|
|
337
|
+
// \`runReactor\`) — a queue nothing drains leaks silently, which is worse
|
|
338
|
+
// than not having the method at all.
|
|
339
|
+
//
|
|
340
|
+
// Wrapped OUTSIDE the read-stamping facade so \`bucket(name)\` still
|
|
341
|
+
// resolves through it and stays stamped, and applied only to
|
|
342
|
+
// \`ctx.storage\` so \`ctx.db.system._storage\` (which shares the adapter
|
|
343
|
+
// above) is untouched.
|
|
344
|
+
const contextStorage = contextKind === "mutation" || contextKind === "action" ? withDeferredDeletes(storage) : storage;
|
|
345
|
+
// \`ctx.log\`: the DO base builds the attributed logger (structured
|
|
346
|
+
// fields + \`.with(...)\` child + trace correlation) and routes each call
|
|
347
|
+
// to the optional \`observability\` sink. It also buffers the line (studio
|
|
348
|
+
// Logs panel) and emits a structured console event the dev-server formats.
|
|
349
|
+
//
|
|
350
|
+
// Resolved BEFORE \`ctx.db\` below, because the database is wrapped in
|
|
351
|
+
// auto-instrumentation that needs the sink, the trace anchor, and the
|
|
352
|
+
// dispatch's wide-event handle.
|
|
353
|
+
const observability = config.observability?.(env);
|
|
354
|
+
const logFunctionPath = options.functionPath ?? "";
|
|
355
|
+
const log = this.makeLogger(logFunctionPath, observability);
|
|
356
|
+
const traceAnchor = this.resolveDispatchAnchor(Boolean(options.identity));
|
|
357
|
+
|
|
358
|
+
// \`ctx.span\`: the handle onto the DISPATCH's own span — the wide-event
|
|
359
|
+
// surface. Attributes attached here accumulate for the whole request
|
|
360
|
+
// and are folded into the one span it already emits, instead of
|
|
361
|
+
// becoming N separate log lines. Shares \`traceAnchor\` with \`ctx.trace\`
|
|
362
|
+
// so both write to the same trace.
|
|
363
|
+
const span = this.makeDispatchSpan(traceAnchor, observability);
|
|
364
|
+
|
|
365
|
+
${w} // \`ctx.db\`, wrapped in automatic instrumentation: by default this
|
|
366
|
+
// adds aggregate counters (call count, total time, per-operation
|
|
367
|
+
// breakdown) to the wide event rather than a span per call, so a
|
|
368
|
+
// handler making hundreds of queries stays readable. See
|
|
369
|
+
// \`instrumentDatabase\` for the \`"spans"\` / \`"off"\` levels.
|
|
370
|
+
const db: DatabaseWriterLike = this.instrumentDb(createShardCtxDb(${d}), logFunctionPath, traceAnchor, observability);
|
|
371
|
+
${c}${L}
|
|
372
|
+
|
|
373
|
+
// \`ctx.trace\` / \`ctx.metrics\`: spans and measurements to the same sink.
|
|
374
|
+
// The trace anchor is threaded explicitly for the same reason \`identity\`
|
|
375
|
+
// is — a deferred caller (a subscription re-run) must not inherit the
|
|
376
|
+
// writing mutation's trace from the shared per-request field.
|
|
377
|
+
const trace = this.makeTracer(logFunctionPath, observability, traceAnchor);
|
|
378
|
+
const metrics = this.makeMetrics(logFunctionPath, observability);
|
|
379
|
+
${S}
|
|
380
|
+
// \`ctx.now\`: the wall-clock instant (epoch ms) this function began,
|
|
381
|
+
// captured ONCE so the whole handler body sees a single stable value.
|
|
382
|
+
// A \`query\` handler is re-run by every live subscription that reads it,
|
|
383
|
+
// so \`Date.now()\` there flickers between re-evaluations. A \`mutation\`
|
|
384
|
+
// handler does not replay under ordinary dispatch (an OCC conflict throws
|
|
385
|
+
// to the caller rather than retrying internally), but one called from a
|
|
386
|
+
// workflow step or queue consumer runs again when that step replays. Both
|
|
387
|
+
// read time through \`ctx.now\` — the \`nondeterministic_query_mutation\`
|
|
388
|
+
// advisor flags \`Date.now()\`. Actions may still use ambient \`Date.now()\`.
|
|
389
|
+
const now = Date.now();
|
|
390
|
+
|
|
391
|
+
const ctx: Record<string, unknown> = {
|
|
392
|
+
auth: {
|
|
393
|
+
getIdentity: async () => identity ?? null,
|
|
394
|
+
userId: userId ?? null,
|
|
395
|
+
},
|
|
396
|
+
db,
|
|
397
|
+
// Instrumented \`fetch\`: a CLIENT span per outbound call plus W3C
|
|
398
|
+
// \`traceparent\` propagation, so time spent in a downstream service
|
|
399
|
+
// is visible and its spans join this trace. Degrades to the bare
|
|
400
|
+
// global when no sink is configured.
|
|
401
|
+
fetch: this.makeFetch(logFunctionPath, traceAnchor, observability),
|
|
402
|
+
// A GETTER, not a plain field, so the reactive cache can tell a
|
|
403
|
+
// handler that reads the caller's address from the majority that
|
|
404
|
+
// never do. \`ctx.ip\` is per-request state the memo must be keyed
|
|
405
|
+
// by — otherwise two anonymous callers share one entry and the
|
|
406
|
+
// second is served the first's address — but keying every entry
|
|
407
|
+
// by address would shard the cache per client for every query.
|
|
408
|
+
// Reading it here marks the dispatch's scope; \`runCachedQuery\`
|
|
409
|
+
// folds the address into the key for this function from then on.
|
|
410
|
+
get ip() {
|
|
411
|
+
options.scope?.markIpRead();
|
|
412
|
+
|
|
413
|
+
return ip;
|
|
414
|
+
},
|
|
415
|
+
log,
|
|
416
|
+
metrics,
|
|
417
|
+
now,
|
|
418
|
+
// The same request origin the storage fallback above uses, handed
|
|
419
|
+
// to the handler so code that signs its own URLs (a copy-in
|
|
420
|
+
// \`createStorage\`) can fall back to it too. \`undefined\` for a
|
|
421
|
+
// query and for a deferred dispatch, for the reasons given there.
|
|
422
|
+
origin: requestOrigin,${y}
|
|
423
|
+
scheduler,
|
|
424
|
+
span,
|
|
425
|
+
storage: contextStorage,
|
|
426
|
+
trace,${P}${f}${i}${o}${R}${I}${M}${n}
|
|
427
|
+
};
|
|
428
|
+
${l?` const isAction = contextKind === "action";
|
|
429
|
+
`:""}${D}
|
|
430
|
+
const installRun = (target: Record<string, unknown>, kind: typeof contextKind): void => {
|
|
431
|
+
target.runAction = (reference: FunctionReference, fnArgs: Record<string, unknown>) => dispatchRun("action", reference.__lunoraRef, fnArgs, target, kind);
|
|
432
|
+
// The composed mutation runs under the SAME wrapper the top-level RPC
|
|
433
|
+
// uses, so "do the transactional work in a mutation and call it from the
|
|
434
|
+
// action" — the recipe the docs give for atomicity — actually is atomic.
|
|
435
|
+
target.runMutation = (reference: FunctionReference, fnArgs: Record<string, unknown>) =>
|
|
436
|
+
dispatchRun("mutation", reference.__lunoraRef, fnArgs, target, kind, async (work) => this.runMutationTransaction(target, work));
|
|
437
|
+
// \`ctx.runQuery(ref, args, { untracked: true })\` runs the sub-query on
|
|
438
|
+
// its OWN query context, built without the subscription's read-footprint
|
|
439
|
+
// hooks — so its reads never enter this subscription's footprint and a
|
|
440
|
+
// write to the tables it touched does not re-run us. Everything else is
|
|
441
|
+
// inherited: \`functionPath\` (log/metric attribution), \`headroom\` (the
|
|
442
|
+
// sub-query must not escape this dispatch's resource ceiling),
|
|
443
|
+
// \`scope\` (the reactive-cache capture — an untracked sub-query's reads
|
|
444
|
+
// must still be deps of the entry the OUTER query is memoized as, or
|
|
445
|
+
// the memo goes stale), and — load-bearing — the resolved \`caller\` BY VALUE
|
|
446
|
+
// (identity, userId AND ip). Omitting it would let \`buildCtx\` fall back
|
|
447
|
+
// to the shared per-request fields, which a concurrent RPC may have
|
|
448
|
+
// re-set, and an RLS-scoped sub-query would then read as the wrong user
|
|
449
|
+
// from the wrong address. A tracked call runs on \`queryContext()\` below.
|
|
450
|
+
target.runQuery = (reference: FunctionReference, fnArgs: Record<string, unknown>, runOptions?: { untracked?: boolean }) =>
|
|
451
|
+
dispatchRun(
|
|
452
|
+
"query",
|
|
453
|
+
reference.__lunoraRef,
|
|
454
|
+
fnArgs,
|
|
455
|
+
runOptions?.untracked === true
|
|
456
|
+
? this.buildCtx({ bookmarks: options.bookmarks, functionPath: options.functionPath, headroom: options.headroom, identity: caller, kind: "query", scope: options.scope })
|
|
457
|
+
: queryContext(),
|
|
458
|
+
kind,
|
|
459
|
+
);
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
// A query composed from a mutation or action runs on a QUERY view of
|
|
463
|
+
// this ctx, so it behaves exactly as it does when called directly or
|
|
464
|
+
// live: same \`db\`, read hooks, trace and \`now\`, but every field that
|
|
465
|
+
// depends on the dispatch kind or the request origin is re-derived for a
|
|
466
|
+
// query — no \`ctx.origin\`, storage with no origin fallback (and no
|
|
467
|
+
// \`deleteAfterCommit\`), the unwrapped scheduler, no ActionCtx-only
|
|
468
|
+
// helpers, and a \`run*\` guard that refuses a mutation or action. A new
|
|
469
|
+
// kind- or origin-dependent ctx field must be overridden here too.
|
|
470
|
+
// Copied by descriptor so the \`ip\` getter is carried over, not read.
|
|
471
|
+
// Built on the first composed call only; a query ctx is its own view.
|
|
472
|
+
let queryView: Record<string, unknown> | undefined;
|
|
473
|
+
const queryContext = (): Record<string, unknown> => {
|
|
474
|
+
if (contextKind === "query") {
|
|
475
|
+
return ctx;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
if (queryView === undefined) {
|
|
479
|
+
const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(ctx);
|
|
480
|
+
${r.map(k=>` delete descriptors.${k};
|
|
481
|
+
`).join("")} // Writable and configurable, like the plain fields they replace.
|
|
482
|
+
const field = (value: unknown): PropertyDescriptor => ({ configurable: true, enumerable: true, value, writable: true });
|
|
483
|
+
|
|
484
|
+
queryView = Object.defineProperties({}, {
|
|
485
|
+
...descriptors,
|
|
486
|
+
origin: field(undefined),
|
|
487
|
+
scheduler: field(schedulerBase),
|
|
488
|
+
storage: field(makeStorage()),
|
|
489
|
+
}) as Record<string, unknown>;
|
|
490
|
+
installRun(queryView, "query");
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return queryView;
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
installRun(ctx, contextKind);
|
|
497
|
+
|
|
498
|
+
return ctx;
|
|
499
|
+
}`},Xt=`// Bound in-process \`ctx.run*\` composition depth so a self- or cyclically-
|
|
500
|
+
// referencing call fails loudly with a clear error instead of overflowing the
|
|
501
|
+
// stack. Tracked across the awaited handler chain (one DO invocation is
|
|
502
|
+
// single-threaded), so the counter reflects true nesting depth.
|
|
503
|
+
const MAX_RUN_DEPTH = 32;
|
|
504
|
+
let runDepth = 0;
|
|
505
|
+
|
|
506
|
+
const dispatchRun = async (
|
|
507
|
+
expected: FunctionKind,
|
|
508
|
+
functionPath: string,
|
|
509
|
+
args: Record<string, unknown>,
|
|
510
|
+
ctx: unknown,
|
|
511
|
+
// The kind of the context making the call, and — for a mutation target — the
|
|
512
|
+
// transaction wrapper to run it under. Both are supplied by \`buildCtx\`, which
|
|
513
|
+
// is the only place that knows which dispatch this \`ctx\` belongs to. Widened
|
|
514
|
+
// past \`FunctionKind\` because the registry also carries \`"stream"\`, and
|
|
515
|
+
// \`undefined\` for a ctx built outside a registered function (admin, migration).
|
|
516
|
+
callerKind?: "stream" | FunctionKind,
|
|
517
|
+
runTransactional?: (work: () => Promise<unknown>) => Promise<unknown>,
|
|
518
|
+
): Promise<unknown> => {
|
|
519
|
+
// A query is read-only. The ctx object installs \`run*\` on every kind (one
|
|
520
|
+
// shape, built once), so the TYPE is all that stops a query from writing —
|
|
521
|
+
// and a cast walks straight past it, inside a subscription re-run that can
|
|
522
|
+
// execute many times per write. Checked on the CALLER, before the registry
|
|
523
|
+
// lookup, so \`ctx.runMutation\` from a query fails identically whatever it
|
|
524
|
+
// aimed at.
|
|
525
|
+
if (callerKind === "query" && expected !== "query") {
|
|
526
|
+
throw new LunoraError(
|
|
527
|
+
"RUN_KIND_FORBIDDEN",
|
|
528
|
+
\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: a query may only compose other queries (tried to run "\${functionPath}")\`,
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
533
|
+
|
|
534
|
+
if (!registered) {
|
|
535
|
+
throw new Error(\`unknown function: \${functionPath}\`);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (registered.kind !== expected) {
|
|
539
|
+
throw new Error(\`ctx.run\${expected[0]!.toUpperCase()}\${expected.slice(1)}: "\${functionPath}" is registered as a \${registered.kind}, not a \${expected}\`);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (runDepth >= MAX_RUN_DEPTH) {
|
|
543
|
+
throw new LunoraError("RUN_DEPTH_EXCEEDED", \`ctx.run*: composition depth limit (\${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation\`);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
runDepth += 1;
|
|
547
|
+
|
|
548
|
+
try {
|
|
549
|
+
// A mutation composed from an action (or an http action) is the shape the
|
|
550
|
+
// docs prescribe for atomicity — "do the transactional reads and writes in
|
|
551
|
+
// a mutation and call it from the action". It only holds if the composed
|
|
552
|
+
// dispatch gets the same BEGIN/COMMIT span and single-writer gate the
|
|
553
|
+
// top-level mutation path gets; without it every write autocommits and a
|
|
554
|
+
// mid-handler throw leaves the earlier ones durable. A \`runMutation\` from
|
|
555
|
+
// inside a mutation rides the enclosing span instead of opening a second
|
|
556
|
+
// one (see \`runMutationTransaction\`).
|
|
557
|
+
if (runTransactional) {
|
|
558
|
+
return await runTransactional(async () => registered.handler(ctx, args));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
return await registered.handler(ctx, args);
|
|
562
|
+
} finally {
|
|
563
|
+
runDepth -= 1;
|
|
564
|
+
}
|
|
565
|
+
};`,Jt=` public override async handleRpc(functionPath: string, args: Record<string, unknown>, headroom?: TransactionHeadroomTracker, scope?: QueryReadScope, bookmarks?: DispatchBookmark): Promise<unknown> {
|
|
566
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
567
|
+
|
|
568
|
+
// Internal functions are reachable server-side only: via \`ctx.run*\`
|
|
569
|
+
// composition, or a trusted system dispatch (scheduler/cron, marked by
|
|
570
|
+
// \`isSystemDispatch()\`). A client RPC never carries that flag, so its
|
|
571
|
+
// internals stay not-found and never leak across the external boundary.
|
|
572
|
+
if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) {
|
|
573
|
+
throw new LunoraError("FUNCTION_NOT_FOUND", \`function not registered: \${functionPath}\`);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
this.ensureMigrated();
|
|
577
|
+
|
|
578
|
+
// \`headroom\`, when the caller supplied one, is threaded straight
|
|
579
|
+
// through to \`buildCtx\` — bypassing its \`this.transactionHeadroom()\`
|
|
580
|
+
// fallback (the racy shared-field read) entirely for THIS dispatch.
|
|
581
|
+
// The main \`/rpc\` path always supplies one; \`dispatchLifecycle\` /
|
|
582
|
+
// \`handleRunAs\` don't mint their own and omit it, so they keep the
|
|
583
|
+
// prior fallback behavior unchanged.
|
|
584
|
+
//
|
|
585
|
+
// \`scope\` is the reactive cache's per-dispatch read capture, threaded
|
|
586
|
+
// the same way and for the same reason: the ctx-db read hooks resolve
|
|
587
|
+
// their tracker at READ time, so binding them to the scope THIS
|
|
588
|
+
// dispatch was handed is what keeps a concurrent query's reads out of
|
|
589
|
+
// our dep set — and ours out of theirs. A dispatch with no scope (a
|
|
590
|
+
// mutation, an action, a cache-less shard) builds unbound hooks that
|
|
591
|
+
// stamp no deps.
|
|
592
|
+
const ctx = this.buildCtx({ bookmarks, functionPath, headroom, scope, trusted: registered.lifecycle === "init" });
|
|
593
|
+
|
|
594
|
+
// A mutation's writes must commit all-or-nothing, so its dispatch runs
|
|
595
|
+
// under \`runMutationTransaction\` — the ONE place that opens the span,
|
|
596
|
+
// settles the deferred schedules and flushes the deferred deletes. The
|
|
597
|
+
// same helper backs \`ctx.runMutation\` and \`runReactor\`, because a
|
|
598
|
+
// mutation reached by composition is promised exactly these guarantees
|
|
599
|
+
// and used to get none of them.
|
|
600
|
+
//
|
|
601
|
+
// The replay bookkeeping (idempotency dedup row + custom-mutator
|
|
602
|
+
// watermark advance) commits INSIDE the span via
|
|
603
|
+
// \`commitMutationBookkeeping\`, so the writes, the dedup row, and the
|
|
604
|
+
// watermark are atomic — a crash can't leave the writes durable without
|
|
605
|
+
// the replay guard. It is deliberately NOT in the shared helper: it is
|
|
606
|
+
// per-REQUEST bookkeeping, and a composed sub-mutation has no request of
|
|
607
|
+
// its own to record.
|
|
608
|
+
if (registered.kind === "mutation") {
|
|
609
|
+
return await this.runMutationTransaction(ctx, async () => {
|
|
610
|
+
const value = await registered.handler(ctx, args);
|
|
611
|
+
|
|
612
|
+
this.commitMutationBookkeeping(value);
|
|
613
|
+
|
|
614
|
+
return value;
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const result = await registered.handler(ctx, args);
|
|
619
|
+
|
|
620
|
+
// An action is not itself transactional, but \`ctx.runMutation\` runs its
|
|
621
|
+
// submutations on THIS ctx, so anything they queued after their own
|
|
622
|
+
// transaction settled lands here. A dispatch with nothing queued no-ops.
|
|
623
|
+
await this.deferPastResponse(flushDeferredDeletes(ctx));
|
|
624
|
+
|
|
625
|
+
return result;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Run one mutation handler with the atomicity every caller of a mutation is
|
|
630
|
+
* promised: a BEGIN/COMMIT span (with the single-writer gate
|
|
631
|
+
* \`ShardRunner.runInTransaction\` composes in front of it), scheduled jobs
|
|
632
|
+
* held until that span commits, and the deferred object deletes flushed
|
|
633
|
+
* only once it has.
|
|
634
|
+
*
|
|
635
|
+
* Shared by the three entry points that dispatch a mutation handler — the
|
|
636
|
+
* top-level RPC, \`ctx.runMutation\` from an action or http action, and a
|
|
637
|
+
* reactor — because the guarantee is a property of the mutation, not of how
|
|
638
|
+
* it was reached. The docs tell users to put the transactional part in a
|
|
639
|
+
* mutation and call it from the action precisely so that composition is
|
|
640
|
+
* atomic.
|
|
641
|
+
*
|
|
642
|
+
* A \`ctx.runMutation\` issued from inside a mutation is NESTED: SQLite-in-DO
|
|
643
|
+
* has no savepoints and \`runInTransaction\` rejects a second open, so it
|
|
644
|
+
* rides the enclosing span, which also owns its commit and therefore its
|
|
645
|
+
* scheduler flush.
|
|
646
|
+
*
|
|
647
|
+
* Both deferral windows are opened here and settled against the SAME
|
|
648
|
+
* outcome. The delete window is what keeps a composed mutation's queued
|
|
649
|
+
* object deletes off the caller's flush when it rolls back: \`ctx\` is
|
|
650
|
+
* shared, so without a window the keys are indistinguishable from the
|
|
651
|
+
* action's own and the action's flush destroys objects whose rows the
|
|
652
|
+
* rollback put back.
|
|
653
|
+
*/
|
|
654
|
+
private async runMutationTransaction<T>(ctx: unknown, work: () => Promise<T>): Promise<T> {
|
|
655
|
+
const settleSchedules = beginDeferredSchedules(ctx as { scheduler?: unknown });
|
|
656
|
+
// Synchronous and non-throwing (it only moves queue entries), so it can
|
|
657
|
+
// settle first on every path and cannot mask the outcome.
|
|
658
|
+
const settleDeletes = beginDeferredDeletes(ctx);
|
|
659
|
+
|
|
660
|
+
if (this.isInTransaction()) {
|
|
661
|
+
try {
|
|
662
|
+
const nested = await work();
|
|
663
|
+
|
|
664
|
+
settleDeletes(true);
|
|
665
|
+
await settleSchedules(true);
|
|
666
|
+
|
|
667
|
+
return nested;
|
|
668
|
+
} catch (error) {
|
|
669
|
+
settleDeletes(false);
|
|
670
|
+
await settleSchedules(false);
|
|
671
|
+
|
|
672
|
+
throw error;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
let result: T;
|
|
677
|
+
|
|
678
|
+
try {
|
|
679
|
+
result = await this.runInTransaction(work);
|
|
680
|
+
} catch (error) {
|
|
681
|
+
// The span rolled back, so the rows are gone and the jobs that were
|
|
682
|
+
// to run "after I commit" must go with them. Dropping them is the
|
|
683
|
+
// whole point of buffering: a persisted job for a write that never
|
|
684
|
+
// landed fires against state that does not exist.
|
|
685
|
+
//
|
|
686
|
+
// The queued object deletes go the same way, and for a sharper
|
|
687
|
+
// reason: the rows they were to clean up after are still there, and
|
|
688
|
+
// an R2 delete cannot be undone.
|
|
689
|
+
settleDeletes(false);
|
|
690
|
+
await settleSchedules(false);
|
|
691
|
+
|
|
692
|
+
throw error;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// Committed, so this span's queued keys join whatever the flush below
|
|
696
|
+
// (or an enclosing span's) will drain.
|
|
697
|
+
settleDeletes(true);
|
|
698
|
+
|
|
699
|
+
// Committed. Schedules first and AWAITED: \`runAfter(0, ...)\` is
|
|
700
|
+
// documented as the deterministic equivalent of an \`afterCommit\` hook,
|
|
701
|
+
// so the job must be enqueued after the commit, and a failure to enqueue
|
|
702
|
+
// it must be visible rather than swallowed.
|
|
703
|
+
//
|
|
704
|
+
// In a \`finally\`, because both halves of this are post-commit cleanup
|
|
705
|
+
// and neither is allowed to cancel the other. \`settleSchedules\` drains
|
|
706
|
+
// its whole queue and then rethrows what failed, so a SchedulerDO that
|
|
707
|
+
// refused one job used to take the object cleanup down with it — the
|
|
708
|
+
// rows were durably gone and their objects leaked with nothing logged.
|
|
709
|
+
try {
|
|
710
|
+
await settleSchedules(true);
|
|
711
|
+
} finally {
|
|
712
|
+
// Then the objects whose rows are now durably gone. Deliberately AFTER
|
|
713
|
+
// the span, never inside it: an R2 delete cannot roll back, so a delete
|
|
714
|
+
// issued from within a transaction that later aborts destroys data the
|
|
715
|
+
// surviving row still points at.
|
|
716
|
+
//
|
|
717
|
+
// \`flushDeferredDeletes\` never rejects — the mutation has already
|
|
718
|
+
// succeeded, so a failed cleanup must not turn into a failed response.
|
|
719
|
+
// A leaked object is reported through \`ctx.log\` instead, with its key.
|
|
720
|
+
await this.deferPastResponse(flushDeferredDeletes(ctx));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
return result;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// Only a \`mutation\` may enter the base class's single-writer gate for
|
|
727
|
+
// mutation-replay dedup — it is \`blockConcurrencyWhile\`, so gating an
|
|
728
|
+
// action would stall every other dispatch on the shard for the length of
|
|
729
|
+
// its outbound I/O, on nothing but a caller-supplied header. Unregistered
|
|
730
|
+
// paths answer \`false\`; \`handleRpc\` above rejects them anyway.
|
|
731
|
+
protected override isMutationFunction(functionPath: string): boolean {
|
|
732
|
+
return LUNORA_FUNCTIONS[functionPath]?.kind === "mutation";
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// The scheduler the deferred-schedule outbox retries through. Only the
|
|
736
|
+
// CONFIGURED one: falling back to \`schedulerStub\` would have an app with no
|
|
737
|
+
// scheduler retry every entry against a thrower until the attempt ceiling
|
|
738
|
+
// parked it, and there is nothing to park — an app with no scheduler has no
|
|
739
|
+
// \`ctx.scheduler\` call that reached the buffer in the first place.
|
|
740
|
+
protected override scheduleOutboxScheduler(): SchedulerLike | undefined {
|
|
741
|
+
return config.scheduler?.((this.env ?? {}) as Record<string, unknown>) as SchedulerLike | undefined;
|
|
742
|
+
}`,Yt=` protected override async executeSubscription(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): Promise<{ ranges?: Map<string, KeyRange[]>; result: unknown; tables: Set<string> } | null> {
|
|
743
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
744
|
+
|
|
745
|
+
if (!registered || registered.kind !== "query" || registered.visibility === "internal") {
|
|
746
|
+
return null;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
this.ensureMigrated();
|
|
750
|
+
|
|
751
|
+
const footprint = createReadFootprint();
|
|
752
|
+
// Identity is threaded EXPLICITLY from the (deferred/interleaved)
|
|
753
|
+
// subscription caller — never read from the shared per-request field
|
|
754
|
+
// here — so a concurrent RPC can't leak its identity into this re-run.
|
|
755
|
+
const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), identity, onRead: footprint.onRead, onReadRange: footprint.onReadRange });
|
|
756
|
+
const result = await registered.handler(ctx, args);
|
|
757
|
+
|
|
758
|
+
// Ranges come from THIS run's reads, never a shared field on the DO:
|
|
759
|
+
// a deferred re-run interleaves with unrelated dispatches.
|
|
760
|
+
return { ranges: footprint.ranges(), result, tables: footprint.tables };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
protected override executeStream(functionPath: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): null | { durable?: { ttlMs?: number }; iterator: (signal: AbortSignal) => AsyncIterable<unknown> } {
|
|
764
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
765
|
+
|
|
766
|
+
if (!registered || registered.kind !== "stream" || registered.visibility === "internal") {
|
|
767
|
+
return null;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
this.ensureMigrated();
|
|
771
|
+
|
|
772
|
+
return {
|
|
773
|
+
...(registered.durable ? { durable: registered.durable as { ttlMs?: number } } : {}),
|
|
774
|
+
// Identity threaded EXPLICITLY from the socket, exactly as
|
|
775
|
+
// \`executeSubscription\` above: the iterator is pulled after this
|
|
776
|
+
// frame returned, interleaved with unrelated dispatches, so
|
|
777
|
+
// \`buildCtx\`'s per-request fallback would run an \`rls()\` /
|
|
778
|
+
// \`ctx.auth\` stream as nobody — or as a concurrent RPC's caller.
|
|
779
|
+
iterator: (signal) => (registered.handler as (context: unknown, args: Record<string, unknown>, signal: AbortSignal) => AsyncIterable<unknown>)(this.buildCtx({ functionPath, identity }), args, signal),
|
|
780
|
+
};
|
|
781
|
+
}`,Zt=a=>{const r={};for(const e of a.tables){const n={};for(const[t,o]of Object.entries(e.shape)){const d=K(o);d.kind==="id"&&d.tableName!==void 0&&(n[t]=d.tableName)}Object.keys(n).length>0&&(r[e.name]=n)}return r},er=a=>{const r={};for(const e of a.tables){const n=[];for(const[t,o]of Object.entries(e.shape))K(o).kind==="storage"&&n.push(t);n.length>0&&(r[e.name]=n)}return r},tr=a=>{const r={};for(const e of a.tables){const n=[...e.indexes.map(t=>({fields:[...t.fields],name:t.name,type:"index",...t.unique===!0?{unique:!0}:{}})),...e.searchIndexes.map(t=>({fields:[t.field,...t.filterFields??[]],name:t.name,type:"search"})),...(e.geoIndexes??[]).map(t=>({fields:[t.field],name:t.name,type:"geo"})),...e.rankIndexes.map(t=>({fields:t.sortBy.map(o=>o.field),name:t.name,type:"rank"})),...e.vectorIndexes.map(t=>({fields:t.field===void 0?[]:[t.field],name:t.name,type:"vector"}))];n.length>0&&(r[e.name]=n)}return r},rr=a=>{const r=[];for(const e of a.tables)!e.ttl||e.shardMode==="global"||r.push({...e.ttl.after===void 0?{}:{after:e.ttl.after},field:e.ttl.field,...e.softDelete?{softDeleteField:e.softDelete.field}:{},table:e.name});return r},ar=a=>{if(a.kind!=="union"||a.members===void 0||a.members.length===0)return;const r=[];for(const e of a.members){if(e.kind!=="literal"||e.literalValue===void 0)return;try{const n=JSON.parse(e.literalValue);if(typeof n!="string")return;r.push(n)}catch{return}}return r},nr=(a,r,e)=>{const n=K(r),t={name:a,optional:Ht(r),type:n.kind};if(n.kind==="id"&&n.tableName!==void 0){t.ref=n.tableName;const d=e.get(a);d!==void 0&&(t.onDelete=d)}n.kind==="storage"&&(t.isStorage=!0,n.bucket!==void 0&&(t.bucket=n.bucket));const o=ar(n);return o!==void 0&&(t.enumValues=o),n.column?.notNull===!1&&(t.nullable=!0),t},sr=a=>{const r={};for(const e of a.tables){const n=[{name:"_id",optional:!1,pk:!0,type:"id"},{name:"_creationTime",optional:!1,type:"number"},...e.commitOrdered===!0?[{name:"_commitSeq",optional:!1,type:"number"}]:[]],t=new Map(e.relations.filter(o=>o.kind==="one").map(o=>[o.field,o.onDelete]));for(const[o,d]of Object.entries(e.shape))n.push(nr(o,d,t));r[e.name]=n}return r},or=({hasMutators:a,hasShapes:r,rlsData:e})=>{const n=r?`
|
|
782
|
+
protected override resolveShape(name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined {
|
|
783
|
+
const shape = LUNORA_SHAPES[name];
|
|
784
|
+
|
|
785
|
+
if (!shape) {
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
this.ensureMigrated();
|
|
790
|
+
|
|
791
|
+
// Trusted ctx from the socket's OWN verified identity — the client
|
|
792
|
+
// supplies only the shape name + args; \`compileWhere\` validates the
|
|
793
|
+
// args then runs the shape's \`where(ctx, args)\` under that identity,
|
|
794
|
+
// so which rows replicate is a server decision (reads-as-permissions).
|
|
795
|
+
const ctx = this.buildCtx({ functionPath: \`__shape__:\${name}\`, identity });
|
|
796
|
+
// \`ownerField\` resolves an \`owner: true\` shape: only here is the table's
|
|
797
|
+
// \`.ownedBy(field)\` column in scope, so the DO hands it to the shape
|
|
798
|
+
// rather than every shape restating the ownership check in its \`where\`.
|
|
799
|
+
const shapeWhere = shape.compileWhere(ctx, args, {
|
|
800
|
+
ownerField: (schema as unknown as { tables: Record<string, { ownerField?: string }> }).tables[shape.table]?.ownerField,
|
|
801
|
+
}) as unknown as WhereInput;
|
|
802
|
+
|
|
803
|
+
// AND-compose with the read policies this SHAPE declares
|
|
804
|
+
// (\`defineShape({ use: [guard] })\`, pre-indexed into
|
|
805
|
+
// \`shape.rlsRegistry\`). A shape runs no procedure, so the
|
|
806
|
+
// \`.use(rls(...))\` middleware never fires; without this merge its
|
|
807
|
+
// reads would bypass the read policies it opted into.
|
|
808
|
+
// \`composeShapeReadWhere\` evaluates them under this same trusted ctx
|
|
809
|
+
// and fails closed under a \`.rls("required")\` schema for a
|
|
810
|
+
// non-\`.public()\` table the shape declared no read policy for.
|
|
811
|
+
//
|
|
812
|
+
// The registry is the shape's OWN — never one folded from every
|
|
813
|
+
// registered function. A project-wide union let one admin-only
|
|
814
|
+
// procedure's allow-all read policy unrestrict every shape on the
|
|
815
|
+
// table; see the SCOPE note in \`shape-read-base.ts\`.
|
|
816
|
+
//
|
|
817
|
+
// It is NOT identical to the request-time path, and must not be
|
|
818
|
+
// described as such: roles come from the identity's \`roles\` claim
|
|
819
|
+
// only, because no middleware runs here to contribute
|
|
820
|
+
// \`ctx.auth.roles\`. Derive roles at the identity if a policy gates
|
|
821
|
+
// on them — see \`shape-read-base.ts\`.
|
|
822
|
+
const effectiveWhere = composeShapeReadWhere(shape.rlsRegistry, {
|
|
823
|
+
ctx,
|
|
824
|
+
identity: identity?.identity ?? null,
|
|
825
|
+
rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required",
|
|
826
|
+
shapeWhere,
|
|
827
|
+
table: shape.table,
|
|
828
|
+
tablePublic: (schema as unknown as { tables: Record<string, { isPublic?: boolean }> }).tables[shape.table]?.isPublic === true,
|
|
829
|
+
userId: identity?.userId ?? null,
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
// A live shape pokes only from its OWN shard's op-log, so a \`where()\`
|
|
833
|
+
// that joins to a \`.shardBy()\` table (rows in another DO) is rejected
|
|
834
|
+
// here — the first point the compiled predicate + shard modes are both
|
|
835
|
+
// known. Remedy: denormalize, or move the joined table to \`.global()\`.
|
|
836
|
+
assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table);
|
|
837
|
+
|
|
838
|
+
// A \`.global()\` table lives in D1 (no per-DO op-log): flag it so the
|
|
839
|
+
// base serves it through the latency-tiered poll path (\`readGlobalShapeRows\`)
|
|
840
|
+
// instead of the CDC poke path.
|
|
841
|
+
const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global";
|
|
842
|
+
|
|
843
|
+
return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table };
|
|
844
|
+
}
|
|
845
|
+
`:"",t=r?[...new Set(e.policies.filter(c=>c.on==="read"&&c.table!=="").map(c=>c.table))].toSorted((c,w)=>c.localeCompare(w)):[],o=t.length>0?`
|
|
846
|
+
/** Refuses to boot a shape that would replicate around the read policies its table is governed by (\`defineShape({ use })\` is how a shape opts in; \`use: []\` acknowledges an ungoverned one). */
|
|
847
|
+
assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(t)}, (schema as unknown as { rlsMode?: string }).rlsMode === "required");
|
|
848
|
+
`:"";return{customMutatorOverride:a?`
|
|
849
|
+
protected override isCustomMutator(functionPath: string): boolean {
|
|
850
|
+
return LUNORA_MUTATOR_PATHS.has(functionPath);
|
|
851
|
+
}
|
|
852
|
+
`:"",shapeGuardImport:r?"assertShapeShardable, ":"",shapeReadPolicyAssertion:o,shapeReadPolicyImport:o===""?"":"assertShapesDeclareReadPolicies, ",shapeResolveOverride:n}},ir=(a,r)=>a?`
|
|
853
|
+
protected override async readGlobalShapeRows(resolved: { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string }, identity?: SubscriptionIdentity): Promise<Array<{ doc: Record<string, unknown>; id: string }>> {
|
|
854
|
+
const env = this.env as Record<string, unknown>;
|
|
855
|
+
// A shape read performs no writes, so the widened request only needs
|
|
856
|
+
// the inbound bookmark (pin the membership drain to the caller's own
|
|
857
|
+
// prior writes) — no \`onBookmark\` here.
|
|
858
|
+
//
|
|
859
|
+
// The two identity members are named rather than spread, matching the
|
|
860
|
+
// dispatch-path request built in \`buildCtx\`. A spread would also hand
|
|
861
|
+
// the global writer \`ip\`, and \`globalShapeReadKey\` — the per-flush
|
|
862
|
+
// cache in front of this read — keys on identity + userId only. Equal
|
|
863
|
+
// keys must mean equal rows, so a field the writer can scope by has to
|
|
864
|
+
// be either in the key or out of the request; it is out.
|
|
865
|
+
const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity: identity?.identity, userId: identity?.userId };
|
|
866
|
+
const globalDb: DatabaseWriterLike = ${r}?.(env, globalRequest) ?? globalDbStub;
|
|
867
|
+
const rows: Array<{ doc: Record<string, unknown>; id: string }> = [];
|
|
868
|
+
|
|
869
|
+
let cursor: null | string = null;
|
|
870
|
+
|
|
871
|
+
// Drain every page of the global membership so the seed/diff sees the
|
|
872
|
+
// full rowset (D1 \`findMany\` is paginated). Stop one row past the cap:
|
|
873
|
+
// a broad \`.global()\` shape would otherwise materialize an unbounded
|
|
874
|
+
// array before the caller's \`withinGlobalShapeBound\` check rejects it,
|
|
875
|
+
// so bail early and let the caller fail it closed.
|
|
876
|
+
do {
|
|
877
|
+
// eslint-disable-next-line no-await-in-loop -- sequential page drain to assemble the full membership
|
|
878
|
+
const page = await globalDb.findMany(resolved.table, { cursor, where: resolved.effectiveWhere });
|
|
879
|
+
|
|
880
|
+
for (const doc of page.page) {
|
|
881
|
+
rows.push({ doc, id: String((doc as { _id?: unknown })._id) });
|
|
882
|
+
|
|
883
|
+
if (rows.length > ShardDOBase.GLOBAL_SHAPE_MAX_ROWS) {
|
|
884
|
+
return rows;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
cursor = page.isDone ? null : page.continueCursor;
|
|
889
|
+
} while (cursor !== null);
|
|
890
|
+
|
|
891
|
+
return rows;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
protected override async readGlobalChangedTables(sinceSeq: number, cursorOnly?: boolean): Promise<{ cursor: number; floor?: number; tables: string[] } | undefined> {
|
|
895
|
+
const env = this.env as Record<string, unknown>;
|
|
896
|
+
// Metadata-only: this asks the global changelog which TABLES moved,
|
|
897
|
+
// never what changed in them, so it costs one small read per poll tick
|
|
898
|
+
// for the whole shard — and a tick whose answer omits a shape's table
|
|
899
|
+
// skips that shape's membership drain entirely.
|
|
900
|
+
// Named local, not an inline object literal — same reason as the
|
|
901
|
+
// dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
|
|
902
|
+
// on the narrower Hyperdrive thunk's \`request\` type, and an inline
|
|
903
|
+
// literal trips an excess-property error (TS2353) that makes the
|
|
904
|
+
// emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
|
|
905
|
+
// a \`defineShape\`. The Hyperdrive factory simply never reads it.
|
|
906
|
+
const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
|
|
907
|
+
const globalDb: DatabaseWriterLike = ${r}?.(env, globalRequest) ?? globalDbStub;
|
|
908
|
+
|
|
909
|
+
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
910
|
+
}
|
|
911
|
+
`:"",dr=a=>({externalSourceOverride:a?`
|
|
912
|
+
protected override async pollExternalSources(trace?: TraceRefLike): Promise<number | undefined> {
|
|
913
|
+
const env = (this.env ?? {}) as Record<string, unknown>;
|
|
914
|
+
const sourced = Object.entries((schema as unknown as SchemaLike).tables)
|
|
915
|
+
.map(([table, definition]) => [table, (definition as { externalSource?: ExternalSourceLike }).externalSource] as const)
|
|
916
|
+
.filter((entry): entry is [string, ExternalSourceLike] => entry[1] !== undefined);
|
|
917
|
+
|
|
918
|
+
if (sourced.length === 0) {
|
|
919
|
+
return undefined;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const shardKey = this.currentShardKey();
|
|
923
|
+
const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike;
|
|
924
|
+
|
|
925
|
+
let clients = sourceClientCache.get(this);
|
|
926
|
+
|
|
927
|
+
if (clients === undefined) {
|
|
928
|
+
clients = new Map();
|
|
929
|
+
sourceClientCache.set(this, clients);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
let polledAt = sourcePollAtCache.get(this);
|
|
933
|
+
|
|
934
|
+
if (polledAt === undefined) {
|
|
935
|
+
polledAt = new Map();
|
|
936
|
+
sourcePollAtCache.set(this, polledAt);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const now = Date.now();
|
|
940
|
+
// \`nextDueAt\` tracks the EARLIEST next-due timestamp across every
|
|
941
|
+
// non-manual source; the shared alarm re-arms there instead of the
|
|
942
|
+
// fixed 2 s global-shape floor, so a large \`refresh.everyMs\` actually
|
|
943
|
+
// sleeps until it's due. Stays \`undefined\` when every source is
|
|
944
|
+
// \`refresh: "manual"\`, so the shared alarm goes idle for this tier.
|
|
945
|
+
let nextDueAt: number | undefined;
|
|
946
|
+
|
|
947
|
+
for (const [table, source] of sourced) {
|
|
948
|
+
if (source.refresh === "manual") {
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
if (isSourceDue(source.refresh, polledAt.get(table), now)) {
|
|
953
|
+
try {
|
|
954
|
+
let client = clients.get(source.binding);
|
|
955
|
+
|
|
956
|
+
if (client === undefined) {
|
|
957
|
+
client = config.sourceClient?.(env, source.binding);
|
|
958
|
+
|
|
959
|
+
if (client !== undefined) {
|
|
960
|
+
clients.set(source.binding, client);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
if (client === undefined) {
|
|
965
|
+
// No SqlClient resolved for this binding (host never wired
|
|
966
|
+
// \`config.sourceClient\`, or wired it wrong). Surface it in the
|
|
967
|
+
// Logs panel and stamp \`polledAt\` so a persistent misconfig backs
|
|
968
|
+
// off to \`refresh.everyMs\` instead of retrying every alarm tick.
|
|
969
|
+
this.recordExternalSourceError(table, new Error(\`external-source: no sourceClient resolved for binding "\${source.binding}"\`), trace);
|
|
970
|
+
} else {
|
|
971
|
+
// A FRESH tracker per TABLE, not one shared across the whole
|
|
972
|
+
// loop: one table's runaway pull must not spend a budget a
|
|
973
|
+
// sibling table needs, and a limit hit here must not block
|
|
974
|
+
// that sibling from getting its own full budget this tick.
|
|
975
|
+
const writer = createShardCtxDb({
|
|
976
|
+
// Admin and maintenance writes go through the SAME reactive-cache hooks as
|
|
977
|
+
// a user mutation. Without this, a studio row edit, a TTL sweep, an admin
|
|
978
|
+
// import, a CDC apply or a data-migration backfill writes without
|
|
979
|
+
// invalidating, and the next query answers from the pre-write snapshot.
|
|
980
|
+
...this.ctxDbTuning(),
|
|
981
|
+
broadcast: (delta) => {
|
|
982
|
+
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
983
|
+
},
|
|
984
|
+
cdc: config.cdc ?? false,
|
|
985
|
+
headroom: this.alarmHeadroom(),
|
|
986
|
+
scheduler,
|
|
987
|
+
schema: schema as unknown as SchemaLike,
|
|
988
|
+
sql: this.sql as SqlExec,
|
|
989
|
+
});
|
|
990
|
+
|
|
991
|
+
if (source.mode === "incremental") {
|
|
992
|
+
// Incremental (plan 136): pull only rows past the durable
|
|
993
|
+
// watermark (or a full-pull seed/reconcile), upsert-only.
|
|
994
|
+
// eslint-disable-next-line no-await-in-loop -- one sourced table at a time; sequential keeps the writer transaction simple
|
|
995
|
+
await pullExternalSourceIncrementalTick(this.sql as SqlExec, writer, client, table, source, shardKey, now);
|
|
996
|
+
} else {
|
|
997
|
+
// eslint-disable-next-line no-await-in-loop -- one sourced table at a time; slices are independent but small and sequential keeps the writer transaction simple
|
|
998
|
+
await pullExternalSourceTick(this.sql as SqlExec, writer, client, table, source, shardKey);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// Timestamp AFTER the poll finishes, not the batch-start \`now\` — a
|
|
1003
|
+
// poll that outruns \`everyMs\` must not make \`nextDueAt\` (below)
|
|
1004
|
+
// stale-immediate and re-arm the alarm in a hammering loop.
|
|
1005
|
+
polledAt.set(table, Date.now());
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
if (error instanceof LunoraError && error.code === "TRANSACTION_LIMIT_EXCEEDED") {
|
|
1008
|
+
// Batch full, not a genuine failure. Incremental mode only
|
|
1009
|
+
// persists its watermark AFTER a full apply (see
|
|
1010
|
+
// \`pullExternalSourceIncrementalTick\`), so this throw left it
|
|
1011
|
+
// untouched — the next tick safely re-pulls/re-applies the
|
|
1012
|
+
// SAME slice (idempotent upsert). Full-pull mode (and an
|
|
1013
|
+
// incremental source's own occasional full-pull/reconcile
|
|
1014
|
+
// sweep) has no resumable cursor at all — deliberately not
|
|
1015
|
+
// inventing one here; a retry just redoes the whole pull,
|
|
1016
|
+
// safe if wasteful. Either way: warn instead of
|
|
1017
|
+
// \`recordExternalSourceError\`, and leave \`polledAt\`
|
|
1018
|
+
// UNCHANGED (skip the stamp below via \`continue\`) so this
|
|
1019
|
+
// table stays "due" and \`nextPollAlarmTarget\`'s existing
|
|
1020
|
+
// due-now floor re-arms the shared alarm promptly — not a
|
|
1021
|
+
// fresh \`setAlarm(now)\`.
|
|
1022
|
+
this.recordExternalSourceWarning(
|
|
1023
|
+
table,
|
|
1024
|
+
\`external-source poll for "\${table}" hit the transaction limit mid-batch; resuming next tick: \${error.message}\`,
|
|
1025
|
+
trace,
|
|
1026
|
+
);
|
|
1027
|
+
|
|
1028
|
+
nextDueAt = nextDueAt === undefined ? now : Math.min(nextDueAt, now);
|
|
1029
|
+
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
this.recordExternalSourceError(table, error, trace);
|
|
1034
|
+
// Stamp on failure too, so a persistently failing source throttles
|
|
1035
|
+
// to \`refresh.everyMs\` rather than being hammered every tick.
|
|
1036
|
+
polledAt.set(table, Date.now());
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
// This source's own next-due time, read AFTER the poll-or-skip above
|
|
1041
|
+
// so a just-polled source reports \`now + everyMs\` (its FRESH due
|
|
1042
|
+
// time), not the stale pre-poll one. An omitted \`refresh\` (poll
|
|
1043
|
+
// every tick) is due again immediately.
|
|
1044
|
+
const sourceNextDueAt = source.refresh === undefined ? now : (polledAt.get(table) ?? now) + source.refresh.everyMs;
|
|
1045
|
+
|
|
1046
|
+
nextDueAt = nextDueAt === undefined ? sourceNextDueAt : Math.min(nextDueAt, sourceNextDueAt);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
return nextDueAt;
|
|
1050
|
+
}
|
|
1051
|
+
`:"",sourceBootstrap:a?`
|
|
1052
|
+
const autoSourced = Object.values((schema as unknown as SchemaLike).tables).some((definition) => {
|
|
1053
|
+
const source = (definition as { externalSource?: ExternalSourceLike }).externalSource;
|
|
1054
|
+
|
|
1055
|
+
return source !== undefined && source.refresh !== "manual";
|
|
1056
|
+
});
|
|
1057
|
+
|
|
1058
|
+
if (autoSourced) {
|
|
1059
|
+
void this.scheduleSourcePoll();
|
|
1060
|
+
}
|
|
1061
|
+
`:"",sourceClientCacheConst:a?`
|
|
1062
|
+
const sourceClientCache = new WeakMap<object, Map<string, SourceClientLike>>();
|
|
1063
|
+
const sourcePollAtCache = new WeakMap<object, Map<string, number>>();
|
|
1064
|
+
`:""}),cr=(a,r)=>{const e=r.length>0,t=a?C("vectorsStub: VectorSearchLike","ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().",["deleteByIds","getByIds","query","upsert","upsertNow"]):"",o=e?` const vectorShardKey = this.currentShardKey();
|
|
1065
|
+
`:"",d=e?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",f=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...e?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${r.map(S=>JSON.stringify(S)).join(", ")}]`]:[]].join(", ")} }`,c=a?`
|
|
1066
|
+
const vectorSync = this.vectorSync(env);
|
|
1067
|
+
// Vectorize lives outside this shard's SQLite, so a query whose result
|
|
1068
|
+
// depends on a similarity search cannot be proven current on reconnect —
|
|
1069
|
+
// an unrelated upsert (or a re-index) moves the matches without touching
|
|
1070
|
+
// \`__cdc_log\`. Only \`ctx.vectors\` is wrapped: the write-through
|
|
1071
|
+
// vector-sync hook keeps calling the bare facade.
|
|
1072
|
+
const bareVectors = vectorSync?.vectors ?? vectorsStub;
|
|
1073
|
+
const vectors = markUnvouchableReads(bareVectors, options.onRead, ["getByIds", "query"]);
|
|
1074
|
+
const onWrite = vectorSync?.onWrite;
|
|
1075
|
+
`:"";return{vectorSyncMethod:a?`
|
|
1076
|
+
private vectorSync(env: Record<string, unknown>): { backfill: VectorBackfillSync; onWrite: WriteHook; vectors: VectorSearchLike } | undefined {
|
|
1077
|
+
if (!config.vectors) {
|
|
1078
|
+
return undefined;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const lunora = createVectors({ indexes: config.vectors(env) });
|
|
1082
|
+
${o} const vectors = createContextVectors(lunora${f});
|
|
1083
|
+
|
|
1084
|
+
return {
|
|
1085
|
+
backfill: createVectorBackfillSync({ ${d}schema: schema as unknown as VectorSchemaLike, upsertMany: lunora.upsertMany, vectors }),
|
|
1086
|
+
onWrite: createVectorSyncHook({ ${d}schema: schema as unknown as VectorSchemaLike, vectors }),
|
|
1087
|
+
vectors,
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// \`__lunora_admin__:backfillVectors\`: the rows that predate a vector index,
|
|
1092
|
+
// a page at a time, each page ordered on the after-commit chain so it
|
|
1093
|
+
// never lands over a newer write's vector.
|
|
1094
|
+
protected override async runShardVectorBackfill(options: { maxPages?: number; restart?: boolean }): Promise<VectorBackfillProgress> {
|
|
1095
|
+
this.ensureMigrated();
|
|
1096
|
+
|
|
1097
|
+
const vectorSync = this.vectorSync((this.env ?? {}) as Record<string, unknown>);
|
|
1098
|
+
|
|
1099
|
+
if (!vectorSync) {
|
|
1100
|
+
throw new LunoraError("NOT_IMPLEMENTED", "vector backfill is unavailable: no vectors configured. Pass \`vectors\` to createShardDO().");
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
return backfillVectorIndexes(this.sql as SqlExec, vectorBackfillTargets(schema as unknown as VectorSchemaLike), vectorSync.backfill, {
|
|
1104
|
+
...options,
|
|
1105
|
+
ordered: async (read, work) => this.runOrderedAfterWrites(read, work),
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
`:"",vectorsBuild:c,vectorsStub:t}},kr=({advisories:a=[],advisorProcedures:r=[],agents:e=[],capabilities:n=new Set,containers:t=[],env:o,flagKeys:d=[],hasFlags:m=!1,hasNotify:f=!1,hasVectors:c=!0,maskMetadata:w,mutators:S=[],queues:y=[],rlsMetadata:L,schema:i,schemaSnapshot:g,shapes:I=[],storageRules:_,studioFeatures:M,services:A=[],topics:P=[],useUmbrella:q=!1,workflows:R=[]})=>{const l=Kt(q),D=S.length>0,v=I.length>0,k=g===void 0?"":kt(g),te=g===void 0?"":`
|
|
1109
|
+
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1110
|
+
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(St(g))}, json: ${JSON.stringify(k)} };
|
|
1111
|
+
`,re=g===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",b=Tt(n),T=Ot(m,l.flags),N=Et(d,m,l.flags),$=jt(f),F=Ct(o),{build:ae,contextField:ne,importLines:se,specs:oe}=Lt(At(y)),{build:ie,contextField:de,importLines:ce,specs:le}=It(P,y),U=_t(A,l.server),{build:he,contextField:ue,importLines:pe,specs:me}=Mt(t,i.jurisdiction),{build:ge,contextField:be,importLines:fe,specs:we}=Pt(R),{build:ye,contextField:ve,importLines:ke,specs:Se}=qt(e),{build:Re,configField:xe,contextField:Ae,imports:De,stub:Te}=Nt(n.has("payments")),Oe=a,Ee=r,G=L??{policies:[],roles:[]},Ce=w??{columns:[]},Le=_??{rules:[]},Ie=M??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:_e,override:Me}=$t(R),{constant:Pe,override:qe}=Ft(y),u=c&&i.vectorIndexes.length>0,B=new Set(i.tables.filter(s=>Dt(s)).map(s=>s.name)),Q=u&&i.vectorIndexes.some(s=>B.has(s.table)),x=i.tables.some(s=>s.shardMode==="global"),W=Ut(B),j=i.tables.some(s=>Rt(s)),z=i.tables.some(s=>xt(s)),O=i.tables.some(s=>s.externalSource!==void 0),X=i.tables.some(s=>s.memory===!0),H=i.tables.some(s=>s.shardMode!=="global"&&s.searchIndexes.length>0);if(z&&j)throw new vt("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const V=i.tables.length>0,Ne=Zt(i),$e=tr(i),Fe=sr(i),Ue=er(i),J=rr(i),Y=Bt(u,R.length>0,y.length>0,m,H);v&&Y.push("WhereInput");const Z=Wt(x),{customMutatorOverride:Be,shapeGuardImport:We,shapeReadPolicyAssertion:je,shapeReadPolicyImport:He,shapeResolveOverride:Ve}=or({hasMutators:D,hasShapes:v,rlsData:G}),E=[`import type { ${Y.join(", ")} } from "${l.do}";`,`import { applyCdcChanges, ${H?"backfillSearchIndexes, ":""}${u?"backfillVectorIndexes, ":""}buildReprojectionMigration, ${X?"clearMemoryTables, ":""}${We}createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, ${O?"isSourceDue, pullExternalSourceIncrementalTick, pullExternalSourceTick, ":""}markUnvouchableReads, ${Q?"ROOT_SHARD_NAME, ":""}runDataMigration, runShardMigrations, ${Z.importFragment}ShardDO as ShardDOBase } from "${l.do}";`,...O?[`import type { ExternalSourceLike, SourceClientLike, TraceRefLike } from "${l.do}";`]:[],v?`import { asBucketStorage, ${He}beginDeferredDeletes, beginDeferredSchedules, composeShapeReadWhere, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`:`import { asBucketStorage, beginDeferredDeletes, beginDeferredSchedules, createSecrets, flushDeferredDeletes, LunoraError, withDeferredDeletes, withDeferredSchedules } from "${l.server}";`];V&&E.push(`import { bindOrm, bindTableFacade } from "${l.server}";`),u&&E.push('import type { SchemaLike as VectorSchemaLike, VectorBackfillSync, VectorizeIndexLike, VectorSearchLike } from "@lunora/bindings/vectors";','import { createContextVectors, createVectorBackfillSync, createVectors, createVectorSyncHook, vectorBackfillTargets } from "@lunora/bindings/vectors";'),E.push(...b.importLines,...T.importLines,...$.importLines,...F.importLines,...pe,...fe,...se,...ce,...U.importLines,...ke,...De,"",'import schema from "../schema.js";',`import { ${["LUNORA_FUNCTIONS","LUNORA_LIFECYCLE_HOOKS","LUNORA_MIGRATIONS",...D?["LUNORA_MUTATOR_PATHS"]:[],...v?["LUNORA_SHAPES"]:[]].join(", ")} } from "./functions.js";`);const Ke=u?`
|
|
1112
|
+
vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ge=z?`
|
|
1113
|
+
d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Qe=j?`
|
|
1114
|
+
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ze=O?`
|
|
1115
|
+
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Xe="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Je="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",Ye="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Ze=x?C("globalDbStub: DatabaseWriterLike",Xe,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:et,vectorsBuild:tt,vectorsStub:rt}=cr(u,Q?i.vectorIndexes.filter(s=>B.has(s.table)).map(s=>s.name):[]),at=`{
|
|
1116
|
+
...this.ctxDbTuning(),
|
|
1117
|
+
auth: { identity: identity ?? null, userId: userId ?? null },
|
|
1118
|
+
broadcast: (delta) => {
|
|
1119
|
+
this.recordChangedTable(delta.table, delta.indexKeys);
|
|
1120
|
+
},
|
|
1121
|
+
// Read at call time, not captured: the baseline belongs to the
|
|
1122
|
+
// dispatch in flight, and a queued mutation admitted after a
|
|
1123
|
+
// sibling's prologue must be judged against ITS caller's cursor.
|
|
1124
|
+
baselineSeq: () => this.getCurrentBaselineSeq(),
|
|
1125
|
+
cdc: config.cdc ?? false,
|
|
1126
|
+
// A dispatch with NO caller identity runs system-trusted: RLS scopes
|
|
1127
|
+
// rows to a user, and these have no user to scope to. This is the tier
|
|
1128
|
+
// migrations, imports and the external-source poll loop already run in
|
|
1129
|
+
// (see \`adminWriterPrelude\`). Only \`onShardInit\` and \`onQueryChange\`
|
|
1130
|
+
// reach it; \`onConnect\`/\`onDisconnect\` carry a verified identity and
|
|
1131
|
+
// stay guarded like any request.
|
|
1132
|
+
enforceRls: options.trusted !== true,
|
|
1133
|
+
headroom: options.headroom ?? this.transactionHeadroom(),
|
|
1134
|
+
// A live predicate, not a flag: the transaction opens AFTER this ctx
|
|
1135
|
+
// is built (a mutation dispatch wraps the handler), so only a call-time
|
|
1136
|
+
// read reports the truth. \`_commitSeq\` reuses one sequence across
|
|
1137
|
+
// writes only while they commit together — an action is not wrapped, so
|
|
1138
|
+
// each of its writes allocates its own.
|
|
1139
|
+
inTransaction: () => this.isInTransaction(),
|
|
1140
|
+
onIndexUse: this.getCtxDbIndexUseHook(),
|
|
1141
|
+
onStalePatchDropped: (event) => {
|
|
1142
|
+
this.recordStalePatchDropped(event);
|
|
1143
|
+
},
|
|
1144
|
+
// Bound to THIS dispatch's reactive-cache read scope (\`handleRpc\`
|
|
1145
|
+
// threads it in), so two concurrent queries never stamp each
|
|
1146
|
+
// other's dep sets. \`executeSubscription\` overrides both with its
|
|
1147
|
+
// own \`ReadFootprint\` pair instead, and a dispatch with neither
|
|
1148
|
+
// gets an unbound hook that stamps no deps.
|
|
1149
|
+
onRead: options.onRead ?? this.getCtxDbReadHook(options.scope),
|
|
1150
|
+
// Left \`undefined\` when there is no scope so \`createShardCtxDb\`
|
|
1151
|
+
// keeps its own "degrade a provable slice to a whole-table dep"
|
|
1152
|
+
// fallback rather than reporting into a no-op.
|
|
1153
|
+
onReadRange: options.onReadRange ?? (options.scope === undefined ? undefined : this.getCtxDbReadRangeHook(options.scope)),${u?`
|
|
1154
|
+
// Vectorize is outside this shard's SQLite and cannot roll back, so
|
|
1155
|
+
// the sync is held until the mutation's transaction has COMMITTED
|
|
1156
|
+
// (\`deferAfterCommit\`) instead of running inline. Inline, a write
|
|
1157
|
+
// that later aborted left a vector pointing at a row that does not
|
|
1158
|
+
// exist — which a search then surfaces — and a rolled-back delete
|
|
1159
|
+
// left the row with its vector already purged. Outside a
|
|
1160
|
+
// transaction (an action) nothing is open and it runs at once.
|
|
1161
|
+
onWrite: onWrite === undefined ? undefined : (event) => this.deferAfterCommit(() => onWrite(event)),`:""}
|
|
1162
|
+
scheduler,
|
|
1163
|
+
schema: schema as unknown as SchemaLike,
|
|
1164
|
+
sql: this.sql as SqlExec,
|
|
1165
|
+
storage,${x?`
|
|
1166
|
+
globalDb,`:""}
|
|
1167
|
+
}`,nt=u?`
|
|
1168
|
+
vectors,`:"",st=V?`
|
|
1169
|
+
orm: bindOrm(facade),`:"",ee=j?"config.hyperdriveGlobal":"config.d1",ot=x?` const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark(), identity, onBookmark: (bookmarkValue: string | undefined) => { if (options.bookmarks !== undefined) { options.bookmarks.value = bookmarkValue; } }, userId };
|
|
1170
|
+
const globalDb: DatabaseWriterLike = ${ee}?.(env, globalRequest) ?? globalDbStub;
|
|
1171
|
+
`:"",it=ir(v&&x,ee),{externalSourceOverride:dt,sourceBootstrap:ct,sourceClientCacheConst:lt}=dr(O),ht=`
|
|
1172
|
+
protected override async runShardInit(): Promise<void> {
|
|
1173
|
+
this.ensureMigrated();
|
|
1174
|
+
${X?` clearMemoryTables(this.sql as SqlExec, schema as unknown as SchemaLike);
|
|
1175
|
+
`:""}
|
|
1176
|
+
await this.dispatchShardInit();
|
|
1177
|
+
}
|
|
1178
|
+
`,ut=J.length>0?`
|
|
1179
|
+
if (LUNORA_TTL_SWEEPS.length > 0) {
|
|
1180
|
+
void this.scheduleTtlSweep();
|
|
1181
|
+
}
|
|
1182
|
+
`:"",pt=`
|
|
1183
|
+
public constructor(state: ShardDOState, env: unknown) {
|
|
1184
|
+
super(state, env, {
|
|
1185
|
+
// Every writer this file builds spreads the ctxDbTuning() slice —
|
|
1186
|
+
// the user-facing ctx and all three admin/maintenance writers — so
|
|
1187
|
+
// the base class can drop its coarse invalidation backstop. Only the
|
|
1188
|
+
// emitter can know that; a hand-written subclass leaves this unset
|
|
1189
|
+
// and keeps the backstop.
|
|
1190
|
+
ctxDbCacheWired: true,
|
|
1191
|
+
...(config.maxRelationKeys === undefined ? {} : { maxRelationKeys: config.maxRelationKeys }),
|
|
1192
|
+
...(config.reactiveCache ? { reactiveCache: config.reactiveCache === true ? {} : config.reactiveCache } : {}),
|
|
1193
|
+
...(config.relationExistsPushDown === undefined ? {} : { relationExistsPushDown: config.relationExistsPushDown }),
|
|
1194
|
+
// The same sink \`buildCtx\` resolves, made reachable before any ctx
|
|
1195
|
+
// exists — a trigger that fails first still flushes and fuses.
|
|
1196
|
+
...(config.observability === undefined ? {} : { telemetrySink: () => config.observability?.((env ?? {}) as Record<string, unknown>) }),
|
|
1197
|
+
});
|
|
1198
|
+
${ct}${ut} }
|
|
1199
|
+
|
|
1200
|
+
protected override isCacheableQuery(functionPath: string): boolean {
|
|
1201
|
+
// NOT \`kind === "query"\` alone. A cache hit answers without running
|
|
1202
|
+
// \`handleRpc\`, so the \`internal\` refusal at the top of it is skipped —
|
|
1203
|
+
// and an \`internalQuery\` primed by a trusted system dispatch was then
|
|
1204
|
+
// served to an anonymous client that the refusal would have 404'd.
|
|
1205
|
+
//
|
|
1206
|
+
// \`perDispatch\` is the same argument one layer out: the procedure's
|
|
1207
|
+
// own \`.use()\` chain runs INSIDE \`handleRpc\`, so a hit skips it too.
|
|
1208
|
+
// A \`.use(rateLimit(...))\` query was therefore charged once and then
|
|
1209
|
+
// served from the memo to every later request — each of which still
|
|
1210
|
+
// reached this Durable Object and still cost it a dispatch, so only
|
|
1211
|
+
// the accounting was skipped. Metering and memoizing are mutually
|
|
1212
|
+
// exclusive; the author asking for the first is choosing against the
|
|
1213
|
+
// second.
|
|
1214
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1215
|
+
|
|
1216
|
+
return registered?.kind === "query" && registered.visibility !== "internal" && registered.perDispatch !== true;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
protected override isPaidFunction(functionPath: string): boolean {
|
|
1220
|
+
return LUNORA_FUNCTIONS[functionPath]?.x402 !== undefined;
|
|
1221
|
+
}
|
|
1222
|
+
`,mt=V?`
|
|
1223
|
+
const facade = db as unknown as Record<string, ReturnType<typeof bindTableFacade>>;
|
|
1224
|
+
${i.tables.map(s=>` facade[${JSON.stringify(s.name)}] = bindTableFacade(db, ${JSON.stringify(s.name)});`).join(`
|
|
1225
|
+
`)}
|
|
1226
|
+
`:"",gt=`${b.everyBuild}${T.build}${F.build}
|
|
1227
|
+
const secrets = createSecrets(env);
|
|
1228
|
+
`,bt=`${b.everyFields}${T.contextField}${$.contextField}${F.contextField}
|
|
1229
|
+
secrets,`,ft=$.build,wt=[...b.actionFields,...A.length>0?["services"]:[]],yt=`${b.actionBuild}${U.build}`;return`${Vt}${E.join(`
|
|
1230
|
+
`)}
|
|
1231
|
+
|
|
1232
|
+
type FunctionKind = "action" | "mutation" | "query";
|
|
1233
|
+
|
|
1234
|
+
interface FunctionReference {
|
|
1235
|
+
__lunoraRef: string;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/** Foreign-key columns per table (\`v.id("target")\` fields) for the data browser. */
|
|
1239
|
+
const LUNORA_TABLE_REFS = ${h(Ne,"Record<string, Record<string, string>>")};
|
|
1240
|
+
|
|
1241
|
+
/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */
|
|
1242
|
+
const LUNORA_TABLE_INDEXES = ${h($e,'Record<string, Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }>>')};
|
|
1243
|
+
|
|
1244
|
+
/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via \`__lunora_admin__:describeTable\`. */
|
|
1245
|
+
const LUNORA_TABLE_COLUMNS = ${h(Fe,`Record<
|
|
1246
|
+
string,
|
|
1247
|
+
Array<{
|
|
1248
|
+
bucket?: string;
|
|
1249
|
+
enumValues?: string[];
|
|
1250
|
+
isStorage?: boolean;
|
|
1251
|
+
name: string;
|
|
1252
|
+
nullable?: boolean;
|
|
1253
|
+
onDelete?: "cascade" | "restrict" | "set null";
|
|
1254
|
+
optional: boolean;
|
|
1255
|
+
pk?: boolean;
|
|
1256
|
+
ref?: string;
|
|
1257
|
+
type: string;
|
|
1258
|
+
}>
|
|
1259
|
+
>`)};
|
|
1260
|
+
|
|
1261
|
+
/** Storage-key columns per table (\`v.storage(...)\` fields) for the file browser's records↔files join. */
|
|
1262
|
+
const LUNORA_STORAGE_COLUMNS = ${h(Ue,"Record<string, string[]>")};
|
|
1263
|
+
|
|
1264
|
+
/** Declarative TTL policies (\`.ttl(field, { after? })\`) the DO alarm sweep auto-expires rows for. */
|
|
1265
|
+
const LUNORA_TTL_SWEEPS = ${h(J,"Array<{ after?: number; field: string; softDeleteField?: string; table: string }>")};
|
|
1266
|
+
|
|
1267
|
+
/** Static schema advisories (computed by @lunora/advisor at codegen time) served via \`__lunora_admin__:getAdvisories\`. */
|
|
1268
|
+
const LUNORA_ADVISORIES = ${h(Oe,"AdvisoryFinding[]")};
|
|
1269
|
+
|
|
1270
|
+
/** Every declared procedure (discovered by @lunora/codegen) served via \`__lunora_admin__:getAdvisorProcedures\` — the health map's denominator. */
|
|
1271
|
+
const LUNORA_ADVISOR_PROCEDURES = ${h(Ee,"AdvisorProcedure[]")};
|
|
1272
|
+
|
|
1273
|
+
/** Read-only RLS metadata (policies + roles discovered from \`.use(rls(...))\` chains) served via \`__lunora_admin__:rlsPolicies\` for the studio's RLS inspector. */
|
|
1274
|
+
const LUNORA_RLS_METADATA = ${h(G,"RlsPoliciesResult")};
|
|
1275
|
+
${je}
|
|
1276
|
+
/** Read-only masking metadata (table + column + strategy discovered from \`.use(mask(...))\` chains) served via \`__lunora_admin__:maskPolicies\` for the studio's data-browser mask preview. */
|
|
1277
|
+
const LUNORA_MASK_METADATA = ${h(Ce,"MaskPoliciesResult")};
|
|
1278
|
+
|
|
1279
|
+
/** Read-only storage access-rule metadata (discovered from \`.use(storageRules(...))\` chains) served via \`__lunora_admin__:storageRules\` for the studio's access-rules view. */
|
|
1280
|
+
const LUNORA_STORAGE_RULES = ${h(Le,"StorageRulesResult")};
|
|
1281
|
+
|
|
1282
|
+
/** Which optional package-backed features this app wires up (discovered from imports / \`ctx.*\` reads / schema signals) served via \`__lunora_admin__:studioFeatures\` so the studio hides nav pages whose package isn't enabled. */
|
|
1283
|
+
const LUNORA_STUDIO_FEATURES = ${h(Ie,"StudioFeaturesResult")};
|
|
1284
|
+
${te}${W.constant}${N.constant}${_e}${Pe}${me}${we}${oe}${le}${U.specs}${Se}
|
|
1285
|
+
export interface ShardDOConfig {
|
|
1286
|
+
/** Opt into change-data-capture: records a post-image to \`__cdc_log\` on every write (backs streaming export + replay-PITR). */
|
|
1287
|
+
cdc?: boolean;
|
|
1288
|
+
/** Ceiling on the join keys one relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
|
|
1289
|
+
maxRelationKeys?: number;
|
|
1290
|
+
/** Enable the per-shard reactive query cache: \`true\` for the defaults, or an options object to tune the caps. Query results are memoized by \`(functionPath, args, identity)\` and invalidated by the ctx-db write hooks before the subscription broadcast, so subscribers never observe a pre-write value. Omitted (or \`false\`) keeps every dispatch re-running its handler. */
|
|
1291
|
+
reactiveCache?: boolean | { maxBytes?: number; maxEntries?: number };
|
|
1292
|
+
/** Resolution policy for a relation-crossing \`where\` whose child is co-located in this shard: \`"auto"\` (cost-based, the engine default), \`"always"\` (inline correlated EXISTS) or \`"never"\` (universal semijoin). All three return identical rows. */
|
|
1293
|
+
relationExistsPushDown?: "always" | "auto" | "never";
|
|
1294
|
+
/** Optional telemetry sink. When supplied, each \`ctx.log.*\` call is forwarded to \`sink.onLog\`. Pass the SAME sink you give \`createWorker({ observability })\` (which drives \`onRpc\`) to route both RPC and log events. */
|
|
1295
|
+
observability?: (env: Record<string, unknown>) => TelemetrySink | undefined;
|
|
1296
|
+
/** \`unknown\` because \`@lunora/scheduler\`'s \`Scheduler\` is not assignable to \`SchedulerLike\`; the shard casts it. */
|
|
1297
|
+
scheduler?: (env: Record<string, unknown>) => unknown;
|
|
1298
|
+
/** \`origin\` is the origin the current \`/rpc\` request reached the worker on — the fallback base for signed object URLs when no \`publicBaseUrl\` is configured. \`undefined\` off the synchronous dispatch path. */
|
|
1299
|
+
storage?: (env: Record<string, unknown>, origin?: string) => unknown;${Ke}${b.configFields}${T.configField}${xe}${Ge}${Qe}${ze}${W.configField}
|
|
1300
|
+
}
|
|
1301
|
+
${C("schedulerStub",Je,["cancel","runAfter","runAt"])}${C("storageStub",Ye,["createMultipartUpload","delete","download","generateUploadUrl","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","list","resumeMultipartUpload","store","upload"],{sync:["getUrl","resumeMultipartUpload"]})}${Ze}${lt}${rt}${b.stubs}${Te}
|
|
1302
|
+
${Xt}
|
|
1303
|
+
|
|
1304
|
+
/**
|
|
1305
|
+
* Build the project's shard Durable Object. Export the result as \`ShardDO\`
|
|
1306
|
+
* from the worker entry so wrangler binds it by name.
|
|
1307
|
+
*/
|
|
1308
|
+
export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase =>
|
|
1309
|
+
class extends ShardDOBase {${pt}
|
|
1310
|
+
private migrated = false;
|
|
1311
|
+
|
|
1312
|
+
${Jt}
|
|
1313
|
+
${Z.override}
|
|
1314
|
+
${Yt}
|
|
1315
|
+
${Be}${Ve}${it}${dt}
|
|
1316
|
+
protected override lifecycleHookPaths(event: "connect" | "disconnect" | "init" | "reactor" | "whisper"): readonly string[] {
|
|
1317
|
+
return LUNORA_LIFECYCLE_HOOKS[event];
|
|
1318
|
+
}
|
|
1319
|
+
${W.override}${ht}
|
|
1320
|
+
// One \`onQueryChange\` dispatch. Mirrors \`executeSubscription\` — the
|
|
1321
|
+
// socket-terminated half of the same reactivity — and differs only in who
|
|
1322
|
+
// consumes the result: the base's \`dispatchReactors\` stores the digest as
|
|
1323
|
+
// the new baseline and the footprint as the "should I even re-run this"
|
|
1324
|
+
// gate, instead of pushing a frame down a socket.
|
|
1325
|
+
//
|
|
1326
|
+
// Dispatched through \`runMutationTransaction\` because a reactor handler is
|
|
1327
|
+
// a mutation: its writes must commit all-or-nothing, the jobs it schedules
|
|
1328
|
+
// must wait for that commit, and the objects its row deletes orphaned must
|
|
1329
|
+
// be flushed once it lands. Safe to open a span here: the refresh drain
|
|
1330
|
+
// runs OUTSIDE any dispatch transaction (it is post-flush background work),
|
|
1331
|
+
// so this never nests.
|
|
1332
|
+
//
|
|
1333
|
+
// NO identity is threaded, and the ctx is built \`trusted\`. A reactor fires
|
|
1334
|
+
// because data moved, not because anyone asked, so there is no user for RLS
|
|
1335
|
+
// to scope to — it runs in the same system tier as migrations and the
|
|
1336
|
+
// external-source poll loop. Inheriting the shared per-request identity
|
|
1337
|
+
// would instead run an app's reactor as whichever user happened to write
|
|
1338
|
+
// last, which is worse than running it as nobody.
|
|
1339
|
+
protected override async runReactor(functionPath: string, previousDigest?: string): Promise<{ digest: string; ran: boolean; tables: readonly string[] } | undefined> {
|
|
1340
|
+
const registered = LUNORA_FUNCTIONS[functionPath];
|
|
1341
|
+
|
|
1342
|
+
if (!registered || registered.kind !== "mutation") {
|
|
1343
|
+
return undefined;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
this.ensureMigrated();
|
|
1347
|
+
|
|
1348
|
+
const footprint = createReadFootprint();
|
|
1349
|
+
const ctx = this.buildCtx({ functionPath, headroom: this.subscriptionHeadroom(), onRead: footprint.onRead, onReadRange: footprint.onReadRange, trusted: true });
|
|
1350
|
+
const outcome = (await this.runMutationTransaction(ctx, async () =>
|
|
1351
|
+
registered.handler(ctx, { previousDigest } as unknown as Record<string, unknown>),
|
|
1352
|
+
)) as {
|
|
1353
|
+
digest: string;
|
|
1354
|
+
ran: boolean;
|
|
1355
|
+
};
|
|
1356
|
+
|
|
1357
|
+
return { digest: outcome.digest, ran: outcome.ran, tables: [...footprint.tables] };
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
protected override tableRefs(table: string): Record<string, string> | undefined {
|
|
1362
|
+
return LUNORA_TABLE_REFS[table];
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> {
|
|
1366
|
+
return LUNORA_TABLE_INDEXES[table] ?? [];
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> {
|
|
1370
|
+
return LUNORA_TTL_SWEEPS;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
protected override tableColumns(table: string): Array<{
|
|
1374
|
+
bucket?: string;
|
|
1375
|
+
enumValues?: string[];
|
|
1376
|
+
isStorage?: boolean;
|
|
1377
|
+
name: string;
|
|
1378
|
+
nullable?: boolean;
|
|
1379
|
+
onDelete?: "cascade" | "restrict" | "set null";
|
|
1380
|
+
optional: boolean;
|
|
1381
|
+
pk?: boolean;
|
|
1382
|
+
ref?: string;
|
|
1383
|
+
type: string;
|
|
1384
|
+
}> {
|
|
1385
|
+
return LUNORA_TABLE_COLUMNS[table] ?? [];
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
protected override storageColumns(): Record<string, string[]> {
|
|
1389
|
+
return LUNORA_STORAGE_COLUMNS;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
protected override rlsMetadata(): RlsPoliciesResult {
|
|
1393
|
+
return LUNORA_RLS_METADATA;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
protected override maskMetadata(): MaskPoliciesResult {
|
|
1397
|
+
return LUNORA_MASK_METADATA;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
protected override storageRulesMetadata(): StorageRulesResult {
|
|
1401
|
+
return LUNORA_STORAGE_RULES;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
protected override studioFeatures(): StudioFeaturesResult {
|
|
1405
|
+
return LUNORA_STUDIO_FEATURES;
|
|
1406
|
+
}
|
|
1407
|
+
${N.evaluateOverride}${N.subscriptionOverride}${Me}${qe}
|
|
1408
|
+
protected override advisories(): AdvisoryFinding[] {
|
|
1409
|
+
return LUNORA_ADVISORIES;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
protected override advisorProcedures(): AdvisorProcedure[] {
|
|
1413
|
+
return LUNORA_ADVISOR_PROCEDURES;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
${Qt}
|
|
1417
|
+
|
|
1418
|
+
protected override ensureMigrated(): void {
|
|
1419
|
+
if (this.migrated) {
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false${re} });
|
|
1424
|
+
this.migrated = true;
|
|
1425
|
+
}
|
|
1426
|
+
${H?`
|
|
1427
|
+
protected override runShardSearchBackfill(options: { maxPages?: number }): SearchBackfillProgress {
|
|
1428
|
+
// Migrations create the fts5 companions; without them every backfill
|
|
1429
|
+
// statement would raise "no such table" on a shard that has never
|
|
1430
|
+
// served a request.
|
|
1431
|
+
this.ensureMigrated();
|
|
1432
|
+
|
|
1433
|
+
return backfillSearchIndexes(this.sql as SqlExec, schema as unknown as SchemaLike, options);
|
|
1434
|
+
}
|
|
1435
|
+
`:""}${et}
|
|
1436
|
+
${zt({actionOnlyFields:wt,agentsBuild:ye,agentsContextField:ve,containersBuild:he,containersContextField:ue,databaseOptions:at,everyContextBuild:gt,everyContextField:bt,facadeBlock:mt,globalDatabaseLine:ot,notifyBuild:ft,ormContextField:st,paymentsBuild:Re,paymentsContextField:Ae,queuesBuild:ae,queuesContextField:ne,topicsBuild:ie,topicsContextField:de,vectorsBuild:tt,vectorsContextField:nt,workflowsBuild:ge,workflowsContextField:be,actionOnlyBuild:yt})}
|
|
1437
|
+
};
|
|
1438
|
+
`};export{er as b,kr as e};
|