@gaganref/confect-test 10.3.1-fork.88 → 10.3.1-fork.89

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.
Files changed (46) hide show
  1. package/dist/internal/Attempt.d.ts +77 -0
  2. package/dist/internal/Attempt.d.ts.map +1 -0
  3. package/dist/internal/Attempt.js +154 -0
  4. package/dist/internal/Attempt.js.map +1 -0
  5. package/dist/internal/ConvexTest.d.ts +34 -0
  6. package/dist/internal/ConvexTest.d.ts.map +1 -0
  7. package/dist/internal/ConvexTest.js +59 -0
  8. package/dist/internal/ConvexTest.js.map +1 -0
  9. package/dist/internal/Execution.d.ts +167 -0
  10. package/dist/internal/Execution.d.ts.map +1 -0
  11. package/dist/internal/Execution.js +790 -0
  12. package/dist/internal/Execution.js.map +1 -0
  13. package/dist/internal/Globals.d.ts +11 -0
  14. package/dist/internal/Globals.d.ts.map +1 -0
  15. package/dist/internal/Globals.js +76 -0
  16. package/dist/internal/Globals.js.map +1 -0
  17. package/dist/internal/Kernel.d.ts +93 -0
  18. package/dist/internal/Kernel.d.ts.map +1 -0
  19. package/dist/internal/Kernel.js +91 -0
  20. package/dist/internal/Kernel.js.map +1 -0
  21. package/dist/internal/KernelQuery.d.ts +55 -0
  22. package/dist/internal/KernelQuery.d.ts.map +1 -0
  23. package/dist/internal/KernelQuery.js +205 -0
  24. package/dist/internal/KernelQuery.js.map +1 -0
  25. package/dist/internal/KernelRefusal.d.ts +77 -0
  26. package/dist/internal/KernelRefusal.d.ts.map +1 -0
  27. package/dist/internal/KernelRefusal.js +73 -0
  28. package/dist/internal/KernelRefusal.js.map +1 -0
  29. package/dist/internal/KernelValues.d.ts +136 -0
  30. package/dist/internal/KernelValues.d.ts.map +1 -0
  31. package/dist/internal/KernelValues.js +266 -0
  32. package/dist/internal/KernelValues.js.map +1 -0
  33. package/dist/internal/ReadSet.d.ts +55 -0
  34. package/dist/internal/ReadSet.d.ts.map +1 -0
  35. package/dist/internal/ReadSet.js +29 -0
  36. package/dist/internal/ReadSet.js.map +1 -0
  37. package/package.json +3 -3
  38. package/src/internal/Attempt.ts +185 -0
  39. package/src/internal/ConvexTest.ts +118 -0
  40. package/src/internal/Execution.ts +1430 -0
  41. package/src/internal/Globals.ts +93 -0
  42. package/src/internal/Kernel.ts +190 -0
  43. package/src/internal/KernelQuery.ts +405 -0
  44. package/src/internal/KernelRefusal.ts +88 -0
  45. package/src/internal/KernelValues.ts +725 -0
  46. package/src/internal/ReadSet.ts +108 -0
@@ -0,0 +1,1430 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import {
3
+ actionGeneric,
4
+ getFunctionAddress,
5
+ mutationGeneric,
6
+ queryGeneric,
7
+ type FunctionReference,
8
+ type GenericSchema,
9
+ type SchemaDefinition,
10
+ type UserIdentity,
11
+ } from "convex/server";
12
+ import { convexToJson, jsonToConvex, type Value } from "convex/values";
13
+ import { KernelAttempt } from "./Attempt.js";
14
+ import * as Globals from "./Globals.js";
15
+ import * as Invocation from "./Invocation.js";
16
+ import * as Kernel from "./Kernel.js";
17
+ import * as KernelQuery from "./KernelQuery.js";
18
+ import * as KernelRefusal from "./KernelRefusal.js";
19
+ import type * as ReadSet from "./ReadSet.js";
20
+ import type {
21
+ DocumentId,
22
+ FunctionPath,
23
+ StoredDocument,
24
+ ValidatorJSON,
25
+ } from "./KernelValues.js";
26
+ import {
27
+ createFunctionHandle,
28
+ createTestJwt,
29
+ deserializeConvexErrorData,
30
+ evaluateValue,
31
+ hasPendingValues,
32
+ parseArgs,
33
+ parseFunctionHandle,
34
+ resolveCommittedValues,
35
+ simpleHash,
36
+ tableNameFromId,
37
+ validateFunctionArgs,
38
+ validateReturnValue,
39
+ } from "./KernelValues.js";
40
+
41
+ const ROOT = "";
42
+ const TYPICAL_CONVEX_ID_LENGTH = 32;
43
+
44
+ type Modules = Record<string, () => Promise<any>>;
45
+
46
+ /**
47
+ * One registered component: its schema and its function modules, each loaded
48
+ * once when the world opens.
49
+ */
50
+ interface Component {
51
+ readonly path: string;
52
+ readonly schema: KernelQuery.KernelSchema | null;
53
+ readonly loaders: ReadonlyMap<string, () => Promise<any>>;
54
+ readonly loaded: Map<string, any>;
55
+ }
56
+
57
+ /**
58
+ * Who is calling: the identity and the request attributes a test accessor set.
59
+ */
60
+ export interface Caller {
61
+ readonly identity: UserIdentity | null;
62
+ readonly token: string | null;
63
+ readonly ip: string | null;
64
+ readonly userAgent: string | null;
65
+ }
66
+
67
+ export const anonymous: Caller = {
68
+ identity: null,
69
+ token: null,
70
+ ip: null,
71
+ userAgent: null,
72
+ };
73
+
74
+ export const withIdentity = (
75
+ caller: Caller,
76
+ identity: Partial<UserIdentity>,
77
+ ): Caller => {
78
+ const subject = identity.subject ?? "" + simpleHash(JSON.stringify(identity));
79
+ const issuer = identity.issuer ?? "https://convex.test";
80
+ const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;
81
+ const full = { ...identity, subject, issuer, tokenIdentifier };
82
+ return { ...caller, identity: full, token: createTestJwt(full) };
83
+ };
84
+
85
+ interface Request {
86
+ readonly ip: string | null;
87
+ readonly userAgent: string | null;
88
+ readonly requestId: string;
89
+ readonly scheduledFunctionId: string | null;
90
+ readonly authToken: string | null;
91
+ }
92
+
93
+ type UdfType = "query" | "mutation" | "action";
94
+
95
+ /**
96
+ * How a prepared attempt's function ended.
97
+ */
98
+ export type Outcome =
99
+ | { readonly _tag: "returned"; readonly value: Value }
100
+ | { readonly _tag: "failed"; readonly error: unknown };
101
+
102
+ /**
103
+ * A mutation attempt run to its commit point and held until `apply`.
104
+ */
105
+ export interface HeldAttempt {
106
+ readonly id: string;
107
+ readonly request: string;
108
+ readonly number: Invocation.Attempt;
109
+ readonly snapshot: Kernel.Version;
110
+ readonly reads: ReadonlyArray<ReadSet.Read>;
111
+ readonly outcome: Outcome;
112
+ }
113
+
114
+ /**
115
+ * What `apply` did with a held attempt. A conflict discards the attempt and
116
+ * holds exactly one next attempt, run against the latest commit. Nothing is
117
+ * retried until that one is applied in turn.
118
+ */
119
+ export type KernelApply =
120
+ | {
121
+ readonly kind: "applied";
122
+ readonly version: Kernel.Version;
123
+ readonly commitTs: bigint;
124
+ readonly result: Value;
125
+ }
126
+ | { readonly kind: "conflict"; readonly next: HeldAttempt }
127
+ | {
128
+ readonly kind: "exhausted";
129
+ readonly error: KernelRefusal.OptimisticConcurrencyControlFailure;
130
+ }
131
+ | { readonly kind: "refused"; readonly tag: string; readonly error: unknown };
132
+
133
+ interface Held {
134
+ readonly view: HeldAttempt;
135
+ readonly attempt: KernelAttempt;
136
+ readonly again: (number: Invocation.Attempt) => Promise<Held>;
137
+ }
138
+
139
+ const lastAttempt: Invocation.Attempt = 5;
140
+
141
+ const tagOf = (error: unknown): string => {
142
+ const tagged = (value: unknown): value is { readonly _tag: string } =>
143
+ typeof value === "object" &&
144
+ value !== null &&
145
+ typeof (value as { _tag?: unknown })._tag === "string";
146
+ const data = (error as { data?: unknown } | null)?.data;
147
+ if (tagged(data)) return data._tag;
148
+ if (tagged(error)) return error._tag;
149
+ return error instanceof Error ? error.name : "Error";
150
+ };
151
+
152
+ /**
153
+ * One running function. Queries and mutations read and write through their
154
+ * attempt. Every async syscall of a query or a mutation, nested calls included,
155
+ * takes its turn on `turn` in the order the function made it.
156
+ */
157
+ interface Execution {
158
+ readonly world: World;
159
+ readonly componentPath: string;
160
+ readonly udfPath: string;
161
+ readonly udfType: UdfType;
162
+ readonly attempt: KernelAttempt | undefined;
163
+ readonly identity: UserIdentity | null;
164
+ readonly request: Request;
165
+ readonly pagination: { calls: number } | undefined;
166
+ readonly turn: Turn;
167
+ }
168
+
169
+ /**
170
+ * A queue that runs one task at a time, in the order they were taken.
171
+ */
172
+ class Turn {
173
+ private tail: Promise<unknown> = Promise.resolve();
174
+
175
+ take<A>(task: () => A | Promise<A>): Promise<A> {
176
+ const result = this.tail.then(task);
177
+ this.tail = result.then(
178
+ () => undefined,
179
+ () => undefined,
180
+ );
181
+ return result;
182
+ }
183
+
184
+ /**
185
+ * Resolves once every task taken so far has settled, including the tasks
186
+ * taken while waiting.
187
+ */
188
+ idle(): Promise<void> {
189
+ const tail = this.tail;
190
+ return tail.then(() => (this.tail === tail ? undefined : this.idle()));
191
+ }
192
+ }
193
+
194
+ /**
195
+ * A function's invocation finishes once its handler returned and every syscall
196
+ * it started has run. On the binary a query or mutation keeps running the
197
+ * syscalls in its queue after its promise resolves, then returns (`run_inner`
198
+ * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write
199
+ * still lands in its own transaction.
200
+ */
201
+ const settled = <A>(execution: Execution, result: A): Promise<A> =>
202
+ execution.turn.idle().then(() => result);
203
+
204
+ const executions = new AsyncLocalStorage<Execution>();
205
+
206
+ /**
207
+ * Run a function's code as `execution`, with its own copy of the globals a test
208
+ * invocation pins.
209
+ */
210
+ const enter = <A>(execution: Execution, run: () => A): A =>
211
+ Globals.own(() => executions.run(execution, run));
212
+ const kernelBrand = Symbol.for("@confect/test/Kernel");
213
+
214
+ const current = (): Execution => {
215
+ const execution = executions.getStore();
216
+ if (execution === undefined) {
217
+ throw new Error(
218
+ "A Convex syscall ran outside any function the test kernel started.",
219
+ );
220
+ }
221
+ return execution;
222
+ };
223
+
224
+ let nextRequestId = 0;
225
+ const newRequest = (caller: Caller): Request => ({
226
+ ip: caller.ip,
227
+ userAgent: caller.userAgent,
228
+ requestId: `kernel-request-${nextRequestId++}`,
229
+ scheduledFunctionId: null,
230
+ authToken: caller.token,
231
+ });
232
+
233
+ const findModulesRoot = (paths: ReadonlyArray<string>): string => {
234
+ const generated = paths.find((path) => path.includes("_generated"));
235
+ if (generated === undefined) {
236
+ throw new Error(
237
+ 'Could not find the "_generated" directory, make sure to run ' +
238
+ "`npx convex dev` or `npx convex codegen`. Make sure your " +
239
+ '`import.meta.glob` includes the files in the "_generated" directory',
240
+ );
241
+ }
242
+ return generated.split("_generated", 2)[0]!;
243
+ };
244
+
245
+ const makeComponent = (
246
+ path: string,
247
+ schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,
248
+ modules: Modules,
249
+ ): Component => {
250
+ const root = findModulesRoot(Object.keys(modules));
251
+ const relative = Object.entries(modules)
252
+ .filter(([key]) => key.startsWith(root))
253
+ .map(([key, load]) => [key.slice(root.length), load] as const);
254
+ const nested = relative
255
+ .map(([file]) => file)
256
+ .filter((file) => file.endsWith("/convex.config.ts"))
257
+ .map((file) => file.slice(0, -"convex.config.ts".length));
258
+ return {
259
+ path,
260
+ schema: KernelQuery.exportSchema(schema),
261
+ loaders: new Map(
262
+ relative
263
+ .filter(
264
+ ([file]) =>
265
+ isFunctionModule(file) &&
266
+ !nested.some((dir) => file.startsWith(dir)),
267
+ )
268
+ .map(([file, load]) => [file.replace(/\.[^.]+$/, ""), load]),
269
+ ),
270
+ loaded: new Map(),
271
+ };
272
+ };
273
+
274
+ const entryExtensions = [
275
+ ".js",
276
+ ".mjs",
277
+ ".cjs",
278
+ ".ts",
279
+ ".tsx",
280
+ ".mts",
281
+ ".cts",
282
+ ".jsx",
283
+ ];
284
+
285
+ /**
286
+ * Whether Convex's bundler deploys this file as a function module, by the rule
287
+ * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a
288
+ * schema, a config and `_generated` never reach the binary, so the kernel
289
+ * neither loads them nor resolves a function in them.
290
+ */
291
+ const isFunctionModule = (file: string): boolean => {
292
+ const base = file.split("/").pop()!;
293
+ return (
294
+ entryExtensions.some((extension) => file.endsWith(extension)) &&
295
+ !file.startsWith("_generated/") &&
296
+ !base.startsWith(".") &&
297
+ !base.startsWith("#") &&
298
+ base !== "schema.ts" &&
299
+ base !== "schema.js" &&
300
+ (base.match(/\./g) ?? []).length <= 1 &&
301
+ !file.includes(" ")
302
+ );
303
+ };
304
+
305
+ const unregistered = (world: World, componentPath: string) => {
306
+ const registered = [...world.components.keys()].filter((p) => p !== ROOT);
307
+ return new Error(
308
+ `Component "${componentPath}" is not registered on this test backend. ` +
309
+ (registered.length === 0
310
+ ? "No components have been registered."
311
+ : `Registered components: ${registered.map((p) => `"${p}"`).join(", ")}.`),
312
+ );
313
+ };
314
+
315
+ type FunctionAddress = {
316
+ readonly name?: string | undefined;
317
+ readonly reference?: string | undefined;
318
+ readonly functionHandle?: string | undefined;
319
+ };
320
+
321
+ /**
322
+ * Where an address points, read from the calling component.
323
+ */
324
+ const functionPathOf = (
325
+ address: FunctionAddress,
326
+ from: string,
327
+ ): FunctionPath => {
328
+ if (address.functionHandle !== undefined) {
329
+ return parseFunctionHandle(address.functionHandle) as FunctionPath;
330
+ }
331
+ if (address.name !== undefined) {
332
+ return { udfPath: address.name, componentPath: from };
333
+ }
334
+ if (address.reference !== undefined) {
335
+ // "_reference/childComponent/<child>/path/to/file/fn"
336
+ const parts = address.reference.split("/");
337
+ const child = parts[2]!;
338
+ const rest = parts.slice(3);
339
+ return {
340
+ componentPath: from.length > 0 ? `${from}/${child}` : child,
341
+ udfPath: `${rest.slice(0, -1).join("/")}:${rest[rest.length - 1]}`,
342
+ };
343
+ }
344
+ throw new Error("Function address not supported");
345
+ };
346
+
347
+ const pathOfReference = (
348
+ reference: FunctionReference<any, any, any, any> | string,
349
+ from: string,
350
+ ) =>
351
+ functionPathOf(getFunctionAddress(reference as any) as FunctionAddress, from);
352
+
353
+ interface Resolved {
354
+ readonly func: any;
355
+ readonly handler: (ctx: any, args: any) => any;
356
+ readonly args: ValidatorJSON;
357
+ readonly returns: ValidatorJSON | null;
358
+ }
359
+
360
+ const kindCheck = {
361
+ query: "isQuery",
362
+ mutation: "isMutation",
363
+ action: "isAction",
364
+ } as const;
365
+
366
+ /**
367
+ * A test backend: its registered components and the kernel state they share.
368
+ */
369
+ export class World {
370
+ readonly components = new Map<string, Component>();
371
+ state: Kernel.State = Kernel.empty;
372
+ private opened: Promise<void> | undefined;
373
+ private nextDocId = 10000;
374
+ private lastCreationTime = 0;
375
+ private nextQueryId = 1;
376
+ private readonly queries = new Map<number, Iterator<any>>();
377
+ private readonly holding = new Map<string, Held>();
378
+ private nextAttemptId = 1;
379
+
380
+ constructor(
381
+ schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,
382
+ modules: Modules,
383
+ private readonly runtime: Kernel.KernelRuntime = Kernel.wallClock(),
384
+ ) {
385
+ installConvexGlobal();
386
+ this.components.set(ROOT, makeComponent(ROOT, schema, modules));
387
+ }
388
+
389
+ register(
390
+ componentPath: string,
391
+ schema: SchemaDefinition<GenericSchema, boolean>,
392
+ modules: Modules,
393
+ ) {
394
+ if (this.opened !== undefined) {
395
+ throw new KernelRefusal.RegisteredAfterOpen({
396
+ componentPath,
397
+ message: `Component "${componentPath}" was registered after the test backend opened. Register every component before the first call.`,
398
+ });
399
+ }
400
+ this.components.set(
401
+ componentPath,
402
+ makeComponent(componentPath, schema, modules),
403
+ );
404
+ }
405
+
406
+ /**
407
+ * Load every registered module of every component, once, before any function
408
+ * runs.
409
+ */
410
+ open(): Promise<void> {
411
+ this.opened ??= Promise.all(
412
+ Array.from(this.components.values(), (component) =>
413
+ Promise.all(
414
+ Array.from(component.loaders, ([path, load]) =>
415
+ load().then((module) => component.loaded.set(path, module)),
416
+ ),
417
+ ),
418
+ ),
419
+ ).then(() => undefined);
420
+ return this.opened;
421
+ }
422
+
423
+ private component(componentPath: string): Component {
424
+ const component = this.components.get(componentPath);
425
+ if (component === undefined) throw unregistered(this, componentPath);
426
+ return component;
427
+ }
428
+
429
+ private resolve(functionPath: FunctionPath, kind: UdfType | "any"): Resolved {
430
+ const [modulePath, maybeExport] = functionPath.udfPath.split(":") as [
431
+ string,
432
+ string | undefined,
433
+ ];
434
+ const exportName = maybeExport ?? "default";
435
+ const component = this.component(functionPath.componentPath);
436
+ const module = component.loaded.get(modulePath);
437
+ if (module === undefined) {
438
+ throw new Error(`Could not find module for: "${modulePath}"`);
439
+ }
440
+ const func = module[exportName];
441
+ if (func === undefined) {
442
+ throw new Error(
443
+ `Expected a Convex function exported from module "${modulePath}" as \`${exportName}\`, but there is no such export.`,
444
+ );
445
+ }
446
+ const handler = "_handler" in func ? func._handler : func;
447
+ if (typeof handler !== "function") {
448
+ throw new Error(
449
+ `Expected a Convex function exported from module "${modulePath}" as \`${exportName}\`, but got: ${func}`,
450
+ );
451
+ }
452
+ if (kind !== "any" && !func[kindCheck[kind]]) {
453
+ throw new Error(
454
+ `Expected a ${kind} function, but the function exported from module "${modulePath}" as \`${exportName}\` is not a ${kind}.`,
455
+ );
456
+ }
457
+ const args = JSON.parse(func.exportArgs()) as ValidatorJSON;
458
+ if (args.type !== "object" && args.type !== "any") {
459
+ throw new Error(
460
+ `Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): ` +
461
+ `Args validator must be an object or any`,
462
+ );
463
+ }
464
+ return { func, handler, args, returns: JSON.parse(func.exportReturns()) };
465
+ }
466
+
467
+ // Calls from the test.
468
+
469
+ query(caller: Caller, reference: any, args: any): Promise<any> {
470
+ return this.open().then(() => {
471
+ const from = { caller, request: newRequest(caller) };
472
+ return typeof reference === "function"
473
+ ? this.runQuery(
474
+ { componentPath: ROOT, udfPath: "inline" },
475
+ { handler: reference, args: { type: "any" }, returns: null },
476
+ args ?? {},
477
+ from,
478
+ )
479
+ : this.queryAt(pathOfReference(reference, ROOT), args, from);
480
+ });
481
+ }
482
+
483
+ mutation(caller: Caller, reference: any, args: any): Promise<any> {
484
+ return this.open().then(() => {
485
+ const from = { caller, request: newRequest(caller) };
486
+ return typeof reference === "function"
487
+ ? this.runMutation(
488
+ { componentPath: ROOT, udfPath: "inline" },
489
+ { handler: reference, args: { type: "any" }, returns: null },
490
+ args ?? {},
491
+ from,
492
+ )
493
+ : this.mutationAt(pathOfReference(reference, ROOT), args, from);
494
+ });
495
+ }
496
+
497
+ action(caller: Caller, reference: any, args: any): Promise<any> {
498
+ return this.open().then(() => {
499
+ const from = { caller, request: newRequest(caller) };
500
+ return typeof reference === "function"
501
+ ? this.runAction(
502
+ { componentPath: ROOT, udfPath: "inline" },
503
+ { handler: reference, args: { type: "any" }, returns: null },
504
+ args ?? {},
505
+ from,
506
+ )
507
+ : this.actionAt(pathOfReference(reference, ROOT), args, from);
508
+ });
509
+ }
510
+
511
+ run(
512
+ caller: Caller,
513
+ componentPath: string,
514
+ handler: (ctx: any) => any,
515
+ ): Promise<any> {
516
+ return this.open().then(() => {
517
+ this.component(componentPath);
518
+ return this.runMutation(
519
+ { componentPath, udfPath: "custom" },
520
+ { handler, args: { type: "any" }, returns: null },
521
+ {},
522
+ { caller, request: newRequest(caller) },
523
+ );
524
+ });
525
+ }
526
+
527
+ // Held attempts.
528
+
529
+ /**
530
+ * Run a mutation to its commit point and hold it as attempt 1.
531
+ */
532
+ prepare(caller: Caller, reference: any, args: any): Promise<HeldAttempt> {
533
+ return this.open().then(() => {
534
+ const functionPath = pathOfReference(reference, ROOT);
535
+ const resolved = this.resolve(functionPath, "mutation");
536
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);
537
+ return this.prepareMutation(
538
+ functionPath,
539
+ resolved,
540
+ args,
541
+ { caller, request: newRequest(caller) },
542
+ 1,
543
+ Invocation.current(),
544
+ ).then((held) => held.view);
545
+ });
546
+ }
547
+
548
+ apply(id: string): Promise<KernelApply> {
549
+ const held = this.holding.get(id);
550
+ return held === undefined
551
+ ? Promise.reject(
552
+ new KernelRefusal.StaleAttempt({
553
+ id,
554
+ message: `The test kernel holds no attempt "${id}". It was already applied, or never prepared.`,
555
+ }),
556
+ )
557
+ : this.applyHeld(held);
558
+ }
559
+
560
+ /**
561
+ * The held attempts, oldest first.
562
+ */
563
+ held(): ReadonlyArray<HeldAttempt> {
564
+ return Array.from(this.holding.values(), (held) => held.view);
565
+ }
566
+
567
+ // Calls by address, from the test or from a running function.
568
+
569
+ private queryAt(
570
+ functionPath: FunctionPath,
571
+ args: any,
572
+ from: From,
573
+ snapshotOnly = false,
574
+ ) {
575
+ const resolved = this.resolve(functionPath, "query");
576
+ validateFunctionArgs(
577
+ resolved.args,
578
+ args ?? {},
579
+ functionPath,
580
+ from.parent?.attempt !== undefined,
581
+ );
582
+ return this.runQuery(functionPath, resolved, args, from, snapshotOnly);
583
+ }
584
+
585
+ private mutationAt(functionPath: FunctionPath, args: any, from: From) {
586
+ const resolved = this.resolve(functionPath, "mutation");
587
+ validateFunctionArgs(
588
+ resolved.args,
589
+ args ?? {},
590
+ functionPath,
591
+ from.parent?.attempt !== undefined,
592
+ );
593
+ return this.runMutation(functionPath, resolved, args, from);
594
+ }
595
+
596
+ private actionAt(functionPath: FunctionPath, args: any, from: From) {
597
+ const resolved = this.resolve(functionPath, "action");
598
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);
599
+ return this.runAction(functionPath, resolved, args, from);
600
+ }
601
+
602
+ // Runners.
603
+
604
+ private execution(
605
+ functionPath: FunctionPath,
606
+ udfType: UdfType,
607
+ attempt: KernelAttempt | undefined,
608
+ from: From,
609
+ pagination: { calls: number } | undefined,
610
+ ): Execution {
611
+ // A function in a component runs with no identity, whoever called it, as
612
+ // Convex gives a component no `ctx.auth` of the caller's. A nested call in
613
+ // the host takes its parent's identity, even when that is none.
614
+ const identity =
615
+ functionPath.componentPath !== ROOT
616
+ ? null
617
+ : from.parent !== undefined
618
+ ? from.parent.identity
619
+ : from.caller.identity;
620
+ return {
621
+ world: this,
622
+ componentPath: functionPath.componentPath,
623
+ udfPath: functionPath.udfPath,
624
+ udfType,
625
+ attempt,
626
+ identity,
627
+ request: from.request,
628
+ pagination,
629
+ turn: new Turn(),
630
+ };
631
+ }
632
+
633
+ private runQuery(
634
+ functionPath: FunctionPath,
635
+ resolved: Pick<Resolved, "handler" | "args" | "returns">,
636
+ args: any,
637
+ from: From,
638
+ snapshotOnly = false,
639
+ ): Promise<any> {
640
+ const parentAttempt = from.parent?.attempt;
641
+ const isNested = parentAttempt !== undefined;
642
+ const attempt =
643
+ parentAttempt === undefined
644
+ ? new KernelAttempt(this.state)
645
+ : snapshotOnly
646
+ ? new KernelAttempt(parentAttempt.snapshot)
647
+ : parentAttempt;
648
+ const execution = this.execution(
649
+ functionPath,
650
+ "query",
651
+ attempt,
652
+ from,
653
+ (isNested && from.parent?.pagination) || { calls: 0 },
654
+ );
655
+ const q = queryGeneric({
656
+ handler: (ctx: any, a: any) =>
657
+ resolved.handler({ ...ctx, auth: queryAuth(execution) }, a),
658
+ }) as unknown as { invokeQuery: (args: string) => Promise<string> };
659
+ return enter(execution, () =>
660
+ q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)]))),
661
+ )
662
+ .then((raw) => settled(execution, raw))
663
+ .then((raw) => {
664
+ const result = jsonToConvex(JSON.parse(raw));
665
+ if (!isNested && hasPendingValues(result)) {
666
+ throw new Error(
667
+ `Function ${functionPath.udfPath} return value invalid: queries ` +
668
+ `cannot return an unresolved placeholder value.`,
669
+ );
670
+ }
671
+ validateReturnValue(resolved.returns, result, "query", functionPath);
672
+ return result;
673
+ })
674
+ .catch((error: unknown) => {
675
+ throw deserializeConvexErrorData(error);
676
+ });
677
+ }
678
+
679
+ private invokeMutation(
680
+ execution: Execution,
681
+ resolved: Pick<Resolved, "handler" | "returns">,
682
+ args: any,
683
+ ): Promise<Value> {
684
+ const m = mutationGeneric({
685
+ handler: (ctx: any, a: any) =>
686
+ resolved.handler({ ...ctx, auth: mutationAuth(execution) }, a),
687
+ }) as unknown as { invokeMutation: (args: string) => Promise<string> };
688
+ return enter(execution, () =>
689
+ m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)]))),
690
+ )
691
+ .then((raw) => settled(execution, raw))
692
+ .then((raw) => {
693
+ const result = jsonToConvex(JSON.parse(raw));
694
+ validateReturnValue(resolved.returns, result, "mutation", {
695
+ componentPath: execution.componentPath,
696
+ udfPath: execution.udfPath,
697
+ });
698
+ return result;
699
+ });
700
+ }
701
+
702
+ private runMutation(
703
+ functionPath: FunctionPath,
704
+ resolved: Pick<Resolved, "handler" | "args" | "returns">,
705
+ args: any,
706
+ from: From,
707
+ ): Promise<any> {
708
+ const parentAttempt = from.parent?.attempt;
709
+ if (parentAttempt !== undefined) {
710
+ const frame = parentAttempt.child();
711
+ const execution = this.execution(
712
+ functionPath,
713
+ "mutation",
714
+ frame,
715
+ from,
716
+ undefined,
717
+ );
718
+ // As at the top level, a nested mutation ends once its function has
719
+ // returned and every syscall it started has settled. Convex runs a
720
+ // nested function's syscall queue to the end before it commits its
721
+ // subtransaction, so a detached fiber's late write lands in this frame
722
+ // and merges with it. A failed one ends at once and rolls back.
723
+ return this.invokeMutation(execution, resolved, args).then(
724
+ (result) =>
725
+ frame.drained().then(() => {
726
+ frame.close();
727
+ frame.merge();
728
+ return result;
729
+ }),
730
+ (error: unknown) => {
731
+ frame.close();
732
+ throw deserializeConvexErrorData(error);
733
+ },
734
+ );
735
+ }
736
+ return this.prepareMutation(
737
+ functionPath,
738
+ resolved,
739
+ args,
740
+ from,
741
+ 1,
742
+ Invocation.current(),
743
+ ).then((held) => this.publish(held));
744
+ }
745
+
746
+ /**
747
+ * Run one attempt of a top-level mutation against the latest commit, then
748
+ * hold it. The commit point is once the function has returned and every
749
+ * syscall it started has settled. A test invocation bound when the mutation
750
+ * was first called reaches each attempt's handler with that attempt's
751
+ * number.
752
+ */
753
+ private prepareMutation(
754
+ functionPath: FunctionPath,
755
+ resolved: Pick<Resolved, "handler" | "returns">,
756
+ args: any,
757
+ from: From,
758
+ number: Invocation.Attempt,
759
+ bound: Invocation.Invocation | undefined,
760
+ ): Promise<Held> {
761
+ const attempt = new KernelAttempt(this.state, number);
762
+ const execution = this.execution(
763
+ functionPath,
764
+ "mutation",
765
+ attempt,
766
+ from,
767
+ undefined,
768
+ );
769
+ const run = () => this.invokeMutation(execution, resolved, args);
770
+ const started =
771
+ bound === undefined
772
+ ? run()
773
+ : Invocation.bind({ ...bound, attempt: number }, run);
774
+ return started
775
+ .then(
776
+ (value) =>
777
+ attempt.drained().then((): Outcome => ({ _tag: "returned", value })),
778
+ (error: unknown): Outcome => ({
779
+ _tag: "failed",
780
+ error: deserializeConvexErrorData(error),
781
+ }),
782
+ )
783
+ .then((outcome) => {
784
+ attempt.close();
785
+ const held: Held = {
786
+ view: {
787
+ id: `attempt-${this.nextAttemptId++}`,
788
+ request: from.request.requestId,
789
+ number,
790
+ snapshot: attempt.snapshot.version,
791
+ reads: attempt.reads,
792
+ outcome,
793
+ },
794
+ attempt,
795
+ again: (next) =>
796
+ this.prepareMutation(
797
+ functionPath,
798
+ resolved,
799
+ args,
800
+ from,
801
+ next,
802
+ bound,
803
+ ),
804
+ };
805
+ this.holding.set(held.view.id, held);
806
+ return held;
807
+ });
808
+ }
809
+
810
+ /**
811
+ * Validate a held attempt's reads against every commit since its snapshot,
812
+ * then publish its writes or prepare its next attempt. An attempt that wrote
813
+ * nothing publishes nothing and has nothing to validate. It answers its
814
+ * snapshot's version and commit timestamp.
815
+ */
816
+ private applyHeld({ view, attempt, again }: Held): Promise<KernelApply> {
817
+ this.holding.delete(view.id);
818
+ const { outcome } = view;
819
+ if (outcome._tag === "failed") {
820
+ return Promise.resolve({
821
+ kind: "refused",
822
+ tag: tagOf(outcome.error),
823
+ error: outcome.error,
824
+ });
825
+ }
826
+ const writes = attempt.writes();
827
+ if (writes.length === 0) {
828
+ // As on the binary, a mutation that wrote nothing is serialized at its
829
+ // snapshot and allocates no timestamp for a later commit.
830
+ const { version, commitTs } = attempt.snapshot;
831
+ return Promise.resolve({
832
+ kind: "applied",
833
+ version,
834
+ commitTs,
835
+ result: resolveCommittedValues(outcome.value, commitTs),
836
+ });
837
+ }
838
+ if (
839
+ Kernel.conflict(this.state, view.snapshot, attempt.reads) !== undefined
840
+ ) {
841
+ if (view.number === lastAttempt) {
842
+ return Promise.resolve({
843
+ kind: "exhausted",
844
+ error: new KernelRefusal.OptimisticConcurrencyControlFailure({
845
+ attempts: lastAttempt,
846
+ message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`,
847
+ }),
848
+ });
849
+ }
850
+ return again((view.number + 1) as Invocation.Attempt).then(
851
+ (next): KernelApply => ({ kind: "conflict", next: next.view }),
852
+ );
853
+ }
854
+ const commitTs = this.runtime.commitTs(this.state.version + 1);
855
+ if (commitTs <= this.state.commitTs) {
856
+ return Promise.reject(
857
+ new KernelRefusal.CommitTsNotIncreasing({
858
+ version: this.state.version + 1,
859
+ previous: this.state.commitTs,
860
+ commitTs,
861
+ message: `The runtime answered commit timestamp ${commitTs} for version ${this.state.version + 1}, which is not greater than the previous commit's ${this.state.commitTs}.`,
862
+ }),
863
+ );
864
+ }
865
+ this.state = Kernel.apply(this.state, writes, commitTs);
866
+ return Promise.resolve({
867
+ kind: "applied",
868
+ version: this.state.version,
869
+ commitTs,
870
+ result: resolveCommittedValues(outcome.value, commitTs),
871
+ });
872
+ }
873
+
874
+ /**
875
+ * Apply until the mutation publishes, is refused or is exhausted, as the
876
+ * binary retries a mutation that conflicts.
877
+ */
878
+ private publish(held: Held): Promise<Value> {
879
+ return this.applyHeld(held).then((applied) => {
880
+ if (applied.kind === "applied") return applied.result;
881
+ if (applied.kind === "conflict") {
882
+ return this.publish(this.holding.get(applied.next.id)!);
883
+ }
884
+ throw applied.error;
885
+ });
886
+ }
887
+
888
+ private runAction(
889
+ functionPath: FunctionPath,
890
+ resolved: Pick<Resolved, "handler" | "args" | "returns">,
891
+ args: any,
892
+ from: From,
893
+ ): Promise<any> {
894
+ const execution = this.execution(
895
+ functionPath,
896
+ "action",
897
+ undefined,
898
+ from,
899
+ undefined,
900
+ );
901
+ const inner: From = { request: from.request, parent: execution };
902
+ const a = actionGeneric({
903
+ handler: (ctx: any, innerArgs: any) =>
904
+ resolved.handler(
905
+ {
906
+ ...ctx,
907
+ runQuery: (reference: any, queryArgs: any) =>
908
+ this.queryAt(
909
+ pathOfReference(reference, functionPath.componentPath),
910
+ queryArgs,
911
+ inner,
912
+ ),
913
+ runMutation: (reference: any, mutationArgs: any) =>
914
+ this.mutationAt(
915
+ pathOfReference(reference, functionPath.componentPath),
916
+ mutationArgs,
917
+ inner,
918
+ ),
919
+ runAction: (reference: any, actionArgs: any) =>
920
+ this.actionAt(
921
+ pathOfReference(reference, functionPath.componentPath),
922
+ actionArgs,
923
+ inner,
924
+ ),
925
+ auth: queryAuth(execution),
926
+ },
927
+ innerArgs,
928
+ ),
929
+ }) as unknown as {
930
+ invokeAction: (requestId: string, args: string) => Promise<string>;
931
+ };
932
+ const run = () =>
933
+ enter(execution, () =>
934
+ a.invokeAction(
935
+ from.request.requestId,
936
+ JSON.stringify(convexToJson([parseArgs(args)])),
937
+ ),
938
+ );
939
+ // An action another function calls is an invocation of its own, with its
940
+ // world's services, a start time read from its world's clock and its
941
+ // world's random stream, as a scheduled job is.
942
+ const bound = from.parent === undefined ? undefined : Invocation.current();
943
+ const { ip, userAgent, requestId, scheduledFunctionId } = from.request;
944
+ const started =
945
+ bound === undefined
946
+ ? run()
947
+ : Invocation.bind(
948
+ {
949
+ world: bound.world,
950
+ componentPath: functionPath.componentPath,
951
+ attempt: 1,
952
+ request: { ip, userAgent, requestId, scheduledFunctionId },
953
+ services: bound.world.services,
954
+ startedAt: bound.world.clock(),
955
+ random: bound.world.random,
956
+ },
957
+ run,
958
+ );
959
+ return started
960
+ .then((raw) => {
961
+ const result = jsonToConvex(JSON.parse(raw));
962
+ validateReturnValue(resolved.returns, result, "action", functionPath);
963
+ return result;
964
+ })
965
+ .catch((error: unknown) => {
966
+ throw deserializeConvexErrorData(error);
967
+ });
968
+ }
969
+
970
+ // Syscalls.
971
+
972
+ private schema(componentPath: string) {
973
+ return this.component(componentPath).schema;
974
+ }
975
+
976
+ private view(execution: Execution): KernelQuery.TableView {
977
+ const attempt = transaction(execution);
978
+ return {
979
+ schema: this.schema(execution.componentPath),
980
+ scan: (tableName) => attempt.scan(execution.componentPath, tableName),
981
+ read: (interval, after) =>
982
+ attempt.readInterval({
983
+ ...interval,
984
+ componentPath: execution.componentPath,
985
+ after,
986
+ }),
987
+ };
988
+ }
989
+
990
+ private generateId(table: string): DocumentId {
991
+ const counter = String(this.nextDocId++).padStart(
992
+ TYPICAL_CONVEX_ID_LENGTH - table.length,
993
+ "0",
994
+ );
995
+ return (counter + table) as DocumentId;
996
+ }
997
+
998
+ syscall(op: string, jsonArgs: string): string {
999
+ const args = JSON.parse(jsonArgs);
1000
+ const execution = current();
1001
+ if (execution.attempt?.closed === true) throw closed(execution, op);
1002
+ switch (op) {
1003
+ case "1.0/getSnapshotTs":
1004
+ return JSON.stringify(
1005
+ convexToJson(transaction(execution).snapshot.commitTs),
1006
+ );
1007
+ case "1.0/queryStream": {
1008
+ // The binary reads a query at each `1.0/queryStreamNext`, which waits
1009
+ // its turn in the queue, so the stream opens at its first read and sees
1010
+ // every write made before it.
1011
+ const queryId = this.nextQueryId++;
1012
+ const view = this.view(execution);
1013
+ let results: Iterator<any> | undefined;
1014
+ this.queries.set(queryId, {
1015
+ next: () => (results ??= KernelQuery.stream(view, args.query)).next(),
1016
+ });
1017
+ return JSON.stringify({ queryId });
1018
+ }
1019
+ case "1.0/queryCleanup":
1020
+ this.queries.delete(args.queryId);
1021
+ return JSON.stringify({});
1022
+ case "1.0/db/normalizeId": {
1023
+ const tableName = tableNameFromId(args.idString);
1024
+ return JSON.stringify({
1025
+ id: tableName === args.table ? args.idString : null,
1026
+ });
1027
+ }
1028
+ default:
1029
+ throw new Error(`The test kernel does not support syscall: "${op}"`);
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * The binary queues a query's or mutation's async syscalls and runs them one
1035
+ * at a time, oldest first (`start_async_syscall` and `run_inner` in
1036
+ * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested
1037
+ * call never share a batch (`AsyncSyscallBatch::can_push` in
1038
+ * `async_syscall.rs`), and a nested call holds the queue until it has
1039
+ * committed or rolled back its subtransaction (`run_udf` in
1040
+ * `async_syscall.rs`). So a caller's write made after its nested call runs
1041
+ * after that call, and a nested mutation sees every write made before it. An
1042
+ * action's calls run side by side.
1043
+ */
1044
+ asyncSyscall(op: string, jsonArgs: string): Promise<string> {
1045
+ const execution = current();
1046
+ const attempt = execution.attempt;
1047
+ if (attempt === undefined) {
1048
+ return Promise.resolve().then(() =>
1049
+ this.dispatchAsync(op, JSON.parse(jsonArgs), execution),
1050
+ );
1051
+ }
1052
+ if (attempt.closed) return Promise.reject(closed(execution, op));
1053
+ // A syscall counts toward its frame's lifetime from the moment it is
1054
+ // queued, so a frame never closes with a write still waiting its turn.
1055
+ const end = attempt.begin();
1056
+ return execution.turn
1057
+ .take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution))
1058
+ .finally(end);
1059
+ }
1060
+
1061
+ private dispatchAsync(
1062
+ op: string,
1063
+ args: any,
1064
+ execution: Execution,
1065
+ ): string | Promise<string> {
1066
+ switch (op) {
1067
+ case "1.0/get": {
1068
+ const { table, id } = args;
1069
+ return JSON.stringify(convexToJson(this.get(execution, table, id)));
1070
+ }
1071
+ case "1.0/queryStreamNext": {
1072
+ const results = this.queries.get(args.queryId);
1073
+ if (results === undefined) throw new Error("Bad queryId");
1074
+ const { value, done } = results.next();
1075
+ return JSON.stringify(
1076
+ convexToJson(
1077
+ done ? { value: null, done: true } : { value, done: false },
1078
+ ),
1079
+ );
1080
+ }
1081
+ case "1.0/queryPage": {
1082
+ const pagination = execution.pagination;
1083
+ if (pagination) {
1084
+ pagination.calls += 1;
1085
+ if (pagination.calls > 1) {
1086
+ throw new Error(
1087
+ "Only a single paginated query (`.paginate()`) is allowed per " +
1088
+ "query, including nested query calls and component calls. " +
1089
+ "This is a Convex limit: https://docs.convex.dev/database/pagination",
1090
+ );
1091
+ }
1092
+ }
1093
+ return JSON.stringify(
1094
+ convexToJson(KernelQuery.paginate(this.view(execution), args) as any),
1095
+ );
1096
+ }
1097
+ case "1.0/insert":
1098
+ return JSON.stringify({
1099
+ _id: this.insert(execution, args.table, jsonToConvex(args.value)),
1100
+ });
1101
+ case "1.0/shallowMerge":
1102
+ this.patch(execution, args.table, args.id, args.value);
1103
+ return JSON.stringify({});
1104
+ case "1.0/replace":
1105
+ this.replace(execution, args.table, args.id, args.value);
1106
+ return JSON.stringify({});
1107
+ case "1.0/remove":
1108
+ this.remove(execution, args.table, args.id);
1109
+ return JSON.stringify({});
1110
+ case "1.0/count": {
1111
+ const attempt = transaction(execution);
1112
+ attempt.readInterval({
1113
+ kind: "interval",
1114
+ componentPath: execution.componentPath,
1115
+ table: args.table,
1116
+ fields: ["_creationTime", "_id"],
1117
+ order: "asc",
1118
+ range: [],
1119
+ after: null,
1120
+ })("end");
1121
+ return JSON.stringify(
1122
+ attempt.scan(execution.componentPath, args.table).length,
1123
+ );
1124
+ }
1125
+ case "1.0/getFunctionMetadata":
1126
+ return JSON.stringify(
1127
+ convexToJson({
1128
+ name: execution.udfPath,
1129
+ componentPath: execution.componentPath,
1130
+ }),
1131
+ );
1132
+ case "1.0/getRequestMetadata":
1133
+ if (execution.udfType === "query") {
1134
+ throw new Error(
1135
+ "getRequestMetadata() can only be called from a mutation, action " +
1136
+ "or HTTP action. It is not available in queries.",
1137
+ );
1138
+ }
1139
+ return JSON.stringify(convexToJson(execution.request as any));
1140
+ case "1.0/getDeploymentMetadata":
1141
+ return JSON.stringify(
1142
+ convexToJson({ name: "test", region: null, class: "s16" }),
1143
+ );
1144
+ case "1.0/actions/query":
1145
+ case "1.0/actions/mutation":
1146
+ case "1.0/actions/action": {
1147
+ const from: From = { request: execution.request, parent: execution };
1148
+ const functionPath = functionPathOf(args, execution.componentPath);
1149
+ const run =
1150
+ op === "1.0/actions/query"
1151
+ ? this.queryAt(functionPath, args.args, from)
1152
+ : op === "1.0/actions/mutation"
1153
+ ? this.mutationAt(functionPath, args.args, from)
1154
+ : this.actionAt(functionPath, args.args, from);
1155
+ return run.then((value) => JSON.stringify(convexToJson(value)));
1156
+ }
1157
+ case "1.0/runUdf": {
1158
+ const { udfType, args: udfArgs } = args;
1159
+ const from: From = { request: execution.request, parent: execution };
1160
+ const functionPath = functionPathOf(args, execution.componentPath);
1161
+ const value = jsonToConvex(udfArgs);
1162
+ const run =
1163
+ udfType === "query"
1164
+ ? this.queryAt(functionPath, value, from)
1165
+ : udfType === "snapshotQuery"
1166
+ ? this.queryAt(functionPath, value, from, true)
1167
+ : udfType === "mutation"
1168
+ ? this.mutationAt(functionPath, value, from)
1169
+ : Promise.reject(
1170
+ new Error(
1171
+ `The test kernel does not support udf type: "${udfType}"`,
1172
+ ),
1173
+ );
1174
+ return run.then((result) => JSON.stringify(convexToJson(result)));
1175
+ }
1176
+ case "1.0/createFunctionHandle": {
1177
+ const functionPath = functionPathOf(args, execution.componentPath);
1178
+ this.component(functionPath.componentPath);
1179
+ return JSON.stringify(createFunctionHandle(functionPath));
1180
+ }
1181
+ case "1.0/auditLog":
1182
+ return JSON.stringify(null);
1183
+ case "1.0/schedule":
1184
+ case "1.0/actions/schedule":
1185
+ case "1.0/cancel_job":
1186
+ case "1.0/actions/cancel_job":
1187
+ throw KernelRefusal.rowPending("the scheduler", 5);
1188
+ case "1.0/storageDelete":
1189
+ case "1.0/storageGetUrl":
1190
+ case "1.0/storageGenerateUploadUrl":
1191
+ throw KernelRefusal.rowPending("storage", 6);
1192
+ case "1.0/getTransactionMetrics":
1193
+ throw KernelRefusal.rowPending("transaction limits", 6);
1194
+ case "1.0/actions/vectorSearch":
1195
+ throw KernelRefusal.requiresBinary("vectorSearch");
1196
+ default:
1197
+ throw new Error(
1198
+ `The test kernel does not support async syscall: "${op}"`,
1199
+ );
1200
+ }
1201
+ }
1202
+
1203
+ jsSyscall(op: string): Promise<never> {
1204
+ return Promise.reject(
1205
+ op.startsWith("storage/")
1206
+ ? KernelRefusal.rowPending("storage", 6)
1207
+ : new Error(`The test kernel does not support js syscall: "${op}"`),
1208
+ );
1209
+ }
1210
+
1211
+ // Documents. The checks and messages are convex-test's.
1212
+
1213
+ private get(execution: Execution, tableName: unknown, id: unknown) {
1214
+ validateId(tableName, id);
1215
+ const attempt = transaction(execution);
1216
+ attempt.readDocument(execution.componentPath, id);
1217
+ return attempt.get(execution.componentPath, id);
1218
+ }
1219
+
1220
+ private insert(execution: Execution, table: string, value: any): DocumentId {
1221
+ const attempt = transaction(execution);
1222
+ KernelQuery.validateDocument(
1223
+ this.schema(execution.componentPath),
1224
+ table,
1225
+ value,
1226
+ );
1227
+ const _id = this.generateId(table);
1228
+ const now = this.runtime.now();
1229
+ const _creationTime =
1230
+ now <= this.lastCreationTime ? this.lastCreationTime + 0.001 : now;
1231
+ this.lastCreationTime = _creationTime;
1232
+ attempt.write(execution.componentPath, _id, {
1233
+ ...value,
1234
+ _id,
1235
+ _creationTime,
1236
+ });
1237
+ return _id;
1238
+ }
1239
+
1240
+ private existing(
1241
+ execution: Execution,
1242
+ tableName: unknown,
1243
+ id: unknown,
1244
+ write: string,
1245
+ value: unknown,
1246
+ ): StoredDocument {
1247
+ validateId(tableName, id);
1248
+ if (value !== undefined && typeof value !== "object") {
1249
+ throw new Error(
1250
+ `Invalid argument \`value\` in \`db.${write}\`, expected object but got '${typeof value}': ${value as any}`,
1251
+ );
1252
+ }
1253
+ const attempt = transaction(execution);
1254
+ attempt.readDocument(execution.componentPath, id);
1255
+ const document = attempt.get(execution.componentPath, id);
1256
+ if (document === null) {
1257
+ throw new Error(
1258
+ write === "delete"
1259
+ ? "Delete on non-existent doc"
1260
+ : `${write === "patch" ? "Patch" : "Replace"} on non-existent document with ID "${id}"`,
1261
+ );
1262
+ }
1263
+ return document;
1264
+ }
1265
+
1266
+ private fields(document: StoredDocument, value: Record<string, any>) {
1267
+ if (value._id !== undefined && value._id !== document._id) {
1268
+ throw new Error(
1269
+ `Provided \`_id\` field value "${value._id}" ` +
1270
+ `does not match the document ID "${document._id}"`,
1271
+ );
1272
+ }
1273
+ if (
1274
+ value._creationTime !== undefined &&
1275
+ value._creationTime !== document._creationTime
1276
+ ) {
1277
+ throw new Error(
1278
+ `Provided \`_creationTime\` field value ${value._creationTime} ` +
1279
+ `does not match the document's creation time ${document._creationTime}`,
1280
+ );
1281
+ }
1282
+ const convexValue: Record<string, Value | undefined> = {};
1283
+ for (const [key, v] of Object.entries(value)) {
1284
+ if (key !== "_id" && key !== "_creationTime") {
1285
+ convexValue[key] = evaluateValue(v);
1286
+ }
1287
+ }
1288
+ return convexValue;
1289
+ }
1290
+
1291
+ private patch(
1292
+ execution: Execution,
1293
+ tableName: unknown,
1294
+ id: unknown,
1295
+ value: Record<string, any>,
1296
+ ) {
1297
+ const document = this.existing(execution, tableName, id, "patch", value);
1298
+ const { _id, _creationTime, ...fields } = document;
1299
+ const merged = { ...fields, ...this.fields(document, value) };
1300
+ KernelQuery.validateDocument(
1301
+ this.schema(execution.componentPath),
1302
+ tableNameFromId(_id)!,
1303
+ merged,
1304
+ );
1305
+ transaction(execution).write(execution.componentPath, _id, {
1306
+ _id,
1307
+ _creationTime,
1308
+ ...merged,
1309
+ } as StoredDocument);
1310
+ }
1311
+
1312
+ private replace(
1313
+ execution: Execution,
1314
+ tableName: unknown,
1315
+ id: unknown,
1316
+ value: Record<string, any>,
1317
+ ) {
1318
+ const document = this.existing(execution, tableName, id, "replace", value);
1319
+ const fields = this.fields(document, value);
1320
+ KernelQuery.validateDocument(
1321
+ this.schema(execution.componentPath),
1322
+ tableNameFromId(document._id)!,
1323
+ fields,
1324
+ );
1325
+ transaction(execution).write(execution.componentPath, document._id, {
1326
+ ...fields,
1327
+ _id: document._id,
1328
+ _creationTime: document._creationTime,
1329
+ } as StoredDocument);
1330
+ }
1331
+
1332
+ private remove(execution: Execution, tableName: unknown, id: unknown) {
1333
+ const document = this.existing(
1334
+ execution,
1335
+ tableName,
1336
+ id,
1337
+ "delete",
1338
+ undefined,
1339
+ );
1340
+ transaction(execution).write(execution.componentPath, document._id, null);
1341
+ }
1342
+ }
1343
+
1344
+ /**
1345
+ * Where a call comes from. A call from the test carries its accessor's caller.
1346
+ * A nested call carries its parent execution and takes its identity from it.
1347
+ */
1348
+ type From =
1349
+ | {
1350
+ readonly caller: Caller;
1351
+ readonly request: Request;
1352
+ readonly parent?: undefined;
1353
+ }
1354
+ | { readonly parent: Execution; readonly request: Request };
1355
+
1356
+ const closed = (execution: Execution, operation: string) =>
1357
+ new KernelRefusal.ClosedAttempt({
1358
+ operation,
1359
+ message: `"${operation}" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`,
1360
+ });
1361
+
1362
+ const transaction = (execution: Execution): KernelAttempt => {
1363
+ if (execution.attempt === undefined) {
1364
+ throw new Error(
1365
+ "The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.",
1366
+ );
1367
+ }
1368
+ return execution.attempt;
1369
+ };
1370
+
1371
+ const queryAuth = (execution: Execution) => ({
1372
+ getUserIdentity: () => Promise.resolve(execution.identity),
1373
+ });
1374
+
1375
+ const mutationAuth = (execution: Execution) => ({
1376
+ ...queryAuth(execution),
1377
+ signJwt: () => Promise.reject(KernelRefusal.rowPending("JWT signing", 6)),
1378
+ });
1379
+
1380
+ function validateId(
1381
+ expectedTableName: unknown,
1382
+ id: unknown,
1383
+ ): asserts id is DocumentId {
1384
+ if (typeof id !== "string") {
1385
+ throw new Error(
1386
+ `Invalid argument \`id\`, expected string but got '${typeof id}': ${id as any}`,
1387
+ );
1388
+ }
1389
+ if (expectedTableName === undefined) return;
1390
+ if (typeof expectedTableName !== "string") {
1391
+ throw new Error(
1392
+ `Invalid argument \`tableName\`, expected string but got '${typeof expectedTableName}': ${expectedTableName as any}`,
1393
+ );
1394
+ }
1395
+ const actualTableName = tableNameFromId(id);
1396
+ if (actualTableName === null) {
1397
+ throw new Error(
1398
+ `Invalid argument \`id\`, expected ID value but got '${id}'`,
1399
+ );
1400
+ }
1401
+ if (actualTableName !== expectedTableName) {
1402
+ throw new Error(
1403
+ `Invalid argument \`id\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`,
1404
+ );
1405
+ }
1406
+ }
1407
+
1408
+ /**
1409
+ * Convex's server library reaches the backend through `globalThis.Convex`. The
1410
+ * kernel answers each syscall for the function that made it.
1411
+ */
1412
+ const installConvexGlobal = () => {
1413
+ const global = globalThis as { Convex?: { [kernelBrand]?: true } };
1414
+ if (global.Convex?.[kernelBrand] === true) return;
1415
+ global.Convex = {
1416
+ [kernelBrand]: true,
1417
+ syscall: (op: string, args: string) => current().world.syscall(op, args),
1418
+ asyncSyscall: (op: string, args: string) =>
1419
+ current().world.asyncSyscall(op, args),
1420
+ jsSyscall: (op: string) => current().world.jsSyscall(op),
1421
+ } as any;
1422
+ };
1423
+
1424
+ /**
1425
+ * Whether `globalThis.Convex` is the kernel's, so no other backend answered.
1426
+ */
1427
+ export const ownsConvexGlobal = (): boolean =>
1428
+ (globalThis as { Convex?: { [kernelBrand]?: true } }).Convex?.[
1429
+ kernelBrand
1430
+ ] === true;