Skip to content

The open alternative to Salesforce, designed for AI.

fix(sync): only mark channels FAILED_INSUFFICIENT_PERMISSIONS on documented permanent account errors (#24035)

neo773db5c6ae73687
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/parse-google-calendar-error.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/parse-google-calendar-error.util.ts
index 224c87910df..a177edcc903 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/parse-google-calendar-error.util.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/parse-google-calendar-error.util.ts
@@ -10,78 +10,42 @@ export const parseGoogleCalendarError = (error: {
}): CalendarEventImportDriverException => {
const { code, reason, message } = error;
- switch (code) {
- case 400:
- if (reason === 'invalid_grant') {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
- if (reason === 'failedPrecondition') {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.UNKNOWN,
- );
-
- case 404:
+ if (code === 400) {
+ if (reason === 'invalid_grant') {
return new CalendarEventImportDriverException(
message,
- CalendarEventImportDriverExceptionCode.NOT_FOUND,
+ CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
);
+ }
- case 429:
+ if (reason !== 'failedPrecondition') {
return new CalendarEventImportDriverException(
message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
+ CalendarEventImportDriverExceptionCode.UNKNOWN,
);
+ }
+ }
- case 403:
- if (
- reason === 'rateLimitExceeded' ||
- reason === 'userRateLimitExceeded'
- ) {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- } else {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
-
- case 401:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- case 500:
- if (reason === 'backendError' || reason === 'internal_failure') {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- } else {
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.UNKNOWN,
- );
- }
+ if (
+ code === 403 &&
+ (reason === 'notACalendarUser' ||
+ message.includes('The user must be signed up for Google Calendar'))
+ ) {
+ return new CalendarEventImportDriverException(
+ message,
+ CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ }
- default:
- break;
+ if (code === 404) {
+ return new CalendarEventImportDriverException(
+ message,
+ CalendarEventImportDriverExceptionCode.NOT_FOUND,
+ );
}
return new CalendarEventImportDriverException(
message,
- CalendarEventImportDriverExceptionCode.UNKNOWN,
+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
);
};
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/__tests__/parse-microsoft-calendar-error.util.spec.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/__tests__/parse-microsoft-calendar-error.util.spec.ts
index 8ebecd9f195..3d2009288d3 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/__tests__/parse-microsoft-calendar-error.util.spec.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/__tests__/parse-microsoft-calendar-error.util.spec.ts
@@ -28,11 +28,53 @@ describe('parseMicrosoftCalendarError', () => {
);
});
- it('should be insufficient permissions when access is denied', () => {
+ it('should be temporary when access is denied because Graph 403s can be transient mailbox-level denials', () => {
const exception = parseMicrosoftCalendarError(
buildGraphError({ statusCode: 403, code: 'ErrorAccessDenied' }),
);
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
+ });
+
+ it('should be insufficient permissions when the mailbox is not enabled for the REST API', () => {
+ const exception = parseMicrosoftCalendarError(
+ buildGraphError({
+ statusCode: 404,
+ code: 'MailboxNotEnabledForRESTAPI',
+ message: 'Some reworded message from Microsoft.',
+ }),
+ );
+
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
+ it('should be insufficient permissions when the account has no valid licence', () => {
+ const exception = parseMicrosoftCalendarError(
+ buildGraphError({
+ statusCode: 403,
+ code: 'ErrorInvalidLicense',
+ message: 'The license of the user is invalid.',
+ }),
+ );
+
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
+ it('should be insufficient permissions on a dead-account code regardless of status code', () => {
+ const exception = parseMicrosoftCalendarError(
+ buildGraphError({
+ statusCode: 500,
+ code: 'ErrorAccountDisabled',
+ message: 'The account in question has been disabled.',
+ }),
+ );
+
expect(exception.code).toBe(
CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
);
@@ -78,11 +120,13 @@ describe('parseMicrosoftCalendarError', () => {
);
});
- it('should be unknown for an unhandled status code', () => {
+ it('should be temporary for an unhandled status code so channels are never killed on unrecognized errors', () => {
const exception = parseMicrosoftCalendarError(
buildGraphError({ statusCode: 418 }),
);
- expect(exception.code).toBe(CalendarEventImportDriverExceptionCode.UNKNOWN);
+ expect(exception.code).toBe(
+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
});
});
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util.ts
index e373fa68950..cff678c9df7 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/parse-microsoft-calendar-error.util.ts
@@ -4,65 +4,47 @@ import {
CalendarEventImportDriverException,
CalendarEventImportDriverExceptionCode,
} from 'src/modules/calendar/calendar-event-import-manager/drivers/exceptions/calendar-event-import-driver.exception';
+import { MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES } from 'src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant';
import { isDefined } from 'twenty-shared/utils';
export const parseMicrosoftCalendarError = (
error: GraphError,
): CalendarEventImportDriverException => {
- const { statusCode, message } = error;
-
- switch (statusCode) {
- case 400:
- if (!isDefined(message)) {
- return new CalendarEventImportDriverException(
- 'Microsoft Graph API returned 400 with empty error body',
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.UNKNOWN,
- );
-
- case 404:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.NOT_FOUND,
- );
-
- case 410:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.SYNC_CURSOR_ERROR,
- );
+ const { statusCode, code, message } = error;
+
+ if (
+ isDefined(code) &&
+ MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES.includes(code)
+ ) {
+ return new CalendarEventImportDriverException(
+ `Disabled, deleted, unlicensed or inaccessible Microsoft account - code:${code}`,
+ CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ }
- case 429:
- case 500:
- case 502:
- case 503:
- case 504:
- case 509:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
+ if (statusCode === 400 && isDefined(message)) {
+ return new CalendarEventImportDriverException(
+ message,
+ CalendarEventImportDriverExceptionCode.UNKNOWN,
+ );
+ }
- case 403:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
+ if (statusCode === 404) {
+ return new CalendarEventImportDriverException(
+ message,
+ CalendarEventImportDriverExceptionCode.NOT_FOUND,
+ );
+ }
- case 401:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- default:
- return new CalendarEventImportDriverException(
- message,
- CalendarEventImportDriverExceptionCode.UNKNOWN,
- );
+ if (statusCode === 410) {
+ return new CalendarEventImportDriverException(
+ message,
+ CalendarEventImportDriverExceptionCode.SYNC_CURSOR_ERROR,
+ );
}
+
+ return new CalendarEventImportDriverException(
+ `Microsoft Graph API ${code} ${statusCode} error: ${message}`,
+ CalendarEventImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
};
diff --git a/packages/twenty-server/src/modules/calendar/common/services/calendar-channel-sync-status.service.ts b/packages/twenty-server/src/modules/calendar/common/services/calendar-channel-sync-status.service.ts
index 6748f2df597..4f9d3f09280 100644
--- a/packages/twenty-server/src/modules/calendar/common/services/calendar-channel-sync-status.service.ts
+++ b/packages/twenty-server/src/modules/calendar/common/services/calendar-channel-sync-status.service.ts
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Any, In, Repository } from 'typeorm';
@@ -21,6 +21,8 @@ import { AccountsToReconnectService } from 'src/modules/connected-account/servic
import { AccountsToReconnectKeys } from 'src/modules/connected-account/types/accounts-to-reconnect-key-value.type';
@Injectable()
export class CalendarChannelSyncStatusService {
+ private readonly logger = new Logger(CalendarChannelSyncStatusService.name);
+
constructor(
private readonly globalWorkspaceOrmManager: GlobalWorkspaceOrmManager,
@InjectCacheStorage(CacheStorageNamespace.ModuleCalendar)
@@ -253,6 +255,10 @@ export class CalendarChannelSyncStatusService {
return;
}
+ this.logger.warn(
+ `Marking calendar channels [${calendarChannelIds.join(', ')}] as ${CalendarChannelSyncStatus.FAILED_UNKNOWN} in workspace ${workspaceId}`,
+ );
+
for (const calendarChannelId of calendarChannelIds) {
await this.cacheStorage.del(
`calendar-events-to-import:${workspaceId}:${calendarChannelId}`,
@@ -289,6 +295,10 @@ export class CalendarChannelSyncStatusService {
return;
}
+ this.logger.warn(
+ `Marking calendar channels [${calendarChannelIds.join(', ')}] as ${CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS} in workspace ${workspaceId}`,
+ );
+
for (const calendarChannelId of calendarChannelIds) {
await this.cacheStorage.del(
`calendar-events-to-import:${workspaceId}:${calendarChannelId}`,
diff --git a/packages/twenty-server/src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant.ts b/packages/twenty-server/src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant.ts
new file mode 100644
index 00000000000..4ee84b85953
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant.ts
@@ -0,0 +1,11 @@
+// dead/unlicensed/on-premise mailbox/calendar (yes MS returns same codes for calendar don't ask why)
+// @see https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/responsecode
+export const MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES = [
+ 'MailboxNotEnabledForRESTAPI',
+ 'MailboxNotSupportedForRESTAPI',
+ 'RESTAPINotEnabledForComponentSharedMailbox',
+ 'ErrorInvalidLicense',
+ 'ErrorNonExistentMailbox',
+ 'ErrorAccountDisabled',
+ 'ErrorOrganizationAccessBlocked',
+];
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 753950110b7..a488da43610 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
@@ -1,4 +1,4 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Any, In, Repository } from 'typeorm';
@@ -26,6 +26,8 @@ import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-membe
@Injectable()
export class MessageChannelSyncStatusService {
+ private readonly logger = new Logger(MessageChannelSyncStatusService.name);
+
constructor(
@InjectCacheStorage(CacheStorageNamespace.ModuleMessaging)
private readonly cacheStorage: CacheStorageService,
@@ -312,6 +314,10 @@ export class MessageChannelSyncStatusService {
return;
}
+ this.logger.warn(
+ `Marking message channels [${messageChannelIds.join(', ')}] as ${syncStatus} in workspace ${workspaceId}`,
+ );
+
const authContext = buildSystemAuthContext(workspaceId);
await this.globalWorkspaceOrmManager.executeInWorkspaceContext(
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-message-list-fetch-error.spec.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-message-list-fetch-error.spec.ts
index 2efd40b937c..a12eabb0b26 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-message-list-fetch-error.spec.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-message-list-fetch-error.spec.ts
@@ -35,13 +35,13 @@ describe('parseGmailApiError', () => {
);
});
- it('should handle 401 Invalid Credentials', () => {
+ it('should handle 401 Invalid Credentials as temporary so the next attempt can refresh the token', () => {
const error = getGmailApiError({ code: 401 });
const exception = parseGmailApiError(error);
expect(exception).toBeInstanceOf(MessageImportDriverException);
expect(exception.code).toBe(
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
});
@@ -75,13 +75,13 @@ describe('parseGmailApiError', () => {
);
});
- it('should handle 403 Domain Policy Error', () => {
+ it('should handle 403 Domain Policy Error as temporary', () => {
const error = getGmailApiError({ code: 403, reason: 'domainPolicy' });
const exception = parseGmailApiError(error);
expect(exception).toBeInstanceOf(MessageImportDriverException);
expect(exception.code).toBe(
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
});
@@ -95,12 +95,14 @@ describe('parseGmailApiError', () => {
);
});
- it('should handle 410 Gone', () => {
+ it('should handle 410 Gone as temporary', () => {
const error = getGmailApiError({ code: 410 });
const exception = parseGmailApiError(error);
expect(exception).toBeInstanceOf(MessageImportDriverException);
- expect(exception.code).toBe(MessageImportDriverExceptionCode.UNKNOWN);
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
});
it('should handle 429 Too Many Requests', () => {
@@ -166,13 +168,13 @@ describe('parseGmailApiError', () => {
);
});
- it('should handle 401 Invalid Credentials with errorCodeAsString', () => {
+ it('should handle 401 Invalid Credentials with errorCodeAsString as temporary', () => {
const error = getGmailApiError({ code: 401 });
const exception = parseGmailApiError(error);
expect(exception).toBeInstanceOf(MessageImportDriverException);
expect(exception.code).toBe(
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
});
@@ -206,13 +208,13 @@ describe('parseGmailApiError', () => {
);
});
- it('should handle 403 Domain Policy Error with errorCodeAsString', () => {
+ it('should handle 403 Domain Policy Error with errorCodeAsString as temporary', () => {
const error = getGmailApiError({ code: 403, reason: 'domainPolicy' });
const exception = parseGmailApiError(error);
expect(exception).toBeInstanceOf(MessageImportDriverException);
expect(exception.code).toBe(
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
});
@@ -269,4 +271,20 @@ describe('parseGmailApiError', () => {
-3,
);
});
+
+ it('should leave retryAfter undefined on non-rate-limit errors even when the message contains a retry-after timestamp', () => {
+ const fifteenMinutesFromNow = new Date(Date.now() + 15 * 60 * 1000);
+ const error = getGmailApiError({
+ code: 500,
+ reason: 'backendError',
+ message: `Backend Error. Retry after ${fifteenMinutesFromNow.toISOString()}`,
+ });
+
+ const exception = parseGmailApiError(error);
+
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
+ expect(exception.throttleRetryAfter).toBeUndefined();
+ });
});
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-messages-import-error.spec.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-messages-import-error.spec.ts
index acdfd0b68c3..da933543104 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-messages-import-error.spec.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/__tests__/parse-gmail-messages-import-error.spec.ts
@@ -41,12 +41,12 @@ describe('GmailMessagesImportErrorHandler', () => {
);
});
- it('should handle 401 Invalid Credentials', () => {
+ it('should handle 401 Invalid Credentials as temporary so the next attempt can refresh the token', () => {
const error = getGmailApiError({ code: 401 });
expect(() => handler.handleError(error, messageExternalId)).toThrow(
expect.objectContaining({
- code: MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ code: MessageImportDriverExceptionCode.TEMPORARY_ERROR,
}),
);
});
@@ -81,12 +81,12 @@ describe('GmailMessagesImportErrorHandler', () => {
);
});
- it('should handle 403 Domain Policy Error', () => {
+ it('should handle 403 Domain Policy Error as temporary', () => {
const error = getGmailApiError({ code: 403, reason: 'domainPolicy' });
expect(() => handler.handleError(error, messageExternalId)).toThrow(
expect.objectContaining({
- code: MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ code: MessageImportDriverExceptionCode.TEMPORARY_ERROR,
}),
);
});
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/parse-gmail-api-error.util.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/parse-gmail-api-error.util.ts
index c2192dbefe3..b3b9f6da34d 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/parse-gmail-api-error.util.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/gmail/utils/parse-gmail-api-error.util.ts
@@ -21,125 +21,51 @@ export const parseGmailApiError = (
'Unknown error',
};
- switch (gmailApiError.code) {
- case 400:
- if (gmailApiError.reason === 'invalid_grant') {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
- if (gmailApiError.reason === 'failedPrecondition') {
- if (gmailApiError.message.includes('Mail service not enabled')) {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
-
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.UNKNOWN,
- );
-
- case 404:
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.SYNC_CURSOR_ERROR,
- );
-
- case 429:
+ if (gmailApiError.code === 400) {
+ if (gmailApiError.reason === 'invalid_grant') {
return new MessageImportDriverException(
gmailApiError.message,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- {
- throttleRetryAfter: parseGmailErrorRetryAfter(gmailApiError.message),
- },
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
);
+ }
- case 403:
- if (
- gmailApiError.reason === 'rateLimitExceeded' ||
- gmailApiError.reason === 'userRateLimitExceeded' ||
- gmailApiError.reason === 'dailyLimitExceeded'
- ) {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- {
- throttleRetryAfter: parseGmailErrorRetryAfter(
- gmailApiError.message,
- ),
- },
- );
- }
- if (gmailApiError.reason === 'domainPolicy') {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
-
- if (gmailApiError.reason === 'insufficientPermissions') {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- );
- }
-
- break;
-
- case 401:
+ if (
+ gmailApiError.reason === 'failedPrecondition' &&
+ gmailApiError.message.includes('Mail service not enabled')
+ ) {
return new MessageImportDriverException(
gmailApiError.message,
MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
);
+ }
- case 503:
+ if (gmailApiError.reason !== 'failedPrecondition') {
return new MessageImportDriverException(
gmailApiError.message,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ MessageImportDriverExceptionCode.UNKNOWN,
);
+ }
+ }
- case 500:
- case 502:
- case 504:
- if (gmailApiError.reason === 'backendError') {
- return new MessageImportDriverException(
- gmailApiError.message,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- if (
- gmailApiError.message.includes(`Authentication backend unavailable`)
- ) {
- return new MessageImportDriverException(
- `${gmailApiError.code} - ${gmailApiError.message}`,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
-
- if (gmailApiError.reason === 'internal_failure') {
- return new MessageImportDriverException(
- `${gmailApiError.code} - ${gmailApiError.message}`,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- );
- }
- break;
+ if (gmailApiError.code === 404) {
+ return new MessageImportDriverException(
+ gmailApiError.message,
+ MessageImportDriverExceptionCode.SYNC_CURSOR_ERROR,
+ );
+ }
- default:
- break;
+ if (gmailApiError.code === 429 || gmailApiError.code === 403) {
+ return new MessageImportDriverException(
+ gmailApiError.message,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ {
+ throttleRetryAfter: parseGmailErrorRetryAfter(gmailApiError.message),
+ },
+ );
}
return new MessageImportDriverException(
gmailApiError.message,
- MessageImportDriverExceptionCode.UNKNOWN,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
};
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/__tests__/parse-microsoft-messages-import.util.spec.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/__tests__/parse-microsoft-messages-import.util.spec.ts
index 2c334d02435..7a482e2f9d1 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/__tests__/parse-microsoft-messages-import.util.spec.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/__tests__/parse-microsoft-messages-import.util.spec.ts
@@ -27,15 +27,15 @@ describe('parseMicrosoftMessagesImportError', () => {
);
});
- it('should be insufficient permissions when access is denied', () => {
+ it('should be temporary when access is denied because Graph 403s can be transient mailbox-level denials', () => {
const exception = parseMicrosoftMessagesImportError({
statusCode: 403,
code: 'ErrorAccessDenied',
- message: 'Access is denied.',
+ message: 'Access is denied. Check credentials and try again.',
});
expect(exception.code).toBe(
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
);
expect(exception.message).toContain('ErrorAccessDenied');
});
@@ -65,6 +65,54 @@ describe('parseMicrosoftMessagesImportError', () => {
);
});
+ it('should be insufficient permissions when the account has no valid licence', () => {
+ const exception = parseMicrosoftMessagesImportError({
+ statusCode: 403,
+ code: 'ErrorInvalidLicense',
+ message: 'The license of the user is invalid.',
+ });
+
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
+ it('should be insufficient permissions when a shared mailbox is not enabled for the REST API', () => {
+ const exception = parseMicrosoftMessagesImportError({
+ statusCode: 404,
+ code: 'RESTAPINotEnabledForComponentSharedMailbox',
+ message: 'REST API is not yet supported for this mailbox.',
+ });
+
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
+ it('should be insufficient permissions on a dead-account code regardless of status code', () => {
+ const exception = parseMicrosoftMessagesImportError({
+ statusCode: 500,
+ code: 'ErrorNonExistentMailbox',
+ message: 'The SMTP address has no mailbox associated with it.',
+ });
+
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
+ it('should be insufficient permissions when the tenant is marked for removal', () => {
+ const exception = parseMicrosoftMessagesImportError({
+ statusCode: 403,
+ code: 'ErrorOrganizationAccessBlocked',
+ message: 'The tenant is marked for removal.',
+ });
+
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ );
+ });
+
it('should be not found for a 404 that is not a mailbox error', () => {
const exception = parseMicrosoftMessagesImportError({
statusCode: 404,
@@ -107,12 +155,14 @@ describe('parseMicrosoftMessagesImportError', () => {
);
});
- it('should be unknown for an unhandled status code', () => {
+ it('should be temporary for an unhandled status code so channels are never killed on unrecognized errors', () => {
const exception = parseMicrosoftMessagesImportError({
statusCode: 418,
message: 'I am a teapot.',
});
- expect(exception.code).toBe(MessageImportDriverExceptionCode.UNKNOWN);
+ expect(exception.code).toBe(
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ );
});
});
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/parse-microsoft-messages-import.util.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/parse-microsoft-messages-import.util.ts
index 3587c6f792b..d33e47c3e41 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/parse-microsoft-messages-import.util.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/microsoft/utils/parse-microsoft-messages-import.util.ts
@@ -1,12 +1,10 @@
+import { MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES } from 'src/modules/connected-account/constants/microsoft-permanent-account-error-codes.constant';
import {
MessageImportDriverException,
MessageImportDriverExceptionCode,
} from 'src/modules/messaging/message-import-manager/drivers/exceptions/message-import-driver.exception';
import { isDefined } from 'twenty-shared/utils';
-const MICROSOFT_MAILBOX_NOT_ENABLED_FOR_REST_API_ERROR_CODE =
- 'MailboxNotEnabledForRESTAPI';
-
export const parseMicrosoftMessagesImportError = (
error: {
statusCode: number;
@@ -15,54 +13,33 @@ export const parseMicrosoftMessagesImportError = (
},
options?: { cause?: Error },
): MessageImportDriverException => {
- if (error.statusCode === 400) {
- if (!isDefined(error.message)) {
- return new MessageImportDriverException(
- `Microsoft Graph API returned 400 with empty error body`,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- { cause: options?.cause },
- );
- }
-
+ if (
+ isDefined(error.code) &&
+ MICROSOFT_PERMANENT_ACCOUNT_ERROR_CODES.includes(error.code)
+ ) {
return new MessageImportDriverException(
- `Invalid request to Microsoft Graph API: ${error.message}`,
- MessageImportDriverExceptionCode.UNKNOWN,
+ `Disabled, deleted, unlicensed or inaccessible Microsoft account - code:${error.code}`,
+ MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
{ cause: options?.cause },
);
}
- if (error.statusCode === 401) {
+ if (error.statusCode === 400 && isDefined(error.message)) {
return new MessageImportDriverException(
- `Unauthorized access to Microsoft Graph API - code:${error.code} ${error.message}`,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
+ `Invalid request to Microsoft Graph API: ${error.message}`,
+ MessageImportDriverExceptionCode.UNKNOWN,
{ cause: options?.cause },
);
}
- if (error.statusCode === 403) {
+ if (error.statusCode === 404) {
return new MessageImportDriverException(
- `Forbidden access to Microsoft Graph API - code:${error.code} ${error.message}`,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
+ `Not found - code:${error.code}`,
+ MessageImportDriverExceptionCode.NOT_FOUND,
{ cause: options?.cause },
);
}
- if (error.statusCode === 404) {
- if (error.code === MICROSOFT_MAILBOX_NOT_ENABLED_FOR_REST_API_ERROR_CODE) {
- return new MessageImportDriverException(
- `Disabled, deleted, inactive or no licence Microsoft account - code:${error.code}`,
- MessageImportDriverExceptionCode.INSUFFICIENT_PERMISSIONS,
- { cause: options?.cause },
- );
- } else {
- return new MessageImportDriverException(
- `Not found - code:${error.code}`,
- MessageImportDriverExceptionCode.NOT_FOUND,
- { cause: options?.cause },
- );
- }
- }
-
if (error.statusCode === 410) {
return new MessageImportDriverException(
`Sync cursor error: ${error.message}`,
@@ -71,24 +48,9 @@ export const parseMicrosoftMessagesImportError = (
);
}
- if (
- error.statusCode === 429 ||
- error.statusCode === 500 ||
- error.statusCode === 502 ||
- error.statusCode === 503 ||
- error.statusCode === 504 ||
- error.statusCode === 509
- ) {
- return new MessageImportDriverException(
- `Microsoft Graph API ${error.code} ${error.statusCode} error: ${error.message}`,
- MessageImportDriverExceptionCode.TEMPORARY_ERROR,
- { cause: options?.cause },
- );
- }
-
return new MessageImportDriverException(
- `Microsoft Graph API unknown error: ${error} with status code ${error.statusCode}`,
- MessageImportDriverExceptionCode.UNKNOWN,
+ `Microsoft Graph API ${error.code} ${error.statusCode} error: ${error.message}`,
+ MessageImportDriverExceptionCode.TEMPORARY_ERROR,
{ cause: options?.cause },
);
};
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-generated/companies-merge-many.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-generated/companies-merge-many.integration-spec.ts
index 89e00a1d5bd..4c0ae44e48f 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-generated/companies-merge-many.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-generated/companies-merge-many.integration-spec.ts
@@ -5,6 +5,7 @@ import { findOneOperationFactory } from 'test/integration/graphql/utils/find-one
import { makeGraphqlAPIRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import { mergeManyOperationFactory } from 'test/integration/graphql/utils/merge-many-operation-factory.util';
import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
+import { waitForTimelineActivities } from 'test/integration/utils/wait-for-timeline-activities.util';
describe('companies merge resolvers (integration)', () => {
let createdCompanyIds: string[] = [];
@@ -71,6 +72,11 @@ describe('companies merge resolvers (integration)', () => {
createdCompanyIds.push(company1Id, company2Id);
+ await waitForTimelineActivities('targetCompanyId', [
+ company1Id,
+ company2Id,
+ ]);
+
const mergeOperation = mergeManyOperationFactory({
objectMetadataPluralName: 'companies',
gqlFields: COMPANY_GQL_FIELDS,
@@ -161,6 +167,11 @@ describe('companies merge resolvers (integration)', () => {
createdCompanyIds.push(company1Id, company2Id);
+ await waitForTimelineActivities('targetCompanyId', [
+ company1Id,
+ company2Id,
+ ]);
+
const mergeOperation = mergeManyOperationFactory({
objectMetadataPluralName: 'companies',
gqlFields: COMPANY_GQL_FIELDS,
@@ -233,6 +244,11 @@ describe('companies merge resolvers (integration)', () => {
createdCompanyIds.push(company1Id, company2Id);
+ await waitForTimelineActivities('targetCompanyId', [
+ company1Id,
+ company2Id,
+ ]);
+
const mergeWithPriority1 = mergeManyOperationFactory({
objectMetadataPluralName: 'companies',
gqlFields: COMPANY_GQL_FIELDS,
@@ -315,6 +331,12 @@ describe('companies merge resolvers (integration)', () => {
expect(relatedPerson.company.id).toBe(duplicateCompanyId);
+ await waitForTimelineActivities('targetCompanyId', [
+ survivorCompanyId,
+ duplicateCompanyId,
+ ]);
+ await waitForTimelineActivities('targetPersonId', [relatedPerson.id]);
+
const mergeOperation = mergeManyOperationFactory({
objectMetadataPluralName: 'companies',
gqlFields: COMPANY_GQL_FIELDS,
@@ -421,6 +443,13 @@ describe('companies merge resolvers (integration)', () => {
createdPersonIds.push(...createdPeopleIds);
+ await waitForTimelineActivities('targetCompanyId', [
+ survivorCompanyId,
+ duplicateOneId,
+ duplicateTwoId,
+ ]);
+ await waitForTimelineActivities('targetPersonId', createdPeopleIds);
+
const mergeOperation = mergeManyOperationFactory({
objectMetadataPluralName: 'companies',
gqlFields: COMPANY_GQL_FIELDS,
diff --git a/packages/twenty-server/test/integration/utils/wait-for-timeline-activities.util.ts b/packages/twenty-server/test/integration/utils/wait-for-timeline-activities.util.ts
new file mode 100644
index 00000000000..f17f642995b
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/wait-for-timeline-activities.util.ts
@@ -0,0 +1,19 @@
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+
+const TEST_SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';
+
+// Timeline activities are inserted by listeners after the mutation resolves;
+// mutating a record while its activities are still in flight races those inserts.
+export const waitForTimelineActivities = async (
+ targetColumnName: 'targetCompanyId' | 'targetPersonId',
+ recordIds: string[],
+) => {
+ await expectEventually(async () => {
+ const [{ count }] = await global.testDataSource.query(
+ `SELECT count(DISTINCT "${targetColumnName}")::int AS count FROM "${TEST_SCHEMA_NAME}"."timelineActivity" WHERE "${targetColumnName}" = ANY($1)`,
+ [recordIds],
+ );
+
+ expect(count).toBe(recordIds.length);
+ });
+};