The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Retry Twenty and Fathom rate limits in the Fathom app (#27667)
nitin55dfb1f3b9f0
diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-rate-limit-error.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-rate-limit-error.util.tsnew file mode 100644index 00000000000..ff4bc13c862--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-rate-limit-error.util.ts@@ -0,0 +1,11 @@+import { FathomError } from 'fathom-typescript/sdk/models/errors';++export const buildFathomRateLimitError = (retryAfter?: string): FathomError =>+ new FathomError('Rate limit exceeded', {+ response: new Response(null, {+ status: 429,+ headers: retryAfter === undefined ? {} : { 'retry-after': retryAfter },+ }),+ request: new Request('https://api.fathom.ai/external/v1/meetings'),+ body: '',+ });diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.tsindex fdc8dfeef0a..480af24b88a 100644--- a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts+++ b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts@@ -10,6 +10,10 @@ export const FATHOM_BACKFILL_BATCH_SIZE = 5;export const FATHOM_IMPORT_SLOT_INTERVAL_MILLISECONDS = 20_000;export const FATHOM_BACKFILL_JOB_RETRY_LIMIT = 3;export const FATHOM_REQUEST_RETRY_MAX_ELAPSED_MILLISECONDS = 10_000;+export const FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS = 60_000;+export const FATHOM_MIN_REQUEUE_DELAY_MILLISECONDS = 5_000;+export const FATHOM_MAX_REQUEUE_DELAY_MILLISECONDS = 5 * 60 * 1_000;+export const MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS = 5;export const MAX_FATHOM_MEETING_PAGES = 20;export const MAX_FATHOM_BACKFILL_PAGES = 1_000;export const MAX_FATHOM_MEETING_TOPIC_CHARACTERS = 80;@@ -29,6 +33,8 @@ export const FATHOM_MEDIA_RECONCILIATION_GRACE_PERIOD_MILLISECONDS =30 * 60 * 1_000;export const FATHOM_MEDIA_RECONCILIATION_PAGE_SIZE = 200;export const FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN = '30 3 * * *';+export const FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS =+ 60 * 60 * 1_000;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/constants/universal-identifiers.ts b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.tsindex eb70779c209..6e7387f0a0d 100644--- a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts@@ -59,6 +59,8 @@ export const FATHOM_IMPORT_MEDIA_DOWNLOAD_UNIVERSAL_IDENTIFIER ='4b46124e-ef53-4649-b414-cc5ae47111ff';export const FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER ='3670d009-0c34-454c-9b21-254fd8349f61';+export const FATHOM_ENQUEUE_MEDIA_RECONCILIATION_UNIVERSAL_IDENTIFIER =+ 'eee857d4-1cc1-4a79-9b4e-77242d8e1003';export const CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER ='bb9523d3-457e-4f4b-8c79-27a77afb87da';export const CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER =diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-batch.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-batch.test.tsnew file mode 100644index 00000000000..cc9998a96b7--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-backfill-batch.test.ts@@ -0,0 +1,220 @@+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomMeeting } from 'src/__tests__/utils/build-fathom-meeting.util';+import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';+import { buildFathomRateLimitError } from 'src/__tests__/utils/build-fathom-rate-limit-error.util';+import { buildFathomServerError } from 'src/__tests__/utils/build-fathom-server-error.util';+import {+ FATHOM_IMPORT_SLOT_INTERVAL_MILLISECONDS,+ MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS,+} from 'src/constants/fathom.constant';+import { FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { serializeFathomMeeting } from 'src/logic-functions/utils/serialize-fathom-meeting.util';++const mocks = vi.hoisted(() => ({+ enqueueJobs: vi.fn(),+ getConnection: vi.fn(),+ kvGet: vi.fn(),+ kvSet: vi.fn(),+ getRecordingTranscript: vi.fn(),+ getRecordingSummary: vi.fn(),+ syncFathomMeetingToCallRecording: 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,+ kv: { get: mocks.kvGet, set: mocks.kvSet },+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ getRecordingTranscript = mocks.getRecordingTranscript;+ getRecordingSummary = mocks.getRecordingSummary;+ },+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {},+}));++vi.mock(+ 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util',+ () => ({+ syncFathomMeetingToCallRecording: mocks.syncFathomMeetingToCallRecording,+ }),+);++const { fathomBackfillBatchHandler } =+ await import('src/logic-functions/fathom-backfill-batch');++const NOW = new Date('2026-09-05T12:00:00.000Z');+const MEETINGS = [1, 2, 3].map((recordingId) =>+ serializeFathomMeeting(buildFathomMeeting({ recordingId })),+);+const PAYLOAD = { connectedAccountId: 'connection-1', meetings: MEETINGS };++const failTranscriptFor = (recordingId: number, error: unknown) =>+ mocks.getRecordingTranscript.mockImplementation(+ async (request: { recordingId: number }) => {+ if (request.recordingId === recordingId) {+ throw error;+ }++ return { transcript: [] };+ },+ );++describe('fathomBackfillBatchHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(NOW);+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ mocks.enqueueJobs.mockResolvedValue({ enqueued: true });+ mocks.getConnection.mockResolvedValue({+ id: 'connection-1',+ accessToken: 'token-1',+ });+ mocks.kvGet.mockResolvedValue(null);+ mocks.getRecordingTranscript.mockResolvedValue({ transcript: [] });+ mocks.getRecordingSummary.mockResolvedValue({ summary: null });+ mocks.syncFathomMeetingToCallRecording.mockImplementation(+ async ({ meeting }: { meeting: { recordingId: number } }) => ({+ recordingId: meeting.recordingId,+ }),+ );+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('re-enqueues only the meetings left after a rate limit, after Retry-After', async () => {+ failTranscriptFor(2, buildFathomRateLimitError('120'));++ const result = await fathomBackfillBatchHandler(PAYLOAD);++ expect(result).toMatchObject({+ success: true,+ importedMeetingCount: 1,+ requeuedMeetingCount: 2,+ });+ expect(mocks.syncFathomMeetingToCallRecording).toHaveBeenCalledTimes(1);+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER,+ payloads: [+ {+ connectedAccountId: 'connection-1',+ meetings: MEETINGS.slice(1),+ requeueAttempt: 1,+ },+ ],+ delayMs: 120_000,+ }),+ );+ });++ it('waits behind batches already scheduled for the connection', async () => {+ const nextBatchAvailableAt = NOW.getTime() + 10 * 60_000;++ mocks.kvGet.mockResolvedValue({ nextBatchAvailableAt });+ failTranscriptFor(1, buildFathomServerError());++ await fathomBackfillBatchHandler(PAYLOAD);++ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ delayMs: 10 * 60_000 }),+ );+ expect(mocks.kvSet).toHaveBeenCalledExactlyOnceWith(+ 'fathom-backfill-schedule:connection-1',+ {+ nextBatchAvailableAt:+ nextBatchAvailableAt + FATHOM_IMPORT_SLOT_INTERVAL_MILLISECONDS,+ },+ );+ });++ it('re-enqueues from the meeting whose save failed, without re-fetching earlier ones', async () => {+ mocks.syncFathomMeetingToCallRecording+ .mockResolvedValueOnce({ recordingId: 1 })+ .mockResolvedValueOnce({ recordingId: 2 })+ .mockRejectedValueOnce(new RetryableLogicFunctionError('rate limited'));++ const result = await fathomBackfillBatchHandler({+ ...PAYLOAD,+ requeueAttempt: 2,+ });++ expect(result).toMatchObject({ success: true, requeuedMeetingCount: 1 });+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ payloads: [+ {+ connectedAccountId: 'connection-1',+ meetings: MEETINGS.slice(2),+ requeueAttempt: 3,+ },+ ],+ delayMs: 60_000,+ }),+ );+ });++ it('hands a save that fails for good back to the platform without re-enqueueing', async () => {+ mocks.syncFathomMeetingToCallRecording.mockRejectedValueOnce(+ new Error('Invalid record'),+ );++ await expect(fathomBackfillBatchHandler(PAYLOAD)).rejects.toBeInstanceOf(+ RetryableLogicFunctionError,+ );+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('hands the batch back to the platform once the re-enqueue budget is spent', async () => {+ failTranscriptFor(1, buildFathomRateLimitError('30'));++ await expect(+ fathomBackfillBatchHandler({+ ...PAYLOAD,+ requeueAttempt: MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS,+ }),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });++ it('hands the batch back to the platform when the re-enqueue fails', async () => {+ failTranscriptFor(2, buildFathomRateLimitError('120'));+ mocks.enqueueJobs.mockResolvedValue({ enqueued: false });++ await expect(fathomBackfillBatchHandler(PAYLOAD)).rejects.toBeInstanceOf(+ RetryableLogicFunctionError,+ );+ expect(mocks.enqueueJobs).toHaveBeenCalledOnce();+ });++ it('skips a recording Fathom rejects permanently and imports the rest', async () => {+ failTranscriptFor(2, buildFathomNotFoundError());++ const result = await fathomBackfillBatchHandler(PAYLOAD);++ expect(result).toMatchObject({+ success: true,+ importedMeetingCount: 2,+ failedMeetingCount: 1,+ requeuedMeetingCount: 0,+ });+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });+});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.tsindex dfbc7171a42..5fdc5f0f620 100644--- 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.ts@@ -3,7 +3,10 @@ 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 { buildFathomRateLimitError } from 'src/__tests__/utils/build-fathom-rate-limit-error.util';import { buildFathomServerError } from 'src/__tests__/utils/build-fathom-server-error.util';+import { MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS } from 'src/constants/fathom.constant';+import { FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';const mocks = vi.hoisted(() => ({enqueueJobs: vi.fn(),@@ -35,6 +38,8 @@ const PAYLOAD = { connectedAccountId: 'connection-1', days: 31 };describe('fathomBackfillWorkerHandler', () => {beforeEach(() => {vi.resetAllMocks();+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ mocks.enqueueJobs.mockResolvedValue({ enqueued: true });mocks.getConnection.mockResolvedValue({id: 'connection-1',accessToken: 'token-1',@@ -42,23 +47,87 @@ describe('fathomBackfillWorkerHandler', () => {});it.each([- { description: 'a Fathom outage', error: buildFathomServerError() },+ {+ description: 'a rate limit',+ error: buildFathomRateLimitError('120'),+ expectedDelay: 120_000,+ },+ {+ description: 'a Fathom outage',+ error: buildFathomServerError(),+ expectedDelay: 60_000,+ },{description: 'a network failure',error: new ConnectionError('connection refused'),+ expectedDelay: 60_000,},])(- 'asks the platform to retry the page after $description',- async ({ error }) => {+ 're-enqueues the same page after $description',+ async ({ error, expectedDelay }) => {mocks.listMeetings.mockRejectedValue(error);- await expect(fathomBackfillWorkerHandler(PAYLOAD)).rejects.toBeInstanceOf(- RetryableLogicFunctionError,+ expect(+ await fathomBackfillWorkerHandler({+ ...PAYLOAD,+ cursor: 'cursor-3',+ pageIndex: 3,+ requeueAttempt: 1,+ }),+ ).toMatchObject({ success: true, requeueDelay: expectedDelay });+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payloads: [+ {+ connectedAccountId: 'connection-1',+ createdAfter: expect.any(String),+ cursor: 'cursor-3',+ pageIndex: 3,+ requeueAttempt: 2,+ },+ ],+ delayMs: expectedDelay,+ }),);- expect(mocks.enqueueJobs).not.toHaveBeenCalled();},);+ it('keeps the original window when re-enqueueing a page', async () => {+ mocks.listMeetings.mockRejectedValue(buildFathomServerError());++ const { createdAfter } = await fathomBackfillWorkerHandler(PAYLOAD);++ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ payloads: [expect.objectContaining({ createdAfter })],+ }),+ );+ });++ it('asks the platform to retry when re-enqueueing the page fails', async () => {+ mocks.listMeetings.mockRejectedValue(buildFathomRateLimitError('120'));+ mocks.enqueueJobs.mockResolvedValue({ enqueued: false });++ await expect(fathomBackfillWorkerHandler(PAYLOAD)).rejects.toBeInstanceOf(+ RetryableLogicFunctionError,+ );+ expect(mocks.enqueueJobs).toHaveBeenCalledOnce();+ });++ it('asks the platform to retry once the re-enqueue budget is spent', async () => {+ mocks.listMeetings.mockRejectedValue(buildFathomRateLimitError('120'));++ await expect(+ fathomBackfillWorkerHandler({+ ...PAYLOAD,+ requeueAttempt: MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS,+ }),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ expect(mocks.enqueueJobs).not.toHaveBeenCalled();+ });+it('does not retry a page Fathom rejects permanently', async () => {const notFoundError = buildFathomNotFoundError();diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-enqueue-media-reconciliation.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-enqueue-media-reconciliation.test.tsnew file mode 100644index 00000000000..2fca9152b15--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-enqueue-media-reconciliation.test.ts@@ -0,0 +1,87 @@+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildLogicFunctionExecutionContext } from 'src/__tests__/utils/logic-function-execution-context.util';+import {+ FATHOM_BACKFILL_JOB_RETRY_LIMIT,+ FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS,+} from 'src/constants/fathom.constant';+import { FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++const mocks = vi.hoisted(() => ({+ 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,+}));++const { fathomEnqueueMediaReconciliationHandler } =+ await import('src/logic-functions/fathom-enqueue-media-reconciliation');++const buildContext = (workspaceId: string) => ({+ ...buildLogicFunctionExecutionContext(null),+ workspaceId,+});++describe('fathomEnqueueMediaReconciliationHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.enqueueJobs.mockResolvedValue({ enqueued: true });+ });++ it('enqueues the reconciliation at a stable delay within the window', async () => {+ const context = buildContext('20202020-1111-4444-8888-303030303030');++ const { delayMs } = await fathomEnqueueMediaReconciliationHandler(+ {},+ context,+ );++ expect(delayMs).toBeGreaterThanOrEqual(0);+ expect(delayMs).toBeLessThan(+ FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS,+ );+ expect(mocks.enqueueJobs).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER,+ payloads: [{}],+ retryLimit: FATHOM_BACKFILL_JOB_RETRY_LIMIT,+ delayMs,+ });+ expect(+ (await fathomEnqueueMediaReconciliationHandler({}, context)).delayMs,+ ).toBe(delayMs);+ });++ it('runs different workspaces at different times', async () => {+ const { delayMs: firstDelay } =+ await fathomEnqueueMediaReconciliationHandler(+ {},+ buildContext('20202020-1111-4444-8888-303030303030'),+ );+ const { delayMs: secondDelay } =+ await fathomEnqueueMediaReconciliationHandler(+ {},+ buildContext('20202020-2222-4444-8888-303030303030'),+ );++ expect(firstDelay).not.toBe(secondDelay);+ });++ it('reports a failed enqueue as retryable', async () => {+ mocks.enqueueJobs.mockResolvedValue({ enqueued: false });++ await expect(+ fathomEnqueueMediaReconciliationHandler(+ {},+ buildContext('20202020-1111-4444-8888-303030303030'),+ ),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.tsindex 9959ecc5ac2..901df0533b9 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.ts@@ -1,38 +1,98 @@-import { CoreApiClient } from 'twenty-client-sdk/core';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';import { defineLogicFunction } from 'twenty-sdk/define';-import { getConnection } from 'twenty-sdk/logic-function';+import {+ getConnection,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';import { isDefined } from 'src/utils/is-defined';+import {+ FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS,+ MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS,+} from 'src/constants/fathom.constant';import { FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';+import { type FathomBackfillBatchPayload } from 'src/logic-functions/types/fathom-backfill-batch-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 { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.util';+import { enqueueFathomBackfillBatch } from 'src/logic-functions/utils/enqueue-fathom-backfill-batch.util';+import { getFathomRequeueDelay } from 'src/logic-functions/utils/get-fathom-requeue-delay.util';import { hydrateFathomMeeting } from 'src/logic-functions/utils/hydrate-fathom-meeting.util';-import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fathom-error.util';import { syncFathomMeetingToCallRecording } from 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util';import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';-export const fathomBackfillBatchHandler = async (payload: {- connectedAccountId: string;- meetings: SerializedFathomMeeting[];-}) => {+export const fathomBackfillBatchHandler = async (+ payload: FathomBackfillBatchPayload,+) => {const connection = await getConnection(payload.connectedAccountId);const fathomClient = createFathomClient(connection.accessToken);- const coreApiClient = new CoreApiClient({ runAs: 'application' });- const results = [];+ const coreApiClient = createFathomCoreApiClient();+ const requeueAttempt = payload.requeueAttempt ?? 0;+ const results: Awaited<+ ReturnType<typeof syncFathomMeetingToCallRecording>+ >[] = [];+ let skippedMeetingCount = 0;++ const requeueRemainingMeetings = async ({+ meetingIndex,+ operation,+ error,+ delay,+ }: {+ meetingIndex: number;+ operation: string;+ error: unknown;+ delay: number;+ }) => {+ if (requeueAttempt >= MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS) {+ throw buildRetryableFathomError({ operation, error });+ }++ const remainingMeetings = payload.meetings.slice(meetingIndex);++ try {+ await enqueueFathomBackfillBatch({+ connectedAccountId: payload.connectedAccountId,+ meetings: remainingMeetings,+ requeueAttempt: requeueAttempt + 1,+ notBeforeDelayMilliseconds: delay,+ });+ } catch (enqueueError) {+ throw buildRetryableFathomError({+ operation: `re-enqueue after ${operation}`,+ error: enqueueError,+ });+ }++ console.warn(+ `[fathom] ${operation} failed, re-enqueued ${remainingMeetings.length} meetings in ${delay}ms: ${toErrorMessage(error)}`,+ );++ return {+ success: true,+ importedMeetingCount: results.length,+ failedMeetingCount: skippedMeetingCount,+ requeuedMeetingCount: remainingMeetings.length,+ results,+ };+ };// Sequential on purpose: the batch is the unit of pacing against Fathom.- for (const serializedMeeting of payload.meetings) {- const meeting = await hydrateFathomMeeting({- fathomClient,- serializedMeeting,- }).catch((error: unknown) => {- // Only a RetryableLogicFunctionError makes the platform retry, so a rate- // limit or a Fathom outage is rethrown as one.- if (isTransientFathomError(error)) {- throw buildRetryableFathomError({- operation: `hydrate recording ${serializedMeeting.recordingId}`,+ for (const [meetingIndex, serializedMeeting] of payload.meetings.entries()) {+ const hydrateOperation = `hydrate recording ${serializedMeeting.recordingId}`;+ let meeting: Meeting;++ try {+ meeting = await hydrateFathomMeeting({ fathomClient, serializedMeeting });+ } catch (error) {+ const delay = getFathomRequeueDelay({ error, now: new Date() });++ if (isDefined(delay)) {+ return requeueRemainingMeetings({+ meetingIndex,+ operation: hydrateOperation,error,+ delay,});}@@ -40,35 +100,40 @@ export const fathomBackfillBatchHandler = async (payload: {console.error(`[fathom] skipped recording ${serializedMeeting.recordingId}: ${toErrorMessage(error)}`,);+ skippedMeetingCount += 1;- return undefined;- });-- if (!isDefined(meeting)) {continue;}- // A failed upsert retries the whole batch. The replay re-fetches the- // meetings already imported, which costs calls but cannot duplicate- // records: the CallRecording id is derived from the recording.- results.push(- await syncFathomMeetingToCallRecording({- coreApiClient,- meeting,- connectedAccountId: payload.connectedAccountId,- }).catch((error: unknown) => {- throw buildRetryableFathomError({- operation: `sync recording ${serializedMeeting.recordingId}`,- error,- });- }),- );+ try {+ results.push(+ await syncFathomMeetingToCallRecording({+ coreApiClient,+ meeting,+ connectedAccountId: payload.connectedAccountId,+ }),+ );+ } catch (error) {+ const operation = `sync recording ${serializedMeeting.recordingId}`;++ if (!(error instanceof RetryableLogicFunctionError)) {+ throw buildRetryableFathomError({ operation, error });+ }++ return requeueRemainingMeetings({+ meetingIndex,+ operation,+ error,+ delay: FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS,+ });+ }}return {success: true,importedMeetingCount: results.length,- failedMeetingCount: payload.meetings.length - results.length,+ failedMeetingCount: skippedMeetingCount,+ requeuedMeetingCount: 0,results,};};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 40db66dc306..b979e7287ec 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@@ -1,5 +1,4 @@import { isNonEmptyString } from '@sniptt/guards';-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import { getConnection } from 'twenty-sdk/logic-function';import { isDefined } from 'src/utils/is-defined';@@ -7,6 +6,7 @@ import { isDefined } from 'src/utils/is-defined';import {FATHOM_BACKFILL_BATCH_SIZE,MAX_FATHOM_BACKFILL_PAGES,+ MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS,MILLISECONDS_PER_DAY,} from 'src/constants/fathom.constant';import {@@ -16,12 +16,14 @@ import {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 { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-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 { getFathomRequeueDelay } from 'src/logic-functions/utils/get-fathom-requeue-delay.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';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';import { chunkIntoBatches } from 'src/utils/chunk-into-batches.util';const getCreatedAfter = ({@@ -52,23 +54,59 @@ export const fathomBackfillWorkerHandler = async (const createdAfter = getCreatedAfter({ payload, now: Date.now() });const pageIndex = payload.pageIndex ?? 0;const connection = await getConnection(payload.connectedAccountId);- const meetingPage = await listFathomMeetingPage({- fathomClient: createFathomClient(connection.accessToken),- createdAfter,- cursor: payload.cursor,- }).catch((error: unknown) => {- if (isTransientFathomError(error)) {+ const requeueAttempt = payload.requeueAttempt ?? 0;+ const listOperation = `list meetings for connected account ${payload.connectedAccountId}`;+ let meetingPage: Awaited<ReturnType<typeof listFathomMeetingPage>>;++ try {+ meetingPage = await listFathomMeetingPage({+ fathomClient: createFathomClient(connection.accessToken),+ createdAfter,+ cursor: payload.cursor,+ });+ } catch (error) {+ const delay = getFathomRequeueDelay({ error, now: new Date() });++ if (!isDefined(delay)) {+ throw error;+ }++ if (requeueAttempt >= MAX_FATHOM_BACKFILL_REQUEUE_ATTEMPTS) {+ throw buildRetryableFathomError({ operation: listOperation, error });+ }++ try {+ await enqueueFathomJobsOrThrow({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payloads: [+ {+ connectedAccountId: payload.connectedAccountId,+ createdAfter,+ cursor: payload.cursor,+ pageIndex,+ requeueAttempt: requeueAttempt + 1,+ },+ ],+ delayMs: delay,+ });+ } catch (enqueueError) {throw buildRetryableFathomError({- operation: `list meetings for connected account ${payload.connectedAccountId}`,- error,+ operation: `re-enqueue after ${listOperation}`,+ error: enqueueError,});}- throw error;- });+ console.warn(+ `[fathom] ${listOperation} failed, re-enqueued in ${delay}ms: ${toErrorMessage(error)}`,+ );++ return { success: true, createdAfter, requeueDelay: delay };+ }+const serializedMeetings = meetingPage.meetings.map(serializeFathomMeeting);const importableMeetings = await excludeDeletedFathomMeetings({- coreApiClient: new CoreApiClient({ runAs: 'application' }),+ coreApiClient: createFathomCoreApiClient(),meetings: serializedMeetings,});const meetingBatches = chunkIntoBatches(@@ -134,6 +172,6 @@ export default defineLogicFunction({name: 'fathom-backfill-worker',description:"Discovers one page of Fathom meetings, schedules paced import batches, and continues from Fathom's cursor.",- timeoutSeconds: 120,+ timeoutSeconds: 300,handler: fathomBackfillWorkerHandler,});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-enqueue-media-reconciliation.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-enqueue-media-reconciliation.tsnew file mode 100644index 00000000000..dbc78fc041f--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-enqueue-media-reconciliation.ts@@ -0,0 +1,32 @@+import { defineLogicFunction } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++import { FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN } from 'src/constants/fathom.constant';+import {+ FATHOM_ENQUEUE_MEDIA_RECONCILIATION_UNIVERSAL_IDENTIFIER,+ FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { enqueueWorkspaceDistributedJob } from 'src/logic-functions/utils/enqueue-workspace-distributed-job.util';++export const fathomEnqueueMediaReconciliationHandler = (+ _payload: unknown,+ { workspaceId }: LogicFunctionExecutionContext,+) =>+ enqueueWorkspaceDistributedJob({+ workspaceId,+ logicFunctionUniversalIdentifier:+ FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER,+ operation: 'media import reconciliation enqueueing',+ });++export default defineLogicFunction({+ universalIdentifier: FATHOM_ENQUEUE_MEDIA_RECONCILIATION_UNIVERSAL_IDENTIFIER,+ name: 'fathom-enqueue-media-reconciliation',+ description:+ 'Enqueues the daily Fathom media reconciliation at a stable workspace-specific delay to spread Twenty API traffic.',+ timeoutSeconds: 30,+ handler: fathomEnqueueMediaReconciliationHandler,+ cronTriggerSettings: {+ pattern: FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN,+ },+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-generate-call-recording-title.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-generate-call-recording-title.tsindex 04e4b59f0cb..f50c62c73f0 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-generate-call-recording-title.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-generate-call-recording-title.ts@@ -1,15 +1,15 @@-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import { FATHOM_GENERATE_CALL_RECORDING_TITLE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { fathomGenerateCallRecordingTitlePayloadSchema } from 'src/logic-functions/schemas/fathom-generate-call-recording-title-payload.schema';+import { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.util';import { renameFathomCallRecording } from 'src/logic-functions/utils/rename-fathom-call-recording.util';export const fathomGenerateCallRecordingTitleHandler = async (payload: unknown,) =>renameFathomCallRecording({- coreApiClient: new CoreApiClient({ runAs: 'application' }),+ coreApiClient: createFathomCoreApiClient(),payload: fathomGenerateCallRecordingTitlePayloadSchema.parse(payload),});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 9518087ac4e..25b49d7eed8 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@@ -1,5 +1,4 @@import { isNonEmptyArray } from '@sniptt/guards';-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import { kv } from 'twenty-sdk/logic-function';import { z } from 'zod';@@ -8,7 +7,6 @@ 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,@@ -17,6 +15,7 @@ import { FATHOM_RECONCILE_MEDIA_IMPORTS_UNIVERSAL_IDENTIFIER } from 'src/constanimport { type FathomMediaReconciliationRun } from 'src/logic-functions/types/fathom-media-reconciliation-plan.type';import { buildRetryableFathomError } from 'src/logic-functions/utils/build-retryable-fathom-error.util';import { cleanupDisconnectedFathomMediaImports } from 'src/logic-functions/utils/cleanup-disconnected-fathom-media-imports.util';+import { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.util';import { enqueueFathomJobsOrThrow } from 'src/logic-functions/utils/enqueue-fathom-jobs-or-throw.util';import { reconcileFathomMediaImports } from 'src/logic-functions/utils/reconcile-fathom-media-imports.util';@@ -67,7 +66,7 @@ export const fathomReconcileMediaImportsHandler = async (payload: unknown) => {}try {- const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const coreApiClient = createFathomCoreApiClient();const { disconnectedAccountId } = payloadParseResult.data;if (isDefined(disconnectedAccountId)) {@@ -163,7 +162,4 @@ export default defineLogicFunction({'Recovers unfinished local Fathom media imports and settles imports for disconnected accounts.',timeoutSeconds: 300,handler: fathomReconcileMediaImportsHandler,- cronTriggerSettings: {- pattern: FATHOM_MEDIA_RECONCILIATION_CRON_PATTERN,- },});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 e366eeb0ec6..7392492cc9c 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@@ -1,4 +1,3 @@-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction } from 'twenty-sdk/define';import {type InputJsonSchema,@@ -10,6 +9,7 @@ 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 { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-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';@@ -83,7 +83,7 @@ export const fathomSyncCallHandler = async (continue;}- const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const coreApiClient = createFathomCoreApiClient();const callRecordingId = computeCallRecordingIdForFathomMeeting(recordingId);const deletedCallRecordingIds = await listDeletedCallRecordingIds({coreApiClient,@@ -124,7 +124,7 @@ export default defineLogicFunction({name: 'fathom-sync-call',description:'Sync one Fathom recording into a CallRecording on demand: fetches its transcript, summary and action items and upserts them onto the record linked to the matching CalendarEvent. Useful to recover a missed webhook or to sync from a workflow.',- timeoutSeconds: 60,+ timeoutSeconds: 300,handler: fathomSyncCallHandler,toolTriggerSettings: { inputSchema: fathomSyncCallInputSchema },workflowActionTriggerSettings: {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 34009867258..bfca3191046 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@@ -1,7 +1,6 @@import { isNonEmptyString } from '@sniptt/guards';import { Fathom } from 'fathom-typescript';import { meetingFromJSON } from 'fathom-typescript/sdk/models/shared';-import { CoreApiClient } from 'twenty-client-sdk/core';import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';import { kv } from 'twenty-sdk/logic-function';import { isDefined } from 'src/utils/is-defined';@@ -10,6 +9,7 @@ import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.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 { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.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';@@ -88,7 +88,7 @@ export const fathomWebhookHandler = async (return { success: false, error: 'Invalid Fathom meeting payload' };}- const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const coreApiClient = createFathomCoreApiClient();const callRecordingId = computeCallRecordingIdForFathomMeeting(meetingParseResult.value.recordingId,);@@ -119,6 +119,6 @@ export default defineLogicFunction({name: 'fathom-webhook',description:'Verifies Fathom meeting webhooks and upserts accessible recordings into CallRecording records.',- timeoutSeconds: 60,+ timeoutSeconds: 300,handler: fathomWebhookHandler,});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-batch-payload.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-batch-payload.type.tsnew file mode 100644index 00000000000..24b06bacd9f--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-batch-payload.type.ts@@ -0,0 +1,7 @@+import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';++export type FathomBackfillBatchPayload = {+ connectedAccountId: string;+ meetings: SerializedFathomMeeting[];+ requeueAttempt?: number;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.tsindex fbd9856379f..865cedbe92e 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.ts@@ -4,4 +4,5 @@ export type FathomBackfillWorkerPayload = {createdAfter?: string;cursor?: string;pageIndex?: number;+ requeueAttempt?: number;};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-workspace-distribution-delay.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-workspace-distribution-delay.test.tsnew file mode 100644index 00000000000..607fcfbd507--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-workspace-distribution-delay.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS } from 'src/constants/fathom.constant';+import { computeWorkspaceDistributionDelay } from 'src/logic-functions/utils/compute-workspace-distribution-delay.util';++describe('computeWorkspaceDistributionDelay', () => {+ it('returns the same delay for the same workspace', () => {+ const workspaceId = '20202020-1111-4444-8888-303030303030';++ expect(computeWorkspaceDistributionDelay(workspaceId)).toBe(+ computeWorkspaceDistributionDelay(workspaceId),+ );+ });++ it('spreads different workspaces across the window', () => {+ expect(+ computeWorkspaceDistributionDelay('20202020-1111-4444-8888-303030303030'),+ ).not.toBe(+ computeWorkspaceDistributionDelay('20202020-2222-4444-8888-303030303030'),+ );+ });++ it('stays inside the distribution window', () => {+ const delayMs = computeWorkspaceDistributionDelay(+ '20202020-2222-4444-8888-303030303030',+ );++ expect(delayMs).toBeGreaterThanOrEqual(0);+ expect(delayMs).toBeLessThan(+ FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS,+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fathom-core-api-client.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fathom-core-api-client.test.tsnew file mode 100644index 00000000000..357fe32837b--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fathom-core-api-client.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it, vi } from 'vitest';++import { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.util';++const mocks = vi.hoisted(() => ({+ coreApiClientConstructor: vi.fn(),+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: class CoreApiClient {+ constructor(options: unknown) {+ mocks.coreApiClientConstructor(options);+ }+ },+}));++describe('createFathomCoreApiClient', () => {+ it('runs as the application and retries Twenty rate limits', () => {+ createFathomCoreApiClient();++ expect(mocks.coreApiClientConstructor).toHaveBeenCalledExactlyOnceWith({+ runAs: 'application',+ fetch: expect.any(Function),+ });+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fetch-with-rate-limit-retry.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fetch-with-rate-limit-retry.test.tsnew file mode 100644index 00000000000..71cc21617ec--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/create-fetch-with-rate-limit-retry.test.ts@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';++import { createFetchWithRateLimitRetry } from 'src/logic-functions/utils/create-fetch-with-rate-limit-retry.util';++const fetchMock = vi.fn<typeof fetch>();+let fetchWithRateLimitRetry: typeof fetch;+const OPTIONS = {+ method: 'POST',+ body: JSON.stringify({ query: 'mutation { cancel }' }),+};+const rateLimitedResponse = (retryAfterMs: number) =>+ Response.json({+ errors: [{ extensions: { code: 'RATE_LIMITED', retryAfterMs } }],+ });++beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(Math, 'random').mockReturnValue(0);+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ fetchWithRateLimitRetry = createFetchWithRateLimitRetry();+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('createFetchWithRateLimitRetry', () => {+ it('waits for GraphQL retryAfterMs and retries only the throttled request', async () => {+ fetchMock+ .mockImplementationOnce(async () => rateLimitedResponse(15_000))+ .mockImplementationOnce(async () =>+ Response.json({ data: { cancel: { id: 'recording' } } }),+ );+ const result = fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ await vi.advanceTimersByTimeAsync(14_000);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(await (await result).json()).toEqual({+ data: { cancel: { id: 'recording' } },+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('honors HTTP Retry-After and adds jitter', async () => {+ vi.mocked(Math.random).mockReturnValue(0.5);+ fetchMock+ .mockImplementationOnce(+ async () =>+ new Response('rate limited', {+ status: 429,+ headers: { 'Retry-After': '5' },+ }),+ )+ .mockImplementationOnce(async () => Response.json({ data: {} }));+ const result = fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ await vi.advanceTimersByTimeAsync(5_000);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(500);+ await result;+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('hands persistent throttling back to the queue after the wait budget', async () => {+ fetchMock.mockImplementation(async () => rateLimitedResponse(60_000));+ const result = fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ const assertion = expect(result).rejects.toBeInstanceOf(+ RetryableLogicFunctionError,+ );+ await vi.advanceTimersByTimeAsync(120_000);+ await assertion;+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });++ it('shares the wait budget across the requests of one run', async () => {+ fetchMock+ .mockImplementationOnce(async () => rateLimitedResponse(60_000))+ .mockImplementationOnce(async () => Response.json({ data: {} }))+ .mockImplementationOnce(async () => rateLimitedResponse(60_000))+ .mockImplementationOnce(async () => Response.json({ data: {} }))+ .mockImplementationOnce(async () => rateLimitedResponse(60_000));+ const firstRequest = fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ await vi.advanceTimersByTimeAsync(60_000);+ await firstRequest;+ const secondRequest = fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ await vi.advanceTimersByTimeAsync(60_000);+ await secondRequest;++ await expect(+ fetchWithRateLimitRetry('https://example.test/graphql', OPTIONS),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ expect(fetchMock).toHaveBeenCalledTimes(5);+ });++ it('does not replay a partially successful mutation', async () => {+ const body = {+ data: { firstMutation: { id: 'recording' }, secondMutation: null },+ errors: [{ extensions: { code: 'RATE_LIMITED', retryAfterMs: 1_000 } }],+ };+ fetchMock.mockImplementation(async () => Response.json(body));+ const response = await fetchWithRateLimitRetry(+ 'https://example.test/graphql',+ OPTIONS,+ );+ expect(await response.json()).toEqual(body);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('does not retry unrelated GraphQL errors or uncertain mutation failures', async () => {+ fetchMock+ .mockImplementationOnce(async () =>+ Response.json({+ errors: [{ extensions: { code: 'FORBIDDEN' } }],+ }),+ )+ .mockImplementationOnce(+ async () => new Response('unavailable', { status: 503 }),+ );+ await fetchWithRateLimitRetry('https://example.test/graphql', OPTIONS);+ expect(+ (await fetchWithRateLimitRetry('https://example.test/graphql', OPTIONS))+ .status,+ ).toBe(503);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-requeue-delay.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-requeue-delay.test.tsnew file mode 100644index 00000000000..ed34900b641--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-requeue-delay.test.ts@@ -0,0 +1,53 @@+import { ConnectionError } from 'fathom-typescript/sdk/models/errors';+import { describe, expect, it } from 'vitest';++import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';+import { buildFathomRateLimitError } from 'src/__tests__/utils/build-fathom-rate-limit-error.util';+import { buildFathomServerError } from 'src/__tests__/utils/build-fathom-server-error.util';+import { getFathomRequeueDelay } from 'src/logic-functions/utils/get-fathom-requeue-delay.util';++const NOW = new Date('2026-09-05T12:00:00.000Z');++describe('getFathomRequeueDelay', () => {+ it('waits for the Retry-After delay of a rate limit', () => {+ expect(+ getFathomRequeueDelay({+ error: buildFathomRateLimitError('90'),+ now: NOW,+ }),+ ).toBe(90_000);+ });++ it('waits at least five seconds when Retry-After is zero', () => {+ expect(+ getFathomRequeueDelay({+ error: buildFathomRateLimitError('0'),+ now: NOW,+ }),+ ).toBe(5_000);+ });++ it('caps a Retry-After delay at five minutes', () => {+ expect(+ getFathomRequeueDelay({+ error: buildFathomRateLimitError('3600'),+ now: NOW,+ }),+ ).toBe(300_000);+ });++ it.each([+ ['a rate limit without Retry-After', buildFathomRateLimitError()],+ ['a Fathom outage', buildFathomServerError()],+ ['a network failure', new ConnectionError('connection refused')],+ ])('waits a minute after %s', (_description, error) => {+ expect(getFathomRequeueDelay({ error, now: NOW })).toBe(60_000);+ });++ it.each([+ ['a permanent Fathom rejection', buildFathomNotFoundError()],+ ['an unexpected error', new Error('boom')],+ ])('does not re-enqueue after %s', (_description, error) => {+ expect(getFathomRequeueDelay({ error, now: NOW })).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/as-record.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/as-record.util.tsnew file mode 100644index 00000000000..63e7cfcddd2--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/as-record.util.ts@@ -0,0 +1,6 @@+import { isArray, isObject } from '@sniptt/guards';++export const asRecord = (value: unknown): Record<string, unknown> | undefined =>+ isObject(value) && !isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-workspace-distribution-delay.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-workspace-distribution-delay.util.tsnew file mode 100644index 00000000000..529f8188e9b--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-workspace-distribution-delay.util.ts@@ -0,0 +1,9 @@+import { createHash } from 'crypto';++import { FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS } from 'src/constants/fathom.constant';++export const computeWorkspaceDistributionDelay = (+ workspaceId: string,+): number =>+ createHash('sha256').update(workspaceId).digest().readUInt32BE(0) %+ FATHOM_WORKSPACE_DISTRIBUTION_WINDOW_MILLISECONDS;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-core-api-client.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-core-api-client.util.tsnew file mode 100644index 00000000000..e8db4db2a16--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-core-api-client.util.ts@@ -0,0 +1,9 @@+import { CoreApiClient } from 'twenty-client-sdk/core';++import { createFetchWithRateLimitRetry } from 'src/logic-functions/utils/create-fetch-with-rate-limit-retry.util';++export const createFathomCoreApiClient = (): CoreApiClient =>+ new CoreApiClient({+ runAs: 'application',+ fetch: createFetchWithRateLimitRetry(),+ });diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fetch-with-rate-limit-retry.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fetch-with-rate-limit-retry.util.tsnew file mode 100644index 00000000000..3513c5d407d--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fetch-with-rate-limit-retry.util.ts@@ -0,0 +1,95 @@+import {+ isNonEmptyArray,+ isNumber,+ isString,+ isUndefined,+} from '@sniptt/guards';+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';++import { asRecord } from 'src/logic-functions/utils/as-record.util';++const MAX_ATTEMPTS = 8;+const MAX_TOTAL_WAIT_MS = 120_000;+const MAX_RETRY_AFTER_MS = 60_000;++const parseRetryAfterHeaderMs = (retryAfter: string | null): number => {+ if (!isString(retryAfter)) {+ return 0;+ }++ if (Number.isFinite(Number(retryAfter))) {+ return Math.max(0, Number(retryAfter) * 1_000);+ }++ const delayMs = Date.parse(retryAfter) - Date.now();++ return Number.isFinite(delayMs) ? Math.max(0, delayMs) : 0;+};++const getRateLimitDelayMs = async (+ response: Response,+): Promise<number | undefined> => {+ const retryAfter = response.headers.get('retry-after');+ const headerDelayMs = parseRetryAfterHeaderMs(retryAfter);++ try {+ const body = asRecord(await response.clone().json());+ const errors = body?.errors;+ const data = asRecord(body?.data);++ if (+ isNonEmptyArray(errors) &&+ Object.values(data ?? {}).every((value) => value === null) &&+ errors.every(+ (error) =>+ asRecord(asRecord(error)?.extensions)?.code === 'RATE_LIMITED',+ )+ ) {+ return Math.max(+ 0,+ ...errors.map((error) => {+ const delayMs = asRecord(asRecord(error)?.extensions)?.retryAfterMs;+ return isNumber(delayMs) && Number.isFinite(delayMs) ? delayMs : 0;+ }),+ );+ }+ } catch {}++ return response.status === 429 ? headerDelayMs : undefined;+};++export const createFetchWithRateLimitRetry = (): typeof fetch => {+ let totalWaitMs = 0;++ return async (input, options) => {+ for (let attempt = 1; ; attempt += 1) {+ const response = await fetch(input, options);+ const retryAfterMs = await getRateLimitDelayMs(response);++ if (isUndefined(retryAfterMs) || options?.signal?.aborted) {+ return response;+ }++ const delayMs =+ Math.max(+ Math.min(2_000 * 2 ** (attempt - 1), 30_000),+ Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),+ ) ++ Math.random() * 1_000;++ await response.body?.cancel();++ if (+ attempt >= MAX_ATTEMPTS ||+ totalWaitMs + delayMs > MAX_TOTAL_WAIT_MS+ ) {+ throw new RetryableLogicFunctionError(+ '[fathom] Twenty API rate limit retry budget exhausted',+ );+ }++ totalWaitMs += delayMs;+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ }+ };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-batch.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-batch.util.tsnew file mode 100644index 00000000000..45bb00001f2--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-batch.util.ts@@ -0,0 +1,24 @@+import { FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type FathomBackfillBatchPayload } from 'src/logic-functions/types/fathom-backfill-batch-payload.type';+import { enqueueFathomJobsOrThrow } from 'src/logic-functions/utils/enqueue-fathom-jobs-or-throw.util';+import { reserveFathomImportSlots } from 'src/logic-functions/utils/reserve-fathom-import-slots.util';++export const enqueueFathomBackfillBatch = async ({+ notBeforeDelayMilliseconds,+ ...payload+}: FathomBackfillBatchPayload & {+ notBeforeDelayMilliseconds?: number;+}): Promise<void> => {+ const { slotDelays } = await reserveFathomImportSlots({+ connectedAccountId: payload.connectedAccountId,+ slotCount: 1,+ notBeforeDelayMilliseconds,+ });++ await enqueueFathomJobsOrThrow({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER,+ payloads: [payload],+ delayMs: slotDelays[0],+ });+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-workspace-distributed-job.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-workspace-distributed-job.util.tsnew file mode 100644index 00000000000..05eef3e1322--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-workspace-distributed-job.util.ts@@ -0,0 +1,27 @@+import { buildRetryableFathomError } from 'src/logic-functions/utils/build-retryable-fathom-error.util';+import { computeWorkspaceDistributionDelay } from 'src/logic-functions/utils/compute-workspace-distribution-delay.util';+import { enqueueFathomJobsOrThrow } from 'src/logic-functions/utils/enqueue-fathom-jobs-or-throw.util';++export const enqueueWorkspaceDistributedJob = async ({+ workspaceId,+ logicFunctionUniversalIdentifier,+ operation,+}: {+ workspaceId: string;+ logicFunctionUniversalIdentifier: string;+ operation: string;+}): Promise<{ delayMs: number }> => {+ const delayMs = computeWorkspaceDistributionDelay(workspaceId);++ try {+ await enqueueFathomJobsOrThrow({+ logicFunctionUniversalIdentifier,+ payloads: [{}],+ delayMs,+ });+ } catch (error) {+ throw buildRetryableFathomError({ operation, error });+ }++ return { delayMs };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-requeue-delay.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-requeue-delay.util.tsnew file mode 100644index 00000000000..bfdb9dac46b--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-requeue-delay.util.ts@@ -0,0 +1,32 @@+import {+ FATHOM_MAX_REQUEUE_DELAY_MILLISECONDS,+ FATHOM_MIN_REQUEUE_DELAY_MILLISECONDS,+ FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS,+} from 'src/constants/fathom.constant';+import { getFathomRetryAfterDelay } from 'src/logic-functions/utils/get-fathom-retry-after-delay.util';+import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fathom-error.util';+import { isDefined } from 'src/utils/is-defined';++export const getFathomRequeueDelay = ({+ error,+ now,+}: {+ error: unknown;+ now: Date;+}): number | undefined => {+ const retryAfterDelay = getFathomRetryAfterDelay({ error, now });++ if (isDefined(retryAfterDelay)) {+ return Math.min(+ Math.max(+ Math.ceil(retryAfterDelay),+ FATHOM_MIN_REQUEUE_DELAY_MILLISECONDS,+ ),+ FATHOM_MAX_REQUEUE_DELAY_MILLISECONDS,+ );+ }++ return isTransientFathomError(error)+ ? FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS+ : undefined;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-retry-after-delay.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-retry-after-delay.util.tsindex 049dc716744..984938d95b1 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-retry-after-delay.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-retry-after-delay.util.ts@@ -1,7 +1,7 @@import { isNonEmptyString } from '@sniptt/guards';import { FathomError } from 'fathom-typescript/sdk/models/errors';-const FATHOM_RATE_LIMIT_FALLBACK_DELAY_MILLISECONDS = 60_000;+import { FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS } from 'src/constants/fathom.constant';export const getFathomRetryAfterDelay = ({error,@@ -17,7 +17,7 @@ export const getFathomRetryAfterDelay = ({const retryAfter = error.headers.get('retry-after')?.trim();if (!isNonEmptyString(retryAfter)) {- return FATHOM_RATE_LIMIT_FALLBACK_DELAY_MILLISECONDS;+ return FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS;}const retryAfterSeconds = Number(retryAfter);@@ -27,5 +27,5 @@ export const getFathomRetryAfterDelay = ({return Number.isFinite(delayMilliseconds) && delayMilliseconds >= 0? delayMilliseconds- : FATHOM_RATE_LIMIT_FALLBACK_DELAY_MILLISECONDS;+ : FATHOM_RETRY_FALLBACK_DELAY_MILLISECONDS;};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/run-fathom-media-import.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/run-fathom-media-import.util.tsindex 1a9a3da40a3..37a7f8861ed 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/run-fathom-media-import.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/run-fathom-media-import.util.ts@@ -1,6 +1,5 @@import { Fathom } from 'fathom-typescript';import { type RecordingDownload } from 'fathom-typescript/sdk/models/shared';-import { CoreApiClient } from 'twenty-client-sdk/core';import { getConnection } from 'twenty-sdk/logic-function';import { FATHOM_MEDIA_FAILURE_REASON } from 'src/constants/fathom-media-failure-reason.constant';@@ -13,6 +12,7 @@ import { applyFathomMediaDownload } from 'src/logic-functions/utils/apply-fathomimport { buildRetryableFathomError } from 'src/logic-functions/utils/build-retryable-fathom-error.util';import { claimFathomMediaImport } from 'src/logic-functions/utils/claim-fathom-media-import.util';import { completeFathomCallRecordingImport } from 'src/logic-functions/utils/complete-fathom-call-recording-import.util';+import { createFathomCoreApiClient } from 'src/logic-functions/utils/create-fathom-core-api-client.util';import { enqueueFathomMediaDownloadPoll } from 'src/logic-functions/utils/enqueue-fathom-media-download-poll.util';import { enqueueFathomMediaDownloadRequest } from 'src/logic-functions/utils/enqueue-fathom-media-download-request.util';import { getFathomMediaFailureReasonForError } from 'src/logic-functions/utils/get-fathom-media-failure-reason-for-error.util';@@ -28,7 +28,7 @@ const MAX_RATE_LIMIT_RETRIES = 3;export const runFathomMediaImport = async (rawPayload: unknown) => {const payload = fathomMediaImportPayloadSchema.parse(rawPayload);const { callRecordingId, attempt } = payload;- const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const coreApiClient = createFathomCoreApiClient();const recordingContext = { coreApiClient, callRecordingId };const fathomRecordingImportId = callRecordingId;const claim = await claimFathomMediaImport({