The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Stop servicing webhook subscriptions for suspended workspaces (#25657)
neo773ad72bbaa09e6
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/google-apis.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/google-apis.service.tsindex bbe5bdf7f78..d8bd0033c20 100644--- a/packages/twenty-server/src/engine/core-modules/auth/services/google-apis.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/services/google-apis.service.ts@@ -42,7 +42,7 @@ import {import { CalendarChannelSyncStatusService } from 'src/modules/calendar/common/services/calendar-channel-sync-status.service';import { EmailAliasManagerService } from 'src/modules/connected-account/email-alias-manager/services/email-alias-manager.service';import { AccountsToReconnectService } from 'src/modules/connected-account/services/accounts-to-reconnect.service';-import { WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';import {CreateWebhookSubscriptionJob,type CreateWebhookSubscriptionJobData,@@ -435,7 +435,7 @@ export class GoogleAPIsService {await this.webhookQueueService.add<CreateWebhookSubscriptionJobData>(CreateWebhookSubscriptionJob.name,{ channelType, channelId, workspaceId },- { retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT },+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },);} catch (error) {this.logger.warn(diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/microsoft-apis.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/microsoft-apis.service.tsindex da17a95b287..9ad91e606c7 100644--- a/packages/twenty-server/src/engine/core-modules/auth/services/microsoft-apis.service.ts+++ b/packages/twenty-server/src/engine/core-modules/auth/services/microsoft-apis.service.ts@@ -40,7 +40,7 @@ import {import { CalendarChannelSyncStatusService } from 'src/modules/calendar/common/services/calendar-channel-sync-status.service';import { EmailAliasManagerService } from 'src/modules/connected-account/email-alias-manager/services/email-alias-manager.service';import { AccountsToReconnectService } from 'src/modules/connected-account/services/accounts-to-reconnect.service';-import { WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';import {CreateWebhookSubscriptionJob,type CreateWebhookSubscriptionJobData,@@ -386,7 +386,7 @@ export class MicrosoftAPIsService {await this.webhookQueueService.add<CreateWebhookSubscriptionJobData>(CreateWebhookSubscriptionJob.name,{ channelType, channelId, workspaceId },- { retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT },+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },);} catch (error) {this.logger.warn(diff --git a/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-reactivated-event.constant.ts b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-reactivated-event.constant.tsnew file mode 100644index 00000000000..769f4ffecd7--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-reactivated-event.constant.ts@@ -0,0 +1 @@+export const WORKSPACE_REACTIVATED_EVENT = 'workspace.reactivated';diff --git a/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-soft-deleted-event.constant.ts b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-soft-deleted-event.constant.tsnew file mode 100644index 00000000000..9b25a15b1d4--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-soft-deleted-event.constant.ts@@ -0,0 +1 @@+export const WORKSPACE_SOFT_DELETED_EVENT = 'workspace.softDeleted';diff --git a/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-suspended-event.constant.ts b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-suspended-event.constant.tsnew file mode 100644index 00000000000..f6695385d7e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/constants/workspace-suspended-event.constant.ts@@ -0,0 +1 @@+export const WORKSPACE_SUSPENDED_EVENT = 'workspace.suspended';diff --git a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.tsindex 49a1e418325..5ed7421f358 100644--- a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts+++ b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts@@ -1,4 +1,5 @@import { Injectable, Logger } from '@nestjs/common';+import { EventEmitter2 } from '@nestjs/event-emitter';import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';import assert from 'assert';@@ -58,6 +59,12 @@ import {type WorkspaceDeletionApplicationUninstallJobData,} from 'src/engine/core-modules/workspace/jobs/workspace-deletion-application-uninstall.job';import { getWorkspaceApplicationUninstallLockName } from 'src/engine/core-modules/workspace/utils/get-workspace-application-uninstall-lock-name.util';+import { WORKSPACE_REACTIVATED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-reactivated-event.constant';+import { WORKSPACE_SOFT_DELETED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-soft-deleted-event.constant';+import { WORKSPACE_SUSPENDED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-suspended-event.constant';+import { type WorkspaceReactivatedEvent } from 'src/engine/core-modules/workspace/types/workspace-reactivated-event.type';+import { type WorkspaceSoftDeletedEvent } from 'src/engine/core-modules/workspace/types/workspace-soft-deleted-event.type';+import { type WorkspaceSuspendedEvent } from 'src/engine/core-modules/workspace/types/workspace-suspended-event.type';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import {WorkspaceException,@@ -134,6 +141,7 @@ export class WorkspaceService {constructor(@InjectRepository(WorkspaceEntity)private readonly workspaceRepository: Repository<WorkspaceEntity>,+ private readonly eventEmitter: EventEmitter2,@InjectRepository(UserEntity)private readonly userRepository: Repository<UserEntity>,@InjectRepository(UserWorkspaceEntity)@@ -526,6 +534,10 @@ export class WorkspaceService {const hasBeenSuspended = isDefined(affected) && affected > 0;if (hasBeenSuspended) {+ this.eventEmitter.emit(WORKSPACE_SUSPENDED_EVENT, {+ workspaceId: id,+ } satisfies WorkspaceSuspendedEvent);+await this.coreEntityCacheService.invalidate('workspaceEntity', id);}@@ -551,6 +563,10 @@ export class WorkspaceService {const hasBeenReactivated = isDefined(affected) && affected > 0;if (hasBeenReactivated) {+ this.eventEmitter.emit(WORKSPACE_REACTIVATED_EVENT, {+ workspaceId: id,+ } satisfies WorkspaceReactivatedEvent);+await this.coreEntityCacheService.invalidate('workspaceEntity', id);}@@ -589,6 +605,11 @@ export class WorkspaceService {await this.workspaceRepository.softDelete({ id, deletedAt: IsNull() });await this.coreEntityCacheService.invalidate('workspaceEntity', id);++ this.eventEmitter.emit(WORKSPACE_SOFT_DELETED_EVENT, {+ workspaceId: id,+ } satisfies WorkspaceSoftDeletedEvent);+await this.enqueueWorkspaceDeletionApplicationUninstall(id);this.logger.log(`workspace ${id} soft deleted`);diff --git a/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-reactivated-event.type.ts b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-reactivated-event.type.tsnew file mode 100644index 00000000000..89000f3e04e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-reactivated-event.type.ts@@ -0,0 +1,3 @@+export type WorkspaceReactivatedEvent = {+ workspaceId: string;+};diff --git a/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-soft-deleted-event.type.ts b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-soft-deleted-event.type.tsnew file mode 100644index 00000000000..e752a45c7aa--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-soft-deleted-event.type.ts@@ -0,0 +1,3 @@+export type WorkspaceSoftDeletedEvent = {+ workspaceId: string;+};diff --git a/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-suspended-event.type.ts b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-suspended-event.type.tsnew file mode 100644index 00000000000..7a8f65e7603--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-suspended-event.type.ts@@ -0,0 +1,3 @@+export type WorkspaceSuspendedEvent = {+ workspaceId: string;+};diff --git a/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts b/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.tsindex 40acb0c0ee1..1e9df6ffc28 100644--- a/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts+++ b/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts@@ -22,7 +22,7 @@ import {CalendarEventListFetchJob,type CalendarEventListFetchJobData,} from 'src/modules/calendar/calendar-event-import-manager/jobs/calendar-event-list-fetch.job';-import { WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';import {CreateWebhookSubscriptionJob,type CreateWebhookSubscriptionJobData,@@ -111,7 +111,7 @@ export class ChannelSyncService {channelId: messageChannel.id,workspaceId,},- { retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT },+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },);} catch (error) {this.logger.warn(@@ -172,7 +172,7 @@ export class ChannelSyncService {channelId: calendarChannel.id,workspaceId,},- { retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT },+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },);} catch (error) {this.logger.warn(diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/commands/create-webhook-subscription-for-connected-account.command.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/commands/create-webhook-subscription-for-connected-account.command.tsindex f072aba4c92..2071bf7cee1 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/commands/create-webhook-subscription-for-connected-account.command.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/commands/create-webhook-subscription-for-connected-account.command.ts@@ -16,7 +16,7 @@ import { MessageQueueService } from 'src/engine/core-modules/message-queue/serviimport { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';import { WEBHOOK_CAPABLE_PROVIDERS } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-capable-providers.constant';-import { WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';import {CreateWebhookSubscriptionJob,type CreateWebhookSubscriptionJobData,@@ -120,7 +120,7 @@ export class CreateWebhookSubscriptionForConnectedAccountCommand extends Provisi{ channelType, channelId, workspaceId },{delay: this.enqueueCursorMs,- retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT,+ retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT,},);diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/claimable-webhook-subscription-statuses.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/claimable-webhook-subscription-statuses.constant.tsnew file mode 100644index 00000000000..7d3088bddaa--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/claimable-webhook-subscription-statuses.constant.ts@@ -0,0 +1,4 @@+import { WebhookSubscriptionStatus } from 'twenty-shared/types';++export const CLAIMABLE_WEBHOOK_SUBSCRIPTION_STATUSES: WebhookSubscriptionStatus[] =+ [WebhookSubscriptionStatus.FAILED, WebhookSubscriptionStatus.EXPIRED];diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/revocable-webhook-subscription-statuses.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/revocable-webhook-subscription-statuses.constant.tsnew file mode 100644index 00000000000..df13f8ec079--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/revocable-webhook-subscription-statuses.constant.ts@@ -0,0 +1,9 @@+import { WebhookSubscriptionStatus } from 'twenty-shared/types';++export const REVOCABLE_WEBHOOK_SUBSCRIPTION_STATUSES: WebhookSubscriptionStatus[] =+ [+ WebhookSubscriptionStatus.ACTIVE,+ WebhookSubscriptionStatus.FAILED,+ WebhookSubscriptionStatus.EXPIRED,+ WebhookSubscriptionStatus.PENDING,+ ];diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/serviceable-workspace-activation-statuses.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/serviceable-workspace-activation-statuses.constant.tsnew file mode 100644index 00000000000..6bb865b35d3--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/serviceable-workspace-activation-statuses.constant.ts@@ -0,0 +1,4 @@+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';++export const SERVICEABLE_WORKSPACE_ACTIVATION_STATUSES: WorkspaceActivationStatus[] =+ [WorkspaceActivationStatus.CREATED, WorkspaceActivationStatus.ACTIVE];diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-claim-stale-ms.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-claim-stale-ms.constant.tsnew file mode 100644index 00000000000..b2f2ee96a4d--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-claim-stale-ms.constant.ts@@ -0,0 +1 @@+export const WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS = 10 * 60 * 1000;diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant.tsdeleted file mode 100644index 7577e5b0790..00000000000--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant.ts+++ /dev/null@@ -1 +0,0 @@-export const WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT = 3;diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant.tsnew file mode 100644index 00000000000..7bb43ad4cbd--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant.ts@@ -0,0 +1 @@+export const WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT = 3;diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job.tsindex 4ff96144e56..ed46841a35e 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job.ts@@ -28,7 +28,8 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entimport { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';import { WEBHOOK_CAPABLE_PROVIDERS } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-capable-providers.constant';-import { WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-creation-retry-limit.constant';+import { WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-claim-stale-ms.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';import { WEBHOOK_SUBSCRIPTION_RENEWAL_BATCH_SIZE } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-renewal-batch-size.constant';import { WEBHOOK_SUBSCRIPTION_RENEWAL_BUFFER_MS } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-renewal-buffer-ms.constant';import { WEBHOOK_SUBSCRIPTION_RENEWAL_CRON_PATTERN } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-renewal-cron-pattern.constant';@@ -201,6 +202,13 @@ export class WebhookSubscriptionRenewalCronJob {...scope,webhookSubscriptionStatus: WebhookSubscriptionStatus.EXPIRED,},+ {+ ...scope,+ webhookSubscriptionStatus: WebhookSubscriptionStatus.PENDING,+ updatedAt: LessThanOrEqual(+ new Date(Date.now() - WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS),+ ),+ },],order: { updatedAt: 'ASC' },take: WEBHOOK_SUBSCRIPTION_RENEWAL_BATCH_SIZE,@@ -224,6 +232,13 @@ export class WebhookSubscriptionRenewalCronJob {...scope,webhookSubscriptionStatus: WebhookSubscriptionStatus.EXPIRED,},+ {+ ...scope,+ webhookSubscriptionStatus: WebhookSubscriptionStatus.PENDING,+ updatedAt: LessThanOrEqual(+ new Date(Date.now() - WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS),+ ),+ },],order: { updatedAt: 'ASC' },take: WEBHOOK_SUBSCRIPTION_RENEWAL_BATCH_SIZE,@@ -248,7 +263,7 @@ export class WebhookSubscriptionRenewalCronJob {workspaceId: channel.workspaceId,},{- retryLimit: WEBHOOK_SUBSCRIPTION_CREATION_RETRY_LIMIT,+ retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT,delay: Math.round(index * spacingMs),},);diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/revoke-webhook-subscription.job.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/revoke-webhook-subscription.job.tsnew file mode 100644index 00000000000..e6cef06073e--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/revoke-webhook-subscription.job.ts@@ -0,0 +1,36 @@+import { WebhookSubscriptionChannelType } from 'twenty-shared/types';++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 { CalendarWebhookSubscriptionService } from 'src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service';+import { MessagingWebhookSubscriptionService } from 'src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service';+import { type WebhookSubscriptionChannelReference } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-channel-reference.type';++@Processor(MessageQueue.webhookQueue)+export class RevokeWebhookSubscriptionJob {+ constructor(+ private readonly messagingWebhookSubscriptionService: MessagingWebhookSubscriptionService,+ private readonly calendarWebhookSubscriptionService: CalendarWebhookSubscriptionService,+ ) {}++ @Process(RevokeWebhookSubscriptionJob.name)+ async handle(data: WebhookSubscriptionChannelReference): Promise<void> {+ const { channelType, channelId, workspaceId } = data;++ switch (channelType) {+ case WebhookSubscriptionChannelType.MESSAGING:+ await this.messagingWebhookSubscriptionService.revokeSubscription({+ messageChannelId: channelId,+ workspaceId,+ });+ break;+ case WebhookSubscriptionChannelType.CALENDAR:+ await this.calendarWebhookSubscriptionService.revokeSubscription({+ calendarChannelId: channelId,+ workspaceId,+ });+ break;+ }+ }+}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/sync-workspace-webhook-subscriptions.job.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/sync-workspace-webhook-subscriptions.job.tsnew file mode 100644index 00000000000..e2c29dfc310--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/jobs/sync-workspace-webhook-subscriptions.job.ts@@ -0,0 +1,37 @@+import { assertUnreachable } from 'twenty-shared/utils';++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 { WebhookSubscriptionWorkspaceSyncService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-workspace-sync.service';+import { type SyncWorkspaceWebhookSubscriptionsJobData } from 'src/modules/connected-account/webhook-subscription-manager/types/sync-workspace-webhook-subscriptions-job-data.type';++@Processor(MessageQueue.webhookQueue)+export class SyncWorkspaceWebhookSubscriptionsJob {+ constructor(+ private readonly webhookSubscriptionWorkspaceSyncService: WebhookSubscriptionWorkspaceSyncService,+ ) {}++ @Process(SyncWorkspaceWebhookSubscriptionsJob.name)+ async handle({+ workspaceId,+ action,+ }: SyncWorkspaceWebhookSubscriptionsJobData): Promise<void> {+ switch (action) {+ case 'REVOKE':+ await this.webhookSubscriptionWorkspaceSyncService.enqueueRevocations(+ workspaceId,+ );++ return;+ case 'CREATE':+ await this.webhookSubscriptionWorkspaceSyncService.enqueueCreations(+ workspaceId,+ );++ return;+ default:+ return assertUnreachable(action);+ }+ }+}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-channel-deleted.listener.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-channel-deleted.listener.tsindex 580a8d25056..2686850b327 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-channel-deleted.listener.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-channel-deleted.listener.ts@@ -3,6 +3,7 @@ import { Injectable } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';import { OnCustomBatchEvent } from 'src/engine/api/graphql/graphql-query-runner/decorators/on-custom-batch-event.decorator';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { CALENDAR_CHANNEL_DELETED_EVENT } from 'src/engine/metadata-modules/calendar-channel/constants/calendar-channel-deleted.constant';import { type CalendarChannelDeletedEvent } from 'src/engine/metadata-modules/calendar-channel/types/calendar-channel-deleted.type';import { MESSAGE_CHANNEL_DELETED_EVENT } from 'src/engine/metadata-modules/message-channel/constants/message-channel-deleted.constant';@@ -16,6 +17,7 @@ export class WebhookSubscriptionChannelDeletedListener {constructor(private readonly messagingWebhookSubscriptionService: MessagingWebhookSubscriptionService,private readonly calendarWebhookSubscriptionService: CalendarWebhookSubscriptionService,+ private readonly exceptionHandlerService: ExceptionHandlerService,) {}@OnCustomBatchEvent(MESSAGE_CHANNEL_DELETED_EVENT)@@ -29,10 +31,13 @@ export class WebhookSubscriptionChannelDeletedListener {}for (const event of batchEvent.events) {- await this.messagingWebhookSubscriptionService.deleteSubscription(- event.messageChannelId,- workspaceId,- );+ await this.messagingWebhookSubscriptionService+ .deleteSubscription(event.messageChannelId, workspaceId)+ .catch((error) =>+ this.exceptionHandlerService.captureExceptions([error], {+ workspace: { id: workspaceId },+ }),+ );}}@@ -47,10 +52,13 @@ export class WebhookSubscriptionChannelDeletedListener {}for (const event of batchEvent.events) {- await this.calendarWebhookSubscriptionService.deleteSubscription(- event.calendarChannelId,- workspaceId,- );+ await this.calendarWebhookSubscriptionService+ .deleteSubscription(event.calendarChannelId, workspaceId)+ .catch((error) =>+ this.exceptionHandlerService.captureExceptions([error], {+ workspace: { id: workspaceId },+ }),+ );}}}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-workspace-activation.listener.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-workspace-activation.listener.tsnew file mode 100644index 00000000000..ae4ae6b0881--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-workspace-activation.listener.ts@@ -0,0 +1,64 @@+import { Injectable } from '@nestjs/common';+import { OnEvent } from '@nestjs/event-emitter';++import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+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 { WORKSPACE_REACTIVATED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-reactivated-event.constant';+import { WORKSPACE_SOFT_DELETED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-soft-deleted-event.constant';+import { WORKSPACE_SUSPENDED_EVENT } from 'src/engine/core-modules/workspace/constants/workspace-suspended-event.constant';+import { type WorkspaceReactivatedEvent } from 'src/engine/core-modules/workspace/types/workspace-reactivated-event.type';+import { type WorkspaceSoftDeletedEvent } from 'src/engine/core-modules/workspace/types/workspace-soft-deleted-event.type';+import { type WorkspaceSuspendedEvent } from 'src/engine/core-modules/workspace/types/workspace-suspended-event.type';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';+import { SyncWorkspaceWebhookSubscriptionsJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/sync-workspace-webhook-subscriptions.job';+import { type SyncWorkspaceWebhookSubscriptionsJobData } from 'src/modules/connected-account/webhook-subscription-manager/types/sync-workspace-webhook-subscriptions-job-data.type';+import { type WebhookSubscriptionSyncAction } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-sync-action.type';++@Injectable()+export class WebhookSubscriptionWorkspaceActivationListener {+ constructor(+ @InjectMessageQueue(MessageQueue.webhookQueue)+ private readonly webhookQueueService: MessageQueueService,+ private readonly exceptionHandlerService: ExceptionHandlerService,+ ) {}++ @OnEvent(WORKSPACE_SUSPENDED_EVENT)+ async handleWorkspaceSuspended({+ workspaceId,+ }: WorkspaceSuspendedEvent): Promise<void> {+ await this.enqueueSync(workspaceId, 'REVOKE');+ }++ @OnEvent(WORKSPACE_SOFT_DELETED_EVENT)+ async handleWorkspaceSoftDeleted({+ workspaceId,+ }: WorkspaceSoftDeletedEvent): Promise<void> {+ await this.enqueueSync(workspaceId, 'REVOKE');+ }++ @OnEvent(WORKSPACE_REACTIVATED_EVENT)+ async handleWorkspaceReactivated({+ workspaceId,+ }: WorkspaceReactivatedEvent): Promise<void> {+ await this.enqueueSync(workspaceId, 'CREATE');+ }++ private async enqueueSync(+ workspaceId: string,+ action: WebhookSubscriptionSyncAction,+ ): Promise<void> {+ await this.webhookQueueService+ .add<SyncWorkspaceWebhookSubscriptionsJobData>(+ SyncWorkspaceWebhookSubscriptionsJob.name,+ { workspaceId, action },+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },+ )+ .catch((error) =>+ this.exceptionHandlerService.captureExceptions([error], {+ workspace: { id: workspaceId },+ }),+ );+ }+}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service.tsindex b954654cdfa..3c8b3c7eedf 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service.ts@@ -7,9 +7,7 @@ import {} from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { Repository } from 'typeorm';-import { v4 } from 'uuid';-import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';@@ -21,7 +19,11 @@ import {import { WebhookSubscriptionDriverFactory } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-driver-factory.service';import { WebhookSubscriptionExceptionHandlerService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-exception-handler.service';import { WebhookSubscriptionStatusService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service';-import { type WebhookSubscriptionContext } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-driver.type';+import { WorkspaceActivationService } from 'src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service';+import {+ type WebhookSubscriptionContext,+ type WebhookSubscriptionResult,+} from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-driver.type';@Injectable()export class CalendarWebhookSubscriptionService {@@ -30,8 +32,8 @@ export class CalendarWebhookSubscriptionService {private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,@InjectRepository(CalendarChannelEntity)private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,+ private readonly workspaceActivationService: WorkspaceActivationService,private readonly webhookSubscriptionDriverFactory: WebhookSubscriptionDriverFactory,- private readonly exceptionHandlerService: ExceptionHandlerService,private readonly metricsService: MetricsService,private readonly webhookSubscriptionStatusService: WebhookSubscriptionStatusService,private readonly webhookSubscriptionExceptionHandlerService: WebhookSubscriptionExceptionHandlerService,@@ -41,6 +43,13 @@ export class CalendarWebhookSubscriptionService {calendarChannelId: string,workspaceId: string,): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (!isWorkspaceServiceable) {+ return;+ }+const calendarChannel = await this.calendarChannelRepository.findOne({where: { id: calendarChannelId, workspaceId },relations: ['connectedAccount'],@@ -67,7 +76,6 @@ export class CalendarWebhookSubscriptionService {return;}- const clientState = calendarChannel.webhookSubscriptionClientState ?? v4();const driver = this.webhookSubscriptionDriverFactory.getDriver(connectedAccount.provider,);@@ -79,30 +87,29 @@ export class CalendarWebhookSubscriptionService {? this.toContext(calendarChannel): null;- try {- const result = await driver.createSubscription(- calendarChannel.connectedAccountId,+ const clientState =+ await this.webhookSubscriptionStatusService.claimSubscriptionCreation(WebhookSubscriptionChannelType.CALENDAR,- clientState,+ calendarChannel.id,+ workspaceId,);- await this.webhookSubscriptionStatusService.markAsActive(+ if (!isDefined(clientState)) {+ return;+ }++ let result: WebhookSubscriptionResult;++ try {+ result = await driver.createSubscription(+ calendarChannel.connectedAccountId,WebhookSubscriptionChannelType.CALENDAR,- calendarChannel.id,- result,clientState,);-- this.metricsService.incrementCounterBy({- key: MetricsKeys.ConnectedAccountWebhookSubscriptionCreated,- amount: 1,- attributes: this.buildMetricAttributes(connectedAccount.provider),- });} catch (error) {await this.webhookSubscriptionStatusService.resetPendingSubscription(WebhookSubscriptionChannelType.CALENDAR,calendarChannel.id,- clientState,);this.metricsService.incrementCounterBy({@@ -122,6 +129,35 @@ export class CalendarWebhookSubscriptionService {return;}+ const hasSettledClaim =+ await this.webhookSubscriptionStatusService.settleClaimedSubscription(+ WebhookSubscriptionChannelType.CALENDAR,+ calendarChannel.id,+ workspaceId,+ clientState,+ result,+ );++ if (!hasSettledClaim) {+ await driver+ .deleteSubscription({+ connectedAccountId: calendarChannel.connectedAccountId,+ channelType: WebhookSubscriptionChannelType.CALENDAR,+ externalSubscriptionId: result.externalSubscriptionId,+ externalResourceId: result.externalResourceId,+ clientState,+ })+ .catch(() => undefined);++ return;+ }++ this.metricsService.incrementCounterBy({+ key: MetricsKeys.ConnectedAccountWebhookSubscriptionCreated,+ amount: 1,+ attributes: this.buildMetricAttributes(connectedAccount.provider),+ });+if (isDefined(previousSubscription)) {await driver.deleteSubscription(previousSubscription)@@ -160,6 +196,13 @@ export class CalendarWebhookSubscriptionService {calendarChannelId: string;workspaceId: string;}): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (!isWorkspaceServiceable) {+ return;+ }+const calendarChannel = await this.calendarChannelRepository.findOne({where: { id: calendarChannelId, workspaceId },relations: ['connectedAccount'],@@ -275,12 +318,32 @@ export class CalendarWebhookSubscriptionService {attributes: this.buildMetricAttributes(connectedAccount.provider),});- this.exceptionHandlerService.captureExceptions([error], {- workspace: { id: calendarChannel.workspaceId },- });+ throw error;}}+ async revokeSubscription({+ calendarChannelId,+ workspaceId,+ }: {+ calendarChannelId: string;+ workspaceId: string;+ }): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (isWorkspaceServiceable) {+ return;+ }++ await this.deleteSubscription(calendarChannelId, workspaceId);++ await this.webhookSubscriptionStatusService.markAsExpired(+ WebhookSubscriptionChannelType.CALENDAR,+ calendarChannelId,+ );+ }+private buildMetricAttributes(provider: string) {return {channel_type: WebhookSubscriptionChannelType.CALENDAR,diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service.tsindex 33912d4bbc0..f9afacad923 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service.ts@@ -7,9 +7,7 @@ import {} from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { Repository } from 'typeorm';-import { v4 } from 'uuid';-import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -21,7 +19,11 @@ import {import { WebhookSubscriptionDriverFactory } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-driver-factory.service';import { WebhookSubscriptionExceptionHandlerService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-exception-handler.service';import { WebhookSubscriptionStatusService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service';-import { type WebhookSubscriptionContext } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-driver.type';+import { WorkspaceActivationService } from 'src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service';+import {+ type WebhookSubscriptionContext,+ type WebhookSubscriptionResult,+} from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-driver.type';@Injectable()export class MessagingWebhookSubscriptionService {@@ -30,8 +32,8 @@ export class MessagingWebhookSubscriptionService {private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,@InjectRepository(MessageChannelEntity)private readonly messageChannelRepository: Repository<MessageChannelEntity>,+ private readonly workspaceActivationService: WorkspaceActivationService,private readonly webhookSubscriptionDriverFactory: WebhookSubscriptionDriverFactory,- private readonly exceptionHandlerService: ExceptionHandlerService,private readonly metricsService: MetricsService,private readonly webhookSubscriptionStatusService: WebhookSubscriptionStatusService,private readonly webhookSubscriptionExceptionHandlerService: WebhookSubscriptionExceptionHandlerService,@@ -41,6 +43,13 @@ export class MessagingWebhookSubscriptionService {messageChannelId: string,workspaceId: string,): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (!isWorkspaceServiceable) {+ return;+ }+const messageChannel = await this.messageChannelRepository.findOne({where: { id: messageChannelId, workspaceId },relations: ['connectedAccount'],@@ -67,7 +76,6 @@ export class MessagingWebhookSubscriptionService {return;}- const clientState = messageChannel.webhookSubscriptionClientState ?? v4();const driver = this.webhookSubscriptionDriverFactory.getDriver(connectedAccount.provider,);@@ -79,30 +87,29 @@ export class MessagingWebhookSubscriptionService {? this.toContext(messageChannel): null;- try {- const result = await driver.createSubscription(- messageChannel.connectedAccountId,+ const clientState =+ await this.webhookSubscriptionStatusService.claimSubscriptionCreation(WebhookSubscriptionChannelType.MESSAGING,- clientState,+ messageChannel.id,+ workspaceId,);- await this.webhookSubscriptionStatusService.markAsActive(+ if (!isDefined(clientState)) {+ return;+ }++ let result: WebhookSubscriptionResult;++ try {+ result = await driver.createSubscription(+ messageChannel.connectedAccountId,WebhookSubscriptionChannelType.MESSAGING,- messageChannel.id,- result,clientState,);-- this.metricsService.incrementCounterBy({- key: MetricsKeys.ConnectedAccountWebhookSubscriptionCreated,- amount: 1,- attributes: this.buildMetricAttributes(connectedAccount.provider),- });} catch (error) {await this.webhookSubscriptionStatusService.resetPendingSubscription(WebhookSubscriptionChannelType.MESSAGING,messageChannel.id,- clientState,);this.metricsService.incrementCounterBy({@@ -122,6 +129,35 @@ export class MessagingWebhookSubscriptionService {return;}+ const hasSettledClaim =+ await this.webhookSubscriptionStatusService.settleClaimedSubscription(+ WebhookSubscriptionChannelType.MESSAGING,+ messageChannel.id,+ workspaceId,+ clientState,+ result,+ );++ if (!hasSettledClaim) {+ await driver+ .deleteSubscription({+ connectedAccountId: messageChannel.connectedAccountId,+ channelType: WebhookSubscriptionChannelType.MESSAGING,+ externalSubscriptionId: result.externalSubscriptionId,+ externalResourceId: null,+ clientState,+ })+ .catch(() => undefined);++ return;+ }++ this.metricsService.incrementCounterBy({+ key: MetricsKeys.ConnectedAccountWebhookSubscriptionCreated,+ amount: 1,+ attributes: this.buildMetricAttributes(connectedAccount.provider),+ });+if (isDefined(previousSubscription)) {await driver.deleteSubscription(previousSubscription)@@ -160,6 +196,13 @@ export class MessagingWebhookSubscriptionService {messageChannelId: string;workspaceId: string;}): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (!isWorkspaceServiceable) {+ return;+ }+const messageChannel = await this.messageChannelRepository.findOne({where: { id: messageChannelId, workspaceId },relations: ['connectedAccount'],@@ -275,12 +318,32 @@ export class MessagingWebhookSubscriptionService {attributes: this.buildMetricAttributes(connectedAccount.provider),});- this.exceptionHandlerService.captureExceptions([error], {- workspace: { id: messageChannel.workspaceId },- });+ throw error;}}+ async revokeSubscription({+ messageChannelId,+ workspaceId,+ }: {+ messageChannelId: string;+ workspaceId: string;+ }): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceable(workspaceId);++ if (isWorkspaceServiceable) {+ return;+ }++ await this.deleteSubscription(messageChannelId, workspaceId);++ await this.webhookSubscriptionStatusService.markAsExpired(+ WebhookSubscriptionChannelType.MESSAGING,+ messageChannelId,+ );+ }+private buildMetricAttributes(provider: string) {return {channel_type: WebhookSubscriptionChannelType.MESSAGING,diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service.tsindex de059b350d3..06674a16f7f 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service.ts@@ -8,9 +8,12 @@ import {import { isDefined } from 'twenty-shared/utils';import { Repository } from 'typeorm';import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';+import { v4 } from 'uuid';import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';+import { CLAIMABLE_WEBHOOK_SUBSCRIPTION_STATUSES } from 'src/modules/connected-account/webhook-subscription-manager/constants/claimable-webhook-subscription-statuses.constant';+import { WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-claim-stale-ms.constant';import {type WebhookSubscribableChannel,type WebhookSubscriptionResult,@@ -25,19 +28,76 @@ export class WebhookSubscriptionStatusService {private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,) {}+ public async claimSubscriptionCreation(+ channelType: WebhookSubscriptionChannelType,+ channelId: string,+ workspaceId: string,+ ): Promise<string | null> {+ const clientState = v4();++ const updateResult = await this.getRepository(channelType)+ .createQueryBuilder()+ .update()+ .set({+ webhookSubscriptionStatus: WebhookSubscriptionStatus.PENDING,+ webhookSubscriptionClientState: clientState,+ })+ .where('"id" = :channelId', { channelId })+ .andWhere('"workspaceId" = :workspaceId', { workspaceId })+ .andWhere(+ `("webhookSubscriptionStatus" IS NULL+ OR "webhookSubscriptionStatus" IN (:...claimableStatuses)+ OR ("webhookSubscriptionStatus" = :pendingStatus AND "updatedAt" <= :staleClaimBefore))`,+ {+ claimableStatuses: CLAIMABLE_WEBHOOK_SUBSCRIPTION_STATUSES,+ pendingStatus: WebhookSubscriptionStatus.PENDING,+ staleClaimBefore: new Date(+ Date.now() - WEBHOOK_SUBSCRIPTION_CLAIM_STALE_MS,+ ),+ },+ )+ .returning('id')+ .execute();++ return updateResult.raw.length > 0 ? clientState : null;+ }++ public async settleClaimedSubscription(+ channelType: WebhookSubscriptionChannelType,+ channelId: string,+ workspaceId: string,+ clientState: string,+ result: WebhookSubscriptionResult,+ ): Promise<boolean> {+ const { affected } = await this.getRepository(channelType).update(+ {+ id: channelId,+ workspaceId,+ webhookSubscriptionStatus: WebhookSubscriptionStatus.PENDING,+ webhookSubscriptionClientState: clientState,+ },+ {+ webhookSubscriptionExternalId: result.externalSubscriptionId,+ webhookSubscriptionStatus: WebhookSubscriptionStatus.ACTIVE,+ webhookSubscriptionExpiresAt: result.expiresAt,+ ...(channelType === WebhookSubscriptionChannelType.CALENDAR+ ? { webhookSubscriptionExternalResourceId: result.externalResourceId }+ : {}),+ },+ );++ return isDefined(affected) && affected > 0;+ }+public async markAsActive(channelType: WebhookSubscriptionChannelType,channelId: string,result: WebhookSubscriptionResult,- clientState?: string,) {await this.update(channelType, channelId, {webhookSubscriptionExternalId: result.externalSubscriptionId,webhookSubscriptionStatus: WebhookSubscriptionStatus.ACTIVE,webhookSubscriptionExpiresAt: result.expiresAt,- ...(isDefined(clientState)- ? { webhookSubscriptionClientState: clientState }- : {}),...(channelType === WebhookSubscriptionChannelType.CALENDAR? { webhookSubscriptionExternalResourceId: result.externalResourceId }: {}),@@ -65,10 +125,8 @@ export class WebhookSubscriptionStatusService {public async resetPendingSubscription(channelType: WebhookSubscriptionChannelType,channelId: string,- clientState: string,) {await this.update(channelType, channelId, {- webhookSubscriptionClientState: clientState,webhookSubscriptionExpiresAt: null,});}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-workspace-sync.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-workspace-sync.service.tsnew file mode 100644index 00000000000..1864326f11f--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-workspace-sync.service.ts@@ -0,0 +1,109 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';++import {+ WebhookSubscriptionChannelType,+ WebhookSubscriptionStatus,+} from 'twenty-shared/types';+import { In, Repository } from 'typeorm';++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 { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';+import { REVOCABLE_WEBHOOK_SUBSCRIPTION_STATUSES } from 'src/modules/connected-account/webhook-subscription-manager/constants/revocable-webhook-subscription-statuses.constant';+import { WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT } from 'src/modules/connected-account/webhook-subscription-manager/constants/webhook-subscription-job-retry-limit.constant';+import { CreateWebhookSubscriptionJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/create-webhook-subscription.job';+import { RevokeWebhookSubscriptionJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/revoke-webhook-subscription.job';+import { type WebhookSubscriptionChannelReference } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-channel-reference.type';++@Injectable()+export class WebhookSubscriptionWorkspaceSyncService {+ constructor(+ @InjectRepository(MessageChannelEntity)+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,+ @InjectRepository(CalendarChannelEntity)+ private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,+ @InjectMessageQueue(MessageQueue.webhookQueue)+ private readonly webhookQueueService: MessageQueueService,+ private readonly twentyConfigService: TwentyConfigService,+ ) {}++ async enqueueRevocations(workspaceId: string): Promise<void> {+ const channels = await this.findChannels({+ workspaceId,+ webhookSubscriptionStatuses: REVOCABLE_WEBHOOK_SUBSCRIPTION_STATUSES,+ });++ await this.enqueue(RevokeWebhookSubscriptionJob.name, channels);+ }++ async enqueueCreations(workspaceId: string): Promise<void> {+ if (+ !this.twentyConfigService.get(+ 'IS_CONNECTED_ACCOUNT_WEBHOOK_SUBSCRIPTION_ENABLED',+ )+ ) {+ return;+ }++ const channels = await this.findChannels({+ workspaceId,+ webhookSubscriptionStatuses: [WebhookSubscriptionStatus.EXPIRED],+ syncEnabledOnly: true,+ });++ await this.enqueue(CreateWebhookSubscriptionJob.name, channels);+ }++ private async findChannels({+ workspaceId,+ webhookSubscriptionStatuses,+ syncEnabledOnly = false,+ }: {+ workspaceId: string;+ webhookSubscriptionStatuses: WebhookSubscriptionStatus[];+ syncEnabledOnly?: boolean;+ }): Promise<WebhookSubscriptionChannelReference[]> {+ const where = {+ workspaceId,+ webhookSubscriptionStatus: In(webhookSubscriptionStatuses),+ ...(syncEnabledOnly ? { isSyncEnabled: true } : {}),+ };++ const messageChannels = await this.messageChannelRepository.find({+ where,+ select: { id: true },+ });+ const calendarChannels = await this.calendarChannelRepository.find({+ where,+ select: { id: true },+ });++ return [+ ...messageChannels.map((channel) => ({+ channelType: WebhookSubscriptionChannelType.MESSAGING,+ channelId: channel.id,+ workspaceId,+ })),+ ...calendarChannels.map((channel) => ({+ channelType: WebhookSubscriptionChannelType.CALENDAR,+ channelId: channel.id,+ workspaceId,+ })),+ ];+ }++ private async enqueue(+ jobName: string,+ channels: WebhookSubscriptionChannelReference[],+ ): Promise<void> {+ await this.webhookQueueService.bulkAdd(+ jobName,+ channels.map((data) => ({ data })),+ { retryLimit: WEBHOOK_SUBSCRIPTION_JOB_RETRY_LIMIT },+ );+ }+}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.tsindex 08507a593c6..89355d2dcbf 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@@ -11,6 +11,7 @@ import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decoraimport { 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';@@ -33,12 +34,22 @@ export class WebhookSyncTriggerService {private readonly cacheStorage: CacheStorageService,@InjectRepository(MessageChannelEntity)private readonly messageChannelRepository: Repository<MessageChannelEntity>,+ private readonly workspaceActivationService: WorkspaceActivationService,) {}async triggerMessagingSync(messageChannelId: string,workspaceId: string,): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceableFromCache(+ workspaceId,+ );++ if (!isWorkspaceServiceable) {+ return;+ }+const updateResult = await this.messageChannelRepository.createQueryBuilder().update()@@ -85,6 +96,15 @@ export class WebhookSyncTriggerService {calendarChannelId: string,workspaceId: string,): Promise<void> {+ const isWorkspaceServiceable =+ await this.workspaceActivationService.isWorkspaceServiceableFromCache(+ workspaceId,+ );++ if (!isWorkspaceServiceable) {+ return;+ }+const debounceCacheKey = `calendar-event-webhook-sync-debounce:${workspaceId}:${calendarChannelId}`;const hasOpenedDebounceWindow = await this.cacheStorage.setIfAbsent(diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service.tsnew file mode 100644index 00000000000..219badfe935--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service.ts@@ -0,0 +1,45 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';++import { isDefined } from 'twenty-shared/utils';+import { In, Repository } from 'typeorm';++import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { SERVICEABLE_WORKSPACE_ACTIVATION_STATUSES } from 'src/modules/connected-account/webhook-subscription-manager/constants/serviceable-workspace-activation-statuses.constant';++@Injectable()+export class WorkspaceActivationService {+ constructor(+ @InjectRepository(WorkspaceEntity)+ private readonly workspaceRepository: Repository<WorkspaceEntity>,+ private readonly coreEntityCacheService: CoreEntityCacheService,+ ) {}++ async isWorkspaceServiceable(workspaceId: string): Promise<boolean> {+ const workspace = await this.workspaceRepository.findOne({+ where: {+ id: workspaceId,+ activationStatus: In(SERVICEABLE_WORKSPACE_ACTIVATION_STATUSES),+ },+ select: { id: true },+ });++ return isDefined(workspace);+ }++ async isWorkspaceServiceableFromCache(workspaceId: string): Promise<boolean> {+ const workspace = await this.coreEntityCacheService.get(+ 'workspaceEntity',+ workspaceId,+ );++ return (+ isDefined(workspace) &&+ !isDefined(workspace.deletedAt) &&+ SERVICEABLE_WORKSPACE_ACTIVATION_STATUSES.includes(+ workspace.activationStatus,+ )+ );+ }+}diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/sync-workspace-webhook-subscriptions-job-data.type.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/sync-workspace-webhook-subscriptions-job-data.type.tsnew file mode 100644index 00000000000..1ba4a9f71e6--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/sync-workspace-webhook-subscriptions-job-data.type.ts@@ -0,0 +1,6 @@+import { type WebhookSubscriptionSyncAction } from 'src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-sync-action.type';++export type SyncWorkspaceWebhookSubscriptionsJobData = {+ workspaceId: string;+ action: WebhookSubscriptionSyncAction;+};diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-channel-reference.type.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-channel-reference.type.tsnew file mode 100644index 00000000000..b65e12f3c67--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-channel-reference.type.ts@@ -0,0 +1,7 @@+import { WebhookSubscriptionChannelType } from 'twenty-shared/types';++export type WebhookSubscriptionChannelReference = {+ channelType: WebhookSubscriptionChannelType;+ channelId: string;+ workspaceId: string;+};diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-sync-action.type.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-sync-action.type.tsnew file mode 100644index 00000000000..d346a4250b5--- /dev/null+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/types/webhook-subscription-sync-action.type.ts@@ -0,0 +1 @@+export type WebhookSubscriptionSyncAction = 'REVOKE' | 'CREATE';diff --git a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/webhook-subscription.module.ts b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/webhook-subscription.module.tsindex 6b3a8585417..3d65a064cc4 100644--- a/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/webhook-subscription.module.ts+++ b/packages/twenty-server/src/modules/connected-account/webhook-subscription-manager/webhook-subscription.module.ts@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';+import { CoreEntityCacheModule } from 'src/engine/core-entity-cache/core-entity-cache.module';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@@ -10,19 +11,25 @@ import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-chanimport { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';import { CreateWebhookSubscriptionForConnectedAccountCommand } from 'src/modules/connected-account/webhook-subscription-manager/commands/create-webhook-subscription-for-connected-account.command';import { WebhookSubscriptionRenewalCronCommand } from 'src/modules/connected-account/webhook-subscription-manager/crons/commands/webhook-subscription-renewal.cron.command';+import { WebhookSubscriptionRenewalCronJob } from 'src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job';import { CreateWebhookSubscriptionJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/create-webhook-subscription.job';import { RenewWebhookSubscriptionJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/renew-webhook-subscription.job';-import { WebhookSubscriptionRenewalCronJob } from 'src/modules/connected-account/webhook-subscription-manager/crons/jobs/webhook-subscription-renewal.cron.job';+import { RevokeWebhookSubscriptionJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/revoke-webhook-subscription.job';+import { SyncWorkspaceWebhookSubscriptionsJob } from 'src/modules/connected-account/webhook-subscription-manager/jobs/sync-workspace-webhook-subscriptions.job';import { WebhookSubscriptionChannelDeletedListener } from 'src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-channel-deleted.listener';+import { WebhookSubscriptionWorkspaceActivationListener } from 'src/modules/connected-account/webhook-subscription-manager/listeners/webhook-subscription-workspace-activation.listener';import { CalendarWebhookSubscriptionService } from 'src/modules/connected-account/webhook-subscription-manager/services/calendar-webhook-subscription.service';import { MessagingWebhookSubscriptionService } from 'src/modules/connected-account/webhook-subscription-manager/services/messaging-webhook-subscription.service';import { WebhookSubscriptionExceptionHandlerService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-exception-handler.service';import { WebhookSubscriptionStatusService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-status.service';+import { WebhookSubscriptionWorkspaceSyncService } from 'src/modules/connected-account/webhook-subscription-manager/services/webhook-subscription-workspace-sync.service';+import { WorkspaceActivationService } from 'src/modules/connected-account/webhook-subscription-manager/services/workspace-activation.service';import { WebhookSubscriptionManagerModule } from 'src/modules/connected-account/webhook-subscription-manager/webhook-subscription-manager.module';@Module({imports: [WebhookSubscriptionManagerModule,+ CoreEntityCacheModule,FeatureFlagModule,MetricsModule,WorkspaceIteratorModule,@@ -34,6 +41,9 @@ import { WebhookSubscriptionManagerModule } from 'src/modules/connected-account/]),],providers: [+ WorkspaceActivationService,+ WebhookSubscriptionWorkspaceSyncService,+ WebhookSubscriptionWorkspaceActivationListener,WebhookSubscriptionStatusService,WebhookSubscriptionExceptionHandlerService,MessagingWebhookSubscriptionService,@@ -43,9 +53,12 @@ import { WebhookSubscriptionManagerModule } from 'src/modules/connected-account/WebhookSubscriptionRenewalCronCommand,CreateWebhookSubscriptionJob,RenewWebhookSubscriptionJob,+ RevokeWebhookSubscriptionJob,+ SyncWorkspaceWebhookSubscriptionsJob,CreateWebhookSubscriptionForConnectedAccountCommand,],exports: [+ WorkspaceActivationService,MessagingWebhookSubscriptionService,CalendarWebhookSubscriptionService,WebhookSubscriptionRenewalCronCommand,