Skip to content

The open alternative to Salesforce, designed for AI.

Run the call recorder calendar event reconcile in batch mode (#26609)

nitinee6477422da9
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.json
index bda2abd4bb0..3c4ba18d0aa 100644
--- a/packages/twenty-apps/public/call-recorder/package.json
+++ b/packages/twenty-apps/public/call-recorder/package.json
@@ -1,12 +1,12 @@
{
"name": "@twentyhq/call-recorder",
- "version": "1.14.1",
+ "version": "1.15.0",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2",
- "twenty": ">=2.38.0"
+ "twenty": ">=2.42.0"
},
"keywords": [
"twenty-app"
@@ -35,8 +35,8 @@
"oxlint": "^0.16.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
- "twenty-client-sdk": "2.38.0",
- "twenty-sdk": "2.38.0",
+ "twenty-client-sdk": "2.42.0",
+ "twenty-sdk": "2.42.0",
"twenty-ui": "^1.0.0-alpha.1",
"typescript": "^5.9.3",
"use-debounce": "^10.0.0",
diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
index 4b9b0fbeeae..7c95a1b99ef 100644
--- a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
@@ -306,6 +306,7 @@ class FakeRecallApi {
hasExpiredMedia = false;
failNextDelete = false;
failCalendarEventUpdates = false;
+ failCallRecordingReads = false;
failRecallRemovals = false;
seedBot(bot: FakeRecallBot): void {
@@ -470,6 +471,14 @@ class FakeRecallApi {
return jsonResponse(500, { errors: [{ message: 'Internal error' }] });
}
+ if (
+ this.failCallRecordingReads &&
+ requestUrl === `${process.env.TWENTY_API_URL}/graphql` &&
+ String(requestInit?.body ?? '').includes('callRecordings')
+ ) {
+ return jsonResponse(500, { errors: [{ message: 'Internal error' }] });
+ }
+
if (!requestUrl.startsWith(RECALL_BASE_URL)) {
return undefined;
}
@@ -1069,29 +1078,30 @@ describe('call recorder app lifecycle (integration)', () => {
},
});
- const deliverCalendarEventUpdate = ({
- calendarEventId,
- updatedFields,
- before,
- after,
- }: {
- calendarEventId: string;
- updatedFields: string[];
- before: Record<string, unknown>;
- after: Record<string, unknown>;
- }) =>
+ const deliverCalendarEventUpdates = (
+ ...calendarEventUpdates: {
+ calendarEventId: string;
+ updatedFields: string[];
+ before: Record<string, unknown>;
+ after: Record<string, unknown>;
+ }[]
+ ) =>
(
reconcileCalendarEventLogicFunction.config.handler as (
- event: unknown,
+ batch: unknown,
) => Promise<object | undefined>
)({
name: 'calendarEvent.updated',
- recordId: calendarEventId,
- properties: {
- updatedFields,
- before: { id: calendarEventId, ...before },
- after: { id: calendarEventId, ...after },
- },
+ events: calendarEventUpdates.map(
+ ({ calendarEventId, updatedFields, before, after }) => ({
+ recordId: calendarEventId,
+ properties: {
+ updatedFields,
+ before: { id: calendarEventId, ...before },
+ after: { id: calendarEventId, ...after },
+ },
+ }),
+ ),
});
// Mocked webhook trigger: invokes the webhook logic function handler with
@@ -1168,6 +1178,121 @@ describe('call recorder app lifecycle (integration)', () => {
}),
).toEqual([]);
});
+
+ it('does not ask the queue to redeliver a batch when the recording On echo lookup fails', async () => {
+ const calendarEventId = await createCalendarEvent();
+
+ recall.failCallRecordingReads = true;
+
+ await expect(
+ deliverCalendarEventUpdates({
+ calendarEventId,
+ updatedFields: ['callRecorderPreference'],
+ before: { callRecorderPreference: null },
+ after: { callRecorderPreference: 'ON' },
+ }),
+ ).rejects.not.toMatchObject({ name: 'RetryableLogicFunctionError' });
+ expect(
+ await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ }),
+ ).toEqual([]);
+ });
+
+ it('retries a Core API read that failed with a 503 and finishes the batch', async () => {
+ const calendarEventId = await createCalendarEvent();
+ const unavailableResponses: Response[] = [];
+ const fetchBeforeOutage = globalThis.fetch;
+
+ vi.stubGlobal(
+ 'fetch',
+ (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ if (
+ unavailableResponses.length === 0 &&
+ String(input) === `${process.env.TWENTY_API_URL}/graphql` &&
+ String(init?.body ?? '').includes('callRecordings(')
+ ) {
+ const unavailableResponse = new Response('Service Unavailable', {
+ status: 503,
+ });
+
+ unavailableResponses.push(unavailableResponse);
+
+ return Promise.resolve(unavailableResponse);
+ }
+
+ return fetchBeforeOutage(input, init);
+ },
+ );
+
+ await deliverCalendarEventUpdates({
+ calendarEventId,
+ updatedFields: ['title'],
+ before: { title: 'Customer Sync' },
+ after: { title: 'Customer Sync (renamed)' },
+ });
+
+ const [callRecording] = await findCallRecordings({
+ calendarEventId: { eq: calendarEventId },
+ });
+
+ expect(unavailableResponses).toHaveLength(1);
+ expect(callRecording.recordingRequestStatus).toBe('REQUESTED');
+ expect(recall.bots.has(callRecording.externalBotId)).toBe(true);
+ });
+
+ it('sends a Core API write once when it fails with a 503', async () => {
+ const { calendarEventId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+ const unavailableWriteBodies: string[] = [];
+ const fetchBeforeOutage = globalThis.fetch;
+
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: {
+ id: calendarEventId,
+ data: { title: 'Customer Sync (renamed)' },
+ },
+ id: true,
+ },
+ });
+
+ vi.stubGlobal(
+ 'fetch',
+ (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ const body = String(init?.body ?? '');
+
+ if (
+ String(input) === `${process.env.TWENTY_API_URL}/graphql` &&
+ body.includes('updateCallRecording(')
+ ) {
+ unavailableWriteBodies.push(body);
+
+ return Promise.resolve(
+ new Response('Service Unavailable', { status: 503 }),
+ );
+ }
+
+ return fetchBeforeOutage(input, init);
+ },
+ );
+
+ const result = await deliverCalendarEventUpdates({
+ calendarEventId,
+ updatedFields: ['title'],
+ before: { title: 'Customer Sync' },
+ after: { title: 'Customer Sync (renamed)' },
+ });
+
+ expect(unavailableWriteBodies).toHaveLength(1);
+ expect(result).toEqual(
+ expect.objectContaining({
+ reconciliationResults: [
+ expect.objectContaining({ action: 'FAILED' }),
+ ],
+ }),
+ );
+ });
});
describe('credit gate', () => {
@@ -1282,6 +1407,37 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.bots.size).toBe(0);
expect(recall.creditCheckRequests).toEqual([]);
});
+
+ it('reconciles a user On change on a meeting whose bot the credit gate blocked', async () => {
+ recall.creditAvailability = {
+ hasAvailableCredits: false,
+ reason: 'no-subscription',
+ };
+ const calendarEventId = await createCalendarEvent({
+ startsAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(),
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ recall.creditAvailability = { hasAvailableCredits: true };
+
+ const result = await deliverCalendarEventUpdates({
+ calendarEventId,
+ updatedFields: ['callRecorderPreference', 'updatedBy'],
+ before: { callRecorderPreference: null },
+ after: { callRecorderPreference: 'ON' },
+ });
+ const [callRecording] = await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ });
+
+ expect(result).toEqual(expect.objectContaining({ reconciled: true }));
+ expect(callRecording.status).toBe('SCHEDULED');
+ expect(callRecording.callRecorderFailureReason).toBeFalsy();
+ });
});
describe('Recall webhook lifecycle', () => {
@@ -2568,7 +2724,7 @@ describe('call recorder app lifecycle (integration)', () => {
calendarEventIds: [calendarEventId],
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
@@ -2581,12 +2737,59 @@ describe('call recorder app lifecycle (integration)', () => {
});
});
+ it('reconciles every change of a batch except the echo of its own On write', async () => {
+ const echoedCalendarEventId = await createCalendarEvent({
+ callRecorderPreference: null,
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [echoedCalendarEventId],
+ });
+
+ const newlyOnCalendarEventId = await createCalendarEvent({
+ callRecorderPreference: 'ON',
+ });
+
+ const result = await deliverCalendarEventUpdates(
+ {
+ calendarEventId: echoedCalendarEventId,
+ updatedFields: ['callRecorderPreference', 'updatedBy'],
+ before: { callRecorderPreference: null },
+ after: { callRecorderPreference: 'ON' },
+ },
+ {
+ calendarEventId: newlyOnCalendarEventId,
+ updatedFields: ['callRecorderPreference', 'updatedBy'],
+ before: { callRecorderPreference: null },
+ after: { callRecorderPreference: 'ON' },
+ },
+ );
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ reconciled: true,
+ calendarEventIds: [newlyOnCalendarEventId],
+ }),
+ );
+
+ const callRecording = (
+ await findCallRecordings({
+ calendarEventId: { in: [newlyOnCalendarEventId] },
+ })
+ )[0];
+
+ expect(callRecording).toBeDefined();
+ expect(callRecording.recordingRequestStatus).toBe('REQUESTED');
+ expect(callRecording.externalBotId).toBeTruthy();
+ });
+
it('schedules a bot when a user sets On on an eligible meeting that has none yet', async () => {
const calendarEventId = await createCalendarEvent({
callRecorderPreference: 'ON',
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
@@ -2612,7 +2815,7 @@ describe('call recorder app lifecycle (integration)', () => {
callRecorderPreference: 'ON',
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
@@ -2638,7 +2841,7 @@ describe('call recorder app lifecycle (integration)', () => {
callRecorderPreference: 'ON',
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
@@ -2669,7 +2872,7 @@ describe('call recorder app lifecycle (integration)', () => {
},
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: 'OFF' },
@@ -2859,7 +3062,7 @@ describe('call recorder app lifecycle (integration)', () => {
},
});
- const result = await deliverCalendarEventUpdate({
+ const result = await deliverCalendarEventUpdates({
calendarEventId,
updatedFields: ['callRecorderPreference'],
before: { callRecorderPreference: null },
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/batch-handler-timeout-seconds.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/batch-handler-timeout-seconds.ts
new file mode 100644
index 00000000000..b5461e65a1f
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/batch-handler-timeout-seconds.ts
@@ -0,0 +1 @@
+export const BATCH_HANDLER_TIMEOUT_SECONDS = 300;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-calendar-event-reconciliation-payload.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-calendar-event-reconciliation-payload.test.ts
new file mode 100644
index 00000000000..80945117dc6
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/build-calendar-event-reconciliation-payload.test.ts
@@ -0,0 +1,228 @@
+import { describe, expect, it } from 'vitest';
+
+import { type CalendarEventForDatabaseEvent } from 'src/logic-functions/types/calendar-event-for-database-event.type';
+import { buildCalendarEventReconciliationPayload } from 'src/logic-functions/domain/build-calendar-event-reconciliation-payload.util';
+
+const PREVIOUS_STARTS_AT = '2026-01-01T13:00:00.000Z';
+const NEXT_STARTS_AT = '2026-01-01T15:00:00.000Z';
+
+const buildCalendarEvent = (
+ overrides: Partial<CalendarEventForDatabaseEvent> = {},
+): CalendarEventForDatabaseEvent => ({
+ id: 'calendar-event-1',
+ callRecorderPreference: null,
+ conferenceLink: { primaryLinkUrl: 'https://meet.google.com/customer-sync' },
+ location: null,
+ description: null,
+ iCalUid: 'calendar-event-uid',
+ startsAt: PREVIOUS_STARTS_AT,
+ ...overrides,
+});
+
+const buildEvent = ({
+ updatedFields,
+ before = buildCalendarEvent(),
+ after = buildCalendarEvent(),
+}: {
+ updatedFields?: string[];
+ before?: CalendarEventForDatabaseEvent;
+ after?: CalendarEventForDatabaseEvent;
+} = {}) => ({
+ recordId: after.id,
+ properties: { updatedFields, before, after },
+});
+
+const PREVIOUS_OCCURRENCE = {
+ calendarEventId: 'calendar-event-1',
+ realMeetingKey: `link:meet.google.com/customer-sync:${PREVIOUS_STARTS_AT}`,
+ startsAt: PREVIOUS_STARTS_AT,
+};
+
+describe('buildCalendarEventReconciliationPayload', () => {
+ it('reconciles created calendar events', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'created',
+ events: [
+ buildEvent({ after: buildCalendarEvent({ id: 'calendar-event-2' }) }),
+ buildEvent(),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1', 'calendar-event-2'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ });
+ });
+
+ it('reconciles an update that keeps the meeting key without removing an occurrence', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [buildEvent({ updatedFields: ['title', 'endsAt'] })],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ });
+ });
+
+ it('removes the previous occurrence when an update changes a key field', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({
+ updatedFields: ['startsAt'],
+ after: buildCalendarEvent({ startsAt: NEXT_STARTS_AT }),
+ }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [PREVIOUS_OCCURRENCE],
+ });
+ });
+
+ it.each(['deleted', 'destroyed'])(
+ 'removes the occurrence of a %s calendar event',
+ (action) => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action,
+ events: [buildEvent()],
+ }),
+ ).toEqual({
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [PREVIOUS_OCCURRENCE],
+ });
+ },
+ );
+
+ it.each([
+ ['blank', 'On', null, 'ON'],
+ ['On', 'blank', 'ON', null],
+ ])(
+ 'treats a preference change from %s to %s as an echo candidate',
+ (_beforeLabel, _afterLabel, beforePreference, afterPreference) => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({
+ updatedFields: ['callRecorderPreference'],
+ before: buildCalendarEvent({
+ callRecorderPreference: beforePreference,
+ }),
+ after: buildCalendarEvent({
+ callRecorderPreference: afterPreference,
+ }),
+ }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: ['calendar-event-1'],
+ removedOccurrences: [],
+ });
+ },
+ );
+
+ it('treats a blank to On preference change that also stamps updatedBy as an echo candidate', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({
+ updatedFields: ['callRecorderPreference', 'updatedBy'],
+ after: buildCalendarEvent({ callRecorderPreference: 'ON' }),
+ }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: ['calendar-event-1'],
+ removedOccurrences: [],
+ });
+ });
+
+ it.each([
+ ['blank', 'Off', null, 'OFF'],
+ ['Off', 'blank', 'OFF', null],
+ ['On', 'Off', 'ON', 'OFF'],
+ ])(
+ 'reconciles a preference change from %s to %s',
+ (_beforeLabel, _afterLabel, beforePreference, afterPreference) => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({
+ updatedFields: ['callRecorderPreference'],
+ before: buildCalendarEvent({
+ callRecorderPreference: beforePreference,
+ }),
+ after: buildCalendarEvent({
+ callRecorderPreference: afterPreference,
+ }),
+ }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ });
+ },
+ );
+
+ it('reconciles a preference change that comes with another field change', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({
+ updatedFields: ['callRecorderPreference', 'title'],
+ after: buildCalendarEvent({ callRecorderPreference: 'ON' }),
+ }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ });
+ });
+
+ it('dedupes calendar event ids across the batch', () => {
+ expect(
+ buildCalendarEventReconciliationPayload({
+ action: 'updated',
+ events: [
+ buildEvent({ updatedFields: ['title'] }),
+ buildEvent({ updatedFields: ['endsAt'] }),
+ ],
+ }),
+ ).toEqual({
+ calendarEventIds: ['calendar-event-1'],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ });
+ });
+
+ it.each([
+ ['an empty batch', 'updated', []],
+ ['an action it does not reconcile', 'restored', [buildEvent()]],
+ ])('returns nothing to reconcile for %s', (_label, action, events) => {
+ expect(buildCalendarEventReconciliationPayload({ action, events })).toEqual(
+ {
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ },
+ );
+ });
+});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-calendar-event-reconciliation-payload.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-calendar-event-reconciliation-payload.util.ts
new file mode 100644
index 00000000000..11e9570d0fd
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/build-calendar-event-reconciliation-payload.util.ts
@@ -0,0 +1,163 @@
+import { isUndefined } from '@sniptt/guards';
+import { type ObjectRecordBaseEvent } from 'twenty-sdk/define';
+
+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
+import { type CalendarEventForDatabaseEvent } from 'src/logic-functions/types/calendar-event-for-database-event.type';
+import { type RemovedCallRecorderOccurrence } from 'src/logic-functions/types/removed-call-recorder-occurrence.type';
+import { computeRealMeetingKey } from 'src/logic-functions/domain/compute-real-meeting-key.util';
+import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
+import { resolveConferenceLinkUrl } from 'src/logic-functions/domain/resolve-conference-link-url.util';
+import { stripRestrictedFieldValue } from 'src/logic-functions/data/strip-restricted-field-value.util';
+
+// location and description are key fields because the conference link is
+// parsed out of them when the structured conferenceLink is empty.
+const CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS = [
+ 'conferenceLink',
+ 'location',
+ 'description',
+ 'startsAt',
+ 'iCalUid',
+];
+
+type CalendarEventReconciliationPayload = {
+ calendarEventIds: string[];
+ echoCandidateCalendarEventIds: string[];
+ removedOccurrences: RemovedCallRecorderOccurrence[];
+};
+
+export const buildCalendarEventReconciliationPayload = ({
+ action,
+ events,
+}: {
+ action: string | undefined;
+ events: ObjectRecordBaseEvent<CalendarEventForDatabaseEvent>[];
+}): CalendarEventReconciliationPayload => {
+ const eventReconciliationPayloads = events.map((event) =>
+ buildEventReconciliationPayload({ action, event }),
+ );
+
+ return {
+ calendarEventIds: getUniqueSortedIds(
+ eventReconciliationPayloads.flatMap(
+ (eventReconciliationPayload) =>
+ eventReconciliationPayload.calendarEventIds,
+ ),
+ ),
+ echoCandidateCalendarEventIds: getUniqueSortedIds(
+ eventReconciliationPayloads.flatMap(
+ (eventReconciliationPayload) =>
+ eventReconciliationPayload.echoCandidateCalendarEventIds,
+ ),
+ ),
+ removedOccurrences: eventReconciliationPayloads.flatMap(
+ (eventReconciliationPayload) =>
+ eventReconciliationPayload.removedOccurrences,
+ ),
+ };
+};
+
+const buildEventReconciliationPayload = ({
+ action,
+ event,
+}: {
+ action: string | undefined;
+ event: ObjectRecordBaseEvent<CalendarEventForDatabaseEvent>;
+}): CalendarEventReconciliationPayload => {
+ const changedCalendarEventIds = getUniqueSortedIds([
+ event.recordId,
+ event.properties.after?.id,
+ ]);
+
+ if (action === 'created') {
+ return {
+ calendarEventIds: changedCalendarEventIds,
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ };
+ }
+
+ if (action === 'updated' && isPreferenceChangeBetweenBlankAndOn(event)) {
+ return {
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: changedCalendarEventIds,
+ removedOccurrences: [],
+ };
+ }
+
+ if (action === 'updated') {
+ return {
+ calendarEventIds: changedCalendarEventIds,
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: hasKeyFieldChange(
+ event.properties.updatedFields ?? [],
+ )
+ ? buildRemovedOccurrences(event.properties.before)
+ : [],
+ };
+ }
+
+ if (action === 'deleted' || action === 'destroyed') {
+ return {
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: buildRemovedOccurrences(event.properties.before),
+ };
+ }
+
+ return {
+ calendarEventIds: [],
+ echoCandidateCalendarEventIds: [],
+ removedOccurrences: [],
+ };
+};
+
+const isPreferenceChangeBetweenBlankAndOn = (
+ event: ObjectRecordBaseEvent<CalendarEventForDatabaseEvent>,
+): boolean => {
+ const updatedFields = (event.properties.updatedFields ?? []).filter(
+ (updatedField) => updatedField !== 'updatedBy',
+ );
+
+ return (
+ updatedFields.length === 1 &&
+ updatedFields[0] === 'callRecorderPreference' &&
+ event.properties.before?.callRecorderPreference !==
+ CallRecorderPreference.OFF &&
+ event.properties.after?.callRecorderPreference !==
+ CallRecorderPreference.OFF
+ );
+};
+
+const hasKeyFieldChange = (updatedFields: string[]): boolean =>
+ updatedFields.some((updatedField) =>
+ CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS.includes(updatedField),
+ );
+
+const buildRemovedOccurrences = (
+ calendarEvent: CalendarEventForDatabaseEvent | undefined,
+): RemovedCallRecorderOccurrence[] => {
+ if (isUndefined(calendarEvent)) {
+ return [];
+ }
+
+ return [
+ {
+ calendarEventId: calendarEvent.id,
+ realMeetingKey: computeRealMeetingKey({
+ calendarEventId: calendarEvent.id,
+ conferenceLinkUrl: resolveConferenceLinkUrl({
+ conferenceLinkUrl: calendarEvent.conferenceLink?.primaryLinkUrl,
+ location: stripRestrictedFieldValue(
+ calendarEvent.location ?? undefined,
+ ),
+ description: stripRestrictedFieldValue(
+ calendarEvent.description ?? undefined,
+ ),
+ }),
+ iCalUid: calendarEvent.iCalUid ?? undefined,
+ startsAt: calendarEvent.startsAt ?? undefined,
+ }),
+ startsAt: calendarEvent.startsAt ?? undefined,
+ },
+ ];
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
index 634f73d2a3d..b5b3ed644d6 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
@@ -1,95 +1,71 @@
-import { isUndefined } from '@sniptt/guards';
import { CoreApiClient } from 'twenty-client-sdk/core';
import {
defineLogicFunction,
- type DatabaseEventPayload,
type ObjectRecordBaseEvent,
} from 'twenty-sdk/define';
+import { type DatabaseEventBatchPayload } from 'twenty-sdk/logic-function';
-import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
-import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
import { CALENDAR_EVENT_RECONCILIATION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { type RemovedCallRecorderOccurrence } from 'src/logic-functions/types/removed-call-recorder-occurrence.type';
+import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/logic-functions/constants/batch-handler-timeout-seconds';
+import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';
+import { type CalendarEventForDatabaseEvent } from 'src/logic-functions/types/calendar-event-for-database-event.type';
+import { type CallRecorderReconciliationResult } from 'src/logic-functions/types/call-recorder-reconciliation-result.type';
+import { buildCalendarEventReconciliationPayload } from 'src/logic-functions/domain/build-calendar-event-reconciliation-payload.util';
import { buildCallRecorderPolicyResult } from 'src/logic-functions/domain/build-call-recorder-policy-result.util';
import { computeCallRecordingIdForMeeting } from 'src/logic-functions/domain/compute-call-recording-id-for-meeting.util';
-import { computeRealMeetingKey } from 'src/logic-functions/domain/compute-real-meeting-key.util';
+import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';
import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calendar-events-by-ids.util';
import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
-import { resolveConferenceLinkUrl } from 'src/logic-functions/domain/resolve-conference-link-url.util';
-import { stripRestrictedFieldValue } from 'src/logic-functions/data/strip-restricted-field-value.util';
+import { fetchWithTransientRetry } from 'src/logic-functions/utils/fetch-with-transient-retry.util';
const CALENDAR_EVENT_OBJECT_NAME = 'calendarEvent';
-const CALL_RECORDER_RELEVANT_CALENDAR_EVENT_FIELDS = [
- 'title',
- 'callRecorderPreference',
- 'conferenceLink',
- 'location',
- 'description',
- 'startsAt',
- 'endsAt',
- 'isCanceled',
- 'iCalUid',
-];
-
-// location and description are key fields because the conference link is
-// parsed out of them when the structured conferenceLink is empty.
-const CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS = [
- 'conferenceLink',
- 'location',
- 'description',
- 'startsAt',
- 'iCalUid',
-];
-
-type CalendarEventForDatabaseEvent = {
- id: string;
- callRecorderPreference?: string | null;
- conferenceLink?: { primaryLinkUrl?: string | null } | null;
- location?: string | null;
- description?: string | null;
- iCalUid?: string | null;
- startsAt?: string | null;
-};
-
-type CalendarEventDatabaseEvent = DatabaseEventPayload<
- ObjectRecordBaseEvent<CalendarEventForDatabaseEvent>
->;
-
-type CalendarEventReconciliationPayload = {
- calendarEventIds: string[];
- removedOccurrences: RemovedCallRecorderOccurrence[];
-};
+type CalendarEventBatchReconciliationResult =
+ | { skipped: true; reason: string }
+ | {
+ reconciled: true;
+ calendarEventIds: string[];
+ removedOccurrenceCount: number;
+ reconciliationResults: CallRecorderReconciliationResult[];
+ };
const handler = async (
- event: CalendarEventDatabaseEvent,
-): Promise<object | undefined> => {
- const [objectName, action] = event.name.split('.');
+ batch: DatabaseEventBatchPayload<
+ ObjectRecordBaseEvent<CalendarEventForDatabaseEvent>
+ >,
+): Promise<CalendarEventBatchReconciliationResult> => {
+ const [objectName, action] = batch.name.split('.');
if (objectName !== CALENDAR_EVENT_OBJECT_NAME) {
return { skipped: true, reason: 'not a calendar event' };
}
const reconciliationPayload = buildCalendarEventReconciliationPayload({
- event,
action,
+ events: batch.events,
});
if (
reconciliationPayload.calendarEventIds.length === 0 &&
+ reconciliationPayload.echoCandidateCalendarEventIds.length === 0 &&
reconciliationPayload.removedOccurrences.length === 0
) {
return { skipped: true, reason: 'no relevant calendar event change' };
}
- const client = new CoreApiClient();
+ const client = new CoreApiClient({ fetch: fetchWithTransientRetry });
+ const calendarEventIds = await resolveCalendarEventIdsToReconcile({
+ client,
+ changedCalendarEventIds: reconciliationPayload.calendarEventIds,
+ echoCandidateCalendarEventIds:
+ reconciliationPayload.echoCandidateCalendarEventIds,
+ });
- // Skips only the echo of the app's own On write; any other blank/On change reconciles, which schedules a missing bot or clears an On the policy cannot honor.
if (
- isPreferenceChangeBetweenBlankAndOn(event) &&
- (await isRecordingOnAlreadyHonored(client, event.recordId))
+ calendarEventIds.length === 0 &&
+ reconciliationPayload.removedOccurrences.length === 0
) {
return {
skipped: true,
@@ -99,151 +75,86 @@ const handler = async (
const reconciliationResults = await reconcileCallRecorderForCalendarEventIds({
client,
- calendarEventIds: reconciliationPayload.calendarEventIds,
+ calendarEventIds,
removedOccurrences: reconciliationPayload.removedOccurrences,
});
return {
reconciled: true,
- calendarEventIds: reconciliationPayload.calendarEventIds,
+ calendarEventIds,
removedOccurrenceCount: reconciliationPayload.removedOccurrences.length,
reconciliationResults,
};
};
-const buildCalendarEventReconciliationPayload = ({
- event,
- action,
+const resolveCalendarEventIdsToReconcile = async ({
+ client,
+ changedCalendarEventIds,
+ echoCandidateCalendarEventIds,
}: {
- event: CalendarEventDatabaseEvent;
- action: string | undefined;
-}): CalendarEventReconciliationPayload => {
- if (action === 'created') {
- return {
- calendarEventIds: getUniqueSortedIds([
- event.recordId,
- event.properties.after?.id,
- ]),
- removedOccurrences: [],
- };
- }
-
- if (action === 'updated') {
- const updatedFields = event.properties.updatedFields ?? [];
-
- if (!hasRelevantFieldChange(updatedFields)) {
- return { calendarEventIds: [], removedOccurrences: [] };
- }
-
- const removedOccurrence = hasKeyFieldChange(updatedFields)
- ? buildRemovedOccurrence(event.properties.before)
- : undefined;
-
- return {
- calendarEventIds: getUniqueSortedIds([
- event.recordId,
- event.properties.after?.id,
- ]),
- removedOccurrences: isUndefined(removedOccurrence)
- ? []
- : [removedOccurrence],
- };
- }
-
- if (action === 'deleted' || action === 'destroyed') {
- const removedOccurrence = buildRemovedOccurrence(event.properties.before);
-
- return {
- calendarEventIds: [],
- removedOccurrences: isUndefined(removedOccurrence)
- ? []
- : [removedOccurrence],
- };
- }
-
- return { calendarEventIds: [], removedOccurrences: [] };
-};
-
-const hasRelevantFieldChange = (updatedFields: string[]): boolean =>
- updatedFields.some((updatedField) =>
- CALL_RECORDER_RELEVANT_CALENDAR_EVENT_FIELDS.includes(updatedField),
- );
-
-const isPreferenceChangeBetweenBlankAndOn = (
- event: CalendarEventDatabaseEvent,
-): boolean => {
- const updatedFields = event.properties.updatedFields ?? [];
-
- return (
- updatedFields.length === 1 &&
- updatedFields[0] === 'callRecorderPreference' &&
- event.properties.before?.callRecorderPreference !==
- CallRecorderPreference.OFF &&
- event.properties.after?.callRecorderPreference !==
- CallRecorderPreference.OFF
- );
+ client: CoreApiClient;
+ changedCalendarEventIds: string[];
+ echoCandidateCalendarEventIds: string[];
+}): Promise<string[]> => {
+ const calendarEventIdsWithRecordingOnAlreadyHonored =
+ await findCalendarEventIdsWithRecordingOnAlreadyHonored(
+ client,
+ echoCandidateCalendarEventIds,
+ );
+
+ return getUniqueSortedIds([
+ ...changedCalendarEventIds,
+ ...echoCandidateCalendarEventIds.filter(
+ (calendarEventId) =>
+ !calendarEventIdsWithRecordingOnAlreadyHonored.includes(
+ calendarEventId,
+ ),
+ ),
+ ]);
};
-const isRecordingOnAlreadyHonored = async (
+const findCalendarEventIdsWithRecordingOnAlreadyHonored = async (
client: CoreApiClient,
- calendarEventId: string,
-): Promise<boolean> => {
- const calendarEvent = (
- await fetchCalendarEventsByIds(client, [calendarEventId])
- )[0];
-
- if (isUndefined(calendarEvent)) {
- return false;
- }
-
- const policyResult = buildCallRecorderPolicyResult(calendarEvent, new Date());
-
- if (!policyResult.shouldRequestBot) {
- return false;
- }
-
- const policyManagedCallRecording = (
- await findCallRecordingsByIds(client, [
- computeCallRecordingIdForMeeting(policyResult.realMeetingKey),
- ])
- )[0];
-
- return (
- policyManagedCallRecording?.recordingRequestStatus ===
- CallRecordingRequestStatus.REQUESTED
- );
-};
-
-const hasKeyFieldChange = (updatedFields: string[]): boolean =>
- updatedFields.some((updatedField) =>
- CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS.includes(updatedField),
+ calendarEventIds: string[],
+): Promise<string[]> => {
+ const now = new Date();
+ const requestingCalendarEvents = (
+ await fetchCalendarEventsByIds(client, calendarEventIds)
+ )
+ .map((calendarEvent) => buildCallRecorderPolicyResult(calendarEvent, now))
+ .filter((policyResult) => policyResult.shouldRequestBot)
+ .map((policyResult) => ({
+ calendarEventId: policyResult.calendarEventId,
+ callRecordingId: computeCallRecordingIdForMeeting(
+ policyResult.realMeetingKey,
+ ),
+ }));
+ const requestedCallRecordingIds = new Set(
+ (
+ await findCallRecordingsByIds(
+ client,
+ getUniqueSortedIds(
+ requestingCalendarEvents.map(
+ (requestingCalendarEvent) =>
+ requestingCalendarEvent.callRecordingId,
+ ),
+ ),
+ )
+ )
+ .filter(
+ (callRecording) =>
+ callRecording.recordingRequestStatus ===
+ CallRecordingRequestStatus.REQUESTED &&
+ !isUnavailableCallRecordingStatus(callRecording.status),
+ )
+ .map((callRecording) => callRecording.id),
);
-const buildRemovedOccurrence = (
- calendarEvent: CalendarEventForDatabaseEvent | undefined,
-): RemovedCallRecorderOccurrence | undefined => {
- if (isUndefined(calendarEvent)) {
- return undefined;
- }
-
- return {
- calendarEventId: calendarEvent.id,
- realMeetingKey: computeRealMeetingKey({
- calendarEventId: calendarEvent.id,
- conferenceLinkUrl: resolveConferenceLinkUrl({
- conferenceLinkUrl: calendarEvent.conferenceLink?.primaryLinkUrl,
- location: stripRestrictedFieldValue(
- calendarEvent.location ?? undefined,
- ),
- description: stripRestrictedFieldValue(
- calendarEvent.description ?? undefined,
- ),
- }),
- iCalUid: calendarEvent.iCalUid ?? undefined,
- startsAt: calendarEvent.startsAt ?? undefined,
- }),
- startsAt: calendarEvent.startsAt ?? undefined,
- };
+ return requestingCalendarEvents
+ .filter((requestingCalendarEvent) =>
+ requestedCallRecordingIds.has(requestingCalendarEvent.callRecordingId),
+ )
+ .map((requestingCalendarEvent) => requestingCalendarEvent.calendarEventId);
};
export default defineLogicFunction({
@@ -252,9 +163,21 @@ export default defineLogicFunction({
name: 'reconcile-call-recorder-calendar-event',
description:
'Reconciles app-managed Recall bot recording requests when calendar events change.',
- timeoutSeconds: 60,
+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
handler,
databaseEventTriggerSettings: {
eventName: `${CALENDAR_EVENT_OBJECT_NAME}.*`,
+ updatedFields: [
+ 'title',
+ 'callRecorderPreference',
+ 'conferenceLink',
+ 'location',
+ 'description',
+ 'startsAt',
+ 'endsAt',
+ 'isCanceled',
+ 'iCalUid',
+ ],
+ batchMode: true,
},
});
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/types/calendar-event-for-database-event.type.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/calendar-event-for-database-event.type.ts
new file mode 100644
index 00000000000..b57325b3b96
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/types/calendar-event-for-database-event.type.ts
@@ -0,0 +1,9 @@
+export type CalendarEventForDatabaseEvent = {
+ id: string;
+ callRecorderPreference?: string | null;
+ conferenceLink?: { primaryLinkUrl?: string | null } | null;
+ location?: string | null;
+ description?: string | null;
+ iCalUid?: string | null;
+ startsAt?: string | null;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-transient-retry.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-transient-retry.util.ts
new file mode 100644
index 00000000000..2b97873b1fd
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/utils/fetch-with-transient-retry.util.ts
@@ -0,0 +1,76 @@
+import { isString } from '@sniptt/guards';
+
+import { asRecord } from 'src/logic-functions/utils/as-record.util';
+import { fetchWithTimeout } from 'src/logic-functions/utils/fetch-with-timeout.util';
+
+const MAX_ATTEMPTS = 3;
+const RETRY_DELAY_MS = 1_000;
+const TRANSIENT_HTTP_STATUSES = [502, 503, 504];
+
+const sleep = (delayMs: number): Promise<void> =>
+ new Promise((resolve) => {
+ setTimeout(resolve, delayMs);
+ });
+
+const resolveRetryDelayMs = (attemptNumber: number): number =>
+ Math.round((RETRY_DELAY_MS * attemptNumber * (1 + Math.random())) / 2);
+
+const isGraphqlQueryRequest = (
+ options: Parameters<typeof fetch>[1],
+): boolean => {
+ const body = options?.body;
+
+ if (!isString(body)) {
+ return false;
+ }
+
+ try {
+ const operation = asRecord(JSON.parse(body))?.query;
+
+ return isString(operation) && operation.startsWith('query');
+ } catch {
+ return false;
+ }
+};
+
+const fetchWithTransientRetryAttempt = async ({
+ input,
+ options,
+ attemptNumber,
+}: {
+ input: Parameters<typeof fetch>[0];
+ options: Parameters<typeof fetch>[1];
+ attemptNumber: number;
+}): Promise<Response> => {
+ const hasAttemptsLeft = attemptNumber < MAX_ATTEMPTS;
+
+ try {
+ const response = await fetchWithTimeout(input, options);
+
+ if (
+ !hasAttemptsLeft ||
+ !TRANSIENT_HTTP_STATUSES.includes(response.status)
+ ) {
+ return response;
+ }
+
+ await response.body?.cancel();
+ } catch (error) {
+ if (!hasAttemptsLeft || options?.signal?.aborted) {
+ throw error;
+ }
+ }
+
+ await sleep(resolveRetryDelayMs(attemptNumber));
+
+ return fetchWithTransientRetryAttempt({
+ input,
+ options,
+ attemptNumber: attemptNumber + 1,
+ });
+};
+
+export const fetchWithTransientRetry: typeof fetch = (input, options) =>
+ isGraphqlQueryRequest(options)
+ ? fetchWithTransientRetryAttempt({ input, options, attemptNumber: 1 })
+ : fetchWithTimeout(input, options);
diff --git a/packages/twenty-apps/public/call-recorder/yarn.lock b/packages/twenty-apps/public/call-recorder/yarn.lock
index 8d017d412ff..029ab907d87 100644
--- a/packages/twenty-apps/public/call-recorder/yarn.lock
+++ b/packages/twenty-apps/public/call-recorder/yarn.lock
@@ -1401,8 +1401,8 @@ __metadata:
react: "npm:^19.0.0"
react-dom: "npm:^19.0.0"
sharp: "npm:^0.35.3"
- twenty-client-sdk: "npm:2.38.0"
- twenty-sdk: "npm:2.38.0"
+ twenty-client-sdk: "npm:2.42.0"
+ twenty-sdk: "npm:2.42.0"
twenty-ui: "npm:^1.0.0-alpha.1"
typescript: "npm:^5.9.3"
use-debounce: "npm:^10.0.0"
@@ -3620,22 +3620,22 @@ __metadata:
languageName: node
linkType: hard
-"twenty-client-sdk@npm:2.38.0":
- version: 2.38.0
- resolution: "twenty-client-sdk@npm:2.38.0"
+"twenty-client-sdk@npm:2.42.0":
+ version: 2.42.0
+ resolution: "twenty-client-sdk@npm:2.42.0"
dependencies:
"@genql/runtime": "npm:^2.10.0"
esbuild: "npm:^0.28.1"
graphql: "npm:^16.8.1"
lodash: "npm:^4.17.21"
prettier: "npm:^3.8.3"
- checksum: 10c0/2ab1c0371a5b48187211477740d833c8454e624d45b4ea1b964864077745d85e6921f5e8452eacb1eceab44e698507a4854686e225e467dd4f5fc481553b047b
+ checksum: 10c0/38f77595ffc2bb365cef23a30d7ab7096fcf129d407921bb97497327da27526e9721ba6a1a16d299bd9b3a2e3f0eeac3fb41ec360c0547e7a2c0f0c044cc570b
languageName: node
linkType: hard
-"twenty-sdk@npm:2.38.0":
- version: 2.38.0
- resolution: "twenty-sdk@npm:2.38.0"
+"twenty-sdk@npm:2.42.0":
+ version: 2.42.0
+ resolution: "twenty-sdk@npm:2.42.0"
dependencies:
"@sniptt/guards": "npm:^0.2.0"
axios: "npm:^1.16.0"
@@ -3654,12 +3654,12 @@ __metadata:
semver: "npm:7.6.3"
sharp: "npm:^0.35.3"
tinyglobby: "npm:^0.2.15"
- twenty-client-sdk: "npm:2.38.0"
+ twenty-client-sdk: "npm:2.42.0"
typescript: "npm:^5.9.3"
uuid: "npm:^13.0.2"
bin:
twenty: dist/cli.cjs
- checksum: 10c0/9946e0018f6233bbd8bd3ab0ca9dcc96276b25126b9c14328b90b15b8f2948d550ebb9395354ec87066bd8ab74372d242d94c4e5629b4cd16421bf21beb8a62e
+ checksum: 10c0/1e43d0c2af55ab8705506f55fe693688575325e506b6cfb16ba4d486d0bfdc0c0f257fc8963ee86f218c10d09b87bacdc769803b6b59283f9e24c7a88346fb84
languageName: node
linkType: hard