Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add support for `mode="deferred"` in `/track/lead`

Steven Teyb902600193ff
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
index 8477610539..ef99a48719 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -39,6 +39,27 @@ export const trackLead = async ({
rawBody,
workspace,
}: TrackLeadParams) => {
+ if (!clickId) {
+ const existingCustomer = await prisma.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: customerExternalId,
+ },
+ },
+ });
+
+ if (!existingCustomer || !existingCustomer.clickId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "The `clickId` attribute was not provided in the request, and no existing customer with the provided `customerExternalId` was found.",
+ });
+ }
+
+ clickId = existingCustomer.clickId;
+ }
+
const stringifiedEventName = eventName.toLowerCase().replaceAll(" ", "-");
// deduplicate lead events – only record 1 unique event for the same customer and event name
@@ -173,9 +194,8 @@ export const trackLead = async ({
let customer: Customer | undefined;
- // Handle customer creation and lead recording based on mode
+ // if wait mode, create the customer and record the lead event synchronously
if (mode === "wait") {
- // Execute customer creation synchronously
customer = await upsertCustomer();
const leadEventPayload = createLeadEventPayload(customer.id);
@@ -204,71 +224,22 @@ export const trackLead = async ({
waitUntil(
(async () => {
- // For async mode, create customer in the background
- if (mode === "async") {
+ // for async and deferred mode, create the customer in the background
+ if (mode == "async" || mode == "deferred") {
customer = await upsertCustomer();
- // Use recordLead which doesn't wait
- await recordLead(createLeadEventPayload(customer.id));
+ // for async mode, record the lead event right away
+ if (mode === "async") {
+ await recordLead(createLeadEventPayload(customer.id));
+ }
}
- // Always process link/project updates, partner rewards, and webhooks in the background
- const [link, _project] = await Promise.all([
- // update link leads count
- prisma.link.update({
- where: {
- id: clickData.link_id,
- },
- data: {
- leads: {
- increment: eventQuantity ?? 1,
- },
- },
- include: includeTags,
- }),
-
- // update workspace events usage
- prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- usage: {
- increment: eventQuantity ?? 1,
- },
- },
- }),
-
- logConversionEvent({
- workspace_id: workspace.id,
- link_id: clickData.link_id,
- path: "/track/lead",
- body: JSON.stringify(rawBody),
- }),
- ]);
-
- if (link.programId && link.partnerId && customer) {
- await createPartnerCommission({
- event: "lead",
- programId: link.programId,
- partnerId: link.partnerId,
- linkId: link.id,
- eventId: leadEventId,
- customerId: customer.id,
- quantity: eventQuantity ?? 1,
- context: {
- customer: {
- country: customer.country,
- },
- },
- });
-
- await executeWorkflows({
- trigger: WorkflowTrigger.leadRecorded,
- programId: link.programId,
- partnerId: link.partnerId,
- });
- }
+ await logConversionEvent({
+ workspace_id: workspace.id,
+ link_id: clickData.link_id,
+ path: "/track/lead",
+ body: JSON.stringify(rawBody),
+ });
if (
customerAvatar &&
@@ -286,21 +257,81 @@ export const trackLead = async ({
);
}
- await sendWorkspaceWebhook({
- trigger: "lead.created",
- data: transformLeadEventData({
- ...clickData,
- eventName,
- link,
- customer,
- }),
- workspace,
- });
+ // if not deferred mode, process the following right away:
+ // - update link leads count
+ // - update workspace events usage
+ // - update customer leads count
+ // - create partner commission (for partner links)
+ // - execute workflows (for partner links)
+ // - send lead.created webhook
+
+ if (mode !== "deferred") {
+ const [link, _project] = await Promise.all([
+ // update link leads count
+ prisma.link.update({
+ where: {
+ id: clickData.link_id,
+ },
+ data: {
+ leads: {
+ increment: eventQuantity ?? 1,
+ },
+ },
+ include: includeTags,
+ }),
+
+ // update workspace events usage
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ usage: {
+ increment: eventQuantity ?? 1,
+ },
+ },
+ }),
+ ]);
+
+ if (link.programId && link.partnerId && customer) {
+ await createPartnerCommission({
+ event: "lead",
+ programId: link.programId,
+ partnerId: link.partnerId,
+ linkId: link.id,
+ eventId: leadEventId,
+ customerId: customer.id,
+ quantity: eventQuantity ?? 1,
+ context: {
+ customer: {
+ country: customer.country,
+ },
+ },
+ });
+
+ await executeWorkflows({
+ trigger: WorkflowTrigger.leadRecorded,
+ programId: link.programId,
+ partnerId: link.partnerId,
+ });
+ }
+
+ await sendWorkspaceWebhook({
+ trigger: "lead.created",
+ data: transformLeadEventData({
+ ...clickData,
+ eventName,
+ link,
+ customer,
+ }),
+ workspace,
+ });
+ }
})(),
);
}
- const lead = trackLeadResponseSchema.parse({
+ return trackLeadResponseSchema.parse({
click: {
id: clickId,
},
@@ -311,13 +342,4 @@ export const trackLead = async ({
externalId: customerExternalId,
},
});
-
- return {
- ...lead,
- // for backwards compatibility – will remove soon
- clickId,
- customerName: finalCustomerName,
- customerEmail: customerEmail,
- customerAvatar: finalCustomerAvatar,
- };
};
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index 896fb71606..99c5d449b1 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -262,7 +262,7 @@ export const trackSale = async ({
})(),
);
- const sale = trackSaleResponseSchema.parse({
+ return trackSaleResponseSchema.parse({
eventName,
customer,
sale: {
@@ -273,14 +273,4 @@ export const trackSale = async ({
metadata,
},
});
-
- return {
- ...sale,
- // for backwards compatibility – will remove soon
- amount,
- currency,
- invoiceId,
- paymentProcessor,
- metadata,
- };
};
diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.ts
index ee89bc0e55..a6ffc0a791 100644
--- a/apps/web/lib/zod/schemas/leads.ts
+++ b/apps/web/lib/zod/schemas/leads.ts
@@ -6,14 +6,14 @@ import { linkEventSchema } from "./links";
export const trackLeadRequestSchema = z.object({
clickId: z
- .string({ required_error: "clickId is required" })
+ .string()
.trim()
- .min(1, "clickId is required")
+ .nullish()
.describe(
"The unique ID of the click that the lead conversion event is attributed to. You can read this value from `dub_id` cookie.",
),
eventName: z
- .string({ required_error: "eventName is required" })
+ .string()
.trim()
.min(1, "eventName is required")
.max(255)
@@ -24,6 +24,7 @@ export const trackLeadRequestSchema = z.object({
customerExternalId: z
.string()
.trim()
+ .min(1, "customerExternalId is required")
.max(100)
.describe(
"The unique ID of the customer in your system. Will be used to identify and attribute all future events to this customer.",
@@ -55,10 +56,10 @@ export const trackLeadRequestSchema = z.object({
"The numerical value associated with this lead event (e.g., number of provisioned seats in a free trial). If defined as N, the lead event will be tracked N times.",
),
mode: z
- .enum(["async", "wait"])
+ .enum(["async", "wait", "deferred"])
.default("async")
.describe(
- "The mode to use for tracking the lead event. `async` will not block the request; `wait` will block the request until the lead event is fully recorded in Dub.",
+ "The mode to use for tracking the lead event. `async` will not block the request; `wait` will block the request until the lead event is fully recorded in Dub; `deferred` will defer the lead event creation to a subsequent request.",
),
metadata: z
.record(z.unknown())