diff --git a/lib/api/index.js b/lib/api/index.js index 6c13eff..81f21e1 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -10,6 +10,7 @@ import { } from './routes/tasks.js'; import { router as pagesRouter, spacesScopedRouter as pagesBySpaceRouter } from './routes/pages.js'; import { router as refsRouter } from './routes/refs.js'; +import { router as resourcesRouter, spacesScopedRouter as resourcesBySpaceRouter } from './routes/resources.js'; export function mountApi(app) { const api = Router(); @@ -19,11 +20,13 @@ export function mountApi(app) { api.use('/spaces/:space_id/projects', projectsBySpaceRouter); api.use('/spaces/:space_id/tasks', tasksBySpaceRouter); api.use('/spaces/:space_id/pages', pagesBySpaceRouter); + api.use('/spaces/:space_id/resources', resourcesBySpaceRouter); api.use('/projects', projectsRouter); api.use('/projects/:project_id/tasks', tasksByProjectRouter); api.use('/tasks', tasksRouter); api.use('/pages', pagesRouter); api.use('/refs', refsRouter); + api.use('/resources', resourcesRouter); api.use((_req, _res, next) => next(new NotFoundError('route not found'))); diff --git a/lib/api/routes/resources.js b/lib/api/routes/resources.js new file mode 100644 index 0000000..3e13008 --- /dev/null +++ b/lib/api/routes/resources.js @@ -0,0 +1,133 @@ +import { Router } from 'express'; +import { z } from 'zod'; +import * as repo from '../../db/repos/resources.js'; +import * as sourceDocs from '../../db/repos/source_docs.js'; +import * as audit from '../../db/repos/audit.js'; +import { validate } from '../validate.js'; +import { NotFoundError, ValidationError, ConflictError, asyncWrap } from '../errors.js'; + +const RUNTIME = ['lxc', 'vm', 'docker', 'bare-metal']; +const STATUSES = ['running', 'stopped', 'down', 'unknown']; + +const baseFields = { + slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/), + name: z.string().min(1).max(200), + runtime_type: z.enum(RUNTIME), + host: z.string().nullable().optional(), + url: z.string().nullable().optional(), + version: z.string().nullable().optional(), + status: z.enum(STATUSES).optional(), + monitoring: z.record(z.string(), z.any()).nullable().optional(), + metadata: z.record(z.string(), z.any()).nullable().optional(), + last_check: z.string().datetime().nullable().optional(), + maintenance_until: z.string().datetime().nullable().optional() +}; + +const createSchema = z.object(baseFields); +const patchSchema = z.object(Object.fromEntries( + Object.entries(baseFields).map(([k, v]) => [k, v.optional()]) +)); + +const idParams = z.object({ id: z.string().uuid() }); +const spaceParams = z.object({ space_id: z.string().uuid() }); +const depParams = z.object({ id: z.string().uuid(), dep_id: z.string().uuid() }); +const depBody = z.object({ + depends_on: z.string().uuid(), + kind: z.string().nullable().optional() +}); + +export const router = Router(); +export const spacesScopedRouter = Router({ mergeParams: true }); + +spacesScopedRouter.get('/', + validate({ params: spaceParams }), + asyncWrap(async (req, res) => { res.json(await repo.listBySpace(req.params.space_id)); }) +); + +spacesScopedRouter.post('/', + validate({ params: spaceParams, body: createSchema }), + asyncWrap(async (req, res) => { + try { + const row = await repo.create({ ...req.body, space_id: req.params.space_id }, req.actor); + res.status(201).json(row); + } catch (e) { + if (e.code === '23503') throw new ValidationError('invalid space', { space_id: req.params.space_id }); + throw e; + } + }) +); + +router.get('/:id', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + const row = await repo.getById(req.params.id); + if (!row) throw new NotFoundError('resource not found'); + res.json(row); + }) +); + +router.patch('/:id', + validate({ params: idParams, body: patchSchema }), + asyncWrap(async (req, res) => { + const existing = await repo.getById(req.params.id); + if (!existing) throw new NotFoundError('resource not found'); + res.json(await repo.update(req.params.id, req.body, req.actor)); + }) +); + +router.delete('/:id', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + const existing = await repo.getById(req.params.id); + if (!existing) throw new NotFoundError('resource not found'); + await repo.del(req.params.id, req.actor); + res.status(204).end(); + }) +); + +router.post('/:id/dependencies', + validate({ params: idParams, body: depBody }), + asyncWrap(async (req, res) => { + if (req.params.id === req.body.depends_on) { + throw new ValidationError('resource cannot depend on itself'); + } + try { + await repo.addDependency(req.params.id, req.body.depends_on, req.body.kind); + res.status(201).json({ resource_id: req.params.id, depends_on: req.body.depends_on }); + } catch (e) { + if (e.code === '23503') throw new ConflictError('cross-space or unknown resource', { + resource_id: req.params.id, depends_on: req.body.depends_on, hint: 'dependencies must share a space_id' + }); + throw e; + } + }) +); + +router.get('/:id/dependencies', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + res.json(await repo.listDependencies(req.params.id)); + }) +); + +router.delete('/:id/dependencies/:dep_id', + validate({ params: depParams }), + asyncWrap(async (req, res) => { + await repo.removeDependency(req.params.id, req.params.dep_id); + res.status(204).end(); + }) +); + +router.get('/:id/source-docs', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + res.json(await sourceDocs.listByResource(req.params.id)); + }) +); + +router.get('/:id/changes', + validate({ params: idParams }), + asyncWrap(async (req, res) => { + res.json(await audit.listForEntity('resource', req.params.id)); + }) +); diff --git a/tests/api/resources.test.js b/tests/api/resources.test.js new file mode 100644 index 0000000..a364d17 --- /dev/null +++ b/tests/api/resources.test.js @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; +import request from 'supertest'; +import { setup } from './helpers.js'; +import * as spaces from '../../lib/db/repos/spaces.js'; + +let app, ownerHeaders, space, otherSpace; +const owner = { kind: 'user', id: null }; + +async function makeResource(spaceId, slug) { + const res = await request(app).post(`/api/spaces/${spaceId}/resources`).set(ownerHeaders) + .send({ slug, name: slug, runtime_type: 'lxc' }); + return res.body; +} + +beforeAll(async () => { ({ app, ownerHeaders } = await setup()); }); +beforeEach(async () => { + space = await spaces.create({ slug: `s-${Date.now()}-${Math.random().toString(36).slice(2,5)}`, name: 'S' }, owner); + otherSpace = await spaces.create({ slug: `o-${Date.now()}-${Math.random().toString(36).slice(2,5)}`, name: 'O' }, owner); +}); + +describe('resources routes', () => { + it('POST creates and lists by space', async () => { + const r = await makeResource(space.id, 'svc'); + expect(r.runtime_type).toBe('lxc'); + const list = await request(app).get(`/api/spaces/${space.id}/resources`).set(ownerHeaders); + expect(list.body.length).toBe(1); + }); + + it('PATCH updates status', async () => { + const r = await makeResource(space.id, 'svc2'); + const res = await request(app).patch(`/api/resources/${r.id}`).set(ownerHeaders) + .send({ status: 'running' }); + expect(res.body.status).toBe('running'); + }); + + it('POST dependencies rejects self-dependency', async () => { + const r = await makeResource(space.id, 'self'); + const res = await request(app).post(`/api/resources/${r.id}/dependencies`).set(ownerHeaders) + .send({ depends_on: r.id }); + expect(res.status).toBe(400); + }); + + it('POST dependencies rejects cross-space → 409', async () => { + const a = await makeResource(space.id, 'a'); + const b = await makeResource(otherSpace.id, 'b'); + const res = await request(app).post(`/api/resources/${a.id}/dependencies`).set(ownerHeaders) + .send({ depends_on: b.id }); + expect(res.status).toBe(409); + expect(res.body.error.code).toBe('conflict'); + }); + + it('list + remove dependency', async () => { + const a = await makeResource(space.id, 'svc-a'); + const b = await makeResource(space.id, 'svc-b'); + await request(app).post(`/api/resources/${a.id}/dependencies`).set(ownerHeaders) + .send({ depends_on: b.id, kind: 'hard' }); + const list = await request(app).get(`/api/resources/${a.id}/dependencies`).set(ownerHeaders); + expect(list.body.length).toBe(1); + expect(list.body[0].depends_on).toBe(b.id); + const del = await request(app).delete(`/api/resources/${a.id}/dependencies/${b.id}`).set(ownerHeaders); + expect(del.status).toBe(204); + const after = await request(app).get(`/api/resources/${a.id}/dependencies`).set(ownerHeaders); + expect(after.body.length).toBe(0); + }); + + it('GET /:id/changes returns audit history', async () => { + const r = await makeResource(space.id, 'audited'); + await request(app).patch(`/api/resources/${r.id}`).set(ownerHeaders).send({ status: 'running' }); + const res = await request(app).get(`/api/resources/${r.id}/changes`).set(ownerHeaders); + expect(res.status).toBe(200); + expect(res.body.length).toBe(2); // create + update + }); +});