|
| 1 | +import { WorkflowEntrypoint, WorkflowStep } from 'cloudflare:workers'; |
| 2 | +import { connectionToDriver } from '../lib/server-utils'; |
| 3 | +import type { WorkflowEvent } from 'cloudflare:workers'; |
| 4 | +import { connection } from '../db/schema'; |
| 5 | +import type { ZeroEnv } from '../env'; |
| 6 | +import { eq } from 'drizzle-orm'; |
| 7 | +import { createDb } from '../db'; |
| 8 | + |
| 9 | +export interface SyncThreadsCoordinatorParams { |
| 10 | + connectionId: string; |
| 11 | + folder: string; |
| 12 | +} |
| 13 | + |
| 14 | +export interface SyncThreadsCoordinatorResult { |
| 15 | + totalSynced: number; |
| 16 | + message: string; |
| 17 | + folder: string; |
| 18 | + totalPagesProcessed: number; |
| 19 | + totalThreads: number; |
| 20 | + totalSuccessfulSyncs: number; |
| 21 | + totalFailedSyncs: number; |
| 22 | + pageWorkflowResults: Array<{ |
| 23 | + pageNumber: number; |
| 24 | + workflowId: string; |
| 25 | + status: 'completed' | 'failed'; |
| 26 | + synced: number; |
| 27 | + error?: string; |
| 28 | + }>; |
| 29 | +} |
| 30 | + |
| 31 | +export class SyncThreadsCoordinatorWorkflow extends WorkflowEntrypoint< |
| 32 | + ZeroEnv, |
| 33 | + SyncThreadsCoordinatorParams |
| 34 | +> { |
| 35 | + async run( |
| 36 | + event: WorkflowEvent<SyncThreadsCoordinatorParams>, |
| 37 | + step: WorkflowStep, |
| 38 | + ): Promise<SyncThreadsCoordinatorResult> { |
| 39 | + const { connectionId, folder } = event.payload; |
| 40 | + |
| 41 | + console.info( |
| 42 | + `[SyncThreadsCoordinatorWorkflow] Starting coordination for connection ${connectionId}, folder ${folder}`, |
| 43 | + ); |
| 44 | + |
| 45 | + const result: SyncThreadsCoordinatorResult = { |
| 46 | + totalSynced: 0, |
| 47 | + message: 'Coordination completed', |
| 48 | + folder, |
| 49 | + totalPagesProcessed: 0, |
| 50 | + totalThreads: 0, |
| 51 | + totalSuccessfulSyncs: 0, |
| 52 | + totalFailedSyncs: 0, |
| 53 | + pageWorkflowResults: [], |
| 54 | + }; |
| 55 | + |
| 56 | + const setupResult = await step.do(`setup-connection-${connectionId}-${folder}`, async () => { |
| 57 | + const { db, conn } = createDb(this.env.HYPERDRIVE.connectionString); |
| 58 | + |
| 59 | + const foundConnection = await db.query.connection.findFirst({ |
| 60 | + where: eq(connection.id, connectionId), |
| 61 | + }); |
| 62 | + |
| 63 | + await conn.end(); |
| 64 | + |
| 65 | + if (!foundConnection) { |
| 66 | + throw new Error(`Connection ${connectionId} not found`); |
| 67 | + } |
| 68 | + |
| 69 | + const maxCount = parseInt(this.env.THREAD_SYNC_MAX_COUNT || '20'); |
| 70 | + const shouldLoop = true; |
| 71 | + |
| 72 | + return { maxCount, shouldLoop, foundConnection }; |
| 73 | + }); |
| 74 | + |
| 75 | + const { maxCount, shouldLoop, foundConnection } = setupResult as { |
| 76 | + maxCount: number; |
| 77 | + shouldLoop: boolean; |
| 78 | + foundConnection: any; |
| 79 | + }; |
| 80 | + const driver = connectionToDriver(foundConnection); |
| 81 | + |
| 82 | + if (connectionId.includes('aggregate')) { |
| 83 | + console.info( |
| 84 | + `[SyncThreadsCoordinatorWorkflow] Skipping sync for aggregate instance - folder ${folder}`, |
| 85 | + ); |
| 86 | + result.message = 'Skipped aggregate instance'; |
| 87 | + return result; |
| 88 | + } |
| 89 | + |
| 90 | + if (!driver) { |
| 91 | + console.warn(`[SyncThreadsCoordinatorWorkflow] No driver available for folder ${folder}`); |
| 92 | + result.message = 'No driver available'; |
| 93 | + return result; |
| 94 | + } |
| 95 | + |
| 96 | + // Process pages sequentially |
| 97 | + let currentPageToken: string | null = null; |
| 98 | + let pageNumber = 0; |
| 99 | + |
| 100 | + do { |
| 101 | + pageNumber++; |
| 102 | + |
| 103 | + // Process this page |
| 104 | + const pageResult = await step.do( |
| 105 | + `process-page-${pageNumber}-${folder}-${connectionId}`, |
| 106 | + async () => { |
| 107 | + console.info( |
| 108 | + `[SyncThreadsCoordinatorWorkflow] Processing page ${pageNumber} for ${folder}`, |
| 109 | + ); |
| 110 | + |
| 111 | + // Create workflow for this page |
| 112 | + const instance = await this.env.SYNC_THREADS_WORKFLOW.create({ |
| 113 | + params: { |
| 114 | + connectionId, |
| 115 | + folder, |
| 116 | + pageNumber, |
| 117 | + pageToken: currentPageToken, |
| 118 | + maxCount, |
| 119 | + singlePageMode: true, |
| 120 | + }, |
| 121 | + }); |
| 122 | + |
| 123 | + console.info( |
| 124 | + `[SyncThreadsCoordinatorWorkflow] Created workflow ${instance.id} for page ${pageNumber}`, |
| 125 | + ); |
| 126 | + |
| 127 | + // Simple polling to wait for completion |
| 128 | + let attempts = 0; |
| 129 | + const maxAttempts = 60; // 5 minutes |
| 130 | + |
| 131 | + while (attempts < maxAttempts) { |
| 132 | + await new Promise((resolve) => setTimeout(resolve, 5000)); |
| 133 | + |
| 134 | + try { |
| 135 | + const status = await instance.status(); |
| 136 | + if (status.status === 'complete') { |
| 137 | + return { result: status.output, workflowId: instance.id }; |
| 138 | + } else if (status.status === 'errored') { |
| 139 | + throw new Error(`Workflow ${instance.id} failed`); |
| 140 | + } |
| 141 | + } catch (error) { |
| 142 | + if (attempts === maxAttempts - 1) { |
| 143 | + throw error; |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + attempts++; |
| 148 | + } |
| 149 | + |
| 150 | + throw new Error(`Workflow ${instance.id} timed out`); |
| 151 | + }, |
| 152 | + ); |
| 153 | + |
| 154 | + // Update result with this page's data |
| 155 | + if (pageResult?.result) { |
| 156 | + const workflowResult = pageResult.result as any; |
| 157 | + result.pageWorkflowResults.push({ |
| 158 | + pageNumber, |
| 159 | + workflowId: pageResult.workflowId, |
| 160 | + status: 'completed', |
| 161 | + synced: workflowResult.synced || 0, |
| 162 | + }); |
| 163 | + |
| 164 | + result.totalSynced += workflowResult.synced || 0; |
| 165 | + result.totalPagesProcessed += 1; |
| 166 | + result.totalThreads += workflowResult.totalThreads || 0; |
| 167 | + result.totalSuccessfulSyncs += workflowResult.successfulSyncs || 0; |
| 168 | + result.totalFailedSyncs += workflowResult.failedSyncs || 0; |
| 169 | + |
| 170 | + // Get next page token from workflow result if available |
| 171 | + currentPageToken = workflowResult.nextPageToken || null; |
| 172 | + } else { |
| 173 | + // If no result, we can't continue |
| 174 | + break; |
| 175 | + } |
| 176 | + |
| 177 | + // If no more pages, stop |
| 178 | + if (!currentPageToken) { |
| 179 | + console.info(`[SyncThreadsCoordinatorWorkflow] No more pages for ${folder}`); |
| 180 | + break; |
| 181 | + } |
| 182 | + } while (currentPageToken && shouldLoop); |
| 183 | + |
| 184 | + console.info( |
| 185 | + `[SyncThreadsCoordinatorWorkflow] Completed ${folder}: ${result.totalSynced} synced across ${result.totalPagesProcessed} pages`, |
| 186 | + ); |
| 187 | + |
| 188 | + return result; |
| 189 | + } |
| 190 | +} |
0 commit comments