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.

wip

Ian MacCalluma463fe0999ae
diff --git a/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts b/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts
index acb112509e..3724dcaaa3 100644
--- a/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts
+++ b/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts
@@ -14,92 +14,103 @@ export async function GET(req: Request) {
console.log("Processing project usage updates from Redis stream...");
- // Read and process updates from the stream
- const { updates, lastProcessedId } =
- await projectUsageStream.readAndProcessProjectUpdates({
- count: 1000, // Process up to 1000 entries at once
- deleteAfterRead: true, // Clean up processed entries
- });
+ const { updates, errors, totalProcessed, lastProcessedId } =
+ await projectUsageStream.readAndProcessProjectUpdates(
+ async (info) => {
+ const { updates, lastProcessedId } = info;
+ if (updates.length === 0) {
+ console.log("No project usage updates to process");
+ return { updates: [], errors: [], totalProcessed: 0 };
+ }
- if (updates.length === 0) {
- console.log("No project usage updates to process");
- return NextResponse.json({
- success: true,
- message: "No updates to process",
- processed: 0,
- });
- }
+ console.log(
+ `Processing ${updates.length} aggregated project usage updates`,
+ );
- console.log(
- `Processing ${updates.length} aggregated project usage updates`,
- );
+ // Process updates in parallel batches to avoid overwhelming the database
+ const BATCH_SIZE = 50;
+ const batches: (typeof updates)[] = [];
- // Process updates in parallel batches to avoid overwhelming the database
- const BATCH_SIZE = 50;
- const batches: (typeof updates)[] = [];
+ for (let i = 0; i < updates.length; i += BATCH_SIZE) {
+ batches.push(updates.slice(i, i + BATCH_SIZE));
+ }
- for (let i = 0; i < updates.length; i += BATCH_SIZE) {
- batches.push(updates.slice(i, i + BATCH_SIZE));
- }
+ let totalProcessed = 0;
+ const errors: any[] = [];
+
+ for (const batch of batches) {
+ try {
+ // Execute all updates in the batch in parallel
+ const batchPromises = batch.map(async (update) => {
+ try {
+ // Update the project usage and click counts
+ await conn.execute(
+ "UPDATE Project SET usage = usage + ?, totalClicks = totalClicks + ? WHERE id = ?",
+ [update.totalUsage, update.totalClicks, update.projectId],
+ );
+
+ return {
+ success: true,
+ projectId: update.projectId,
+ usage: update.totalUsage,
+ clicks: update.totalClicks,
+ };
+ } catch (error) {
+ console.error(
+ `Failed to update project ${update.projectId}:`,
+ error,
+ );
+ return { success: false, projectId: update.projectId, error };
+ }
+ });
+
+ const batchResults = await Promise.allSettled(batchPromises);
+
+ // Count successful updates and collect errors
+ batchResults.forEach((result) => {
+ if (result.status === "fulfilled" && result.value.success) {
+ totalProcessed++;
+ } else {
+ errors.push(
+ result.status === "fulfilled"
+ ? result.value
+ : result.reason,
+ );
+ }
+ });
+ } catch (error) {
+ console.error("Failed to process batch:", error);
+ errors.push(error);
+ }
+ }
+
+ // Log results
+ const successRate = (totalProcessed / updates.length) * 100;
+ console.log(
+ `Processed ${totalProcessed}/${updates.length} project usage updates (${successRate.toFixed(1)}% success rate)`,
+ );
- let totalProcessed = 0;
- const errors: any[] = [];
-
- for (const batch of batches) {
- try {
- // Execute all updates in the batch in parallel
- const batchPromises = batch.map(async (update) => {
- try {
- // Update the project usage and click counts
- await conn.execute(
- "UPDATE Project SET usage = usage + ?, totalClicks = totalClicks + ? WHERE id = ?",
- [update.totalUsage, update.totalClicks, update.projectId],
- );
-
- return {
- success: true,
- projectId: update.projectId,
- usage: update.totalUsage,
- clicks: update.totalClicks,
- };
- } catch (error) {
+ if (errors.length > 0) {
console.error(
- `Failed to update project ${update.projectId}:`,
- error,
- );
- return { success: false, projectId: update.projectId, error };
- }
- });
-
- const batchResults = await Promise.allSettled(batchPromises);
-
- // Count successful updates and collect errors
- batchResults.forEach((result) => {
- if (result.status === "fulfilled" && result.value.success) {
- totalProcessed++;
- } else {
- errors.push(
- result.status === "fulfilled" ? result.value : result.reason,
- );
+ `Encountered ${errors.length} errors while processing:`,
+ errors.slice(0, 5),
+ ); // Log first 5 errors
}
- });
- } catch (error) {
- console.error("Failed to process batch:", error);
- errors.push(error);
- }
- }
- // Log results
- const successRate = (totalProcessed / updates.length) * 100;
- console.log(
- `Processed ${totalProcessed}/${updates.length} project usage updates (${successRate.toFixed(1)}% success rate)`,
- );
-
- if (errors.length > 0) {
- console.error(
- `Encountered ${errors.length} errors while processing:`,
- errors.slice(0, 5),
- ); // Log first 5 errors
+ return { updates, errors, totalProcessed, lastProcessedId };
+ },
+ {
+ count: 1000, // Process up to 1000 entries at once
+ deleteAfterRead: true, // Clean up processed entries
+ },
+ );
+
+ if (!updates.length) {
+ return NextResponse.json({
+ success: true,
+ message: "No updates to process",
+ processed: 0,
+ });
}
// Get stream info for monitoring
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index b6a6941b44..1ca3db77ff 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -182,8 +182,26 @@ export async function recordClick({
// cache the recorded click for the corresponding IP address in Redis for 1 hour
recordClickCache.set({ domain, key, ip, clickId }),
- // Publish the click event to the click events stream
- publishLinkClick({ linkId, timestamp: clickData.timestamp, url }),
+ // increment the click count for the link (based on their ID)
+ // we have to use planetscale connection directly (not prismaEdge) because of connection pooling
+ conn.execute(
+ "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
+ [linkId],
+ ),
+ // if the link has a destination URL, increment the usage count for the workspace
+ // and then we have a cron that will reset it at the start of new billing cycle
+ url &&
+ publishLinkClick({
+ linkId,
+ timestamp: clickData.timestamp,
+ url,
+ }).catch((err) => {
+ // Fallback on writing directly to the database
+ return conn.execute(
+ "UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1, p.totalClicks = p.totalClicks + 1 WHERE l.id = ?",
+ [linkId],
+ );
+ }),
]);
// Find the rejected promises and log them
diff --git a/apps/web/lib/upstash/redis-streams.ts b/apps/web/lib/upstash/redis-streams.ts
index 9e3106be6d..7e544e4032 100644
--- a/apps/web/lib/upstash/redis-streams.ts
+++ b/apps/web/lib/upstash/redis-streams.ts
@@ -141,19 +141,6 @@ export class RedisStream {
}
}
}
-
- // Additionally, trim the stream to prevent unbounded growth
- // Keep only the last 2000 entries (soft limit)
- try {
- // Upstash/Redis xtrim expects an options object, not just a number
- await redis.xtrim(this.streamKey, {
- strategy: "MAXLEN",
- threshold: 2000,
- exactness: "~",
- });
- } catch (trimError) {
- // Not critical if trim fails
- }
} catch (error) {
console.warn("Failed to clean up stream entries:", error);
// Don't throw - this is not critical
@@ -174,17 +161,18 @@ export class RedisStream {
* Read and process project usage updates from the stream
* This method aggregates usage and clicks by projectId and returns the total counts
*/
- async readAndProcessProjectUpdates(
+ async readAndProcessProjectUpdates<T>(
+ handler: (info: {
+ updates: ProcessedProjectUpdate[];
+ lastProcessedId: string | null;
+ }) => Promise<T>,
options: {
startId?: string;
endId?: string;
count?: number;
deleteAfterRead?: boolean;
} = {},
- ): Promise<{
- updates: ProcessedProjectUpdate[];
- lastProcessedId: string | null;
- }> {
+ ): Promise<T> {
const {
startId = "0",
endId = "+",
@@ -197,7 +185,7 @@ export class RedisStream {
const entries = await redis.xrange(this.streamKey, startId, endId, count);
if (!entries || Object.keys(entries).length === 0) {
- return { updates: [], lastProcessedId: null };
+ return handler({ updates: [], lastProcessedId: null });
}
// Aggregate usage by projectId
@@ -238,6 +226,11 @@ export class RedisStream {
}
}
+ const response = await handler({
+ updates: Array.from(aggregatedUsage.values()),
+ lastProcessedId: lastId,
+ });
+
// Optionally delete processed entries to prevent memory buildup
if (deleteAfterRead && lastId) {
try {
@@ -268,10 +261,7 @@ export class RedisStream {
}
}
- return {
- updates: Array.from(aggregatedUsage.values()),
- lastProcessedId: lastId,
- };
+ return response;
} catch (error) {
console.error("Failed to read project usage updates from stream:", error);
throw error;
@@ -356,7 +346,8 @@ export const publishLinkClick = async (event: ClickEvent) => {
try {
const pipeline = redis.pipeline();
- pipeline.xadd(LINK_CLICK_UPDATES_STREAM_KEY, "*", entry);
+ // TODO: - Uncomment when we handle
+ // pipeline.xadd(LINK_CLICK_UPDATES_STREAM_KEY, "*", entry);
if (url) {
pipeline.xadd(PROJECT_USAGE_UPDATES_STREAM_KEY, "*", entry);
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 5c0709dd7d..321a3e838b 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -12,6 +12,10 @@
"path": "/api/cron/domains/renewal-payments",
"schedule": "0 8 * * *"
},
+ {
+ "path": "/api/cron/projects/usage-updates-queue",
+ "schedule": "*/5 * * * * *"
+ },
{
"path": "/api/cron/usage",
"schedule": "0 12 * * *"