@gaganref/confect-test 10.3.1-fork.89 → 10.3.1-fork.90
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/dist/TestConfect.d.ts +33 -7
- package/dist/TestConfect.d.ts.map +1 -1
- package/dist/TestConfect.js +11 -6
- package/dist/TestConfect.js.map +1 -1
- package/dist/internal/Attempt.js.map +1 -1
- package/dist/internal/Clock.d.ts +29 -0
- package/dist/internal/Clock.d.ts.map +1 -0
- package/dist/internal/Clock.js +66 -0
- package/dist/internal/Clock.js.map +1 -0
- package/dist/internal/ConvexTest.d.ts +33 -1
- package/dist/internal/ConvexTest.d.ts.map +1 -1
- package/dist/internal/ConvexTest.js +8 -5
- package/dist/internal/ConvexTest.js.map +1 -1
- package/dist/internal/Execution.d.ts +85 -5
- package/dist/internal/Execution.d.ts.map +1 -1
- package/dist/internal/Execution.js +285 -51
- package/dist/internal/Execution.js.map +1 -1
- package/dist/internal/Globals.d.ts.map +1 -1
- package/dist/internal/Globals.js +12 -0
- package/dist/internal/Globals.js.map +1 -1
- package/dist/internal/Invocation.d.ts +11 -0
- package/dist/internal/Invocation.d.ts.map +1 -1
- package/dist/internal/Invocation.js +34 -21
- package/dist/internal/Invocation.js.map +1 -1
- package/dist/internal/Kernel.d.ts +3 -1
- package/dist/internal/Kernel.d.ts.map +1 -1
- package/dist/internal/Kernel.js +2 -2
- package/dist/internal/Kernel.js.map +1 -1
- package/dist/internal/KernelRefusal.d.ts +25 -0
- package/dist/internal/KernelRefusal.d.ts.map +1 -1
- package/dist/internal/KernelRefusal.js +22 -1
- package/dist/internal/KernelRefusal.js.map +1 -1
- package/dist/internal/KernelValues.d.ts +6 -4
- package/dist/internal/KernelValues.d.ts.map +1 -1
- package/dist/internal/KernelValues.js +20 -5
- package/dist/internal/KernelValues.js.map +1 -1
- package/dist/internal/MountedHttp.d.ts.map +1 -1
- package/dist/internal/MountedHttp.js +3 -3
- package/dist/internal/MountedHttp.js.map +1 -1
- package/dist/internal/Scheduling.d.ts +71 -0
- package/dist/internal/Scheduling.d.ts.map +1 -0
- package/dist/internal/Scheduling.js +60 -0
- package/dist/internal/Scheduling.js.map +1 -0
- package/package.json +3 -3
- package/src/TestConfect.ts +62 -15
- package/src/internal/Attempt.ts +1 -1
- package/src/internal/Clock.ts +95 -0
- package/src/internal/ConvexTest.ts +51 -6
- package/src/internal/Execution.ts +415 -50
- package/src/internal/Globals.ts +20 -0
- package/src/internal/Invocation.ts +38 -13
- package/src/internal/Kernel.ts +5 -5
- package/src/internal/KernelRefusal.ts +24 -0
- package/src/internal/KernelValues.ts +44 -4
- package/src/internal/MountedHttp.ts +13 -6
- package/src/internal/Scheduling.ts +126 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Execution.js","names":["Globals.own","KernelQuery.exportSchema","Kernel.empty","Kernel.wallClock","KernelRefusal.RegisteredAfterOpen","Invocation.current","KernelRefusal.StaleAttempt","Invocation.bind","Kernel.conflict","KernelRefusal.OptimisticConcurrencyControlFailure","KernelRefusal.CommitTsNotIncreasing","Kernel.apply","KernelQuery.stream","KernelQuery.paginate","KernelRefusal.rowPending","KernelRefusal.requiresBinary","KernelRefusal.ClosedAttempt"],"sources":["../../src/internal/Execution.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n actionGeneric,\n getFunctionAddress,\n mutationGeneric,\n queryGeneric,\n type FunctionReference,\n type GenericSchema,\n type SchemaDefinition,\n type UserIdentity,\n} from \"convex/server\";\nimport { convexToJson, jsonToConvex, type Value } from \"convex/values\";\nimport { KernelAttempt } from \"./Attempt.js\";\nimport * as Globals from \"./Globals.js\";\nimport * as Invocation from \"./Invocation.js\";\nimport * as Kernel from \"./Kernel.js\";\nimport * as KernelQuery from \"./KernelQuery.js\";\nimport * as KernelRefusal from \"./KernelRefusal.js\";\nimport type * as ReadSet from \"./ReadSet.js\";\nimport type {\n DocumentId,\n FunctionPath,\n StoredDocument,\n ValidatorJSON,\n} from \"./KernelValues.js\";\nimport {\n createFunctionHandle,\n createTestJwt,\n deserializeConvexErrorData,\n evaluateValue,\n hasPendingValues,\n parseArgs,\n parseFunctionHandle,\n resolveCommittedValues,\n simpleHash,\n tableNameFromId,\n validateFunctionArgs,\n validateReturnValue,\n} from \"./KernelValues.js\";\n\nconst ROOT = \"\";\nconst TYPICAL_CONVEX_ID_LENGTH = 32;\n\ntype Modules = Record<string, () => Promise<any>>;\n\n/**\n * One registered component: its schema and its function modules, each loaded\n * once when the world opens.\n */\ninterface Component {\n readonly path: string;\n readonly schema: KernelQuery.KernelSchema | null;\n readonly loaders: ReadonlyMap<string, () => Promise<any>>;\n readonly loaded: Map<string, any>;\n}\n\n/**\n * Who is calling: the identity and the request attributes a test accessor set.\n */\nexport interface Caller {\n readonly identity: UserIdentity | null;\n readonly token: string | null;\n readonly ip: string | null;\n readonly userAgent: string | null;\n}\n\nexport const anonymous: Caller = {\n identity: null,\n token: null,\n ip: null,\n userAgent: null,\n};\n\nexport const withIdentity = (\n caller: Caller,\n identity: Partial<UserIdentity>,\n): Caller => {\n const subject = identity.subject ?? \"\" + simpleHash(JSON.stringify(identity));\n const issuer = identity.issuer ?? \"https://convex.test\";\n const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;\n const full = { ...identity, subject, issuer, tokenIdentifier };\n return { ...caller, identity: full, token: createTestJwt(full) };\n};\n\ninterface Request {\n readonly ip: string | null;\n readonly userAgent: string | null;\n readonly requestId: string;\n readonly scheduledFunctionId: string | null;\n readonly authToken: string | null;\n}\n\ntype UdfType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * How a prepared attempt's function ended.\n */\nexport type Outcome =\n | { readonly _tag: \"returned\"; readonly value: Value }\n | { readonly _tag: \"failed\"; readonly error: unknown };\n\n/**\n * A mutation attempt run to its commit point and held until `apply`.\n */\nexport interface HeldAttempt {\n readonly id: string;\n readonly request: string;\n readonly number: Invocation.Attempt;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly outcome: Outcome;\n}\n\n/**\n * What `apply` did with a held attempt. A conflict discards the attempt and\n * holds exactly one next attempt, run against the latest commit. Nothing is\n * retried until that one is applied in turn.\n */\nexport type KernelApply =\n | {\n readonly kind: \"applied\";\n readonly version: Kernel.Version;\n readonly commitTs: bigint;\n readonly result: Value;\n }\n | { readonly kind: \"conflict\"; readonly next: HeldAttempt }\n | {\n readonly kind: \"exhausted\";\n readonly error: KernelRefusal.OptimisticConcurrencyControlFailure;\n }\n | { readonly kind: \"refused\"; readonly tag: string; readonly error: unknown };\n\ninterface Held {\n readonly view: HeldAttempt;\n readonly attempt: KernelAttempt;\n readonly again: (number: Invocation.Attempt) => Promise<Held>;\n}\n\nconst lastAttempt: Invocation.Attempt = 5;\n\nconst tagOf = (error: unknown): string => {\n const tagged = (value: unknown): value is { readonly _tag: string } =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\";\n const data = (error as { data?: unknown } | null)?.data;\n if (tagged(data)) return data._tag;\n if (tagged(error)) return error._tag;\n return error instanceof Error ? error.name : \"Error\";\n};\n\n/**\n * One running function. Queries and mutations read and write through their\n * attempt. Every async syscall of a query or a mutation, nested calls included,\n * takes its turn on `turn` in the order the function made it.\n */\ninterface Execution {\n readonly world: World;\n readonly componentPath: string;\n readonly udfPath: string;\n readonly udfType: UdfType;\n readonly attempt: KernelAttempt | undefined;\n readonly identity: UserIdentity | null;\n readonly request: Request;\n readonly pagination: { calls: number } | undefined;\n readonly turn: Turn;\n}\n\n/**\n * A queue that runs one task at a time, in the order they were taken.\n */\nclass Turn {\n private tail: Promise<unknown> = Promise.resolve();\n\n take<A>(task: () => A | Promise<A>): Promise<A> {\n const result = this.tail.then(task);\n this.tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /**\n * Resolves once every task taken so far has settled, including the tasks\n * taken while waiting.\n */\n idle(): Promise<void> {\n const tail = this.tail;\n return tail.then(() => (this.tail === tail ? undefined : this.idle()));\n }\n}\n\n/**\n * A function's invocation finishes once its handler returned and every syscall\n * it started has run. On the binary a query or mutation keeps running the\n * syscalls in its queue after its promise resolves, then returns (`run_inner`\n * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write\n * still lands in its own transaction.\n */\nconst settled = <A>(execution: Execution, result: A): Promise<A> =>\n execution.turn.idle().then(() => result);\n\nconst executions = new AsyncLocalStorage<Execution>();\n\n/**\n * Run a function's code as `execution`, with its own copy of the globals a test\n * invocation pins.\n */\nconst enter = <A>(execution: Execution, run: () => A): A =>\n Globals.own(() => executions.run(execution, run));\nconst kernelBrand = Symbol.for(\"@confect/test/Kernel\");\n\nconst current = (): Execution => {\n const execution = executions.getStore();\n if (execution === undefined) {\n throw new Error(\n \"A Convex syscall ran outside any function the test kernel started.\",\n );\n }\n return execution;\n};\n\nlet nextRequestId = 0;\nconst newRequest = (caller: Caller): Request => ({\n ip: caller.ip,\n userAgent: caller.userAgent,\n requestId: `kernel-request-${nextRequestId++}`,\n scheduledFunctionId: null,\n authToken: caller.token,\n});\n\nconst findModulesRoot = (paths: ReadonlyArray<string>): string => {\n const generated = paths.find((path) => path.includes(\"_generated\"));\n if (generated === undefined) {\n throw new Error(\n 'Could not find the \"_generated\" directory, make sure to run ' +\n \"`npx convex dev` or `npx convex codegen`. Make sure your \" +\n '`import.meta.glob` includes the files in the \"_generated\" directory',\n );\n }\n return generated.split(\"_generated\", 2)[0]!;\n};\n\nconst makeComponent = (\n path: string,\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n): Component => {\n const root = findModulesRoot(Object.keys(modules));\n const relative = Object.entries(modules)\n .filter(([key]) => key.startsWith(root))\n .map(([key, load]) => [key.slice(root.length), load] as const);\n const nested = relative\n .map(([file]) => file)\n .filter((file) => file.endsWith(\"/convex.config.ts\"))\n .map((file) => file.slice(0, -\"convex.config.ts\".length));\n return {\n path,\n schema: KernelQuery.exportSchema(schema),\n loaders: new Map(\n relative\n .filter(\n ([file]) =>\n isFunctionModule(file) &&\n !nested.some((dir) => file.startsWith(dir)),\n )\n .map(([file, load]) => [file.replace(/\\.[^.]+$/, \"\"), load]),\n ),\n loaded: new Map(),\n };\n};\n\nconst entryExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".jsx\",\n];\n\n/**\n * Whether Convex's bundler deploys this file as a function module, by the rule\n * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a\n * schema, a config and `_generated` never reach the binary, so the kernel\n * neither loads them nor resolves a function in them.\n */\nconst isFunctionModule = (file: string): boolean => {\n const base = file.split(\"/\").pop()!;\n return (\n entryExtensions.some((extension) => file.endsWith(extension)) &&\n !file.startsWith(\"_generated/\") &&\n !base.startsWith(\".\") &&\n !base.startsWith(\"#\") &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n (base.match(/\\./g) ?? []).length <= 1 &&\n !file.includes(\" \")\n );\n};\n\nconst unregistered = (world: World, componentPath: string) => {\n const registered = [...world.components.keys()].filter((p) => p !== ROOT);\n return new Error(\n `Component \"${componentPath}\" is not registered on this test backend. ` +\n (registered.length === 0\n ? \"No components have been registered.\"\n : `Registered components: ${registered.map((p) => `\"${p}\"`).join(\", \")}.`),\n );\n};\n\ntype FunctionAddress = {\n readonly name?: string | undefined;\n readonly reference?: string | undefined;\n readonly functionHandle?: string | undefined;\n};\n\n/**\n * Where an address points, read from the calling component.\n */\nconst functionPathOf = (\n address: FunctionAddress,\n from: string,\n): FunctionPath => {\n if (address.functionHandle !== undefined) {\n return parseFunctionHandle(address.functionHandle) as FunctionPath;\n }\n if (address.name !== undefined) {\n return { udfPath: address.name, componentPath: from };\n }\n if (address.reference !== undefined) {\n // \"_reference/childComponent/<child>/path/to/file/fn\"\n const parts = address.reference.split(\"/\");\n const child = parts[2]!;\n const rest = parts.slice(3);\n return {\n componentPath: from.length > 0 ? `${from}/${child}` : child,\n udfPath: `${rest.slice(0, -1).join(\"/\")}:${rest[rest.length - 1]}`,\n };\n }\n throw new Error(\"Function address not supported\");\n};\n\nconst pathOfReference = (\n reference: FunctionReference<any, any, any, any> | string,\n from: string,\n) =>\n functionPathOf(getFunctionAddress(reference as any) as FunctionAddress, from);\n\ninterface Resolved {\n readonly func: any;\n readonly handler: (ctx: any, args: any) => any;\n readonly args: ValidatorJSON;\n readonly returns: ValidatorJSON | null;\n}\n\nconst kindCheck = {\n query: \"isQuery\",\n mutation: \"isMutation\",\n action: \"isAction\",\n} as const;\n\n/**\n * A test backend: its registered components and the kernel state they share.\n */\nexport class World {\n readonly components = new Map<string, Component>();\n state: Kernel.State = Kernel.empty;\n private opened: Promise<void> | undefined;\n private nextDocId = 10000;\n private lastCreationTime = 0;\n private nextQueryId = 1;\n private readonly queries = new Map<number, Iterator<any>>();\n private readonly holding = new Map<string, Held>();\n private nextAttemptId = 1;\n\n constructor(\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n private readonly runtime: Kernel.KernelRuntime = Kernel.wallClock(),\n ) {\n installConvexGlobal();\n this.components.set(ROOT, makeComponent(ROOT, schema, modules));\n }\n\n register(\n componentPath: string,\n schema: SchemaDefinition<GenericSchema, boolean>,\n modules: Modules,\n ) {\n if (this.opened !== undefined) {\n throw new KernelRefusal.RegisteredAfterOpen({\n componentPath,\n message: `Component \"${componentPath}\" was registered after the test backend opened. Register every component before the first call.`,\n });\n }\n this.components.set(\n componentPath,\n makeComponent(componentPath, schema, modules),\n );\n }\n\n /**\n * Load every registered module of every component, once, before any function\n * runs.\n */\n open(): Promise<void> {\n this.opened ??= Promise.all(\n Array.from(this.components.values(), (component) =>\n Promise.all(\n Array.from(component.loaders, ([path, load]) =>\n load().then((module) => component.loaded.set(path, module)),\n ),\n ),\n ),\n ).then(() => undefined);\n return this.opened;\n }\n\n private component(componentPath: string): Component {\n const component = this.components.get(componentPath);\n if (component === undefined) throw unregistered(this, componentPath);\n return component;\n }\n\n private resolve(functionPath: FunctionPath, kind: UdfType | \"any\"): Resolved {\n const [modulePath, maybeExport] = functionPath.udfPath.split(\":\") as [\n string,\n string | undefined,\n ];\n const exportName = maybeExport ?? \"default\";\n const component = this.component(functionPath.componentPath);\n const module = component.loaded.get(modulePath);\n if (module === undefined) {\n throw new Error(`Could not find module for: \"${modulePath}\"`);\n }\n const func = module[exportName];\n if (func === undefined) {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but there is no such export.`,\n );\n }\n const handler = \"_handler\" in func ? func._handler : func;\n if (typeof handler !== \"function\") {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but got: ${func}`,\n );\n }\n if (kind !== \"any\" && !func[kindCheck[kind]]) {\n throw new Error(\n `Expected a ${kind} function, but the function exported from module \"${modulePath}\" as \\`${exportName}\\` is not a ${kind}.`,\n );\n }\n const args = JSON.parse(func.exportArgs()) as ValidatorJSON;\n if (args.type !== \"object\" && args.type !== \"any\") {\n throw new Error(\n `Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): ` +\n `Args validator must be an object or any`,\n );\n }\n return { func, handler, args, returns: JSON.parse(func.exportReturns()) };\n }\n\n // Calls from the test.\n\n query(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runQuery(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.queryAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n mutation(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runMutation(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.mutationAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n action(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runAction(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.actionAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n run(\n caller: Caller,\n componentPath: string,\n handler: (ctx: any) => any,\n ): Promise<any> {\n return this.open().then(() => {\n this.component(componentPath);\n return this.runMutation(\n { componentPath, udfPath: \"custom\" },\n { handler, args: { type: \"any\" }, returns: null },\n {},\n { caller, request: newRequest(caller) },\n );\n });\n }\n\n // Held attempts.\n\n /**\n * Run a mutation to its commit point and hold it as attempt 1.\n */\n prepare(caller: Caller, reference: any, args: any): Promise<HeldAttempt> {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n 1,\n Invocation.current(),\n ).then((held) => held.view);\n });\n }\n\n apply(id: string): Promise<KernelApply> {\n const held = this.holding.get(id);\n return held === undefined\n ? Promise.reject(\n new KernelRefusal.StaleAttempt({\n id,\n message: `The test kernel holds no attempt \"${id}\". It was already applied, or never prepared.`,\n }),\n )\n : this.applyHeld(held);\n }\n\n /**\n * The held attempts, oldest first.\n */\n held(): ReadonlyArray<HeldAttempt> {\n return Array.from(this.holding.values(), (held) => held.view);\n }\n\n // Calls by address, from the test or from a running function.\n\n private queryAt(\n functionPath: FunctionPath,\n args: any,\n from: From,\n snapshotOnly = false,\n ) {\n const resolved = this.resolve(functionPath, \"query\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runQuery(functionPath, resolved, args, from, snapshotOnly);\n }\n\n private mutationAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runMutation(functionPath, resolved, args, from);\n }\n\n private actionAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"action\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.runAction(functionPath, resolved, args, from);\n }\n\n // Runners.\n\n private execution(\n functionPath: FunctionPath,\n udfType: UdfType,\n attempt: KernelAttempt | undefined,\n from: From,\n pagination: { calls: number } | undefined,\n ): Execution {\n // A function in a component runs with no identity, whoever called it, as\n // Convex gives a component no `ctx.auth` of the caller's. A nested call in\n // the host takes its parent's identity, even when that is none.\n const identity =\n functionPath.componentPath !== ROOT\n ? null\n : from.parent !== undefined\n ? from.parent.identity\n : from.caller.identity;\n return {\n world: this,\n componentPath: functionPath.componentPath,\n udfPath: functionPath.udfPath,\n udfType,\n attempt,\n identity,\n request: from.request,\n pagination,\n turn: new Turn(),\n };\n }\n\n private runQuery(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n snapshotOnly = false,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n const isNested = parentAttempt !== undefined;\n const attempt =\n parentAttempt === undefined\n ? new KernelAttempt(this.state)\n : snapshotOnly\n ? new KernelAttempt(parentAttempt.snapshot)\n : parentAttempt;\n const execution = this.execution(\n functionPath,\n \"query\",\n attempt,\n from,\n (isNested && from.parent?.pagination) || { calls: 0 },\n );\n const q = queryGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: queryAuth(execution) }, a),\n }) as unknown as { invokeQuery: (args: string) => Promise<string> };\n return enter(execution, () =>\n q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n if (!isNested && hasPendingValues(result)) {\n throw new Error(\n `Function ${functionPath.udfPath} return value invalid: queries ` +\n `cannot return an unresolved placeholder value.`,\n );\n }\n validateReturnValue(resolved.returns, result, \"query\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n private invokeMutation(\n execution: Execution,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n ): Promise<Value> {\n const m = mutationGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: mutationAuth(execution) }, a),\n }) as unknown as { invokeMutation: (args: string) => Promise<string> };\n return enter(execution, () =>\n m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"mutation\", {\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n });\n return result;\n });\n }\n\n private runMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n if (parentAttempt !== undefined) {\n const frame = parentAttempt.child();\n const execution = this.execution(\n functionPath,\n \"mutation\",\n frame,\n from,\n undefined,\n );\n // As at the top level, a nested mutation ends once its function has\n // returned and every syscall it started has settled. Convex runs a\n // nested function's syscall queue to the end before it commits its\n // subtransaction, so a detached fiber's late write lands in this frame\n // and merges with it. A failed one ends at once and rolls back.\n return this.invokeMutation(execution, resolved, args).then(\n (result) =>\n frame.drained().then(() => {\n frame.close();\n frame.merge();\n return result;\n }),\n (error: unknown) => {\n frame.close();\n throw deserializeConvexErrorData(error);\n },\n );\n }\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n 1,\n Invocation.current(),\n ).then((held) => this.publish(held));\n }\n\n /**\n * Run one attempt of a top-level mutation against the latest commit, then\n * hold it. The commit point is once the function has returned and every\n * syscall it started has settled. A test invocation bound when the mutation\n * was first called reaches each attempt's handler with that attempt's\n * number.\n */\n private prepareMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n from: From,\n number: Invocation.Attempt,\n bound: Invocation.Invocation | undefined,\n ): Promise<Held> {\n const attempt = new KernelAttempt(this.state, number);\n const execution = this.execution(\n functionPath,\n \"mutation\",\n attempt,\n from,\n undefined,\n );\n const run = () => this.invokeMutation(execution, resolved, args);\n const started =\n bound === undefined\n ? run()\n : Invocation.bind({ ...bound, attempt: number }, run);\n return started\n .then(\n (value) =>\n attempt.drained().then((): Outcome => ({ _tag: \"returned\", value })),\n (error: unknown): Outcome => ({\n _tag: \"failed\",\n error: deserializeConvexErrorData(error),\n }),\n )\n .then((outcome) => {\n attempt.close();\n const held: Held = {\n view: {\n id: `attempt-${this.nextAttemptId++}`,\n request: from.request.requestId,\n number,\n snapshot: attempt.snapshot.version,\n reads: attempt.reads,\n outcome,\n },\n attempt,\n again: (next) =>\n this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n next,\n bound,\n ),\n };\n this.holding.set(held.view.id, held);\n return held;\n });\n }\n\n /**\n * Validate a held attempt's reads against every commit since its snapshot,\n * then publish its writes or prepare its next attempt. An attempt that wrote\n * nothing publishes nothing and has nothing to validate. It answers its\n * snapshot's version and commit timestamp.\n */\n private applyHeld({ view, attempt, again }: Held): Promise<KernelApply> {\n this.holding.delete(view.id);\n const { outcome } = view;\n if (outcome._tag === \"failed\") {\n return Promise.resolve({\n kind: \"refused\",\n tag: tagOf(outcome.error),\n error: outcome.error,\n });\n }\n const writes = attempt.writes();\n if (writes.length === 0) {\n // As on the binary, a mutation that wrote nothing is serialized at its\n // snapshot and allocates no timestamp for a later commit.\n const { version, commitTs } = attempt.snapshot;\n return Promise.resolve({\n kind: \"applied\",\n version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n if (\n Kernel.conflict(this.state, view.snapshot, attempt.reads) !== undefined\n ) {\n if (view.number === lastAttempt) {\n return Promise.resolve({\n kind: \"exhausted\",\n error: new KernelRefusal.OptimisticConcurrencyControlFailure({\n attempts: lastAttempt,\n message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`,\n }),\n });\n }\n return again((view.number + 1) as Invocation.Attempt).then(\n (next): KernelApply => ({ kind: \"conflict\", next: next.view }),\n );\n }\n const commitTs = this.runtime.commitTs(this.state.version + 1);\n if (commitTs <= this.state.commitTs) {\n return Promise.reject(\n new KernelRefusal.CommitTsNotIncreasing({\n version: this.state.version + 1,\n previous: this.state.commitTs,\n commitTs,\n 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}.`,\n }),\n );\n }\n this.state = Kernel.apply(this.state, writes, commitTs);\n return Promise.resolve({\n kind: \"applied\",\n version: this.state.version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n\n /**\n * Apply until the mutation publishes, is refused or is exhausted, as the\n * binary retries a mutation that conflicts.\n */\n private publish(held: Held): Promise<Value> {\n return this.applyHeld(held).then((applied) => {\n if (applied.kind === \"applied\") return applied.result;\n if (applied.kind === \"conflict\") {\n return this.publish(this.holding.get(applied.next.id)!);\n }\n throw applied.error;\n });\n }\n\n private runAction(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const execution = this.execution(\n functionPath,\n \"action\",\n undefined,\n from,\n undefined,\n );\n const inner: From = { request: from.request, parent: execution };\n const a = actionGeneric({\n handler: (ctx: any, innerArgs: any) =>\n resolved.handler(\n {\n ...ctx,\n runQuery: (reference: any, queryArgs: any) =>\n this.queryAt(\n pathOfReference(reference, functionPath.componentPath),\n queryArgs,\n inner,\n ),\n runMutation: (reference: any, mutationArgs: any) =>\n this.mutationAt(\n pathOfReference(reference, functionPath.componentPath),\n mutationArgs,\n inner,\n ),\n runAction: (reference: any, actionArgs: any) =>\n this.actionAt(\n pathOfReference(reference, functionPath.componentPath),\n actionArgs,\n inner,\n ),\n auth: queryAuth(execution),\n },\n innerArgs,\n ),\n }) as unknown as {\n invokeAction: (requestId: string, args: string) => Promise<string>;\n };\n const run = () =>\n enter(execution, () =>\n a.invokeAction(\n from.request.requestId,\n JSON.stringify(convexToJson([parseArgs(args)])),\n ),\n );\n // An action another function calls is an invocation of its own, with its\n // world's services, a start time read from its world's clock and its\n // world's random stream, as a scheduled job is.\n const bound = from.parent === undefined ? undefined : Invocation.current();\n const { ip, userAgent, requestId, scheduledFunctionId } = from.request;\n const started =\n bound === undefined\n ? run()\n : Invocation.bind(\n {\n world: bound.world,\n componentPath: functionPath.componentPath,\n attempt: 1,\n request: { ip, userAgent, requestId, scheduledFunctionId },\n services: bound.world.services,\n startedAt: bound.world.clock(),\n random: bound.world.random,\n },\n run,\n );\n return started\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"action\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n // Syscalls.\n\n private schema(componentPath: string) {\n return this.component(componentPath).schema;\n }\n\n private view(execution: Execution): KernelQuery.TableView {\n const attempt = transaction(execution);\n return {\n schema: this.schema(execution.componentPath),\n scan: (tableName) => attempt.scan(execution.componentPath, tableName),\n read: (interval, after) =>\n attempt.readInterval({\n ...interval,\n componentPath: execution.componentPath,\n after,\n }),\n };\n }\n\n private generateId(table: string): DocumentId {\n const counter = String(this.nextDocId++).padStart(\n TYPICAL_CONVEX_ID_LENGTH - table.length,\n \"0\",\n );\n return (counter + table) as DocumentId;\n }\n\n syscall(op: string, jsonArgs: string): string {\n const args = JSON.parse(jsonArgs);\n const execution = current();\n if (execution.attempt?.closed === true) throw closed(execution, op);\n switch (op) {\n case \"1.0/getSnapshotTs\":\n return JSON.stringify(\n convexToJson(transaction(execution).snapshot.commitTs),\n );\n case \"1.0/queryStream\": {\n // The binary reads a query at each `1.0/queryStreamNext`, which waits\n // its turn in the queue, so the stream opens at its first read and sees\n // every write made before it.\n const queryId = this.nextQueryId++;\n const view = this.view(execution);\n let results: Iterator<any> | undefined;\n this.queries.set(queryId, {\n next: () => (results ??= KernelQuery.stream(view, args.query)).next(),\n });\n return JSON.stringify({ queryId });\n }\n case \"1.0/queryCleanup\":\n this.queries.delete(args.queryId);\n return JSON.stringify({});\n case \"1.0/db/normalizeId\": {\n const tableName = tableNameFromId(args.idString);\n return JSON.stringify({\n id: tableName === args.table ? args.idString : null,\n });\n }\n default:\n throw new Error(`The test kernel does not support syscall: \"${op}\"`);\n }\n }\n\n /**\n * The binary queues a query's or mutation's async syscalls and runs them one\n * at a time, oldest first (`start_async_syscall` and `run_inner` in\n * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested\n * call never share a batch (`AsyncSyscallBatch::can_push` in\n * `async_syscall.rs`), and a nested call holds the queue until it has\n * committed or rolled back its subtransaction (`run_udf` in\n * `async_syscall.rs`). So a caller's write made after its nested call runs\n * after that call, and a nested mutation sees every write made before it. An\n * action's calls run side by side.\n */\n asyncSyscall(op: string, jsonArgs: string): Promise<string> {\n const execution = current();\n const attempt = execution.attempt;\n if (attempt === undefined) {\n return Promise.resolve().then(() =>\n this.dispatchAsync(op, JSON.parse(jsonArgs), execution),\n );\n }\n if (attempt.closed) return Promise.reject(closed(execution, op));\n // A syscall counts toward its frame's lifetime from the moment it is\n // queued, so a frame never closes with a write still waiting its turn.\n const end = attempt.begin();\n return execution.turn\n .take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution))\n .finally(end);\n }\n\n private dispatchAsync(\n op: string,\n args: any,\n execution: Execution,\n ): string | Promise<string> {\n switch (op) {\n case \"1.0/get\": {\n const { table, id } = args;\n return JSON.stringify(convexToJson(this.get(execution, table, id)));\n }\n case \"1.0/queryStreamNext\": {\n const results = this.queries.get(args.queryId);\n if (results === undefined) throw new Error(\"Bad queryId\");\n const { value, done } = results.next();\n return JSON.stringify(\n convexToJson(\n done ? { value: null, done: true } : { value, done: false },\n ),\n );\n }\n case \"1.0/queryPage\": {\n const pagination = execution.pagination;\n if (pagination) {\n pagination.calls += 1;\n if (pagination.calls > 1) {\n throw new Error(\n \"Only a single paginated query (`.paginate()`) is allowed per \" +\n \"query, including nested query calls and component calls. \" +\n \"This is a Convex limit: https://docs.convex.dev/database/pagination\",\n );\n }\n }\n return JSON.stringify(\n convexToJson(KernelQuery.paginate(this.view(execution), args) as any),\n );\n }\n case \"1.0/insert\":\n return JSON.stringify({\n _id: this.insert(execution, args.table, jsonToConvex(args.value)),\n });\n case \"1.0/shallowMerge\":\n this.patch(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/replace\":\n this.replace(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/remove\":\n this.remove(execution, args.table, args.id);\n return JSON.stringify({});\n case \"1.0/count\": {\n const attempt = transaction(execution);\n attempt.readInterval({\n kind: \"interval\",\n componentPath: execution.componentPath,\n table: args.table,\n fields: [\"_creationTime\", \"_id\"],\n order: \"asc\",\n range: [],\n after: null,\n })(\"end\");\n return JSON.stringify(\n attempt.scan(execution.componentPath, args.table).length,\n );\n }\n case \"1.0/getFunctionMetadata\":\n return JSON.stringify(\n convexToJson({\n name: execution.udfPath,\n componentPath: execution.componentPath,\n }),\n );\n case \"1.0/getRequestMetadata\":\n if (execution.udfType === \"query\") {\n throw new Error(\n \"getRequestMetadata() can only be called from a mutation, action \" +\n \"or HTTP action. It is not available in queries.\",\n );\n }\n return JSON.stringify(convexToJson(execution.request as any));\n case \"1.0/getDeploymentMetadata\":\n return JSON.stringify(\n convexToJson({ name: \"test\", region: null, class: \"s16\" }),\n );\n case \"1.0/actions/query\":\n case \"1.0/actions/mutation\":\n case \"1.0/actions/action\": {\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const run =\n op === \"1.0/actions/query\"\n ? this.queryAt(functionPath, args.args, from)\n : op === \"1.0/actions/mutation\"\n ? this.mutationAt(functionPath, args.args, from)\n : this.actionAt(functionPath, args.args, from);\n return run.then((value) => JSON.stringify(convexToJson(value)));\n }\n case \"1.0/runUdf\": {\n const { udfType, args: udfArgs } = args;\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const value = jsonToConvex(udfArgs);\n const run =\n udfType === \"query\"\n ? this.queryAt(functionPath, value, from)\n : udfType === \"snapshotQuery\"\n ? this.queryAt(functionPath, value, from, true)\n : udfType === \"mutation\"\n ? this.mutationAt(functionPath, value, from)\n : Promise.reject(\n new Error(\n `The test kernel does not support udf type: \"${udfType}\"`,\n ),\n );\n return run.then((result) => JSON.stringify(convexToJson(result)));\n }\n case \"1.0/createFunctionHandle\": {\n const functionPath = functionPathOf(args, execution.componentPath);\n this.component(functionPath.componentPath);\n return JSON.stringify(createFunctionHandle(functionPath));\n }\n case \"1.0/auditLog\":\n return JSON.stringify(null);\n case \"1.0/schedule\":\n case \"1.0/actions/schedule\":\n case \"1.0/cancel_job\":\n case \"1.0/actions/cancel_job\":\n throw KernelRefusal.rowPending(\"the scheduler\", 5);\n case \"1.0/storageDelete\":\n case \"1.0/storageGetUrl\":\n case \"1.0/storageGenerateUploadUrl\":\n throw KernelRefusal.rowPending(\"storage\", 6);\n case \"1.0/getTransactionMetrics\":\n throw KernelRefusal.rowPending(\"transaction limits\", 6);\n case \"1.0/actions/vectorSearch\":\n throw KernelRefusal.requiresBinary(\"vectorSearch\");\n default:\n throw new Error(\n `The test kernel does not support async syscall: \"${op}\"`,\n );\n }\n }\n\n jsSyscall(op: string): Promise<never> {\n return Promise.reject(\n op.startsWith(\"storage/\")\n ? KernelRefusal.rowPending(\"storage\", 6)\n : new Error(`The test kernel does not support js syscall: \"${op}\"`),\n );\n }\n\n // Documents. The checks and messages are convex-test's.\n\n private get(execution: Execution, tableName: unknown, id: unknown) {\n validateId(tableName, id);\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n return attempt.get(execution.componentPath, id);\n }\n\n private insert(execution: Execution, table: string, value: any): DocumentId {\n const attempt = transaction(execution);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n table,\n value,\n );\n const _id = this.generateId(table);\n const now = this.runtime.now();\n const _creationTime =\n now <= this.lastCreationTime ? this.lastCreationTime + 0.001 : now;\n this.lastCreationTime = _creationTime;\n attempt.write(execution.componentPath, _id, {\n ...value,\n _id,\n _creationTime,\n });\n return _id;\n }\n\n private existing(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n write: string,\n value: unknown,\n ): StoredDocument {\n validateId(tableName, id);\n if (value !== undefined && typeof value !== \"object\") {\n throw new Error(\n `Invalid argument \\`value\\` in \\`db.${write}\\`, expected object but got '${typeof value}': ${value as any}`,\n );\n }\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n const document = attempt.get(execution.componentPath, id);\n if (document === null) {\n throw new Error(\n write === \"delete\"\n ? \"Delete on non-existent doc\"\n : `${write === \"patch\" ? \"Patch\" : \"Replace\"} on non-existent document with ID \"${id}\"`,\n );\n }\n return document;\n }\n\n private fields(document: StoredDocument, value: Record<string, any>) {\n if (value._id !== undefined && value._id !== document._id) {\n throw new Error(\n `Provided \\`_id\\` field value \"${value._id}\" ` +\n `does not match the document ID \"${document._id}\"`,\n );\n }\n if (\n value._creationTime !== undefined &&\n value._creationTime !== document._creationTime\n ) {\n throw new Error(\n `Provided \\`_creationTime\\` field value ${value._creationTime} ` +\n `does not match the document's creation time ${document._creationTime}`,\n );\n }\n const convexValue: Record<string, Value | undefined> = {};\n for (const [key, v] of Object.entries(value)) {\n if (key !== \"_id\" && key !== \"_creationTime\") {\n convexValue[key] = evaluateValue(v);\n }\n }\n return convexValue;\n }\n\n private patch(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"patch\", value);\n const { _id, _creationTime, ...fields } = document;\n const merged = { ...fields, ...this.fields(document, value) };\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(_id)!,\n merged,\n );\n transaction(execution).write(execution.componentPath, _id, {\n _id,\n _creationTime,\n ...merged,\n } as StoredDocument);\n }\n\n private replace(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"replace\", value);\n const fields = this.fields(document, value);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(document._id)!,\n fields,\n );\n transaction(execution).write(execution.componentPath, document._id, {\n ...fields,\n _id: document._id,\n _creationTime: document._creationTime,\n } as StoredDocument);\n }\n\n private remove(execution: Execution, tableName: unknown, id: unknown) {\n const document = this.existing(\n execution,\n tableName,\n id,\n \"delete\",\n undefined,\n );\n transaction(execution).write(execution.componentPath, document._id, null);\n }\n}\n\n/**\n * Where a call comes from. A call from the test carries its accessor's caller.\n * A nested call carries its parent execution and takes its identity from it.\n */\ntype From =\n | {\n readonly caller: Caller;\n readonly request: Request;\n readonly parent?: undefined;\n }\n | { readonly parent: Execution; readonly request: Request };\n\nconst closed = (execution: Execution, operation: string) =>\n new KernelRefusal.ClosedAttempt({\n operation,\n message: `\"${operation}\" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`,\n });\n\nconst transaction = (execution: Execution): KernelAttempt => {\n if (execution.attempt === undefined) {\n throw new Error(\n \"The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.\",\n );\n }\n return execution.attempt;\n};\n\nconst queryAuth = (execution: Execution) => ({\n getUserIdentity: () => Promise.resolve(execution.identity),\n});\n\nconst mutationAuth = (execution: Execution) => ({\n ...queryAuth(execution),\n signJwt: () => Promise.reject(KernelRefusal.rowPending(\"JWT signing\", 6)),\n});\n\nfunction validateId(\n expectedTableName: unknown,\n id: unknown,\n): asserts id is DocumentId {\n if (typeof id !== \"string\") {\n throw new Error(\n `Invalid argument \\`id\\`, expected string but got '${typeof id}': ${id as any}`,\n );\n }\n if (expectedTableName === undefined) return;\n if (typeof expectedTableName !== \"string\") {\n throw new Error(\n `Invalid argument \\`tableName\\`, expected string but got '${typeof expectedTableName}': ${expectedTableName as any}`,\n );\n }\n const actualTableName = tableNameFromId(id);\n if (actualTableName === null) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID value but got '${id}'`,\n );\n }\n if (actualTableName !== expectedTableName) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`,\n );\n }\n}\n\n/**\n * Convex's server library reaches the backend through `globalThis.Convex`. The\n * kernel answers each syscall for the function that made it.\n */\nconst installConvexGlobal = () => {\n const global = globalThis as { Convex?: { [kernelBrand]?: true } };\n if (global.Convex?.[kernelBrand] === true) return;\n global.Convex = {\n [kernelBrand]: true,\n syscall: (op: string, args: string) => current().world.syscall(op, args),\n asyncSyscall: (op: string, args: string) =>\n current().world.asyncSyscall(op, args),\n jsSyscall: (op: string) => current().world.jsSyscall(op),\n } as any;\n};\n\n/**\n * Whether `globalThis.Convex` is the kernel's, so no other backend answered.\n */\nexport const ownsConvexGlobal = (): boolean =>\n (globalThis as { Convex?: { [kernelBrand]?: true } }).Convex?.[\n kernelBrand\n ] === true;\n"],"mappings":";;;;;;;;;;;AAwCA,MAAM,OAAO;AACb,MAAM,2BAA2B;AAyBjC,MAAa,YAAoB;CAC/B,UAAU;CACV,OAAO;CACP,IAAI;CACJ,WAAW;AACb;AAEA,MAAa,gBACX,QACA,aACW;CACX,MAAM,UAAU,SAAS,WAAW,KAAK,WAAW,KAAK,UAAU,QAAQ,CAAC;CAC5E,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,kBAAkB,SAAS,mBAAmB,GAAG,OAAO,GAAG;CACjE,MAAM,OAAO;EAAE,GAAG;EAAU;EAAS;EAAQ;CAAgB;CAC7D,OAAO;EAAE,GAAG;EAAQ,UAAU;EAAM,OAAO,cAAc,IAAI;CAAE;AACjE;AAwDA,MAAM,cAAkC;AAExC,MAAM,SAAS,UAA2B;CACxC,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EF,IAAI,sBAAsB,KAAA,GAAW;CACrC,IAAI,OAAO,sBAAsB,UAC/B,MAAM,IAAI,MACR,4DAA4D,OAAO,kBAAkB,KAAK,mBAC5F;CAEF,MAAM,kBAAkB,gBAAgB,EAAE;CAC1C,IAAI,oBAAoB,MACtB,MAAM,IAAI,MACR,uDAAuD,GAAG,EAC5D;CAEF,IAAI,oBAAoB,mBACtB,MAAM,IAAI,MACR,kDAAkD,kBAAkB,yBAAyB,gBAAgB,EAC/G;AAEJ;;;;;AAMA,MAAM,4BAA4B;CAChC,MAAM,SAAS;CACf,IAAI,OAAO,SAAS,iBAAiB,MAAM;CAC3C,OAAO,SAAS;GACb,cAAc;EACf,UAAU,IAAY,SAAiB,QAAQ,CAAC,CAAC,MAAM,QAAQ,IAAI,IAAI;EACvE,eAAe,IAAY,SACzB,QAAQ,CAAC,CAAC,MAAM,aAAa,IAAI,IAAI;EACvC,YAAY,OAAe,QAAQ,CAAC,CAAC,MAAM,UAAU,EAAE;CACzD;AACF;;;;AAKA,MAAa,yBACV,WAAqD,SACpD,iBACI"}
|
|
1
|
+
{"version":3,"file":"Execution.js","names":["Globals.own","KernelQuery.exportSchema","Kernel.empty","Kernel.wallClock","KernelRefusal.RegisteredAfterOpen","KernelRefusal.UnknownStandingSource","Invocation.current","KernelRefusal.StaleAttempt","Scheduling.pending","Scheduling.functions","KernelRefusal.DrainBudgetExceeded","Invocation.unbound","Invocation.bind","Invocation.fresh","Scheduling.stateOf","KernelRefusal.CommitTsNotIncreasing","Kernel.apply","Scheduling.table","Scheduling.row","Kernel.conflict","KernelRefusal.OptimisticConcurrencyControlFailure","KernelQuery.stream","KernelQuery.paginate","KernelRefusal.rowPending","KernelRefusal.requiresBinary","KernelRefusal.ClosedAttempt"],"sources":["../../src/internal/Execution.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n actionGeneric,\n getFunctionAddress,\n mutationGeneric,\n queryGeneric,\n type FunctionReference,\n type GenericSchema,\n type SchemaDefinition,\n type UserIdentity,\n} from \"convex/server\";\nimport { convexToJson, jsonToConvex, type Value } from \"convex/values\";\nimport { KernelAttempt } from \"./Attempt.js\";\nimport * as Clock from \"./Clock.js\";\nimport * as Globals from \"./Globals.js\";\nimport * as Invocation from \"./Invocation.js\";\nimport * as Kernel from \"./Kernel.js\";\nimport * as KernelQuery from \"./KernelQuery.js\";\nimport * as KernelRefusal from \"./KernelRefusal.js\";\nimport type * as ReadSet from \"./ReadSet.js\";\nimport * as Scheduling from \"./Scheduling.js\";\nimport type {\n DocumentId,\n FunctionPath,\n StoredDocument,\n ValidatorJSON,\n} from \"./KernelValues.js\";\nimport {\n createFunctionHandle,\n createTestJwt,\n deserializeConvexErrorData,\n evaluateValue,\n hasPendingValues,\n parseArgs,\n parseFunctionHandle,\n resolveCommittedValues,\n simpleHash,\n tableNameFromId,\n validateFunctionArgs,\n validateReturnValue,\n} from \"./KernelValues.js\";\n\nconst ROOT = \"\";\nconst TYPICAL_CONVEX_ID_LENGTH = 32;\n\ntype Modules = Record<string, () => Promise<any>>;\n\n/**\n * One registered component: its schema, its function modules, each loaded once\n * when the world opens, and its standing sources.\n */\ninterface Component {\n readonly path: string;\n readonly schema: KernelQuery.KernelSchema | null;\n readonly loaders: ReadonlyMap<string, () => Promise<any>>;\n readonly loaded: Map<string, any>;\n /**\n * The functions, as `module:export`, that schedule their own next run. A job\n * that runs one, or that one schedules, is never drain work.\n */\n readonly standing: ReadonlySet<string>;\n}\n\n/**\n * Who is calling: the identity and the request attributes a test accessor set.\n */\nexport interface Caller {\n readonly identity: UserIdentity | null;\n readonly token: string | null;\n readonly ip: string | null;\n readonly userAgent: string | null;\n}\n\nexport const anonymous: Caller = {\n identity: null,\n token: null,\n ip: null,\n userAgent: null,\n};\n\nexport const withIdentity = (\n caller: Caller,\n identity: Partial<UserIdentity>,\n): Caller => {\n const subject = identity.subject ?? \"\" + simpleHash(JSON.stringify(identity));\n const issuer = identity.issuer ?? \"https://convex.test\";\n const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;\n const full = { ...identity, subject, issuer, tokenIdentifier };\n return { ...caller, identity: full, token: createTestJwt(full) };\n};\n\ninterface Request {\n readonly ip: string | null;\n readonly userAgent: string | null;\n readonly requestId: string;\n readonly scheduledFunctionId: string | null;\n readonly authToken: string | null;\n}\n\ntype UdfType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * How a prepared attempt's function ended.\n */\nexport type Outcome =\n | { readonly _tag: \"returned\"; readonly value: Value }\n | { readonly _tag: \"failed\"; readonly error: unknown };\n\n/**\n * A mutation attempt run to its commit point and held until `apply`.\n */\nexport interface HeldAttempt {\n readonly id: string;\n readonly request: string;\n readonly number: Invocation.Attempt;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly outcome: Outcome;\n}\n\n/**\n * What `apply` did with a held attempt. A conflict discards the attempt and\n * holds exactly one next attempt, run against the latest commit. Nothing is\n * retried until that one is applied in turn.\n */\nexport type KernelApply =\n | {\n readonly kind: \"applied\";\n readonly version: Kernel.Version;\n readonly commitTs: bigint;\n readonly result: Value;\n }\n | { readonly kind: \"conflict\"; readonly next: HeldAttempt }\n | {\n readonly kind: \"exhausted\";\n readonly error: KernelRefusal.OptimisticConcurrencyControlFailure;\n }\n | { readonly kind: \"refused\"; readonly tag: string; readonly error: unknown };\n\ninterface Held {\n readonly view: HeldAttempt;\n readonly attempt: KernelAttempt;\n readonly again: (number: Invocation.Attempt) => Promise<Held>;\n}\n\nconst lastAttempt: Invocation.Attempt = 5;\n\nconst tagOf = (error: unknown): string => {\n const tagged = (value: unknown): value is { readonly _tag: string } =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\";\n const data = (error as { data?: unknown } | null)?.data;\n if (tagged(data)) return data._tag;\n if (tagged(error)) return error._tag;\n return error instanceof Error ? error.name : \"Error\";\n};\n\n/**\n * One running function. Queries and mutations read and write through their\n * attempt. Every async syscall of a query or a mutation, nested calls included,\n * takes its turn on `turn` in the order the function made it.\n */\ninterface Execution {\n readonly world: World;\n readonly componentPath: string;\n readonly udfPath: string;\n readonly udfType: UdfType;\n readonly attempt: KernelAttempt | undefined;\n readonly identity: UserIdentity | null;\n readonly request: Request;\n /**\n * The kernel's time when the outermost query or mutation began. Its nested\n * calls share it, and `Date` answers it inside them.\n */\n readonly startTime: number;\n readonly pagination: { calls: number } | undefined;\n readonly turn: Turn;\n}\n\n/**\n * A queue that runs one task at a time, in the order they were taken.\n */\nclass Turn {\n private tail: Promise<unknown> = Promise.resolve();\n\n take<A>(task: () => A | Promise<A>): Promise<A> {\n const result = this.tail.then(task);\n this.tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /**\n * Resolves once every task taken so far has settled, including the tasks\n * taken while waiting.\n */\n idle(): Promise<void> {\n const tail = this.tail;\n return tail.then(() => (this.tail === tail ? undefined : this.idle()));\n }\n}\n\n/**\n * A function's invocation finishes once its handler returned and every syscall\n * it started has run. On the binary a query or mutation keeps running the\n * syscalls in its queue after its promise resolves, then returns (`run_inner`\n * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write\n * still lands in its own transaction.\n */\nconst settled = <A>(execution: Execution, result: A): Promise<A> =>\n execution.turn.idle().then(() => result);\n\nconst executions = new AsyncLocalStorage<Execution>();\n\n/**\n * Run a function's code as `execution`, with its own copy of the globals a test\n * invocation pins.\n */\nconst enter = <A>(execution: Execution, run: () => A): A => {\n installConvexGlobal();\n return Globals.own(() => executions.run(execution, run));\n};\nconst kernelBrand = Symbol.for(\"@confect/test/Kernel\");\n\n/**\n * The time `Date` answers inside a kernel invocation: a query's or mutation's\n * start, or the clock as it runs in an action. Outside one, none.\n */\nconst pinnedTime = (): number | undefined => {\n const execution = executions.getStore();\n if (execution === undefined) return undefined;\n return execution.udfType === \"action\"\n ? execution.world.now()\n : execution.startTime;\n};\n\n/**\n * How many jobs one drain or advance runs before it gives up, as convex-test's\n * `finishAllScheduledFunctions` defaults to.\n */\nconst defaultBudget = 100;\n\nconst current = (): Execution => {\n const execution = executions.getStore();\n if (execution === undefined) {\n throw new Error(\n \"A Convex syscall ran outside any function the test kernel started.\",\n );\n }\n return execution;\n};\n\nlet nextRequestId = 0;\nconst newRequest = (caller: Caller): Request => ({\n ip: caller.ip,\n userAgent: caller.userAgent,\n requestId: `kernel-request-${nextRequestId++}`,\n scheduledFunctionId: null,\n authToken: caller.token,\n});\n\n/**\n * A scheduled call is a request of its own: no caller's attributes, and its\n * job's ID.\n */\nconst jobRequest = (jobId: DocumentId): Request => ({\n ...newRequest(anonymous),\n scheduledFunctionId: jobId,\n});\n\nconst findModulesRoot = (paths: ReadonlyArray<string>): string => {\n const generated = paths.find((path) => path.includes(\"_generated\"));\n if (generated === undefined) {\n throw new Error(\n 'Could not find the \"_generated\" directory, make sure to run ' +\n \"`npx convex dev` or `npx convex codegen`. Make sure your \" +\n '`import.meta.glob` includes the files in the \"_generated\" directory',\n );\n }\n return generated.split(\"_generated\", 2)[0]!;\n};\n\nconst makeComponent = (\n path: string,\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n): Component => {\n const root = findModulesRoot(Object.keys(modules));\n const relative = Object.entries(modules)\n .filter(([key]) => key.startsWith(root))\n .map(([key, load]) => [key.slice(root.length), load] as const);\n const nested = relative\n .map(([file]) => file)\n .filter((file) => file.endsWith(\"/convex.config.ts\"))\n .map((file) => file.slice(0, -\"convex.config.ts\".length));\n return {\n path,\n schema: KernelQuery.exportSchema(schema),\n loaders: new Map(\n relative\n .filter(\n ([file]) =>\n isFunctionModule(file) &&\n !nested.some((dir) => file.startsWith(dir)),\n )\n .map(([file, load]) => [file.replace(/\\.[^.]+$/, \"\"), load]),\n ),\n loaded: new Map(),\n standing: new Set(standing),\n };\n};\n\nconst entryExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".jsx\",\n];\n\n/**\n * Whether Convex's bundler deploys this file as a function module, by the rule\n * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a\n * schema, a config and `_generated` never reach the binary, so the kernel\n * neither loads them nor resolves a function in them.\n */\nconst isFunctionModule = (file: string): boolean => {\n const base = file.split(\"/\").pop()!;\n return (\n entryExtensions.some((extension) => file.endsWith(extension)) &&\n !file.startsWith(\"_generated/\") &&\n !base.startsWith(\".\") &&\n !base.startsWith(\"#\") &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n (base.match(/\\./g) ?? []).length <= 1 &&\n !file.includes(\" \")\n );\n};\n\nconst unregistered = (world: World, componentPath: string) => {\n const registered = [...world.components.keys()].filter((p) => p !== ROOT);\n return new Error(\n `Component \"${componentPath}\" is not registered on this test backend. ` +\n (registered.length === 0\n ? \"No components have been registered.\"\n : `Registered components: ${registered.map((p) => `\"${p}\"`).join(\", \")}.`),\n );\n};\n\ntype FunctionAddress = {\n readonly name?: string | undefined;\n readonly reference?: string | undefined;\n readonly functionHandle?: string | undefined;\n};\n\n/**\n * Where an address points, read from the calling component.\n */\nconst functionPathOf = (\n address: FunctionAddress,\n from: string,\n): FunctionPath => {\n if (address.functionHandle !== undefined) {\n return parseFunctionHandle(address.functionHandle);\n }\n if (address.name !== undefined) {\n return { udfPath: address.name, componentPath: from };\n }\n if (address.reference !== undefined) {\n // \"_reference/childComponent/<child>/path/to/file/fn\"\n const parts = address.reference.split(\"/\");\n const child = parts[2]!;\n const rest = parts.slice(3);\n return {\n componentPath: from.length > 0 ? `${from}/${child}` : child,\n udfPath: `${rest.slice(0, -1).join(\"/\")}:${rest[rest.length - 1]}`,\n };\n }\n throw new Error(\"Function address not supported\");\n};\n\nconst pathOfReference = (\n reference: FunctionReference<any, any, any, any> | string,\n from: string,\n) =>\n functionPathOf(getFunctionAddress(reference as any) as FunctionAddress, from);\n\ninterface Resolved {\n readonly func: any;\n readonly handler: (ctx: any, args: any) => any;\n readonly args: ValidatorJSON;\n readonly returns: ValidatorJSON | null;\n}\n\nconst kindCheck = {\n query: \"isQuery\",\n mutation: \"isMutation\",\n action: \"isAction\",\n} as const;\n\n/**\n * A test backend: its registered components and the kernel state they share.\n */\nexport class World {\n readonly components = new Map<string, Component>();\n state: Kernel.State = Kernel.empty;\n private opened: Promise<void> | undefined;\n private nextDocId = 10000;\n private lastCreationTime = 0;\n private nextQueryId = 1;\n private readonly queries = new Map<number, Iterator<any>>();\n private readonly holding = new Map<string, Held>();\n private nextAttemptId = 1;\n /**\n * The latest deadline time has been advanced to. The clock never reads\n * earlier.\n */\n private floor = Number.NEGATIVE_INFINITY;\n private readonly targets = new Map<DocumentId, Scheduling.Target>();\n\n constructor(\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n private readonly runtime: Kernel.KernelRuntime = Kernel.wallClock(),\n ) {\n installConvexGlobal();\n Clock.install(pinnedTime, () => executions.getStore() !== undefined);\n this.components.set(ROOT, makeComponent(ROOT, schema, modules));\n }\n\n register(\n componentPath: string,\n schema: SchemaDefinition<GenericSchema, boolean>,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n ) {\n if (this.opened !== undefined) {\n throw new KernelRefusal.RegisteredAfterOpen({\n componentPath,\n message: `Component \"${componentPath}\" was registered after the test backend opened. Register every component before the first call.`,\n });\n }\n this.components.set(\n componentPath,\n makeComponent(componentPath, schema, modules, standing),\n );\n }\n\n /**\n * Load every registered module of every component, once, before any function\n * runs, then check that each standing source names an exported function.\n */\n open(): Promise<void> {\n this.opened ??= Promise.all(\n Array.from(this.components.values(), (component) =>\n Promise.all(\n Array.from(component.loaders, ([path, load]) =>\n load().then((module) => component.loaded.set(path, module)),\n ),\n ),\n ),\n ).then(() => this.checkStanding());\n return this.opened;\n }\n\n /**\n * Refuse a standing source no module of its component exports.\n */\n private checkStanding() {\n for (const component of this.components.values()) {\n for (const name of component.standing) {\n const [modulePath, exportName = \"default\"] = name.split(\":\");\n const func = component.loaded.get(modulePath!)?.[exportName];\n if (func?.isMutation !== true && func?.isAction !== true) {\n throw new KernelRefusal.UnknownStandingSource({\n componentPath: component.path,\n name,\n message: `Component \"${component.path}\" declares \"${name}\" standing, but exports no mutation or action by that name. Name the self-rescheduling function as module:export.`,\n });\n }\n }\n }\n }\n\n /**\n * The kernel's time: the runtime's, never earlier than the latest deadline\n * time was advanced to.\n */\n now(): number {\n return Math.max(this.runtime.now(), this.floor);\n }\n\n private component(componentPath: string): Component {\n const component = this.components.get(componentPath);\n if (component === undefined) throw unregistered(this, componentPath);\n return component;\n }\n\n private resolve(functionPath: FunctionPath, kind: UdfType | \"any\"): Resolved {\n const [modulePath, maybeExport] = functionPath.udfPath.split(\":\") as [\n string,\n string | undefined,\n ];\n const exportName = maybeExport ?? \"default\";\n const component = this.component(functionPath.componentPath);\n const module = component.loaded.get(modulePath);\n if (module === undefined) {\n throw new Error(`Could not find module for: \"${modulePath}\"`);\n }\n const func = module[exportName];\n if (func === undefined) {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but there is no such export.`,\n );\n }\n const handler = \"_handler\" in func ? func._handler : func;\n if (typeof handler !== \"function\") {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but got: ${func}`,\n );\n }\n if (kind !== \"any\" && !func[kindCheck[kind]]) {\n throw new Error(\n `Expected a ${kind} function, but the function exported from module \"${modulePath}\" as \\`${exportName}\\` is not a ${kind}.`,\n );\n }\n const args = JSON.parse(func.exportArgs()) as ValidatorJSON;\n if (args.type !== \"object\" && args.type !== \"any\") {\n throw new Error(\n `Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): ` +\n `Args validator must be an object or any`,\n );\n }\n return { func, handler, args, returns: JSON.parse(func.exportReturns()) };\n }\n\n // Calls from the test.\n\n query(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runQuery(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.queryAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n mutation(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runMutation(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.mutationAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n action(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runAction(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.actionAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n run(\n caller: Caller,\n componentPath: string,\n handler: (ctx: any) => any,\n ): Promise<any> {\n return this.open().then(() => {\n this.component(componentPath);\n return this.runMutation(\n { componentPath, udfPath: \"custom\" },\n { handler, args: { type: \"any\" }, returns: null },\n {},\n { caller, request: newRequest(caller) },\n );\n });\n }\n\n // Held attempts.\n\n /**\n * Run a mutation to its commit point and hold it as attempt 1.\n */\n prepare(caller: Caller, reference: any, args: any): Promise<HeldAttempt> {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n 1,\n Invocation.current(),\n ).then((held) => held.view);\n });\n }\n\n apply(id: string): Promise<KernelApply> {\n const held = this.holding.get(id);\n return held === undefined\n ? Promise.reject(\n new KernelRefusal.StaleAttempt({\n id,\n message: `The test kernel holds no attempt \"${id}\". It was already applied, or never prepared.`,\n }),\n )\n : this.applyHeld(held);\n }\n\n /**\n * The held attempts, oldest first.\n */\n held(): ReadonlyArray<HeldAttempt> {\n return Array.from(this.holding.values(), (held) => held.view);\n }\n\n // Scheduled functions, on the kernel's clock.\n\n /**\n * The committed pending jobs, earliest deadline first.\n */\n jobs(): ReadonlyArray<Scheduling.Job> {\n return Scheduling.pending(this.state, this.targets).map(\n ({ id, componentPath, name, scheduledTime, standing }) => ({\n id,\n componentPath,\n name,\n scheduledTime,\n standing,\n }),\n );\n }\n\n /**\n * Move the clock forward `ms`, running every job whose deadline falls on the\n * way, in deadline order, each starting at its deadline. Jobs those jobs\n * schedule inside the window run too. `advance(0)` runs what is due now and\n * crosses no future deadline.\n */\n advance(ms: number, budget = defaultBudget): Promise<void> {\n return this.open().then(() => {\n const until = this.now() + ms;\n return this.walk(\n (pending) => pending.filter((job) => job.scheduledTime <= until),\n budget,\n ).then(() => this.raiseFloor(until));\n });\n }\n\n /**\n * Run jobs, earliest deadline first and each at its deadline, until only\n * standing jobs are pending. Every job run counts against `budget`.\n */\n drain(budget = defaultBudget): Promise<void> {\n return this.open().then(() =>\n this.walk((pending) => pending.filter((job) => !job.standing), budget),\n );\n }\n\n /**\n * Run the first of `select(pending)` until it is empty, moving the clock to\n * each job's deadline as it starts.\n */\n private walk(\n select: (pending: Array<Scheduling.Due>) => Array<Scheduling.Due>,\n budget: number,\n ): Promise<void> {\n const step = (ran: number): Promise<void> => {\n const left = select(Scheduling.pending(this.state, this.targets));\n const next = left[0];\n if (next === undefined) return Promise.resolve();\n if (ran === budget) {\n const pending = Scheduling.functions(left);\n return Promise.reject(\n new KernelRefusal.DrainBudgetExceeded({\n budget,\n pending,\n message: `Scheduled functions ran ${budget} jobs and work remains: ${pending\n .map(({ componentPath, name }) =>\n componentPath === ROOT ? name : `${name} in \"${componentPath}\"`,\n )\n .join(\n \", \",\n )}. A function that schedules its own next run never lets the drain end, so its kit declares it with registerComponent's \\`standing\\` option.`,\n }),\n );\n }\n this.raiseFloor(next.scheduledTime);\n return this.runJob(next).then(() => step(ran + 1));\n };\n return step(0);\n }\n\n private raiseFloor(to: number) {\n this.floor = Math.max(this.floor, to);\n }\n\n /**\n * Run one pending job as its own request, moving its row through in progress\n * to success or failed. `walk` picks it from the committed pending jobs and\n * starts it in the same turn, so no cancel can land in between. The job runs\n * as a fresh invocation of the world that scheduled it, whatever invocation\n * the drain itself runs under.\n */\n private runJob(job: Scheduling.Due): Promise<void> {\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id)!;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state: { kind: \"inProgress\" },\n });\n });\n const request = jobRequest(job.id);\n const from: From = { caller: anonymous, request };\n const run = () =>\n Promise.resolve().then(() => {\n const { func } = this.resolve(job.target, \"any\");\n return func.isQuery\n ? this.queryAt(job.target, job.args, from)\n : func.isMutation\n ? this.mutationAt(job.target, job.args, from)\n : this.actionAt(job.target, job.args, from);\n });\n return (\n job.world === undefined\n ? Invocation.unbound(run)\n : Invocation.bind(\n Invocation.fresh(job.world, job.target.componentPath, request),\n run,\n )\n )\n .then(\n (): Scheduling.JobState => ({ kind: \"success\" }),\n (error: unknown): Scheduling.JobState => ({\n kind: \"failed\",\n error: error instanceof Error ? error.message : String(error),\n }),\n )\n .then((state) =>\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id);\n if (doc === null || Scheduling.stateOf(doc).kind !== \"inProgress\")\n return;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state,\n completedTime: this.now(),\n });\n }),\n );\n }\n\n /**\n * Write through a fresh attempt and publish it at once, as the scheduler does\n * for an action's schedule and a job's state. Nothing runs between the\n * snapshot and the commit, so no other commit can conflict with it.\n */\n private commitNow<A>(write: (attempt: KernelAttempt) => A): A {\n const attempt = new KernelAttempt(this.state);\n const result = write(attempt);\n this.publishWrites(attempt.writes());\n return result;\n }\n\n /**\n * Publish `writes` as the next commit, at the runtime's timestamp for it. No\n * writes publish nothing and ask the runtime for no timestamp, which answers\n * the latest commit's.\n */\n private publishWrites(writes: ReadonlyArray<Kernel.Write>): bigint {\n if (writes.length === 0) return this.state.commitTs;\n const commitTs = this.runtime.commitTs(this.state.version + 1);\n if (commitTs <= this.state.commitTs) {\n throw new KernelRefusal.CommitTsNotIncreasing({\n version: this.state.version + 1,\n previous: this.state.commitTs,\n commitTs,\n 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}.`,\n });\n }\n this.state = Kernel.apply(this.state, writes, commitTs);\n return commitTs;\n }\n\n /**\n * Write a pending job into `attempt`, so the job exists only once that\n * attempt publishes. A job that a standing function schedules, or that runs\n * one, is standing.\n */\n private scheduleJob(\n attempt: KernelAttempt,\n execution: Execution,\n args: any,\n ): DocumentId {\n const target = functionPathOf(args, execution.componentPath);\n this.component(target.componentPath);\n const jobArgs = jsonToConvex(args.args);\n if (hasPendingValues(jobArgs)) {\n throw new Error(\n `Invalid arguments for \"${target.udfPath}\": a scheduled function cannot take an unresolved placeholder value.`,\n );\n }\n const id = this.generateId(Scheduling.table);\n attempt.write(\n execution.componentPath,\n id,\n Scheduling.row(\n id,\n this.creationTime(execution.startTime),\n target.udfPath,\n jobArgs,\n args.ts * 1000,\n ),\n );\n this.targets.set(id, {\n functionPath: target,\n standing:\n this.isStanding({\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n }) || this.isStanding(target),\n world: Invocation.current()?.world,\n });\n return id;\n }\n\n /**\n * Cancel a job that has not finished. A finished job stays as it ended.\n */\n private cancelJob(attempt: KernelAttempt, componentPath: string, id: any) {\n validateId(Scheduling.table, id);\n attempt.readDocument(componentPath, id);\n const doc = attempt.get(componentPath, id);\n if (doc === null) {\n throw new Error(`Patch on non-existent document with ID \"${id}\"`);\n }\n const { kind } = Scheduling.stateOf(doc);\n if (kind === \"pending\" || kind === \"inProgress\") {\n attempt.write(componentPath, id, { ...doc, state: { kind: \"canceled\" } });\n }\n }\n\n private isStanding({ componentPath, udfPath }: FunctionPath): boolean {\n return this.components.get(componentPath)?.standing.has(udfPath) ?? false;\n }\n\n // Calls by address, from the test or from a running function.\n\n private queryAt(\n functionPath: FunctionPath,\n args: any,\n from: From,\n snapshotOnly = false,\n ) {\n const resolved = this.resolve(functionPath, \"query\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runQuery(functionPath, resolved, args, from, snapshotOnly);\n }\n\n private mutationAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runMutation(functionPath, resolved, args, from);\n }\n\n private actionAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"action\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.runAction(functionPath, resolved, args, from);\n }\n\n // Runners.\n\n private execution(\n functionPath: FunctionPath,\n udfType: UdfType,\n attempt: KernelAttempt | undefined,\n from: From,\n pagination: { calls: number } | undefined,\n ): Execution {\n // A function in a component runs with no identity, whoever called it, as\n // Convex gives a component no `ctx.auth` of the caller's. A nested call in\n // the host takes its parent's identity, even when that is none.\n const identity =\n functionPath.componentPath !== ROOT\n ? null\n : from.parent !== undefined\n ? from.parent.identity\n : from.caller.identity;\n return {\n world: this,\n componentPath: functionPath.componentPath,\n udfPath: functionPath.udfPath,\n udfType,\n attempt,\n identity,\n request: from.request,\n startTime:\n from.parent !== undefined && from.parent.udfType !== \"action\"\n ? from.parent.startTime\n : this.now(),\n pagination,\n turn: new Turn(),\n };\n }\n\n private runQuery(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n snapshotOnly = false,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n const isNested = parentAttempt !== undefined;\n const attempt =\n parentAttempt === undefined\n ? new KernelAttempt(this.state)\n : snapshotOnly\n ? new KernelAttempt(parentAttempt.snapshot)\n : parentAttempt;\n const execution = this.execution(\n functionPath,\n \"query\",\n attempt,\n from,\n (isNested && from.parent?.pagination) || { calls: 0 },\n );\n const q = queryGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: queryAuth(execution) }, a),\n }) as unknown as { invokeQuery: (args: string) => Promise<string> };\n return enter(execution, () =>\n q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n if (!isNested && hasPendingValues(result)) {\n throw new Error(\n `Function ${functionPath.udfPath} return value invalid: queries ` +\n `cannot return an unresolved placeholder value.`,\n );\n }\n validateReturnValue(resolved.returns, result, \"query\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n private invokeMutation(\n execution: Execution,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n ): Promise<Value> {\n const m = mutationGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: mutationAuth(execution) }, a),\n }) as unknown as { invokeMutation: (args: string) => Promise<string> };\n return enter(execution, () =>\n m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"mutation\", {\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n });\n return result;\n });\n }\n\n private runMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n if (parentAttempt !== undefined) {\n const frame = parentAttempt.child();\n const execution = this.execution(\n functionPath,\n \"mutation\",\n frame,\n from,\n undefined,\n );\n // As at the top level, a nested mutation ends once its function has\n // returned and every syscall it started has settled. Convex runs a\n // nested function's syscall queue to the end before it commits its\n // subtransaction, so a detached fiber's late write lands in this frame\n // and merges with it. A failed one ends at once and rolls back.\n return this.invokeMutation(execution, resolved, args).then(\n (result) =>\n frame.drained().then(() => {\n frame.close();\n frame.merge();\n return result;\n }),\n (error: unknown) => {\n frame.close();\n throw deserializeConvexErrorData(error);\n },\n );\n }\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n 1,\n Invocation.current(),\n ).then((held) => this.publish(held));\n }\n\n /**\n * Run one attempt of a top-level mutation against the latest commit, then\n * hold it. The commit point is once the function has returned and every\n * syscall it started has settled. A test invocation bound when the mutation\n * was first called reaches each attempt's handler with that attempt's\n * number.\n */\n private prepareMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n from: From,\n number: Invocation.Attempt,\n bound: Invocation.Invocation | undefined,\n ): Promise<Held> {\n const attempt = new KernelAttempt(this.state, number);\n const execution = this.execution(\n functionPath,\n \"mutation\",\n attempt,\n from,\n undefined,\n );\n const run = () => this.invokeMutation(execution, resolved, args);\n const started =\n bound === undefined\n ? run()\n : Invocation.bind({ ...bound, attempt: number }, run);\n return started\n .then(\n (value) =>\n attempt.drained().then((): Outcome => ({ _tag: \"returned\", value })),\n (error: unknown): Outcome => ({\n _tag: \"failed\",\n error: deserializeConvexErrorData(error),\n }),\n )\n .then((outcome) => {\n attempt.close();\n const held: Held = {\n view: {\n id: `attempt-${this.nextAttemptId++}`,\n request: from.request.requestId,\n number,\n snapshot: attempt.snapshot.version,\n reads: attempt.reads,\n outcome,\n },\n attempt,\n again: (next) =>\n this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n next,\n bound,\n ),\n };\n this.holding.set(held.view.id, held);\n return held;\n });\n }\n\n /**\n * Validate a held attempt's reads against every commit since its snapshot,\n * then publish its writes or prepare its next attempt. An attempt that wrote\n * nothing publishes nothing and has nothing to validate. It answers its\n * snapshot's version and commit timestamp.\n */\n private applyHeld({ view, attempt, again }: Held): Promise<KernelApply> {\n this.holding.delete(view.id);\n const { outcome } = view;\n if (outcome._tag === \"failed\") {\n return Promise.resolve({\n kind: \"refused\",\n tag: tagOf(outcome.error),\n error: outcome.error,\n });\n }\n const writes = attempt.writes();\n if (writes.length === 0) {\n // As on the binary, a mutation that wrote nothing is serialized at its\n // snapshot and allocates no timestamp for a later commit.\n const { version, commitTs } = attempt.snapshot;\n return Promise.resolve({\n kind: \"applied\",\n version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n if (\n Kernel.conflict(this.state, view.snapshot, attempt.reads) !== undefined\n ) {\n if (view.number === lastAttempt) {\n return Promise.resolve({\n kind: \"exhausted\",\n error: new KernelRefusal.OptimisticConcurrencyControlFailure({\n attempts: lastAttempt,\n message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`,\n }),\n });\n }\n return again((view.number + 1) as Invocation.Attempt).then(\n (next): KernelApply => ({ kind: \"conflict\", next: next.view }),\n );\n }\n // Validation, publication and the version read share one synchronous turn,\n // so no other commit lands between them.\n let commitTs: bigint;\n try {\n commitTs = this.publishWrites(writes);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve({\n kind: \"applied\",\n version: this.state.version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n\n /**\n * Apply until the mutation publishes, is refused or is exhausted, as the\n * binary retries a mutation that conflicts.\n */\n private publish(held: Held): Promise<Value> {\n return this.applyHeld(held).then((applied) => {\n if (applied.kind === \"applied\") return applied.result;\n if (applied.kind === \"conflict\") {\n return this.publish(this.holding.get(applied.next.id)!);\n }\n throw applied.error;\n });\n }\n\n private runAction(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const execution = this.execution(\n functionPath,\n \"action\",\n undefined,\n from,\n undefined,\n );\n const inner: From = { request: from.request, parent: execution };\n const a = actionGeneric({\n handler: (ctx: any, innerArgs: any) =>\n resolved.handler(\n {\n ...ctx,\n runQuery: (reference: any, queryArgs: any) =>\n this.queryAt(\n pathOfReference(reference, functionPath.componentPath),\n queryArgs,\n inner,\n ),\n runMutation: (reference: any, mutationArgs: any) =>\n this.mutationAt(\n pathOfReference(reference, functionPath.componentPath),\n mutationArgs,\n inner,\n ),\n runAction: (reference: any, actionArgs: any) =>\n this.actionAt(\n pathOfReference(reference, functionPath.componentPath),\n actionArgs,\n inner,\n ),\n auth: queryAuth(execution),\n },\n innerArgs,\n ),\n }) as unknown as {\n invokeAction: (requestId: string, args: string) => Promise<string>;\n };\n const run = () =>\n enter(execution, () =>\n a.invokeAction(\n from.request.requestId,\n JSON.stringify(convexToJson([parseArgs(args)])),\n ),\n );\n // An action another function calls is an invocation of its own, with its\n // world's services, a start time read from its world's clock and its\n // world's random stream, as a scheduled job is.\n const bound = from.parent === undefined ? undefined : Invocation.current();\n const started =\n bound === undefined\n ? run()\n : Invocation.bind(\n Invocation.fresh(\n bound.world,\n functionPath.componentPath,\n from.request,\n ),\n run,\n );\n return started\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"action\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n // Syscalls.\n\n private schema(componentPath: string) {\n return this.component(componentPath).schema;\n }\n\n private view(execution: Execution): KernelQuery.TableView {\n const attempt = transaction(execution);\n return {\n schema: this.schema(execution.componentPath),\n scan: (tableName) => attempt.scan(execution.componentPath, tableName),\n read: (interval, after) =>\n attempt.readInterval({\n ...interval,\n componentPath: execution.componentPath,\n after,\n }),\n };\n }\n\n private generateId(table: string): DocumentId {\n const counter = String(this.nextDocId++).padStart(\n TYPICAL_CONVEX_ID_LENGTH - table.length,\n \"0\",\n );\n return (counter + table) as DocumentId;\n }\n\n syscall(op: string, jsonArgs: string): string {\n const args = JSON.parse(jsonArgs);\n const execution = current();\n if (execution.attempt?.closed === true) throw closed(execution, op);\n switch (op) {\n case \"1.0/getSnapshotTs\":\n return JSON.stringify(\n convexToJson(transaction(execution).snapshot.commitTs),\n );\n case \"1.0/queryStream\": {\n // The binary reads a query at each `1.0/queryStreamNext`, which waits\n // its turn in the queue, so the stream opens at its first read and sees\n // every write made before it.\n const queryId = this.nextQueryId++;\n const view = this.view(execution);\n let results: Iterator<any> | undefined;\n this.queries.set(queryId, {\n next: () => (results ??= KernelQuery.stream(view, args.query)).next(),\n });\n return JSON.stringify({ queryId });\n }\n case \"1.0/queryCleanup\":\n this.queries.delete(args.queryId);\n return JSON.stringify({});\n case \"1.0/db/normalizeId\": {\n const tableName = tableNameFromId(args.idString);\n return JSON.stringify({\n id: tableName === args.table ? args.idString : null,\n });\n }\n default:\n throw new Error(`The test kernel does not support syscall: \"${op}\"`);\n }\n }\n\n /**\n * The binary queues a query's or mutation's async syscalls and runs them one\n * at a time, oldest first (`start_async_syscall` and `run_inner` in\n * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested\n * call never share a batch (`AsyncSyscallBatch::can_push` in\n * `async_syscall.rs`), and a nested call holds the queue until it has\n * committed or rolled back its subtransaction (`run_udf` in\n * `async_syscall.rs`). So a caller's write made after its nested call runs\n * after that call, and a nested mutation sees every write made before it. An\n * action's calls run side by side.\n */\n asyncSyscall(op: string, jsonArgs: string): Promise<string> {\n const execution = current();\n const attempt = execution.attempt;\n if (attempt === undefined) {\n return Promise.resolve().then(() =>\n this.dispatchAsync(op, JSON.parse(jsonArgs), execution),\n );\n }\n if (attempt.closed) return Promise.reject(closed(execution, op));\n // A syscall counts toward its frame's lifetime from the moment it is\n // queued, so a frame never closes with a write still waiting its turn.\n const end = attempt.begin();\n return execution.turn\n .take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution))\n .finally(end);\n }\n\n private dispatchAsync(\n op: string,\n args: any,\n execution: Execution,\n ): string | Promise<string> {\n switch (op) {\n case \"1.0/get\": {\n const { table, id } = args;\n return JSON.stringify(convexToJson(this.get(execution, table, id)));\n }\n case \"1.0/queryStreamNext\": {\n const results = this.queries.get(args.queryId);\n if (results === undefined) throw new Error(\"Bad queryId\");\n const { value, done } = results.next();\n return JSON.stringify(\n convexToJson(\n done ? { value: null, done: true } : { value, done: false },\n ),\n );\n }\n case \"1.0/queryPage\": {\n const pagination = execution.pagination;\n if (pagination) {\n pagination.calls += 1;\n if (pagination.calls > 1) {\n throw new Error(\n \"Only a single paginated query (`.paginate()`) is allowed per \" +\n \"query, including nested query calls and component calls. \" +\n \"This is a Convex limit: https://docs.convex.dev/database/pagination\",\n );\n }\n }\n return JSON.stringify(\n convexToJson(KernelQuery.paginate(this.view(execution), args) as any),\n );\n }\n case \"1.0/insert\":\n return JSON.stringify({\n _id: this.insert(execution, args.table, jsonToConvex(args.value)),\n });\n case \"1.0/shallowMerge\":\n this.patch(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/replace\":\n this.replace(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/remove\":\n this.remove(execution, args.table, args.id);\n return JSON.stringify({});\n case \"1.0/count\": {\n const attempt = transaction(execution);\n attempt.readInterval({\n kind: \"interval\",\n componentPath: execution.componentPath,\n table: args.table,\n fields: [\"_creationTime\", \"_id\"],\n order: \"asc\",\n range: [],\n after: null,\n })(\"end\");\n return JSON.stringify(\n attempt.scan(execution.componentPath, args.table).length,\n );\n }\n case \"1.0/getFunctionMetadata\":\n return JSON.stringify(\n convexToJson({\n name: execution.udfPath,\n componentPath: execution.componentPath,\n }),\n );\n case \"1.0/getRequestMetadata\":\n if (execution.udfType === \"query\") {\n throw new Error(\n \"getRequestMetadata() can only be called from a mutation, action \" +\n \"or HTTP action. It is not available in queries.\",\n );\n }\n return JSON.stringify(convexToJson(execution.request as any));\n case \"1.0/getDeploymentMetadata\":\n return JSON.stringify(\n convexToJson({ name: \"test\", region: null, class: \"s16\" }),\n );\n case \"1.0/actions/query\":\n case \"1.0/actions/mutation\":\n case \"1.0/actions/action\": {\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const run =\n op === \"1.0/actions/query\"\n ? this.queryAt(functionPath, args.args, from)\n : op === \"1.0/actions/mutation\"\n ? this.mutationAt(functionPath, args.args, from)\n : this.actionAt(functionPath, args.args, from);\n return run.then((value) => JSON.stringify(convexToJson(value)));\n }\n case \"1.0/runUdf\": {\n const { udfType, args: udfArgs } = args;\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const value = jsonToConvex(udfArgs);\n const run =\n udfType === \"query\"\n ? this.queryAt(functionPath, value, from)\n : udfType === \"snapshotQuery\"\n ? this.queryAt(functionPath, value, from, true)\n : udfType === \"mutation\"\n ? this.mutationAt(functionPath, value, from)\n : Promise.reject(\n new Error(\n `The test kernel does not support udf type: \"${udfType}\"`,\n ),\n );\n return run.then((result) => JSON.stringify(convexToJson(result)));\n }\n case \"1.0/createFunctionHandle\": {\n const functionPath = functionPathOf(args, execution.componentPath);\n this.component(functionPath.componentPath);\n return JSON.stringify(createFunctionHandle(functionPath));\n }\n case \"1.0/auditLog\":\n return JSON.stringify(null);\n case \"1.0/schedule\":\n return JSON.stringify(\n convexToJson(\n this.scheduleJob(transaction(execution), execution, args),\n ),\n );\n case \"1.0/actions/schedule\":\n return JSON.stringify(\n convexToJson(\n this.commitNow((attempt) =>\n this.scheduleJob(attempt, execution, args),\n ),\n ),\n );\n case \"1.0/cancel_job\":\n this.cancelJob(\n transaction(execution),\n execution.componentPath,\n args.id,\n );\n return JSON.stringify({});\n case \"1.0/actions/cancel_job\":\n this.commitNow((attempt) =>\n this.cancelJob(attempt, execution.componentPath, args.id),\n );\n return JSON.stringify({});\n case \"1.0/storageDelete\":\n case \"1.0/storageGetUrl\":\n case \"1.0/storageGenerateUploadUrl\":\n throw KernelRefusal.rowPending(\"storage\", 6);\n case \"1.0/getTransactionMetrics\":\n throw KernelRefusal.rowPending(\"transaction limits\", 6);\n case \"1.0/actions/vectorSearch\":\n throw KernelRefusal.requiresBinary(\"vectorSearch\");\n default:\n throw new Error(\n `The test kernel does not support async syscall: \"${op}\"`,\n );\n }\n }\n\n jsSyscall(op: string): Promise<never> {\n return Promise.reject(\n op.startsWith(\"storage/\")\n ? KernelRefusal.rowPending(\"storage\", 6)\n : new Error(`The test kernel does not support js syscall: \"${op}\"`),\n );\n }\n\n // Documents. The checks and messages are convex-test's.\n\n private get(execution: Execution, tableName: unknown, id: unknown) {\n validateId(tableName, id);\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n return attempt.get(execution.componentPath, id);\n }\n\n private insert(execution: Execution, table: string, value: any): DocumentId {\n const attempt = transaction(execution);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n table,\n value,\n );\n const _id = this.generateId(table);\n attempt.write(execution.componentPath, _id, {\n ...value,\n _id,\n _creationTime: this.creationTime(execution.startTime),\n });\n return _id;\n }\n\n /**\n * A new document's creation time: `at`, or just past the latest one, so no\n * two documents share one.\n */\n private creationTime(at: number): number {\n const time =\n at <= this.lastCreationTime ? this.lastCreationTime + 0.001 : at;\n this.lastCreationTime = time;\n return time;\n }\n\n private existing(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n write: string,\n value: unknown,\n ): StoredDocument {\n validateId(tableName, id);\n if (value !== undefined && typeof value !== \"object\") {\n throw new Error(\n `Invalid argument \\`value\\` in \\`db.${write}\\`, expected object but got '${typeof value}': ${value as any}`,\n );\n }\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n const document = attempt.get(execution.componentPath, id);\n if (document === null) {\n throw new Error(\n write === \"delete\"\n ? \"Delete on non-existent doc\"\n : `${write === \"patch\" ? \"Patch\" : \"Replace\"} on non-existent document with ID \"${id}\"`,\n );\n }\n return document;\n }\n\n private fields(document: StoredDocument, value: Record<string, any>) {\n if (value._id !== undefined && value._id !== document._id) {\n throw new Error(\n `Provided \\`_id\\` field value \"${value._id}\" ` +\n `does not match the document ID \"${document._id}\"`,\n );\n }\n if (\n value._creationTime !== undefined &&\n value._creationTime !== document._creationTime\n ) {\n throw new Error(\n `Provided \\`_creationTime\\` field value ${value._creationTime} ` +\n `does not match the document's creation time ${document._creationTime}`,\n );\n }\n const convexValue: Record<string, Value | undefined> = {};\n for (const [key, v] of Object.entries(value)) {\n if (key !== \"_id\" && key !== \"_creationTime\") {\n convexValue[key] = evaluateValue(v);\n }\n }\n return convexValue;\n }\n\n private patch(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"patch\", value);\n const { _id, _creationTime, ...fields } = document;\n const merged = { ...fields, ...this.fields(document, value) };\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(_id)!,\n merged,\n );\n transaction(execution).write(execution.componentPath, _id, {\n _id,\n _creationTime,\n ...merged,\n } as StoredDocument);\n }\n\n private replace(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"replace\", value);\n const fields = this.fields(document, value);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(document._id)!,\n fields,\n );\n transaction(execution).write(execution.componentPath, document._id, {\n ...fields,\n _id: document._id,\n _creationTime: document._creationTime,\n } as StoredDocument);\n }\n\n private remove(execution: Execution, tableName: unknown, id: unknown) {\n const document = this.existing(\n execution,\n tableName,\n id,\n \"delete\",\n undefined,\n );\n transaction(execution).write(execution.componentPath, document._id, null);\n }\n}\n\n/**\n * Where a call comes from. A call from the test carries its accessor's caller.\n * A nested call carries its parent execution and takes its identity from it.\n */\ntype From =\n | {\n readonly caller: Caller;\n readonly request: Request;\n readonly parent?: undefined;\n }\n | { readonly parent: Execution; readonly request: Request };\n\nconst closed = (execution: Execution, operation: string) =>\n new KernelRefusal.ClosedAttempt({\n operation,\n message: `\"${operation}\" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`,\n });\n\nconst transaction = (execution: Execution): KernelAttempt => {\n if (execution.attempt === undefined) {\n throw new Error(\n \"The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.\",\n );\n }\n return execution.attempt;\n};\n\nconst queryAuth = (execution: Execution) => ({\n getUserIdentity: () => Promise.resolve(execution.identity),\n});\n\nconst mutationAuth = (execution: Execution) => ({\n ...queryAuth(execution),\n signJwt: () => Promise.reject(KernelRefusal.rowPending(\"JWT signing\", 6)),\n});\n\nfunction validateId(\n expectedTableName: unknown,\n id: unknown,\n): asserts id is DocumentId {\n if (typeof id !== \"string\") {\n throw new Error(\n `Invalid argument \\`id\\`, expected string but got '${typeof id}': ${id as any}`,\n );\n }\n if (expectedTableName === undefined) return;\n if (typeof expectedTableName !== \"string\") {\n throw new Error(\n `Invalid argument \\`tableName\\`, expected string but got '${typeof expectedTableName}': ${expectedTableName as any}`,\n );\n }\n const actualTableName = tableNameFromId(id);\n if (actualTableName === null) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID value but got '${id}'`,\n );\n }\n if (actualTableName !== expectedTableName) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`,\n );\n }\n}\n\ninterface Syscalls {\n readonly syscall: (op: string, args: string) => string;\n readonly asyncSyscall: (op: string, args: string) => Promise<string>;\n readonly jsSyscall: (op: string, args: unknown) => unknown;\n}\n\ntype Branded = { readonly [kernelBrand]?: true };\n\n/**\n * The backend another library installed as `globalThis.Convex`, which answers\n * every syscall made outside a kernel function.\n */\nlet forwarded: Syscalls | undefined;\n\n// With neither, `current` refuses the syscall.\nconst backend = (): Syscalls =>\n executions.getStore()?.world ?? forwarded ?? current().world;\n\nconst dispatcher: Syscalls & Branded = {\n [kernelBrand]: true,\n syscall: (op, args) => backend().syscall(op, args),\n asyncSyscall: (op, args) => backend().asyncSyscall(op, args),\n jsSyscall: (op, args) => backend().jsSyscall(op, args),\n};\n\n/**\n * Convex's server library reaches the backend through `globalThis.Convex`, one\n * global for the whole test runtime. convex-test 0.0.65 assigns its own the\n * first time it builds a world (its `dist/index.js:1936-1951`), whenever that\n * is. The kernel keeps the global an accessor that always reads its dispatcher,\n * and takes an assignment, or the global it found, as the backend for syscalls\n * made outside a kernel function. So a kernel world and a convex-test world\n * stay live together, whichever was built first, and no world restores the\n * global when it ends. A test that redefines the global removes the accessor,\n * so every kernel function installs it again over what the test left.\n */\nconst installConvexGlobal = () => {\n const found = (globalThis as { Convex?: Syscalls & Branded }).Convex;\n if (found?.[kernelBrand] === true) return;\n forwarded = found;\n Object.defineProperty(globalThis, \"Convex\", {\n get: () => dispatcher,\n set: (value: (Syscalls & Branded) | undefined) => {\n if (value?.[kernelBrand] !== true) forwarded = value;\n },\n configurable: true,\n enumerable: true,\n });\n};\n\n/**\n * Whether `globalThis.Convex` is the kernel's, and no other backend installed\n * one behind it.\n */\nexport const ownsConvexGlobal = (): boolean =>\n (globalThis as { Convex?: Branded }).Convex?.[kernelBrand] === true &&\n forwarded === undefined;\n"],"mappings":";;;;;;;;;;;;;AA0CA,MAAM,OAAO;AACb,MAAM,2BAA2B;AA8BjC,MAAa,YAAoB;CAC/B,UAAU;CACV,OAAO;CACP,IAAI;CACJ,WAAW;AACb;AAEA,MAAa,gBACX,QACA,aACW;CACX,MAAM,UAAU,SAAS,WAAW,KAAK,WAAW,KAAK,UAAU,QAAQ,CAAC;CAC5E,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,kBAAkB,SAAS,mBAAmB,GAAG,OAAO,GAAG;CACjE,MAAM,OAAO;EAAE,GAAG;EAAU;EAAS;EAAQ;CAAgB;CAC7D,OAAO;EAAE,GAAG;EAAQ,UAAU;EAAM,OAAO,cAAc,IAAI;CAAE;AACjE;AAwDA,MAAM,cAAkC;AAExC,MAAM,SAAS,UAA2B;CACxC,MAAM,UAAU,UACd,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;CAChD,MAAM,OAAQ,OAAqC;CACnD,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK;CAC9B,IAAI,OAAO,KAAK,GAAG,OAA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BAAkB,gBAAgB,EAAE;CAC1C,IAAI,oBAAoB,MACtB,MAAM,IAAI,MACR,uDAAuD,GAAG,EAC5D;CAEF,IAAI,oBAAoB,mBACtB,MAAM,IAAI,MACR,kDAAkD,kBAAkB,yBAAyB,gBAAgB,EAC/G;AAEJ;;;;;AAcA,IAAI;AAGJ,MAAM,gBACJ,WAAW,SAAS,CAAC,EAAE,SAAS,aAAa,QAAQ,CAAC,CAAC;AAEzD,MAAM,aAAiC;EACpC,cAAc;CACf,UAAU,IAAI,SAAS,QAAQ,CAAC,CAAC,QAAQ,IAAI,IAAI;CACjD,eAAe,IAAI,SAAS,QAAQ,CAAC,CAAC,aAAa,IAAI,IAAI;CAC3D,YAAY,IAAI,SAAS,QAAQ,CAAC,CAAC,UAAU,IAAI,IAAI;AACvD;;;;;;;;;;;;AAaA,MAAM,4BAA4B;CAChC,MAAM,QAAS,WAA+C;CAC9D,IAAI,QAAQ,iBAAiB,MAAM;CACnC,YAAY;CACZ,OAAO,eAAe,YAAY,UAAU;EAC1C,WAAW;EACX,MAAM,UAA4C;GAChD,IAAI,QAAQ,iBAAiB,MAAM,YAAY;EACjD;EACA,cAAc;EACd,YAAY;CACd,CAAC;AACH;;;;;AAMA,MAAa,yBACV,WAAoC,SAAS,iBAAiB,QAC/D,cAAc,KAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Globals.d.ts","sourceRoot":"","sources":["../../src/internal/Globals.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Globals.d.ts","sourceRoot":"","sources":["../../src/internal/Globals.ts"],"names":[],"mappings":"AAkGA;;;GAGG;AACH,eAAO,MAAM,GAAG,GAAI,CAAC,QAAQ,MAAM,CAAC,KAAG,CAItC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,IAAI,GAAI,CAAC,QAAQ,MAAM,CAAC,KAAG,CAA8B,CAAC"}
|
package/dist/internal/Globals.js
CHANGED
|
@@ -19,6 +19,17 @@ const state = () => globalThis[key] ??= {
|
|
|
19
19
|
getters: /* @__PURE__ */ new WeakSet()
|
|
20
20
|
};
|
|
21
21
|
/**
|
|
22
|
+
* Whether `accessor`, another library's, already reads through one of this
|
|
23
|
+
* module's, as convex-test's does once it wraps the kernel's: it answers a
|
|
24
|
+
* value only a fresh copy holds. convex-test reinstalls its accessor whenever
|
|
25
|
+
* another is on top (its `dist/index.js:1854-1866`), so wrapping it again would
|
|
26
|
+
* add a layer at every call while both kinds of world are live.
|
|
27
|
+
*/
|
|
28
|
+
const readsThrough = (copies, accessor, name) => {
|
|
29
|
+
const probe = {};
|
|
30
|
+
return copies.run({ [name]: probe }, () => accessor.get?.call(globalThis)) === probe;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
22
33
|
* Point each global at the calling function's copy, falling back to the
|
|
23
34
|
* global's own value outside one. A test that redefines a global, as
|
|
24
35
|
* `vi.stubGlobal` does, removes the accessor, so every call installs it again
|
|
@@ -29,6 +40,7 @@ const install = ({ copies, getters }) => {
|
|
|
29
40
|
for (const name of names) {
|
|
30
41
|
const own = Object.getOwnPropertyDescriptor(global, name);
|
|
31
42
|
if (own?.get !== void 0 && getters.has(own.get)) continue;
|
|
43
|
+
if (own?.get !== void 0 && readsThrough(copies, own, name)) continue;
|
|
32
44
|
const base = own ?? {
|
|
33
45
|
value: void 0,
|
|
34
46
|
writable: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Globals.js","names":[],"sources":["../../src/internal/Globals.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Convex gives every function execution its own globals. The kernel gives each\n * function call it starts its own copy of the globals a test invocation pins,\n * as convex-test 0.0.65 does for every handler (its `dist/index.js:1744`,\n * `:1883-1905` and `:1927-1930`). An assignment inside the call lands in its\n * copy only, so the invocation bridge's pins stay with the handler that made\n * them, and overlapping or nested calls keep their own.\n */\n\nconst names = [\"Date\", \"Math\", \"crypto\"] as const;\n\ntype Name = (typeof names)[number];\n\ntype Copies = { [name in Name]?: unknown };\n\ninterface State {\n readonly copies: AsyncLocalStorage<Copies>;\n /**\n * The getters this module installed, so a later install skips them.\n */\n readonly getters: WeakSet<() => unknown>;\n}\n\nconst key = Symbol.for(\"@confect/test/Globals\");\n\n// One store per test runtime, so every copy of this module reads the same\n// copies.\nconst state = (): State =>\n ((globalThis as { [key]?: State })[key] ??= {\n copies: new AsyncLocalStorage(),\n getters: new WeakSet(),\n });\n\n/**\n * Point each global at the calling function's copy, falling back to the\n * global's own value outside one. A test that redefines a global, as\n * `vi.stubGlobal` does, removes the accessor, so every call installs it again\n * over what the test left.\n */\nconst install = ({ copies, getters }: State) => {\n const global = globalThis as unknown as Record<Name, unknown>;\n for (const name of names) {\n const own = Object.getOwnPropertyDescriptor(global, name);\n // oxlint-disable-next-line typescript/unbound-method -- Compared by identity, never called.\n if (own?.get !== undefined && getters.has(own.get)) continue;\n const base: PropertyDescriptor = own ?? {\n value: undefined,\n writable: true,\n };\n const get = () => {\n const copy = copies.getStore();\n if (copy !== undefined && name in copy) return copy[name];\n return \"value\" in base ? base.value : base.get?.call(global);\n };\n const set = (value: unknown) => {\n const copy = copies.getStore();\n if (copy !== undefined) copy[name] = value;\n else if (\"value\" in base && base.writable === true) base.value = value;\n else if (base.set !== undefined) base.set.call(global, value);\n else throw new TypeError(`Cannot assign to read only global '${name}'`);\n };\n try {\n Object.defineProperty(global, name, {\n get,\n set,\n configurable: true,\n enumerable: own?.enumerable ?? false,\n });\n getters.add(get);\n } catch {\n // A global that cannot be redefined keeps no copy, and the bridge\n // refuses to pin it.\n }\n }\n};\n\n/**\n * Run `call` with a fresh copy of the globals. It starts from the test\n * environment's, whatever the caller assigned in its own copy.\n */\nexport const own = <A>(call: () => A): A => {\n const current = state();\n install(current);\n return current.copies.run({}, call);\n};\n\n/**\n * Read `read` against the test environment's globals, never a function call's\n * copy, as the kernel's own clock must.\n */\nexport const host = <A>(read: () => A): A => state().copies.exit(read);\n"],"mappings":";;;;;;;;;;AAWA,MAAM,QAAQ;CAAC;CAAQ;CAAQ;AAAQ;AAcvC,MAAM,MAAM,OAAO,IAAI,uBAAuB;AAI9C,MAAM,cACH,WAAkC,SAAS;CAC1C,QAAQ,IAAI,kBAAkB;CAC9B,yBAAS,IAAI,QAAQ;AACvB;;;;;;;
|
|
1
|
+
{"version":3,"file":"Globals.js","names":[],"sources":["../../src/internal/Globals.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * Convex gives every function execution its own globals. The kernel gives each\n * function call it starts its own copy of the globals a test invocation pins,\n * as convex-test 0.0.65 does for every handler (its `dist/index.js:1744`,\n * `:1883-1905` and `:1927-1930`). An assignment inside the call lands in its\n * copy only, so the invocation bridge's pins stay with the handler that made\n * them, and overlapping or nested calls keep their own.\n */\n\nconst names = [\"Date\", \"Math\", \"crypto\"] as const;\n\ntype Name = (typeof names)[number];\n\ntype Copies = { [name in Name]?: unknown };\n\ninterface State {\n readonly copies: AsyncLocalStorage<Copies>;\n /**\n * The getters this module installed, so a later install skips them.\n */\n readonly getters: WeakSet<() => unknown>;\n}\n\nconst key = Symbol.for(\"@confect/test/Globals\");\n\n// One store per test runtime, so every copy of this module reads the same\n// copies.\nconst state = (): State =>\n ((globalThis as { [key]?: State })[key] ??= {\n copies: new AsyncLocalStorage(),\n getters: new WeakSet(),\n });\n\n/**\n * Whether `accessor`, another library's, already reads through one of this\n * module's, as convex-test's does once it wraps the kernel's: it answers a\n * value only a fresh copy holds. convex-test reinstalls its accessor whenever\n * another is on top (its `dist/index.js:1854-1866`), so wrapping it again would\n * add a layer at every call while both kinds of world are live.\n */\nconst readsThrough = (\n copies: State[\"copies\"],\n accessor: PropertyDescriptor,\n name: Name,\n): boolean => {\n const probe = {};\n return (\n copies.run({ [name]: probe }, () => accessor.get?.call(globalThis)) ===\n probe\n );\n};\n\n/**\n * Point each global at the calling function's copy, falling back to the\n * global's own value outside one. A test that redefines a global, as\n * `vi.stubGlobal` does, removes the accessor, so every call installs it again\n * over what the test left.\n */\nconst install = ({ copies, getters }: State) => {\n const global = globalThis as unknown as Record<Name, unknown>;\n for (const name of names) {\n const own = Object.getOwnPropertyDescriptor(global, name);\n // oxlint-disable-next-line typescript/unbound-method -- Compared by identity, never called.\n if (own?.get !== undefined && getters.has(own.get)) continue;\n if (own?.get !== undefined && readsThrough(copies, own, name)) continue;\n const base: PropertyDescriptor = own ?? {\n value: undefined,\n writable: true,\n };\n const get = () => {\n const copy = copies.getStore();\n if (copy !== undefined && name in copy) return copy[name];\n return \"value\" in base ? base.value : base.get?.call(global);\n };\n const set = (value: unknown) => {\n const copy = copies.getStore();\n if (copy !== undefined) copy[name] = value;\n else if (\"value\" in base && base.writable === true) base.value = value;\n else if (base.set !== undefined) base.set.call(global, value);\n else throw new TypeError(`Cannot assign to read only global '${name}'`);\n };\n try {\n Object.defineProperty(global, name, {\n get,\n set,\n configurable: true,\n enumerable: own?.enumerable ?? false,\n });\n getters.add(get);\n } catch {\n // A global that cannot be redefined keeps no copy, and the bridge\n // refuses to pin it.\n }\n }\n};\n\n/**\n * Run `call` with a fresh copy of the globals. It starts from the test\n * environment's, whatever the caller assigned in its own copy.\n */\nexport const own = <A>(call: () => A): A => {\n const current = state();\n install(current);\n return current.copies.run({}, call);\n};\n\n/**\n * Read `read` against the test environment's globals, never a function call's\n * copy, as the kernel's own clock must.\n */\nexport const host = <A>(read: () => A): A => state().copies.exit(read);\n"],"mappings":";;;;;;;;;;AAWA,MAAM,QAAQ;CAAC;CAAQ;CAAQ;AAAQ;AAcvC,MAAM,MAAM,OAAO,IAAI,uBAAuB;AAI9C,MAAM,cACH,WAAkC,SAAS;CAC1C,QAAQ,IAAI,kBAAkB;CAC9B,yBAAS,IAAI,QAAQ;AACvB;;;;;;;;AASF,MAAM,gBACJ,QACA,UACA,SACY;CACZ,MAAM,QAAQ,CAAC;CACf,OACE,OAAO,IAAI,GAAG,OAAO,MAAM,SAAS,SAAS,KAAK,KAAK,UAAU,CAAC,MAClE;A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
|
|
47
|
+
/**
|
|
48
|
+
* A fresh invocation of `world` for a request of its own, as an action or a
|
|
49
|
+
* scheduled job starts: attempt 1, the world's services and random stream, and
|
|
50
|
+
* a start time read from the world's clock.
|
|
51
|
+
*/
|
|
52
|
+
export declare const fresh: (world: World, componentPath: string, { ip, userAgent, requestId, scheduledFunctionId }: Invocation["request"]) => Invocation;
|
|
47
53
|
/**
|
|
48
54
|
* Run `start` with `invocation` bound. Every registered handler it reaches
|
|
49
55
|
* through convex-test runs with the invocation's services, clock and random
|
|
50
56
|
* stream.
|
|
51
57
|
*/
|
|
52
58
|
export declare const bind: <A>(invocation: Invocation, start: () => Promise<A>) => Promise<A>;
|
|
59
|
+
/**
|
|
60
|
+
* Run `start` with no invocation bound, so every registered handler it reaches
|
|
61
|
+
* keeps its production runtime, whatever the caller has bound.
|
|
62
|
+
*/
|
|
63
|
+
export declare const unbound: <A>(start: () => Promise<A>) => Promise<A>;
|
|
53
64
|
/**
|
|
54
65
|
* The invocation the calling handler runs under, if one is bound.
|
|
55
66
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Invocation.d.ts","sourceRoot":"","sources":["../../src/internal/Invocation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,eAAe,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,KAAK,OAAO,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"Invocation.d.ts","sourceRoot":"","sources":["../../src/internal/Invocation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,eAAe,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAG/C;;GAEG;AACH,MAAM,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAExC;;;GAGG;AACH,MAAM,WAAW,KAAK;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAA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|
const key = Symbol.for("@confect/test/Invocation");
|
|
4
5
|
/**
|
|
6
|
+
* A fresh invocation of `world` for a request of its own, as an action or a
|
|
7
|
+
* scheduled job starts: attempt 1, the world's services and random stream, and
|
|
8
|
+
* a start time read from the world's clock.
|
|
9
|
+
*/
|
|
10
|
+
const fresh = (world, componentPath, { ip, userAgent, requestId, scheduledFunctionId }) => ({
|
|
11
|
+
world,
|
|
12
|
+
componentPath,
|
|
13
|
+
attempt: 1,
|
|
14
|
+
request: {
|
|
15
|
+
ip,
|
|
16
|
+
userAgent,
|
|
17
|
+
requestId,
|
|
18
|
+
scheduledFunctionId
|
|
19
|
+
},
|
|
20
|
+
services: world.services,
|
|
21
|
+
startedAt: world.clock(),
|
|
22
|
+
random: world.random
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
5
25
|
* The invocation a function of `functionType` called from `running` joins. A
|
|
6
26
|
* query or mutation an action calls is a transaction of its own, so it starts
|
|
7
27
|
* at the world's time when it begins. Any other call shares its caller's
|
|
@@ -19,23 +39,7 @@ const caller = (running, functionType) => running.functionType === "action" && f
|
|
|
19
39
|
* random stream.
|
|
20
40
|
*/
|
|
21
41
|
const resolve = (bound, componentPath, request) => {
|
|
22
|
-
if (request !== void 0 && request.scheduledFunctionId !== bound.request.scheduledFunctionId)
|
|
23
|
-
const { ip, userAgent, requestId, scheduledFunctionId } = request;
|
|
24
|
-
return {
|
|
25
|
-
world: bound.world,
|
|
26
|
-
componentPath,
|
|
27
|
-
attempt: 1,
|
|
28
|
-
request: {
|
|
29
|
-
ip,
|
|
30
|
-
userAgent,
|
|
31
|
-
requestId,
|
|
32
|
-
scheduledFunctionId
|
|
33
|
-
},
|
|
34
|
-
services: bound.world.services,
|
|
35
|
-
startedAt: bound.world.clock(),
|
|
36
|
-
random: bound.world.random
|
|
37
|
-
};
|
|
38
|
-
}
|
|
42
|
+
if (request !== void 0 && request.scheduledFunctionId !== bound.request.scheduledFunctionId) return fresh(bound.world, componentPath, request);
|
|
39
43
|
return componentPath === bound.componentPath ? bound : {
|
|
40
44
|
...bound,
|
|
41
45
|
componentPath
|
|
@@ -85,18 +89,19 @@ const pin = (invocation, functionType, outside) => {
|
|
|
85
89
|
Math: host.Math,
|
|
86
90
|
crypto: host.crypto
|
|
87
91
|
};
|
|
92
|
+
const kernelDate = answersInvocation(previous.Date);
|
|
88
93
|
const pinned = {
|
|
89
|
-
Date: pinnedDate(previous.Date, clockOf(invocation, functionType)),
|
|
94
|
+
Date: kernelDate ? previous.Date : pinnedDate(previous.Date, clockOf(invocation, functionType)),
|
|
90
95
|
Math: drawingMath(previous.Math, invocation.random),
|
|
91
96
|
crypto: drawingCrypto(previous.crypto, invocation.random)
|
|
92
97
|
};
|
|
93
98
|
try {
|
|
94
|
-
host.Date = pinned.Date;
|
|
99
|
+
if (!kernelDate) host.Date = pinned.Date;
|
|
95
100
|
host.Math = pinned.Math;
|
|
96
101
|
host.crypto = pinned.crypto;
|
|
97
102
|
} catch {}
|
|
98
103
|
const reached = outside(() => ({
|
|
99
|
-
Date: host.Date === pinned.Date,
|
|
104
|
+
Date: !kernelDate && host.Date === pinned.Date,
|
|
100
105
|
Math: host.Math === pinned.Math,
|
|
101
106
|
crypto: host.crypto === pinned.crypto
|
|
102
107
|
}));
|
|
@@ -136,10 +141,18 @@ const bind = (invocation, start) => (installed[key] ??= make()).storage.run({
|
|
|
136
141
|
functionType: void 0
|
|
137
142
|
}, start);
|
|
138
143
|
/**
|
|
144
|
+
* Run `start` with no invocation bound, so every registered handler it reaches
|
|
145
|
+
* keeps its production runtime, whatever the caller has bound.
|
|
146
|
+
*/
|
|
147
|
+
const unbound = (start) => {
|
|
148
|
+
const bridge = installed[key];
|
|
149
|
+
return bridge === void 0 ? start() : bridge.storage.exit(start);
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
139
152
|
* The invocation the calling handler runs under, if one is bound.
|
|
140
153
|
*/
|
|
141
154
|
const current = () => installed[key]?.storage.getStore()?.invocation;
|
|
142
155
|
//#endregion
|
|
143
|
-
export { bind, current };
|
|
156
|
+
export { bind, current, fresh, unbound };
|
|
144
157
|
|
|
145
158
|
//# sourceMappingURL=Invocation.js.map
|