Skip to content
Open
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: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules
.next
.dist
.DS_Store
.env
.env.local
*.log
coverage
30 changes: 30 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "ai-image-studio-api",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "vitest run"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"uuid": "^9.0.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.12.12",
"@types/swagger-ui-express": "^4.1.6",
"@types/uuid": "^9.0.8",
"tsx": "^4.11.2",
"typescript": "^5.4.5",
"vitest": "^1.6.0"
}
}
135 changes: 135 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import express from "express";
import cors from "cors";
import swaggerUi from "swagger-ui-express";
import { z } from "zod";
import { JobService } from "./jobs/service";
import { JobStore } from "./jobs/store";
import { JobType } from "./jobs/types";
import { openapiSpec } from "./openapi";

const app = express();
const port = process.env.PORT ? Number(process.env.PORT) : 4000;

app.use(cors());
app.use(express.json({ limit: "2mb" }));

const store = new JobStore();
const service = new JobService(store);

/**
* @openapi
* /health:
* get:
* summary: Health check
* responses:
* 200:
* description: OK
*/
app.get("/health", (_req, res) => {
res.json({ status: "ok" });
});

/**
* @openapi
* /jobs:
* post:
* summary: Create a new generation or edit job
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* type:
* type: string
* enum: [txt2img, img2img, inpaint, outpaint, upscale, bgremove]
* input:
* type: object
* responses:
* 201:
* description: Job created
*/
app.post("/jobs", (req, res) => {
const schema = z.object({
type: z.enum(["txt2img", "img2img", "inpaint", "outpaint", "upscale", "bgremove"]),
input: z.record(z.unknown()).default({})
});

const parsed = schema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
}

const job = service.createJob(parsed.data.type as JobType, parsed.data.input);
return res.status(201).json(job);
});

/**
* @openapi
* /jobs:
* get:
* summary: List jobs
* responses:
* 200:
* description: Job list
*/
app.get("/jobs", (_req, res) => {
res.json(service.listJobs());
});

/**
* @openapi
* /jobs/{id}:
* get:
* summary: Get job status
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Job details
* 404:
* description: Not found
*/
app.get("/jobs/:id", (req, res) => {
const job = service.getJob(req.params.id);
if (!job) {
return res.status(404).json({ error: "Job not found" });
}
return res.json(job);
});

/**
* @openapi
* /jobs/{id}/cancel:
* post:
* summary: Cancel a job
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Job canceled
* 404:
* description: Not found
*/
app.post("/jobs/:id/cancel", (req, res) => {
const job = service.cancelJob(req.params.id);
if (!job) {
return res.status(404).json({ error: "Job not found" });
}
return res.json(job);
});

app.use("/docs", swaggerUi.serve, swaggerUi.setup(openapiSpec));

app.listen(port, () => {
console.log(`API listening on http://localhost:${port}`);
});
93 changes: 93 additions & 0 deletions apps/api/src/jobs/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { v4 as uuidv4 } from "uuid";
import { JobRecord, JobStatus, JobType } from "./types";
import { JobStore } from "./store";
import { buildMockResult } from "../providers/mock";

const randomDuration = () => 3000 + Math.floor(Math.random() * 4000);

export class JobService {
private readonly timers = new Map<string, NodeJS.Timeout>();

constructor(private readonly store: JobStore) {}

createJob(type: JobType, input: Record<string, unknown>): JobRecord {
const id = uuidv4();
const now = new Date().toISOString();
const job: JobRecord = {
id,
type,
status: "queued",
progress: 0,
input,
createdAt: now
};

this.store.create(job);
this.startJob(id);
return job;
}

cancelJob(id: string): JobRecord | undefined {
const current = this.store.get(id);
if (!current || current.status === "succeeded" || current.status === "failed") {
return current;
}
const timer = this.timers.get(id);
if (timer) {
clearInterval(timer);
this.timers.delete(id);
}
return this.store.update(id, (job) => ({
...job,
status: "canceled",
finishedAt: new Date().toISOString()
}));
}

getJob(id: string): JobRecord | undefined {
return this.store.get(id);
}

listJobs(): JobRecord[] {
return this.store.list();
}

private startJob(id: string): void {
const duration = randomDuration();
const interval = 500;
const steps = Math.ceil(duration / interval);
let tick = 0;

this.store.update(id, (job) => ({
...job,
status: "running",
startedAt: new Date().toISOString()
}));

const timer = setInterval(() => {
tick += 1;
const progress = Math.min(100, Math.round((tick / steps) * 100));
const status: JobStatus = progress >= 100 ? "succeeded" : "running";

const next = this.store.update(id, (job) => {
if (job.status === "canceled") {
return job;
}
return {
...job,
status,
progress,
output: progress >= 100 ? buildMockResult(job.type, job.id) : job.output,
finishedAt: progress >= 100 ? new Date().toISOString() : job.finishedAt
};
});

if (!next || next.status === "canceled" || status === "succeeded") {
clearInterval(timer);
this.timers.delete(id);
}
}, interval);

this.timers.set(id, timer);
}
}
27 changes: 27 additions & 0 deletions apps/api/src/jobs/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { JobRecord } from "./types";

export class JobStore {
private readonly jobs = new Map<string, JobRecord>();

create(job: JobRecord): void {
this.jobs.set(job.id, job);
}

update(id: string, updater: (current: JobRecord) => JobRecord): JobRecord | undefined {
const current = this.jobs.get(id);
if (!current) {
return undefined;
}
const next = updater(current);
this.jobs.set(id, next);
return next;
}

get(id: string): JobRecord | undefined {
return this.jobs.get(id);
}

list(): JobRecord[] {
return Array.from(this.jobs.values());
}
}
18 changes: 18 additions & 0 deletions apps/api/src/jobs/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export type JobStatus = "queued" | "running" | "succeeded" | "failed" | "canceled";

export type JobType = "txt2img" | "img2img" | "inpaint" | "outpaint" | "upscale" | "bgremove";

export interface JobRecord {
id: string;
type: JobType;
status: JobStatus;
progress: number;
input: Record<string, unknown>;
output?: {
images: Array<{ url: string; content?: string }>;
};
error?: string;
createdAt: string;
startedAt?: string;
finishedAt?: string;
}
13 changes: 13 additions & 0 deletions apps/api/src/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import swaggerJsdoc from "swagger-jsdoc";

export const openapiSpec = swaggerJsdoc({
definition: {
openapi: "3.0.0",
info: {
title: "AI Image Studio API",
version: "0.1.0",
description: "Minimal API for AI Image Studio MVP."
}
},
apis: ["./src/index.ts"]
});
18 changes: 18 additions & 0 deletions apps/api/src/providers/mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { JobType } from "../jobs/types";

export interface MockGenerationResult {
images: Array<{ url: string; content?: string }>;
}

export const buildMockResult = (jobType: JobType, seed: string): MockGenerationResult => {
const label = `${jobType.toUpperCase()} preview`;
const size = jobType === "upscale" ? "1024" : "768";
return {
images: [
{
url: `https://picsum.photos/seed/${encodeURIComponent(seed)}/${size}/${size}`,
content: label
}
]
};
};
37 changes: 37 additions & 0 deletions apps/api/tests/job-store.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { JobStore } from "../src/jobs/store";
import { JobRecord } from "../src/jobs/types";

const createJob = (id: string): JobRecord => ({
id,
type: "txt2img",
status: "queued",
progress: 0,
input: {},
createdAt: new Date().toISOString()
});

describe("JobStore", () => {
it("creates and retrieves jobs", () => {
const store = new JobStore();
const job = createJob("job-1");

store.create(job);

expect(store.get("job-1")).toEqual(job);
});

it("updates jobs", () => {
const store = new JobStore();
const job = createJob("job-2");

store.create(job);

const updated = store.update("job-2", (current) => ({
...current,
progress: 42
}));

expect(updated?.progress).toBe(42);
});
});
Loading