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.

Store events customers in MySQL instead of TB

Steven Teydc76a5a24589
diff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
index 1cee940abe..08d83a2f36 100644
--- a/apps/web/app/api/stripe/connect/webhook/customer-created.ts
+++ b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
@@ -1,5 +1,5 @@
import { prisma } from "@/lib/prisma";
-import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
+import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
@@ -77,16 +77,7 @@ export async function customerCreated(event: Stripe.Event) {
customer_id: customer.id,
};
- const [_customer, _lead, _link, workspace] = await Promise.all([
- // Record customer
- recordCustomer({
- workspace_id: customer.projectId,
- customer_id: customer.id,
- name: customer.name || "",
- email: customer.email || "",
- avatar: customer.avatar || "",
- }),
-
+ const [_lead, _link, workspace] = await Promise.all([
// Record lead
recordLead(leadData),
diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.ts
index abfb50c0bd..2ba3a86688 100644
--- a/apps/web/app/api/track/customer/route.ts
+++ b/apps/web/app/api/track/customer/route.ts
@@ -2,12 +2,10 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { generateRandomName } from "@/lib/names";
import { prismaEdge } from "@/lib/prisma/edge";
-import { recordCustomer } from "@/lib/tinybird";
import {
trackCustomerRequestSchema,
trackCustomerResponseSchema,
} from "@/lib/zod/schemas/customers";
-import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
export const runtime = "edge";
@@ -47,16 +45,6 @@ export const POST = withWorkspaceEdge(
},
});
- waitUntil(
- recordCustomer({
- workspace_id: workspace.id,
- customer_id: customer.id,
- name: customer.name || "",
- email: customer.email || "",
- avatar: customer.avatar || "",
- }),
- );
-
const response = trackCustomerResponseSchema.parse({
customerId: customer.externalId,
customerName: customer.name,
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 1f07fd35fe..918edb467e 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -3,7 +3,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { generateRandomName } from "@/lib/names";
import { prismaEdge } from "@/lib/prisma/edge";
-import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
+import { getClickEvent, recordLead } from "@/lib/tinybird";
import { ratelimit } from "@/lib/upstash";
import { sendWorkspaceWebhookOnEdge } from "@/lib/webhook/publish-edge";
import { transformLeadEventData } from "@/lib/webhook/transform";
@@ -85,7 +85,7 @@ export const POST = withWorkspaceEdge(
},
});
- const [_lead, _customer, link, _project] = await Promise.all([
+ const [_lead, link, _project] = await Promise.all([
recordLead({
...clickData,
event_id: nanoid(16),
@@ -94,14 +94,6 @@ export const POST = withWorkspaceEdge(
metadata: metadata ? JSON.stringify(metadata) : "",
}),
- recordCustomer({
- workspace_id: workspace.id,
- customer_id: customer.id,
- name: customer.name || "",
- email: customer.email || "",
- avatar: customer.avatar || "",
- }),
-
// update link leads count
prismaEdge.link.update({
where: {
diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.ts
index c583dc4afb..2b740904b7 100644
--- a/apps/web/lib/analytics/get-events.ts
+++ b/apps/web/lib/analytics/get-events.ts
@@ -3,12 +3,14 @@ import { tb } from "@/lib/tinybird";
import { Link } from "@prisma/client";
import { transformLink } from "../api/links";
import { tbDemo } from "../tinybird/demo-client";
+import z from "../zod";
import { eventsFilterTB } from "../zod/schemas/analytics";
import {
clickEventEnrichedSchema,
clickEventResponseSchema,
clickEventSchema,
} from "../zod/schemas/clicks";
+import { customerSchema } from "../zod/schemas/customers";
import {
leadEventEnrichedSchema,
leadEventResponseSchema,
@@ -39,7 +41,7 @@ export const getEvents = async (params: EventsFilters) => {
}
const pipe = (isDemo ? tbDemo : tb).buildPipe({
- pipe: "v1_events",
+ pipe: "v2_events",
parameters: eventsFilterTB,
data:
{
@@ -58,21 +60,10 @@ export const getEvents = async (params: EventsFilters) => {
end: end.toISOString().replace("T", " ").replace("Z", ""),
});
- const links = await prisma.link.findMany({
- where: {
- id: {
- in: response.data.map((d) => d.link_id),
- },
- },
- });
-
- const linksMap = links.reduce(
- (acc, link) => {
- acc[link.id] = link;
- return acc;
- },
- {} as Record<string, Link>,
- );
+ const [linksMap, customersMap] = await Promise.all([
+ getLinksMap(response.data),
+ getCustomersMap(response.data),
+ ]);
const events = response.data
.map((evt) => {
@@ -81,6 +72,26 @@ export const getEvents = async (params: EventsFilters) => {
return null;
}
+ let customer: z.infer<typeof customerSchema> = {
+ id: "",
+ name: "",
+ email: "",
+ avatar: "",
+ };
+
+ if (evt.event === "lead" || evt.event === "sale") {
+ customer = customersMap[evt.customer_id];
+ if (!customer) {
+ console.log("customer not found", evt.customer_id);
+ customer = customerSchema.parse({
+ id: evt.customer_id,
+ name: "Deleted Customer",
+ email: "[email protected]",
+ avatar: `https://api.dicebear.com/7.x/micah/svg?seed=${evt.customer_id}`,
+ });
+ }
+ }
+
const eventData = {
...evt,
// use link domain & key from mysql instead of tinybird
@@ -98,13 +109,7 @@ export const getEvents = async (params: EventsFilters) => {
? {
eventId: evt.event_id,
eventName: evt.event_name,
- customer: {
- name: evt.customer_name,
- email: evt.customer_email,
- avatar:
- evt.customer_avatar ||
- `https://api.dicebear.com/7.x/micah/svg?seed=${evt.customer_email}`,
- },
+ customer,
...(evt.event === "sale"
? {
sale: {
@@ -114,6 +119,11 @@ export const getEvents = async (params: EventsFilters) => {
},
}
: {}),
+ // backwards compatibility for old events
+ customer_id: customer.id,
+ customer_name: customer.name,
+ customer_email: customer.email,
+ customer_avatar: customer.avatar,
}
: {}),
};
@@ -132,3 +142,57 @@ export const getEvents = async (params: EventsFilters) => {
return events;
};
+
+type EnrichedEvent = z.infer<
+ | typeof clickEventEnrichedSchema
+ | typeof leadEventEnrichedSchema
+ | typeof saleEventEnrichedSchema
+>;
+
+const getLinksMap = async (data: EnrichedEvent[]) => {
+ const linkIds = data.map((d) => d.link_id);
+ const links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: linkIds,
+ },
+ },
+ });
+
+ return links.reduce(
+ (acc, link) => {
+ acc[link.id] = link;
+ return acc;
+ },
+ {} as Record<string, Link>,
+ );
+};
+
+const getCustomersMap = async (data: EnrichedEvent[]) => {
+ if (data.every((d) => d.event === "lead" || d.event === "sale")) {
+ const customerIds = data.map((d) => d.customer_id);
+ const customers = await prisma.customer.findMany({
+ where: {
+ id: {
+ in: customerIds,
+ },
+ },
+ });
+
+ return customers.reduce(
+ (acc, customer) => {
+ acc[customer.id] = customerSchema.parse({
+ ...customer,
+ id: customer.externalId,
+ avatar:
+ customer.avatar ||
+ `https://api.dicebear.com/7.x/micah/svg?seed=${customer.id}`,
+ });
+ return acc;
+ },
+ {} as Record<string, z.infer<typeof customerSchema>>,
+ );
+ } else {
+ return {};
+ }
+};
diff --git a/apps/web/lib/tinybird/record-customer.ts b/apps/web/lib/tinybird/record-customer.ts
deleted file mode 100644
index 6614218a11..0000000000
--- a/apps/web/lib/tinybird/record-customer.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { customersMetadataSchema } from "../zod/schemas/customers";
-import { tb } from "./client";
-
-export const recordCustomer = tb.buildIngestEndpoint({
- datasource: "dub_customers_metadata",
- event: customersMetadataSchema,
-});
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index e062009924..793e1a15bd 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -37,23 +37,9 @@ export const trackCustomerResponseSchema = z.object({
customerAvatar: z.string().nullable(),
});
-export const customersMetadataSchema = z.object({
- workspace_id: z.string().transform((v) => {
- if (!v.startsWith("ws_")) {
- return `ws_${v}`;
- } else {
- return v;
- }
- }),
- customer_id: z.string(),
- name: z.string().default(""),
- email: z.string().default(""),
- avatar: z.string().default(""),
- deleted: z.number().default(0),
-});
-
// simple schema returned by /events API
export const customerSchema = z.object({
+ id: z.string(),
name: z.string(),
email: z.string(),
avatar: z.string(),
diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.ts
index b35a05d1f9..c79e4e8d46 100644
--- a/apps/web/lib/zod/schemas/leads.ts
+++ b/apps/web/lib/zod/schemas/leads.ts
@@ -84,9 +84,7 @@ export const leadEventEnrichedSchema = z.object({
timestamp: z.string(),
event_id: z.string(),
event_name: z.string(),
- customer_name: z.string(),
- customer_email: z.string(),
- customer_avatar: z.string(),
+ customer_id: z.string(),
click_id: z.string(),
link_id: z.string(),
url: z.string(),
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index 48455d9378..8f57aa7e56 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -87,9 +87,7 @@ export const saleEventEnrichedSchema = z.object({
timestamp: z.string(),
event_id: z.string(),
event_name: z.string(),
- customer_name: z.string(),
- customer_email: z.string(),
- customer_avatar: z.string(),
+ customer_id: z.string(),
payment_processor: z.string(),
invoice_id: z.string(),
saleAmount: z.number(),
diff --git a/packages/tinybird/datasources/dub_customers_metadata.datasource b/packages/tinybird/datasources/dub_customers_metadata.datasource
deleted file mode 100644
index 33540abdec..0000000000
--- a/packages/tinybird/datasources/dub_customers_metadata.datasource
+++ /dev/null
@@ -1,11 +0,0 @@
-SCHEMA >
- `timestamp` DateTime `json:$.timestamp` DEFAULT now(),
- `customer_id` String `json:$.customer_id`,
- `name` String `json:$.name`,
- `email` String `json:$.email`,
- `avatar` String `json:$.avatar`,
- `workspace_id` String `json:$.workspace_id`,
- `deleted` UInt8 `json:$.deleted`
-
-ENGINE "MergeTree"
-ENGINE_SORTING_KEY "timestamp, customer_id, workspace_id, deleted"
\ No newline at end of file