|
| 1 | +import type { |
| 2 | + SignupConversionJob, |
| 3 | + SignupConversionPage, |
| 4 | + SignupConversionsController, |
| 5 | + SignupConversionsPlugin, |
| 6 | + SignupConversionUser, |
| 7 | +} from "@trigger.dev/plugins"; |
| 8 | +import { z } from "zod"; |
| 9 | +import { logger } from "~/services/logger.server"; |
| 10 | +import { singleton } from "~/utils/singleton"; |
| 11 | + |
| 12 | +const MODULE_NAME = "@triggerdotdev/plugins/signup-conversions"; |
| 13 | + |
| 14 | +type MaybeController = Promise<SignupConversionsController | null>; |
| 15 | + |
| 16 | +/** |
| 17 | + * Loads the plugin. Null when it isn't installed (self-hosted). With REQUIRE_PLUGINS=1 a plugin |
| 18 | + * that doesn't load throws; the page path catches it. |
| 19 | + */ |
| 20 | +export async function loadSignupConversionsController({ |
| 21 | + requirePlugins, |
| 22 | + moduleName = MODULE_NAME, |
| 23 | +}: { |
| 24 | + requirePlugins: boolean; |
| 25 | + moduleName?: string; |
| 26 | +}): Promise<SignupConversionsController | null> { |
| 27 | + try { |
| 28 | + const plugin = ( |
| 29 | + (await import(/* @vite-ignore */ moduleName)) as { default: SignupConversionsPlugin } |
| 30 | + ).default; |
| 31 | + return plugin.create(); |
| 32 | + } catch (error) { |
| 33 | + const message = error instanceof Error ? error.message : String(error); |
| 34 | + if (requirePlugins) { |
| 35 | + throw new Error(`REQUIRE_PLUGINS=1 but plugin "${moduleName}" did not load: ${message}`, { |
| 36 | + cause: error, |
| 37 | + }); |
| 38 | + } |
| 39 | + return null; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// Lazy, so tests that pass a controller never load the startup config. |
| 44 | +function getController(): MaybeController { |
| 45 | + return singleton("signupConversionsController", async () => { |
| 46 | + const { env } = await import("~/env.server"); |
| 47 | + return loadSignupConversionsController({ requirePlugins: env.REQUIRE_PLUGINS === "1" }); |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); |
| 52 | + |
| 53 | +// A slow queue must never hold up a sign-up page. |
| 54 | +const ENQUEUE_TIMEOUT_MS = 2_000; |
| 55 | + |
| 56 | +function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> { |
| 57 | + let timer: ReturnType<typeof setTimeout> | undefined; |
| 58 | + const timeout = new Promise<never>((_, reject) => { |
| 59 | + timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms); |
| 60 | + }); |
| 61 | + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Asks the plugin what to do on a sign-up page and queues its conversions, each on its own: one |
| 66 | + * failing never blocks another. Returns the cookies of the jobs that were queued. Never throws: a |
| 67 | + * missing or broken plugin means no conversion, never a broken page. |
| 68 | + */ |
| 69 | +export async function signupConversionsForPage( |
| 70 | + request: Request, |
| 71 | + user: SignupConversionUser, |
| 72 | + { |
| 73 | + controller, |
| 74 | + enqueue = enqueueSignupConversionJob, |
| 75 | + enqueueTimeoutMs = ENQUEUE_TIMEOUT_MS, |
| 76 | + }: { |
| 77 | + controller?: MaybeController; |
| 78 | + enqueue?: (job: SignupConversionJob) => Promise<void>; |
| 79 | + enqueueTimeoutMs?: number; |
| 80 | + } = {} |
| 81 | +): Promise<{ setCookies: string[] }> { |
| 82 | + let page: SignupConversionPage; |
| 83 | + try { |
| 84 | + const plugin = await (controller ?? getController()); |
| 85 | + if (!plugin) return { setCookies: [] }; |
| 86 | + page = await plugin.onSignupPage({ request, user }); |
| 87 | + if (!Array.isArray(page?.jobs)) throw new Error("plugin returned no jobs array"); |
| 88 | + } catch (error) { |
| 89 | + logger.error("Sign-up conversions failed on a sign-up page", { error: errorMessage(error) }); |
| 90 | + return { setCookies: [] }; |
| 91 | + } |
| 92 | + |
| 93 | + // Queued together, so the page waits at most one deadline however many jobs there are. |
| 94 | + const results = await Promise.allSettled( |
| 95 | + page.jobs.map((job) => withTimeout(enqueue(job), enqueueTimeoutMs)) |
| 96 | + ); |
| 97 | + const setCookies: string[] = []; |
| 98 | + results.forEach((result, index) => { |
| 99 | + const job = page.jobs[index]!; |
| 100 | + if (result.status === "fulfilled") { |
| 101 | + if (job.setCookie) setCookies.push(job.setCookie); |
| 102 | + } else { |
| 103 | + logger.error("Could not queue a sign-up conversion", { |
| 104 | + jobId: job.id, |
| 105 | + error: errorMessage(result.reason), |
| 106 | + }); |
| 107 | + } |
| 108 | + }); |
| 109 | + return { setCookies }; |
| 110 | +} |
| 111 | + |
| 112 | +export const SignupConversionJobSchema = z.object({ |
| 113 | + id: z.string(), |
| 114 | + payload: z.record(z.string(), z.unknown()), |
| 115 | +}); |
| 116 | + |
| 117 | +export const signupConversionJob = { |
| 118 | + schema: SignupConversionJobSchema, |
| 119 | + visibilityTimeoutMs: 60_000, |
| 120 | + retry: { maxAttempts: 5, minTimeoutInMs: 30_000, maxTimeoutInMs: 10 * 60_000, factor: 2 }, |
| 121 | +}; |
| 122 | + |
| 123 | +async function enqueueSignupConversionJob(job: SignupConversionJob) { |
| 124 | + // Lazy: a static import would pull the worker into the root loader's module graph. |
| 125 | + const { commonWorker } = await import("~/v3/commonWorker.server"); |
| 126 | + const { setCookie: _cookie, ...queued } = job; |
| 127 | + await commonWorker.enqueueOnce({ id: job.id, job: "signupConversions.send", payload: queued }); |
| 128 | +} |
| 129 | + |
| 130 | +/** Runs one queued conversion. A missing plugin drops it: there's nothing to send it with. */ |
| 131 | +export async function runSignupConversionJob( |
| 132 | + job: z.infer<typeof SignupConversionJobSchema>, |
| 133 | + controller?: MaybeController |
| 134 | +): Promise<void> { |
| 135 | + const plugin = await (controller ?? getController()); |
| 136 | + if (!plugin) { |
| 137 | + logger.warn("Dropped a sign-up conversion: plugin not loaded", { jobId: job.id }); |
| 138 | + return; |
| 139 | + } |
| 140 | + await plugin.sendJob(job as SignupConversionJob); |
| 141 | +} |
0 commit comments