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
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ createdb webhooks_journal_example # or use your preferred method
npm run db-init
```

> **Upgrading an existing checkout?** Re-run `npm run db-init` (`prisma db push`) to add the `deletedAt` column to the `Contact` table.

### 5. Start the App

In two terminal windows:
Expand Down Expand Up @@ -180,11 +182,14 @@ The app uses **two OAuth flows**:
1. The **Journal Poller** calls `GET /webhooks-journal/journal/2027-03-beta/batch/{offset}/next/100` once per second
2. Each journal entry URL is enqueued as a BullMQ job with 3 retry attempts and exponential backoff
3. **Event Processor** workers (5 concurrent) dequeue jobs, download the S3 file, and process each event:
- `CREATE` / `UPDATE` / `RESTORE` / `SNAPSHOT` → upsert contact in database
- `DELETE` → remove contact from database
- `MERGE` → delete merged contacts, upsert surviving contact
- `CREATE` / `UPDATE` / `SNAPSHOT` → upsert contact in database
- `DELETE` → soft delete: the row is kept and `deletedAt` is set, so the contact disappears from the UI but its data is retained
- `RESTORE` → upsert contact and clear `deletedAt`; the stored email and names come back even though a `RESTORE` event carries few or no properties
- `MERGE` → remove merged contacts permanently (merged IDs never come back), upsert surviving contact
4. **Last-write-wins**: if an incoming event's `occurredAt` is older than the contact's `lastModifiedDate`, it's skipped

> **Note:** Journal file URLs are presigned S3 URLs. Their query string is a credential, so never log a URL in full. This example logs only the origin and path (see `redactPresignedUrl`).

### 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.
Expand Down
57 changes: 57 additions & 0 deletions __tests__/download.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import axios from 'axios';
import { downloadJournalFile } from '../src/journal/processor';

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: {} }));
jest.mock('../src/portals', () => ({ registerPortal: jest.fn(), unregisterPortal: jest.fn() }));
jest.mock('../src/hubspot/subscriptions', () => ({ createContactSubscription: jest.fn() }));

const mockedGet = jest.mocked(axios.get);

const PRESIGNED_URL =
'https://bucket.s3.amazonaws.com/journal/file.json?X-Amz-Credential=AKIA123&X-Amz-Signature=deadbeef';

describe('downloadJournalFile', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('returns the downloaded journal file', async () => {
mockedGet.mockResolvedValue({ data: { journalEvents: [] } });
await expect(downloadJournalFile(PRESIGNED_URL)).resolves.toEqual({ journalEvents: [] });
});

it('reports the status and path but not the presigned query on HTTP failure', async () => {
mockedGet.mockRejectedValue({
isAxiosError: true,
message: `Request failed with status code 403 for ${PRESIGNED_URL}`,
response: { status: 403 },
});

const error = await downloadJournalFile(PRESIGNED_URL).catch((e: unknown) => e);

expect(error).toBeInstanceOf(Error);
const message = error instanceof Error ? error.message : '';
expect(message).toBe(
'Journal file download failed (403) for https://bucket.s3.amazonaws.com/journal/file.json?<redacted>'
);
expect(message).not.toContain('deadbeef');
expect(message).not.toContain('X-Amz');
});

it('reports a network error when there is no response', async () => {
mockedGet.mockRejectedValue(new Error('socket hang up'));

await expect(downloadJournalFile(PRESIGNED_URL)).rejects.toThrow(
'Journal file download failed (network error) for https://bucket.s3.amazonaws.com/journal/file.json?<redacted>'
);
});
});
208 changes: 208 additions & 0 deletions __tests__/processor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { Server } from 'http';
import express from 'express';
import { prisma } from '../src/clients';
import { processEvent } from '../src/journal/processor';
import contactRoutes from '../src/routes/contactRoutes';
import { CrmObjectEvent } from '../src/types/common';

jest.mock('../src/portals', () => ({
registerPortal: jest.fn(),
unregisterPortal: jest.fn(),
}));

jest.mock('../src/hubspot/subscriptions', () => ({
createContactSubscription: jest.fn(),
}));

const PORTAL_ID = 111;
const OBJECT_ID = 222;
const T0 = '2025-12-31T00:00:00.000Z';
const T1 = '2026-01-01T00:00:00.000Z';
const T2 = '2026-01-02T00:00:00.000Z';
const T3 = '2026-01-03T00:00:00.000Z';

const hasTestDatabase = (process.env.DATABASE_URL ?? '').includes('_test');
const describeWithDb = hasTestDatabase ? describe : describe.skip;

function crmEvent(
action: CrmObjectEvent['action'],
occurredAt: string,
propertyChanges?: Record<string, string>,
): CrmObjectEvent {
return {
type: 'crmObjectEvent',
portalId: PORTAL_ID,
occurredAt,
action,
objectTypeId: '0-1',
objectId: OBJECT_ID,
propertyChanges,
};
}

async function processAll(events: CrmObjectEvent[]): Promise<void> {
await prisma.$transaction(async (tx) => {
for (const event of events) {
await processEvent(event, tx);
}
});
}

async function findContact() {
return prisma.contact.findUnique({
where: { hsObjectId_portalId: { hsObjectId: String(OBJECT_ID), portalId: String(PORTAL_ID) } },
});
}

describeWithDb('contact soft delete reconciliation', () => {
beforeEach(async () => {
await prisma.$executeRaw`TRUNCATE TABLE "Contact" RESTART IDENTITY`;
});

afterAll(async () => {
await prisma.$disconnect();
});

it('soft-deletes on DELETE and keeps the contact data', async () => {
await processAll([
crmEvent('CREATE', T1, { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' }),
crmEvent('DELETE', T2),
]);

const contact = await findContact();
expect(contact?.deletedAt).not.toBeNull();
expect(contact?.deletedAt).toEqual(contact?.lastModifiedDate);
expect(contact?.email).toBe('a@example.com');
expect(contact?.firstname).toBe('Ada');
expect(contact?.lastname).toBe('Lovelace');
});

it('brings the original data back on RESTORE without any properties', async () => {
await processAll([
crmEvent('CREATE', T1, { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' }),
crmEvent('DELETE', T2),
crmEvent('RESTORE', T3),
]);

const contact = await findContact();
expect(contact?.deletedAt).toBeNull();
expect(contact?.email).toBe('a@example.com');
expect(contact?.firstname).toBe('Ada');
expect(contact?.lastname).toBe('Lovelace');
});

it('keeps a contact deleted when an older UPDATE is processed after the DELETE', async () => {
await processAll([
crmEvent('CREATE', T0, { email: 'a@example.com' }),
crmEvent('DELETE', T2),
]);
const deleted = await findContact();

await processAll([crmEvent('UPDATE', T1, { email: 'stale@example.com' })]);

const contact = await findContact();
expect(contact?.deletedAt).not.toBeNull();
expect(contact?.deletedAt).toEqual(deleted?.deletedAt);
expect(contact?.lastModifiedDate).toEqual(deleted?.lastModifiedDate);
expect(contact?.email).toBe('a@example.com');
});

it('writes a tombstone for an unknown contact so an older CREATE cannot resurrect it', async () => {
await processAll([crmEvent('DELETE', T2)]);

const tombstone = await findContact();
expect(tombstone?.deletedAt).not.toBeNull();
expect(tombstone?.email).toBeNull();

await processAll([crmEvent('CREATE', T1, { email: 'a@example.com' })]);

const contact = await findContact();
expect(contact?.deletedAt).toEqual(tombstone?.deletedAt);
expect(contact?.email).toBeNull();
});

it('un-deletes when a newer UPDATE arrives after the DELETE', async () => {
await processAll([
crmEvent('CREATE', T1, { email: 'a@example.com' }),
crmEvent('DELETE', T2),
crmEvent('UPDATE', T3, { firstname: 'Ada' }),
]);

const contact = await findContact();
expect(contact?.deletedAt).toBeNull();
expect(contact?.email).toBe('a@example.com');
expect(contact?.firstname).toBe('Ada');
});

it('un-deletes when a newer SNAPSHOT arrives after the DELETE', async () => {
await processAll([
crmEvent('CREATE', T1, { email: 'a@example.com' }),
crmEvent('DELETE', T2),
]);
await processAll([
{
...crmEvent('SNAPSHOT', T3),
propertyChanges: undefined,
properties: { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' },
},
]);

const contact = await findContact();
expect(contact?.deletedAt).toBeNull();
expect(contact?.lastname).toBe('Lovelace');
});

it('hard-deletes merged contacts', async () => {
await processAll([crmEvent('CREATE', T1, { email: 'merged@example.com' })]);

await processAll([
{
...crmEvent('MERGE', T2, { email: 'survivor@example.com' }),
objectId: OBJECT_ID + 1,
mergedObjectIds: [OBJECT_ID],
},
]);

expect(await findContact()).toBeNull();
const survivor = await prisma.contact.findUnique({
where: { hsObjectId_portalId: { hsObjectId: String(OBJECT_ID + 1), portalId: String(PORTAL_ID) } },
});
expect(survivor?.email).toBe('survivor@example.com');
});

describe('GET /api/contacts', () => {
let server: Server;
let baseUrl: string;

beforeAll(async () => {
const app = express();
app.use('/api', contactRoutes);
await new Promise<void>((resolve) => {
server = app.listen(0, () => resolve());
});
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Test server did not bind to a port');
}
baseUrl = `http://127.0.0.1:${address.port}`;
});

afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});

it('excludes soft-deleted contacts from the list and the total', async () => {
await processAll([
crmEvent('CREATE', T1, { email: 'gone@example.com' }),
crmEvent('DELETE', T2),
{ ...crmEvent('CREATE', T1, { email: 'kept@example.com' }), objectId: OBJECT_ID + 1 },
]);

const response = await fetch(`${baseUrl}/api/contacts`);
const body: unknown = await response.json();

expect(body).toMatchObject({ total: 1, contacts: [{ email: 'kept@example.com' }] });
expect(body).toHaveProperty('contacts.length', 1);
});
});
});
20 changes: 20 additions & 0 deletions __tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
OAUTH_SCOPES,
JOURNAL_POLL_INTERVAL_MS,
JOURNAL_BATCH_SIZE,
redactPresignedUrl,
} from '../src/utils/utils';

describe('utils constants', () => {
Expand Down Expand Up @@ -34,3 +35,22 @@ describe('utils constants', () => {
expect(JOURNAL_BATCH_SIZE).toBeGreaterThan(0);
});
});

describe('redactPresignedUrl', () => {
it('strips the query string from a presigned S3 URL', () => {
const url =
'https://bucket.s3.amazonaws.com/journal/2027/file.json?X-Amz-Credential=AKIA%2F20270101%2Fus-east-1&X-Amz-Signature=deadbeef';
const redacted = redactPresignedUrl(url);
expect(redacted).toBe('https://bucket.s3.amazonaws.com/journal/2027/file.json?<redacted>');
expect(redacted).not.toContain('deadbeef');
expect(redacted).not.toContain('AKIA');
});

it('leaves a URL without a query string unchanged', () => {
expect(redactPresignedUrl('https://example.com/a/b.json')).toBe('https://example.com/a/b.json');
});

it('returns a placeholder for invalid input', () => {
expect(redactPresignedUrl('not a url')).toBe('<invalid url>');
});
});
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ model Contact {
firstname String?
lastname String?
lastModifiedDate DateTime?
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

Expand Down
4 changes: 2 additions & 2 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import * as hubspot from '@hubspot/api-client';
import { prisma, hubspotClient, LIMITER_OPTIONS } from './clients';
import { HUBSPOT_API_BASE, JOURNAL_SCOPES, OAUTH_SCOPES } from './utils/utils';
import { OAUTH_TOKEN_URL, JOURNAL_SCOPES, OAUTH_SCOPES } from './utils/utils';
import { registerPortal } from './portals';
import { createLogger } from './utils/logger';

Expand Down Expand Up @@ -137,7 +137,7 @@ export async function getClientCredentialToken(): Promise<string> {
logger.info('Requesting new client credentials token...');

const response = await axios.post(
`${HUBSPOT_API_BASE}/oauth/v1/token`,
OAUTH_TOKEN_URL,
new URLSearchParams({
grant_type: 'client_credentials',
client_id: CLIENT_ID!,
Expand Down
Loading
Loading