|
1 | 1 | import { IS_CLOUD } from "@dokploy/server"; |
2 | | -import { db } from "@dokploy/server/db"; |
| 2 | +import { db, dbUrl } from "@dokploy/server/db"; |
3 | 3 | import TrialExpiringEmail from "@dokploy/server/emails/emails/trial-expiring"; |
4 | 4 | import { sendEmail } from "@dokploy/server/verification/send-verification-email"; |
5 | 5 | import { render } from "@react-email/components"; |
6 | 6 | import { format } from "date-fns"; |
7 | 7 | import { eq } from "drizzle-orm"; |
8 | 8 | import { scheduleJob } from "node-schedule"; |
| 9 | +import postgres from "postgres"; |
9 | 10 | import type Stripe from "stripe"; |
10 | 11 | import { user } from "@/server/db/schema"; |
11 | 12 | import { getStripeClient, planFromPriceIds } from "@/server/utils/billing"; |
12 | 13 | import { WEBSITE_URL } from "@/server/utils/stripe"; |
13 | 14 |
|
14 | 15 | const REMINDER_THRESHOLDS = [ |
15 | | - { days: 3, metadataKey: "trialReminder3Sent" }, |
16 | 16 | { days: 1, metadataKey: "trialReminder1Sent" }, |
17 | 17 | ] as const; |
18 | 18 |
|
| 19 | +// Cloud runs several replicas and node-schedule fires on each one, so without |
| 20 | +// this every trial user would get one email per replica. Advisory locks live |
| 21 | +// in the connection rather than the schema, so no migration is needed. |
| 22 | +const ADVISORY_LOCK_KEY = 4820260918; |
| 23 | + |
| 24 | +const withAdvisoryLock = async <T>(run: () => Promise<T>) => { |
| 25 | + const sql = postgres(dbUrl, { max: 1 }); |
| 26 | + try { |
| 27 | + const [row] = |
| 28 | + await sql`select pg_try_advisory_lock(${ADVISORY_LOCK_KEY}) as locked`; |
| 29 | + if (!row?.locked) return null; |
| 30 | + try { |
| 31 | + return await run(); |
| 32 | + } finally { |
| 33 | + await sql`select pg_advisory_unlock(${ADVISORY_LOCK_KEY})`; |
| 34 | + } |
| 35 | + } finally { |
| 36 | + await sql.end({ timeout: 5 }); |
| 37 | + } |
| 38 | +}; |
| 39 | + |
19 | 40 | const PLAN_LABELS: Record<string, string> = { |
20 | 41 | hobby: "Hobby", |
21 | 42 | startup: "Startup", |
@@ -148,7 +169,14 @@ export const initTrialNotificationsCronJob = () => { |
148 | 169 |
|
149 | 170 | scheduleJob("trial-expiration-reminders", "0 14 * * *", async () => { |
150 | 171 | try { |
151 | | - await processTrialExpirations(); |
| 172 | + const result = await withAdvisoryLock(processTrialExpirations); |
| 173 | + if (!result) { |
| 174 | + console.log("Trial reminders: another replica holds the lock"); |
| 175 | + return; |
| 176 | + } |
| 177 | + console.log( |
| 178 | + `Trial reminders: scanned ${result.scanned}, sent ${result.sent}`, |
| 179 | + ); |
152 | 180 | } catch (error) { |
153 | 181 | console.error( |
154 | 182 | "Trial reminder job failed:", |
|
0 commit comments