Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
110 changes: 110 additions & 0 deletions __tests__/poller.test.ts
Original file line number Diff line number Diff line change
@@ -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: '<html><h2>HTTP ERROR 404</h2></html>' },
};
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);
});
});
39 changes: 23 additions & 16 deletions src/journal/poller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,34 @@ async function getAuthHeaders(): Promise<Record<string, string>> {

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<JournalEntry | null> {
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<JournalEntry>(`${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<JournalBatchResponse | null> {
Expand All @@ -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;
Expand Down Expand Up @@ -107,7 +116,7 @@ async function pollOnce(queue: Queue): Promise<void> {
// 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) {
Expand Down Expand Up @@ -196,8 +205,6 @@ async function pollOnce(queue: Queue): Promise<void> {
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);
}
Expand Down
Loading