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
7 changes: 6 additions & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4158,6 +4158,7 @@ export interface operations {
cursor?: string;
q?: string;
enabled?: "true" | "false";
sort?: "id" | "updated";
};
header?: never;
path?: never;
Expand Down Expand Up @@ -4211,6 +4212,7 @@ export interface operations {
cursor?: string;
q?: string;
enabled?: "true" | "false";
sort?: "id" | "updated";
};
header?: never;
path?: never;
Expand Down Expand Up @@ -4248,7 +4250,10 @@ export interface operations {
};
get_api_v1_projects: {
parameters: {
query?: never;
query?: {
limit?: number;
sort?: "name" | "updated";
};
header?: never;
path?: never;
cookie?: never;
Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { exeConnection, integrationStatus, authorizedClient, accessToken, create
import { executionTargetResponse, triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts";
import { runSummaryResponse, runPageResponse, runStatusResponse, revisionTracePage, revisionTraceQuery } from "./run-read-contracts";
import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts";
import { projectInput, projectResponse } from "./project-contracts";
import { projectInput, projectListQuery, projectResponse } from "./project-contracts";
import { z } from "zod";
import type { ApiService } from "./flow-service";
import {
Expand Down Expand Up @@ -669,7 +669,8 @@ export const API_ROUTES: RouteContract[] = [
"/api/v1/projects",
"flows:read",
{ summary: "List projects", responses: { "200": { description: "Projects", content: { "application/json": { schema: jsonSchema(z.array(projectResponse), "output") } } } } },
(service) => service.listProjects(),
(service, { query }) => service.listProjects(query),
{ query: projectListQuery },
),
route("POST", "/api/v1/projects", "flows:write", { summary: "Create project", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { body }) => service.createProject(body), { body: projectInput }),
route("GET", "/api/v1/projects/{projectId}", "flows:read", { summary: "Get project", responses: { "200": { description: "Project", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params }) => service.getProject(params.projectId)),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export class ApiService {
async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); }
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() { await this.authorize("projects:read"); return this.projects().list(); }
async listProjects(options?: { limit?: number; sort?: "name" | "updated" }) { await this.authorize("projects:read"); return this.projects().list(options); }
async getProject(projectId: string) { await this.authorize("projects:read"); const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); return project; }
async createProject(input: { name: string; description?: string }) { await this.authorize("projects:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } }
async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("projects:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; }
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/job-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const jobPageQuery = z.object({
cursor: z.guid().optional(),
q: z.string().trim().max(120).default(""),
enabled: z.enum(["true", "false"]).optional(),
sort: z.enum(["id", "updated"]).optional(),
});
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 Down
7 changes: 4 additions & 3 deletions packages/api/src/postgres/job-summary-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,24 @@ export class JobSummaryRepository {
if (!tenantId) throw new Error("tenantId is required");
}
async page(input: JobPageQuery, selector = false) {
const sort = input.sort ?? "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_target->>'agentKind' agent_kind,
concurrency_limit,created_at,updated_at
FROM app.jobs WHERE tenant_id=$1 AND ($2::uuid IS NULL OR id<$2)
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 id DESC LIMIT $6
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 (
SELECT r.job_id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::text running_count,
(array_agg(r.state ORDER BY r.created_at DESC,r.id DESC))[1] last_run_state
FROM app.job_runs r JOIN page ON page.id=r.job_id WHERE r.tenant_id=$1 GROUP BY r.job_id
) s ON s.job_id=p.id`}
ORDER BY p.id DESC`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.projectId ?? null, input.limit + 1]);
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]);
const rows = result.rows.slice(0, input.limit);
return {
items: rows.map(row => ({ id: row.id, projectId: row.project_id, name: row.name, slug: row.slug, enabled: row.enabled,
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/postgres/project-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export interface Project { id: string; name: string; description?: string; creat
export class ProjectRepository {
constructor(private database: Database, private tenantId: string) {}
private map(row: any): Project { return { id: row.id, name: row.name, ...(row.description ? { description: row.description } : {}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), jobCount: Number(row.job_count ?? 0) }; }
async list() { const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 GROUP BY p.tenant_id,p.id ORDER BY p.name,p.id`, [this.tenantId]); return result.rows.map(row => this.map(row)); }
async list(options: { limit?: number; sort?: "name" | "updated" } = {}) { const limit = Math.max(1, Math.min(100, options.limit ?? 100)); const order = options.sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.name,p.id"; const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 GROUP BY p.tenant_id,p.id ORDER BY ${order} LIMIT $2`, [this.tenantId, limit]); return result.rows.map(row => this.map(row)); }
async get(id: string) { const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 AND p.id=$2 GROUP BY p.tenant_id,p.id`, [this.tenantId,id]); return result.rows[0] ? this.map(result.rows[0]) : null; }
async defaultProjectId() { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,md5(($1::uuid)::text || ':default')::uuid,'Default','Jobs created by legacy clients') ON CONFLICT (tenant_id,name) DO UPDATE SET updated_at=app.projects.updated_at RETURNING id`, [this.tenantId]); return result.rows[0].id as string; }
async create(name: string, description?: string) { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,gen_random_uuid(),$2,$3) RETURNING *`, [this.tenantId,name.trim(),description?.trim() || null]); return this.map({ ...result.rows[0], job_count: 0 }); }
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/project-contracts.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { z } from "zod";
export const projectResponse = z.object({ id: z.guid(), name: z.string(), description: z.string().optional(), createdAt: z.string(), updatedAt: z.string(), jobCount: z.number().int() });
export const projectListQuery = z.object({
limit: z.coerce.number().int().min(1).max(100).default(100),
sort: z.enum(["name", "updated"]).default("name"),
});
export const projectInput = z.object({ name: z.string().trim().min(1).max(120), description: z.string().trim().max(2000).optional() }).strict();
1 change: 1 addition & 0 deletions packages/app/src/features/jobs/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const jobsQuery = (search: JobsSearch) => queryOptions({
return { items: page, nextCursor: start + 30 < items.length ? page.at(-1)!.id : null };
}, staleTime: 10_000,
});
export const recentJobsQuery = queryOptions({ queryKey: ["jobs", "recent"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/job-summaries", { signal, params: { query: { limit: 5, sort: "updated", q: "" } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 });
export const jobQuery = (jobId: string) => queryOptions({
queryKey: ["jobs", "detail", jobId],
queryFn: async ({ signal }) => {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/features/projects/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ import { api } from "factorize-api-client";
import { queryOptions } from "@tanstack/react-query";
import { messageOf } from "../auth/session";
export const projectsQuery = queryOptions({ queryKey: ["projects"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/projects", { signal }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 });
export const recentProjectsQuery = queryOptions({ queryKey: ["projects", "recent"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/projects", { signal, params: { query: { limit: 5, sort: "updated" } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 });
export const projectQuery = (projectId: string) => queryOptions({ queryKey: ["projects", projectId], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/projects/{projectId}", { signal, params: { path: { projectId } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 });
19 changes: 17 additions & 2 deletions packages/app/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
import { Card, Page } from "../shared/ui";
import { Badge, Card, Page, RunStatusDot } from "../shared/ui";
import { Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { sessionQuery } from "../features/auth/session";
import { recentProjectsQuery } from "../features/projects/queries";
import { recentJobsQuery } from "../features/jobs/queries";
import { runPageQuery } from "../features/runs/queries";
import type { ReactNode } from "react";

const timestamp = (value: string) => new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
function RecentSection({ title, children, empty }: { title: string; children: ReactNode; empty: string }) {
return <Card><h2 className="text-lg font-semibold">{title}</h2>{children || <p className="mt-4 text-sm text-slate-600 dark:text-slate-400">{empty}</p>}</Card>;
}
function RecentDashboard() {
const projects = useQuery(recentProjectsQuery), jobs = useQuery(recentJobsQuery), runs = useQuery(runPageQuery({ limit: 5 }));
const error = projects.error || jobs.error || runs.error;
return <Page><div className="mb-8"><p className="mb-2 text-xs font-semibold uppercase tracking-widest text-factorize-700 dark:text-factorize-500">Your software factory</p><h1>Recent work</h1><p className="mt-2 text-slate-600 dark:text-slate-400">Pick up where you left off.</p></div>{error && <p className="mb-6" role="alert">{error.message}</p>}<div className="grid gap-5 lg:grid-cols-3"><RecentSection title="Recent projects" empty="Projects you update will appear here.">{projects.data?.length ? <ul className="mt-4 divide-y divide-stone-200 dark:divide-slate-800">{projects.data.map(project => <li key={project.id} className="py-3 first:pt-0 last:pb-0"><Link to="/projects/$projectId" params={{ projectId: project.id }} className="block rounded-md hover:text-factorize-700"><span className="font-semibold">{project.name}</span><span className="mt-1 block text-xs text-slate-500">{project.jobCount} {project.jobCount === 1 ? "job" : "jobs"} · Updated {timestamp(project.updatedAt)}</span></Link></li>)}</ul> : null}</RecentSection><RecentSection title="Recent jobs" empty="Jobs you update will appear here.">{jobs.data?.items.length ? <ul className="mt-4 divide-y divide-stone-200 dark:divide-slate-800">{jobs.data.items.map(job => <li key={job.id} className="py-3 first:pt-0 last:pb-0"><Link to="/jobs/$jobId" params={{ jobId: job.id }} className="block rounded-md hover:text-factorize-700"><span className="font-semibold">{job.name}</span><span className="mt-1 block text-xs text-slate-500">{job.lastRunState ? <><RunStatusDot state={job.lastRunState} decorative /> <span className="ml-1">{job.lastRunState}</span> · </> : "No runs · "}Updated {timestamp(job.updatedAt)}</span></Link></li>)}</ul> : null}</RecentSection><RecentSection title="Recent runs" empty="Runs from your jobs will appear here.">{runs.data?.items.length ? <ul className="mt-4 divide-y divide-stone-200 dark:divide-slate-800">{runs.data.items.map(run => <li key={run.id} className="py-3 first:pt-0 last:pb-0"><Link to="/job-runs/$runId" params={{ runId: run.id }} className="block rounded-md hover:text-factorize-700"><span className="font-semibold">{run.run_name || "Unnamed run"}</span><span className="mt-1 block text-xs text-slate-500"><Badge>{run.state}</Badge><span className="ml-2">{run.job_name} · {timestamp(run.created_at)}</span></span></Link></li>)}</ul> : null}</RecentSection></div></Page>;
}
export function MigrationIndex() {
const session = useQuery(sessionQuery);
if (session.data?.authenticated) return <RecentDashboard />;
return <Page className="mx-auto max-w-3xl p-6"><Card className="mx-auto my-8 max-w-xl"><p className="mb-2 text-xs font-semibold uppercase tracking-widest text-factorize-700 dark:text-factorize-500">Your software factory</p><h1>Welcome to Factorize</h1><p className="mb-6 text-slate-600 dark:text-slate-400">Connect your tools, configure your jobs, and follow every run.</p>
{session.isPending && <p role="status">Loading your account…</p>}{session.error && <p role="alert">{session.error.message}</p>}
{session.data?.authenticated ? <p className="mt-4"><Link to="/projects">Projects</Link> · <Link to="/settings">Settings</Link></p> : <p className="mt-4"><Link to="/auth/login">Sign in</Link> · <Link to="/auth/signup">Create an account</Link></p>}
<p className="mt-4"><Link to="/auth/login">Sign in</Link> · <Link to="/auth/signup">Create an account</Link></p>
<p className="mt-4"><a href="https://factorize.sh">About Factorize</a></p>
</Card></Page>;
}
34 changes: 34 additions & 0 deletions packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5122,6 +5122,14 @@ paths:
enum:
- "true"
- "false"
- name: sort
in: query
required: false
schema:
type: string
enum:
- id
- updated
/api/v1/job-selector:
get:
summary: Search bounded lifecycle job options
Expand Down Expand Up @@ -5230,6 +5238,14 @@ paths:
enum:
- "true"
- "false"
- name: sort
in: query
required: false
schema:
type: string
enum:
- id
- updated
/api/v1/projects:
get:
summary: List projects
Expand Down Expand Up @@ -5294,6 +5310,24 @@ paths:
- cookieAuth: []
x-required-scope: projects:read
x-owner-session-required: false
parameters:
- name: limit
in: query
required: false
schema:
default: 100
type: integer
minimum: 1
maximum: 100
- name: sort
in: query
required: false
schema:
default: name
type: string
enum:
- name
- updated
post:
summary: Create project
responses:
Expand Down
Loading