The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Fix Fathom imports that silently lose data (#27663)
nitin4421496c1b94
diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.tsindex e5599a605a8..fdc8dfeef0a 100644--- a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts+++ b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts@@ -30,3 +30,5 @@ export const FATHOM_MEDIA_RECONCILIATION_GRACE_PERIOD_MILLISECONDS =export const FATHOM_MEDIA_RECONCILIATION_PAGE_SIZE = 200;export const FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN = '30 3 * * *';export const FATHOM_MEDIA_RECONCILIATION_BATCH_SIZE = 5;+export const FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASS_DELAY_MILLISECONDS = 60_000;+export const MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES = 100;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-worker.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-worker.test.tsnew file mode 100644index 00000000000..dfbc7171a42--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-worker.test.ts@@ -0,0 +1,71 @@+import { ConnectionError } from 'fathom-typescript/sdk/models/errors';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';+import { buildFathomServerError } from 'src/__tests__/utils/build-fathom-server-error.util';++const mocks = vi.hoisted(() => ({+ enqueueJobs: vi.fn(),+ getConnection: vi.fn(),+ listMeetings: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),+ enqueueJobs: mocks.enqueueJobs,+ getConnection: mocks.getConnection,+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ listMeetings = mocks.listMeetings;+ },+}));++const { fathomBackfillWorkerHandler } =+ await import('src/logic-functions/fathom-backfill-worker');++const PAYLOAD = { connectedAccountId: 'connection-1', days: 31 };++describe('fathomBackfillWorkerHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.getConnection.mockResolvedValue({+ id: 'connection-1',+ accessToken: 'token-1',+ });+ });++ it.each([+ { description: 'a Fathom outage', error: buildFathomServerError() },+ {+ description: 'a network failure',+ error: new ConnectionError('connection refused'),+ },+ ])(+ 'asks the platform to retry the page after $description',+ async ({ error }) => {+ mocks.listMeetings.mockRejectedValue(error);++ await expect(fathomBackfillWorkerHandler(PAYLOAD)).rejects.toBeInstanceOf(+ RetryableLogicFunctionError,+ );+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ },+ );++ it('does not retry a page Fathom rejects permanently', async () => {+ const notFoundError = buildFathomNotFoundError();++ mocks.listMeetings.mockRejectedValue(notFoundError);++ await expect(fathomBackfillWorkerHandler(PAYLOAD)).rejects.toBe(+ notFoundError,+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-reconcile-media-imports.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-reconcile-media-imports.test.tsnew file mode 100644index 00000000000..04202ee94d6--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-reconcile-media-imports.test.ts@@ -0,0 +1,128 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASS_DELAY_MILLISECONDS,+ MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES,+} from 'src/constants/fathom.constant';+import { FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++const mocks = vi.hoisted(() => ({+ cleanupDisconnectedFathomMediaImports: vi.fn(),+ enqueueJobs: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),+ enqueueJobs: mocks.enqueueJobs,+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {},+}));++vi.mock(+ 'src/logic-functions/utils/cleanup-disconnected-fathom-media-imports.util',+ () => ({+ cleanupDisconnectedFathomMediaImports:+ mocks.cleanupDisconnectedFathomMediaImports,+ }),+);++const { fathomReconcileMediaImportsHandler } =+ await import('src/logic-functions/fathom-reconcile-media-imports');++const DISCONNECTED_ACCOUNT_ID = '7f1d6c2e-3b4a-4c5d-8e9f-0a1b2c3d4e5f';++const STALLED_CLEANUP_RESULT = {+ candidateCount: 2,+ updatedRecordingCount: 0,+ shouldContinue: true,+ skipped: false,+};++describe('fathomReconcileMediaImportsHandler disconnected cleanup', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ mocks.enqueueJobs.mockResolvedValue({ enqueued: true });+ mocks.cleanupDisconnectedFathomMediaImports.mockResolvedValue(+ STALLED_CLEANUP_RESULT,+ );+ });++ it('chains the next pass immediately while passes keep settling imports', async () => {+ mocks.cleanupDisconnectedFathomMediaImports.mockResolvedValue({+ ...STALLED_CLEANUP_RESULT,+ updatedRecordingCount: 1,+ });++ await fathomReconcileMediaImportsHandler({+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ disconnectedCleanupStalledPassCount: 3,+ });++ expect(mocks.enqueueJobs).toHaveBeenCalledTimes(1);+ expect(mocks.enqueueJobs.mock.calls[0][0]).toEqual(+ expect.objectContaining({+ logicFunctionUniversalIdentifier:+ FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER,+ payloads: [+ {+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ disconnectedCleanupStalledPassCount: 0,+ },+ ],+ }),+ );+ expect(mocks.enqueueJobs.mock.calls[0][0].delayMs).toBeUndefined();+ });++ it('delays the next pass when a pass settles nothing', async () => {+ await fathomReconcileMediaImportsHandler({+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ disconnectedCleanupStalledPassCount: 3,+ });++ expect(mocks.enqueueJobs).toHaveBeenCalledWith(+ expect.objectContaining({+ payloads: [+ {+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ disconnectedCleanupStalledPassCount: 4,+ },+ ],+ delayMs:+ FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASS_DELAY_MILLISECONDS,+ }),+ );+ });++ it('stops scheduling passes once too many passes in a row settle nothing', async () => {+ expect(+ await fathomReconcileMediaImportsHandler({+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ disconnectedCleanupStalledPassCount:+ MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES - 1,+ }),+ ).toEqual(STALLED_CLEANUP_RESULT);+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('does not schedule another pass once every import is settled', async () => {+ mocks.cleanupDisconnectedFathomMediaImports.mockResolvedValue({+ ...STALLED_CLEANUP_RESULT,+ updatedRecordingCount: 2,+ shouldContinue: false,+ });++ await fathomReconcileMediaImportsHandler({+ disconnectedAccountId: DISCONNECTED_ACCOUNT_ID,+ });++ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-sync-call.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-sync-call.test.tsnew file mode 100644index 00000000000..dd843922863--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-sync-call.test.ts@@ -0,0 +1,117 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomMeeting } from 'src/__tests__/utils/build-fathom-meeting.util';+import { buildFathomMeetingPages } from 'src/__tests__/utils/build-fathom-meeting-pages.util';+import { buildLogicFunctionExecutionContext } from 'src/__tests__/utils/logic-function-execution-context.util';+import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';++const mocks = vi.hoisted(() => ({+ getRecordingSummary: vi.fn(),+ getRecordingTranscript: vi.fn(),+ listFathomConnectionsForRequest: vi.fn(),+ listMeetings: vi.fn(),+ mutation: vi.fn(),+ query: vi.fn(),+ syncFathomMeetingToCallRecording: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ jsonSchemaToInputSchema: () => [],+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ listMeetings = mocks.listMeetings;+ getRecordingTranscript = mocks.getRecordingTranscript;+ getRecordingSummary = mocks.getRecordingSummary;+ },+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {+ query = mocks.query;+ mutation = mocks.mutation;+ },+}));++vi.mock(+ 'src/logic-functions/utils/list-fathom-connections-for-request.util',+ () => ({+ listFathomConnectionsForRequest: mocks.listFathomConnectionsForRequest,+ }),+);++vi.mock(+ 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util',+ () => ({+ syncFathomMeetingToCallRecording: mocks.syncFathomMeetingToCallRecording,+ }),+);++const { fathomSyncCallHandler } =+ await import('src/logic-functions/fathom-sync-call');++const RECORDING_ID = 42;+const CALL_RECORDING_ID = computeCallRecordingIdForFathomMeeting(RECORDING_ID);+const CONTEXT = buildLogicFunctionExecutionContext('user-workspace-1');++const mockDeletedCallRecordingIds = (callRecordingIds: string[]) =>+ mocks.query.mockResolvedValue({+ callRecordings: {+ edges: callRecordingIds.map((id) => ({ node: { id } })),+ },+ });++describe('fathomSyncCallHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.listFathomConnectionsForRequest.mockResolvedValue([+ { id: 'connection-1', accessToken: 'token' },+ ]);+ mocks.listMeetings.mockImplementation(+ buildFathomMeetingPages([+ [buildFathomMeeting({ recordingId: RECORDING_ID })],+ ]),+ );+ mocks.getRecordingTranscript.mockResolvedValue({ transcript: [] });+ mocks.getRecordingSummary.mockResolvedValue({ summary: null });+ mocks.syncFathomMeetingToCallRecording.mockResolvedValue({+ callRecordingId: CALL_RECORDING_ID,+ created: false,+ });+ });++ it('reports a recording the user deleted as skipped without recreating it', async () => {+ mockDeletedCallRecordingIds([CALL_RECORDING_ID]);++ expect(+ await fathomSyncCallHandler({ recordingId: RECORDING_ID }, CONTEXT),+ ).toEqual({+ success: true,+ recordingId: RECORDING_ID,+ callRecordingId: CALL_RECORDING_ID,+ skipped: true,+ reason: 'The call recording has been deleted',+ });+ expect(mocks.syncFathomMeetingToCallRecording).not.toHaveBeenCalled();+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('syncs a recording that was never deleted', async () => {+ mockDeletedCallRecordingIds([]);++ expect(+ await fathomSyncCallHandler({ recordingId: RECORDING_ID }, CONTEXT),+ ).toEqual({+ success: true,+ recordingId: RECORDING_ID,+ callRecordingId: CALL_RECORDING_ID,+ created: false,+ });+ expect(mocks.syncFathomMeetingToCallRecording).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-webhook.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-webhook.test.tsnew file mode 100644index 00000000000..a58bce55444--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-webhook.test.ts@@ -0,0 +1,129 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';+import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';++const mocks = vi.hoisted(() => ({+ kvGet: vi.fn(),+ mutation: vi.fn(),+ query: vi.fn(),+ syncFathomMeetingToCallRecording: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ kv: { get: mocks.kvGet },+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ static verifyWebhook = () => undefined;+ },+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {+ query = mocks.query;+ mutation = mocks.mutation;+ },+}));++vi.mock(+ 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util',+ () => ({+ syncFathomMeetingToCallRecording: mocks.syncFathomMeetingToCallRecording,+ }),+);++const { fathomWebhookHandler } =+ await import('src/logic-functions/fathom-webhook');++const RECORDING_ID = 42;+const CALL_RECORDING_ID = computeCallRecordingIdForFathomMeeting(RECORDING_ID);++const MEETING_BODY = JSON.stringify({+ title: 'Customer call',+ meeting_title: 'Customer call',+ meeting_type: null,+ recording_id: RECORDING_ID,+ url: `https://fathom.video/calls/${RECORDING_ID}`,+ share_url: `https://fathom.video/share/${RECORDING_ID}`,+ created_at: '2026-08-20T10:00:00.000Z',+ scheduled_start_time: '2026-08-20T10:00:00.000Z',+ scheduled_end_time: '2026-08-20T10:30:00.000Z',+ recording_start_time: '2026-08-20T10:00:00.000Z',+ recording_end_time: '2026-08-20T10:30:00.000Z',+ calendar_invitees_domains_type: 'one_or_more_external',+ shared_with: 'single_team',+ transcript_language: 'en',+ calendar_invitees: [],+ recorded_by: {+ name: 'Owner',+ email: '[email protected]',+ email_domain: 'example.com',+ team: null,+ },+});++const ROUTE_PAYLOAD = {+ queryStringParameters: {+ [FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER]: 'connection-1',+ },+ headers: {+ 'webhook-id': 'message-1',+ 'webhook-timestamp': '1787220000',+ 'webhook-signature': 'v1,signature',+ },+ rawBody: MEETING_BODY,+} as unknown as Parameters<typeof fathomWebhookHandler>[0];++const mockDeletedCallRecordingIds = (callRecordingIds: string[]) =>+ mocks.query.mockResolvedValue({+ callRecordings: {+ edges: callRecordingIds.map((id) => ({ node: { id } })),+ },+ });++describe('fathomWebhookHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.kvGet.mockResolvedValue({+ webhookId: 'webhook-1',+ secret: 'secret',+ isActive: true,+ isInitialBackfillEnqueued: true,+ });+ mocks.syncFathomMeetingToCallRecording.mockResolvedValue({+ callRecordingId: CALL_RECORDING_ID,+ created: true,+ });+ });++ it('acknowledges a recording the user deleted without recreating it', async () => {+ mockDeletedCallRecordingIds([CALL_RECORDING_ID]);++ expect(await fathomWebhookHandler(ROUTE_PAYLOAD)).toEqual({+ success: true,+ skipped: true,+ reason: 'The call recording has been deleted',+ });+ expect(mocks.syncFathomMeetingToCallRecording).not.toHaveBeenCalled();+ expect(mocks.mutation).not.toHaveBeenCalled();+ });++ it('syncs a recording that was never deleted', async () => {+ mockDeletedCallRecordingIds([]);++ expect(await fathomWebhookHandler(ROUTE_PAYLOAD)).toEqual({+ success: true,+ callRecordingId: CALL_RECORDING_ID,+ created: true,+ });+ expect(mocks.syncFathomMeetingToCallRecording).toHaveBeenCalledWith(+ expect.objectContaining({ connectedAccountId: 'connection-1' }),+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.tsindex d6b59ba6f99..40db66dc306 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.ts@@ -14,9 +14,11 @@ import {FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';import { type FathomBackfillWorkerPayload } from 'src/logic-functions/types/fathom-backfill-worker-payload.type';+import { buildRetryableFathomError } from 'src/logic-functions/utils/build-retryable-fathom-error.util';import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';import { excludeDeletedFathomMeetings } from 'src/logic-functions/utils/exclude-deleted-fathom-meetings.util';import { enqueueFathomJobsOrThrow } from 'src/logic-functions/utils/enqueue-fathom-jobs-or-throw.util';+import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fathom-error.util';import { listFathomMeetingPage } from 'src/logic-functions/utils/list-fathom-meeting-page.util';import { reserveFathomImportSlots } from 'src/logic-functions/utils/reserve-fathom-import-slots.util';import { serializeFathomMeeting } from 'src/logic-functions/utils/serialize-fathom-meeting.util';@@ -54,6 +56,15 @@ export const fathomBackfillWorkerHandler = async (fathomClient: createFathomClient(connection.accessToken),createdAfter,cursor: payload.cursor,+ }).catch((error: unknown) => {+ if (isTransientFathomError(error)) {+ throw buildRetryableFathomError({+ operation: `list meetings for connected account ${payload.connectedAccountId}`,+ error,+ });+ }++ throw error;});const serializedMeetings = meetingPage.meetings.map(serializeFathomMeeting);const importableMeetings = await excludeDeletedFathomMeetings({diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-reconcile-media-imports.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-reconcile-media-imports.tsindex 9894efcd148..9518087ac4e 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-reconcile-media-imports.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-reconcile-media-imports.ts@@ -6,9 +6,11 @@ import { z } from 'zod';import { isDefined } from 'src/utils/is-defined';import {+ FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASS_DELAY_MILLISECONDS,FATHOM_HEALING_WINDOW_DAYS,FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN,FATHOM_MEDIA_RECONCILIATION_GRACE_PERIOD_MILLISECONDS,+ MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES,MILLISECONDS_PER_DAY,} from 'src/constants/fathom.constant';import { FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';@@ -29,6 +31,11 @@ const fathomMediaReconciliationRunSchema = z.object({const fathomMediaReconciliationPayloadSchema = z.object({disconnectedAccountId: z.string().uuid().optional(),+ disconnectedCleanupStalledPassCount: z+ .number()+ .int()+ .nonnegative()+ .optional(),recoveryRun: fathomMediaReconciliationRunSchema.optional(),});@@ -68,12 +75,36 @@ export const fathomReconcileMediaImportsHandler = async (payload: unknown) => {coreApiClient,connectedAccountId: disconnectedAccountId,});+ const isStalled = result.updatedRecordingCount === 0;+ const stalledPassCount = isStalled+ ? (payloadParseResult.data.disconnectedCleanupStalledPassCount ?? 0) + 1+ : 0;+ const isStalledPassBoundReached =+ stalledPassCount >=+ MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES;++ if (result.shouldContinue && isStalledPassBoundReached) {+ console.error(+ `[fathom] media cleanup for disconnected account ${disconnectedAccountId} stopped after ${MAX_FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASSES} stalled passes with imports still unsettled`,+ );+ }- if (result.shouldContinue) {+ if (result.shouldContinue && !isStalledPassBoundReached) {await enqueueFathomJobsOrThrow({logicFunctionUniversalIdentifier:FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER,- payloads: [{ disconnectedAccountId }],+ payloads: [+ {+ disconnectedAccountId,+ disconnectedCleanupStalledPassCount: stalledPassCount,+ },+ ],+ ...(isStalled+ ? {+ delayMs:+ FATHOM_DISCONNECTED_MEDIA_CLEANUP_STALLED_PASS_DELAY_MILLISECONDS,+ }+ : {}),});}diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.tsindex d86be9bd526..e366eeb0ec6 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.ts@@ -8,8 +8,10 @@ import {import { isDefined } from 'src/utils/is-defined';import { FATHOM_SYNC_CALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';import { hydrateFathomMeeting } from 'src/logic-functions/utils/hydrate-fathom-meeting.util';+import { listDeletedCallRecordingIds } from 'src/logic-functions/utils/list-deleted-call-recording-ids.util';import { listFathomConnectionsForRequest } from 'src/logic-functions/utils/list-fathom-connections-for-request.util';import { listFathomMeetings } from 'src/logic-functions/utils/list-fathom-meetings.util';import { serializeFathomMeeting } from 'src/logic-functions/utils/serialize-fathom-meeting.util';@@ -37,6 +39,13 @@ type FathomSyncCallResult =calendarEventId?: string;created: boolean;}+ | {+ success: true;+ recordingId: number;+ callRecordingId: string;+ skipped: true;+ reason: string;+ }| { success: false; error: string };export const fathomSyncCallHandler = async (@@ -74,8 +83,25 @@ export const fathomSyncCallHandler = async (continue;}+ const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const callRecordingId = computeCallRecordingIdForFathomMeeting(recordingId);+ const deletedCallRecordingIds = await listDeletedCallRecordingIds({+ coreApiClient,+ callRecordingIds: [callRecordingId],+ });++ if (deletedCallRecordingIds.has(callRecordingId)) {+ return {+ success: true,+ recordingId,+ callRecordingId,+ skipped: true,+ reason: 'The call recording has been deleted',+ };+ }+const syncResult = await syncFathomMeetingToCallRecording({- coreApiClient: new CoreApiClient({ runAs: 'application' }),+ coreApiClient,meeting: await hydrateFathomMeeting({fathomClient,serializedMeeting: serializeFathomMeeting(meeting),@@ -114,6 +140,8 @@ export default defineLogicFunction({callRecordingId: { type: 'string' },calendarEventId: { type: 'string' },created: { type: 'boolean' },+ skipped: { type: 'boolean' },+ reason: { type: 'string' },},},],diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.tsindex c88c686cabf..34009867258 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.ts@@ -9,7 +9,9 @@ import { isDefined } from 'src/utils/is-defined';import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';import { FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';+import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';import { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';+import { listDeletedCallRecordingIds } from 'src/logic-functions/utils/list-deleted-call-recording-ids.util';import { syncFathomMeetingToCallRecording } from 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util';type FathomWebhookResult =@@ -86,8 +88,25 @@ export const fathomWebhookHandler = async (return { success: false, error: 'Invalid Fathom meeting payload' };}+ const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const callRecordingId = computeCallRecordingIdForFathomMeeting(+ meetingParseResult.value.recordingId,+ );+ const deletedCallRecordingIds = await listDeletedCallRecordingIds({+ coreApiClient,+ callRecordingIds: [callRecordingId],+ });++ if (deletedCallRecordingIds.has(callRecordingId)) {+ return {+ success: true,+ skipped: true,+ reason: 'The call recording has been deleted',+ };+ }+const syncResult = await syncFathomMeetingToCallRecording({- coreApiClient: new CoreApiClient({ runAs: 'application' }),+ coreApiClient,meeting: meetingParseResult.value,connectedAccountId,});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.tsindex d2ec513e419..5d7d15832cc 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts@@ -1,16 +1,22 @@import { createServer, type Server } from 'node:http';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { openFathomMediaDownload } from 'src/logic-functions/utils/open-fathom-media-download.util';+vi.mock('src/constants/fathom.constant', async (importOriginal) => ({+ ...(await importOriginal<typeof import('src/constants/fathom.constant')>()),+ FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS: 50,+}));++const { openFathomMediaDownload } =+ await import('src/logic-functions/utils/open-fathom-media-download.util');const openServers: Server[] = [];+const pendingResponseTimers: NodeJS.Timeout[] = [];-const startEmptyDownloadServer = async (): Promise<string> => {- const server = createServer((_request, response) => {- response.writeHead(200, { 'content-length': '0' });- response.end();- });+const startDownloadServer = async (+ handleRequest: Parameters<typeof createServer>[1],+): Promise<string> => {+ const server = createServer(handleRequest);await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));openServers.push(server);@@ -24,7 +30,27 @@ const startEmptyDownloadServer = async (): Promise<string> => {return `http://127.0.0.1:${address.port}/download`;};+const startEmptyDownloadServer = async (): Promise<string> =>+ await startDownloadServer((_request, response) => {+ response.writeHead(200, { 'content-length': '0' });+ response.end();+ });++const readBodyBytes = async (+ body: ReadableStream<Uint8Array>,+): Promise<number[]> => {+ const bytes: number[] = [];++ for await (const chunk of body) {+ bytes.push(...chunk);+ }++ return bytes;+};+afterEach(async () => {+ pendingResponseTimers.splice(0).forEach(clearTimeout);+ openServers.forEach((server) => server.closeAllConnections());await Promise.all(openServers.splice(0)@@ -51,4 +77,38 @@ describe('openFathomMediaDownload', () => {}),).resolves.toEqual({ outcome: 'empty' });});++ it('keeps streaming a body that outlasts the response timeout', async () => {+ const downloadUrl = await startDownloadServer((_request, response) => {+ response.writeHead(200, { 'content-length': '4' });+ response.write(Uint8Array.from([1, 2]));+ pendingResponseTimers.push(+ setTimeout(() => response.end(Uint8Array.from([3, 4])), 200),+ );+ });++ const download = await openFathomMediaDownload({+ callRecordingId: 'call-recording-id',+ fileName: 'video.mp4',+ downloadFile: { url: downloadUrl },+ });++ if (download.outcome !== 'opened') {+ throw new Error(`Expected an opened download, got ${download.outcome}`);+ }++ expect(await readBodyBytes(download.body)).toEqual([1, 2, 3, 4]);+ });++ it('gives up when the response headers do not arrive in time', async () => {+ const downloadUrl = await startDownloadServer(() => undefined);++ await expect(+ openFathomMediaDownload({+ callRecordingId: 'call-recording-id',+ fileName: 'video.mp4',+ downloadFile: { url: downloadUrl },+ }),+ ).rejects.toMatchObject({ name: 'TimeoutError' });+ });});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target-timeout.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target-timeout.test.tsnew file mode 100644index 00000000000..07ced6728f7--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target-timeout.test.ts@@ -0,0 +1,69 @@+import { createServer, type Server } from 'node:http';++import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('src/constants/fathom.constant', async (importOriginal) => ({+ ...(await importOriginal<typeof import('src/constants/fathom.constant')>()),+ FATHOM_MEDIA_UPLOAD_TIMEOUT_MILLISECONDS: 100,+}));++const { putFathomMediaBodyToUploadTarget } =+ await import('src/logic-functions/utils/put-fathom-media-body-to-upload-target.util');++const openServers: Server[] = [];++const startUploadServer = async (): Promise<string> => {+ const server = createServer((request) => {+ request.resume();+ });++ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ openServers.push(server);++ const address = server.address();++ if (address === null || typeof address === 'string') {+ throw new Error('Upload test server did not bind a TCP port');+ }++ return `http://127.0.0.1:${address.port}/upload`;+};++afterEach(async () => {+ await Promise.all(+ openServers.splice(0).map(+ async (server) =>+ await new Promise<void>((resolve) => {+ server.closeAllConnections();+ server.close(() => resolve());+ }),+ ),+ );+});++describe('putFathomMediaBodyToUploadTarget upload timeout', () => {+ it('rejects and cancels a download that stalls after its first chunk', async () => {+ let isCancelled = false;+ const mediaDownloadBody = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(Uint8Array.from([1, 2]));+ },+ cancel() {+ isCancelled = true;+ },+ });+ const uploadUrl = await startUploadServer();++ await expect(+ putFathomMediaBodyToUploadTarget({+ callRecordingId: 'call-recording-id',+ fileName: 'video.mp4',+ mediaDownloadBody,+ sizeBytes: 4,+ uploadTarget: { uploadUrl, contentType: 'video/mp4' },+ }),+ ).rejects.toThrow();++ expect(isCancelled).toBe(true);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.tsindex 38512ce71ce..17bd67b179a 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts@@ -21,9 +21,17 @@ export const openFathomMediaDownload = async ({fileName: string;downloadFile: Pick<RecordingDownloadFile, 'url'>;}): Promise<OpenFathomMediaDownloadResult> => {+ const headersAbortController = new AbortController();+ const headersTimeout = setTimeout(+ () =>+ headersAbortController.abort(+ new DOMException('media download headers timed out', 'TimeoutError'),+ ),+ FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS,+ );const response = await fetch(downloadFile.url, {- signal: AbortSignal.timeout(FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS),- });+ signal: headersAbortController.signal,+ }).finally(() => clearTimeout(headersTimeout));const contentLengthBytes = parseContentLengthBytes(response.headers.get('content-length'),);diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.tsindex 783a3b5087d..4a562343b51 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts@@ -4,7 +4,7 @@ import { Readable } from 'node:stream';import { finished, pipeline } from 'node:stream/promises';import { FATHOM_MEDIA_UPLOAD_TIMEOUT_MILLISECONDS } from 'src/constants/fathom.constant';-import { cancelFathomMediaDownloadBody } from 'src/logic-functions/utils/cancel-fathom-media-download-body.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';type MediaUploadTarget = {uploadUrl: string;@@ -27,32 +27,36 @@ export const putFathomMediaBodyToUploadTarget = async ({sizeBytes: number;uploadTarget: MediaUploadTarget;}): Promise<void> => {+ const mediaDownloadReader = mediaDownloadBody.getReader();const mediaDownloadReadable = Readable.from(- readMediaDownloadBody({ mediaDownloadBody }),+ readMediaDownloadBody({ reader: mediaDownloadReader }),);+ const cancelMediaDownload = async () => {+ await mediaDownloadReader.cancel().catch((error: unknown) => {+ console.warn(+ `[fathom] media download body cancellation failed callRecordingId=${callRecordingId} fileName=${fileName}: ${toErrorMessage(error)}`,+ );+ });+ };await streamMediaDownloadReadableToUploadTarget({+ cancelMediaDownload,fileName,mediaDownloadReadable,sizeBytes,uploadTarget,}).catch(async (error: unknown) => {- await cancelFathomMediaDownloadBody({- body: mediaDownloadBody,- callRecordingId,- fileName,- });+ await cancelMediaDownload();throw error;});};const readMediaDownloadBody = async function* ({- mediaDownloadBody,+ reader,}: {- mediaDownloadBody: ReadableStream<Uint8Array>;+ reader: ReadableStreamDefaultReader<Uint8Array>;}) {- const reader = mediaDownloadBody.getReader();let isComplete = false;try {@@ -76,11 +80,13 @@ const readMediaDownloadBody = async function* ({};const streamMediaDownloadReadableToUploadTarget = async ({+ cancelMediaDownload,fileName,mediaDownloadReadable,sizeBytes,uploadTarget,}: {+ cancelMediaDownload: () => Promise<void>;fileName: string;mediaDownloadReadable: Readable;sizeBytes: number;@@ -112,6 +118,7 @@ const streamMediaDownloadReadableToUploadTarget = async ({]).catch(async (error: unknown) => {mediaDownloadReadable.destroy();uploadRequest.destroy();+ await cancelMediaDownload();await uploadPipelinePromise.catch(() => undefined);throw error;@@ -132,6 +139,7 @@ const streamMediaDownloadReadableToUploadTarget = async ({mediaDownloadReadable.destroy(uploadError);uploadRequest.destroy(uploadError);+ await cancelMediaDownload();await Promise.allSettled([uploadPipelinePromise,