Skip to content

The open alternative to Salesforce, designed for AI.

Last contact: spend fewer calls of the shared rate limit (#27662)

martmullea52ed018c2a
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.md
index a230b9f4ccd..07c0dc9c57d 100644
--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md
+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## 1.9.0
+
+- Drop the `on-person-created` and `on-company-created` triggers. Last contact only comes from a synced email or meeting linked to a person, so a newly created person or company never has one, and recomputing the company on creation could not change anything. A mailbox sync that creates contacts spent 6 API calls per batch of 100 contacts on them.
+- Pace the backfill. Its API calls are now at least 600 ms apart, about 100 calls per minute or a fifth of the limit every install shares. It used to send them back to back, so a large workspace could use the whole limit on its own for 15 minutes. The meeting scheduling that every install and upgrade runs is paced the same way.
+- Let the backfill resume instead of starting over. A run stops taking new batches after 8 minutes and enqueues itself to continue from its cursor, so a large workspace is backfilled over several runs instead of being cut off by the 900-second timeout. When the rate limit makes it give up, it continues 2 minutes later from the batch that failed, where it used to restart from the first person. After 5 runs in a row fail before finishing a batch, the backfill stops instead of retrying that batch forever. This also applies to the "Trigger backfill" button.
+- Compute opportunities and companies in the backfill from the last contact it just wrote on people, instead of reading every email and meeting of their people again, which more than doubled its cost. Opportunities without a contacted point of contact and companies without a contacted person are now reset to empty, as they already are when an opportunity or person changes. Since those phases now trust the people's stored values, the people phase writes every field of every person and clears the ones no remaining email or meeting supports, so the last contact of an email deleted with its account or a meeting canceled after it started no longer lingers.
+- Read only the sender and team members of each email when an email is linked to a person. The other recipients never change the result, but they were read too, so a batch of emails sent to many people cost one extra call per 200 recipients. An email with neither a sender nor a team member among its participants is still counted as an inbound contact, with its date read from the message.
+
## 1.8.0
All installs of the app share one API rate limit, 500 calls per minute across every workspace. This version is about spending far fewer of those calls.
diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.json
index cc8855d5450..35214db19b5 100644
--- a/packages/twenty-apps/public/last-contact/package.json
+++ b/packages/twenty-apps/public/last-contact/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/last-contact",
- "version": "1.8.0",
+ "version": "1.9.0",
"license": "MIT",
"engines": {
"node": "^24.5.0",
diff --git a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
index 15436d83c83..b4a7506d661 100644
--- a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
+++ b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
@@ -13,7 +13,6 @@ import {
MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
} from 'src/constants/universal-identifiers';
import onCalendarInteraction from 'src/logic-functions/on-calendar-interaction';
-import onCompanyCreated from 'src/logic-functions/on-company-created';
import onMeetingHorizonReached from 'src/logic-functions/on-meeting-horizon-reached';
import onMeetingSlotReached from 'src/logic-functions/on-meeting-slot-reached';
import onEmailInteraction from 'src/logic-functions/on-email-interaction';
@@ -40,9 +39,6 @@ const opportunityCreatedHandler = onOpportunityCreated.config.handler as (
const opportunityUpdatedHandler = onOpportunityUpdated.config.handler as (
batch: unknown,
) => Promise<void>;
-const companyCreatedHandler = onCompanyCreated.config.handler as (
- batch: unknown,
-) => Promise<void>;
const personUpdatedHandler = onPersonUpdated.config.handler as (
batch: unknown,
) => Promise<void>;
@@ -1280,20 +1276,4 @@ describe('last contact handlers', () => {
expect(companyContact.lastContactItemMessageId).toBeNull();
expect(companyContact.lastContactItemCalendarEventId).toBeNull();
});
-
- it('leaves the company last contact empty when the company has no contacted people on creation', async () => {
- const companyId = await createCompany(client);
- createdCompanyIds.push(companyId);
-
- await companyCreatedHandler(
- buildBatch('company.created', companyId, { after: { id: companyId } }),
- );
-
- const companyContact = await getRelatedLastContact(
- client,
- 'company',
- companyId,
- );
- expect(companyContact.lastContactAt).toBeNull();
- });
});
diff --git a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts b/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
index c67d1a87c2d..f6a00222018 100644
--- a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
+++ b/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
@@ -11,3 +11,11 @@ export const BACKFILL_BATCH_SIZE_ENV_VAR_NAME =
'LAST_CONTACT_BACKFILL_BATCH_SIZE';
export const DEFAULT_BACKFILL_BATCH_SIZE = 200;
+
+export const BACKFILL_MIN_CALL_INTERVAL_MS = 600;
+
+export const BACKFILL_RUN_BUDGET_MS = 8 * 60 * 1000;
+
+export const BACKFILL_RATE_LIMITED_RESUME_DELAY_MS = 2 * 60 * 1000;
+
+export const BACKFILL_MAX_STALLED_RUNS = 5;
diff --git a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
index ee59b8f89a0..af4e91daa49 100644
--- a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
@@ -21,10 +21,6 @@ export const OPPORTUNITY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'6659b54f-2f46-412b-aa7d-03aa9f1c5133';
export const OPPORTUNITY_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'071a1c3e-b580-4312-806d-ff27287292ae';
-export const COMPANY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
- 'd0631934-2f06-4799-9b33-6937f78e16ff';
-export const PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
- 'cf7460cc-4c48-4412-9a1a-0c30e4960fce';
export const PERSON_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'a967064f-f440-43cd-bfbe-907c95d4563f';
export const HEALTH_CHECK_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
index be96dedecee..a39ba1f1f3e 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
@@ -1,21 +1,25 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
const {
queryMock,
+ enqueueJobsMock,
scheduleUpcomingPersonMeetingsMock,
collectPersonMeetingParticipantsMock,
applyMeetingInteractionsMock,
backfillPeopleMock,
- backfillOpportunitiesMock,
- backfillCompaniesMock,
+ recomputeOpportunitiesMock,
+ recomputeCompaniesMock,
} = vi.hoisted(() => ({
queryMock: vi.fn(),
+ enqueueJobsMock: vi.fn(),
scheduleUpcomingPersonMeetingsMock: vi.fn(),
collectPersonMeetingParticipantsMock: vi.fn(),
applyMeetingInteractionsMock: vi.fn(),
backfillPeopleMock: vi.fn(),
- backfillOpportunitiesMock: vi.fn(),
- backfillCompaniesMock: vi.fn(),
+ recomputeOpportunitiesMock: vi.fn(),
+ recomputeCompaniesMock: vi.fn(),
}));
vi.mock('twenty-client-sdk/core', () => ({
@@ -24,6 +28,15 @@ vi.mock('twenty-client-sdk/core', () => ({
}),
}));
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
+vi.mock('src/utils/create-paced-client', () => ({
+ createPacedClient: (client: unknown) => client,
+}));
+
vi.mock('src/utils/schedule-meetings', () => ({
scheduleUpcomingPersonMeetings: scheduleUpcomingPersonMeetingsMock,
}));
@@ -44,14 +57,21 @@ vi.mock('src/utils/backfill-people-last-contact', () => ({
backfillPeopleLastContact: backfillPeopleMock,
}));
-vi.mock('src/utils/backfill-opportunities-last-contact', () => ({
- backfillOpportunitiesLastContact: backfillOpportunitiesMock,
+vi.mock('src/utils/recompute-opportunity-last-contact', () => ({
+ recomputeOpportunitiesLastContact: recomputeOpportunitiesMock,
}));
-vi.mock('src/utils/backfill-companies-last-contact', () => ({
- backfillCompaniesLastContact: backfillCompaniesMock,
+vi.mock('src/utils/recompute-company-last-contact', () => ({
+ recomputeCompaniesLastContact: recomputeCompaniesMock,
}));
+import {
+ BACKFILL_MAX_STALLED_RUNS,
+ BACKFILL_RATE_LIMITED_RESUME_DELAY_MS,
+ BACKFILL_RUN_BUDGET_MS,
+} from 'src/constants/backfill';
+import { BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+
import backfillLastContact from '../backfill-last-contact';
type ConnectionQuery = Record<
@@ -59,9 +79,9 @@ type ConnectionQuery = Record<
{ __args: { first: number; after?: string } }
>;
-const RECORDS_BY_QUERY_FIELD: Record<string, Record<string, unknown>[]> = {
+const RECORDS_BY_QUERY_FIELD: Record<string, { id: string }[]> = {
people: [{ id: 'person-1' }, { id: 'person-2' }, { id: 'person-3' }],
- opportunities: [{ id: 'opportunity-1', pointOfContactId: 'person-1' }],
+ opportunities: [{ id: 'opportunity-1' }],
companies: [],
};
@@ -72,19 +92,16 @@ const handler = backfillLastContact.config.handler as (
let events: string[] = [];
const recordBatch =
- (phase: string) =>
- async (_client: unknown, records: (string | { id: string })[]) => {
+ (phase: string) => async (_client: unknown, recordIds: string[]) => {
await Promise.resolve();
- events.push(
- `backfilled ${phase} ${records
- .map((record) => (typeof record === 'string' ? record : record.id))
- .join(',')}`,
- );
+ events.push(`backfilled ${phase} ${recordIds.join(',')}`);
};
beforeEach(() => {
events = [];
+ enqueueJobsMock.mockReset();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
scheduleUpcomingPersonMeetingsMock.mockReset();
scheduleUpcomingPersonMeetingsMock.mockResolvedValue(undefined);
collectPersonMeetingParticipantsMock.mockReset();
@@ -113,10 +130,14 @@ beforeEach(() => {
backfillPeopleMock.mockReset();
backfillPeopleMock.mockImplementation(recordBatch('people'));
- backfillOpportunitiesMock.mockReset();
- backfillOpportunitiesMock.mockImplementation(recordBatch('opportunities'));
- backfillCompaniesMock.mockReset();
- backfillCompaniesMock.mockImplementation(recordBatch('companies'));
+ recomputeOpportunitiesMock.mockReset();
+ recomputeOpportunitiesMock.mockImplementation(recordBatch('opportunities'));
+ recomputeCompaniesMock.mockReset();
+ recomputeCompaniesMock.mockImplementation(recordBatch('companies'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
});
describe('backfill-last-contact', () => {
@@ -139,14 +160,7 @@ describe('backfill-last-contact', () => {
'backfilled opportunities opportunity-1',
'read companies from 0',
]);
- });
-
- it('should hand each opportunity to its batch with its point of contact', async () => {
- await handler({ newVersion: '1.6.0' });
-
- expect(backfillOpportunitiesMock).toHaveBeenCalledWith(expect.anything(), [
- { id: 'opportunity-1', pointOfContactId: 'person-1' },
- ]);
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
});
it.each(['1.4.1', '1.5.0'])(
@@ -181,7 +195,138 @@ describe('backfill-last-contact', () => {
},
);
expect(applyMeetingInteractionsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should hand the rest of the backfill to a new run once the run budget is spent', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-12T12:00:00.000Z'));
+ backfillPeopleMock.mockImplementationOnce(async (_client, recordIds) => {
+ await recordBatch('people')(_client, recordIds);
+ vi.setSystemTime(Date.now() + BACKFILL_RUN_BUDGET_MS);
+ });
- vi.useRealTimers();
+ await expect(handler({ newVersion: '1.6.0' })).resolves.toEqual({
+ outcome: 'paused',
+ phases: [{ phase: 'people', count: 2 }],
+ resumeFrom: { phase: 'people', after: '2' },
+ });
+
+ expect(events).toEqual([
+ 'read people from 0',
+ 'backfilled people person-1,person-2',
+ ]);
+ expect(enqueueJobsMock).toHaveBeenCalledWith({
+ logicFunctionUniversalIdentifier:
+ BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ payload: {
+ resumeFrom: { phase: 'people', after: '2' },
+ stalledRunCount: 0,
+ },
+ },
+ ],
+ });
+ });
+
+ it('should resume from the cursor without scheduling meetings again', async () => {
+ await expect(
+ handler({ resumeFrom: { phase: 'people', after: '2' } }),
+ ).resolves.toMatchObject({ outcome: 'completed' });
+
+ expect(events).toEqual([
+ 'read people from 2',
+ 'backfilled people person-3',
+ 'read opportunities from 0',
+ 'backfilled opportunities opportunity-1',
+ 'read companies from 0',
+ ]);
+ expect(scheduleUpcomingPersonMeetingsMock).not.toHaveBeenCalled();
+ expect(applyMeetingInteractionsMock).not.toHaveBeenCalled();
+ });
+
+ it('should resume a later phase from its start', async () => {
+ await handler({ resumeFrom: { phase: 'opportunities' } });
+
+ expect(events).toEqual([
+ 'read opportunities from 0',
+ 'backfilled opportunities opportunity-1',
+ 'read companies from 0',
+ ]);
+ });
+
+ it('should redo the rate-limited batch in a delayed run instead of restarting the backfill', async () => {
+ backfillPeopleMock
+ .mockImplementationOnce(recordBatch('people'))
+ .mockRejectedValueOnce(new RetryableLogicFunctionError('Rate limited'));
+
+ await expect(handler({ newVersion: '1.6.0' })).resolves.toEqual({
+ outcome: 'paused',
+ phases: [{ phase: 'people', count: 2 }],
+ resumeFrom: { phase: 'people', after: '2' },
+ });
+
+ expect(enqueueJobsMock).toHaveBeenCalledWith({
+ logicFunctionUniversalIdentifier:
+ BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ payload: {
+ resumeFrom: { phase: 'people', after: '2' },
+ stalledRunCount: 0,
+ },
+ },
+ ],
+ delayMs: BACKFILL_RATE_LIMITED_RESUME_DELAY_MS,
+ });
+ });
+
+ it('should count the runs in a row that fail before finishing a batch', async () => {
+ backfillPeopleMock.mockRejectedValueOnce(
+ new RetryableLogicFunctionError('Gateway time-out'),
+ );
+
+ await expect(
+ handler({
+ resumeFrom: { phase: 'people', after: '2' },
+ stalledRunCount: BACKFILL_MAX_STALLED_RUNS - 2,
+ }),
+ ).resolves.toMatchObject({ outcome: 'paused' });
+
+ expect(enqueueJobsMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ jobs: [
+ {
+ payload: {
+ resumeFrom: { phase: 'people', after: '2' },
+ stalledRunCount: BACKFILL_MAX_STALLED_RUNS - 1,
+ },
+ },
+ ],
+ }),
+ );
+ });
+
+ it('should stop the backfill once too many runs in a row fail before finishing a batch', async () => {
+ backfillPeopleMock.mockRejectedValueOnce(
+ new RetryableLogicFunctionError('Gateway time-out'),
+ );
+
+ await expect(
+ handler({
+ resumeFrom: { phase: 'people', after: '2' },
+ stalledRunCount: BACKFILL_MAX_STALLED_RUNS - 1,
+ }),
+ ).rejects.toThrow('Backfill stopped');
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ });
+
+ it('should fail the run on errors that are not rate limits', async () => {
+ backfillPeopleMock.mockRejectedValueOnce(new Error('Bad Request'));
+
+ await expect(handler({ newVersion: '1.6.0' })).rejects.toThrow(
+ 'Bad Request',
+ );
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
});
});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts
index 41ee57e859c..9703c554749 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts
@@ -41,7 +41,10 @@ const buildBatch = (
})),
});
-const setupQueryMock = (messageParticipants: Record<string, unknown>[]) => {
+const setupQueryMock = (
+ messageParticipants: Record<string, unknown>[],
+ messages: Record<string, unknown>[] = [],
+) => {
queryMock.mockImplementation((query) => {
if (query.messageParticipants) {
return Promise.resolve({
@@ -49,6 +52,10 @@ const setupQueryMock = (messageParticipants: Record<string, unknown>[]) => {
});
}
+ if (query.messages) {
+ return Promise.resolve({ messages: buildPage(messages) });
+ }
+
if (query.people) {
const requestedIds: string[] = query.people.__args.filter.id.in;
return Promise.resolve({
@@ -151,7 +158,20 @@ describe('on-email-interaction handler', () => {
expect(participantQueries).toHaveLength(1);
expect(
participantQueries[0][0].messageParticipants.__args.filter,
- ).toEqual({ messageId: { in: [OLDER_MESSAGE_ID, MESSAGE_ID] } });
+ ).toEqual({
+ and: [
+ { messageId: { in: [OLDER_MESSAGE_ID, MESSAGE_ID] } },
+ {
+ or: [
+ { role: { eq: 'FROM' } },
+ { workspaceMemberId: { is: 'NOT_NULL' } },
+ ],
+ },
+ ],
+ });
+ expect(queryMock.mock.calls.some(([query]) => query.messages)).toBe(
+ false,
+ );
const personUpserts = mutationMock.mock.calls.filter(
([mutation]) => mutation.createPeople,
@@ -199,4 +219,31 @@ describe('on-email-interaction handler', () => {
expect(mutationMock).not.toHaveBeenCalled();
});
+
+ it('counts a message without a sender or team member participant as an inbound email', async () => {
+ setupQueryMock([], [{ id: MESSAGE_ID, receivedAt: RECEIVED_AT }]);
+
+ await handler(
+ buildBatch([{ personId: PERSON_ID, messageId: MESSAGE_ID }]),
+ );
+
+ const messageQueries = queryMock.mock.calls.filter(
+ ([query]) => query.messages,
+ );
+ expect(messageQueries).toHaveLength(1);
+ expect(messageQueries[0][0].messages.__args.filter).toEqual({
+ id: { in: [MESSAGE_ID] },
+ });
+ expect(mutationMock.mock.calls[0][0].createPeople.__args.data).toEqual([
+ {
+ id: PERSON_ID,
+ lastContactAt: RECEIVED_AT,
+ lastContactById: null,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ lastInboundAt: RECEIVED_AT,
+ lastEmailId: MESSAGE_ID,
+ },
+ ]);
+ });
});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
index bad6a6d40c3..991bbab1722 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
@@ -1,16 +1,33 @@
import { CoreApiClient } from 'twenty-client-sdk/core';
import { definePostInstallLogicFunction, type InstallPayload } from 'twenty-sdk/define';
+import { enqueueJobs } from 'twenty-sdk/logic-function';
import { compare } from 'semver'
+import {
+ BACKFILL_MAX_STALLED_RUNS,
+ BACKFILL_MIN_CALL_INTERVAL_MS,
+ BACKFILL_RATE_LIMITED_RESUME_DELAY_MS,
+ BACKFILL_RUN_BUDGET_MS,
+} from 'src/constants/backfill';
import { MEETING_INSTALL_LOOKBACK_MS } from 'src/constants/meeting-schedule';
import { BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { getBackfillBatchSize } from 'src/utils/backfill-settings';
import { applyMeetingInteractions } from 'src/utils/apply-meeting-interactions';
import { collectPersonMeetingParticipants } from 'src/utils/collect-person-meeting-participants';
+import { createPacedClient } from 'src/utils/create-paced-client';
+import { executeWithRetry } from 'src/utils/execute-with-retry';
import { scheduleUpcomingPersonMeetings } from 'src/utils/schedule-meetings';
-import { runLastContactBackfill } from 'src/utils/run-last-contact-backfill';
+import {
+ type BackfillCursor,
+ runLastContactBackfill,
+} from 'src/utils/run-last-contact-backfill';
import { isDefined } from 'twenty-sdk/utils';
+type BackfillPayload = InstallPayload & {
+ resumeFrom?: BackfillCursor;
+ stalledRunCount?: number;
+};
+
const shouldRunPostInstall = ({
previousVersion,
newVersion
@@ -26,45 +43,79 @@ const shouldRunPostInstall = ({
return false
}
-const handler = async ({
- previousVersion,
- newVersion
-}: InstallPayload): Promise<object> => {
- const client = new CoreApiClient();
+const handler = async (payload: BackfillPayload): Promise<object> => {
+ const deadlineMs = Date.now() + BACKFILL_RUN_BUDGET_MS;
+ const client = createPacedClient(
+ new CoreApiClient(),
+ BACKFILL_MIN_CALL_INTERVAL_MS,
+ );
+ const { resumeFrom } = payload;
+
+ if (!isDefined(resumeFrom)) {
+ await scheduleUpcomingPersonMeetings(client);
- await scheduleUpcomingPersonMeetings(client);
+ const recentlyStartedParticipants = await collectPersonMeetingParticipants(
+ client,
+ { from: new Date(Date.now() - MEETING_INSTALL_LOOKBACK_MS), to: new Date() },
+ );
- const recentlyStartedParticipants = await collectPersonMeetingParticipants(
- client,
- { from: new Date(Date.now() - MEETING_INSTALL_LOOKBACK_MS), to: new Date() },
- );
+ await applyMeetingInteractions(client, recentlyStartedParticipants);
+
+ if(!shouldRunPostInstall(payload)) {
+ console.log('Post install skipped');
- await applyMeetingInteractions(client, recentlyStartedParticipants);
+ return {};
+ }
- if(!shouldRunPostInstall({
- previousVersion,
- newVersion
- })) {
- console.log('Post install skipped');
+ console.log(
+ 'Backfill params',
+ JSON.stringify({ batchSize: getBackfillBatchSize() }),
+ );
+ }
+
+ const { phases, pause } = await runLastContactBackfill(client, {
+ resumeFrom,
+ deadlineMs,
+ });
+
+ if (!isDefined(pause)) {
+ return { outcome: 'completed', phases };
+ }
+
+ const hasStalled =
+ pause.reason === 'rate-limited' && phases.every(({ count }) => count === 0);
+ const stalledRunCount = hasStalled ? (payload.stalledRunCount ?? 0) + 1 : 0;
- return {}
+ if (stalledRunCount >= BACKFILL_MAX_STALLED_RUNS) {
+ throw new Error(
+ `Backfill stopped: ${stalledRunCount} runs in a row failed before finishing a batch at ${JSON.stringify(pause.resumeFrom)}`,
+ );
}
console.log(
- 'Backfill params',
- JSON.stringify({ batchSize: getBackfillBatchSize() }),
+ 'Backfill paused',
+ JSON.stringify({ reason: pause.reason, resumeFrom: pause.resumeFrom }),
);
- const phases = await runLastContactBackfill(client);
+ await executeWithRetry(() =>
+ enqueueJobs({
+ logicFunctionUniversalIdentifier:
+ BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [{ payload: { resumeFrom: pause.resumeFrom, stalledRunCount } }],
+ ...(pause.reason === 'rate-limited'
+ ? { delayMs: BACKFILL_RATE_LIMITED_RESUME_DELAY_MS }
+ : {}),
+ }),
+ );
- return { outcome: 'completed', phases };
+ return { outcome: 'paused', phases, resumeFrom: pause.resumeFrom };
};
export default definePostInstallLogicFunction({
universalIdentifier: BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'backfill-last-contact',
description:
- 'Schedules upcoming meetings, then backfills last-contact fields on people, then opportunities, then companies after installation, one batch of records at a time within this run.',
+ 'Schedules upcoming meetings, then backfills last-contact fields on people, then opportunities, then companies after installation, one batch of records at a time at a paced call rate. A run that reaches its time budget or keeps getting rate limited enqueues itself to resume from where it stopped, and the backfill stops after 5 runs in a row fail before finishing a batch.',
timeoutSeconds: 900,
shouldRunOnVersionUpgrade: true,
handler,
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts
deleted file mode 100644
index 999b5baf183..00000000000
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import {
- defineLogicFunction,
- type ObjectRecordCreateEvent,
-} from 'twenty-sdk/define';
-import { type DatabaseEventBatchPayload } from 'twenty-sdk/logic-function';
-import { CoreApiClient } from 'twenty-client-sdk/core';
-
-import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
-import { COMPANY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';
-
-type CompanyCreate = { id?: string | null };
-
-const handler = async (
- batch: DatabaseEventBatchPayload<ObjectRecordCreateEvent<CompanyCreate>>,
-): Promise<void> => {
- const companyIds = new Set<string>();
-
- for (const event of batch.events) {
- const companyId = event.properties.after.id ?? event.recordId;
-
- if (companyId) {
- companyIds.add(companyId);
- }
- }
-
- if (companyIds.size === 0) {
- return;
- }
-
- await recomputeCompaniesLastContact(new CoreApiClient(), [...companyIds]);
-};
-
-export default defineLogicFunction({
- universalIdentifier: COMPANY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- name: 'on-company-created',
- description:
- "Computes a company's last contact from its people when the company is created.",
- timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
- databaseEventTriggerSettings: {
- eventName: 'company.created',
- batchMode: true,
- },
- handler,
-});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts
deleted file mode 100644
index 8f33bf0a138..00000000000
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import {
- defineLogicFunction,
- type ObjectRecordCreateEvent,
-} from 'twenty-sdk/define';
-import { type DatabaseEventBatchPayload } from 'twenty-sdk/logic-function';
-import { CoreApiClient } from 'twenty-client-sdk/core';
-
-import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
-import { PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';
-
-type PersonCreate = { companyId?: string | null };
-
-const handler = async (
- batch: DatabaseEventBatchPayload<ObjectRecordCreateEvent<PersonCreate>>,
-): Promise<void> => {
- const companyIds = new Set<string>();
-
- for (const event of batch.events) {
- const companyId = event.properties.after.companyId;
-
- if (companyId) {
- companyIds.add(companyId);
- }
- }
-
- if (companyIds.size === 0) {
- return;
- }
-
- await recomputeCompaniesLastContact(new CoreApiClient(), [...companyIds]);
-};
-
-export default defineLogicFunction({
- universalIdentifier: PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- name: 'on-person-created',
- description:
- "Recomputes the company's last contact when a person is created with a company.",
- timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
- databaseEventTriggerSettings: {
- eventName: 'person.created',
- batchMode: true,
- },
- handler,
-});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts
new file mode 100644
index 00000000000..d59ffd458c1
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { buildPersonAggregatesMock } = vi.hoisted(() => ({
+ buildPersonAggregatesMock: vi.fn(),
+}));
+
+vi.mock('src/utils/person-last-contact-aggregation', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ buildPersonAggregates: buildPersonAggregatesMock,
+}));
+
+import { backfillPeopleLastContact } from 'src/utils/backfill-people-last-contact';
+
+const CONTACTED_PERSON_ID = '11111111-1111-1111-1111-111111111111';
+const UNCONTACTED_PERSON_ID = '22222222-2222-2222-2222-222222222222';
+const MESSAGE_ID = '33333333-3333-3333-3333-333333333333';
+const MEMBER_ID = '44444444-4444-4444-4444-444444444444';
+const RECEIVED_AT = '2026-06-10T09:00:00.000Z';
+
+const client = {
+ query: vi.fn(),
+ mutation: vi.fn().mockResolvedValue({}),
+};
+
+beforeEach(() => {
+ client.mutation.mockClear();
+ buildPersonAggregatesMock.mockReset();
+});
+
+describe('backfillPeopleLastContact', () => {
+ it('writes every field of every person, clearing those no interaction supports', async () => {
+ buildPersonAggregatesMock.mockResolvedValue(
+ new Map([
+ [
+ CONTACTED_PERSON_ID,
+ {
+ lastContactAt: RECEIVED_AT,
+ lastContactById: MEMBER_ID,
+ item: { kind: 'email', id: MESSAGE_ID },
+ lastOutboundAt: RECEIVED_AT,
+ lastEmail: { at: RECEIVED_AT, id: MESSAGE_ID },
+ },
+ ],
+ ]),
+ );
+
+ await backfillPeopleLastContact(client as never, [
+ CONTACTED_PERSON_ID,
+ UNCONTACTED_PERSON_ID,
+ ]);
+
+ expect(client.mutation).toHaveBeenCalledTimes(1);
+ expect(client.mutation.mock.calls[0][0].createPeople.__args).toEqual({
+ upsert: true,
+ data: [
+ {
+ id: CONTACTED_PERSON_ID,
+ lastContactAt: RECEIVED_AT,
+ lastContactById: MEMBER_ID,
+ lastOutboundAt: RECEIVED_AT,
+ lastInboundAt: null,
+ lastEmailId: MESSAGE_ID,
+ lastMeetingId: null,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ {
+ id: UNCONTACTED_PERSON_ID,
+ lastContactAt: null,
+ lastContactById: null,
+ lastOutboundAt: null,
+ lastInboundAt: null,
+ lastEmailId: null,
+ lastMeetingId: null,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: null,
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/create-paced-client.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/create-paced-client.test.ts
new file mode 100644
index 00000000000..20c8534b4fe
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/create-paced-client.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createPacedClient } from 'src/utils/create-paced-client';
+
+const MIN_CALL_INTERVAL_MS = 600;
+
+let callTimes: number[] = [];
+
+const buildClient = () => ({
+ query: vi.fn(async (request: unknown) => {
+ callTimes.push(Date.now());
+
+ return { request };
+ }),
+ mutation: vi.fn(async (request: unknown) => {
+ callTimes.push(Date.now());
+
+ return { request };
+ }),
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ callTimes = [];
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('createPacedClient', () => {
+ it('forwards queries and mutations to the client', async () => {
+ const pacedClient = createPacedClient(
+ buildClient() as never,
+ MIN_CALL_INTERVAL_MS,
+ );
+
+ await expect(pacedClient.query({ people: {} })).resolves.toEqual({
+ request: { people: {} },
+ });
+
+ const mutation = pacedClient.mutation({ createPeople: {} });
+ await vi.advanceTimersByTimeAsync(MIN_CALL_INTERVAL_MS);
+
+ await expect(mutation).resolves.toEqual({
+ request: { createPeople: {} },
+ });
+ });
+
+ it('spaces consecutive calls by the minimum interval', async () => {
+ const pacedClient = createPacedClient(
+ buildClient() as never,
+ MIN_CALL_INTERVAL_MS,
+ );
+
+ const calls = (async () => {
+ await pacedClient.query({});
+ await pacedClient.mutation({});
+ await pacedClient.query({});
+ })();
+ await vi.advanceTimersByTimeAsync(2 * MIN_CALL_INTERVAL_MS);
+ await calls;
+
+ expect(callTimes).toEqual([0, 600, 1200]);
+ });
+
+ it('spaces concurrent calls as well', async () => {
+ const pacedClient = createPacedClient(
+ buildClient() as never,
+ MIN_CALL_INTERVAL_MS,
+ );
+
+ const calls = Promise.all([
+ pacedClient.query({}),
+ pacedClient.query({}),
+ pacedClient.query({}),
+ ]);
+ await vi.advanceTimersByTimeAsync(2 * MIN_CALL_INTERVAL_MS);
+ await calls;
+
+ expect(callTimes).toEqual([0, 600, 1200]);
+ });
+
+ it('does not wait when calls are already further apart', async () => {
+ const pacedClient = createPacedClient(
+ buildClient() as never,
+ MIN_CALL_INTERVAL_MS,
+ );
+
+ await pacedClient.query({});
+ vi.setSystemTime(5_000);
+ await pacedClient.query({});
+
+ expect(callTimes).toEqual([0, 5_000]);
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.ts
deleted file mode 100644
index f481506a5ba..00000000000
--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import { collectPeopleByCompany } from 'src/utils/collect-people-by-company';
-import {
- buildRelatedUpdateData,
- buildPersonAggregates,
- pickLatestLastContact,
- pickPersonLastContact,
-} from 'src/utils/person-last-contact-aggregation';
-import {
- type RecordUpsert,
- upsertRecordsInBatches,
-} from 'src/utils/upsert-records-in-batches';
-
-export const backfillCompaniesLastContact = async (
- client: CoreApiClient,
- companyIds: string[],
-): Promise<void> => {
- const peopleByCompanyId = await collectPeopleByCompany(client, companyIds);
- const personIds = [...new Set([...peopleByCompanyId.values()].flat())];
- const aggByPersonId = await buildPersonAggregates(client, personIds);
-
- const upserts: RecordUpsert[] = [];
-
- for (const companyId of companyIds) {
- const lastContact = pickLatestLastContact(
- (peopleByCompanyId.get(companyId) ?? [])
- .map((personId) => pickPersonLastContact(aggByPersonId.get(personId)))
- .filter((contact) => contact !== undefined),
- );
-
- if (!lastContact) {
- continue;
- }
-
- upserts.push({ id: companyId, ...buildRelatedUpdateData(lastContact) });
- }
-
- await upsertRecordsInBatches(client, 'createCompanies', upserts);
-};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.ts
deleted file mode 100644
index 89ec7046987..00000000000
--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import {
- buildRelatedUpdateData,
- buildPersonAggregates,
- pickPersonLastContact,
-} from 'src/utils/person-last-contact-aggregation';
-import {
- type RecordUpsert,
- upsertRecordsInBatches,
-} from 'src/utils/upsert-records-in-batches';
-
-export type OpportunityNode = { id: string; pointOfContactId: string | null };
-
-export const backfillOpportunitiesLastContact = async (
- client: CoreApiClient,
- nodes: OpportunityNode[],
-): Promise<void> => {
- const personIds = [
- ...new Set(
- nodes
- .map((node) => node.pointOfContactId)
- .filter((id): id is string => Boolean(id)),
- ),
- ];
- const aggByPersonId = await buildPersonAggregates(client, personIds);
-
- const upserts: RecordUpsert[] = [];
-
- for (const node of nodes) {
- const lastContact = node.pointOfContactId
- ? pickPersonLastContact(aggByPersonId.get(node.pointOfContactId))
- : undefined;
-
- if (!lastContact) {
- continue;
- }
-
- upserts.push({ id: node.id, ...buildRelatedUpdateData(lastContact) });
- }
-
- await upsertRecordsInBatches(client, 'createOpportunities', upserts);
-};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
index 076e446f074..c48c2909954 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
@@ -4,28 +4,20 @@ import {
buildPersonAggregates,
buildPersonUpdateData,
} from 'src/utils/person-last-contact-aggregation';
-import {
- type RecordUpsert,
- upsertRecordsInBatches,
-} from 'src/utils/upsert-records-in-batches';
+import { upsertRecordsInBatches } from 'src/utils/upsert-records-in-batches';
export const backfillPeopleLastContact = async (
client: CoreApiClient,
personIds: string[],
): Promise<void> => {
const aggByPersonId = await buildPersonAggregates(client, personIds);
- const upserts: RecordUpsert[] = [];
-
- for (const personId of personIds) {
- const agg = aggByPersonId.get(personId);
- const data = agg ? buildPersonUpdateData(agg) : {};
-
- if (Object.keys(data).length === 0) {
- continue;
- }
-
- upserts.push({ id: personId, ...data });
- }
- await upsertRecordsInBatches(client, 'createPeople', upserts);
+ await upsertRecordsInBatches(
+ client,
+ 'createPeople',
+ personIds.map((personId) => ({
+ id: personId,
+ ...buildPersonUpdateData(aggByPersonId.get(personId)),
+ })),
+ );
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts
index 8f67529de3c..b07d9db2bc7 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts
@@ -10,6 +10,13 @@ import { type InteractionDirection } from 'src/utils/update-person-last-contact'
const PAGE_SIZE = 200;
+const SENDER_OR_TEAM_MEMBER_FILTER = {
+ or: [
+ { role: { eq: 'FROM' } },
+ { workspaceMemberId: { is: 'NOT_NULL' } },
+ ],
+};
+
export type MessageInteraction = {
receivedAt: string;
workspaceMemberId: string | null;
@@ -21,10 +28,10 @@ type MessageParticipantNode = Participant & {
message?: { receivedAt: string | null } | null;
};
-export const collectMessageInteractions = async (
+const collectSenderAndTeamMemberParticipants = async (
client: CoreApiClient,
messageIds: string[],
-): Promise<Map<string, MessageInteraction>> => {
+): Promise<Map<string, MessageParticipantNode[]>> => {
const participantsByMessageId = new Map<string, MessageParticipantNode[]>();
for (const ids of chunk(messageIds, PAGE_SIZE)) {
@@ -35,7 +42,12 @@ export const collectMessageInteractions = async (
client.query({
messageParticipants: {
__args: {
- filter: { messageId: { in: ids } },
+ filter: {
+ and: [
+ { messageId: { in: ids } },
+ SENDER_OR_TEAM_MEMBER_FILTER,
+ ],
+ },
first: PAGE_SIZE,
after,
},
@@ -74,6 +86,45 @@ export const collectMessageInteractions = async (
} while (after);
}
+ return participantsByMessageId;
+};
+
+const collectReceivedAtByMessageId = async (
+ client: CoreApiClient,
+ messageIds: string[],
+): Promise<Map<string, string>> => {
+ const receivedAtByMessageId = new Map<string, string>();
+
+ for (const ids of chunk(messageIds, PAGE_SIZE)) {
+ const { messages } = await executeWithRetry(() =>
+ client.query({
+ messages: {
+ __args: { filter: { id: { in: ids } }, first: PAGE_SIZE },
+ edges: { node: { id: true, receivedAt: true } },
+ },
+ }),
+ );
+
+ for (const edge of messages?.edges ?? []) {
+ const { id, receivedAt } = edge.node;
+
+ if (id && receivedAt) {
+ receivedAtByMessageId.set(id, receivedAt);
+ }
+ }
+ }
+
+ return receivedAtByMessageId;
+};
+
+export const collectMessageInteractions = async (
+ client: CoreApiClient,
+ messageIds: string[],
+): Promise<Map<string, MessageInteraction>> => {
+ const participantsByMessageId = await collectSenderAndTeamMemberParticipants(
+ client,
+ messageIds,
+ );
const interactionByMessageId = new Map<string, MessageInteraction>();
for (const [messageId, participants] of participantsByMessageId) {
@@ -96,5 +147,26 @@ export const collectMessageInteractions = async (
});
}
+ const messageIdsWithoutSenderOrTeamMember = messageIds.filter(
+ (messageId) => !participantsByMessageId.has(messageId),
+ );
+
+ if (messageIdsWithoutSenderOrTeamMember.length === 0) {
+ return interactionByMessageId;
+ }
+
+ const receivedAtByMessageId = await collectReceivedAtByMessageId(
+ client,
+ messageIdsWithoutSenderOrTeamMember,
+ );
+
+ for (const [messageId, receivedAt] of receivedAtByMessageId) {
+ interactionByMessageId.set(messageId, {
+ receivedAt,
+ workspaceMemberId: null,
+ direction: 'inbound',
+ });
+ }
+
return interactionByMessageId;
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-people-by-company.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-people-by-company.ts
deleted file mode 100644
index 735a01bc9e8..00000000000
--- a/packages/twenty-apps/public/last-contact/src/utils/collect-people-by-company.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { type CoreApiClient } from 'twenty-client-sdk/core';
-
-import { executeWithRetry } from 'src/utils/execute-with-retry';
-
-const PAGE_SIZE = 200;
-
-export const collectPeopleByCompany = async (
- client: CoreApiClient,
- companyIds: string[],
-): Promise<Map<string, string[]>> => {
- const peopleByCompanyId = new Map<string, string[]>();
- let after: string | undefined;
-
- do {
- const { people } = await executeWithRetry(() =>
- client.query({
- people: {
- __args: {
- filter: { companyId: { in: companyIds } },
- first: PAGE_SIZE,
- after,
- },
- edges: { node: { id: true, companyId: true } },
- pageInfo: { hasNextPage: true, endCursor: true },
- },
- }),
- );
-
- for (const edge of people?.edges ?? []) {
- const { id, companyId } = edge.node;
- if (id && companyId) {
- const existing = peopleByCompanyId.get(companyId);
- if (existing) {
- existing.push(id);
- } else {
- peopleByCompanyId.set(companyId, [id]);
- }
- }
- }
-
- after = people?.pageInfo.hasNextPage
- ? (people.pageInfo.endCursor ?? undefined)
- : undefined;
- } while (after);
-
- return peopleByCompanyId;
-};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/create-paced-client.ts b/packages/twenty-apps/public/last-contact/src/utils/create-paced-client.ts
new file mode 100644
index 00000000000..9a7bac839f7
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/create-paced-client.ts
@@ -0,0 +1,40 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+const sleep = (durationMs: number): Promise<void> =>
+ new Promise((resolve) => setTimeout(resolve, durationMs));
+
+export const createPacedClient = (
+ client: CoreApiClient,
+ minCallIntervalMs: number,
+): CoreApiClient => {
+ let nextCallAtMs = 0;
+
+ const waitForTurn = async (): Promise<void> => {
+ const nowMs = Date.now();
+ const callAtMs = Math.max(nowMs, nextCallAtMs);
+
+ nextCallAtMs = callAtMs + minCallIntervalMs;
+
+ if (callAtMs > nowMs) {
+ await sleep(callAtMs - nowMs);
+ }
+ };
+
+ const pacedClient = Object.create(client) as CoreApiClient;
+
+ pacedClient.query = (async (...args: Parameters<CoreApiClient['query']>) => {
+ await waitForTurn();
+
+ return client.query(...args);
+ }) as CoreApiClient['query'];
+
+ pacedClient.mutation = (async (
+ ...args: Parameters<CoreApiClient['mutation']>
+ ) => {
+ await waitForTurn();
+
+ return client.mutation(...args);
+ }) as CoreApiClient['mutation'];
+
+ return pacedClient;
+};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts b/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts
index 246891c0d63..eec6dec1af3 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts
@@ -18,7 +18,6 @@ type MeetingInteraction = {
type MessageMemberInfo = { ownerId: string; fromIsMember: boolean };
type ContactItem = { kind: 'email' | 'meeting'; id: string };
-export type LastContact = { at: string; item: ContactItem };
export type PersonUpdateData = Record<string, string | null>;
export type PersonAgg = {
@@ -348,51 +347,16 @@ export const buildPersonAggregates = async (
return aggByPersonId;
};
-export const pickPersonLastContact = (
+export const buildPersonUpdateData = (
agg: PersonAgg | undefined,
-): LastContact | undefined =>
- agg?.lastContactAt && agg.item
- ? { at: agg.lastContactAt, item: agg.item }
- : undefined;
-
-export const pickLatestLastContact = (
- contacts: LastContact[],
-): LastContact | undefined =>
- contacts.reduce<LastContact | undefined>(
- (latest, contact) =>
- !latest || contact.at > latest.at ? contact : latest,
- undefined,
- );
-
-export const buildPersonUpdateData = (agg: PersonAgg): PersonUpdateData => ({
- ...(agg.lastContactAt
- ? {
- lastContactAt: agg.lastContactAt,
- lastContactById: agg.lastContactById ?? null,
- }
- : {}),
- ...(agg.lastOutboundAt ? { lastOutboundAt: agg.lastOutboundAt } : {}),
- ...(agg.lastInboundAt ? { lastInboundAt: agg.lastInboundAt } : {}),
- ...(agg.lastEmail ? { lastEmailId: agg.lastEmail.id } : {}),
- ...(agg.lastMeeting ? { lastMeetingId: agg.lastMeeting.id } : {}),
- ...(agg.item?.kind === 'email'
- ? {
- lastContactItemMessageId: agg.item.id,
- lastContactItemCalendarEventId: null,
- }
- : agg.item?.kind === 'meeting'
- ? {
- lastContactItemCalendarEventId: agg.item.id,
- lastContactItemMessageId: null,
- }
- : {}),
-});
-
-export const buildRelatedUpdateData = ({
- at,
- item,
-}: LastContact): PersonUpdateData => ({
- lastContactAt: at,
- lastContactItemMessageId: item.kind === 'email' ? item.id : null,
- lastContactItemCalendarEventId: item.kind === 'meeting' ? item.id : null,
+): PersonUpdateData => ({
+ lastContactAt: agg?.lastContactAt ?? null,
+ lastContactById: agg?.lastContactById ?? null,
+ lastOutboundAt: agg?.lastOutboundAt ?? null,
+ lastInboundAt: agg?.lastInboundAt ?? null,
+ lastEmailId: agg?.lastEmail?.id ?? null,
+ lastMeetingId: agg?.lastMeeting?.id ?? null,
+ lastContactItemMessageId: agg?.item?.kind === 'email' ? agg.item.id : null,
+ lastContactItemCalendarEventId:
+ agg?.item?.kind === 'meeting' ? agg.item.id : null,
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts b/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts
index 508fae0c165..880a01b2515 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts
@@ -1,17 +1,15 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
import {
type BackfillPhase,
BACKFILL_PHASE_ORDER,
} from 'src/constants/backfill';
-import { backfillCompaniesLastContact } from 'src/utils/backfill-companies-last-contact';
-import {
- backfillOpportunitiesLastContact,
- type OpportunityNode,
-} from 'src/utils/backfill-opportunities-last-contact';
import { backfillPeopleLastContact } from 'src/utils/backfill-people-last-contact';
import { getBackfillBatchSize } from 'src/utils/backfill-settings';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';
+import { recomputeOpportunitiesLastContact } from 'src/utils/recompute-opportunity-last-contact';
// A total order over createdAt then id keeps the cursor stable while the
// backfill runs: records created meanwhile sort to the tail.
@@ -20,89 +18,85 @@ const BACKFILL_ORDER_BY = [
{ id: 'AscNullsFirst' },
];
+const BACKFILL_BATCH_HANDLERS: Record<
+ BackfillPhase,
+ (client: CoreApiClient, recordIds: string[]) => Promise<void>
+> = {
+ people: backfillPeopleLastContact,
+ opportunities: recomputeOpportunitiesLastContact,
+ companies: recomputeCompaniesLastContact,
+};
+
export type BackfillPhaseResult = { phase: BackfillPhase; count: number };
-const backfillRecordsInBatches = async <TRecord extends { id: string }>({
+export type BackfillCursor = { phase: BackfillPhase; after?: string };
+
+export type BackfillPauseReason = 'deadline' | 'rate-limited';
+
+export type BackfillRunResult = {
+ phases: BackfillPhaseResult[];
+ pause?: { reason: BackfillPauseReason; resumeFrom: BackfillCursor };
+};
+
+type PhaseRunResult = {
+ count: number;
+ pause?: { reason: BackfillPauseReason; after?: string };
+};
+
+const backfillPhaseInBatches = async ({
client,
- queryField,
- recordSelection,
+ phase,
batchSize,
- backfillBatch,
+ after: startAfter,
+ deadlineMs,
}: {
client: CoreApiClient;
- queryField: string;
- recordSelection: Record<keyof TRecord, true>;
+ phase: BackfillPhase;
batchSize: number;
- backfillBatch: (records: TRecord[]) => Promise<void>;
-}): Promise<number> => {
+ after?: string;
+ deadlineMs: number;
+}): Promise<PhaseRunResult> => {
let count = 0;
- let after: string | undefined;
+ let after = startAfter;
do {
- const result = await executeWithRetry(() =>
- client.query({
- [queryField]: {
- __args: { first: batchSize, after, orderBy: BACKFILL_ORDER_BY },
- edges: { node: recordSelection },
- pageInfo: { hasNextPage: true, endCursor: true },
- },
- }),
- );
- const connection = result?.[queryField];
- const records: TRecord[] = (connection?.edges ?? []).map(
- (edge: { node: TRecord }) => edge.node,
- );
-
- if (records.length > 0) {
- await backfillBatch(records);
- count += records.length;
+ if (Date.now() >= deadlineMs) {
+ return { count, pause: { reason: 'deadline', after } };
}
- after = connection?.pageInfo.hasNextPage
- ? (connection.pageInfo.endCursor ?? undefined)
- : undefined;
- } while (after);
+ try {
+ const result = await executeWithRetry(() =>
+ client.query({
+ [phase]: {
+ __args: { first: batchSize, after, orderBy: BACKFILL_ORDER_BY },
+ edges: { node: { id: true } },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ }),
+ );
+ const connection = result?.[phase];
+ const recordIds: string[] = (connection?.edges ?? []).map(
+ (edge: { node: { id: string } }) => edge.node.id,
+ );
- return count;
-};
+ if (recordIds.length > 0) {
+ await BACKFILL_BATCH_HANDLERS[phase](client, recordIds);
+ count += recordIds.length;
+ }
-const BACKFILL_PHASE_RUNNERS: Record<
- BackfillPhase,
- (client: CoreApiClient, batchSize: number) => Promise<number>
-> = {
- people: (client, batchSize) =>
- backfillRecordsInBatches<{ id: string }>({
- client,
- queryField: 'people',
- recordSelection: { id: true },
- batchSize,
- backfillBatch: (people) =>
- backfillPeopleLastContact(
- client,
- people.map(({ id }) => id),
- ),
- }),
- opportunities: (client, batchSize) =>
- backfillRecordsInBatches<OpportunityNode>({
- client,
- queryField: 'opportunities',
- recordSelection: { id: true, pointOfContactId: true },
- batchSize,
- backfillBatch: (opportunities) =>
- backfillOpportunitiesLastContact(client, opportunities),
- }),
- companies: (client, batchSize) =>
- backfillRecordsInBatches<{ id: string }>({
- client,
- queryField: 'companies',
- recordSelection: { id: true },
- batchSize,
- backfillBatch: (companies) =>
- backfillCompaniesLastContact(
- client,
- companies.map(({ id }) => id),
- ),
- }),
+ after = connection?.pageInfo.hasNextPage
+ ? (connection.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } catch (error) {
+ if (error instanceof RetryableLogicFunctionError) {
+ return { count, pause: { reason: 'rate-limited', after } };
+ }
+
+ throw error;
+ }
+ } while (after);
+
+ return { count };
};
// Processes every batch in this execution, one after the other, so the
@@ -110,16 +104,41 @@ const BACKFILL_PHASE_RUNNERS: Record<
// jobs that compete for the same rate limit.
export const runLastContactBackfill = async (
client: CoreApiClient,
-): Promise<BackfillPhaseResult[]> => {
+ {
+ resumeFrom,
+ deadlineMs,
+ }: { resumeFrom?: BackfillCursor; deadlineMs: number },
+): Promise<BackfillRunResult> => {
const batchSize = getBackfillBatchSize();
- const results: BackfillPhaseResult[] = [];
+ const firstPhaseIndex = resumeFrom
+ ? Math.max(BACKFILL_PHASE_ORDER.indexOf(resumeFrom.phase), 0)
+ : 0;
+ const phases: BackfillPhaseResult[] = [];
- for (const phase of BACKFILL_PHASE_ORDER) {
- const count = await BACKFILL_PHASE_RUNNERS[phase](client, batchSize);
+ for (const [index, phase] of BACKFILL_PHASE_ORDER.slice(
+ firstPhaseIndex,
+ ).entries()) {
+ const { count, pause } = await backfillPhaseInBatches({
+ client,
+ phase,
+ batchSize,
+ after: index === 0 ? resumeFrom?.after : undefined,
+ deadlineMs,
+ });
console.log(`Backfilled last contact on ${count} ${phase}`);
- results.push({ phase, count });
+ phases.push({ phase, count });
+
+ if (pause) {
+ return {
+ phases,
+ pause: {
+ reason: pause.reason,
+ resumeFrom: { phase, after: pause.after },
+ },
+ };
+ }
}
- return results;
+ return { phases };
};