The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Cleans up redis streams class and project usage route
Ian MacCallum74745539248f
diff --git a/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts b/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.tsdeleted file mode 100644index d74482e993..0000000000--- a/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts+++ /dev/null@@ -1,119 +0,0 @@-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";-import { conn } from "@/lib/planetscale";-import { clickUpdatesStream } from "@/lib/upstash/redis-streams";-import { NextResponse } from "next/server";--export const dynamic = "force-dynamic";--// This route is used to process aggregated click events from Redis streams-// It runs every 5 seconds to consume high-frequency click updates-export async function GET(req: Request) {- try {- await verifyVercelSignature(req);-- console.log("Processing click updates from Redis stream...");-- // Read and process updates from the stream- const { updates, lastProcessedId } =- await clickUpdatesStream.readAndProcessUpdates({- count: 1000, // Process up to 1000 entries at once- deleteAfterRead: true, // Clean up processed entries- });-- if (updates.length === 0) {- console.log("No click updates to process");- return NextResponse.json({- success: true,- message: "No updates to process",- processed: 0,- });- }-- console.log(`Processing ${updates.length} aggregated click 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));- }-- let totalProcessed = 0;- const errors: any[] = [];-- for (const batch of batches) {- console.log("Processing batch:", JSON.stringify(batch, null, 2));- try {- // Execute all updates in the batch in parallel- const batchPromises = batch.map(async (update) => {- try {- // Update the click count for the link- await conn.execute(- "UPDATE Link SET clicks = clicks + ?, lastClicked = FROM_UNIXTIME(?) WHERE id = ?",- [- update.totalCount,- Math.floor(update.lastTimestamp / 1000),- update.linkId,- ],- );-- return {- success: true,- linkId: update.linkId,- count: update.totalCount,- };- } catch (error) {- console.error(`Failed to update link ${update.linkId}:`, error);- return { success: false, linkId: update.linkId, 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} click 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- }-- // Get stream info for monitoring- const streamInfo = await clickUpdatesStream.getStreamInfo();-- return NextResponse.json({- success: true,- processed: totalProcessed,- errors: errors.length,- lastProcessedId,- streamInfo,- message: `Successfully processed ${totalProcessed} click updates`,- });- } catch (error) {- console.error("Failed to process click updates:", error);- return handleAndReturnErrorResponse(error);- }-}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.tsindex 3724dcaaa3..734b7be25d 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@@ -1,11 +1,185 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";import { verifyVercelSignature } from "@/lib/cron/verify-vercel";import { conn } from "@/lib/planetscale";-import { projectUsageStream } from "@/lib/upstash/redis-streams";+import {+ ClickEvent,+ Entry,+ projectUsageStream,+} from "@/lib/upstash/redis-streams";import { NextResponse } from "next/server";export const dynamic = "force-dynamic";+const BATCH_SIZE = 1000;++type ProjectAggregateUsage = {+ projectId: string;+ usage: number;+ clicks: number;+ firstTimestamp: number;+ lastTimestamp: number;+};++type ProcessResponse = {+ success: boolean;+ updates: ProjectAggregateUsage[];+ errors?: { projectId: string; error: any }[];+ totalProcessed?: number;+ lastProcessedId?: string | null;+};++const aggregateProjectUsage = (+ entries: Entry<ClickEvent>[],+): { updates: ProjectAggregateUsage[]; lastProcessedId: string | null } => {+ // Aggregate usage by projectId+ const aggregatedUsage = new Map<string, ProjectAggregateUsage>();++ let lastId: string | null = null;++ // The entries are a batch of project usage events, each with projectId, timestamp, and possibly linkId.+ // We want to aggregate by projectId, counting total events (clicks) and tracking first/last timestamps.++ for (const [streamId, fields] of Object.entries(entries)) {+ const entry = fields as unknown as {+ projectId: string;+ timestamp: string;+ linkId?: string;+ };+ const projectId = entry.projectId;+ const timestamp = Date.parse(entry.timestamp) / 1000;++ lastId = streamId;++ if (aggregatedUsage.has(projectId)) {+ const existing = aggregatedUsage.get(projectId)!;+ existing.usage += 1;+ existing.clicks += 1;+ existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);+ existing.firstTimestamp = Math.min(existing.firstTimestamp, timestamp);+ } else {+ aggregatedUsage.set(projectId, {+ projectId,+ usage: 1,+ clicks: 1,+ firstTimestamp: timestamp,+ lastTimestamp: timestamp,+ });+ }+ }++ return {+ updates: Array.from(aggregatedUsage.values()),+ lastProcessedId: lastId,+ };+};++const processProjectUpdateStreamBatch = () =>+ projectUsageStream.processBatch<ClickEvent, ProcessResponse>(+ async (entries) => {+ if (!entries || Object.keys(entries).length === 0) {+ return {+ success: true,+ updates: [],+ } as ProcessResponse;+ }++ const { updates, lastProcessedId } = aggregateProjectUsage(entries);++ if (updates.length === 0) {+ console.log("No project usage updates to process");+ return { success: true, updates: [] } as ProcessResponse;+ }++ console.log(+ `Processing ${updates.length} aggregated project usage updates`,+ );++ // Process updates in parallel batches to avoid overwhelming the database+ const SUB_BATCH_SIZE = 50;+ const batches: (typeof updates)[] = [];++ for (let i = 0; i < updates.length; i += SUB_BATCH_SIZE) {+ batches.push(updates.slice(i, i + SUB_BATCH_SIZE));+ }++ let totalProcessed = 0;+ const errors: { projectId: string; error: any }[] = [];++ for (const batch of batches) {+ console.log(`BATCH: ${JSON.stringify(batch)}`);+ try {+ // Execute all updates in the batch in parallel+ const batchPromises = batch.map(async (update) => {+ try {+ // Update the project usage and click counts+ // "usage" is a reserved keyword in MySQL, so we must escape it with backticks+ await conn.execute(+ "UPDATE Project p SET p.usage = p.usage + ?, p.totalClicks = p.totalClicks + ? WHERE id = ?",+ [update.usage, update.clicks, update.projectId],+ );++ return {+ ...update,+ success: true,+ };+ } catch (error) {+ console.error(+ `Failed to update project ${update.projectId}:`,+ error,+ );+ return {+ success: false,+ error: { 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 if (+ result.status === "fulfilled" &&+ !result.value.success &&+ result.value.error+ ) {+ errors.push(result.value.error);+ }+ });+ } 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,+ } as ProcessResponse;+ },+ {+ count: BATCH_SIZE,+ deleteAfterRead: true,+ },+ );+// This route is used to process aggregated project usage events from Redis streams// It runs every 5 seconds to consume high-frequency usage updatesexport async function GET(req: Request) {@@ -15,95 +189,7 @@ export async function GET(req: Request) {console.log("Processing project usage updates from Redis stream...");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 };- }-- 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)[] = [];-- 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)`,- );-- 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- },- );+ await processProjectUpdateStreamBatch();if (!updates.length) {return NextResponse.json({@@ -119,7 +205,7 @@ export async function GET(req: Request) {return NextResponse.json({success: true,processed: totalProcessed,- errors: errors.length,+ errors: errors?.length || 0,lastProcessedId,streamInfo,message: `Successfully processed ${totalProcessed} project usage updates`,diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex 1ca3db77ff..5e74aa674d 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -19,7 +19,7 @@ import {import { conn } from "../planetscale";import { WorkspaceProps } from "../types";import { redis } from "../upstash";-import { publishLinkClick } from "../upstash/redis-streams";+import { publishClickEvent } from "../upstash/redis-streams";import { webhookCache } from "../webhook/cache";import { sendWebhooks } from "../webhook/qstash";import { transformClickEventData } from "../webhook/transform";@@ -191,11 +191,12 @@ export async function recordClick({// 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 cycleurl &&- publishLinkClick({+ publishClickEvent({linkId,+ projectId: workspaceId,timestamp: clickData.timestamp,url,- }).catch((err) => {+ }).catch(() => {// Fallback on writing directly to the databasereturn 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 = ?",diff --git a/apps/web/lib/upstash/README.md b/apps/web/lib/upstash/README.mddeleted file mode 100644index 54075f210a..0000000000--- a/apps/web/lib/upstash/README.md+++ /dev/null@@ -1,204 +0,0 @@-# Redis Streams for High-Frequency Click Tracking--This implementation uses Redis Streams to handle high-frequency link click and project usage updates efficiently. Instead of immediately updating the database for each event, we publish events to separate Redis Streams and process them in batches via dedicated cron jobs.--## Architecture--1. **High-frequency publishing**: Click and usage events are published to separate Redis Streams at 10+ times per second-2. **Dual-stream processing**: Separate cron jobs run every 5 seconds to consume and aggregate updates-3. **Database efficiency**: Aggregated updates reduce database load and improve performance-4. **Separation of concerns**: Link clicks and project usage are handled in separate streams for better modularity--## Components--### RedisStream Class (`redis-streams.ts`)--Core class that handles stream operations:--- `publishClickUpdate(event)`: Publishes click events to the stream-- `publishProjectUsageUpdate(event)`: Publishes project usage events to the stream-- `readAndProcessUpdates(options)`: Reads and aggregates click data from the stream-- `readAndProcessProjectUpdates(options)`: Reads and aggregates project usage data from the stream-- `getStreamInfo()`: Gets stream metadata for monitoring--### Stream Instances--Two separate stream instances for different concerns:--- `clickUpdatesStream`: Handles link click events (`link-click-updates` stream)-- `projectUsageStream`: Handles project usage events (`project-usage-updates` stream)--### Cron Jobs--**Link Clicks** (`/api/cron/links/click-updates-queue/route.ts`):--- Processes aggregated click updates every 5 seconds-- Reads up to 1000 entries at once-- Aggregates clicks by linkId-- Updates Link table with click counts-- Cleans up processed entries--**Project Usage** (`/api/cron/projects/usage-updates-queue/route.ts`):--- Processes aggregated usage updates every 5 seconds-- Reads up to 1000 entries at once-- Aggregates usage and clicks by projectId-- Updates Project table with usage and totalClicks-- Cleans up processed entries--## Usage Example--### Publishing Click Updates--```typescript-import { clickUpdatesStream } from "@/lib/upstash/redis-streams";--// Publish a single click-await clickUpdatesStream.publishClickUpdate({- linkId: "link-123",- timestamp: Date.now(),- count: 1,-});-```--### Publishing Project Usage Updates--```typescript-import { projectUsageStream } from "@/lib/upstash/redis-streams";--// Publish project usage update-await projectUsageStream.publishProjectUsageUpdate({- projectId: "project-456",- timestamp: Date.now(),- usageCount: 1,- clickCount: 1,-});-```--### Integration with Existing Click Recording--Instead of directly updating the database in your click recording logic:--```typescript-// Before (direct database updates)-await conn.execute(- "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",- [linkId],-);-await 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],-);--// After (dual-stream approach)-await clickUpdatesStream.publishClickUpdate({- linkId,- timestamp: Date.now(),- count: 1,-});--await projectUsageStream.publishProjectUsageUpdate({- projectId,- timestamp: Date.now(),- usageCount: 1,- clickCount: 1,-});-```--### Monitoring Stream Health--```typescript-// Monitor click stream-const clickStreamInfo = await clickUpdatesStream.getStreamInfo();-console.log(`Click stream has ${clickStreamInfo.length} entries`);--// Monitor project usage stream-const usageStreamInfo = await projectUsageStream.getStreamInfo();-console.log(`Usage stream has ${usageStreamInfo.length} entries`);-```--## Configuration--### Cron Job Setup--Set up cron jobs to run both processing endpoints every 5 seconds:--```bash-# In your cron configuration or deployment platform--# Link clicks processing-*/5 * * * * curl -X GET https://your-domain.com/api/cron/links/click-updates-queue--# Project usage processing-*/5 * * * * curl -X GET https://your-domain.com/api/cron/projects/usage-updates-queue-```--### Environment Variables--Make sure these are set in your environment:--- `UPSTASH_REDIS_REST_URL`-- `UPSTASH_REDIS_REST_TOKEN`--## Performance Benefits--1. **Reduced Database Load**: Batch processing reduces individual database calls-2. **High Throughput**: Can handle 10+ events per second without performance degradation-3. **Fault Tolerance**: If processing fails, events remain in streams for retry-4. **Memory Management**: Automatic cleanup prevents unbounded memory growth-5. **Separation of Concerns**: Independent processing of clicks and usage allows for different scaling strategies-6. **Better Resource Utilization**: Dedicated streams prevent blocking between different types of updates--## Monitoring--Both cron jobs return detailed metrics:--**Click Updates Response:**--```json-{- "success": true,- "processed": 150,- "errors": 0,- "lastProcessedId": "1734633600000-5",- "streamInfo": {- "length": 0,- "firstEntryId": null,- "lastEntryId": null- },- "message": "Successfully processed 150 click updates"-}-```--**Project Usage Response:**--```json-{- "success": true,- "processed": 75,- "errors": 0,- "lastProcessedId": "1734633600000-3",- "streamInfo": {- "length": 0,- "firstEntryId": null,- "lastEntryId": null- },- "message": "Successfully processed 75 project usage updates"-}-```--## Error Handling--- Stream operations include comprehensive error handling-- Failed database updates are logged but don't stop processing-- Stream cleanup failures are non-fatal-- Detailed logging for debugging--## Deployment Notes--1. Make sure both cron job endpoints are secured with Vercel signature verification-2. Monitor both stream lengths to ensure they don't grow unbounded-3. Set up alerts for processing errors on both streams-4. Consider adjusting batch sizes based on your database capacity-5. Both streams can be scaled independently based on their respective load patterns-6. Consider staggering the cron jobs slightly to avoid database contention (e.g., run one at :00, :05, :10 and the other at :02, :07, :12)diff --git a/apps/web/lib/upstash/redis-streams.ts b/apps/web/lib/upstash/redis-streams.tsindex 7e544e4032..6c0428bbfc 100644--- a/apps/web/lib/upstash/redis-streams.ts+++ b/apps/web/lib/upstash/redis-streams.ts@@ -1,41 +1,19 @@import { redis } from "./redis";// Stream key constants-export const LINK_CLICK_UPDATES_STREAM_KEY = "link:click:updates";export const PROJECT_USAGE_UPDATES_STREAM_KEY = "project:usage:updates";export interface ClickEvent {linkId: string;+ projectId?: string;timestamp: string;url?: string;}-export interface StreamEntry {+export type Entry<T> = {id: string;- linkId: string;- timestamp: string;-}--export interface ProjectStreamEntry {- id: string;- linkId: string;- timestamp: string;-}--export interface ProcessedClickUpdate {- linkId: string;- totalCount: number;- firstTimestamp: number;- lastTimestamp: number;-}--export interface ProcessedProjectUpdate {- projectId: string;- totalUsage: number;- totalClicks: number;- firstTimestamp: number;- lastTimestamp: number;-}+ data: T;+};export class RedisStream {private streamKey: string;@@ -45,20 +23,18 @@ export class RedisStream {}/**- * Read and process click updates from the stream- * This method aggregates clicks by linkId and returns the total counts+ * Read and process a batch of items from the stream+ * This provides a consumable batch of messages with the ability to delete them upon successful completion of the handler*/- async readAndProcessUpdates(+ async processBatch<T, Response>(+ handler: (records: Entry<T>[]) => Promise<Response>,options: {startId?: string;endId?: string;count?: number;deleteAfterRead?: boolean;} = {},- ): Promise<{- updates: ProcessedClickUpdate[];- lastProcessedId: string | null;- }> {+ ): Promise<Response> {const {startId = "0",endId = "+",@@ -68,195 +44,36 @@ export class RedisStream {try {// Read entries from the stream- const entries = await redis.xrange(this.streamKey, startId, endId, count);-- if (!entries || Object.keys(entries).length === 0) {- return { updates: [], lastProcessedId: null };- }-- // Aggregate clicks by linkId- const aggregatedClicks = new Map<string, ProcessedClickUpdate>();- let lastId: string | null = null;-- for (const [streamId, fields] of Object.entries(entries)) {- const entry = fields as unknown as {- linkId: string;- timestamp: string;- };- const linkId = entry.linkId;- const timestamp = Date.parse(entry.timestamp) / 1000;- const count = 1;-- lastId = streamId;-- if (aggregatedClicks.has(linkId)) {- const existing = aggregatedClicks.get(linkId)!;- existing.totalCount += count;- existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);- existing.firstTimestamp = Math.min(- existing.firstTimestamp,- timestamp,- );- } else {- aggregatedClicks.set(linkId, {- linkId,- totalCount: count,- firstTimestamp: timestamp,- lastTimestamp: timestamp,- });- }- }+ const entriesMap = await redis.xrange(+ this.streamKey,+ startId,+ endId,+ count,+ );++ const entries: Entry<T>[] = Object.entries(entriesMap).map(+ ([id, data]) => ({+ id,+ data: data as any,+ }),+ );++ const response = await handler(entries);// Optionally delete processed entries to prevent memory buildup- // xackdel is not a standard Redis command, but if you are referring to a custom helper or a pattern- // that acknowledges and deletes entries in a consumer group (as with xack + xdel), you could use it- // if you are using consumer groups. However, this code is not using consumer groups, so xdel is correct.- // If you want to use xackdel, you must be using XREADGROUP and have a consumer group context.- // For now, keep xdel, but add a note:-- if (deleteAfterRead && lastId) {+ if (deleteAfterRead) {try {- // NOTE: If using Redis Streams with consumer groups, you should use XACK to acknowledge- // entries for a group/consumer, and optionally XDEL to delete. Here, we are not using consumer groups,- // so we just delete processed entries directly.- // If you migrate to consumer groups, replace this with xack + xdel as appropriate.+ // Delete all entries up to and including the last processed ID+ // We do this by collecting the IDs we just processed and deleting them+ // (Assumes entries is the batch we just processed)+ const processedEntryIds = Object.keys(entries);- // Remove all processed entries up to and including lastId- // Get all entry IDs up to lastId- const processedEntries = await redis.xrange(- this.streamKey,- "-",- lastId,- );- const processedEntryIds = Object.keys(processedEntries || {});if (processedEntryIds.length > 0) {- // xdel supports deleting multiple IDs at once, but Upstash limits batch size, so chunk if needed- const BATCH_SIZE = 100;- for (let i = 0; i < processedEntryIds.length; i += BATCH_SIZE) {- const batch = processedEntryIds.slice(i, i + BATCH_SIZE);- try {- await redis.xdel(this.streamKey, batch);- } catch (delError) {- // Continue if individual batch delete fails- }- }+ // xdel supports deleting multiple IDs at once+ await redis.xdel(this.streamKey, processedEntryIds);}} catch (error) {- console.warn("Failed to clean up stream entries:", error);- // Don't throw - this is not critical- }- }-- return {- updates: Array.from(aggregatedClicks.values()),- lastProcessedId: lastId,- };- } catch (error) {- console.error("Failed to read updates from stream:", error);- throw error;- }- }-- /**- * Read and process project usage updates from the stream- * This method aggregates usage and clicks by projectId and returns the total counts- */- async readAndProcessProjectUpdates<T>(- handler: (info: {- updates: ProcessedProjectUpdate[];- lastProcessedId: string | null;- }) => Promise<T>,- options: {- startId?: string;- endId?: string;- count?: number;- deleteAfterRead?: boolean;- } = {},- ): Promise<T> {- const {- startId = "0",- endId = "+",- count = 1000,- deleteAfterRead = true,- } = options;-- try {- // Read entries from the stream- const entries = await redis.xrange(this.streamKey, startId, endId, count);-- if (!entries || Object.keys(entries).length === 0) {- return handler({ updates: [], lastProcessedId: null });- }-- // Aggregate usage by projectId- const aggregatedUsage = new Map<string, ProcessedProjectUpdate>();- let lastId: string | null = null;-- for (const [streamId, fields] of Object.entries(entries)) {- const entry = fields as unknown as {- projectId: string;- timestamp: string;- usageCount: string;- clickCount: string;- };- const projectId = entry.projectId;- const timestamp = Date.parse(entry.timestamp) / 1000;- const usageCount = parseInt(entry.usageCount);- const clickCount = parseInt(entry.clickCount);-- lastId = streamId;-- if (aggregatedUsage.has(projectId)) {- const existing = aggregatedUsage.get(projectId)!;- existing.totalUsage += usageCount;- existing.totalClicks += clickCount;- existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);- existing.firstTimestamp = Math.min(- existing.firstTimestamp,- timestamp,- );- } else {- aggregatedUsage.set(projectId, {- projectId,- totalUsage: usageCount,- totalClicks: clickCount,- firstTimestamp: timestamp,- lastTimestamp: timestamp,- });- }- }-- const response = await handler({- updates: Array.from(aggregatedUsage.values()),- lastProcessedId: lastId,- });-- // Optionally delete processed entries to prevent memory buildup- if (deleteAfterRead && lastId) {- try {- // Remove entries up to the last processed ID- // We'll implement this by deleting all entries older than the last processed one- // For now, we'll keep a maximum number of entries to prevent unbounded growth- const allEntries = await redis.xrange(this.streamKey, "-", "+");- const totalEntries = Object.keys(allEntries || {}).length;-- // Keep only the last 1000 entries if we have more than 2000- if (totalEntries > 2000) {- const entryIds = Object.keys(allEntries);- const keepFromIndex = totalEntries - 1000;- const minIdToKeep = entryIds[keepFromIndex];-- // Delete entries older than minIdToKeep (this is a workaround for xtrim)- for (let i = 0; i < keepFromIndex; i++) {- try {- await redis.xdel(this.streamKey, entryIds[i]);- } catch (delError) {- // Continue if individual delete fails- }- }- }- } catch (error) {- console.warn("Failed to clean up stream entries:", error);+ console.warn("Failed to clean up processed stream entries:", error);// Don't throw - this is not critical}}@@ -331,22 +148,19 @@ export class RedisStream {}}-// Export instances for both click and project usage updates-export const clickUpdatesStream = new RedisStream(- LINK_CLICK_UPDATES_STREAM_KEY,-);export const projectUsageStream = new RedisStream(PROJECT_USAGE_UPDATES_STREAM_KEY,);-export const publishLinkClick = async (event: ClickEvent) => {- const { linkId, timestamp, url } = event;- const entry = { linkId, timestamp };+// Publishes a click event to any relevant streams in a single transaction+export const publishClickEvent = async (event: ClickEvent) => {+ const { linkId, timestamp, projectId, url } = event;+ const entry = { linkId, timestamp, projectId };try {const pipeline = redis.pipeline();- // TODO: - Uncomment when we handle+ // TODO: - Uncomment when we handle click updates// pipeline.xadd(LINK_CLICK_UPDATES_STREAM_KEY, "*", entry);if (url) {