Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nice error on nested triggers #348

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions packages/convex-helpers/server/triggers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,20 @@ export const createUser = mutation({
},
});

export const incorrectMutationCallingOtherMutation = mutation({
args: { firstName: v.string(), lastName: v.string() },
handler: async (ctx, args) => {
// createUser is a mutation so you aren't supposed to call it like this.
// But if you happen to do it anyway, we should throw an informative error.
const id = await createUser(ctx, args);
return id;
},
});

const testApi: ApiFromModules<{
fns: {
createUser: typeof createUser;
incorrectMutationCallingOtherMutation: typeof incorrectMutationCallingOtherMutation;
};
}>["fns"] = anyApi["triggers.test"] as any;

Expand All @@ -65,3 +76,20 @@ test("trigger denormalizes field", async () => {
expect(user!.fullName).toStrictEqual("John Doe");
});
});

test("incorrect mutation calling other mutation", async () => {
const t = convexTest(schema, modules);
await expect(t.mutation(testApi.incorrectMutationCallingOtherMutation, {
firstName: "John",
lastName: "Doe",
}),
).rejects.toThrow(
new RegExp(
`Triggers\\.wrapDB called multiple times in a single mutation\\.\\s+` +
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I'd be less aggressive on the regex because I find it annoying to have to update the test whenever the error message changes. Maybe just checking the first sentence + checking a link to docs shows up in there somewhere?

`Not allowed due to potential deadlock\\.\\s+` +
`Call it once in a single \`customMutation\`\\.\\s+` +
`Do not call mutations directly as functions\\.\\s+` +
`See https:\\/\\/docs\\.convex\\.dev\\/production\\/best-practices\\/#use-helper-functions-to-write-shared-code`,
),
);
});
10 changes: 10 additions & 0 deletions packages/convex-helpers/server/triggers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ export class Triggers<
}

wrapDB = <C extends Ctx>(ctx: C): C => {
if (wrapDBCalled) {
throw new Error(
`Triggers.wrapDB called multiple times in a single mutation. Not allowed due to potential deadlock.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could merit a specific example of what this looks like, maybe just in the triggers docs? And we could link to it from the error message?

Like

Troubleshooting: Triggers.wrapDB called multiple times in a single mutation

This usually happens if a mutation is directly calling another mutation, for instance:

export const joinTeam = mutation(...)

export const createTeam = mutation({
	handler: (ctx) => {
		const currentUserId = // load from auth
		const team = await ctx.db.insert("teams", { creatorId: currentUserId, ... })
		// ❌ This creates a new `Triggers` since it's calling another mutation
		await joinTeam({ teamId })
	}
})

See for the recommended pattern.

Call it once in a single \`customMutation\`.
Do not call mutations directly as functions.
See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code`,
);
}
wrapDBCalled = true;
return { ...ctx, db: new DatabaseWriterWithTriggers(ctx, ctx.db, this) };
};
}
Expand Down Expand Up @@ -148,6 +157,7 @@ class Lock {
let innerWriteLock = new Lock();
let outerWriteLock = new Lock();
const triggerQueue: (() => Promise<void>)[] = [];
let wrapDBCalled = false;

export class DatabaseWriterWithTriggers<
DataModel extends GenericDataModel,
Expand Down