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: 10 additions & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,22 @@ export const listEventsSchema = z.object({
});

const stringRecordSchema = z.record(z.string(), z.string());
const webhookCommonSchema = z.object({
context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}),
});
export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [
webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(),
webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(),
webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), signingSecret: z.string().min(16), handlerCode: z.string().max(16_384).optional() }).strict(),
webhookCommonSchema.extend({ provider: z.literal("custom"), secret: z.string().min(16).optional() }).strict(),
]);
export const triggerSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("manual"), config: z.object({}).strict().default({}) }).strict(),
z.object({ kind: z.literal("schedule"), config: z.object({
cron: z.string().trim().min(1), timezone: z.string().trim().min(1),
context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}),
}).strict() }).strict(),
z.object({ kind: z.literal("webhook"), config: z.record(z.string(), z.unknown()) }).strict(),
z.object({ kind: z.literal("webhook"), config: webhookTriggerConfigSchema }).strict(),
]);
export const jobInputSchema = z.object({
name: z.string().trim().min(1).max(120),
Expand Down
16 changes: 12 additions & 4 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ export class FlowService {
};
}

private publicJob(value: any) {
const provider = value?.trigger?.kind === "webhook" ? value.trigger.config?.provider : undefined;
if (provider === "cloudflareTail") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
if (provider === "custom") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
return value;
}

async listFlows() { return (await this.call("flows:read", "/pipes") as any[]).map(row => this.publicFlow(row)); }
async getFlow(flowId: string) {
const value = await this.call("flows:read", `/v1/flows/${encodeURIComponent(flowId)}`) as any;
Expand Down Expand Up @@ -76,10 +83,11 @@ export class FlowService {
getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); }
listFlowEvents(query: URLSearchParams) { return this.call("runs:read", `/v1/events?${query}`); }
stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); }
listJobs() { return this.call("flows:read", "/v1/jobs"); }
getJob(jobId: string) { return this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`); }
createJob(input: JobInput) { return this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
updateJob(jobId: string, input: JobInput) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); }
async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); }
listJobEvents(jobId: string, limit = 50) { return this.call("runs:read", `/v1/jobs/${encodeURIComponent(jobId)}/events?limit=${limit}`); }
async createJob(input: JobInput) { return this.publicJob(await this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); }
async updateJob(jobId: string, input: JobInput) { return this.publicJob(await this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); }
deleteJob(jobId: string) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE" }); }
setJobEnabled(jobId: string, enabled: boolean) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}/${enabled ? "enable" : "disable"}`, { method: "POST" }); }
invokeJob(jobId: string, input: ManualInvocationInput) { return this.call("runs:write", `/v1/jobs/${encodeURIComponent(jobId)}/invocations`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
Expand Down
4 changes: 4 additions & 0 deletions packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,10 @@ app.post("/webhooks/cloudflare/:tenantId/:flowId", async (c) => {
});
});

app.post("/webhooks/custom/:tenantId/:jobId", async (c) => {
return tenant(c, c.req.param("tenantId")).fetch(`https://tenant/webhook/custom/${encodeURIComponent(c.req.param("jobId"))}`, { method: "POST", headers: c.req.raw.headers, body: await c.req.text() });
});

app.post("/webhooks/linear", async (c) => {
if (!c.env.LINEAR_WEBHOOK_SIGNING_SECRET) return c.text("Webhook verification is not configured", 503);
const raw = await c.req.text();
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ export const JOB_SCHEMA = `
);
CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at);
CREATE INDEX IF NOT EXISTS job_runs_active ON job_runs(job_id, state);
CREATE TABLE IF NOT EXISTS job_events (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
provider TEXT NOT NULL, delivery_id TEXT NOT NULL, outcome TEXT NOT NULL,
detail TEXT NOT NULL, received_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS job_events_by_job ON job_events(job_id, received_at DESC);
CREATE TABLE IF NOT EXISTS schedule_state (
trigger_id TEXT PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE,
job_id TEXT NOT NULL UNIQUE REFERENCES jobs(id) ON DELETE CASCADE,
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
if (request.method === "POST" && path === "/api/v1/jobs") return Response.json(await service.createJob(jobInputSchema.parse(await request.json())), { status: 201 });
const invocationMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/invocations$/);
if (invocationMatch && request.method === "POST") return Response.json(await service.invokeJob(decodeURIComponent(invocationMatch[1]), manualInvocationSchema.parse(await request.json())), { status: 202 });
const jobEventsMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/events$/);
if (jobEventsMatch && request.method === "GET") return Response.json(await service.listJobEvents(decodeURIComponent(jobEventsMatch[1]), z.coerce.number().int().min(1).max(100).default(50).parse(url.searchParams.get("limit") ?? 50)));
const enabledMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/(enable|disable)$/);
if (enabledMatch && request.method === "POST") return Response.json(await service.setJobEnabled(decodeURIComponent(enabledMatch[1]), enabledMatch[2] === "enable"));
const jobMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)$/);
Expand Down Expand Up @@ -95,6 +97,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true));
tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false));
tool("invoke_job", "Manually invoke any enabled job, overriding string parameters and optional reserved context", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit));
tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets());
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await server.connect(transport);
Expand Down
Loading