diff --git a/README.md b/README.md index 2520a25..a33437b 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,19 @@ The app uses **two OAuth flows**: - `MERGE` → delete merged contacts, upsert surviving contact 4. **Last-write-wins**: if an incoming event's `occurredAt` is older than the contact's `lastModifiedDate`, it's skipped +### Empty and Not-Found Responses + +The journal API signals "nothing here" differently depending on the endpoint. Handle each case explicitly; if you port this example to `fetch` or another HTTP client, don't rely on how that client happens to treat an empty body. + +| Endpoint | No entries | Offset unknown or expired | +|---|---|---| +| `GET .../earliest`, `GET .../latest` | `204 No Content`, empty body | n/a | +| `GET .../offset/{offset}/next` | `204 No Content`, empty body | `404` with `subCategory: "WebhooksJournalErrorType.JOURNAL_NOT_FOUND"` | +| `GET .../batch/{offset}/next/{count}` | `200` with `results: []` | `404` with `subCategory: "WebhooksJournalErrorType.JOURNAL_NOT_FOUND"` | + +- When a batch has no errors, `numErrors` and `errors` are omitted from the response, so check `results` rather than `numErrors === 0`. +- Treat only a `JOURNAL_NOT_FOUND` 404 as an expired cursor. Any other 404 (for example, an HTML 404 after a beta API version is retired) is a real error and should be surfaced, not treated as an empty journal or used as a reason to reset the cursor. + ### Subscription Filters Filters narrow which events a subscription delivers to the journal. They are evaluated server-side before events are written — filtered-out events never appear in the journal. diff --git a/__tests__/poller.test.ts b/__tests__/poller.test.ts new file mode 100644 index 0000000..7447c10 --- /dev/null +++ b/__tests__/poller.test.ts @@ -0,0 +1,110 @@ +import axios from 'axios'; +import { prisma } from '../src/clients'; +import { fetchBatchNext, resetCursorToLatest } from '../src/journal/poller'; + +jest.mock('axios', () => ({ + __esModule: true, + default: { + get: jest.fn(), + isAxiosError: (error: unknown) => + typeof error === 'object' && error !== null && 'isAxiosError' in error, + }, +})); + +jest.mock('../src/clients', () => ({ + prisma: { + journalCursor: { upsert: jest.fn(), deleteMany: jest.fn() }, + }, +})); + +jest.mock('../src/auth', () => ({ + getClientCredentialToken: jest.fn(async () => 'test-token'), +})); + +const mockedGet = jest.mocked(axios.get); +const mockedCursor = jest.mocked(prisma.journalCursor); + +describe('resetCursorToLatest', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('clears the cursor when the journal returns 204 No Content', async () => { + mockedGet.mockResolvedValueOnce({ status: 204, data: '' }); + + await resetCursorToLatest(); + + expect(mockedGet).toHaveBeenCalledWith( + expect.stringMatching(/\/latest$/), + expect.anything() + ); + expect(mockedCursor.deleteMany).toHaveBeenCalledWith({ where: { portalId: 'all' } }); + expect(mockedCursor.upsert).not.toHaveBeenCalled(); + }); + + it('surfaces a 404 instead of treating it as an empty journal', async () => { + const notFound = { isAxiosError: true, message: 'Not Found', response: { status: 404 } }; + mockedGet.mockRejectedValueOnce(notFound); + + await expect(resetCursorToLatest()).rejects.toBe(notFound); + expect(mockedCursor.deleteMany).not.toHaveBeenCalled(); + expect(mockedCursor.upsert).not.toHaveBeenCalled(); + }); + + it('moves the cursor to the latest offset when an entry is returned', async () => { + mockedGet.mockResolvedValueOnce({ + status: 200, + data: { url: 'https://example.com/entry', expiresAt: '2026-10-21T00:00:00Z', currentOffset: 'offset-1' }, + }); + + await resetCursorToLatest(); + + expect(mockedCursor.upsert).toHaveBeenCalledWith({ + where: { portalId: 'all' }, + update: { currentOffset: 'offset-1' }, + create: { portalId: 'all', currentOffset: 'offset-1' }, + }); + expect(mockedCursor.deleteMany).not.toHaveBeenCalled(); + }); +}); + +describe('fetchBatchNext', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('returns null when the offset is not in the journal (JOURNAL_NOT_FOUND)', async () => { + mockedGet.mockRejectedValueOnce({ + isAxiosError: true, + message: 'Not Found', + response: { + status: 404, + data: { + status: 'error', + category: 'OBJECT_NOT_FOUND', + subCategory: 'WebhooksJournalErrorType.JOURNAL_NOT_FOUND', + }, + }, + }); + + await expect(fetchBatchNext('expired-offset', 100)).resolves.toBeNull(); + }); + + it('surfaces a 404 that is not JOURNAL_NOT_FOUND, such as a retired API version', async () => { + const routeNotFound = { + isAxiosError: true, + message: 'Not Found', + response: { status: 404, data: '

HTTP ERROR 404

' }, + }; + mockedGet.mockRejectedValueOnce(routeNotFound); + + await expect(fetchBatchNext('some-offset', 100)).rejects.toBe(routeNotFound); + }); + + it('returns the batch when entries are available', async () => { + const batch = { status: 'COMPLETE', startedAt: '', completedAt: '', results: [] }; + mockedGet.mockResolvedValueOnce({ status: 200, data: batch }); + + await expect(fetchBatchNext('some-offset', 100)).resolves.toEqual(batch); + }); +}); diff --git a/src/journal/poller.ts b/src/journal/poller.ts index 4b55908..6aca922 100644 --- a/src/journal/poller.ts +++ b/src/journal/poller.ts @@ -22,25 +22,34 @@ async function getAuthHeaders(): Promise> { const ALL_PORTALS_KEY = 'all'; +const JOURNAL_NOT_FOUND = 'WebhooksJournalErrorType.JOURNAL_NOT_FOUND'; + +function isJournalNotFound(error: unknown): boolean { + if (!axios.isAxiosError(error) || error.response?.status !== 404) return false; + const body: unknown = error.response.data; + return ( + typeof body === 'object' && + body !== null && + 'subCategory' in body && + body.subCategory === JOURNAL_NOT_FOUND + ); +} + async function fetchBoundaryEntry(position: 'earliest' | 'latest'): Promise { - try { - const headers = await getAuthHeaders(); - const response = await requestWithRetry(() => - axios.get(`${JOURNAL_API_BASE}/${position}`, { headers }) - ); - return response.data; - } catch (error: unknown) { - if (axios.isAxiosError(error) && error.response?.status === 404) { - return null; - } - throw error; + const headers = await getAuthHeaders(); + const response = await requestWithRetry(() => + axios.get(`${JOURNAL_API_BASE}/${position}`, { headers }) + ); + if (response.status === 204) { + return null; } + return response.data; } // Poll all portals — the journal is app-scoped. Each event carries a portalId field // that the processor uses to store contacts per-portal. Filtering is done at the API // layer when returning contacts to the frontend. -async function fetchBatchNext( +export async function fetchBatchNext( offset: string, count: number ): Promise { @@ -51,7 +60,7 @@ async function fetchBatchNext( ); return response.data; } catch (error: unknown) { - if (axios.isAxiosError(error) && error.response?.status === 404) { + if (isJournalNotFound(error)) { return null; } throw error; @@ -107,7 +116,7 @@ async function pollOnce(queue: Queue): Promise { // sequence. Treat offsets as opaque pagination cursors, not sortable identifiers. const batch = await fetchBatchNext(cursor.currentOffset, JOURNAL_BATCH_SIZE); - // A 404 means the stored offset is invalid or has aged out of the journal. + // A JOURNAL_NOT_FOUND 404 means the stored offset is invalid or has aged out of the journal. // Retrying it would stall forever, so clear the cursor and re-initialize from the // earliest retained entry. Events that aged out are lost — run a bulk snapshot to backfill. if (!batch) { @@ -196,8 +205,6 @@ async function pollOnce(queue: Queue): Promise { logger.warn('Auth error during polling, token may need refresh'); } else if (status === 429) { logger.warn('Still rate limited after backoff retries, will retry next cycle'); - } else if (status === 404) { - logger.debug('No entries found at current offset'); } else { logger.error('API error during polling', error); }