-
Notifications
You must be signed in to change notification settings - Fork 188
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
add email queue to handle email sending failures #1587
Open
mahendraHegde
wants to merge
1
commit into
main
Choose a base branch
from
email-queue
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { transporter } from "~/emails/transporter.server"; | ||
import { QueueNames, scheduler } from "~/utils/scheduler.server"; | ||
import type { EmailPayloadType } from "./types"; | ||
import { SMTP_FROM } from "../utils/env"; | ||
import { ShelfError } from "../utils/error"; | ||
|
||
export const registerEmailWorkers = async () => { | ||
await scheduler.work<EmailPayloadType>( | ||
QueueNames.emailQueue, | ||
{ newJobCheckIntervalSeconds: 60 * 3, teamSize: 2 }, | ||
async (job) => { | ||
await triggerEmail(job.data); | ||
} | ||
); | ||
}; | ||
|
||
export const triggerEmail = async ({ | ||
to, | ||
subject, | ||
text, | ||
html, | ||
from, | ||
replyTo, | ||
}: EmailPayloadType) => { | ||
try { | ||
// send mail with defined transport object | ||
await transporter.sendMail({ | ||
from: from || SMTP_FROM || `"Shelf" <[email protected]>`, // sender address | ||
replyTo: replyTo || "[email protected]", // reply to | ||
to, // list of receivers | ||
subject, // Subject line | ||
text, // plain text body | ||
html: html || "", // html body | ||
}); | ||
} catch (cause) { | ||
throw new ShelfError({ | ||
cause, | ||
message: "Unable to send email", | ||
additionalData: { to, subject, from }, | ||
label: "Email", | ||
}); | ||
} | ||
|
||
// verify connection configuration | ||
// transporter.verify(function (error) { | ||
// if (error) { | ||
// // eslint-disable-next-line no-console | ||
// console.log(error); | ||
// } else { | ||
// // eslint-disable-next-line no-console | ||
// console.log("Server is ready to take our messages"); | ||
// } | ||
// }); | ||
|
||
// Message sent: <[email protected]> | ||
|
||
// Preview only available when sending through an Ethereal account | ||
// console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,104 +1,39 @@ | ||
import type { Attachment } from "nodemailer/lib/mailer"; | ||
import { transporter } from "~/emails/transporter.server"; | ||
import { SMTP_FROM } from "../utils/env"; | ||
import { ShelfError } from "../utils/error"; | ||
|
||
export const sendEmail = async ({ | ||
to, | ||
subject, | ||
text, | ||
html, | ||
attachments, | ||
from, | ||
replyTo, | ||
}: { | ||
/** Email address of recipient */ | ||
to: string; | ||
|
||
/** Subject of email */ | ||
subject: string; | ||
|
||
/** Text content of email */ | ||
text: string; | ||
|
||
/** HTML content of email */ | ||
html?: string; | ||
|
||
attachments?: Attachment[]; | ||
|
||
/** Override the default sender */ | ||
from?: string; | ||
import { Logger } from "~/utils/logger"; | ||
import { QueueNames, scheduler } from "~/utils/scheduler.server"; | ||
import { triggerEmail } from "./email.worker.server"; | ||
import type { EmailPayloadType } from "./types"; | ||
|
||
export const sendEmail = (payload: EmailPayloadType) => { | ||
// attempt to send email, push to the queue if it fails | ||
triggerEmail(payload).catch((err) => { | ||
Logger.warn({ | ||
err, | ||
details: { | ||
to: payload.to, | ||
subject: payload.subject, | ||
from: payload.from, | ||
}, | ||
message: "email sending failed, pushing to the queue", | ||
}); | ||
void addToQueue(payload); | ||
}); | ||
}; | ||
|
||
/** Override the default reply to email address */ | ||
replyTo?: string; | ||
}) => { | ||
const addToQueue = async (payload: EmailPayloadType) => { | ||
try { | ||
// send mail with defined transport object | ||
await transporter.sendMail({ | ||
from: from || SMTP_FROM || `"Shelf" <[email protected]>`, // sender address | ||
replyTo: replyTo || "[email protected]", // reply to | ||
to, // list of receivers | ||
subject, // Subject line | ||
text, // plain text body | ||
html: html || "", // html body | ||
attachments: [...(attachments || [])], | ||
await scheduler.send(QueueNames.emailQueue, payload, { | ||
retryLimit: 5, | ||
retryDelay: 5, | ||
}); | ||
} catch (cause) { | ||
throw new ShelfError({ | ||
cause, | ||
message: "Unable to send email", | ||
additionalData: { to, subject, from }, | ||
label: "Email", | ||
} catch (err) { | ||
Logger.warn({ | ||
err, | ||
details: { | ||
to: payload.to, | ||
subject: payload.subject, | ||
from: payload.from, | ||
}, | ||
message: "Failed to push email payload to queue", | ||
}); | ||
} | ||
|
||
// verify connection configuration | ||
// transporter.verify(function (error) { | ||
// if (error) { | ||
// // eslint-disable-next-line no-console | ||
// console.log(error); | ||
// } else { | ||
// // eslint-disable-next-line no-console | ||
// console.log("Server is ready to take our messages"); | ||
// } | ||
// }); | ||
|
||
// Message sent: <[email protected]> | ||
|
||
// Preview only available when sending through an Ethereal account | ||
// console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); | ||
}; | ||
|
||
/** Utility function to add delay between operations */ | ||
async function delay(ms: number): Promise<void> { | ||
return new Promise((resolve) => setTimeout(resolve, ms)); | ||
} | ||
|
||
/** Process emails in batches with rate limiting | ||
* @param emails - Array of email configurations to send | ||
* @param batchSize - Number of emails to process per batch (default: 2) | ||
* @param delayMs - Milliseconds to wait between batches (default: 1000ms) | ||
*/ | ||
export async function sendEmailsWithRateLimit( | ||
emails: Array<{ | ||
to: string; | ||
subject: string; | ||
text: string; | ||
html: string; | ||
}>, | ||
batchSize = 2, | ||
delayMs = 1100 | ||
): Promise<void> { | ||
for (let i = 0; i < emails.length; i += batchSize) { | ||
// Process emails in batches of specified size | ||
const batch = emails.slice(i, i + batchSize); | ||
|
||
// Send emails in current batch concurrently | ||
await Promise.all(batch.map((email) => sendEmail(email))); | ||
|
||
// If there are more emails to process, add delay before next batch | ||
if (i + batchSize < emails.length) { | ||
await delay(delayMs); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we dont
await
, so users dont have to wait for long running email api calls.