The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
use redis list
Kiran K4f5f6398c2f8
diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.tsindex b093018614..b4c795fa14 100644--- a/apps/web/app/api/cron/import/csv/route.ts+++ b/apps/web/app/api/cron/import/csv/route.ts@@ -35,6 +35,7 @@ const payloadSchema = z.object({folderId: z.string().nullable(),url: z.string(),mapping: linkMappingSchema,+ action: z.enum(["queue-links", "process-links"]).default("queue-links"),});interface MapperResult {@@ -57,13 +58,11 @@ interface ErrorLink {error: string;}-const MAX_ROWS_PER_EXECUTION = 50;-// POST /api/cron/import/csvexport async function POST(req: Request) {- console.time("import:csv");-try {+ console.time("import:csv");+const rawBody = await req.text();await verifyQstashSignature({@@ -73,128 +72,152 @@ export async function POST(req: Request) {const body = JSON.parse(rawBody);const payload = payloadSchema.parse(body);- const { id, url, mapping, workspaceId } = payload;+ const { action } = payload;- if (!id || !url) {- throw new Error("Missing ID or URL for the import file.");+ if (action === "queue-links") {+ await prepareRows(payload);+ } else if (action === "process-links") {+ await processRows(payload);}- const redisKey = `import:csv:${workspaceId}:${id}`;- const cursor = parseInt((await redis.get(`${redisKey}:cursor`)) || "0");-- const response = await storage.fetch(url);- if (!response || !response.body) {- throw new Error("CSV import file not found.");- }+ console.timeEnd("import:csv");- let mappedLinks: MapperResult[] = []; // Stores processed rows- let currentRow = 0; // Tracks both current position and processed count- let isComplete = false; // We've reached the end of the file-- await new Promise((resolve, reject) => {- Papa.parse(Readable.fromWeb(response.body as any), {- header: true,- skipEmptyLines: true,- worker: false,- complete: (results) => {- isComplete = currentRow >= results.data.length;- resolve(results);- },- error: reject,- step: async (results: { data: Record<string, string> }, parser) => {- parser.pause();+ return NextResponse.json("OK");+ } catch (error) {+ await log({+ message: `Error importing CSV links: ${error.message}`,+ type: "cron",+ });- // Skip rows until we reach our cursor position- if (currentRow < cursor) {- currentRow++;- parser.resume();- return;- }+ return handleAndReturnErrorResponse(error);+ }+}- if (currentRow - cursor >= MAX_ROWS_PER_EXECUTION) {- parser.abort();- return;- }+// Add rows to Redis+const prepareRows = async (payload: z.infer<typeof payloadSchema>) => {+ const { id, url, workspaceId } = payload;- mappedLinks.push(mapCsvRowToLink(results.data, mapping));+ if (!id || !url) {+ throw new Error("Missing ID or URL for the import file.");+ }- currentRow++;+ const response = await storage.fetch(url);+ if (!response || !response.body) {+ throw new Error("CSV import file not found.");+ }- await redis.set(`${redisKey}:cursor`, currentRow);+ const BATCH_SIZE = 1000; // Push 1000 rows to Redis at a time+ const redisKey = `import:csv:${workspaceId}:${id}`;+ let rows: Record<string, string>[] = [];++ await new Promise((resolve, reject) => {+ Papa.parse(Readable.fromWeb(response.body as any), {+ header: true,+ skipEmptyLines: true,+ worker: false,+ complete: (results) => {+ resolve(results);+ },+ error: reject,+ step: async (results: { data: Record<string, string> }, parser) => {+ parser.pause();+ rows.push(results.data);++ if (rows.length >= BATCH_SIZE) {+ await redis.lpush(`${redisKey}:rows`, ...rows);+ rows = [];+ }- parser.resume();- },- });+ parser.resume();+ },});+ });++ // Add any remaining rows to Redis+ if (rows.length > 0) {+ await redis.lpush(`${redisKey}:rows`, ...rows);+ }++ if ((await redis.llen(`import:csv:${workspaceId}:${id}:rows`)) === 0) {+ throw new Error("No rows to add to Redis.");+ }++ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,+ body: {+ ...payload,+ action: "process-links",+ },+ });+};++// Process rows in Redis+const processRows = async (payload: z.infer<typeof payloadSchema>) => {+ const { id, workspaceId, mapping } = payload;+ const redisKey = `import:csv:${workspaceId}:${id}`;+ const BATCH_SIZE = 500; // Process 500 links at a time++ const cursor = parseInt((await redis.get(`${redisKey}:cursor`)) || "0");++ const rows = await redis.lrange<Record<string, string>>(+ `${redisKey}:rows`,+ cursor,+ cursor + BATCH_SIZE - 1,+ );++ if (rows.length > 0) {+ const mappedLinks: MapperResult[] = rows.map((row) =>+ mapCsvRowToLink(row, mapping),+ );await processMappedLinks({mappedLinks,payload,});- // If we processed the maximum rows and haven't reached the end, trigger next batch- if (currentRow - cursor >= MAX_ROWS_PER_EXECUTION && !isComplete) {- // await qstash.publishJSON({- // url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,- // body: payload,- // });- } else {- const errorLinks = await redis.lrange<ErrorLink>(- `${redisKey}:failed`,- 0,- -1,- );-- const createdCount = parseInt(- (await redis.get(`${redisKey}:created`)) || "0",- );-- const domains = await redis.smembers(`${redisKey}:domains`);-- console.log({- domains,- createdCount,- errorLinks,- });+ const newCursor = cursor + rows.length;+ await redis.set(`${redisKey}:cursor`, newCursor);- await sendCsvImportEmails({- workspaceId,- count: createdCount,- domains,- errorLinks,+ if (rows.length === BATCH_SIZE) {+ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,+ body: {+ ...payload,+ action: "process-links",+ },});- const results = await Promise.allSettled([- redis.del(`${redisKey}:cursor`),- redis.del(`${redisKey}:created`),- redis.del(`${redisKey}:failed`),- redis.del(`${redisKey}:domains`),- storage.delete(url),- ]);-- results.forEach((result, idx) => {- if (result.status === "rejected") {- console.error(- `Error clearing CSV import data (${idx})`,- result.reason,- );- }- });+ return;}+ }- console.timeEnd("import:csv");+ // Finished processing all rows+ const errorLinks = await redis.lrange<ErrorLink>(`${redisKey}:failed`, 0, -1);- return NextResponse.json("OK");- } catch (error) {- await log({- message: `Error importing CSV links: ${error.message}`,- type: "cron",- });+ const createdCount = parseInt(+ (await redis.get(`${redisKey}:created`)) || "0",+ );- return handleAndReturnErrorResponse(error);- }-}+ const domains = await redis.smembers(`${redisKey}:domains`);++ await sendCsvImportEmails({+ workspaceId,+ count: createdCount,+ domains,+ errorLinks,+ });++ await Promise.allSettled([+ redis.del(`${redisKey}:cursor`),+ redis.del(`${redisKey}:created`),+ redis.del(`${redisKey}:failed`),+ redis.del(`${redisKey}:domains`),+ redis.del(`${redisKey}:rows`),+ storage.delete(payload.url),+ ]);+};+// Map a CSV row to a linkconst mapCsvRowToLink = (row: Record<string, string>,mapping: z.infer<typeof linkMappingSchema>,@@ -296,6 +319,7 @@ const mapCsvRowToLink = (}};+// Process the mapped links and create the tag/domain/link in the databaseconst processMappedLinks = async ({mappedLinks,payload,@@ -445,7 +469,7 @@ const processMappedLinks = async ({payload: {...createLinkBodySchema.parse({...link,- tagNames: tags || undefined,+ tagNames: tags || [],folderId,}),},diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 419bb7093d..3d33264cb5 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -123,7 +123,9 @@ export const POST = withWorkspace(});const workspaceTagIds = workspaceTags.map(({ id }) => id);- const workspaceTagNames = workspaceTags.map(({ name }) => name);+ const workspaceTagNames = workspaceTags.map(({ name }) =>+ name.toLowerCase(),+ );validLinks.forEach((link, index) => {const combinedTagIds =diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex 40415e1250..507da5c37f 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -102,6 +102,7 @@ export async function bulkCreateLinks({const allTagNames = [...new Set(links.flatMap((link) => link.tagNames).filter(Boolean)),] as string[];+const allTagIds = await prisma.tag.findMany({where: {projectId: links[0].projectId!,@@ -113,7 +114,7 @@ export async function bulkCreateLinks({tagNameToIdMap = allTagIds.reduce((acc, tag) => {- acc[tag.name] = tag.id;+ acc[tag.name.toLowerCase()] = tag.id;return acc;},{} as Record<string, string>,