-
Notifications
You must be signed in to change notification settings - Fork 0
OUT-3065 | Resync files that are failed to upload #86
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a605c56
fix(OUT-3065): added an api to resync files failed to upload on assembly
arpandhakal b4a48ba
fix(OUT-3065): added an api to resync files failed to upload on assembly
arpandhakal 2e42d54
fix(OUT-3065): renamed the worker route
arpandhakal c01c407
fix(OUT-3065): applied requested changes
arpandhakal 2fa0ada
fix(OUT-3065): applied cron job in a new vercel.json file
arpandhakal 2cf3d7f
fix(OUT-3065): applied cron job in a new vercel.json file
arpandhakal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import { resyncFailedFiles } from '@/features/workers/resync-failed-files/api/resync-failed-files.controller' | ||
| import { withErrorHandler } from '@/utils/withErrorHandler' | ||
|
|
||
| export const maxDuration = 300 | ||
|
|
||
| export const GET = withErrorHandler(resyncFailedFiles) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
src/features/workers/resync-failed-files/api/resync-failed-files.controller.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import httpStatus from 'http-status' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import env from '@/config/server.env' | ||
| import APIError from '@/errors/APIError' | ||
| import { ResyncService } from '@/features/workers/resync-failed-files/lib/resync-failed-files.service' | ||
|
|
||
| export const resyncFailedFiles = async (request: NextRequest) => { | ||
| const authHeader = request.headers.get('authorization') | ||
| if (authHeader !== `Bearer ${env.CRON_SECRET}`) { | ||
| throw new APIError('Unauthorized', httpStatus.UNAUTHORIZED) | ||
| } | ||
|
|
||
| const resyncService = new ResyncService() | ||
| await resyncService.resyncFailedFiles() | ||
| return NextResponse.json({ message: 'Succeslyfully trigger re syncing of files.' }) | ||
| } |
126 changes: 126 additions & 0 deletions
126
src/features/workers/resync-failed-files/helper/resync-failed-files.helper.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import { and, eq } from 'drizzle-orm' | ||
| import z from 'zod' | ||
| import env from '@/config/server.env' | ||
| import db from '@/db' | ||
| import { type FileSyncSelectType, fileFolderSync } from '@/db/schema/fileFolderSync.schema' | ||
| import APIError from '@/errors/APIError' | ||
| import { SyncService } from '@/features/sync/lib/Sync.service' | ||
| import { DropboxFileListFolderSingleEntrySchema } from '@/features/sync/types' | ||
| import { CopilotAPI } from '@/lib/copilot/CopilotAPI' | ||
| import { generateToken } from '@/lib/copilot/generateToken' | ||
| import User from '@/lib/copilot/models/User.model' | ||
| import { DropboxClient } from '@/lib/dropbox/DropboxClient' | ||
|
|
||
| export const syncFailedFilesToAssembly = async ( | ||
| portalId: string, | ||
| failedSyncs: FileSyncSelectType[], | ||
| ) => { | ||
| const dropboxConnection = await getDropboxConnection(portalId) | ||
| if (!dropboxConnection) { | ||
| console.warn('Dropbox account not found for portal:', portalId) | ||
| return null | ||
| } | ||
|
|
||
| const { user, copilotApi, dbxClient, connectionToken, syncService } = | ||
| await initializeSyncDependencies(dropboxConnection, portalId) | ||
|
|
||
| for (const failedSync of failedSyncs) { | ||
| await processFailedSync(failedSync, copilotApi, dbxClient, syncService, user, connectionToken) | ||
| } | ||
| } | ||
|
|
||
| const getDropboxConnection = async (portalId: string) => { | ||
| const connection = await db.query.dropboxConnections.findFirst({ | ||
| where: (dropboxConnections, { eq }) => | ||
| and(eq(dropboxConnections.portalId, portalId), eq(dropboxConnections.status, true)), | ||
| }) | ||
|
|
||
| if (!connection?.refreshToken || !connection?.accountId) { | ||
| console.error('⚠️ Dropbox connection not found for portal:', portalId) | ||
| return null | ||
| } | ||
|
|
||
| return connection | ||
| } | ||
|
|
||
| const initializeSyncDependencies = async ( | ||
| dropboxConnection: NonNullable<Awaited<ReturnType<typeof getDropboxConnection>>>, | ||
| portalId: string, | ||
| ) => { | ||
| const { refreshToken, rootNamespaceId, accountId, initiatedBy } = dropboxConnection | ||
|
|
||
| if (!refreshToken || !accountId || !rootNamespaceId) { | ||
| throw new APIError(`Dropbox connection not found for portal: ${portalId}`, 404) | ||
| } | ||
|
|
||
| const token = generateToken(env.COPILOT_API_KEY, { | ||
| workspaceId: portalId, | ||
| internalUserId: initiatedBy, | ||
| }) | ||
|
|
||
| const user = await User.authenticate(token) | ||
| const copilotApi = new CopilotAPI(token) | ||
| const dbxClient = new DropboxClient(refreshToken, rootNamespaceId) | ||
|
|
||
| const connectionToken = { | ||
| refreshToken, | ||
| accountId, | ||
| rootNamespaceId, | ||
| } | ||
|
|
||
| const syncService = new SyncService(user, connectionToken) | ||
|
|
||
| return { user, copilotApi, dbxClient, connectionToken, syncService } | ||
| } | ||
|
|
||
| const processFailedSync = async ( | ||
| failedSync: FileSyncSelectType, | ||
| copilotApi: CopilotAPI, | ||
| dbxClient: DropboxClient, | ||
| syncService: SyncService, | ||
| user: Awaited<ReturnType<typeof User.authenticate>>, | ||
| connectionToken: { refreshToken: string; accountId: string; rootNamespaceId: string }, | ||
| ) => { | ||
| const fileId = z.string().parse(failedSync.assemblyFileId) | ||
| const file = await copilotApi.retrieveFile(fileId) | ||
|
|
||
| // Only proceed if file is missing or pending in Assembly | ||
| if (file && file.status !== 'pending') return | ||
|
|
||
| const fileInDropbox = await getFileFromDropbox(dbxClient, failedSync.dbxFileId ?? '') | ||
| if (!fileInDropbox) return | ||
|
|
||
| const channelSync = await db.query.channelSync.findFirst({ | ||
| where: (channelSync, { eq }) => eq(channelSync.id, failedSync.channelSyncId), | ||
| }) | ||
|
|
||
| if (!channelSync) return | ||
|
|
||
| // Sync file from Dropbox to Assembly | ||
| const payload = { | ||
| entry: DropboxFileListFolderSingleEntrySchema.parse(fileInDropbox), | ||
| opts: { | ||
| dbxRootPath: channelSync.dbxRootPath, | ||
| assemblyChannelId: channelSync.assemblyChannelId, | ||
| channelSyncId: channelSync.id, | ||
| user, | ||
| connectionToken, | ||
| }, | ||
| } | ||
|
|
||
| await syncService.syncDropboxFilesToAssembly(payload) | ||
| await db.delete(fileFolderSync).where(eq(fileFolderSync.id, failedSync.id)) | ||
| } | ||
|
|
||
| const getFileFromDropbox = async (dbxClient: DropboxClient, dropboxFileId: string) => { | ||
| if (!dropboxFileId) return null | ||
|
|
||
| const dropboxClient = dbxClient.getDropboxClient() | ||
|
|
||
| try { | ||
| const fileMetadata = await dropboxClient.filesGetMetadata({ path: dropboxFileId }) | ||
| return fileMetadata.result | ||
| } catch (_err) { | ||
| return null | ||
| } | ||
| } |
44 changes: 44 additions & 0 deletions
44
src/features/workers/resync-failed-files/lib/resync-failed-files.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { and, isNull } from 'drizzle-orm' | ||
| import db from '@/db' | ||
| import { ObjectType } from '@/db/constants' | ||
| import { resyncFailedFilesInAssembly } from '@/trigger/processFileSync' | ||
| import type { FailedSyncWorkspaceMap } from '../utils/types' | ||
|
|
||
| export class ResyncService { | ||
| async resyncFailedFiles() { | ||
| const failedSyncs = await db.query.fileFolderSync.findMany({ | ||
| where: (fileFolderSync, { eq }) => | ||
| and( | ||
| isNull(fileFolderSync.contentHash), | ||
| eq(fileFolderSync.object, ObjectType.FILE), | ||
| isNull(fileFolderSync.deletedAt), | ||
| ), | ||
| }) | ||
|
|
||
| console.info('Total number of failed syncs: ', failedSyncs.length) | ||
| const failedSyncWorkspaceMap: FailedSyncWorkspaceMap = failedSyncs.reduce( | ||
| (acc: FailedSyncWorkspaceMap, failedSync) => { | ||
| const portalId = failedSync.portalId | ||
|
|
||
| if (!acc[portalId]) { | ||
| acc[portalId] = [] | ||
| } | ||
|
|
||
| acc[portalId].push(failedSync) | ||
| return acc | ||
| }, | ||
| {}, | ||
| ) | ||
|
|
||
| for (const portalId in failedSyncWorkspaceMap) { | ||
| const failedSyncsForPortal = failedSyncWorkspaceMap[portalId] | ||
| resyncFailedFilesInAssembly.trigger({ | ||
| portalId, | ||
| failedSyncs: failedSyncsForPortal, | ||
| }) | ||
| console.info( | ||
| `Enqueued resync job for portal: ${portalId} with ${failedSyncsForPortal.length} files`, | ||
| ) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import type { FileSyncSelectType } from '@/db/schema/fileFolderSync.schema' | ||
|
|
||
| export type FailedSyncWorkspaceMap = Record<string, FileSyncSelectType[]> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "$schema": "https://openapi.vercel.sh/vercel.json", | ||
| "regions": ["iad1", "pdx1"], | ||
| "buildCommand": "./scripts/build/build.sh", | ||
| "crons": [ | ||
| { | ||
| "path": "/api/workers/resync-failed-files", | ||
| "schedule": "0 0 * * *" | ||
| } | ||
| ] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should also consider defining
machinehere since single portal could have many files and can be long running as well. We haveTRIGGER_MACHINEenv that you can import fromserver.env.tsfile and use that here.