Skip to content

The open alternative to Salesforce, designed for AI.

Sync message channels from webhooks without the cron hand-off (#26180)

neo7735a8e238735c0
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
index d470466edcf..b1a3365eb9c 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
@@ -414,6 +414,7 @@ export class BullMQDriver
count: QUEUE_RETENTION.failedMaxCount,
},
delay: options?.delay,
+ deduplication: options?.deduplication,
broadcastTo: options?.broadcastTo,
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface.ts b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface.ts
index 9e283e10d4f..23656443a3c 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface.ts
@@ -4,6 +4,11 @@ export type QueueJobBackoffOptions = {
jitter?: number;
};
+export type QueueJobDeduplicationOptions = {
+ id: string;
+ keepLastIfActive?: boolean;
+};
+
export type QueueJobRecipient = {
workspaceId: string;
userWorkspaceId?: string;
@@ -16,6 +21,7 @@ export interface QueueJobOptions {
retryLimit?: number;
backoff?: QueueJobBackoffOptions;
delay?: number;
+ deduplication?: QueueJobDeduplicationOptions;
broadcastTo?: QueueJobRecipient;
}
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-debounce-ms.constant.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-debounce-ms.constant.ts
deleted file mode 100644
index 7fc96b1652c..00000000000
--- a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-debounce-ms.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_EVENT_WEBHOOK_SYNC_DEBOUNCE_MS = 30000;
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-initial-delay-ms.constant.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-initial-delay-ms.constant.ts
deleted file mode 100644
index 8d0050f4927..00000000000
--- a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-initial-delay-ms.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_INITIAL_DELAY_MS = 5000;
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-jitter.constant.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-jitter.constant.ts
deleted file mode 100644
index ca28c4d2247..00000000000
--- a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-jitter.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_JITTER = 0.5;
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-limit.constant.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-limit.constant.ts
deleted file mode 100644
index 03c31f77464..00000000000
--- a/packages/twenty-server/src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-limit.constant.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_LIMIT = 3;
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/connected-account-sync-webhooks.module.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/connected-account-sync-webhooks.module.ts
index e411bb5a596..e2c76fa9361 100644
--- a/packages/twenty-server/src/modules/connected-account-sync-webhooks/connected-account-sync-webhooks.module.ts
+++ b/packages/twenty-server/src/modules/connected-account-sync-webhooks/connected-account-sync-webhooks.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { ConnectedAccountSyncWebhooksController } from 'src/modules/connected-account-sync-webhooks/connected-account-sync-webhooks.controller';
import { CalendarEventWebhookSyncModule } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/calendar-event-webhook-sync.module';
+import { MessagingMessageWebhookSyncModule } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/messaging-message-webhook-sync.module';
import { GoogleWebhookDriverModule } from 'src/modules/connected-account-sync-webhooks/drivers/google/google-webhook-driver.module';
import { MicrosoftWebhookDriverModule } from 'src/modules/connected-account-sync-webhooks/drivers/microsoft/microsoft-webhook-driver.module';
@@ -10,6 +11,7 @@ import { MicrosoftWebhookDriverModule } from 'src/modules/connected-account-sync
GoogleWebhookDriverModule,
MicrosoftWebhookDriverModule,
CalendarEventWebhookSyncModule,
+ MessagingMessageWebhookSyncModule,
],
controllers: [ConnectedAccountSyncWebhooksController],
})
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job.ts
new file mode 100644
index 00000000000..9d9f12dea9c
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job.ts
@@ -0,0 +1,24 @@
+import { Scope } from '@nestjs/common';
+
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessagingMessageWebhookSyncService } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/services/messaging-message-webhook-sync.service';
+import { type MessagingMessageWebhookSyncJobData } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type';
+
+@Processor({
+ queueName: MessageQueue.connectedAccountSyncWebhookQueue,
+ scope: Scope.REQUEST,
+})
+export class MessagingMessageWebhookSyncJob {
+ constructor(
+ private readonly messagingMessageWebhookSyncService: MessagingMessageWebhookSyncService,
+ ) {}
+
+ @Process(MessagingMessageWebhookSyncJob.name)
+ async handle(data: MessagingMessageWebhookSyncJobData): Promise<void> {
+ await this.messagingMessageWebhookSyncService.processMessagingMessageWebhookSync(
+ data,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/messaging-message-webhook-sync.module.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/messaging-message-webhook-sync.module.ts
new file mode 100644
index 00000000000..9358b67e955
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/messaging-message-webhook-sync.module.ts
@@ -0,0 +1,21 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MessagingMessageWebhookSyncJob } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job';
+import { MessagingMessageWebhookSyncService } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/services/messaging-message-webhook-sync.service';
+import { MessagingCommonModule } from 'src/modules/messaging/common/messaging-common.module';
+import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
+
+@Module({
+ imports: [
+ MessagingCommonModule,
+ MessagingImportManagerModule,
+ TypeOrmModule.forFeature([MessageChannelEntity]),
+ ],
+ providers: [
+ MessagingMessageWebhookSyncService,
+ MessagingMessageWebhookSyncJob,
+ ],
+})
+export class MessagingMessageWebhookSyncModule {}
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/services/messaging-message-webhook-sync.service.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/services/messaging-message-webhook-sync.service.ts
new file mode 100644
index 00000000000..3746a4539e0
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/services/messaging-message-webhook-sync.service.ts
@@ -0,0 +1,55 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { isDefined } from 'twenty-shared/utils';
+import { Repository } from 'typeorm';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { type MessagingMessageWebhookSyncJobData } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type';
+import { MessageChannelSyncStatusService } from 'src/modules/messaging/common/services/message-channel-sync-status.service';
+import { MessagingMessageListFetchService } from 'src/modules/messaging/message-import-manager/services/messaging-message-list-fetch.service';
+
+@Injectable()
+export class MessagingMessageWebhookSyncService {
+ private readonly logger = new Logger(MessagingMessageWebhookSyncService.name);
+
+ constructor(
+ @InjectRepository(MessageChannelEntity)
+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,
+ private readonly messageChannelSyncStatusService: MessageChannelSyncStatusService,
+ private readonly messagingMessageListFetchService: MessagingMessageListFetchService,
+ ) {}
+
+ async processMessagingMessageWebhookSync({
+ messageChannelId,
+ workspaceId,
+ }: MessagingMessageWebhookSyncJobData): Promise<void> {
+ const [scheduledMessageChannelId] =
+ await this.messageChannelSyncStatusService.markAsMessagesListFetchScheduledIfPending(
+ [messageChannelId],
+ workspaceId,
+ );
+
+ if (!isDefined(scheduledMessageChannelId)) {
+ this.logger.log(
+ `Skipping webhook sync for message channel ${messageChannelId}, a sync is already in progress`,
+ );
+
+ return;
+ }
+
+ const messageChannel = await this.messageChannelRepository.findOne({
+ where: { id: messageChannelId, workspaceId, isSyncEnabled: true },
+ relations: { connectedAccount: true, messageFolders: true },
+ });
+
+ if (!isDefined(messageChannel)) {
+ return;
+ }
+
+ await this.messagingMessageListFetchService.processMessageListFetch(
+ messageChannel,
+ workspaceId,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type.ts b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type.ts
new file mode 100644
index 00000000000..4045af4ea83
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type.ts
@@ -0,0 +1,4 @@
+export type MessagingMessageWebhookSyncJobData = {
+ messageChannelId: string;
+ workspaceId: string;
+};
diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-sync-trigger.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-sync-trigger.service.ts
index 89355d2dcbf..31f4dc0c7cd 100644
--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-sync-trigger.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-sync-trigger.service.ts
@@ -1,39 +1,19 @@
import { Injectable } from '@nestjs/common';
-import { InjectRepository } from '@nestjs/typeorm';
-import { MessageChannelSyncStage } from 'twenty-shared/types';
-import { Repository } from 'typeorm';
-
-import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
-import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
-import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceActivationService } from 'src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service';
import { CalendarEventWebhookSyncJob } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/jobs/calendar-event-webhook-sync.job';
import { type CalendarEventWebhookSyncJobData } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/types/calendar-event-webhook-sync-job-data.type';
-import { CALENDAR_EVENT_WEBHOOK_SYNC_DEBOUNCE_MS } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-debounce-ms.constant';
-import { CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_INITIAL_DELAY_MS } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-initial-delay-ms.constant';
-import { CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_JITTER } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-jitter.constant';
-import { CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_LIMIT } from 'src/modules/connected-account-sync-webhooks/calendar-event-webhook-sync/constants/calendar-event-webhook-sync-retry-limit.constant';
-import {
- MessagingMessageListFetchJob,
- type MessagingMessageListFetchJobData,
-} from 'src/modules/messaging/message-import-manager/jobs/messaging-message-list-fetch.job';
+import { MessagingMessageWebhookSyncJob } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job';
+import { type MessagingMessageWebhookSyncJobData } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/types/messaging-message-webhook-sync-job-data.type';
@Injectable()
export class WebhookSyncTriggerService {
constructor(
- @InjectMessageQueue(MessageQueue.messagingQueue)
- private readonly messagingQueueService: MessageQueueService,
@InjectMessageQueue(MessageQueue.connectedAccountSyncWebhookQueue)
private readonly connectedAccountSyncWebhookQueueService: MessageQueueService,
- @InjectCacheStorage(CacheStorageNamespace.ModuleCalendar)
- private readonly cacheStorage: CacheStorageService,
- @InjectRepository(MessageChannelEntity)
- private readonly messageChannelRepository: Repository<MessageChannelEntity>,
private readonly workspaceActivationService: WorkspaceActivationService,
) {}
@@ -50,46 +30,16 @@ export class WebhookSyncTriggerService {
return;
}
- const updateResult = await this.messageChannelRepository
- .createQueryBuilder()
- .update()
- .set({
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_SCHEDULED,
- syncStageStartedAt: new Date(),
- })
- .where({
- id: messageChannelId,
- workspaceId,
- isSyncEnabled: true,
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- })
- .returning('id')
- .execute();
-
- if (updateResult.raw.length === 0) {
- return;
- }
-
- try {
- await this.messagingQueueService.add<MessagingMessageListFetchJobData>(
- MessagingMessageListFetchJob.name,
- { workspaceId, messageChannelId },
- );
- } catch (error) {
- await this.messageChannelRepository
- .createQueryBuilder()
- .update()
- .set({
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- })
- .where({
- id: messageChannelId,
- workspaceId,
- })
- .execute();
-
- throw error;
- }
+ await this.connectedAccountSyncWebhookQueueService.add<MessagingMessageWebhookSyncJobData>(
+ MessagingMessageWebhookSyncJob.name,
+ { workspaceId, messageChannelId },
+ {
+ deduplication: {
+ id: `messaging-message-webhook-sync:${workspaceId}:${messageChannelId}`,
+ keepLastIfActive: true,
+ },
+ },
+ );
}
async triggerCalendarSync(
@@ -105,37 +55,15 @@ export class WebhookSyncTriggerService {
return;
}
- const debounceCacheKey = `calendar-event-webhook-sync-debounce:${workspaceId}:${calendarChannelId}`;
-
- const hasOpenedDebounceWindow = await this.cacheStorage.setIfAbsent(
- debounceCacheKey,
- true,
- CALENDAR_EVENT_WEBHOOK_SYNC_DEBOUNCE_MS,
- );
-
- if (!hasOpenedDebounceWindow) {
- return;
- }
-
- try {
- await this.connectedAccountSyncWebhookQueueService.add<CalendarEventWebhookSyncJobData>(
- CalendarEventWebhookSyncJob.name,
- { workspaceId, calendarChannelId },
- {
- delay: CALENDAR_EVENT_WEBHOOK_SYNC_DEBOUNCE_MS,
- retryLimit: CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_LIMIT,
- backoff: {
- strategy: 'exponential',
- initialDelayMilliseconds:
- CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_INITIAL_DELAY_MS,
- jitter: CALENDAR_EVENT_WEBHOOK_SYNC_RETRY_JITTER,
- },
+ await this.connectedAccountSyncWebhookQueueService.add<CalendarEventWebhookSyncJobData>(
+ CalendarEventWebhookSyncJob.name,
+ { workspaceId, calendarChannelId },
+ {
+ deduplication: {
+ id: `calendar-event-webhook-sync:${workspaceId}:${calendarChannelId}`,
+ keepLastIfActive: true,
},
- );
- } catch (error) {
- await this.cacheStorage.del(debounceCacheKey);
-
- throw error;
- }
+ },
+ );
}
}
diff --git a/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts b/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
index c4e9c88b493..fe644045d52 100644
--- a/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
+++ b/packages/twenty-server/src/modules/messaging/common/services/message-channel-sync-status.service.ts
@@ -193,6 +193,33 @@ export class MessageChannelSyncStatusService {
);
}
+ public async markAsMessagesListFetchScheduledIfPending(
+ messageChannelIds: string[],
+ workspaceId: string,
+ ): Promise<string[]> {
+ if (!messageChannelIds.length) {
+ return [];
+ }
+
+ const updateResult = await this.messageChannelRepository
+ .createQueryBuilder()
+ .update()
+ .set({
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_SCHEDULED,
+ syncStageStartedAt: new Date(),
+ })
+ .where({
+ id: In(messageChannelIds),
+ workspaceId,
+ isSyncEnabled: true,
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ })
+ .returning('id')
+ .execute();
+
+ return updateResult.raw.map((row: { id: string }) => row.id);
+ }
+
public async markAsMessagesListFetchOngoing(
messageChannelIds: string[],
workspaceId: string,
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
index e00aa487a7b..3cb40f71e4a 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
@@ -23,6 +23,7 @@ import {
} from 'src/modules/messaging/message-import-manager/jobs/messaging-message-list-fetch.job';
import { isLastSuccessfulSyncStale } from 'src/modules/connected-account/utils/is-last-successful-sync-stale.util';
import { isThrottled } from 'src/modules/connected-account/utils/is-throttled';
+import { MessageChannelSyncStatusService } from 'src/modules/messaging/common/services/message-channel-sync-status.service';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { toIsoStringOrNull } from 'src/utils/date/toIsoStringOrNull';
@@ -38,6 +39,7 @@ export class MessagingMessageListFetchCronJob {
@InjectRepository(MessageChannelEntity)
private readonly messageChannelRepository: Repository<MessageChannelEntity>,
private readonly exceptionHandlerService: ExceptionHandlerService,
+ private readonly messageChannelSyncStatusService: MessageChannelSyncStatusService,
) {}
@Process(MessagingMessageListFetchCronJob.name)
@@ -99,25 +101,11 @@ export class MessagingMessageListFetchCronJob {
(messageChannel) => messageChannel.id,
);
- const updateResult = await this.messageChannelRepository
- .createQueryBuilder()
- .update()
- .set({
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_SCHEDULED,
- syncStageStartedAt: new Date(),
- })
- .where({
- id: In(messageChannelIdsToSchedule),
+ const updatedIds =
+ await this.messageChannelSyncStatusService.markAsMessagesListFetchScheduledIfPending(
+ messageChannelIdsToSchedule,
workspaceId,
- isSyncEnabled: true,
- syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- })
- .returning('id')
- .execute();
-
- const updatedIds = updateResult.raw.map(
- (row: { id: string }) => row.id,
- );
+ );
for (const messageChannelId of updatedIds) {
await this.messageQueueService.add<MessagingMessageListFetchJobData>(
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/messaging-import-manager.module.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/messaging-import-manager.module.ts
index baf0a24bea0..2182f745b99 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/messaging-import-manager.module.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/messaging-import-manager.module.ts
@@ -129,6 +129,7 @@ import { BlocklistRepository } from 'src/modules/blocklist/repositories/blocklis
InboundEmailImportService,
MessagingSaveMessagesAndEnqueueContactCreationService,
MessagingMessagesImportService,
+ MessagingMessageListFetchService,
],
})
export class MessagingImportManagerModule {}
diff --git a/packages/twenty-server/test/integration/google/messaging/webhook-sync.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/webhook-sync.integration-spec.ts
new file mode 100644
index 00000000000..1f193db70b2
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/webhook-sync.integration-spec.ts
@@ -0,0 +1,66 @@
+import {
+ ConnectedAccountProvider,
+ MessageChannelSyncStage,
+} from 'twenty-shared/types';
+
+import { getGmailMessageSubject } from 'test/integration/google/mocks/gmail-message-subject.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findImportedMessageSubjects } from 'test/integration/utils/find-imported-records.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+import { runMessageChannelWebhookSync } from 'test/integration/utils/run-message-channel-webhook-sync.util';
+
+const HANDLE = '[email protected]';
+
+describe('Messaging webhook sync (integration)', () => {
+ const inbox = [gmailMessage()];
+
+ const gmail = setupGoogleMock({ handle: HANDLE, inbox });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ await runMessageChannelSync(channel.channelId);
+ }, 120000);
+
+ afterAll(async () => {
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('imports a new message in a single job without the list fetch cron', async () => {
+ const newMessage = gmailMessage();
+
+ inbox.push(newMessage);
+ gmail.serveHistory([newMessage]);
+
+ await runMessageChannelWebhookSync(channel.channelId);
+
+ const newSubject = getGmailMessageSubject(newMessage);
+
+ expect(await findImportedMessageSubjects([newSubject])).toEqual([
+ newSubject,
+ ]);
+ }, 120000);
+
+ it('does not sync when the channel is already being synced', async () => {
+ const newMessage = gmailMessage();
+
+ inbox.push(newMessage);
+ gmail.serveHistory([newMessage]);
+
+ await runMessageChannelWebhookSync(
+ channel.channelId,
+ MessageChannelSyncStage.MESSAGE_LIST_FETCH_ONGOING,
+ );
+
+ expect(
+ await findImportedMessageSubjects([getGmailMessageSubject(newMessage)]),
+ ).toEqual([]);
+ }, 120000);
+});
diff --git a/packages/twenty-server/test/integration/utils/run-message-channel-webhook-sync.util.ts b/packages/twenty-server/test/integration/utils/run-message-channel-webhook-sync.util.ts
new file mode 100644
index 00000000000..50ed33a8303
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/run-message-channel-webhook-sync.util.ts
@@ -0,0 +1,25 @@
+import { MessageChannelSyncStage } from 'twenty-shared/types';
+
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MessagingMessageWebhookSyncJob } from 'src/modules/connected-account-sync-webhooks/messaging-message-webhook-sync/jobs/messaging-message-webhook-sync.job';
+
+import { enqueueJobAndDrain } from 'test/integration/utils/enqueue-job-and-drain.util';
+import { scheduleChannelStage } from 'test/integration/utils/schedule-channel-stage.util';
+
+export const runMessageChannelWebhookSync = async (
+ messageChannelId: string,
+ startingStage: MessageChannelSyncStage = MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+): Promise<void> => {
+ const workspaceId = await scheduleChannelStage(
+ MessageChannelEntity,
+ messageChannelId,
+ startingStage,
+ );
+
+ await enqueueJobAndDrain(
+ MessageQueue.connectedAccountSyncWebhookQueue,
+ MessagingMessageWebhookSyncJob.name,
+ { workspaceId, messageChannelId },
+ );
+};