Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/convex-150-parity.md
Original file line number Diff line number Diff line change
@@ -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.
85 changes: 85 additions & 0 deletions convex/futureReferences.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof fixture.api.refs.empty>,
null
> = fixture.api.refs.empty;
expectTypeOf(t.query(query, { value: 1 })).toEqualTypeOf<Promise<number>>();
expectTypeOf(t.mutation(mutation, { value: 2 })).toEqualTypeOf<
Promise<number>
>();
expectTypeOf(t.action(action, { value: 3 })).toEqualTypeOf<Promise<number>>();
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<Promise<string>>();
});

// Typechecking must reject the same invalid calls for both reference forms.
function invalidCalls(
t: ReturnType<typeof fixture.createTest>,
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;
224 changes: 224 additions & 0 deletions convex/selfCancellation.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("convex")>()),
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();
}
},
);
73 changes: 73 additions & 0 deletions convex/services.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
2 changes: 1 addition & 1 deletion convex/signJwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
},
});

Expand Down
Loading
Loading