Compare commits
41 Commits
v1.5.0
...
53fbcbe22c
| Author | SHA1 | Date | |
|---|---|---|---|
| 53fbcbe22c | |||
| e330119753 | |||
| 72b8d60985 | |||
| 917fb26e05 | |||
| a28867b398 | |||
| ac71ea2c49 | |||
| efa1750cac | |||
| aa6e28d818 | |||
| 2cf797545c | |||
| a0381b12cc | |||
| 64eacb28d2 | |||
| ea671535fc | |||
| fb3c6405c9 | |||
| b6ca460ac6 | |||
| 8312701147 | |||
| edf6f674b3 | |||
| a8d367b4be | |||
| 5ca0b648ca | |||
| 518ed42f60 | |||
| a9147b0198 | |||
| 2e3484b1d9 | |||
| cb83d11261 | |||
| 047fd0653e | |||
| 027ed52768 | |||
| e2935c58c8 | |||
| 1bbe743dba | |||
| d88b79e9f0 | |||
| 8a9de6d72a | |||
| ddd528a682 | |||
| 03cf2aa9c6 | |||
| d84674b0c6 | |||
| 7999f46ca2 | |||
| 307c5cf9e8 | |||
| 34af8e5a8f | |||
| 76d2bffb4f | |||
| 64de0e432c | |||
| a5b409a348 | |||
| 8f35724bde | |||
| cec82a3347 | |||
| 883e59789b | |||
| 817fdaef13 |
@@ -153,6 +153,8 @@ main { flex: 1; }
|
||||
}
|
||||
|
||||
.stat-cell:last-child { border-right: none; }
|
||||
.stat-clickable { cursor: pointer; user-select: none; }
|
||||
.stat-clickable:hover { background: var(--bg2); }
|
||||
|
||||
.stat-label {
|
||||
font-size: 10px;
|
||||
|
||||
@@ -48,6 +48,13 @@
|
||||
<select id="filter-stack" onchange="filterInstances()">
|
||||
<option value="">all stacks</option>
|
||||
</select>
|
||||
<select id="sort-field" onchange="filterInstances()">
|
||||
<option value="name">name</option>
|
||||
<option value="vmid">vmid</option>
|
||||
<option value="updated_at">last updated</option>
|
||||
<option value="created_at">last created</option>
|
||||
</select>
|
||||
<button id="sort-dir" class="btn" data-dir="asc" onclick="toggleSortDir()" title="reverse sort">↑</button>
|
||||
<div class="toolbar-right">
|
||||
<button class="btn primary" onclick="openNewModal()">+ new instance</button>
|
||||
</div>
|
||||
|
||||
@@ -53,4 +53,6 @@ if (VERSION) {
|
||||
document.getElementById('nav-version').textContent = label;
|
||||
}
|
||||
|
||||
fetch('/api/jobs').then(r => r.json()).then(_updateJobsNavDot).catch(() => {});
|
||||
|
||||
handleRoute();
|
||||
|
||||
@@ -71,10 +71,10 @@ async function renderDashboard() {
|
||||
all.forEach(i => { states[i.state] = (states[i.state] || 0) + 1; });
|
||||
|
||||
document.getElementById('stats-bar').innerHTML = `
|
||||
<div class="stat-cell"><div class="stat-label">total</div><div class="stat-value accent">${all.length}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">deployed</div><div class="stat-value">${states['deployed'] || 0}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">testing</div><div class="stat-value amber">${states['testing'] || 0}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">degraded</div><div class="stat-value red">${states['degraded'] || 0}</div></div>
|
||||
<div class="stat-cell stat-clickable" onclick="setStateFilter('')"><div class="stat-label">total</div><div class="stat-value accent">${all.length}</div></div>
|
||||
<div class="stat-cell stat-clickable" onclick="setStateFilter('deployed')"><div class="stat-label">deployed</div><div class="stat-value">${states['deployed'] || 0}</div></div>
|
||||
<div class="stat-cell stat-clickable" onclick="setStateFilter('testing')"><div class="stat-label">testing</div><div class="stat-value amber">${states['testing'] || 0}</div></div>
|
||||
<div class="stat-cell stat-clickable" onclick="setStateFilter('degraded')"><div class="stat-label">degraded</div><div class="stat-value red">${states['degraded'] || 0}</div></div>
|
||||
`;
|
||||
|
||||
await populateStackFilter();
|
||||
@@ -95,11 +95,26 @@ async function populateStackFilter() {
|
||||
});
|
||||
}
|
||||
|
||||
function setStateFilter(state) {
|
||||
document.getElementById('filter-state').value = state;
|
||||
filterInstances();
|
||||
}
|
||||
|
||||
function toggleSortDir() {
|
||||
const btn = document.getElementById('sort-dir');
|
||||
const next = btn.dataset.dir === 'asc' ? 'desc' : 'asc';
|
||||
btn.dataset.dir = next;
|
||||
btn.textContent = next === 'asc' ? '↑' : '↓';
|
||||
filterInstances();
|
||||
}
|
||||
|
||||
async function filterInstances() {
|
||||
const search = document.getElementById('search-input').value;
|
||||
const state = document.getElementById('filter-state').value;
|
||||
const stack = document.getElementById('filter-stack').value;
|
||||
const instances = await getInstances({ search, state, stack });
|
||||
const sort = document.getElementById('sort-field').value;
|
||||
const order = document.getElementById('sort-dir').dataset.dir || 'asc';
|
||||
const instances = await getInstances({ search, state, stack, sort, order });
|
||||
const grid = document.getElementById('instance-grid');
|
||||
|
||||
if (!instances.length) {
|
||||
@@ -289,6 +304,10 @@ async function saveInstance() {
|
||||
hardware_acceleration: +document.getElementById('f-hardware-accel').checked,
|
||||
};
|
||||
|
||||
// Snapshot job state before creation — jobs fire immediately after the 201
|
||||
// so the baseline must be captured before the POST, not after.
|
||||
const jobBaseline = !editingVmid ? await _snapshotJobBaseline() : null;
|
||||
|
||||
const result = editingVmid
|
||||
? await updateInstance(editingVmid, data)
|
||||
: await createInstance(data);
|
||||
@@ -298,6 +317,8 @@ async function saveInstance() {
|
||||
showToast(`${name} ${editingVmid ? 'updated' : 'created'}`, 'success');
|
||||
closeModal();
|
||||
|
||||
if (jobBaseline) await _waitForOnCreateJobs(jobBaseline);
|
||||
|
||||
if (currentVmid && document.getElementById('page-detail').classList.contains('active')) {
|
||||
await renderDetailPage(vmid);
|
||||
} else {
|
||||
@@ -305,6 +326,30 @@ async function saveInstance() {
|
||||
}
|
||||
}
|
||||
|
||||
async function _snapshotJobBaseline() {
|
||||
const jobs = await fetch('/api/jobs').then(r => r.json());
|
||||
return new Map(jobs.map(j => [j.id, j.last_run_id ?? null]));
|
||||
}
|
||||
|
||||
async function _waitForOnCreateJobs(baseline) {
|
||||
const jobs = await fetch('/api/jobs').then(r => r.json());
|
||||
const relevant = jobs.filter(j => (j.config ?? {}).run_on_create);
|
||||
if (!relevant.length) return;
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
const current = await fetch('/api/jobs').then(r => r.json());
|
||||
const allDone = relevant.every(j => {
|
||||
const cur = current.find(c => c.id === j.id);
|
||||
if (!cur) return true;
|
||||
if (cur.last_run_id === baseline.get(j.id)) return false; // new run not started yet
|
||||
return cur.last_status !== 'running'; // new run complete
|
||||
});
|
||||
if (allDone) return;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Confirm Dialog ────────────────────────────────────────────────────────────
|
||||
|
||||
function confirmDeleteDialog(inst) {
|
||||
@@ -463,6 +508,13 @@ async function loadJobDetail(jobId) {
|
||||
<label class="form-label" for="job-schedule">Poll interval (minutes)</label>
|
||||
<input class="form-input" id="job-schedule" type="number" min="1" value="${job.schedule}" style="max-width:100px">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label" style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="job-run-on-create" ${cfg.run_on_create ? 'checked' : ''}
|
||||
style="accent-color:var(--accent);width:13px;height:13px">
|
||||
Run on instance creation
|
||||
</label>
|
||||
</div>
|
||||
${_renderJobConfigFields(job.key, cfg)}
|
||||
<div class="job-actions">
|
||||
<button class="btn btn-secondary" onclick="saveJobDetail(${job.id})">Save</button>
|
||||
@@ -487,6 +539,7 @@ function _renderJobConfigFields(key, cfg) {
|
||||
</div>`;
|
||||
if (key === 'patchmon_sync' || key === 'semaphore_sync') {
|
||||
const label = key === 'semaphore_sync' ? 'API Token (Bearer)' : 'API Token (Basic)';
|
||||
const tokenPlaceholder = key === 'patchmon_sync' ? 'token_key:token_secret' : '';
|
||||
return `
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="job-cfg-api-url">API URL</label>
|
||||
@@ -496,6 +549,7 @@ function _renderJobConfigFields(key, cfg) {
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="job-cfg-api-token">${label}</label>
|
||||
<input class="form-input" id="job-cfg-api-token" type="password"
|
||||
placeholder="${tokenPlaceholder}"
|
||||
value="${esc(cfg.api_token ?? '')}">
|
||||
</div>`;
|
||||
}
|
||||
@@ -521,10 +575,12 @@ async function saveJobDetail(jobId) {
|
||||
const apiKey = document.getElementById('job-cfg-api-key');
|
||||
const apiUrl = document.getElementById('job-cfg-api-url');
|
||||
const apiToken = document.getElementById('job-cfg-api-token');
|
||||
if (tailnet) cfg.tailnet = tailnet.value.trim();
|
||||
if (apiKey) cfg.api_key = apiKey.value;
|
||||
if (apiUrl) cfg.api_url = apiUrl.value.trim();
|
||||
if (apiToken) cfg.api_token = apiToken.value;
|
||||
if (tailnet) cfg.tailnet = tailnet.value.trim();
|
||||
if (apiKey) cfg.api_key = apiKey.value;
|
||||
if (apiUrl) cfg.api_url = apiUrl.value.trim();
|
||||
if (apiToken) cfg.api_token = apiToken.value;
|
||||
const runOnCreate = document.getElementById('job-run-on-create');
|
||||
if (runOnCreate) cfg.run_on_create = runOnCreate.checked;
|
||||
const res = await fetch(`/api/jobs/${jobId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
const VERSION = "1.5.0";
|
||||
const VERSION = "1.7.1";
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "catalyst",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node server/server.js",
|
||||
|
||||
+40
-9
@@ -6,6 +6,8 @@ import { fileURLToPath } from 'url';
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const DEFAULT_PATH = join(__dirname, '../data/catalyst.db');
|
||||
|
||||
const JOB_RUN_LIMIT = 10;
|
||||
|
||||
let db;
|
||||
|
||||
function init(path) {
|
||||
@@ -17,7 +19,7 @@ function init(path) {
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA synchronous = NORMAL');
|
||||
createSchema();
|
||||
if (path !== ':memory:') { seed(); seedJobs(); }
|
||||
if (path !== ':memory:') { seed(); seedJobs(); pruneAllJobRuns(); }
|
||||
}
|
||||
|
||||
function createSchema() {
|
||||
@@ -133,6 +135,8 @@ function seedJobs() {
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const VALID_SORTS = ['name', 'vmid', 'updated_at', 'created_at'];
|
||||
|
||||
export function getInstances(filters = {}) {
|
||||
const parts = ['SELECT * FROM instances WHERE 1=1'];
|
||||
const params = {};
|
||||
@@ -142,7 +146,11 @@ export function getInstances(filters = {}) {
|
||||
}
|
||||
if (filters.state) { parts.push('AND state = @state'); params.state = filters.state; }
|
||||
if (filters.stack) { parts.push('AND stack = @stack'); params.stack = filters.stack; }
|
||||
parts.push('ORDER BY name ASC');
|
||||
const sortField = VALID_SORTS.includes(filters.sort) ? filters.sort : 'name';
|
||||
const sortOrder = filters.order === 'desc' ? 'DESC' : 'ASC';
|
||||
// id is a stable tiebreaker for timestamp fields (datetime precision is 1 s)
|
||||
const tiebreaker = (sortField === 'created_at' || sortField === 'updated_at') ? `, id ${sortOrder}` : '';
|
||||
parts.push(`ORDER BY ${sortField} ${sortOrder}${tiebreaker}`);
|
||||
return db.prepare(parts.join(' ')).all(params);
|
||||
}
|
||||
|
||||
@@ -173,7 +181,8 @@ export function createInstance(data) {
|
||||
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
|
||||
`).run(data);
|
||||
db.prepare(
|
||||
`INSERT INTO instance_history (vmid, field, old_value, new_value) VALUES (?, 'created', NULL, NULL)`
|
||||
`INSERT INTO instance_history (vmid, field, old_value, new_value, changed_at)
|
||||
VALUES (?, 'created', NULL, NULL, strftime('%Y-%m-%dT%H:%M:%f', 'now'))`
|
||||
).run(data.vmid);
|
||||
}
|
||||
|
||||
@@ -184,12 +193,13 @@ export function updateInstance(vmid, data) {
|
||||
name=@name, state=@state, stack=@stack, vmid=@newVmid,
|
||||
atlas=@atlas, argus=@argus, semaphore=@semaphore, patchmon=@patchmon,
|
||||
tailscale=@tailscale, andromeda=@andromeda, tailscale_ip=@tailscale_ip,
|
||||
hardware_acceleration=@hardware_acceleration, updated_at=datetime('now')
|
||||
hardware_acceleration=@hardware_acceleration, updated_at=strftime('%Y-%m-%dT%H:%M:%f', 'now')
|
||||
WHERE vmid=@vmid
|
||||
`).run({ ...data, newVmid: data.vmid, vmid });
|
||||
const newVmid = data.vmid;
|
||||
const insertEvt = db.prepare(
|
||||
`INSERT INTO instance_history (vmid, field, old_value, new_value) VALUES (?, ?, ?, ?)`
|
||||
`INSERT INTO instance_history (vmid, field, old_value, new_value, changed_at)
|
||||
VALUES (?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%f', 'now'))`
|
||||
);
|
||||
for (const field of HISTORY_FIELDS) {
|
||||
const oldVal = String(old[field] ?? '');
|
||||
@@ -227,7 +237,7 @@ export function importInstances(rows, historyRows = []) {
|
||||
|
||||
export function getInstanceHistory(vmid) {
|
||||
return db.prepare(
|
||||
'SELECT * FROM instance_history WHERE vmid = ? ORDER BY changed_at DESC'
|
||||
'SELECT * FROM instance_history WHERE vmid = ? ORDER BY changed_at DESC, id DESC'
|
||||
).all(vmid);
|
||||
}
|
||||
|
||||
@@ -259,6 +269,7 @@ export function importJobs(jobRows, jobRunRows = []) {
|
||||
`);
|
||||
for (const r of jobRunRows) insertRun.run(r);
|
||||
}
|
||||
pruneAllJobRuns();
|
||||
db.exec('COMMIT');
|
||||
}
|
||||
|
||||
@@ -309,17 +320,37 @@ export function updateJob(id, { enabled, schedule, config }) {
|
||||
}
|
||||
|
||||
export function createJobRun(jobId) {
|
||||
return Number(db.prepare('INSERT INTO job_runs (job_id) VALUES (?)').run(jobId).lastInsertRowid);
|
||||
return Number(db.prepare(
|
||||
`INSERT INTO job_runs (job_id, started_at) VALUES (?, strftime('%Y-%m-%dT%H:%M:%f', 'now'))`
|
||||
).run(jobId).lastInsertRowid);
|
||||
}
|
||||
|
||||
export function completeJobRun(runId, status, result) {
|
||||
db.prepare(`
|
||||
UPDATE job_runs SET ended_at=datetime('now'), status=@status, result=@result WHERE id=@id
|
||||
UPDATE job_runs SET ended_at=strftime('%Y-%m-%dT%H:%M:%f', 'now'), status=@status, result=@result WHERE id=@id
|
||||
`).run({ id: runId, status, result });
|
||||
const row = db.prepare('SELECT job_id FROM job_runs WHERE id = ?').get(runId);
|
||||
if (row) pruneJobRuns(row.job_id);
|
||||
}
|
||||
|
||||
export function getJobRuns(jobId) {
|
||||
return db.prepare('SELECT * FROM job_runs WHERE job_id = ? ORDER BY id DESC').all(jobId);
|
||||
return db.prepare(`SELECT * FROM job_runs WHERE job_id = ? ORDER BY id DESC LIMIT ${JOB_RUN_LIMIT}`).all(jobId);
|
||||
}
|
||||
|
||||
function pruneJobRuns(jobId) {
|
||||
db.prepare(`
|
||||
DELETE FROM job_runs
|
||||
WHERE job_id = ?
|
||||
AND id NOT IN (
|
||||
SELECT id FROM job_runs WHERE job_id = ? ORDER BY id DESC LIMIT ?
|
||||
)
|
||||
`).run(jobId, jobId, JOB_RUN_LIMIT);
|
||||
}
|
||||
|
||||
function pruneAllJobRuns() {
|
||||
for (const j of db.prepare('SELECT id FROM jobs').all()) {
|
||||
pruneJobRuns(j.id);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Test helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
+16
-1
@@ -41,8 +41,14 @@ async function patchmonSyncHandler(cfg) {
|
||||
const { api_url, api_token } = cfg;
|
||||
if (!api_url || !api_token) throw new Error('Patchmon not configured — set API URL and token');
|
||||
|
||||
// Accept raw "key:secret" (recommended) or a pre-encoded base64 string.
|
||||
// ":" cannot appear in a valid base64 string, so it's a reliable discriminator.
|
||||
const credential = api_token.includes(':')
|
||||
? Buffer.from(api_token).toString('base64')
|
||||
: api_token;
|
||||
|
||||
const res = await fetch(api_url, {
|
||||
headers: { Authorization: `Basic ${api_token}` },
|
||||
headers: { Authorization: `Basic ${credential}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`Patchmon API ${res.status}`);
|
||||
|
||||
@@ -129,6 +135,15 @@ export async function runJob(jobId) {
|
||||
|
||||
const _intervals = new Map();
|
||||
|
||||
export async function runJobsOnCreate() {
|
||||
for (const job of getJobs()) {
|
||||
const cfg = JSON.parse(job.config || '{}');
|
||||
if (cfg.run_on_create) {
|
||||
try { await runJob(job.id); } catch (e) { console.error(`runJobsOnCreate job ${job.id}:`, e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function restartJobs() {
|
||||
for (const iv of _intervals.values()) clearInterval(iv);
|
||||
_intervals.clear();
|
||||
|
||||
+11
-6
@@ -5,7 +5,7 @@ import {
|
||||
getConfig, setConfig, getJobs, getJob, updateJob, getJobRuns,
|
||||
getAllJobs, getAllJobRuns, importJobs,
|
||||
} from './db.js';
|
||||
import { runJob, restartJobs } from './jobs.js';
|
||||
import { runJob, restartJobs, runJobsOnCreate } from './jobs.js';
|
||||
|
||||
export const router = Router();
|
||||
|
||||
@@ -69,8 +69,8 @@ router.get('/instances/stacks', (_req, res) => {
|
||||
|
||||
// GET /api/instances
|
||||
router.get('/instances', (req, res) => {
|
||||
const { search, state, stack } = req.query;
|
||||
res.json(getInstances({ search, state, stack }));
|
||||
const { search, state, stack, sort, order } = req.query;
|
||||
res.json(getInstances({ search, state, stack, sort, order }));
|
||||
});
|
||||
|
||||
// GET /api/instances/:vmid/history
|
||||
@@ -102,6 +102,7 @@ router.post('/instances', (req, res) => {
|
||||
createInstance(data);
|
||||
const created = getInstance(data.vmid);
|
||||
res.status(201).json(created);
|
||||
runJobsOnCreate().catch(() => {});
|
||||
} catch (e) {
|
||||
handleDbError('POST /api/instances', e, res);
|
||||
}
|
||||
@@ -111,13 +112,17 @@ router.post('/instances', (req, res) => {
|
||||
router.put('/instances/:vmid', (req, res) => {
|
||||
const vmid = parseInt(req.params.vmid, 10);
|
||||
if (!vmid) return res.status(400).json({ error: 'invalid vmid' });
|
||||
if (!getInstance(vmid)) return res.status(404).json({ error: 'instance not found' });
|
||||
|
||||
const errors = validate(req.body);
|
||||
const existing = getInstance(vmid);
|
||||
if (!existing) return res.status(404).json({ error: 'instance not found' });
|
||||
|
||||
const merged = { ...existing, ...(req.body ?? {}) };
|
||||
|
||||
const errors = validate(merged);
|
||||
if (errors.length) return res.status(400).json({ errors });
|
||||
|
||||
try {
|
||||
const data = normalise(req.body);
|
||||
const data = normalise(merged);
|
||||
updateInstance(vmid, data);
|
||||
res.json(getInstance(data.vmid));
|
||||
} catch (e) {
|
||||
|
||||
@@ -74,6 +74,54 @@ describe('GET /api/instances', () => {
|
||||
expect(res.body).toHaveLength(1)
|
||||
expect(res.body[0].name).toBe('plex')
|
||||
})
|
||||
|
||||
it('sorts by vmid ascending', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 200, name: 'b' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 100, name: 'a' })
|
||||
const res = await request(app).get('/api/instances?sort=vmid&order=asc')
|
||||
expect(res.body[0].vmid).toBe(100)
|
||||
expect(res.body[1].vmid).toBe(200)
|
||||
})
|
||||
|
||||
it('sorts by vmid descending', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 100, name: 'a' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 200, name: 'b' })
|
||||
const res = await request(app).get('/api/instances?sort=vmid&order=desc')
|
||||
expect(res.body[0].vmid).toBe(200)
|
||||
expect(res.body[1].vmid).toBe(100)
|
||||
})
|
||||
|
||||
it('sorts by name descending', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 1, name: 'alpha' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 2, name: 'zebra' })
|
||||
const res = await request(app).get('/api/instances?sort=name&order=desc')
|
||||
expect(res.body[0].name).toBe('zebra')
|
||||
expect(res.body[1].name).toBe('alpha')
|
||||
})
|
||||
|
||||
it('sorts by created_at desc — id tiebreaker preserves insertion order', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 1, name: 'first' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 2, name: 'second' })
|
||||
const res = await request(app).get('/api/instances?sort=created_at&order=desc')
|
||||
expect(res.body[0].name).toBe('second') // id=2 before id=1
|
||||
expect(res.body[1].name).toBe('first')
|
||||
})
|
||||
|
||||
it('sorts by updated_at desc — id tiebreaker preserves insertion order', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 1, name: 'a' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 2, name: 'b' })
|
||||
const res = await request(app).get('/api/instances?sort=updated_at&order=desc')
|
||||
expect(res.body[0].name).toBe('b') // id=2 before id=1
|
||||
expect(res.body[1].name).toBe('a')
|
||||
})
|
||||
|
||||
it('ignores invalid sort field and falls back to name asc', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 1, name: 'zebra' })
|
||||
await request(app).post('/api/instances').send({ ...base, vmid: 2, name: 'alpha' })
|
||||
const res = await request(app).get('/api/instances?sort=bad_field')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body[0].name).toBe('alpha')
|
||||
})
|
||||
})
|
||||
|
||||
// ── GET /api/instances/stacks ─────────────────────────────────────────────────
|
||||
@@ -209,6 +257,18 @@ describe('PUT /api/instances/:vmid', () => {
|
||||
const res = await request(app).put('/api/instances/100').send({ ...base, vmid: 200 })
|
||||
expect(res.status).toBe(409)
|
||||
})
|
||||
|
||||
it('accepts a partial body and preserves unspecified fields', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, atlas: 1, tailscale_ip: '100.64.0.1' })
|
||||
const res = await request(app).put('/api/instances/100').send({ state: 'degraded' })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body.state).toBe('degraded')
|
||||
expect(res.body.name).toBe(base.name)
|
||||
expect(res.body.vmid).toBe(100)
|
||||
expect(res.body.stack).toBe(base.stack)
|
||||
expect(res.body.atlas).toBe(1)
|
||||
expect(res.body.tailscale_ip).toBe('100.64.0.1')
|
||||
})
|
||||
})
|
||||
|
||||
// ── DELETE /api/instances/:vmid ───────────────────────────────────────────────
|
||||
@@ -623,6 +683,25 @@ describe('POST /api/jobs/:id/run', () => {
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
|
||||
it('run_on_create: triggers matching jobs when an instance is created', async () => {
|
||||
createJob({ ...testJob, config: JSON.stringify({ api_key: 'k', tailnet: 't', run_on_create: true }) })
|
||||
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ devices: [] }) }))
|
||||
await request(app).post('/api/instances').send(base)
|
||||
await new Promise(r => setImmediate(r))
|
||||
const detail = await request(app).get(`/api/jobs/${id}`)
|
||||
expect(detail.body.runs).toHaveLength(1)
|
||||
expect(detail.body.runs[0].status).toBe('success')
|
||||
})
|
||||
|
||||
it('run_on_create: does not trigger jobs without the flag', async () => {
|
||||
createJob(testJob)
|
||||
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||
await request(app).post('/api/instances').send(base)
|
||||
await new Promise(r => setImmediate(r))
|
||||
expect((await request(app).get(`/api/jobs/${id}`)).body.runs).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('semaphore_sync: parses ansible inventory and updates instances', async () => {
|
||||
const semaphoreJob = {
|
||||
key: 'semaphore_sync', name: 'Semaphore Sync', description: 'test',
|
||||
|
||||
@@ -58,6 +58,71 @@ describe('getInstances', () => {
|
||||
createInstance({ name: 'plex2', state: 'degraded', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
expect(getInstances({ search: 'plex', state: 'deployed' })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('sorts by vmid ascending', () => {
|
||||
createInstance({ name: 'b', state: 'deployed', stack: 'production', vmid: 200, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'a', state: 'deployed', stack: 'production', vmid: 100, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'vmid' });
|
||||
expect(result[0].vmid).toBe(100);
|
||||
expect(result[1].vmid).toBe(200);
|
||||
});
|
||||
|
||||
it('sorts by vmid descending', () => {
|
||||
createInstance({ name: 'a', state: 'deployed', stack: 'production', vmid: 100, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'b', state: 'deployed', stack: 'production', vmid: 200, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'vmid', order: 'desc' });
|
||||
expect(result[0].vmid).toBe(200);
|
||||
expect(result[1].vmid).toBe(100);
|
||||
});
|
||||
|
||||
it('sorts by name descending', () => {
|
||||
createInstance({ name: 'alpha', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'zebra', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'name', order: 'desc' });
|
||||
expect(result[0].name).toBe('zebra');
|
||||
expect(result[1].name).toBe('alpha');
|
||||
});
|
||||
|
||||
it('sorts by created_at asc — id is tiebreaker when timestamps are equal (same second)', () => {
|
||||
// datetime('now') has second precision; rapid inserts share the same timestamp.
|
||||
// The implementation uses id ASC as secondary sort so insertion order is preserved.
|
||||
createInstance({ name: 'first', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'second', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'created_at', order: 'asc' });
|
||||
expect(result[0].name).toBe('first'); // id=1 before id=2
|
||||
expect(result[1].name).toBe('second');
|
||||
});
|
||||
|
||||
it('sorts by created_at desc — id is tiebreaker when timestamps are equal (same second)', () => {
|
||||
createInstance({ name: 'first', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'second', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'created_at', order: 'desc' });
|
||||
expect(result[0].name).toBe('second'); // id=2 before id=1
|
||||
expect(result[1].name).toBe('first');
|
||||
});
|
||||
|
||||
it('sorts by updated_at asc — id is tiebreaker when timestamps are equal (same second)', () => {
|
||||
createInstance({ name: 'a', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'b', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'updated_at', order: 'asc' });
|
||||
expect(result[0].name).toBe('a'); // id=1 before id=2
|
||||
expect(result[1].name).toBe('b');
|
||||
});
|
||||
|
||||
it('sorts by updated_at desc — id is tiebreaker when timestamps are equal (same second)', () => {
|
||||
createInstance({ name: 'a', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'b', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'updated_at', order: 'desc' });
|
||||
expect(result[0].name).toBe('b'); // id=2 before id=1
|
||||
expect(result[1].name).toBe('a');
|
||||
});
|
||||
|
||||
it('falls back to name asc for an invalid sort field', () => {
|
||||
createInstance({ name: 'zebra', state: 'deployed', stack: 'production', vmid: 1, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
createInstance({ name: 'alpha', state: 'deployed', stack: 'production', vmid: 2, atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 });
|
||||
const result = getInstances({ sort: 'injected; DROP TABLE instances--' });
|
||||
expect(result[0].name).toBe('alpha');
|
||||
});
|
||||
});
|
||||
|
||||
// ── getInstance ───────────────────────────────────────────────────────────────
|
||||
@@ -385,4 +450,17 @@ describe('job_runs', () => {
|
||||
expect(runs[0].id).toBe(r2);
|
||||
expect(runs[1].id).toBe(r1);
|
||||
});
|
||||
|
||||
it('caps history at the last 10 runs per job', () => {
|
||||
createJob(baseJob);
|
||||
const id = getJobs()[0].id;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
const runId = createJobRun(id);
|
||||
completeJobRun(runId, 'success', `run ${i}`);
|
||||
}
|
||||
const runs = getJobRuns(id);
|
||||
expect(runs).toHaveLength(10);
|
||||
expect(runs[0].result).toBe('run 14');
|
||||
expect(runs[9].result).toBe('run 5');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user