Sync records with the change feed
Change feed explains what the events record and the feed’s guarantees.
The files use Node’s built-in file APIs. Keep this script on your server. Run it daily, and keep the gap between successful syncs below 30 days; Change feed explains retention.
Before you start
- The
apihelper, from Platform quickstart. - Your project,
project, and its secret key,key, for an environment that adopted IdentityHound, from Platform quickstart.
This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.
1. Open the saved cursor
Keep one directory per project and environment beside the script, on storage that survives between runs. Run only one copy at a time for each directory. This creates the directory for the event records and loads cursor.json, or starts at 0 when it doesn’t exist:
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
const feedEnvironment = key.startsWith('sk_test_') ? 'dev' : 'prd';
const feedDirectory = new URL(
`./identityhound-feed-${project.id}-${feedEnvironment}/`,
import.meta.url,
);
const recordsDirectory = new URL('events/', feedDirectory);
const cursorFile = new URL('cursor.json', feedDirectory);
const pendingCursorFile = new URL('cursor.tmp', feedDirectory);
await mkdir(recordsDirectory, { recursive: true });
async function loadFeedCursor(): Promise<number> {
try {
const cursor = JSON.parse(await readFile(cursorFile, 'utf8'));
if (!Number.isSafeInteger(cursor) || cursor < 0)
throw new Error('The saved cursor must be a nonnegative integer');
return cursor;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return 0;
}
}
To skip the feed’s history, save the next of one read with after=latest as the first cursor instead of 0.
2. Process and save each page
Read with after set to the saved cursor. Handle every event before saving next, then read again while a page holds limit events. Here each event becomes a JSON file named by its seq:
type FeedEvent = { seq: number; [field: string]: unknown };
async function syncChangeFeed(limit = 100): Promise<number> {
let cursor = await loadFeedCursor();
for (;;) {
const page: { events: FeedEvent[]; next: number } = await api(
'GET',
`/v1/identity/events?after=${cursor}&limit=${limit}`,
key,
);
for (const event of page.events) {
await writeFile(
new URL(`${event.seq}.json`, recordsDirectory),
JSON.stringify(event, null, 2),
);
}
await writeFile(pendingCursorFile, JSON.stringify(page.next));
await rename(pendingCursorFile, cursorFile);
cursor = page.next;
if (page.events.length < limit) return cursor;
}
}
const syncedCursor = await syncChangeFeed();
console.log('Saved cursor:', syncedCursor); // Saved cursor: …
The same event keeps its seq, so writing that file again replaces the same record. If the process stops after handling an event but before saving the page’s cursor, the next run repeats those writes safely. The cursor file is replaced only after all the page’s records are written. For another handler, make the effect safe to repeat too, such as an upsert keyed by the event’s seq within this project and environment, before advancing the cursor.
The events reference covers the query limits and filtering by type.
3. Recover when the cursor fell behind
A run more than 30 days after the last one finds events already removed, and the read answers cursor_expired instead of skipping them. The feed can’t give those changes back. Bring your records up to date from IdentityHound’s records instead, such as GET /sessions/:id for each session you keep. Then save the cursor right before the oldest event kept, so the next sync keeps every change still in the feed:
async function syncOrRecover(): Promise<number> {
try {
return await syncChangeFeed();
} catch (error) {
const failure = (
error as { error?: { code: string; details: { oldest: number } } }
).error;
if (failure?.code !== 'cursor_expired') throw error;
// Bring your records up to date from IdentityHound's records here.
await writeFile(
pendingCursorFile,
JSON.stringify(failure.details.oldest - 1),
);
await rename(pendingCursorFile, cursorFile);
return syncChangeFeed();
}
}
Check it worked
Read once from the cursor saved on disk:
const savedFeedCursor = await loadFeedCursor();
const again = await api(
'GET',
`/v1/identity/events?after=${savedFeedCursor}&limit=100`,
key,
);
console.log(again.events.length, again.next === savedFeedCursor); // 0 true
With no changes since the sync, the feed answers with no events and keeps the cursor. If new changes arrived, run syncChangeFeed() again to process them.