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
8 changes: 5 additions & 3 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,7 @@ export interface paths {
};
/**
* List bounded job summaries
* @description Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.
* @description Additive bounded list representation. Omitted sort preserves legacy immutable UUID descending; updated preserves updated time descending with UUID descending ties. active sorts jobs with live runs first, then name and UUID ascending; running sorts numeric live-run counts in direction with name and UUID ascending ties; title sorts name in direction with UUID ascending ties. Name ordering uses the PostgreSQL en-US ICU collation. Non-ID sorts return opaque cursors bound to their sort and direction; keep filters and sort unchanged between pages. Live run-count changes can move jobs between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.
*
* Requires the jobs:read scope.
*
Expand Down Expand Up @@ -4308,7 +4308,8 @@ export interface operations {
cursor?: string;
q?: string;
enabled?: "true" | "false";
sort?: "id" | "updated";
sort?: "id" | "updated" | "active" | "running" | "title";
direction?: "asc" | "desc";
};
header?: never;
path?: never;
Expand Down Expand Up @@ -4364,7 +4365,8 @@ export interface operations {
cursor?: string;
q?: string;
enabled?: "true" | "false";
sort?: "id" | "updated";
sort?: "id" | "updated" | "active" | "running" | "title";
direction?: "asc" | "desc";
};
header?: never;
path?: never;
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ export const API_ROUTES: RouteContract[] = [
),
route("GET", "/api/v1/job-summaries", "flows:read", {
summary: "List bounded job summaries",
description: "Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.",
description: "Additive bounded list representation. Omitted sort preserves legacy immutable UUID descending; updated preserves updated time descending with UUID descending ties. active sorts jobs with live runs first, then name and UUID ascending; running sorts numeric live-run counts in direction with name and UUID ascending ties; title sorts name in direction with UUID ascending ties. Name ordering uses the PostgreSQL en-US ICU collation. Non-ID sorts return opaque cursors bound to their sort and direction; keep filters and sort unchanged between pages. Live run-count changes can move jobs between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.",
responses: { "200": { description: "Summary page", content: { "application/json": { schema: jsonSchema(jobSummaryPage, "output") } } } },
}, (service, { query }) => service.listJobSummaries(query), { query: jobPageQuery }),
route("GET", "/api/v1/job-selector", "flows:read", {
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { nextOccurrence, validateScheduleConfig } from "./schedule";
import { databaseFor } from "./postgres/database";
import { IdentityRepository } from "./postgres/identity-repository";
import { AccessTokenRepository } from "./postgres/access-token-repository";
import { JobSummaryRepository } from "./postgres/job-summary-repository";
import { InvalidJobSummaryCursor, JobSummaryRepository } from "./postgres/job-summary-repository";
import { jobResponse } from "./job-contracts";
import type { JobPageQuery } from "./job-contracts";
import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository";
Expand Down Expand Up @@ -260,7 +260,7 @@ export class ApiService {
}
async stopRun(runId: string) { await this.authorize("runs:cancel"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; }
killRun(runId: string) { return this.stopRun(runId); }
async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); }
async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); try { return await new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } catch (error) { if (error instanceof InvalidJobSummaryCursor) throw new ServiceError(400, "invalid_request", error.message); throw error; } }
async listJobs() { await this.authorize("jobs:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); }
async getJob(jobId: string) { await this.authorize("jobs:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); }
async listProjects(options?: { limit?: number; sort?: "name" | "updated" }) { await this.authorize("projects:read"); return this.projects().list(options); }
Expand Down
15 changes: 11 additions & 4 deletions packages/api/src/job-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ import { jobInputSchema, scopeSchema, triggerSchema, webhookTriggerConfigSchema
export const jobPageQuery = z.object({
projectId: z.guid().optional(),
limit: z.coerce.number().int().min(1).max(100).default(30),
cursor: z.guid().optional(),
cursor: z.string().max(512).optional(),
q: z.string().trim().max(120).default(""),
enabled: z.enum(["true", "false"]).optional(),
sort: z.enum(["id", "updated"]).optional(),
sort: z.enum(["id", "updated", "active", "running", "title"]).optional(),
direction: z.enum(["asc", "desc"]).optional(),
}).superRefine((query, context) => {
if (!query.cursor) return;
const legacySort = query.sort === undefined || query.sort === "id" || query.sort === "updated";
if (z.guid().safeParse(query.cursor).success !== legacySort) {
context.addIssue({ code: "custom", path: ["cursor"], message: "Cursor format does not match the selected sort" });
}
});
export type JobPageQuery = z.infer<typeof jobPageQuery>;
export const jobSelectorItem = z.object({ id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean() });
Expand All @@ -17,8 +24,8 @@ export const jobSummary = jobSelectorItem.extend({
concurrencyLimit: z.number().int(), runningCount: z.number().int(),
lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(),
});
export const jobSummaryPage = z.object({ items: z.array(jobSummary), nextCursor: z.guid().nullable() });
export const jobSelectorPage = z.object({ items: z.array(jobSelectorItem), nextCursor: z.guid().nullable() });
export const jobSummaryPage = z.object({ items: z.array(jobSummary), nextCursor: z.string().nullable() });
export const jobSelectorPage = z.object({ items: z.array(jobSelectorItem), nextCursor: z.string().nullable() });
const triggerIdentity = { id: z.guid(), jobId: z.guid(), slug: z.string(), createdAt: z.string(), updatedAt: z.string() };
const webhookResponse = z.discriminatedUnion("provider", [
webhookTriggerConfigSchema.options[0].extend({ secretConfigured: z.boolean().optional() }).strip(),
Expand Down
129 changes: 106 additions & 23 deletions packages/api/src/postgres/job-summary-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,128 @@ import type { JobPageQuery } from "../job-contracts";

interface SummaryRow {
id: string; project_id: string; name: string; slug: string; enabled: boolean; model: string; effort: string;
agent_kind: string; execution_type: string | null; concurrency_limit: number; running_count: string; last_run_state: string | null;
created_at: Date; updated_at: Date;
agent_kind: string; execution_type: string | null; concurrency_limit: number; running_count: string; active: boolean;
last_run_state: string | null; created_at: Date; updated_at: Date;
}

const nameOrder = `name COLLATE "en-US-x-icu"`;
const encodeCursor = (tuple: unknown[]) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(tuple)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
const decodeCursor = (cursor: string) => {
try {
const padded = cursor.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((cursor.length + 3) % 4);
const parsed: unknown = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(padded), char => char.charCodeAt(0))));
return Array.isArray(parsed) ? parsed : null;
}
catch { return null; }
};
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export class InvalidJobSummaryCursor extends Error {}

/** Never reads/decrypts prompts or loads triggers. One bounded query per page. */
export class JobSummaryRepository {
constructor(private database: Database, private tenantId: string) {
if (!tenantId) throw new Error("tenantId is required");
}
async page(input: JobPageQuery, selector = false) {
const sort = input.sort ?? "id";
const direction = sort === "active" ? "desc" : input.direction ?? "asc";
const legacyCursor = input.cursor && uuid.test(input.cursor) ? input.cursor : null;
const cursorTuple = input.cursor && !legacyCursor ? decodeCursor(input.cursor) : null;
const values: unknown[] = [this.tenantId];
const clauses = ["j.tenant_id=$1", "($2='' OR strpos(lower(j.name),lower($2))>0 OR strpos(lower(j.slug),lower($2))>0)"];
let cursorClause = "TRUE";
values.push(input.q);
values.push(input.enabled === undefined ? null : input.enabled === "true");
clauses.push(`($3::boolean IS NULL OR j.enabled=$3)`);
values.push(input.projectId ?? null);
clauses.push(`($4::uuid IS NULL OR j.project_id=$4)`);
if (legacyCursor && (sort === "id" || sort === "updated")) {
values.push(legacyCursor);
cursorClause = `j.id<$${values.length}::uuid`;
} else if (input.cursor) {
const expectedLength = sort === "active" || sort === "running" ? 5 : sort === "title" ? 4 : 0;
const tupleValid = !!cursorTuple && (sort === "active"
? typeof cursorTuple[2] === "boolean" && typeof cursorTuple[3] === "string"
: sort === "running" ? Number.isInteger(cursorTuple[2]) && typeof cursorTuple[3] === "string"
: sort === "title" && typeof cursorTuple[2] === "string");
if (!cursorTuple || !tupleValid || cursorTuple.length !== expectedLength || cursorTuple[0] !== sort || cursorTuple[1] !== direction || !uuid.test(String(cursorTuple.at(-1)))) {
throw new InvalidJobSummaryCursor("Invalid job summary cursor for sort or direction");
}
if (sort === "active") {
values.push(Number(cursorTuple[2]), String(cursorTuple[3]), String(cursorTuple[4]));
cursorClause = `(coalesce(c.active,false) < $5::boolean OR (coalesce(c.active,false)=$5::boolean AND (${nameOrder} > $6 COLLATE "en-US-x-icu" OR (${nameOrder}=$6 COLLATE "en-US-x-icu" AND j.id>$7::uuid))))`;
} else if (sort === "running") {
values.push(Number(cursorTuple[2]), String(cursorTuple[3]), String(cursorTuple[4]));
const op = direction === "asc" ? ">" : "<";
cursorClause = `(c.running_count ${op} $5::integer OR (c.running_count=$5::integer AND (${nameOrder} > $6 COLLATE "en-US-x-icu" OR (${nameOrder}=$6 COLLATE "en-US-x-icu" AND j.id>$7::uuid))))`;
} else if (sort === "title") {
values.push(String(cursorTuple[2]), String(cursorTuple[3]));
const op = direction === "asc" ? ">" : "<";
cursorClause = `(${nameOrder} ${op} $5 COLLATE "en-US-x-icu" OR (${nameOrder}=$5 COLLATE "en-US-x-icu" AND j.id>$6::uuid))`;
}
}
values.push(input.limit + 1);
const sortOrder = sort === "active"
? `coalesce(c.active,false) DESC, ${nameOrder} ASC, j.id ASC`
: sort === "running"
? `coalesce(c.running_count,0) ${direction.toUpperCase()}, ${nameOrder} ASC, j.id ASC`
: sort === "title"
? `${nameOrder} ${direction.toUpperCase()}, j.id ASC`
: sort === "updated"
? "j.updated_at DESC,j.id DESC"
: "j.id DESC";
const sortsByRunCount = sort === "active" || sort === "running";
const lastRunState = selector ? "NULL::text" : "(array_agg(r.state ORDER BY r.created_at DESC,r.id DESC))[1]";
const summaryPages = sortsByRunCount
? `counts AS MATERIALIZED (
SELECT f.id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::integer running_count,
bool_or(r.state IN ('reserved','starting','running','blocked','stopping')) active,
${lastRunState} last_run_state
FROM filtered f LEFT JOIN app.job_runs r ON r.tenant_id=$1 AND r.job_id=f.id GROUP BY f.id
), page AS MATERIALIZED (
SELECT j.*,coalesce(c.running_count,0) running_count,coalesce(c.active,false) active,c.last_run_state
FROM filtered j LEFT JOIN counts c ON c.id=j.id WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length}
)`
: selector
? `page AS MATERIALIZED (
SELECT j.*,0::integer running_count,false active,NULL::text last_run_state
FROM filtered j WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length}
)`
: `page_core AS MATERIALIZED (
SELECT j.* FROM filtered j WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length}
), counts AS MATERIALIZED (
SELECT p.id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::integer running_count,
bool_or(r.state IN ('reserved','starting','running','blocked','stopping')) active,
${lastRunState} last_run_state
FROM page_core p LEFT JOIN app.job_runs r ON r.tenant_id=$1 AND r.job_id=p.id GROUP BY p.id
), page AS MATERIALIZED (
SELECT p.*,coalesce(c.running_count,0) running_count,coalesce(c.active,false) active,c.last_run_state
FROM page_core p LEFT JOIN counts c ON c.id=p.id
)`;
const result = await this.database.pool.query<SummaryRow>(`
WITH page AS MATERIALIZED (
SELECT id,project_id project_id,name,slug,enabled,model,effort,execution_config->>'agentKind' agent_kind,execution_config->>'executionType' execution_type,
concurrency_limit,created_at,updated_at
FROM app.jobs WHERE tenant_id=$1 AND ($2::uuid IS NULL OR ($7='updated' OR id<$2))
AND ($3='' OR strpos(lower(name),lower($3))>0 OR strpos(lower(slug),lower($3))>0)
AND ($4::boolean IS NULL OR enabled=$4)
AND ($5::uuid IS NULL OR project_id=$5)
ORDER BY ${sort === "updated" ? "updated_at DESC,id DESC" : "id DESC"} LIMIT $6
)
SELECT p.*,s.running_count,s.last_run_state FROM page p
${selector ? "LEFT JOIN LATERAL (SELECT '0'::text running_count,NULL::text last_run_state) s ON true" : `LEFT JOIN LATERAL (
SELECT
(SELECT count(*)::text FROM app.job_runs active
WHERE active.tenant_id=$1 AND active.job_id=p.id
AND active.state IN ('reserved','starting','running','blocked','stopping')) running_count,
(SELECT latest.state FROM app.job_runs latest
WHERE latest.tenant_id=$1 AND latest.job_id=p.id
ORDER BY latest.created_at DESC,latest.id DESC LIMIT 1) last_run_state
) s ON true`}
ORDER BY ${sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.id DESC"}`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.projectId ?? null, input.limit + 1, sort]);
WITH filtered AS ${sortsByRunCount ? "MATERIALIZED" : ""} (
SELECT j.id,j.project_id,j.name,j.slug,j.enabled,j.model,j.effort,j.execution_config->>'agentKind' agent_kind,
j.execution_config->>'executionType' execution_type,j.concurrency_limit,j.created_at,j.updated_at
FROM app.jobs j WHERE ${clauses.join(" AND ")}
), ${summaryPages}
SELECT p.* FROM page p ORDER BY ${sort === "active" ? `p.active DESC, p.name COLLATE "en-US-x-icu" ASC, p.id ASC` : sort === "running" ? `p.running_count ${direction.toUpperCase()}, p.name COLLATE "en-US-x-icu" ASC, p.id ASC` : sort === "title" ? `p.name COLLATE "en-US-x-icu" ${direction.toUpperCase()}, p.id ASC` : sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.id DESC"}`, values);
const rows = result.rows.slice(0, input.limit);
const last = rows.at(-1);
const nextCursor = result.rows.length <= input.limit || !last ? null : sort === "active"
? encodeCursor([sort, direction, last.active, last.name, last.id])
: sort === "running"
? encodeCursor([sort, direction, Number(last.running_count), last.name, last.id])
: sort === "title"
? encodeCursor([sort, direction, last.name, last.id])
: sort === "updated"
? last.id
: last.id;
return {
items: rows.map(row => ({ id: row.id, projectId: row.project_id, name: row.name, slug: row.slug, enabled: row.enabled,
...(selector ? {} : { model: row.model, effort: row.effort, agentKind: row.agent_kind, executionType: row.execution_type ?? "agent",
concurrencyLimit: row.concurrency_limit, runningCount: Number(row.running_count ?? 0), lastRunState: row.last_run_state ?? null,
createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }) })),
nextCursor: result.rows.length > input.limit ? rows.at(-1)!.id : null,
nextCursor,
};
}
}
1 change: 1 addition & 0 deletions packages/api/test/api-boundary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ describe("Worker OpenAPI request/response boundaries", () => {
await assertResponse(await request("GET", path + "?limit=2&q=Review&enabled=true"), "GET", path, 200);
await assertResponse(await request("GET", path + "?limit=101"), "GET", path, 400);
await assertResponse(await request("GET", path + "?cursor=broken"), "GET", path, 400);
await assertResponse(await request("GET", path + "?sort=title&cursor=00000000-0000-4000-8000-000000000001"), "GET", path, 400);
await assertResponse(await request("GET", path, undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", path, 403);
}
expect(summaries).toHaveBeenCalledWith({ limit: 2, q: "Review", enabled: "true" }, true);
Expand Down
Loading
Loading