From 3d204df7bfc7a93ab62b21a16ee1c479fe700d82 Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 15:26:35 -0400 Subject: [PATCH 1/3] Treat 204 as the journal's empty signal, not 404 WebhooksJournal's /earliest and /latest return 204 No Content with an empty body when an app has no journal entries; they never return 404 for that. The poller only worked because axios hands back '' for a 204, which happened to be falsy. Worse, it mapped 404 to "no entries", so a 404 from a missing route (for example the 2027-03-beta version being retired) would log "No journal entries available yet" forever instead of an error. --- __tests__/poller.test.ts | 69 ++++++++++++++++++++++++++++++++++++++++ src/journal/poller.ts | 20 ++++-------- 2 files changed, 76 insertions(+), 13 deletions(-) create mode 100644 __tests__/poller.test.ts diff --git a/__tests__/poller.test.ts b/__tests__/poller.test.ts new file mode 100644 index 0000000..716efc8 --- /dev/null +++ b/__tests__/poller.test.ts @@ -0,0 +1,69 @@ +import axios from 'axios'; +import { prisma } from '../src/clients'; +import { 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(); + }); +}); diff --git a/src/journal/poller.ts b/src/journal/poller.ts index 4b55908..bac5a9c 100644 --- a/src/journal/poller.ts +++ b/src/journal/poller.ts @@ -23,18 +23,14 @@ async function getAuthHeaders(): Promise> { const ALL_PORTALS_KEY = 'all'; 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 @@ -196,8 +192,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); } From 184149088dc0cb899d8bec249c357fc25456415b Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 15:32:28 -0400 Subject: [PATCH 2/3] Only reset the journal cursor on JOURNAL_NOT_FOUND batch/{offset}/next returns a JSON 404 whose subCategory is WebhooksJournalErrorType.JOURNAL_NOT_FOUND when an offset has expired. A retired or mistyped API version also returns 404, but as an HTML page. Treating every 404 as an expired offset would wipe the cursor on each poll instead of reporting the real problem. The README now spells out how each endpoint signals empty and not found (204 vs 200 with empty results vs JOURNAL_NOT_FOUND), because apps ported from this example to fetch crashed parsing the empty 204 body that axios had been quietly absorbing. --- README.md | 12 +++++++++++ __tests__/poller.test.ts | 43 +++++++++++++++++++++++++++++++++++++++- src/journal/poller.ts | 19 +++++++++++++++--- 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2520a25..8237357 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,18 @@ 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`, `GET .../offset/{offset}/next` | `204 No Content`, empty body | — | +| `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 index 716efc8..7447c10 100644 --- a/__tests__/poller.test.ts +++ b/__tests__/poller.test.ts @@ -1,6 +1,6 @@ import axios from 'axios'; import { prisma } from '../src/clients'; -import { resetCursorToLatest } from '../src/journal/poller'; +import { fetchBatchNext, resetCursorToLatest } from '../src/journal/poller'; jest.mock('axios', () => ({ __esModule: true, @@ -67,3 +67,44 @@ describe('resetCursorToLatest', () => { 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 bac5a9c..6aca922 100644 --- a/src/journal/poller.ts +++ b/src/journal/poller.ts @@ -22,6 +22,19 @@ 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 { const headers = await getAuthHeaders(); const response = await requestWithRetry(() => @@ -36,7 +49,7 @@ async function fetchBoundaryEntry(position: 'earliest' | 'latest'): Promise { @@ -47,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; @@ -103,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) { From 0d8857103a46381eed3e08f6dab20b74103395cc Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 15:32:40 -0400 Subject: [PATCH 3/3] Document JOURNAL_NOT_FOUND for offset/{offset}/next in the README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8237357..a33437b 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,8 @@ The journal API signals "nothing here" differently depending on the endpoint. Ha | Endpoint | No entries | Offset unknown or expired | |---|---|---| -| `GET .../earliest`, `GET .../latest`, `GET .../offset/{offset}/next` | `204 No Content`, empty body | — | +| `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`.