Skip to content

The open alternative to Salesforce, designed for AI.

8.3 KB
Raw Blame
import { Injectable, Logger } from '@nestjs/common';

import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import {
  ConnectedAccountRefreshAccessTokenException,
  ConnectedAccountRefreshAccessTokenExceptionCode,
} from 'src/engine/metadata-modules/connected-account/exceptions/connected-account-refresh-tokens.exception';
import {
  type TwentyOrmException,
  TwentyOrmExceptionCode,
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { CALENDAR_THROTTLE_MAX_ATTEMPTS } from 'src/modules/calendar/calendar-event-import-manager/constants/calendar-throttle-max-attempts';
import {
  type CalendarEventImportDriverException,
  CalendarEventImportDriverExceptionCode,
} from 'src/modules/calendar/calendar-event-import-manager/drivers/exceptions/calendar-event-import-driver.exception';
import {
  CalendarEventImportException,
  CalendarEventImportExceptionCode,
} from 'src/modules/calendar/calendar-event-import-manager/exceptions/calendar-event-import.exception';
import { CalendarChannelSyncStatusService } from 'src/modules/calendar/common/services/calendar-channel-sync-status.service';
export enum CalendarEventImportSyncStep {
  CALENDAR_EVENT_LIST_FETCH = 'CALENDAR_EVENT_LIST_FETCH',
  CALENDAR_EVENTS_IMPORT = 'CALENDAR_EVENTS_IMPORT',
}

@Injectable()
export class CalendarEventImportErrorHandlerService {
  private readonly logger = new Logger(
    CalendarEventImportErrorHandlerService.name,
  );
  constructor(
    @InjectWorkspaceScopedRepository(CalendarChannelEntity)
    private readonly calendarChannelRepository: WorkspaceScopedRepository<CalendarChannelEntity>,
    private readonly calendarChannelSyncStatusService: CalendarChannelSyncStatusService,
    private readonly exceptionHandlerService: ExceptionHandlerService,
  ) {}

  public async handleDriverException(
    exception:
      | CalendarEventImportDriverException
      | TwentyOrmException
      | ConnectedAccountRefreshAccessTokenException,
    syncStep: CalendarEventImportSyncStep,
    calendarChannel: Pick<CalendarChannelEntity, 'id' | 'throttleFailureCount'>,
    workspaceId: string,
  ): Promise<void> {
    switch (exception.code) {
      case CalendarEventImportDriverExceptionCode.NOT_FOUND:
        await this.handleNotFoundException(
          syncStep,
          calendarChannel,
          workspaceId,
        );
        break;
      case TwentyOrmExceptionCode.QUERY_READ_TIMEOUT:
      case TwentyOrmExceptionCode.TRANSIENT_DATABASE_ERROR:
      case CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR:
      case ConnectedAccountRefreshAccessTokenExceptionCode.TEMPORARY_NETWORK_ERROR:
        await this.handleTemporaryException(
          syncStep,
          calendarChannel,
          workspaceId,
        );
        break;
      case CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS:
      case ConnectedAccountRefreshAccessTokenExceptionCode.REFRESH_TOKEN_NOT_FOUND:
      case ConnectedAccountRefreshAccessTokenExceptionCode.INVALID_REFRESH_TOKEN:
        await this.handleInsufficientPermissionsException(
          calendarChannel,
          workspaceId,
        );
        break;
      case CalendarEventImportDriverExceptionCode.SYNC_CURSOR_ERROR:
        await this.handleSyncCursorErrorException(calendarChannel, workspaceId);
        break;
      case CalendarEventImportDriverExceptionCode.CHANNEL_MISCONFIGURED:
      case CalendarEventImportDriverExceptionCode.UNKNOWN:
      case CalendarEventImportDriverExceptionCode.UNKNOWN_NETWORK_ERROR:
      case ConnectedAccountRefreshAccessTokenExceptionCode.ACCESS_TOKEN_NOT_FOUND:
      case ConnectedAccountRefreshAccessTokenExceptionCode.PROVIDER_NOT_SUPPORTED:
      default:
        await this.handleUnknownException(
          exception,
          calendarChannel,
          workspaceId,
        );
        break;
    }
  }

  private async handleSyncCursorErrorException(
    calendarChannel: Pick<CalendarChannelEntity, 'id'>,
    workspaceId: string,
  ): Promise<void> {
    this.logger.debug(
      `CalendarChannelId: ${calendarChannel.id} - Sync cursor error, resetting and rescheduling`,
    );

    await this.calendarChannelSyncStatusService.resetAndMarkAsCalendarEventListFetchPending(
      [calendarChannel.id],
      workspaceId,
    );
  }

  private async handleTemporaryException(
    syncStep: CalendarEventImportSyncStep,
    calendarChannel: Pick<CalendarChannelEntity, 'id' | 'throttleFailureCount'>,
    workspaceId: string,
  ): Promise<void> {
    if (
      calendarChannel.throttleFailureCount >= CALENDAR_THROTTLE_MAX_ATTEMPTS
    ) {
      await this.calendarChannelSyncStatusService.markAsFailedUnknownAndFlushCalendarEventsToImport(
        [calendarChannel.id],
        workspaceId,
      );

      const calendarEventImportException = new CalendarEventImportException(
        `Temporary error occurred ${CALENDAR_THROTTLE_MAX_ATTEMPTS} times while importing calendar events for calendar channel ${calendarChannel.id} in workspace ${workspaceId} with throttleFailureCount ${calendarChannel.throttleFailureCount}`,
        CalendarEventImportExceptionCode.UNKNOWN,
      );

      this.exceptionHandlerService.captureExceptions(
        [calendarEventImportException],
        {
          additionalData: {
            calendarChannelId: calendarChannel.id,
            syncStep,
            throttleFailureCount: calendarChannel.throttleFailureCount,
          },
          workspace: {
            id: workspaceId,
          },
        },
      );

      throw calendarEventImportException;
    }

    await this.calendarChannelRepository.increment(
      workspaceId,
      { id: calendarChannel.id },
      'throttleFailureCount',
      1,
    );

    switch (syncStep) {
      case CalendarEventImportSyncStep.CALENDAR_EVENT_LIST_FETCH:
        await this.calendarChannelSyncStatusService.markAsCalendarEventListFetchPending(
          [calendarChannel.id],
          workspaceId,
          true,
        );
        break;

      case CalendarEventImportSyncStep.CALENDAR_EVENTS_IMPORT:
        await this.calendarChannelSyncStatusService.markAsCalendarEventsImportPending(
          [calendarChannel.id],
          workspaceId,
          true,
        );
        break;

      default:
        break;
    }
  }

  private async handleInsufficientPermissionsException(
    calendarChannel: Pick<CalendarChannelEntity, 'id'>,
    workspaceId: string,
  ): Promise<void> {
    await this.calendarChannelSyncStatusService.markAsFailedInsufficientPermissionsAndFlushCalendarEventsToImport(
      [calendarChannel.id],
      workspaceId,
    );
  }

  private async handleUnknownException(
    exception: { message: string },
    calendarChannel: Pick<CalendarChannelEntity, 'id'>,
    workspaceId: string,
  ): Promise<void> {
    await this.calendarChannelSyncStatusService.markAsFailedUnknownAndFlushCalendarEventsToImport(
      [calendarChannel.id],
      workspaceId,
    );

    const calendarEventImportException = new CalendarEventImportException(
      `Unknown error importing calendar events for calendar channel ${calendarChannel.id} in workspace ${workspaceId}: ${exception.message}`,
      CalendarEventImportExceptionCode.UNKNOWN,
    );

    this.logger.error(exception);
    this.exceptionHandlerService.captureExceptions(
      [calendarEventImportException],
      {
        additionalData: {
          calendarChannelId: calendarChannel.id,
          exceptionMessage: exception.message,
        },
        workspace: {
          id: workspaceId,
        },
      },
    );

    throw calendarEventImportException;
  }

  private async handleNotFoundException(
    syncStep: CalendarEventImportSyncStep,
    calendarChannel: Pick<CalendarChannelEntity, 'id'>,
    workspaceId: string,
  ): Promise<void> {
    if (syncStep === CalendarEventImportSyncStep.CALENDAR_EVENT_LIST_FETCH) {
      return;
    }

    await this.calendarChannelSyncStatusService.resetAndMarkAsCalendarEventListFetchPending(
      [calendarChannel.id],
      workspaceId,
    );
  }
}