Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

Replace database export jobs with Redis-based job storage

Cursor Agent4784ac13b6aa
diff --git a/EXPORT_VISITS_BACKGROUND_TASK.md b/EXPORT_VISITS_BACKGROUND_TASK.md
index ce6776a7..9df9832d 100644
--- a/EXPORT_VISITS_BACKGROUND_TASK.md
+++ b/EXPORT_VISITS_BACKGROUND_TASK.md
@@ -20,31 +20,33 @@ The export visits functionality has been converted from a synchronous API call t
- **Timeout**: 15 minutes maximum duration
- **Machine**: Medium-1x preset for more resources
-### 2. Database Schema
-A new `ExportJob` table has been added to track export jobs:
-
-```sql
-CREATE TABLE "ExportJob" (
- "id" TEXT NOT NULL,
- "type" TEXT NOT NULL,
- "status" "ExportStatus" NOT NULL DEFAULT 'PENDING',
- "resourceId" TEXT NOT NULL,
- "resourceName" TEXT,
- "groupId" TEXT,
- "result" TEXT,
- "error" TEXT,
- "userId" TEXT NOT NULL,
- "teamId" TEXT NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
- "completedAt" TIMESTAMP(3),
-
- CONSTRAINT "ExportJob_pkey" PRIMARY KEY ("id")
-);
+### 2. Redis Job Storage
+Export jobs are stored in Redis for fast access and automatic cleanup:
-CREATE TYPE "ExportStatus" AS ENUM ('PENDING', 'PROCESSING', 'COMPLETED', 'FAILED');
+```typescript
+interface ExportJob {
+ id: string;
+ type: "document" | "dataroom" | "dataroom-group";
+ status: "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
+ resourceId: string;
+ resourceName?: string;
+ groupId?: string;
+ result?: string; // CSV data
+ error?: string;
+ userId: string;
+ teamId: string;
+ createdAt: string;
+ updatedAt: string;
+ completedAt?: string;
+}
```
+**Benefits of Redis storage:**
+- **Fast access**: Redis is much faster than database queries
+- **Automatic cleanup**: Jobs expire after 7 days (configurable)
+- **No database migrations**: Uses existing Redis infrastructure
+- **Sorted job lists**: Jobs are automatically sorted by creation time
+
### 3. API Endpoints
#### Create Export Job
@@ -67,14 +69,7 @@ The frontend components now:
## Setup Instructions
-### 1. Database Migration
-Apply the database migration to add the export jobs table:
-
-```bash
-npx prisma migrate dev --name add-export-jobs --schema prisma/schema/schema.prisma
-```
-
-### 2. Environment Variables
+### 1. Environment Variables
Ensure your Trigger.dev environment variables are set:
```bash
@@ -82,14 +77,14 @@ TRIGGER_PROJECT_ID=your_project_id
TRIGGER_ACCESS_TOKEN=your_access_token
```
-### 3. Start Trigger.dev Development Server
+### 2. Start Trigger.dev Development Server
Run the Trigger.dev development server:
```bash
npm run trigger:v3:dev
```
-### 4. Deploy to Production
+### 3. Deploy to Production
When ready for production, deploy the Trigger.dev tasks:
```bash
@@ -112,7 +107,8 @@ You can adjust these values based on your Tinybird API limits and requirements.
## Monitoring
Export jobs can be monitored through:
-- Database queries on the `ExportJob` table
+- Redis commands to inspect job data (`HGETALL export_job:*`)
+- API endpoints for job listing and status
- Trigger.dev dashboard (if using Trigger.dev Cloud)
- Application logs
@@ -164,6 +160,8 @@ const blob = await response.blob();
## Migration Notes
+**No database migrations required!** This solution uses Redis for job storage.
+
The following endpoints have been changed from GET to POST:
- `/api/teams/[teamId]/documents/[id]/export-visits`
- `/api/teams/[teamId]/datarooms/[id]/export-visits`
diff --git a/export_jobs_migration.sql b/export_jobs_migration.sql
deleted file mode 100644
index 0247c824..00000000
--- a/export_jobs_migration.sql
+++ /dev/null
@@ -1,37 +0,0 @@
--- Migration: Add Export Jobs Table
--- This file adds the necessary tables and enums for the export visits background task system
-
--- Create the ExportStatus enum
-CREATE TYPE "ExportStatus" AS ENUM ('PENDING', 'PROCESSING', 'COMPLETED', 'FAILED');
-
--- Create the ExportJob table
-CREATE TABLE "ExportJob" (
- "id" TEXT NOT NULL,
- "type" TEXT NOT NULL,
- "status" "ExportStatus" NOT NULL DEFAULT 'PENDING',
- "resourceId" TEXT NOT NULL,
- "resourceName" TEXT,
- "groupId" TEXT,
- "result" TEXT,
- "error" TEXT,
- "userId" TEXT NOT NULL,
- "teamId" TEXT NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
- "completedAt" TIMESTAMP(3),
-
- CONSTRAINT "ExportJob_pkey" PRIMARY KEY ("id")
-);
-
--- Create indexes for better performance
-CREATE INDEX "ExportJob_userId_idx" ON "ExportJob"("userId");
-CREATE INDEX "ExportJob_teamId_idx" ON "ExportJob"("teamId");
-CREATE INDEX "ExportJob_status_idx" ON "ExportJob"("status");
-CREATE INDEX "ExportJob_createdAt_idx" ON "ExportJob"("createdAt");
-
--- Add foreign key constraints
-ALTER TABLE "ExportJob" ADD CONSTRAINT "ExportJob_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-ALTER TABLE "ExportJob" ADD CONSTRAINT "ExportJob_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- Update the default timestamp for updatedAt
-ALTER TABLE "ExportJob" ALTER COLUMN "updatedAt" SET DEFAULT CURRENT_TIMESTAMP;
\ No newline at end of file
diff --git a/lib/redis-job-store.ts b/lib/redis-job-store.ts
new file mode 100644
index 00000000..236cae48
--- /dev/null
+++ b/lib/redis-job-store.ts
@@ -0,0 +1,176 @@
+import { nanoid } from "nanoid";
+import { redis } from "./redis";
+
+export type ExportJobStatus = "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
+
+export interface ExportJob {
+ id: string;
+ type: "document" | "dataroom" | "dataroom-group";
+ status: ExportJobStatus;
+ resourceId: string;
+ resourceName?: string;
+ groupId?: string;
+ result?: string; // CSV data
+ error?: string;
+ userId: string;
+ teamId: string;
+ createdAt: string;
+ updatedAt: string;
+ completedAt?: string;
+}
+
+const JOB_PREFIX = "export_job:";
+const USER_JOBS_PREFIX = "user_jobs:";
+const TEAM_JOBS_PREFIX = "team_jobs:";
+const JOB_TTL = 60 * 60 * 24 * 7; // 7 days
+
+export class RedisJobStore {
+ private getJobKey(jobId: string): string {
+ return `${JOB_PREFIX}${jobId}`;
+ }
+
+ private getUserJobsKey(userId: string): string {
+ return `${USER_JOBS_PREFIX}${userId}`;
+ }
+
+ private getTeamJobsKey(teamId: string): string {
+ return `${TEAM_JOBS_PREFIX}${teamId}`;
+ }
+
+ async createJob(jobData: Omit<ExportJob, "id" | "createdAt" | "updatedAt">): Promise<ExportJob> {
+ const jobId = nanoid();
+ const now = new Date().toISOString();
+
+ const job: ExportJob = {
+ ...jobData,
+ id: jobId,
+ createdAt: now,
+ updatedAt: now,
+ };
+
+ const jobKey = this.getJobKey(jobId);
+ const userJobsKey = this.getUserJobsKey(jobData.userId);
+ const teamJobsKey = this.getTeamJobsKey(jobData.teamId);
+
+ // Store job data with TTL
+ await redis.setex(jobKey, JOB_TTL, JSON.stringify(job));
+
+ // Add to user's job list (sorted by creation time)
+ await redis.zadd(userJobsKey, Date.now(), jobId);
+ await redis.expire(userJobsKey, JOB_TTL);
+
+ // Add to team's job list (sorted by creation time)
+ await redis.zadd(teamJobsKey, Date.now(), jobId);
+ await redis.expire(teamJobsKey, JOB_TTL);
+
+ return job;
+ }
+
+ async getJob(jobId: string): Promise<ExportJob | null> {
+ const jobKey = this.getJobKey(jobId);
+ const jobData = await redis.get(jobKey);
+
+ if (!jobData) {
+ return null;
+ }
+
+ try {
+ return JSON.parse(jobData);
+ } catch (error) {
+ console.error("Error parsing job data:", error);
+ return null;
+ }
+ }
+
+ async updateJob(jobId: string, updates: Partial<ExportJob>): Promise<ExportJob | null> {
+ const job = await this.getJob(jobId);
+ if (!job) {
+ return null;
+ }
+
+ const updatedJob: ExportJob = {
+ ...job,
+ ...updates,
+ updatedAt: new Date().toISOString(),
+ };
+
+ const jobKey = this.getJobKey(jobId);
+ await redis.setex(jobKey, JOB_TTL, JSON.stringify(updatedJob));
+
+ return updatedJob;
+ }
+
+ async deleteJob(jobId: string): Promise<boolean> {
+ const job = await this.getJob(jobId);
+ if (!job) {
+ return false;
+ }
+
+ const jobKey = this.getJobKey(jobId);
+ const userJobsKey = this.getUserJobsKey(job.userId);
+ const teamJobsKey = this.getTeamJobsKey(job.teamId);
+
+ // Remove from all locations
+ await Promise.all([
+ redis.del(jobKey),
+ redis.zrem(userJobsKey, jobId),
+ redis.zrem(teamJobsKey, jobId),
+ ]);
+
+ return true;
+ }
+
+ async getUserJobs(userId: string, limit: number = 20): Promise<ExportJob[]> {
+ const userJobsKey = this.getUserJobsKey(userId);
+
+ // Get job IDs sorted by creation time (newest first)
+ const jobIds = await redis.zrevrange(userJobsKey, 0, limit - 1);
+
+ if (!jobIds.length) {
+ return [];
+ }
+
+ // Get all job data
+ const jobs = await Promise.all(
+ jobIds.map(jobId => this.getJob(jobId))
+ );
+
+ // Filter out null values (deleted jobs)
+ return jobs.filter((job): job is ExportJob => job !== null);
+ }
+
+ async getTeamJobs(teamId: string, limit: number = 20): Promise<ExportJob[]> {
+ const teamJobsKey = this.getTeamJobsKey(teamId);
+
+ // Get job IDs sorted by creation time (newest first)
+ const jobIds = await redis.zrevrange(teamJobsKey, 0, limit - 1);
+
+ if (!jobIds.length) {
+ return [];
+ }
+
+ // Get all job data
+ const jobs = await Promise.all(
+ jobIds.map(jobId => this.getJob(jobId))
+ );
+
+ // Filter out null values (deleted jobs)
+ return jobs.filter((job): job is ExportJob => job !== null);
+ }
+
+ async getUserTeamJobs(userId: string, teamId: string, limit: number = 20): Promise<ExportJob[]> {
+ const userJobs = await this.getUserJobs(userId, limit * 2); // Get more to filter
+
+ // Filter jobs by team
+ return userJobs
+ .filter(job => job.teamId === teamId)
+ .slice(0, limit);
+ }
+
+ async cleanupExpiredJobs(): Promise<void> {
+ // This would be called by a cron job or cleanup task
+ // For now, we rely on Redis TTL for automatic cleanup
+ }
+}
+
+export const jobStore = new RedisJobStore();
\ No newline at end of file
diff --git a/lib/trigger/export-visits.ts b/lib/trigger/export-visits.ts
index 481d4b46..cb2d6ce0 100644
--- a/lib/trigger/export-visits.ts
+++ b/lib/trigger/export-visits.ts
@@ -2,6 +2,7 @@ import { logger, task } from "@trigger.dev/sdk/v3";
import Bottleneck from "bottleneck";
import prisma from "@/lib/prisma";
+import { jobStore } from "@/lib/redis-job-store";
import {
getViewPageDuration,
getViewUserAgent,
@@ -37,10 +38,7 @@ export const exportVisitsTask = task({
try {
// Update job status to processing
- await prisma.exportJob.update({
- where: { id: exportId },
- data: { status: "PROCESSING" },
- });
+ await jobStore.updateJob(exportId, { status: "PROCESSING" });
// Verify team access
const team = await prisma.team.findUnique({
@@ -74,15 +72,12 @@ export const exportVisitsTask = task({
throw new Error("Invalid export type");
}
- // Store the result in the database
- await prisma.exportJob.update({
- where: { id: exportId },
- data: {
- status: "COMPLETED",
- result: csvData,
- resourceName,
- completedAt: new Date(),
- },
+ // Store the result in Redis
+ await jobStore.updateJob(exportId, {
+ status: "COMPLETED",
+ result: csvData,
+ resourceName,
+ completedAt: new Date().toISOString(),
});
logger.info("Export visits task completed successfully", {
@@ -105,12 +100,9 @@ export const exportVisitsTask = task({
});
// Update job status to failed
- await prisma.exportJob.update({
- where: { id: exportId },
- data: {
- status: "FAILED",
- error: error instanceof Error ? error.message : String(error),
- },
+ await jobStore.updateJob(exportId, {
+ status: "FAILED",
+ error: error instanceof Error ? error.message : String(error),
});
throw error;
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/export-visits.ts b/pages/api/teams/[teamId]/datarooms/[id]/export-visits.ts
index 89d243d6..59ff282e 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/export-visits.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/export-visits.ts
@@ -3,8 +3,9 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
-import prisma from "@/lib/prisma";
+import { jobStore } from "@/lib/redis-job-store";
import { exportVisitsTask } from "@/lib/trigger/export-visits";
+import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
export default async function handler(
@@ -68,15 +69,13 @@ export default async function handler(
}
// Create export job record
- const exportJob = await prisma.exportJob.create({
- data: {
- type: "dataroom",
- resourceId: dataroomId,
- resourceName: dataroom.name,
- userId,
- teamId,
- status: "PENDING",
- },
+ const exportJob = await jobStore.createJob({
+ type: "dataroom",
+ resourceId: dataroomId,
+ resourceName: dataroom.name,
+ userId,
+ teamId,
+ status: "PENDING",
});
// Trigger the background task
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts
index 29efada7..7f2bc13c 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts
@@ -3,8 +3,9 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
-import prisma from "@/lib/prisma";
+import { jobStore } from "@/lib/redis-job-store";
import { exportVisitsTask } from "@/lib/trigger/export-visits";
+import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
export default async function handler(
@@ -73,16 +74,14 @@ export default async function handler(
}
// Create export job record
- const exportJob = await prisma.exportJob.create({
- data: {
- type: "dataroom",
- resourceId: dataroomId,
- resourceName: dataroom.name,
- groupId,
- userId,
- teamId,
- status: "PENDING",
- },
+ const exportJob = await jobStore.createJob({
+ type: "dataroom",
+ resourceId: dataroomId,
+ resourceName: dataroom.name,
+ groupId,
+ userId,
+ teamId,
+ status: "PENDING",
});
// Trigger the background task
diff --git a/pages/api/teams/[teamId]/documents/[id]/export-visits.ts b/pages/api/teams/[teamId]/documents/[id]/export-visits.ts
index 799689df..ef30bde8 100644
--- a/pages/api/teams/[teamId]/documents/[id]/export-visits.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/export-visits.ts
@@ -3,8 +3,9 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
-import prisma from "@/lib/prisma";
+import { jobStore } from "@/lib/redis-job-store";
import { exportVisitsTask } from "@/lib/trigger/export-visits";
+import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
export default async function handler(
@@ -65,15 +66,13 @@ export default async function handler(
}
// Create export job record
- const exportJob = await prisma.exportJob.create({
- data: {
- type: "document",
- resourceId: docId,
- resourceName: document.name,
- userId,
- teamId,
- status: "PENDING",
- },
+ const exportJob = await jobStore.createJob({
+ type: "document",
+ resourceId: docId,
+ resourceName: document.name,
+ userId,
+ teamId,
+ status: "PENDING",
});
// Trigger the background task
diff --git a/pages/api/teams/[teamId]/export-jobs.ts b/pages/api/teams/[teamId]/export-jobs.ts
index 4752165a..f0d5eae9 100644
--- a/pages/api/teams/[teamId]/export-jobs.ts
+++ b/pages/api/teams/[teamId]/export-jobs.ts
@@ -1,10 +1,10 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { nanoid } from "nanoid";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
import { exportVisitsTask } from "@/lib/trigger/export-visits";
+import { jobStore } from "@/lib/redis-job-store";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
@@ -57,15 +57,13 @@ export default async function handler(
}
// Create export job record
- const exportJob = await prisma.exportJob.create({
- data: {
- type,
- resourceId,
- groupId,
- userId,
- teamId,
- status: "PENDING",
- },
+ const exportJob = await jobStore.createJob({
+ type,
+ resourceId,
+ groupId,
+ userId,
+ teamId,
+ status: "PENDING",
});
// Trigger the background task
@@ -102,16 +100,7 @@ export default async function handler(
if (req.method === "GET") {
// Get export jobs for the team
try {
- const exportJobs = await prisma.exportJob.findMany({
- where: {
- teamId,
- userId,
- },
- orderBy: {
- createdAt: "desc",
- },
- take: 20, // Limit to last 20 jobs
- });
+ const exportJobs = await jobStore.getUserTeamJobs(userId, teamId, 20);
return res.status(200).json(exportJobs);
} catch (error) {
diff --git a/pages/api/teams/[teamId]/export-jobs/[exportId].ts b/pages/api/teams/[teamId]/export-jobs/[exportId].ts
index 9cbe53c1..87a66033 100644
--- a/pages/api/teams/[teamId]/export-jobs/[exportId].ts
+++ b/pages/api/teams/[teamId]/export-jobs/[exportId].ts
@@ -3,7 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
-import prisma from "@/lib/prisma";
+import { jobStore } from "@/lib/redis-job-store";
import { CustomUser } from "@/lib/types";
export default async function handler(
@@ -24,15 +24,9 @@ export default async function handler(
if (req.method === "GET") {
try {
// Get export job details
- const exportJob = await prisma.exportJob.findUnique({
- where: {
- id: exportId,
- teamId,
- userId,
- },
- });
+ const exportJob = await jobStore.getJob(exportId);
- if (!exportJob) {
+ if (!exportJob || exportJob.teamId !== teamId || exportJob.userId !== userId) {
return res.status(404).json({ error: "Export job not found" });
}
@@ -74,14 +68,15 @@ export default async function handler(
if (req.method === "DELETE") {
try {
+ // Get the job first to verify ownership
+ const exportJob = await jobStore.getJob(exportId);
+
+ if (!exportJob || exportJob.teamId !== teamId || exportJob.userId !== userId) {
+ return res.status(404).json({ error: "Export job not found" });
+ }
+
// Delete export job
- await prisma.exportJob.delete({
- where: {
- id: exportId,
- teamId,
- userId,
- },
- });
+ await jobStore.deleteJob(exportId);
return res.status(200).json({ message: "Export job deleted successfully" });
} catch (error) {
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 82ec6596..843b94eb 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -62,9 +62,6 @@ model User {
// conversation
participatedConversations ConversationParticipant[]
messages Message[]
-
- // export jobs
- exportJobs ExportJob[]
}
model Team {
@@ -101,9 +98,6 @@ model Team {
restrictedTokens RestrictedToken[]
webhooks Webhook[]
- // export jobs
- exportJobs ExportJob[]
-
conversations Conversation[]
uploadedDocuments DocumentUpload[]
@@ -138,13 +132,6 @@ enum Role {
MEMBER
}
-enum ExportStatus {
- PENDING
- PROCESSING
- COMPLETED
- FAILED
-}
-
model UserTeam {
role Role @default(MEMBER)
status String @default("ACTIVE")
@@ -656,28 +643,4 @@ model TagItem {
@@index([tagId, dataroomId])
}
-model ExportJob {
- id String @id @default(cuid())
- type String // "document" | "dataroom" | "dataroom-group"
- status ExportStatus @default(PENDING)
- resourceId String // document ID or dataroom ID
- resourceName String? // document name or dataroom name
- groupId String? // for dataroom groups
- result String? @db.Text // CSV data
- error String? // error message if failed
-
- userId String
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
-
- teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- completedAt DateTime?
-
- @@index([userId])
- @@index([teamId])
- @@index([status])
- @@index([createdAt])
-}
+