Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(billing): throttle trial reminders so they cannot exhaust the quota

Andrejc4150a89f826
diff --git a/apps/api/src/scheduler/trial-reminders.ts b/apps/api/src/scheduler/trial-reminders.ts
index 371c54c36..8b9e21252 100644
--- a/apps/api/src/scheduler/trial-reminders.ts
+++ b/apps/api/src/scheduler/trial-reminders.ts
@@ -1,5 +1,5 @@
import { isSmtpConfigured, sendTrialReminderEmail } from "@kaneo/email";
-import { and, eq, gt, isNotNull, isNull, lte } from "drizzle-orm";
+import { and, asc, eq, gt, isNotNull, isNull, lte } from "drizzle-orm";
import { isBillingEnabled } from "../billing/config";
import db from "../database";
import {
@@ -12,6 +12,24 @@ import {
const DAY_MS = 24 * 60 * 60 * 1000;
+// Sending is deliberately slow. The provider rate-limits per second and per
+// day, and a burst that trips either is silently dropped downstream: SMTP has
+// already accepted the message, so nothing surfaces as an error here.
+const DEFAULT_MAX_PER_RUN = 25;
+const SEND_SPACING_MS = 600;
+
+function maxPerRun() {
+ const parsed = Number.parseInt(
+ process.env.BILLING_REMINDER_MAX_PER_RUN ?? "",
+ 10,
+ );
+ return Number.isNaN(parsed) || parsed <= 0 ? DEFAULT_MAX_PER_RUN : parsed;
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
type ReminderType = "trial_ending" | "trial_expired";
const REMINDERS: {
@@ -89,7 +107,8 @@ async function getWorkspacesNeedingReminder(type: ReminderType, now: Date) {
eq(userTable.banned, false),
),
)
- .limit(500);
+ .orderBy(asc(workspaceBillingTable.trialEndsAt))
+ .limit(maxPerRun());
}
export async function checkTrialReminders(): Promise<void> {
@@ -98,6 +117,7 @@ export async function checkTrialReminders(): Promise<void> {
}
const now = new Date();
+ let sent = 0;
for (const reminder of REMINDERS) {
let rows: Awaited<ReturnType<typeof getWorkspacesNeedingReminder>>;
@@ -139,6 +159,10 @@ export async function checkTrialReminders(): Promise<void> {
Math.ceil((row.trialEndsAt.getTime() - now.getTime()) / DAY_MS),
);
+ if (sent > 0) {
+ await sleep(SEND_SPACING_MS);
+ }
+
await sendTrialReminderEmail(
row.email,
reminder.subject(row.workspaceName),
@@ -148,6 +172,11 @@ export async function checkTrialReminders(): Promise<void> {
billingUrl: `${clientUrl()}/dashboard/settings/workspace/billing`,
},
);
+ sent++;
}
}
+
+ if (sent > 0) {
+ console.log(`Sent ${sent} trial reminder email(s)`);
+ }
}
diff --git a/tests/api-integration/trial-reminders.test.ts b/tests/api-integration/trial-reminders.test.ts
index 102c9fb4e..eb0890312 100644
--- a/tests/api-integration/trial-reminders.test.ts
+++ b/tests/api-integration/trial-reminders.test.ts
@@ -33,6 +33,7 @@ const CLOUD_ENV = {
CREEM_WEBHOOK_SECRET: "whsec_dummy",
SMTP_HOST: "smtp.example.com",
SMTP_FROM: "[email protected]",
+ BILLING_REMINDER_MAX_PER_RUN: "2",
};
const saved: Record<string, string | undefined> = {};
@@ -150,4 +151,24 @@ describe("trial reminder emails", () => {
expect(rows).toHaveLength(1);
expect(rows[0]?.reminderType).toBe("trial_expired");
});
+
+ it("caps how many it sends per run so the provider is not flooded", async () => {
+ for (let i = 0; i < 5; i++) {
+ await seedTrial(new Date(Date.now() - (i + 1) * DAY));
+ }
+
+ await checkTrialReminders();
+
+ expect(sendTrialReminderEmail).toHaveBeenCalledTimes(2);
+ });
+
+ it("sends the most urgent trials first", async () => {
+ const soonest = await seedTrial(new Date(Date.now() - 9 * DAY));
+ await seedTrial(new Date(Date.now() - 2 * DAY));
+ await seedTrial(new Date(Date.now() - 1 * DAY));
+
+ await checkTrialReminders();
+
+ expect(recipients()[0]).toBe(soonest.user.email);
+ });
});