|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { createWorkflowRecord } from '@sim/testing/factories/permission.factory' |
| 3 | +import { jsonResponse } from '@sim/testing/helpers/http' |
| 4 | +import { idempotencyServiceMock } from '@sim/testing/mocks/idempotency-service.mock' |
| 5 | +import { |
| 6 | + webhooksPollingUtilsMock, |
| 7 | + webhooksPollingUtilsMockFns, |
| 8 | +} from '@sim/testing/mocks/webhooks-polling-utils.mock' |
| 9 | +import { |
| 10 | + webhooksProcessorMock, |
| 11 | + webhooksProcessorMockFns, |
| 12 | +} from '@sim/testing/mocks/webhooks-processor.mock' |
| 13 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 14 | + |
| 15 | +vi.mock('@/lib/core/idempotency/service', () => idempotencyServiceMock) |
| 16 | + |
| 17 | +vi.mock('@/lib/webhooks/processor', () => webhooksProcessorMock) |
| 18 | + |
| 19 | +vi.mock('@/lib/webhooks/polling/utils', () => webhooksPollingUtilsMock) |
| 20 | + |
| 21 | +import { gmailPollingHandler } from '@/lib/webhooks/polling/gmail' |
| 22 | +import type { PollWebhookContext, WebhookRecord } from '@/lib/webhooks/polling/types' |
| 23 | + |
| 24 | +const { mockUpdateWebhookProviderConfig: mockUpdateConfig, mockResolveOAuthCredential } = |
| 25 | + webhooksPollingUtilsMockFns |
| 26 | +const mockProcessEvent = webhooksProcessorMockFns.mockProcessPolledWebhookEvent |
| 27 | + |
| 28 | +const EXPIRED_HISTORY_ID = '30000' |
| 29 | + |
| 30 | +interface MailboxState { |
| 31 | + profileHistoryId: string |
| 32 | + inboxMessages: { id: string; historyId: string }[] |
| 33 | +} |
| 34 | + |
| 35 | +function context(providerConfig: Record<string, unknown>): PollWebhookContext { |
| 36 | + const webhookData: WebhookRecord = { |
| 37 | + id: 'gmail-webhook', |
| 38 | + workflowId: 'gmail-listener', |
| 39 | + deploymentVersionId: null, |
| 40 | + registrationStatus: null, |
| 41 | + registrationGeneration: null, |
| 42 | + configFingerprint: null, |
| 43 | + preparedAt: null, |
| 44 | + blockId: null, |
| 45 | + path: 'gmail-listener', |
| 46 | + routingKey: null, |
| 47 | + provider: 'gmail', |
| 48 | + providerConfig: { |
| 49 | + labelIds: ['INBOX'], |
| 50 | + labelFilterBehavior: 'INCLUDE', |
| 51 | + markAsRead: false, |
| 52 | + lastCheckedTimestamp: new Date(Date.now() - 60_000).toISOString(), |
| 53 | + ...providerConfig, |
| 54 | + }, |
| 55 | + isActive: true, |
| 56 | + failedCount: 0, |
| 57 | + lastFailedAt: null, |
| 58 | + archivedAt: null, |
| 59 | + createdAt: new Date('2026-10-01T00:00:00.000Z'), |
| 60 | + updatedAt: new Date('2026-10-01T00:00:00.000Z'), |
| 61 | + } |
| 62 | + return { |
| 63 | + webhookData, |
| 64 | + workflowData: createWorkflowRecord({ |
| 65 | + id: 'gmail-listener', |
| 66 | + }) as PollWebhookContext['workflowData'], |
| 67 | + requestId: 'gmail-request', |
| 68 | + logger: createLogger('GmailTest'), |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * A Gmail mailbox whose history records older than the stored cursor have aged out: |
| 74 | + * `history.list` answers 404 for that cursor, as the Gmail sync guide documents. |
| 75 | + */ |
| 76 | +function mailboxWithExpiredHistory(state: MailboxState) { |
| 77 | + const fetchMock = vi.fn(async (input: string | URL | Request) => { |
| 78 | + const url = new URL(typeof input === 'string' ? input : input.toString()) |
| 79 | + if (url.pathname.endsWith('/users/me/history')) { |
| 80 | + return jsonResponse( |
| 81 | + { error: { code: 404, message: 'Requested entity was not found.', status: 'NOT_FOUND' } }, |
| 82 | + 404 |
| 83 | + ) |
| 84 | + } |
| 85 | + if (url.pathname.endsWith('/users/me/profile')) { |
| 86 | + return jsonResponse({ historyId: state.profileHistoryId }) |
| 87 | + } |
| 88 | + if (url.pathname.endsWith('/users/me/messages')) { |
| 89 | + return jsonResponse( |
| 90 | + state.inboxMessages.length |
| 91 | + ? { messages: state.inboxMessages.map(({ id }) => ({ id, threadId: id })) } |
| 92 | + : { resultSizeEstimate: 0 } |
| 93 | + ) |
| 94 | + } |
| 95 | + const message = state.inboxMessages.find((m) => url.pathname.endsWith(`/messages/${m.id}`)) |
| 96 | + if (message) { |
| 97 | + return jsonResponse({ |
| 98 | + id: message.id, |
| 99 | + threadId: message.id, |
| 100 | + historyId: message.historyId, |
| 101 | + labelIds: ['INBOX'], |
| 102 | + payload: { headers: [{ name: 'Subject', value: 'hello' }] }, |
| 103 | + }) |
| 104 | + } |
| 105 | + return new Response('unexpected request', { status: 500 }) |
| 106 | + }) |
| 107 | + vi.stubGlobal('fetch', fetchMock) |
| 108 | +} |
| 109 | + |
| 110 | +function persistedHistoryIds() { |
| 111 | + return mockUpdateConfig.mock.calls.map( |
| 112 | + ([, updates]) => (updates as { historyId?: string }).historyId |
| 113 | + ) |
| 114 | +} |
| 115 | + |
| 116 | +describe('gmailPollingHandler expired history cursor', () => { |
| 117 | + beforeEach(() => { |
| 118 | + vi.clearAllMocks() |
| 119 | + mockResolveOAuthCredential.mockResolvedValue('access-token') |
| 120 | + mockProcessEvent.mockResolvedValue({ success: true }) |
| 121 | + }) |
| 122 | + |
| 123 | + it('drops a cursor the quiet mailbox cannot replace instead of re-saving the expired one', async () => { |
| 124 | + mailboxWithExpiredHistory({ |
| 125 | + profileHistoryId: EXPIRED_HISTORY_ID, |
| 126 | + inboxMessages: [], |
| 127 | + }) |
| 128 | + |
| 129 | + await expect( |
| 130 | + gmailPollingHandler.pollWebhook(context({ historyId: EXPIRED_HISTORY_ID })) |
| 131 | + ).resolves.toBe('success') |
| 132 | + |
| 133 | + expect(mockUpdateConfig).toHaveBeenCalledTimes(1) |
| 134 | + const [, updates] = mockUpdateConfig.mock.calls[0] |
| 135 | + expect(updates).toHaveProperty('historyId', undefined) |
| 136 | + }) |
| 137 | + |
| 138 | + it('resumes from the newest searched message when the full sync finds mail', async () => { |
| 139 | + mailboxWithExpiredHistory({ |
| 140 | + profileHistoryId: '40100', |
| 141 | + inboxMessages: [{ id: 'm-new', historyId: '40050' }], |
| 142 | + }) |
| 143 | + |
| 144 | + await expect( |
| 145 | + gmailPollingHandler.pollWebhook(context({ historyId: EXPIRED_HISTORY_ID })) |
| 146 | + ).resolves.toBe('success') |
| 147 | + |
| 148 | + expect(mockProcessEvent).toHaveBeenCalledTimes(1) |
| 149 | + expect(persistedHistoryIds()).toEqual(['40050']) |
| 150 | + }) |
| 151 | + |
| 152 | + it('resumes from the mailbox cursor when activity moved it past the expired one', async () => { |
| 153 | + mailboxWithExpiredHistory({ profileHistoryId: '40100', inboxMessages: [] }) |
| 154 | + |
| 155 | + await expect( |
| 156 | + gmailPollingHandler.pollWebhook(context({ historyId: EXPIRED_HISTORY_ID })) |
| 157 | + ).resolves.toBe('success') |
| 158 | + |
| 159 | + expect(persistedHistoryIds()).toEqual(['40100']) |
| 160 | + }) |
| 161 | +}) |
0 commit comments