feat: move email sending into background jobs for retry support

Each direct mailer.sendMail() call is replaced by a dedicated background
job so that email delivery failures can be retried independently.

New jobs: send-pending-email, send-completed-email, send-forgot-password-email,
send-document-super-delete-email, send-recipient-removed-email,
send-document-deleted-emails, send-2fa-token-email, send-resend-document-email,
send-direct-template-created-email.

Existing handlers (send-document-cancelled-emails, send-organisation-member-*,
send-recipient-signed-email) have io.runTask wrappers removed since they
interfere with the job scheduler. Job triggers are dispatched after
transactions commit to avoid race conditions with uncommitted data.
This commit is contained in:
Lucas Smith
2026-02-20 23:25:37 +11:00
parent 653ab3678a
commit 844af17ec2
28 changed files with 1080 additions and 441 deletions
@@ -1,5 +1,4 @@
import { adminSuperDeleteDocument } from '@documenso/lib/server-only/admin/admin-super-delete-document';
import { sendDeleteEmail } from '@documenso/lib/server-only/document/send-delete-email';
import { adminProcedure } from '../trpc';
import {
@@ -19,10 +18,9 @@ export const deleteDocumentRoute = adminProcedure
},
});
await sendDeleteEmail({ envelopeId: id, reason });
await adminSuperDeleteDocument({
envelopeId: id,
reason,
requestMetadata: ctx.metadata.requestMetadata,
});
});
@@ -2,8 +2,8 @@ import { EnvelopeType } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { DateTime } from 'luxon';
import { jobs } from '@documenso/lib/jobs/client';
import { TWO_FACTOR_EMAIL_EXPIRATION_MINUTES } from '@documenso/lib/server-only/2fa/email/constants';
import { send2FATokenEmail } from '@documenso/lib/server-only/2fa/email/send-2fa-token-email';
import { assertRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limit-middleware';
import { request2FAEmailRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limits';
import { DocumentAuth } from '@documenso/lib/types/document-auth';
@@ -30,8 +30,6 @@ export const accessAuthRequest2FAEmailRoute = procedure
assertRateLimit(rateLimitResult);
const user = ctx.user;
// Get document and recipient by token
const envelope = await prisma.envelope.findFirst({
where: {
@@ -72,18 +70,14 @@ export const accessAuthRequest2FAEmailRoute = procedure
});
}
// if (user && recipient.email !== user.email) {
// throw new TRPCError({
// code: 'UNAUTHORIZED',
// message: 'User does not match recipient',
// });
// }
const expiresAt = DateTime.now().plus({ minutes: TWO_FACTOR_EMAIL_EXPIRATION_MINUTES });
await send2FATokenEmail({
token,
envelopeId: envelope.id,
await jobs.triggerJob({
name: 'send.2fa.token.email',
payload: {
envelopeId: envelope.id,
recipientId: recipient.id,
},
});
return {