diff --git a/.changeset/convex-150-parity.md b/.changeset/convex-150-parity.md new file mode 100644 index 0000000..716c7d1 --- /dev/null +++ b/.changeset/convex-150-parity.md @@ -0,0 +1,5 @@ +--- +"convex-test": patch +--- + +Match version-dependent scheduled mutation self-cancellation: Convex 1.50+ throws and rolls back uncaught failures, while older versions warn and ignore the cancellation. Accept future function references using Convex’s exported types and signature helpers. This requires Convex 1.46.0 or newer; the peer dependency is now `^1.46.0`. Support action and HTTP action service token/URL syscalls with an unsigned test JWT and a reserved `.test` URL. diff --git a/convex/futureReferences.test.ts b/convex/futureReferences.test.ts new file mode 100644 index 0000000..861712a --- /dev/null +++ b/convex/futureReferences.test.ts @@ -0,0 +1,85 @@ +import type { FunctionReference_future, FunctionArgs } from "convex/server"; +import { expect, expectTypeOf, test } from "vitest"; +import { defineTestApp } from "../index"; +import schema from "./schema"; +import { v } from "convex/values"; + +const app = defineTestApp({ schema }); +const fixture = app.defineModules({ + refs: { + query: app.query({ + args: { value: v.number() }, + returns: v.number(), + handler: async (_, { value }) => value, + }), + mutation: app.internalMutation({ + args: { value: v.number() }, + returns: v.number(), + handler: async (_, { value }) => value, + }), + action: app.action({ + args: { value: v.number() }, + returns: v.number(), + handler: async (_, { value }) => value, + }), + empty: app.query({ + args: {}, + returns: v.null(), + handler: async () => null, + }), + }, +}); + +test("future references preserve arguments, visibility, and results", async () => { + const t = fixture.createTest(); + const query: FunctionReference_future< + "query", + "public", + { value: number }, + number + > = fixture.api.refs.query; + const mutation: FunctionReference_future< + "mutation", + "internal", + { value: number }, + number + > = fixture.internal.refs.mutation; + const action: FunctionReference_future< + "action", + "public", + { value: number }, + number + > = fixture.api.refs.action; + const empty: FunctionReference_future< + "query", + "public", + FunctionArgs, + null + > = fixture.api.refs.empty; + expectTypeOf(t.query(query, { value: 1 })).toEqualTypeOf>(); + expectTypeOf(t.mutation(mutation, { value: 2 })).toEqualTypeOf< + Promise + >(); + expectTypeOf(t.action(action, { value: 3 })).toEqualTypeOf>(); + expect(await t.query(query, { value: 1 })).toBe(1); + expect(await t.mutation(mutation, { value: 2 })).toBe(2); + expect(await t.action(action, { value: 3 })).toBe(3); + expect(await t.query(empty)).toBeNull(); + expectTypeOf(t.query(async () => "inline")).toEqualTypeOf>(); +}); + +// Typechecking must reject the same invalid calls for both reference forms. +function invalidCalls( + t: ReturnType, + query: FunctionReference_future<"query", "public", { value: number }, number>, +) { + // @ts-expect-error Required arguments cannot be omitted. + void t.query(query); + // @ts-expect-error Wrong argument type. + void t.query(query, { value: "bad" }); + // @ts-expect-error Extra arguments are rejected. + void t.query(query, { value: 1, extra: true }); + // @ts-expect-error A query cannot be called as a mutation. + void t.mutation(query, { value: 1 }); +} +void invalidCalls; diff --git a/convex/selfCancellation.test.ts b/convex/selfCancellation.test.ts new file mode 100644 index 0000000..0bc02cd --- /dev/null +++ b/convex/selfCancellation.test.ts @@ -0,0 +1,224 @@ +import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import { anyApi, componentsGeneric } from "convex/server"; +import { v, type GenericId } from "convex/values"; +import { defineTestApp } from "../index"; +import schema from "./schema"; + +const runtime = vi.hoisted(() => ({ version: "1.50.0" })); +vi.mock("convex", async (importOriginal) => ({ + ...(await importOriginal()), + get version() { + return runtime.version; + }, +})); + +const app = defineTestApp({ schema }); +const modules = { + selfCancel: { + cancel: app.internalMutation({ + args: { id: v.id("_scheduled_functions") }, + returns: v.null(), + handler: async (ctx, { id }) => { + await ctx.scheduler.cancel(id); + return null; + }, + }), + run: app.internalMutation({ + args: { + caught: v.boolean(), + nested: v.boolean(), + component: v.optional(v.boolean()), + }, + returns: v.null(), + handler: async (ctx, { caught, nested, component }) => { + await ctx.db.insert("messages", { + author: "test", + body: "before cancel", + }); + await ctx.scheduler.runAfter(60_000, anyApi.selfCancel.cancel, { + id: (await ctx.meta.getRequestMetadata()).scheduledFunctionId!, + }); + const id = (await ctx.meta.getRequestMetadata()).scheduledFunctionId!; + try { + if (component) { + await ctx.runMutation(componentsGeneric().child.selfCancel.cancel, { + id, + }); + } else if (nested) { + await ctx.runMutation(anyApi.selfCancel.cancel, { id }); + } else { + await ctx.scheduler.cancel(id as GenericId<"_scheduled_functions">); + } + } catch (error) { + if (!caught) throw error; + await ctx.db.insert("messages", { + author: "test", + body: (error as Error).message, + }); + } + return null; + }, + }), + action: app.internalAction({ + args: { nested: v.optional(v.boolean()) }, + returns: v.null(), + handler: async (ctx, { nested }) => { + const id = (await ctx.meta.getRequestMetadata()).scheduledFunctionId!; + if (nested) { + await ctx.runMutation(anyApi.selfCancel.cancel, { id }); + } else { + await ctx.scheduler.cancel(id as GenericId<"_scheduled_functions">); + } + return null; + }, + }), + }, +}; +const fixture = app.defineModules(modules); + +beforeEach(() => { + runtime.version = "1.50.0"; + vi.useFakeTimers(); +}); +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +async function runSelfCancel( + caught = false, + nested = false, + component = false, +) { + const t = fixture.createTest(); + t.registerComponent("child", schema, { + "./_generated/server.ts": async () => ({}), + "./selfCancel.ts": async () => modules.selfCancel, + }); + const id = await t.mutation(async (ctx) => + ctx.scheduler.runAfter(0, fixture.internal.selfCancel.run, { + caught, + nested, + component, + }), + ); + vi.runAllTimers(); + await t.finishInProgressScheduledFunctions(); + const job = await t.query(async (ctx) => ctx.db.system.get(id)); + const messages = await t.query(async (ctx) => + ctx.db.query("messages").take(10), + ); + return { t, job, messages }; +} + +test.each([false, true])( + "uncaught self-cancel rolls back (nested=%s)", + async (nested) => { + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const { t, job, messages } = await runSelfCancel(false, nested); + expect(job?.state.kind).toBe("failed"); + expect(messages).toEqual([]); + expect( + await t.query(async (ctx) => + ctx.db.system.query("_scheduled_functions").take(10), + ), + ).toHaveLength(1); + expect(errors).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + message: expect.stringContaining("ScheduledFunctionCancelingItself"), + }), + ); + }, +); + +test.each([false, true])( + "caught self-cancel can commit (nested=%s)", + async (nested) => { + const { job, messages } = await runSelfCancel(true, nested); + expect(job?.state.kind).toBe("success"); + expect(messages.map((m) => m.body)).toEqual([ + "before cancel", + "ScheduledFunctionCancelingItself: A mutation cannot cancel itself", + ]); + }, +); + +test.each(["1.43.0", "1.49.0"])( + "%s warns and ignores self-cancellation", + async (version) => { + runtime.version = version; + const warnings = vi.spyOn(console, "warn").mockImplementation(() => {}); + const { job, messages } = await runSelfCancel(); + expect(job?.state.kind).toBe("success"); + expect(messages).toHaveLength(1); + expect(warnings).toHaveBeenCalledWith( + expect.stringContaining("deprecated"), + ); + }, +); + +test.each(["1.50.0", "1.50.1", "1.51.0", "2.0.0", "2.1.0"])( + "%s rejects self-cancellation", + async (version) => { + runtime.version = version; + vi.spyOn(console, "error").mockImplementation(() => {}); + expect((await runSelfCancel()).job?.state.kind).toBe("failed"); + }, +); + +test("scheduled actions can cancel themselves", async () => { + const t = fixture.createTest(); + const id = await t.mutation(async (ctx) => + ctx.scheduler.runAfter(0, fixture.internal.selfCancel.action, {}), + ); + vi.runAllTimers(); + await t.finishInProgressScheduledFunctions(); + expect( + (await t.query(async (ctx) => ctx.db.system.get(id)))?.state.kind, + ).toBe("canceled"); +}); + +test("a child component cannot cancel its parent scheduled mutation", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { job, messages } = await runSelfCancel(false, false, true); + expect(job?.state.kind).toBe("failed"); + expect(messages).toEqual([]); +}); + +test.each([ + { version: "1.49.0", state: "success" }, + { version: "1.50.0", state: "failed" }, +])( + "a mutation called by a scheduled action follows $version cancellation behavior", + async ({ version, state }) => { + runtime.version = version; + const warnings = vi.spyOn(console, "warn").mockImplementation(() => {}); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const t = fixture.createTest(); + const id = await t.mutation(async (ctx) => + ctx.scheduler.runAfter(0, fixture.internal.selfCancel.action, { + nested: true, + }), + ); + vi.runAllTimers(); + await t.finishInProgressScheduledFunctions(); + expect( + (await t.query(async (ctx) => ctx.db.system.get(id)))?.state.kind, + ).toBe(state); + if (state === "success") { + expect(warnings).toHaveBeenCalledWith( + expect.stringContaining("deprecated"), + ); + expect(errors).not.toHaveBeenCalled(); + } else { + expect(errors).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + message: expect.stringContaining("ScheduledFunctionCancelingItself"), + }), + ); + expect(warnings).not.toHaveBeenCalled(); + } + }, +); diff --git a/convex/services.test.ts b/convex/services.test.ts new file mode 100644 index 0000000..06c66bb --- /dev/null +++ b/convex/services.test.ts @@ -0,0 +1,73 @@ +import { decodeJwt, decodeProtectedHeader } from "jose"; +import { + getServiceToken, + getServiceUrl, + httpActionGeneric, + httpRouter, +} from "convex/server"; +import { afterEach, expect, test, vi } from "vitest"; +import { convexTest } from "../index"; +import schema from "./schema"; + +afterEach(() => { + vi.useRealTimers(); +}); + +test("actions receive a test URL and a short-lived test JWT", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-11-12T00:00:00Z")); + const t = convexTest(schema); + const { url, token } = await t.action(async () => ({ + url: await getServiceUrl("ai-gateway"), + token: await getServiceToken("ai-gateway"), + })); + expect(url).toBe("https://ai-gateway.convex.test"); + expect(decodeProtectedHeader(token)).toEqual({ alg: "none", typ: "JWT" }); + expect(decodeJwt(token)).toEqual({ + iss: "convex-test", + aud: "ai-gateway", + iat: 1794441600, + exp: 1794441900, + }); + expect(token.endsWith(".")).toBe(true); +}); + +test.each([getServiceToken, getServiceUrl])( + "service syscalls reject queries, mutations, and unsupported services", + async (helper) => { + const t = convexTest(schema); + await expect(t.query(async () => helper("ai-gateway"))).rejects.toThrow( + "Unknown async operation", + ); + await expect(t.mutation(async () => helper("ai-gateway"))).rejects.toThrow( + "Unknown async operation", + ); + await expect( + t.action(async () => helper("unknown" as "ai-gateway")), + ).rejects.toThrow("Unsupported Convex service: unknown"); + }, +); + +test("HTTP actions can use service helpers", async () => { + const router = httpRouter(); + router.route({ + path: "/service", + method: "GET", + handler: httpActionGeneric( + async () => + new Response( + JSON.stringify({ + url: await getServiceUrl("ai-gateway"), + token: await getServiceToken("ai-gateway"), + }), + ), + ), + }); + const t = convexTest(schema, { + "./_generated/server.ts": async () => ({}), + "./http.ts": async () => ({ default: router }), + }); + const result = await (await t.fetch("/service")).json(); + expect(result.url).toBe("https://ai-gateway.convex.test"); + expect(decodeJwt(result.token).aud).toBe("ai-gateway"); +}); diff --git a/convex/signJwt.ts b/convex/signJwt.ts index 9e6e88d..7479fa7 100644 --- a/convex/signJwt.ts +++ b/convex/signJwt.ts @@ -16,7 +16,7 @@ export const sign = mutation({ args: { claims: v.optional(v.any()), expiresInSeconds: v.number() }, returns: v.string(), handler: async (ctx, args) => { - return await ctx.auth.signJwt(args); + return await ctx.auth.signJwt({ ...args, claims: args.claims }); }, }); diff --git a/index.ts b/index.ts index f5c7a88..2657371 100644 --- a/index.ts +++ b/index.ts @@ -1,6 +1,7 @@ /// import { AsyncLocalStorage } from "node:async_hooks"; +import { version } from "convex"; import { ActionBuilder, ApiFromModules, @@ -9,6 +10,7 @@ import { DocumentByName, FilterApi, FunctionReference, + FunctionReference_future, FunctionReturnType, GenericActionCtx, GenericDataModel, @@ -1888,6 +1890,9 @@ async function runScheduledFunction({ } await withAuth().runInComponent(componentPath, async () => { const job = db.get("_scheduled_functions", jobId) as ScheduledFunction; + if (job.state.kind === "canceled") { + return; + } if (job.state.kind !== "inProgress") { throw new Error( `\`convexTest\` invariant error: Unexpected scheduled function state after it finished running: ${job.state.kind}`, @@ -2213,8 +2218,16 @@ function asyncSyscallImpl() { return JSON.stringify(convexToJson(jobId)); } case "1.0/actions/cancel_job": { + // TODO: Match the remaining backend cancellation semantics: tasks + // scheduled after cancellation, including through nested calls, should + // start canceled. A canceled action should stay canceled if it later + // throws, and canceling a terminal job should leave its state unchanged. await withAuth().run(async () => { - await getSyscalls().asyncSyscall("1.0/cancel_job", jsonArgs); + // Actions may cancel their own job; only mutation cancellation + // checks the scheduled request ID. + db.patch("_scheduled_functions", args.id, { + state: { kind: "canceled" }, + }); }); return JSON.stringify({}); } @@ -2234,6 +2247,19 @@ function asyncSyscallImpl() { } case "1.0/cancel_job": { const { id } = args; + if (requestMetadataStorage.getStore()?.scheduledFunctionId === id) { + // The backend gates this on the function's installed Convex version. + const [major, minor] = version.split(".").map(Number); + if (major > 1 || (major === 1 && minor >= 50)) { + throw new Error( + "ScheduledFunctionCancelingItself: A mutation cannot cancel itself", + ); + } + console.warn( + "A scheduled mutation canceling itself is deprecated and will throw an error in a future version of Convex.", + ); + return JSON.stringify(null); + } db.patch("_scheduled_functions", id, { state: { kind: "canceled" } }); return JSON.stringify({}); } @@ -2329,6 +2355,35 @@ function asyncSyscallImpl() { case "1.0/auditLog": { return JSON.stringify(null); } + case "1.0/createServiceToken": + case "1.0/getServiceUrl": { + const udfType = executionContextStorage.getStore()?.udfType; + if (udfType !== "action" && udfType !== "http") { + throw new Error(`Unknown async operation ${op}`); + } + const { service } = args; + if (service !== "ai-gateway") { + throw new Error(`Unsupported Convex service: ${String(service)}`); + } + if (op === "1.0/getServiceUrl") { + return JSON.stringify("https://ai-gateway.convex.test"); + } + // An unsecured, short-lived test credential cannot authenticate to a + // real service. The reserved .test URL above avoids production endpoints. + const iat = Math.floor(Date.now() / 1000); + const header = base64UrlEncode( + JSON.stringify({ alg: "none", typ: "JWT" }), + ); + const payload = base64UrlEncode( + JSON.stringify({ + iss: "convex-test", + aud: service, + iat, + exp: iat + 300, + }), + ); + return JSON.stringify(`${header}.${payload}.`); + } case "1.0/signJwt": { // Signing reads the current time, which query caching could serve // stale, so the backend only allows it in mutations. Actions don't @@ -2620,14 +2675,17 @@ export type TestConvexForDataModel = { query: < QueryOrFunc extends | FunctionReference<"query", any> + | FunctionReference_future<"query", any> | ((ctx: GenericQueryCtx) => Promise), >( queryOrFunc: QueryOrFunc, - ...args: QueryOrFunc extends FunctionReference<"query", any> + ...args: QueryOrFunc extends + FunctionReference<"query", any> | FunctionReference_future<"query", any> ? OptionalRestArgs : [] ) => Promise< - QueryOrFunc extends FunctionReference<"query", any> + QueryOrFunc extends + FunctionReference<"query", any> | FunctionReference_future<"query", any> ? FunctionReturnType : QueryOrFunc extends (ctx: any) => Promise ? Output @@ -2646,14 +2704,19 @@ export type TestConvexForDataModel = { mutation: < MutationOrFunc extends | FunctionReference<"mutation", any> + | FunctionReference_future<"mutation", any> | ((ctx: GenericMutationCtx) => Promise), >( mutationOrFunc: MutationOrFunc, - ...args: MutationOrFunc extends FunctionReference<"mutation", any> + ...args: MutationOrFunc extends + | FunctionReference<"mutation", any> + | FunctionReference_future<"mutation", any> ? OptionalRestArgs : [] ) => Promise< - MutationOrFunc extends FunctionReference<"mutation", any> + MutationOrFunc extends + | FunctionReference<"mutation", any> + | FunctionReference_future<"mutation", any> ? FunctionReturnType : MutationOrFunc extends (ctx: any) => Promise ? Output @@ -2672,14 +2735,17 @@ export type TestConvexForDataModel = { action: < ActionOrFunc extends | FunctionReference<"action", any> + | FunctionReference_future<"action", any> | ((ctx: GenericActionCtx) => Promise), >( actionOrFunc: ActionOrFunc, - ...args: ActionOrFunc extends FunctionReference<"action", any> + ...args: ActionOrFunc extends + FunctionReference<"action", any> | FunctionReference_future<"action", any> ? OptionalRestArgs : [] ) => Promise< - ActionOrFunc extends FunctionReference<"action", any> + ActionOrFunc extends + FunctionReference<"action", any> | FunctionReference_future<"action", any> ? FunctionReturnType : ActionOrFunc extends (ctx: any) => Promise ? Output diff --git a/package-lock.json b/package-lock.json index e32275c..97ecdb9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "convex-test", - "version": "0.0.70", + "version": "0.0.71", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "convex-test", - "version": "0.0.70", + "version": "0.0.71", "license": "Apache-2.0", "devDependencies": { "@changesets/cli": "3.0.3", @@ -17,7 +17,7 @@ "@typescript-eslint/eslint-plugin": "8.72.2", "@typescript-eslint/parser": "8.72.2", "@vitest/coverage-v8": "1.6.1", - "convex": "1.49.0", + "convex": "1.50.0", "eslint": "10.14.0", "globals": "17.14.0", "jose": "6.2.12", @@ -28,7 +28,7 @@ "vitest": "1.6.1" }, "peerDependencies": { - "convex": "^1.43.0" + "convex": "^1.46.0" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -2227,9 +2227,9 @@ "license": "MIT" }, "node_modules/convex": { - "version": "1.49.0", - "resolved": "https://registry.npmjs.org/convex/-/convex-1.49.0.tgz", - "integrity": "sha512-mkr9oXF8/arkCI1kvYyGytWd62oVXNABh4uwLeI4UQVN6Zuudm4DlmSzNUJKF63djk6f/uUXC+6ffuVSkPLvzA==", + "version": "1.50.0", + "resolved": "https://registry.npmjs.org/convex/-/convex-1.50.0.tgz", + "integrity": "sha512-WzzCad5hyzU4zzW0ChyUGB3Mil4LgRYMYii9cyQtC24WQnfaRgkZB0IKyhIIgRm1a2IXiGJoZnVYYSfttiap3Q==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -6224,9 +6224,9 @@ "dev": true }, "convex": { - "version": "1.49.0", - "resolved": "https://registry.npmjs.org/convex/-/convex-1.49.0.tgz", - "integrity": "sha512-mkr9oXF8/arkCI1kvYyGytWd62oVXNABh4uwLeI4UQVN6Zuudm4DlmSzNUJKF63djk6f/uUXC+6ffuVSkPLvzA==", + "version": "1.50.0", + "resolved": "https://registry.npmjs.org/convex/-/convex-1.50.0.tgz", + "integrity": "sha512-WzzCad5hyzU4zzW0ChyUGB3Mil4LgRYMYii9cyQtC24WQnfaRgkZB0IKyhIIgRm1a2IXiGJoZnVYYSfttiap3Q==", "dev": true, "requires": { "esbuild": "0.27.0", diff --git a/package.json b/package.json index 472136d..187845c 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "author": "Sarah Shader & Michal Srb ", "license": "Apache-2.0", "peerDependencies": { - "convex": "^1.43.0" + "convex": "^1.46.0" }, "devDependencies": { "@changesets/cli": "3.0.3", @@ -46,7 +46,7 @@ "@typescript-eslint/eslint-plugin": "8.72.2", "@typescript-eslint/parser": "8.72.2", "@vitest/coverage-v8": "1.6.1", - "convex": "1.49.0", + "convex": "1.50.0", "eslint": "10.14.0", "globals": "17.14.0", "jose": "6.2.12",