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
20 changes: 20 additions & 0 deletions apps/api/src/__tests__/helpers/webhooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// The paths where the example of a webhook event and a body it was sent differ in keys, nested
// objects and the first item of arrays included. A null or empty array on either side is not
// compared: the example may fill a field the sent body left empty, or the reverse.
export function exampleDrift(example: unknown, sent: unknown, path = ''): string[] {
if (Array.isArray(example) && Array.isArray(sent)) {
if (example.length === 0 || sent.length === 0) return [];
return exampleDrift(example[0], sent[0], `${path}[0]`);
}
if (!isRecord(example) || !isRecord(sent)) return [];
const keys = new Set([...Object.keys(example), ...Object.keys(sent)]);
return [...keys].flatMap((key) => {
const at = path ? `${path}.${key}` : key;
if (!(key in example) || !(key in sent)) return [at];
return exampleDrift(example[key], sent[key], at);
});
}

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { apiKeyApi, authedApi, createProject } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { createAgent } from '#tests/helpers/agents';
import { exampleDrift } from '#tests/helpers/webhooks';
import { onProjectEvent, type ProjectEvent } from '#modules/webhooks/emit';
import { enqueueAgentRun, markRunFailed, markRunSuccess } from '../../run-queue';

Expand Down Expand Up @@ -95,6 +96,12 @@ describe('agent_run.finished', () => {
}),
]);
expect((deliveries[0]!.payload as { data: object }).data).not.toHaveProperty('output');

// The example the webhook dialog shows drifts when runPayload gains or loses a field.
const types = (await asOwner.projects({ projectKey: 'MKT' }).webhooks['event-types'].get())
.data!;
const example = types.find((one) => one.event === 'agent_run.finished')!.example;
expect(exampleDrift(example, deliveries[0]!.payload)).toEqual([]);
});

it("sends how an external agent's run ended", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,21 @@ import { setWebhookEvents } from '../../service';
// An event an extension adds is listed, subscribed to and sent as the core's are, and a
// webhook keeps it once it is taken away.

const THING_DONE = { event: 'thing.done', action: 'update', type: 'Thing' } as const;
const THING_DONE = {
event: 'thing.done',
group: 'thing',
action: 'update',
type: 'Thing',
example: { id: 1 },
} as const;
// One the extension puts in a group of the core's.
const ISSUE_ESCALATED = {
event: 'issue.escalated',
group: 'issue',
action: 'update',
type: 'Issue',
example: { id: 2 },
} as const;

const hooks = (api: Api) => api.projects({ projectKey: 'MKT' }).webhooks;

Expand All @@ -26,15 +40,29 @@ async function sent(api: Api, webhookId: number) {
describe('webhook events an extension adds', () => {
beforeEach(async () => {
await resetDb();
setWebhookEvents([THING_DONE]);
setWebhookEvents([THING_DONE, ISSUE_ESCALATED]);
});
afterEach(() => setWebhookEvents());

it('lists them after the core’s and sends them as the core’s', async () => {
it('lists them after the core’s, in their groups, and sends them as the core’s', async () => {
const { asOwner, projectId } = await setup();
const types = (await hooks(asOwner)['event-types'].get()).data!;
expect(types.at(-1)).toBe('thing.done');
expect(types).toContain('agent_run.finished');
expect(types.map((one) => one.event).slice(-3)).toEqual([
'agent_run.finished',
'thing.done',
'issue.escalated',
]);
expect(types.at(-2)).toEqual({
event: 'thing.done',
group: 'thing',
example: expect.objectContaining({
action: 'update',
type: 'Thing',
event: 'thing.done',
data: { id: 1 },
}),
});
expect(types.at(-1)).toMatchObject({ event: 'issue.escalated', group: 'issue' });

const created = await hooks(asOwner).post({
url: 'https://example.com/hook',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { resetDb } from '#tests/helpers/db';
import { createAgent } from '#tests/helpers/agents';
import { addProjectMember } from '#tests/helpers/members';
import { createRole } from '#tests/helpers/roles';
import { exampleDrift } from '#tests/helpers/webhooks';
import type { WebhookEventType } from '../../service';
import { onProjectEvent, type ProjectEvent } from '../../emit';
import { createComment } from '#modules/issues/activity';
Expand Down Expand Up @@ -553,6 +554,53 @@ describe('webhooks', () => {
});
});

describe('examples', () => {
it('lists every core event in its group', async () => {
const { asOwner } = await setupOwnerProject();
const types = (await asOwner.projects({ projectKey: 'MKT' }).webhooks['event-types'].get())
.data!;
expect(types.map((one) => [one.event, one.group])).toEqual([
['issue.created', 'issue'],
['issue.updated', 'issue'],
['issue.deleted', 'issue'],
['issue.assigned', 'issue'],
['issue.state_changed', 'issue'],
['issue.label_changed', 'issue'],
['issue.link_changed', 'issue'],
['comment.created', 'comment'],
['comment.updated', 'comment'],
['comment.deleted', 'comment'],
['agent_run.finished', 'agent_run'],
]);
});

// An example drifts from the payload when a payload builder gains or loses a field.
it('has the keys of the body an issue, a label and a comment event send', async () => {
const { asOwner, columnId } = await setupOwnerProject();
const id = await createWebhook(asOwner, [
'issue.created',
'issue.label_changed',
'comment.created',
]);
const label = (await asOwner.projects({ projectKey: 'MKT' }).labels.post({ name: 'bug' }))
.data!;
const issue = (
await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })
).data!;
await asOwner.issues({ issueId: issue.id }).patch({ labelIds: [label.id] });
await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'looks good' });

const types = (await asOwner.projects({ projectKey: 'MKT' }).webhooks['event-types'].get())
.data!;
const sentBy = (await asOwner.webhooks({ webhookId: id }).deliveries.get()).data!.items;
for (const event of ['issue.created', 'issue.label_changed', 'comment.created']) {
const example = types.find((one) => one.event === event)!.example;
const payload = sentBy.find((one) => one.eventType === event)!.payload;
expect(exampleDrift(example, payload)).toEqual([]);
}
});
});

describe('events without a field edit', () => {
it('fires issue.updated on archive and restore', async () => {
const { asOwner, columnId } = await setupOwnerProject();
Expand Down
66 changes: 11 additions & 55 deletions apps/api/src/modules/webhooks/emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,12 @@ import { aiAgent, db, user, webhook, webhookDelivery } from '@repo/db';
import { and, eq, sql } from 'drizzle-orm';
import type { ActivityActor } from '#modules/issues/activity';
import {
extensionWebhookEvent,
type WebhookEventDefinition,
type WebhookEventType,
} from './service';

// Maps our granular event type to the Linear-style envelope's action + resource
// type. action is create | update | remove. type is the PascalCase resource.
// Linear's action/type pair cannot distinguish our assigned, state_changed, and
// label_changed variants, because all of them are an issue update. The payload keeps
// the granular event in its own `event` field.
type EventShape = Pick<WebhookEventDefinition, 'action' | 'type'>;

const EVENT_SHAPE: Record<WebhookEventType, EventShape> = {
'issue.created': { action: 'create', type: 'Issue' },
'issue.updated': { action: 'update', type: 'Issue' },
'issue.deleted': { action: 'remove', type: 'Issue' },
'issue.assigned': { action: 'update', type: 'Issue' },
'issue.state_changed': { action: 'update', type: 'Issue' },
'issue.label_changed': { action: 'update', type: 'Issue' },
'issue.link_changed': { action: 'update', type: 'Issue' },
'comment.created': { action: 'create', type: 'Comment' },
'comment.updated': { action: 'update', type: 'Comment' },
'comment.deleted': { action: 'remove', type: 'Comment' },
'agent_run.finished': { action: 'update', type: 'AgentRun' },
};

// Who caused the event. An agent acts through its own bot user, so a user id is an
// agent when an ai_agent row points at it. A system write has no user: it carries
// the system's name ('GitHub', 'Auto-archive'), or null for an unnamed one.
interface WebhookActor {
type: 'human' | 'agent' | 'system';
id: string | null;
name: string | null;
}
CORE_WEBHOOK_EVENTS,
webhookBody,
type WebhookActor,
type WebhookEventShape,
} from './events';
import { extensionWebhookEvent, type WebhookEventType } from './service';

async function resolveActor(actor: ActivityActor): Promise<WebhookActor> {
if (!actor) return { type: 'system', id: null, name: null };
Expand Down Expand Up @@ -104,13 +76,8 @@ function subscribedWebhooks(projectId: number, eventType: string) {
// receiver can deduplicate; the deliveries go in as one insert. Call it right after a
// domain mutation, next to the activity log. The payloads are built at most once, when a
// listener of onProjectEvent or a subscribed webhook needs them, so a project with no
// webhooks and no listener pays one indexed SELECT.
//
// The body follows Linear's webhook envelope: top-level action, type, actor, data,
// plus createdAt and webhookTimestamp (epoch ms). `event` is our extension, and it
// carries the granular event type. We omit organizationId, because there is no
// organization concept. The shared dedup id goes in the X-Itsaplan-Event-Id header,
// not in the body.
// webhooks and no listener pays one indexed SELECT. The body is webhookBody's; the shared
// dedup id goes in the X-Itsaplan-Event-Id header, not in the body.
export async function emitWebhookEvents(
projectId: number,
eventType: WebhookEventType,
Expand All @@ -127,7 +94,7 @@ export async function emitWebhookEvents(
}
}

await deliver(projectId, eventType, EVENT_SHAPE[eventType], loadOnce, actor);
await deliver(projectId, eventType, CORE_WEBHOOK_EVENTS[eventType], loadOnce, actor);
}

// Sends an event an extension adds (setWebhookEvents) to the webhooks of the project that
Expand All @@ -146,7 +113,7 @@ export async function emitExtensionWebhookEvent(
async function deliver(
projectId: number,
eventType: string,
{ action, type }: EventShape,
shape: WebhookEventShape,
load: () => Promise<unknown[]>,
actor: ActivityActor,
): Promise<void> {
Expand All @@ -158,8 +125,6 @@ async function deliver(

const resolvedActor = await resolveActor(actor);
const now = new Date();
const createdAt = now.toISOString();
const webhookTimestamp = now.getTime();

await db.insert(webhookDelivery).values(
payloads.flatMap((data) => {
Expand All @@ -168,16 +133,7 @@ async function deliver(
webhookId: h.id,
eventId,
eventType,
payload: {
action,
type,
event: eventType,
actor: resolvedActor,
createdAt,
data,
webhookTimestamp,
webhookId: h.id,
},
payload: webhookBody(shape, eventType, resolvedActor, data, now, h.id),
}));
}),
);
Expand Down
Loading
Loading