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: '