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
140 changes: 140 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1778,6 +1778,54 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/event-subscriptions/{subscriptionId}/occurrences": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List matched occurrences for the signed-in owner's exact subscription
* @description Newest first. HTTP acceptance confirms receipt, not processing. Acknowledgment is independent. Webhook configuration and payloads are omitted.
*
* Requires the triggers:read scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
get: operations["get_api_v1_event_subscriptions_subscriptionId_occurrences"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/events/{eventId}/occurrence-summaries": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List bounded, payload-free Event occurrence summaries
* @description Newest first, with occurrence IDs and safe source classifications. The full occurrence endpoint is unchanged.
*
* Requires the triggers:read scope.
*
* Accepts a scoped bearer token or interactive owner session.
*/
get: operations["get_api_v1_events_eventId_occurrence_summaries"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/events": {
parameters: {
query?: never;
Expand Down Expand Up @@ -6416,6 +6464,98 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_event_subscriptions_subscriptionId_occurrences: {
parameters: {
query?: {
limit?: number;
cursor?: string;
};
header?: never;
path: {
subscriptionId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Subscription occurrence summaries */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
items: {
/** Format: uuid */
id: string;
/** Format: date-time */
occurredAt: string;
/** @enum {string} */
source: "manual" | "schedule" | "github" | "linear" | "cloudflare" | "webhook" | "unknown";
/** @enum {string} */
delivery: "pending" | "sending" | "accepted" | "failed" | "cancelled";
/** @enum {string} */
acknowledgment: "off" | "pending" | "awaiting_ack" | "processed" | "waived" | "exhausted" | "cancelled";
}[];
nextCursor: string | null;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
/** @description Event subscription not found */
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_events_eventId_occurrence_summaries: {
parameters: {
query?: {
limit?: number;
cursor?: string;
};
header?: never;
path: {
eventId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Event occurrence summaries */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
items: {
/** Format: uuid */
id: string;
/** Format: date-time */
occurredAt: string;
/** @enum {string} */
source: "manual" | "schedule" | "github" | "linear" | "cloudflare" | "webhook" | "unknown";
}[];
nextCursor: string | null;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
/** @description Event not found */
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_events: {
parameters: {
query?: never;
Expand Down
19 changes: 19 additions & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { eventOccurrenceSummaryPage, subscriptionOccurrenceSummaryPage, occurrenceSummaryQuery } from "./event-contracts";
import { cloudflareCookieValue, cloudflareSelectInput, cloudflareStartInput, cloudflareStartResult, cloudflareStatus } from "./cloudflare-oauth";
import { cloneInfo, gitCredential } from "./git-https-contracts";
import { profileInput, profileResponse } from "./usernames";
Expand Down Expand Up @@ -699,6 +700,24 @@ export const API_ROUTES: RouteContract[] = [
responses: { "200": { description: "Event subscription", content: { "application/json": { schema: jsonSchema(eventSubscription, "output") } } }, "404": { description: "Event subscription not found" } },
}, (service, { params }) => service.getDashboardEventSubscription(params.subscriptionId),
{ ownerSession: true, parameters: z.object({ subscriptionId: eventSubscriptionId }) }),
route("GET", "/api/v1/event-subscriptions/{subscriptionId}/occurrences", "triggers:read", {
summary: "List matched occurrences for the signed-in owner's exact subscription",
description: "Newest first. HTTP acceptance confirms receipt, not processing. Acknowledgment is independent. Webhook configuration and payloads are omitted.",
responses: {
"200": { description: "Subscription occurrence summaries", content: { "application/json": { schema: jsonSchema(subscriptionOccurrenceSummaryPage, "output") } } },
"404": { description: "Event subscription not found" },
},
}, (service, { params, query }) => service.listSubscriptionOccurrences(params.subscriptionId, query.limit, query.cursor),
{ ownerSession: true, parameters: z.object({ subscriptionId: eventSubscriptionId }), query: occurrenceSummaryQuery }),
route("GET", "/api/v1/events/{eventId}/occurrence-summaries", "triggers:read", {
summary: "List bounded, payload-free Event occurrence summaries",
description: "Newest first, with occurrence IDs and safe source classifications. The full occurrence endpoint is unchanged.",
responses: {
"200": { description: "Event occurrence summaries", content: { "application/json": { schema: jsonSchema(eventOccurrenceSummaryPage, "output") } } },
"404": { description: "Event not found" },
},
}, (service, { params, query }) => service.listEventOccurrenceSummaries(params.eventId, query.limit, query.cursor),
{ parameters: z.object({ eventId: z.uuid() }), query: occurrenceSummaryQuery }),
route("GET", "/api/v1/events", "triggers:read", { summary: "List Events", responses: { "200": { description: "Events and current revisions", content: { "application/json": { schema: jsonSchema(eventDefinitionList, "output") } } } } }, service => service.listEvents()),
route("POST", "/api/v1/events", "triggers:write", { summary: "Create an Event", responses: { "201": { description: "Created Event", content: { "application/json": { schema: jsonSchema(eventDefinitionResponse, "output") } } } } }, (service, { body }) => service.createEvent(body), { body: eventDefinitionInput }),
route("GET", "/api/v1/events/{eventId}", "triggers:read", { summary: "Get an Event", responses: { "200": { description: "Event", content: { "application/json": { schema: jsonSchema(eventDefinitionResponse, "output") } } } } }, (service, { params }) => service.getEvent(params.eventId), { parameters: z.object({ eventId: z.uuid() }) }),
Expand Down
23 changes: 23 additions & 0 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { readOccurrenceSummaries } from "./postgres/occurrence-summary-repository";
import { eventOccurrenceSummaryPage, subscriptionOccurrenceSummaryPage, parseOccurrenceSummaryCursor } from "./event-contracts";
import { cloudflareState, disconnectCloudflare, selectCloudflare, startCloudflare } from "./cloudflare-oauth";
import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect";
import { deleteMcpGrantSubscriptions, lockMcpEventGrant } from "./postgres/mcp-event-outbox";
Expand Down Expand Up @@ -225,6 +227,27 @@ export class ApiService {
async createEvent(input: unknown) { await this.authorize("triggers:write"); return publicValue(eventDefinitionResponse, await this.eventDefinitions().create(eventDefinitionInput.parse(input))); }
async updateEvent(id: string, input: unknown) { await this.authorize("triggers:write"); const parsed = eventDefinitionUpdate.parse(input); try { const result = await this.eventDefinitions().update(id, parsed, parsed.expectedRevision); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventDefinitionResponse, result); } catch (error) { if (error instanceof EventDefinitionConflict) throw new ServiceError(409, "stale_event", "Event changed since it was loaded."); throw error; } }
async deleteEvent(id: string) { await this.authorize("triggers:write"); if (!await this.eventDefinitions().delete(id)) throw new ServiceError(404, "not_found", "Event not found"); return { id, deleted: true as const }; }
private occurrenceSummaryBoundary(id: string, cursor?: string) {
if (cursor === undefined) return undefined;
const boundary = parseOccurrenceSummaryCursor(cursor, id);
if (!boundary) throw new ServiceError(400, "invalid_request", "Cursor does not match this occurrence history.");
return boundary;
}
async listEventOccurrenceSummaries(id: string, limit: number, cursor?: string) {
await this.authorize("triggers:read");
id = id.toLowerCase();
const result = await readOccurrenceSummaries(databaseFor(this.env), this.auth.tenantId,
{ kind: "event", id }, limit, this.occurrenceSummaryBoundary(id, cursor));
if (!result) throw new ServiceError(404, "not_found", "Event not found");
return publicValue(eventOccurrenceSummaryPage, result);
}
async listSubscriptionOccurrences(id: string, limit: number, cursor?: string) {
await this.authorizeOwnerSession("triggers:read");
const result = await readOccurrenceSummaries(databaseFor(this.env), this.auth.tenantId,
{ kind: "subscription", id, userId: this.auth.userId }, limit, this.occurrenceSummaryBoundary(id, cursor));
if (!result) throw new ServiceError(404, "not_found", "Event subscription not found");
return publicValue(subscriptionOccurrenceSummaryPage, result);
}
async listEventOccurrences(id: string, limit: number, cursor?: string) { await this.authorize("triggers:read"); const result = await this.eventDefinitions().occurrences(id, limit, cursor); if (!result) throw new ServiceError(404, "not_found", "Event not found"); return publicValue(eventOccurrencePage, result); }
async mcpEventCatalog() {
await this.authorize("triggers:read");
Expand Down
21 changes: 21 additions & 0 deletions packages/api/src/event-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,24 @@ export const eventSubscription = z.object({
expiresAt: z.iso.datetime(),
});
export const eventSubscriptionList = z.array(eventSubscription);

export const occurrenceSummaryQuery = z.object({
limit: z.coerce.number().int().min(1).max(50).default(10),
cursor: z.string().min(1).max(384).optional(),
});
const summarySource = z.enum(["manual", "schedule", "github", "linear", "cloudflare", "webhook", "unknown"]);
const occurrenceSummary = z.object({ id: z.uuid(), occurredAt: z.iso.datetime(), source: summarySource });
const subscriptionOccurrenceSummary = occurrenceSummary.extend({
delivery: z.enum(["pending", "sending", "accepted", "failed", "cancelled"]),
acknowledgment: z.enum(["off", "pending", "awaiting_ack", "processed", "waived", "exhausted", "cancelled"]),
});
export const eventOccurrenceSummaryPage = z.object({ items: z.array(occurrenceSummary), nextCursor: z.string().nullable() });
export const subscriptionOccurrenceSummaryPage = z.object({ items: z.array(subscriptionOccurrenceSummary), nextCursor: z.string().nullable() });
const summaryCursor = z.tuple([z.string(), z.iso.datetime(), z.uuid()]);
export function parseOccurrenceSummaryCursor(cursor: string, collectionId: string): [string, string] | null {
try {
const [id, occurredAt, occurrenceId] = summaryCursor.parse(JSON.parse(atob(cursor)));
if (id === collectionId) return [occurredAt, occurrenceId];
} catch { /* Invalid or foreign cursor. */ }
return null;
}
42 changes: 42 additions & 0 deletions packages/api/src/postgres/occurrence-summary-repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Database } from "./database";

type Collection = { kind: "event"; id: string } | { kind: "subscription"; id: string; userId: string };
type Row = { id: string | null; occurred_at: string; source: string; delivery: string; acknowledgment: string };

// Project only safe columns. The ID is usable with the existing occurrence read
// protocol; payload, raw sources, credentials and callbacks never go to the table.
export async function readOccurrenceSummaries(db: Database, tenantId: string, collection: Collection, limit: number, boundary?: [string, string]) {
const isSubscription = collection.kind === "subscription";
const parent = isSubscription
? "SELECT tenant_id,id,definition_id FROM app.mcp_event_subscriptions WHERE tenant_id=$1 AND id=$2 AND user_id=$6"
: "SELECT tenant_id,id AS definition_id FROM app.event_definitions WHERE tenant_id=$1 AND id=$2";
const fields = isSubscription ? ",d.status AS delivery,COALESCE(d.ack_state,'off') AS acknowledgment" : "";
const delivery = isSubscription
? "JOIN app.mcp_event_deliveries d ON d.tenant_id=o.tenant_id AND d.subscription_id=p.id AND d.occurrence_id=o.id"
: "";
const { rows } = await db.pool.query<Row>(
`SELECT page.id,page.occurred_at,page.source${isSubscription ? ",page.delivery,page.acknowledgment" : ""}
FROM (${parent}) p
LEFT JOIN LATERAL (
SELECT o.id,o.occurred_at AS sort_time,
to_char(o.occurred_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS occurred_at,
CASE split_part(o.source_identity,':',1)
WHEN 'manual' THEN 'manual' WHEN 'schedule' THEN 'schedule' WHEN 'github' THEN 'github'
WHEN 'linear' THEN 'linear' WHEN 'cloudflare' THEN 'cloudflare' WHEN 'webhook' THEN 'webhook'
ELSE 'unknown' END AS source${fields}
FROM app.event_occurrences o ${delivery}
WHERE o.tenant_id=p.tenant_id AND o.definition_id=p.definition_id
AND ($3::timestamptz IS NULL OR (o.occurred_at,o.id)<($3,$4::uuid))
ORDER BY o.occurred_at DESC,o.id DESC LIMIT $5
) page ON TRUE
ORDER BY page.sort_time DESC,page.id DESC`,
[tenantId, collection.id, boundary?.[0] ?? null, boundary?.[1] ?? null, limit + 1, ...(isSubscription ? [collection.userId] : [])],
);
if (!rows.length) return null;
const items = rows.slice(0, limit).flatMap(row => !row.id ? [] : [{
id: row.id, occurredAt: row.occurred_at, source: row.source,
...(isSubscription ? { delivery: row.delivery, acknowledgment: row.acknowledgment } : {}),
}]);
const last = items.at(-1);
return { items, nextCursor: rows.length > limit && last ? btoa(JSON.stringify([collection.id, last.occurredAt, last.id])) : null };
}
Loading
Loading