Skip to content

Commit dc412a4

Browse files
isshaddadTrigger.dev RepoOps
authored andcommitted
feat(webapp): optional sign-up conversions plugin hook
Mono-RevId: 44f0f96b41a2192159ea6e7eabce0a3c0f791931
1 parent 07212da commit dc412a4

8 files changed

Lines changed: 444 additions & 0 deletions

File tree

‎apps/webapp/app/root.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ import { getImpersonationState, getRawImpersonationId } from "./services/imperso
2828
import { getUser } from "./services/session.server";
2929
import { adminOriginForRequest } from "./services/adminOrigin.server";
3030
import { docsHintCookie } from "./services/docsReader.server";
31+
import { signupConversionsForPage } from "./services/signupConversions.server";
32+
import {
33+
enteringSignupConversionPage,
34+
isSignupConversionPage,
35+
} from "./utils/signupConversionPages";
3136
import {
3237
normalizeIconContrast,
3338
normalizeSystemDarkTheme,
@@ -132,6 +137,12 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
132137
// Every login, logout and ended session passes through a dashboard page.
133138
const docsHint = docsHintCookie(request, !!user);
134139
if (docsHint) headers.append("Set-Cookie", docsHint);
140+
141+
// Managed cloud only. Never throws; the plugin decides and queues any ad conversions.
142+
if (user && features.isManagedCloud && isSignupConversionPage(new URL(request.url).pathname)) {
143+
const { setCookies } = await signupConversionsForPage(request, user);
144+
for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
145+
}
135146
const appOrigin = adminOriginForRequest(request) ?? env.APP_ORIGIN;
136147

137148
return typedjson(
@@ -171,6 +182,10 @@ export const shouldRevalidate: ShouldRevalidateFunction = (options) => {
171182
return false;
172183
}
173184

185+
if (enteringSignupConversionPage(options.currentUrl, options.nextUrl)) {
186+
return true;
187+
}
188+
174189
// A detail page tab switch: nothing here reads `?tab=`.
175190
if (onlyDetailTabChanged(options)) {
176191
return false;
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Pages every new account passes through; their URLs carry nothing about the customer.
2+
const SIGNUP_PATHS = new Set(["/confirm-basic-details", "/orgs/new"]);
3+
4+
/** Whether a page is a sign-up page, ignoring case, encoding and a trailing slash. */
5+
export function isSignupConversionPage(pathname: string): boolean {
6+
let path = pathname;
7+
try {
8+
path = decodeURIComponent(pathname);
9+
} catch {
10+
// keep the raw path
11+
}
12+
return SIGNUP_PATHS.has(path.toLowerCase().replace(/\/+$/, ""));
13+
}
14+
15+
/** Root keeps its data on pathname-only navigations, so re-run it when entering a sign-up page. */
16+
export function enteringSignupConversionPage(currentUrl: URL, nextUrl: URL): boolean {
17+
return currentUrl.pathname !== nextUrl.pathname && isSignupConversionPage(nextUrl.pathname);
18+
}

‎apps/webapp/app/v3/commonWorker.server.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import {
6767
runOrgProvisioningJob,
6868
} from "./services/orgProvisioningJobs.server";
6969
import { webhookEngine } from "./webhookEngine.server";
70+
import { runSignupConversionJob, signupConversionJob } from "~/services/signupConversions.server";
7071

7172
function initializeWorker() {
7273
const redisOptions = {
@@ -352,6 +353,7 @@ function initializeWorker() {
352353
maxAttempts: 12,
353354
},
354355
},
356+
"signupConversions.send": signupConversionJob,
355357
"org.provisionStagingEnvironments": {
356358
schema: OrgProvisioningPayloadSchema,
357359
visibilityTimeoutMs: ORG_PROVISIONING_VISIBILITY_TIMEOUT_MS,
@@ -511,6 +513,9 @@ function initializeWorker() {
511513
"org.provisionStagingEnvironments": async ({ payload }) => {
512514
await runOrgProvisioningJob("org.provisionStagingEnvironments", payload.organizationId);
513515
},
516+
"signupConversions.send": async ({ payload }) => {
517+
await runSignupConversionJob(payload);
518+
},
514519
},
515520
});
516521

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import type { SignupConversionsPlugin } from "@trigger.dev/plugins";
2+
3+
/** A real plugin module for loader tests. */
4+
const plugin: SignupConversionsPlugin = {
5+
create() {
6+
return {
7+
onSignupPage: async () => ({ jobs: [{ id: "f1", payload: {}, setCookie: "fixture=1" }] }),
8+
sendJob: async () => {},
9+
};
10+
},
11+
};
12+
13+
export default plugin;

0 commit comments

Comments
 (0)