Compare commits
108 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 9295354e72 | |||
| 372cda6a58 | |||
| 3301e942ef | |||
| c4ebb76deb | |||
| bb765453ab | |||
| 88474d1048 | |||
| 954d85ca81 | |||
| 117dfc5f17 | |||
| c39c7a8aef | |||
| a934db1a14 | |||
| ea4c5f7c95 | |||
| 5c12acb6c7 | |||
| 0b350f3b28 | |||
| db4071a2cf | |||
| 37cd77850e | |||
| 14a4826bb6 | |||
| 550135ca37 | |||
| d7727badb1 | |||
| 537d78e71b | |||
| 47e9c4faf7 | |||
| 31a5090f4f | |||
| ecdac6fe23 | |||
| 07cef73fae | |||
| 1a84edc064 | |||
| bfb2c26821 | |||
| a985268987 | |||
| 218cdb08c5 | |||
| 2855cc7f81 | |||
| 07d2e215e4 | |||
| 8ef839d6d0 | |||
| 7af88328c8 | |||
| 096e2afb3d | |||
| e3d089a71f | |||
| 668e7c34bb | |||
| e796b4f400 | |||
| a4b5c20993 | |||
| d17f364fc5 | |||
| 5f79eec3dd | |||
| ed98bb57c0 | |||
| 120b61a423 | |||
| 074f0600af | |||
| e4f9407827 | |||
| fde5ce7dc1 | |||
| 20df10b333 | |||
| c906511bfc | |||
| 745e5920ad | |||
| 90e0a98914 | |||
| cba4b73798 | |||
| 0d567472a9 | |||
| 9f6b2ece52 | |||
| e3911157e9 | |||
| 0589288dfe | |||
| 8ead7687e5 | |||
| 0e1e9b6699 | |||
| 3c008c5bce | |||
| 1582c28b28 | |||
| bcd934f5b1 | |||
| 4c9acd20c7 | |||
| 520fb98d96 | |||
| 800184d2be | |||
| 82c314f85c | |||
| 2fba532ec7 | |||
| 9177578aaf | |||
| 94c4a0af51 | |||
| ec60d53767 | |||
| ad81d7ace7 | |||
| badd542bd7 | |||
| 7c31ee3327 | |||
| 0ecfa7dbc9 | |||
| f16fb3e088 | |||
| cb01573cdf | |||
| b48d5fb836 | |||
| 6e124576cb | |||
| 1f328e026d | |||
| 71c2c68fbc | |||
| 8bcf8229db | |||
| 6e1e9f7153 | |||
| 1fbb74d1ef | |||
| 617a5b5800 | |||
| 0985d9d481 | |||
| 2af6c56558 | |||
| af207339a4 |
@@ -79,7 +79,29 @@ jobs:
|
|||||||
|
|
||||||
- name: Create Gitea release
|
- name: Create Gitea release
|
||||||
run: |
|
run: |
|
||||||
python3 -c "import json,os; v=os.environ['VERSION']; img=os.environ['IMAGE']; notes=open('/tmp/release_notes.txt').read(); open('/tmp/release_body.json','w').write(json.dumps({'tag_name':'v'+v,'name':'Catalyst v'+v,'body':'### Changes\n\n'+notes+'\n\n### Image\n\n'+img+':'+v,'draft':False,'prerelease':False}))"
|
cat > /tmp/make_release.py << 'PYEOF'
|
||||||
|
import json, os
|
||||||
|
v = os.environ['VERSION']
|
||||||
|
img = os.environ['IMAGE']
|
||||||
|
raw = open('/tmp/release_notes.txt').read().strip()
|
||||||
|
feats, fixes = [], []
|
||||||
|
for line in raw.splitlines():
|
||||||
|
msg = line.lstrip('- ').strip()
|
||||||
|
if msg.startswith('feat:'):
|
||||||
|
feats.append('- ' + msg[5:].strip())
|
||||||
|
elif msg.startswith('fix:'):
|
||||||
|
fixes.append('- ' + msg[4:].strip())
|
||||||
|
sections = []
|
||||||
|
if feats:
|
||||||
|
sections.append('### New Features\n\n' + '\n'.join(feats))
|
||||||
|
if fixes:
|
||||||
|
sections.append('### Bug Fixes\n\n' + '\n'.join(fixes))
|
||||||
|
notes = '\n\n'.join(sections) or '_No changes_'
|
||||||
|
body = notes + '\n\n### Image\n\n`' + img + ':' + v + '`'
|
||||||
|
payload = {'tag_name': 'v'+v, 'name': 'Catalyst v'+v, 'body': body, 'draft': False, 'prerelease': False}
|
||||||
|
open('/tmp/release_body.json', 'w').write(json.dumps(payload))
|
||||||
|
PYEOF
|
||||||
|
python3 /tmp/make_release.py
|
||||||
curl -sf -X POST \
|
curl -sf -X POST \
|
||||||
-H "Authorization: token ${{ secrets.TOKEN }}" \
|
-H "Authorization: token ${{ secrets.TOKEN }}" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,4 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
js/version.js
|
|
||||||
data/*.db
|
data/*.db
|
||||||
data/*.db-shm
|
data/*.db-shm
|
||||||
data/*.db-wal
|
data/*.db-wal
|
||||||
|
|||||||
187
README.md
187
README.md
@@ -1,39 +1,38 @@
|
|||||||
# Catalyst
|
# Catalyst
|
||||||
|
|
||||||
A self-hosted infrastructure registry. Track every VM, container, and service across your homelab — their state, stack, and which internal services are running on them.
|
A self-hosted infrastructure registry for homelab Proxmox environments. Track virtual machines across stacks, monitor service health, and maintain a full audit log of every configuration change.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Dashboard** — filterable, searchable instance list with state and stack badges
|
- **Dashboard** — filterable, searchable instance list with state and stack badges
|
||||||
- **Detail pages** — per-instance view with service flags, Tailscale IP, and timestamps
|
- **Detail pages** — per-instance view with service flags, Tailscale IP, and a full change timeline
|
||||||
|
- **Audit log** — every field change is recorded with before/after values and a timestamp
|
||||||
- **Full CRUD** — add, edit, and delete instances via a clean modal interface
|
- **Full CRUD** — add, edit, and delete instances via a clean modal interface
|
||||||
- **Production safeguard** — only development instances can be deleted; production instances must be demoted first
|
- **Production safeguard** — only development instances can be deleted; production instances must be demoted first
|
||||||
- **REST API** — every operation is a plain HTTP call; no magic, no framework lock-in
|
- **Export / import** — JSON backup and restore via the settings modal
|
||||||
- **Persistent storage** — SQLite database on a Docker named volume; survives restarts and upgrades
|
- **REST API** — every operation is a plain HTTP call
|
||||||
- **Zero native dependencies** — SQLite via Node's built-in `node:sqlite`. No compilation, no binaries.
|
- **Persistent storage** — SQLite on a Docker named volume; survives restarts and upgrades
|
||||||
|
- **Zero native dependencies** — SQLite via Node's built-in `node:sqlite`; no compilation, no binaries
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
```bash
|
|
||||||
docker run -d \
|
|
||||||
--name catalyst \
|
|
||||||
-p 3000:3000 \
|
|
||||||
-v catalyst-data:/app/data \
|
|
||||||
gitea.thewrightserver.net/josh/catalyst:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
Or with the included Compose file:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
Open [http://localhost:3000](http://localhost:3000).
|
Open [http://localhost:3000](http://localhost:3000).
|
||||||
|
|
||||||
|
### Environment variables
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
|---|---|---|
|
||||||
|
| `PORT` | `3000` | HTTP port the server binds to |
|
||||||
|
| `DB_PATH` | `data/catalyst.db` | Path to the SQLite database file |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## REST API
|
## REST API
|
||||||
@@ -44,13 +43,13 @@ All endpoints are under `/api`. Request and response bodies are JSON.
|
|||||||
|
|
||||||
#### `GET /api/instances`
|
#### `GET /api/instances`
|
||||||
|
|
||||||
Returns all instances, sorted by name. All query parameters are optional.
|
Returns all instances sorted by name. All query parameters are optional.
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
|-----------|--------|-----------------------------------------|
|
|---|---|---|
|
||||||
| `search` | string | Partial match on `name` or `vmid` |
|
| `search` | string | Partial match on `name`, `vmid`, or `stack` |
|
||||||
| `state` | string | Exact match: `deployed`, `testing`, `degraded` |
|
| `state` | string | Exact match: `deployed`, `testing`, `degraded` |
|
||||||
| `stack` | string | Exact match: `production`, `development` |
|
| `stack` | string | Exact match: `production`, `development` |
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /api/instances?search=plex&state=deployed
|
GET /api/instances?search=plex&state=deployed
|
||||||
@@ -64,11 +63,11 @@ GET /api/instances?search=plex&state=deployed
|
|||||||
"state": "deployed",
|
"state": "deployed",
|
||||||
"stack": "production",
|
"stack": "production",
|
||||||
"tailscale_ip": "100.64.0.1",
|
"tailscale_ip": "100.64.0.1",
|
||||||
"atlas": 1, "argus": 0, "semaphore": 0,
|
"atlas": 1, "argus": 1, "semaphore": 0,
|
||||||
"patchmon": 1, "tailscale": 1, "andromeda": 0,
|
"patchmon": 1, "tailscale": 1, "andromeda": 0,
|
||||||
"hardware_acceleration": 1,
|
"hardware_acceleration": 1,
|
||||||
"created_at": "2024-01-15T10:30:00.000Z",
|
"created_at": "2024-01-15T10:30:00",
|
||||||
"updated_at": "2024-03-10T14:22:00.000Z"
|
"updated_at": "2024-03-10T14:22:00"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
@@ -91,10 +90,43 @@ GET /api/instances/stacks
|
|||||||
Returns a single instance by VMID.
|
Returns a single instance by VMID.
|
||||||
|
|
||||||
| Status | Condition |
|
| Status | Condition |
|
||||||
|--------|-----------|
|
|---|---|
|
||||||
| `200` | Instance found |
|
| `200` | Instance found |
|
||||||
| `404` | No instance with that VMID |
|
| `400` | VMID is not a valid integer |
|
||||||
| `400` | VMID is not a valid integer |
|
| `404` | No instance with that VMID |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `GET /api/instances/:vmid/history`
|
||||||
|
|
||||||
|
Returns the audit log for an instance — newest events first.
|
||||||
|
|
||||||
|
| Status | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `200` | History returned (may be empty array) |
|
||||||
|
| `400` | VMID is not a valid integer |
|
||||||
|
| `404` | No instance with that VMID |
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"vmid": 117,
|
||||||
|
"field": "state",
|
||||||
|
"old_value": "testing",
|
||||||
|
"new_value": "deployed",
|
||||||
|
"changed_at": "2024-03-10T14:22:00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"vmid": 117,
|
||||||
|
"field": "created",
|
||||||
|
"old_value": null,
|
||||||
|
"new_value": null,
|
||||||
|
"changed_at": "2024-01-15T10:30:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -103,21 +135,21 @@ Returns a single instance by VMID.
|
|||||||
Creates a new instance. Returns the created record.
|
Creates a new instance. Returns the created record.
|
||||||
|
|
||||||
| Status | Condition |
|
| Status | Condition |
|
||||||
|--------|-----------|
|
|---|---|
|
||||||
| `201` | Created successfully |
|
| `201` | Created successfully |
|
||||||
| `400` | Validation error (see `errors` array in response) |
|
| `400` | Validation error — see `errors` array in response |
|
||||||
| `409` | VMID already exists |
|
| `409` | VMID already exists |
|
||||||
|
|
||||||
**Request body:**
|
**Request body:**
|
||||||
|
|
||||||
| Field | Type | Required | Notes |
|
| Field | Type | Required | Notes |
|
||||||
|-------|------|----------|-------|
|
|---|---|---|---|
|
||||||
| `name` | string | yes | |
|
| `name` | string | yes | |
|
||||||
| `vmid` | integer | yes | Must be > 0, unique |
|
| `vmid` | integer | yes | Must be > 0 and unique |
|
||||||
| `state` | string | yes | `deployed`, `testing`, or `degraded` |
|
| `state` | string | yes | `deployed`, `testing`, or `degraded` |
|
||||||
| `stack` | string | yes | `production` or `development` |
|
| `stack` | string | yes | `production` or `development` |
|
||||||
| `tailscale_ip` | string | no | Defaults to `""` |
|
| `tailscale_ip` | string | no | Valid IPv4 or empty string |
|
||||||
| `atlas` | 0\|1 | no | Defaults to `0` |
|
| `atlas` | 0\|1 | no | |
|
||||||
| `argus` | 0\|1 | no | |
|
| `argus` | 0\|1 | no | |
|
||||||
| `semaphore` | 0\|1 | no | |
|
| `semaphore` | 0\|1 | no | |
|
||||||
| `patchmon` | 0\|1 | no | |
|
| `patchmon` | 0\|1 | no | |
|
||||||
@@ -132,11 +164,11 @@ Creates a new instance. Returns the created record.
|
|||||||
Replaces all fields on an existing instance. Accepts the same body shape as `POST`. The `vmid` in the body may differ from the URL — this is how you change a VMID.
|
Replaces all fields on an existing instance. Accepts the same body shape as `POST`. The `vmid` in the body may differ from the URL — this is how you change a VMID.
|
||||||
|
|
||||||
| Status | Condition |
|
| Status | Condition |
|
||||||
|--------|-----------|
|
|---|---|
|
||||||
| `200` | Updated successfully |
|
| `200` | Updated successfully |
|
||||||
| `400` | Validation error |
|
| `400` | Validation error |
|
||||||
| `404` | No instance with that VMID |
|
| `404` | No instance with that VMID |
|
||||||
| `409` | New VMID conflicts with an existing instance |
|
| `409` | New VMID conflicts with an existing instance |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -145,11 +177,36 @@ Replaces all fields on an existing instance. Accepts the same body shape as `POS
|
|||||||
Deletes an instance. Only instances on the `development` stack may be deleted.
|
Deletes an instance. Only instances on the `development` stack may be deleted.
|
||||||
|
|
||||||
| Status | Condition |
|
| Status | Condition |
|
||||||
|--------|-----------|
|
|---|---|
|
||||||
| `204` | Deleted successfully |
|
| `204` | Deleted successfully |
|
||||||
| `404` | No instance with that VMID |
|
| `400` | VMID is not a valid integer |
|
||||||
| `422` | Instance is on the `production` stack |
|
| `404` | No instance with that VMID |
|
||||||
| `400` | VMID is not a valid integer |
|
| `422` | Instance is on the `production` stack |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Backup
|
||||||
|
|
||||||
|
#### `GET /api/export`
|
||||||
|
|
||||||
|
Downloads a JSON backup of all instances as a file attachment.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"exported_at": "2024-03-10T14:22:00.000Z",
|
||||||
|
"instances": [ ... ]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `POST /api/import`
|
||||||
|
|
||||||
|
Replaces all instances from a JSON backup. Validates every row before committing — if any row is invalid the entire import is rejected.
|
||||||
|
|
||||||
|
| Status | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `200` | Import successful — returns `{ "imported": N }` |
|
||||||
|
| `400` | Body missing `instances` array, or validation errors |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -157,42 +214,30 @@ Deletes an instance. Only instances on the `development` stack may be deleted.
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm test # run all tests once
|
npm test # run all tests once
|
||||||
npm run test:watch # watch mode
|
npm run test:watch # watch mode
|
||||||
npm start # start the server on :3000
|
npm start # start the server on :3000
|
||||||
```
|
```
|
||||||
|
|
||||||
Tests are split across three files:
|
Tests are split across three files:
|
||||||
|
|
||||||
| File | What it covers |
|
| File | What it covers |
|
||||||
|------|----------------|
|
|---|---|
|
||||||
| `tests/db.test.js` | SQLite data layer — all CRUD operations, constraints, filters |
|
| `tests/db.test.js` | SQLite data layer — CRUD, constraints, filters, history logging |
|
||||||
| `tests/api.test.js` | HTTP API — all endpoints, status codes, error cases |
|
| `tests/api.test.js` | HTTP API — all endpoints, status codes, error cases |
|
||||||
| `tests/helpers.test.js` | UI helper functions — `esc()` XSS contract, `fmtDate()` |
|
| `tests/helpers.test.js` | UI helpers — `esc()` XSS contract, date formatting, history formatters |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Versioning
|
## Versioning
|
||||||
|
|
||||||
Catalyst uses [semantic versioning](https://semver.org). `package.json` is the single source of truth for the version number.
|
Catalyst uses [semantic versioning](https://semver.org). `package.json` is the single source of truth.
|
||||||
|
|
||||||
| Change | Bump | Example |
|
| Change | Bump |
|
||||||
|--------|------|---------|
|
|---|---|
|
||||||
| Bug fix | patch | `1.0.0` → `1.0.1` |
|
| Bug fix | patch |
|
||||||
| New feature, backward compatible | minor | `1.0.0` → `1.1.0` |
|
| New feature, backward compatible | minor |
|
||||||
| Breaking change | major | `1.0.0` → `2.0.0` |
|
| Breaking change | major |
|
||||||
|
|
||||||
### Cutting a release
|
Pushing a tag triggers the CI pipeline: **test → build → release**.
|
||||||
|
Docker images are tagged `:x.y.z`, `:x.y`, and `:latest`.
|
||||||
```bash
|
|
||||||
# 1. Bump version in package.json, then:
|
|
||||||
git add package.json
|
|
||||||
git commit -m "chore: release v1.1.0"
|
|
||||||
git tag v1.1.0
|
|
||||||
git push && git push --tags
|
|
||||||
```
|
|
||||||
|
|
||||||
Pushing a tag triggers the full CI pipeline: **test → build → release**.
|
|
||||||
|
|
||||||
- Docker image tagged `:1.1.0`, `:1.1`, and `:latest` in the Gitea registry
|
|
||||||
- A Gitea release is created at `v1.1.0`
|
|
||||||
|
|||||||
233
css/app.css
233
css/app.css
@@ -25,6 +25,10 @@
|
|||||||
--mono: 'JetBrains Mono', 'IBM Plex Mono', monospace;
|
--mono: 'JetBrains Mono', 'IBM Plex Mono', monospace;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
zoom: 1.1;
|
||||||
|
}
|
||||||
|
|
||||||
html, body {
|
html, body {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background: var(--bg);
|
background: var(--bg);
|
||||||
@@ -70,6 +74,19 @@ nav {
|
|||||||
|
|
||||||
.nav-sep { flex: 1; }
|
.nav-sep { flex: 1; }
|
||||||
|
|
||||||
|
.nav-btn {
|
||||||
|
background: none;
|
||||||
|
border: 1px solid var(--border2);
|
||||||
|
color: var(--text2);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-left: 10px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.nav-btn:hover { border-color: var(--accent); color: var(--accent); }
|
||||||
|
|
||||||
.nav-divider { color: var(--border2); }
|
.nav-divider { color: var(--border2); }
|
||||||
|
|
||||||
.nav-status {
|
.nav-status {
|
||||||
@@ -136,6 +153,8 @@ main { flex: 1; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
.stat-cell:last-child { border-right: none; }
|
.stat-cell:last-child { border-right: none; }
|
||||||
|
.stat-clickable { cursor: pointer; user-select: none; }
|
||||||
|
.stat-clickable:hover { background: var(--bg2); }
|
||||||
|
|
||||||
.stat-label {
|
.stat-label {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
@@ -361,16 +380,25 @@ select:focus { border-color: var(--accent); }
|
|||||||
}
|
}
|
||||||
|
|
||||||
.detail-sub {
|
.detail-sub {
|
||||||
font-size: 12px;
|
font-size: 13px;
|
||||||
color: var(--text3);
|
margin-top: 8px;
|
||||||
margin-top: 6px;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 16px;
|
align-items: center;
|
||||||
|
gap: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.detail-sub span { display: flex; gap: 4px; }
|
.detail-sub > span {
|
||||||
.detail-sub .lbl { color: var(--text3); }
|
display: flex;
|
||||||
.detail-sub .val { color: var(--text2); }
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.detail-sub > span + span {
|
||||||
|
margin-left: 12px;
|
||||||
|
padding-left: 12px;
|
||||||
|
border-left: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.detail-sub .lbl { color: var(--text3); font-size: 11px; }
|
||||||
|
.detail-sub .val { color: var(--text); }
|
||||||
|
|
||||||
.detail-actions { display: flex; gap: 8px; }
|
.detail-actions { display: flex; gap: 8px; }
|
||||||
|
|
||||||
@@ -615,6 +643,58 @@ select:focus { border-color: var(--accent); }
|
|||||||
|
|
||||||
.confirm-actions { display: flex; justify-content: flex-end; gap: 10px; }
|
.confirm-actions { display: flex; justify-content: flex-end; gap: 10px; }
|
||||||
|
|
||||||
|
/* ── HISTORY TIMELINE ── */
|
||||||
|
.tl-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 9px 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.tl-item:last-child { border-bottom: none; }
|
||||||
|
.tl-event { display: flex; align-items: center; gap: 7px; font-size: 13px; min-width: 0; }
|
||||||
|
.tl-label { color: var(--text2); }
|
||||||
|
.tl-sep { color: var(--text3); user-select: none; }
|
||||||
|
.tl-old { color: var(--text3); text-decoration: line-through; font-size: 12px; }
|
||||||
|
.tl-arrow { color: var(--text3); font-size: 11px; }
|
||||||
|
.tl-new { color: var(--text); font-weight: 500; }
|
||||||
|
.tl-time { color: var(--text3); font-size: 11px; white-space: nowrap; flex-shrink: 0; }
|
||||||
|
.tl-deployed { color: var(--accent); }
|
||||||
|
.tl-testing { color: var(--amber); }
|
||||||
|
.tl-degraded { color: var(--red); }
|
||||||
|
.tl-created .tl-event { color: var(--accent); font-weight: 500; }
|
||||||
|
.tl-empty { color: var(--text3); font-size: 12px; padding: 8px 0; }
|
||||||
|
|
||||||
|
/* ── SETTINGS MODAL ── */
|
||||||
|
#settings-modal .modal-body { padding-top: 0; }
|
||||||
|
.settings-section { padding: 16px 0; border-bottom: 1px solid var(--border); }
|
||||||
|
.settings-section:last-child { border-bottom: none; padding-bottom: 0; }
|
||||||
|
.settings-section-title {
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
color: var(--text3);
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.settings-desc { font-size: 12px; color: var(--text2); margin: 0 0 14px; line-height: 1.6; }
|
||||||
|
.settings-row { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.settings-label { font-size: 13px; color: var(--text2); white-space: nowrap; min-width: 80px; }
|
||||||
|
.settings-select { flex: 1; }
|
||||||
|
.import-row { display: flex; gap: 10px; align-items: center; }
|
||||||
|
.import-file-input { flex: 1; }
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg3);
|
||||||
|
border-color: var(--border2);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.btn-secondary:hover { border-color: var(--accent); color: var(--accent); }
|
||||||
|
|
||||||
|
.btn-danger { background: var(--red2); border-color: var(--red); color: var(--text); }
|
||||||
|
.btn-danger:hover { background: var(--red); }
|
||||||
|
|
||||||
/* ── SCROLLBAR ── */
|
/* ── SCROLLBAR ── */
|
||||||
::-webkit-scrollbar { width: 6px; }
|
::-webkit-scrollbar { width: 6px; }
|
||||||
::-webkit-scrollbar-track { background: var(--bg); }
|
::-webkit-scrollbar-track { background: var(--bg); }
|
||||||
@@ -634,3 +714,142 @@ select:focus { border-color: var(--accent); }
|
|||||||
0%, 100% { opacity: 1; }
|
0%, 100% { opacity: 1; }
|
||||||
50% { opacity: 0; }
|
50% { opacity: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── MOBILE ── */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
/* Reset desktop zoom — mobile browsers handle scaling themselves */
|
||||||
|
html { zoom: 1; }
|
||||||
|
|
||||||
|
/* Nav */
|
||||||
|
nav { padding: 0 16px; }
|
||||||
|
|
||||||
|
/* Dashboard header */
|
||||||
|
.dash-header { padding: 18px 16px 14px; }
|
||||||
|
|
||||||
|
/* Stats bar */
|
||||||
|
.stat-cell { padding: 10px 16px; }
|
||||||
|
|
||||||
|
/* Toolbar — search full-width on first row, filters + button below */
|
||||||
|
.toolbar { flex-wrap: wrap; padding: 10px 16px; gap: 8px; }
|
||||||
|
.search-wrap { max-width: 100%; }
|
||||||
|
.toolbar-right { margin-left: 0; width: 100%; justify-content: flex-end; }
|
||||||
|
|
||||||
|
/* Instance grid — single column */
|
||||||
|
.instance-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
padding: 12px 16px;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Detail page */
|
||||||
|
.detail-page { padding: 16px; }
|
||||||
|
|
||||||
|
/* Detail header — stack title block above actions */
|
||||||
|
.detail-header { flex-direction: column; align-items: flex-start; gap: 14px; }
|
||||||
|
|
||||||
|
/* Detail sub — wrap items when they don't fit */
|
||||||
|
.detail-sub { flex-wrap: wrap; row-gap: 4px; }
|
||||||
|
|
||||||
|
/* Detail grid — single column */
|
||||||
|
.detail-grid { grid-template-columns: 1fr; }
|
||||||
|
|
||||||
|
/* Toggle grid — 2 columns instead of 3 */
|
||||||
|
.toggle-grid { grid-template-columns: 1fr 1fr; }
|
||||||
|
|
||||||
|
/* Confirm box — no fixed width on mobile */
|
||||||
|
.confirm-box { width: auto; max-width: calc(100vw - 32px); padding: 18px; }
|
||||||
|
|
||||||
|
/* History timeline — stack timestamp above event */
|
||||||
|
.tl-item { flex-direction: column; align-items: flex-start; gap: 3px; }
|
||||||
|
.tl-time { order: -1; }
|
||||||
|
|
||||||
|
/* Toast — stretch across bottom */
|
||||||
|
.toast { right: 16px; left: 16px; bottom: 16px; }
|
||||||
|
|
||||||
|
/* Jobs — stack sidebar above detail */
|
||||||
|
.jobs-layout { grid-template-columns: 1fr; }
|
||||||
|
.jobs-sidebar { border-right: none; border-bottom: 1px solid var(--border); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── JOBS PAGE ───────────────────────────────────────────────────────────────── */
|
||||||
|
|
||||||
|
.jobs-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 220px 1fr;
|
||||||
|
height: calc(100vh - 48px);
|
||||||
|
}
|
||||||
|
.jobs-sidebar {
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
.jobs-sidebar-title {
|
||||||
|
padding: 16px 16px 8px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
color: var(--text3);
|
||||||
|
}
|
||||||
|
.job-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.job-item:hover, .job-item.active { background: var(--bg2); }
|
||||||
|
.job-item-name { font-size: 13px; color: var(--text); }
|
||||||
|
.jobs-detail {
|
||||||
|
padding: 28px 32px;
|
||||||
|
overflow-y: auto;
|
||||||
|
max-width: 600px;
|
||||||
|
}
|
||||||
|
.jobs-detail-hd { margin-bottom: 20px; }
|
||||||
|
.jobs-detail-title { font-size: 17px; font-weight: 600; color: var(--text); }
|
||||||
|
.jobs-detail-desc { font-size: 12px; color: var(--text2); margin-top: 4px; line-height: 1.6; }
|
||||||
|
.job-actions { display: flex; gap: 8px; margin: 16px 0 0; }
|
||||||
|
.jobs-placeholder { padding: 48px 32px; color: var(--text3); font-size: 13px; }
|
||||||
|
|
||||||
|
/* Shared job status dot */
|
||||||
|
.job-dot {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
.job-dot--success { background: var(--accent); }
|
||||||
|
.job-dot--error { background: var(--red); }
|
||||||
|
.job-dot--running { background: var(--amber); animation: pulse 2s ease-in-out infinite; }
|
||||||
|
.job-dot--none { background: var(--border2); }
|
||||||
|
|
||||||
|
/* Run history list */
|
||||||
|
.run-item {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 10px 1fr 60px 1fr;
|
||||||
|
gap: 0 12px;
|
||||||
|
padding: 7px 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-size: 12px;
|
||||||
|
align-items: baseline;
|
||||||
|
}
|
||||||
|
.run-item:last-child { border-bottom: none; }
|
||||||
|
.run-time { color: var(--text3); }
|
||||||
|
.run-status { color: var(--text2); }
|
||||||
|
.run-result { color: var(--text); }
|
||||||
|
.run-empty { color: var(--text3); font-size: 12px; padding: 8px 0; }
|
||||||
|
|
||||||
|
/* Nav dot */
|
||||||
|
.nav-job-dot {
|
||||||
|
display: inline-block;
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
margin-left: 5px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
.nav-job-dot--success { background: var(--accent); }
|
||||||
|
.nav-job-dot--error { background: var(--red); }
|
||||||
|
.nav-job-dot--none { display: none; }
|
||||||
|
|||||||
50
index.html
50
index.html
@@ -22,6 +22,8 @@
|
|||||||
<span class="nav-divider">·</span>
|
<span class="nav-divider">·</span>
|
||||||
<span id="nav-version"></span>
|
<span id="nav-version"></span>
|
||||||
</div>
|
</div>
|
||||||
|
<button class="nav-btn" onclick="navigate('jobs')">Jobs <span id="nav-jobs-dot" class="nav-job-dot nav-job-dot--none"></span></button>
|
||||||
|
<button class="nav-btn" onclick="openSettingsModal()" title="Settings">⚙</button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<main>
|
<main>
|
||||||
@@ -68,7 +70,6 @@
|
|||||||
<div class="detail-name" id="detail-name">—</div>
|
<div class="detail-name" id="detail-name">—</div>
|
||||||
<div class="detail-sub">
|
<div class="detail-sub">
|
||||||
<span><span class="lbl">vmid</span> <span class="val" id="detail-vmid-sub">—</span></span>
|
<span><span class="lbl">vmid</span> <span class="val" id="detail-vmid-sub">—</span></span>
|
||||||
<span><span class="lbl">id</span> <span class="val" id="detail-id-sub">—</span></span>
|
|
||||||
<span><span class="lbl">created</span> <span class="val" id="detail-created-sub">—</span></span>
|
<span><span class="lbl">created</span> <span class="val" id="detail-created-sub">—</span></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -91,12 +92,25 @@
|
|||||||
<div class="services-grid" id="detail-services"></div>
|
<div class="services-grid" id="detail-services"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="detail-section full">
|
<div class="detail-section full">
|
||||||
<div class="section-title">timestamps</div>
|
<div class="section-title">history</div>
|
||||||
<div id="detail-timestamps"></div>
|
<div id="detail-timestamps"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- JOBS PAGE -->
|
||||||
|
<div class="page" id="page-jobs">
|
||||||
|
<div class="jobs-layout">
|
||||||
|
<div class="jobs-sidebar">
|
||||||
|
<div class="jobs-sidebar-title">Jobs</div>
|
||||||
|
<div id="jobs-list"></div>
|
||||||
|
</div>
|
||||||
|
<div class="jobs-detail" id="jobs-detail">
|
||||||
|
<div class="jobs-placeholder">Select a job</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -171,6 +185,38 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- SETTINGS MODAL -->
|
||||||
|
<div id="settings-modal" class="modal-overlay">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-header">
|
||||||
|
<span class="modal-title">Settings</span>
|
||||||
|
<button class="modal-close" onclick="closeSettingsModal()">✕</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="settings-section">
|
||||||
|
<div class="settings-section-title">Display</div>
|
||||||
|
<div class="settings-row">
|
||||||
|
<label class="settings-label" for="tz-select">Timezone</label>
|
||||||
|
<select id="tz-select" class="form-input settings-select"></select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="settings-section">
|
||||||
|
<div class="settings-section-title">Export</div>
|
||||||
|
<p class="settings-desc">Download all instance data as a JSON backup file.</p>
|
||||||
|
<button class="btn btn-secondary" onclick="exportDB()">Export Database</button>
|
||||||
|
</div>
|
||||||
|
<div class="settings-section">
|
||||||
|
<div class="settings-section-title">Import</div>
|
||||||
|
<p class="settings-desc">Restore from a backup file. This replaces all current instances.</p>
|
||||||
|
<div class="import-row">
|
||||||
|
<input type="file" id="import-file" accept=".json" class="form-input import-file-input">
|
||||||
|
<button class="btn btn-danger" onclick="importDB()">Import</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- TOAST -->
|
<!-- TOAST -->
|
||||||
<div class="toast" id="toast">
|
<div class="toast" id="toast">
|
||||||
<div class="toast-dot"></div>
|
<div class="toast-dot"></div>
|
||||||
|
|||||||
14
js/app.js
14
js/app.js
@@ -11,12 +11,19 @@ function navigate(page, vmid) {
|
|||||||
document.getElementById('page-detail').classList.add('active');
|
document.getElementById('page-detail').classList.add('active');
|
||||||
history.pushState({ page: 'instance', vmid }, '', `/instance/${vmid}`);
|
history.pushState({ page: 'instance', vmid }, '', `/instance/${vmid}`);
|
||||||
renderDetailPage(vmid);
|
renderDetailPage(vmid);
|
||||||
|
} else if (page === 'jobs') {
|
||||||
|
document.getElementById('page-jobs').classList.add('active');
|
||||||
|
history.pushState({ page: 'jobs' }, '', '/jobs');
|
||||||
|
renderJobsPage();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleRoute() {
|
function handleRoute() {
|
||||||
const m = window.location.pathname.match(/^\/instance\/(\d+)/);
|
const m = window.location.pathname.match(/^\/instance\/(\d+)/);
|
||||||
if (m) {
|
if (window.location.pathname === '/jobs') {
|
||||||
|
document.getElementById('page-jobs').classList.add('active');
|
||||||
|
renderJobsPage();
|
||||||
|
} else if (m) {
|
||||||
document.getElementById('page-detail').classList.add('active');
|
document.getElementById('page-detail').classList.add('active');
|
||||||
renderDetailPage(parseInt(m[1], 10));
|
renderDetailPage(parseInt(m[1], 10));
|
||||||
} else {
|
} else {
|
||||||
@@ -30,6 +37,9 @@ window.addEventListener('popstate', e => {
|
|||||||
if (e.state?.page === 'instance') {
|
if (e.state?.page === 'instance') {
|
||||||
document.getElementById('page-detail').classList.add('active');
|
document.getElementById('page-detail').classList.add('active');
|
||||||
renderDetailPage(e.state.vmid);
|
renderDetailPage(e.state.vmid);
|
||||||
|
} else if (e.state?.page === 'jobs') {
|
||||||
|
document.getElementById('page-jobs').classList.add('active');
|
||||||
|
renderJobsPage();
|
||||||
} else {
|
} else {
|
||||||
document.getElementById('page-dashboard').classList.add('active');
|
document.getElementById('page-dashboard').classList.add('active');
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
@@ -43,4 +53,6 @@ if (VERSION) {
|
|||||||
document.getElementById('nav-version').textContent = label;
|
document.getElementById('nav-version').textContent = label;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fetch('/api/jobs').then(r => r.json()).then(_updateJobsNavDot).catch(() => {});
|
||||||
|
|
||||||
handleRoute();
|
handleRoute();
|
||||||
|
|||||||
5
js/db.js
5
js/db.js
@@ -55,3 +55,8 @@ async function updateInstance(vmid, data) {
|
|||||||
async function deleteInstance(vmid) {
|
async function deleteInstance(vmid) {
|
||||||
await api(`/instances/${vmid}`, { method: 'DELETE' });
|
await api(`/instances/${vmid}`, { method: 'DELETE' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getInstanceHistory(vmid) {
|
||||||
|
const res = await fetch(`${BASE}/instances/${vmid}/history`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|||||||
360
js/ui.js
360
js/ui.js
@@ -3,6 +3,34 @@ let editingVmid = null;
|
|||||||
let currentVmid = null;
|
let currentVmid = null;
|
||||||
let toastTimer = null;
|
let toastTimer = null;
|
||||||
|
|
||||||
|
// ── Timezone ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const TIMEZONES = [
|
||||||
|
{ label: 'UTC', tz: 'UTC' },
|
||||||
|
{ label: 'Hawaii (HST)', tz: 'Pacific/Honolulu' },
|
||||||
|
{ label: 'Alaska (AKT)', tz: 'America/Anchorage' },
|
||||||
|
{ label: 'Pacific (PT)', tz: 'America/Los_Angeles' },
|
||||||
|
{ label: 'Mountain (MT)', tz: 'America/Denver' },
|
||||||
|
{ label: 'Central (CT)', tz: 'America/Chicago' },
|
||||||
|
{ label: 'Eastern (ET)', tz: 'America/New_York' },
|
||||||
|
{ label: 'Atlantic (AT)', tz: 'America/Halifax' },
|
||||||
|
{ label: 'London (GMT/BST)', tz: 'Europe/London' },
|
||||||
|
{ label: 'Paris / Berlin (CET)', tz: 'Europe/Paris' },
|
||||||
|
{ label: 'Helsinki (EET)', tz: 'Europe/Helsinki' },
|
||||||
|
{ label: 'Istanbul (TRT)', tz: 'Europe/Istanbul' },
|
||||||
|
{ label: 'Dubai (GST)', tz: 'Asia/Dubai' },
|
||||||
|
{ label: 'India (IST)', tz: 'Asia/Kolkata' },
|
||||||
|
{ label: 'Singapore (SGT)', tz: 'Asia/Singapore' },
|
||||||
|
{ label: 'China (CST)', tz: 'Asia/Shanghai' },
|
||||||
|
{ label: 'Japan / Korea (JST/KST)', tz: 'Asia/Tokyo' },
|
||||||
|
{ label: 'Sydney (AEST)', tz: 'Australia/Sydney' },
|
||||||
|
{ label: 'Auckland (NZST)', tz: 'Pacific/Auckland' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function getTimezone() {
|
||||||
|
return localStorage.getItem('catalyst_tz') || 'UTC';
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function esc(str) {
|
function esc(str) {
|
||||||
@@ -11,17 +39,25 @@ function esc(str) {
|
|||||||
return d.innerHTML;
|
return d.innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SQLite datetime('now') → 'YYYY-MM-DD HH:MM:SS' (UTC, no timezone marker).
|
||||||
|
// Appending 'Z' tells JS to parse it as UTC rather than local time.
|
||||||
|
function parseUtc(d) {
|
||||||
|
if (typeof d !== 'string') return new Date(d);
|
||||||
|
const hasZone = d.endsWith('Z') || /[+-]\d{2}:\d{2}$/.test(d);
|
||||||
|
return new Date(hasZone ? d : d.replace(' ', 'T') + 'Z');
|
||||||
|
}
|
||||||
|
|
||||||
function fmtDate(d) {
|
function fmtDate(d) {
|
||||||
if (!d) return '—';
|
if (!d) return '—';
|
||||||
try {
|
try {
|
||||||
return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
|
return parseUtc(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: getTimezone() });
|
||||||
} catch (e) { return d; }
|
} catch (e) { return d; }
|
||||||
}
|
}
|
||||||
|
|
||||||
function fmtDateFull(d) {
|
function fmtDateFull(d) {
|
||||||
if (!d) return '—';
|
if (!d) return '—';
|
||||||
try {
|
try {
|
||||||
return new Date(d).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
return parseUtc(d).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', timeZone: getTimezone(), timeZoneName: 'short' });
|
||||||
} catch (e) { return d; }
|
} catch (e) { return d; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,11 +71,10 @@ async function renderDashboard() {
|
|||||||
all.forEach(i => { states[i.state] = (states[i.state] || 0) + 1; });
|
all.forEach(i => { states[i.state] = (states[i.state] || 0) + 1; });
|
||||||
|
|
||||||
document.getElementById('stats-bar').innerHTML = `
|
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 stat-clickable" onclick="setStateFilter('')"><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 stat-clickable" onclick="setStateFilter('deployed')"><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 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"><div class="stat-label">degraded</div><div class="stat-value red">${states['degraded'] || 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>
|
||||||
<div class="stat-cell"><div class="stat-label">stacks</div><div class="stat-value">${(await getDistinctStacks()).length}</div></div>
|
|
||||||
`;
|
`;
|
||||||
|
|
||||||
await populateStackFilter();
|
await populateStackFilter();
|
||||||
@@ -60,6 +95,11 @@ async function populateStackFilter() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setStateFilter(state) {
|
||||||
|
document.getElementById('filter-state').value = state;
|
||||||
|
filterInstances();
|
||||||
|
}
|
||||||
|
|
||||||
async function filterInstances() {
|
async function filterInstances() {
|
||||||
const search = document.getElementById('search-input').value;
|
const search = document.getElementById('search-input').value;
|
||||||
const state = document.getElementById('filter-state').value;
|
const state = document.getElementById('filter-state').value;
|
||||||
@@ -100,23 +140,50 @@ async function filterInstances() {
|
|||||||
|
|
||||||
// ── Detail Page ───────────────────────────────────────────────────────────────
|
// ── Detail Page ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const BOOL_FIELDS = ['atlas','argus','semaphore','patchmon','tailscale','andromeda','hardware_acceleration'];
|
||||||
|
|
||||||
|
const FIELD_LABELS = {
|
||||||
|
name: 'name',
|
||||||
|
state: 'state',
|
||||||
|
stack: 'stack',
|
||||||
|
vmid: 'vmid',
|
||||||
|
tailscale_ip: 'tailscale ip',
|
||||||
|
atlas: 'atlas',
|
||||||
|
argus: 'argus',
|
||||||
|
semaphore: 'semaphore',
|
||||||
|
patchmon: 'patchmon',
|
||||||
|
tailscale: 'tailscale',
|
||||||
|
andromeda: 'andromeda',
|
||||||
|
hardware_acceleration: 'hw acceleration',
|
||||||
|
};
|
||||||
|
|
||||||
|
function stateClass(field, val) {
|
||||||
|
if (field !== 'state') return '';
|
||||||
|
return { deployed: 'tl-deployed', testing: 'tl-testing', degraded: 'tl-degraded' }[val] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtHistVal(field, val) {
|
||||||
|
if (val == null || val === '') return '—';
|
||||||
|
if (BOOL_FIELDS.includes(field)) return val === '1' ? 'on' : 'off';
|
||||||
|
return esc(val);
|
||||||
|
}
|
||||||
|
|
||||||
async function renderDetailPage(vmid) {
|
async function renderDetailPage(vmid) {
|
||||||
const inst = await getInstance(vmid);
|
const [inst, history, all] = await Promise.all([getInstance(vmid), getInstanceHistory(vmid), getInstances()]);
|
||||||
if (!inst) { navigate('dashboard'); return; }
|
if (!inst) { navigate('dashboard'); return; }
|
||||||
currentVmid = vmid;
|
currentVmid = vmid;
|
||||||
|
document.getElementById('nav-count').textContent = `${all.length} instance${all.length !== 1 ? 's' : ''}`;
|
||||||
|
|
||||||
document.getElementById('detail-vmid-crumb').textContent = vmid;
|
document.getElementById('detail-vmid-crumb').textContent = vmid;
|
||||||
document.getElementById('detail-name').textContent = inst.name;
|
document.getElementById('detail-name').textContent = inst.name;
|
||||||
document.getElementById('detail-vmid-sub').textContent = inst.vmid;
|
document.getElementById('detail-vmid-sub').textContent = inst.vmid;
|
||||||
document.getElementById('detail-id-sub').textContent = inst.id;
|
|
||||||
document.getElementById('detail-created-sub').textContent = fmtDate(inst.created_at);
|
document.getElementById('detail-created-sub').textContent = fmtDate(inst.created_at);
|
||||||
|
|
||||||
document.getElementById('detail-identity').innerHTML = `
|
document.getElementById('detail-identity').innerHTML = `
|
||||||
<div class="kv-row"><span class="kv-key">name</span><span class="kv-val highlight">${esc(inst.name)}</span></div>
|
<div class="kv-row"><span class="kv-key">name</span><span class="kv-val highlight">${esc(inst.name)}</span></div>
|
||||||
<div class="kv-row"><span class="kv-key">state</span><span class="kv-val"><span class="badge ${esc(inst.state)}">${esc(inst.state)}</span></span></div>
|
<div class="kv-row"><span class="kv-key">state</span><span class="kv-val"><span class="badge ${esc(inst.state)}">${esc(inst.state)}</span></span></div>
|
||||||
<div class="kv-row"><span class="kv-key">stack</span><span class="kv-val highlight">${esc(inst.stack) || '—'}</span></div>
|
<div class="kv-row"><span class="kv-key">stack</span><span class="kv-val"><span class="badge ${esc(inst.stack)}">${esc(inst.stack) || '—'}</span></span></div>
|
||||||
<div class="kv-row"><span class="kv-key">vmid</span><span class="kv-val highlight">${inst.vmid}</span></div>
|
<div class="kv-row"><span class="kv-key">vmid</span><span class="kv-val highlight">${inst.vmid}</span></div>
|
||||||
<div class="kv-row"><span class="kv-key">internal id</span><span class="kv-val">${inst.id}</span></div>
|
|
||||||
`;
|
`;
|
||||||
|
|
||||||
document.getElementById('detail-network').innerHTML = `
|
document.getElementById('detail-network').innerHTML = `
|
||||||
@@ -134,10 +201,30 @@ async function renderDetailPage(vmid) {
|
|||||||
</div>
|
</div>
|
||||||
`).join('');
|
`).join('');
|
||||||
|
|
||||||
document.getElementById('detail-timestamps').innerHTML = `
|
document.getElementById('detail-timestamps').innerHTML = history.length
|
||||||
<div class="kv-row"><span class="kv-key">created</span><span class="kv-val">${fmtDateFull(inst.created_at)}</span></div>
|
? history.map(e => {
|
||||||
<div class="kv-row"><span class="kv-key">updated</span><span class="kv-val">${fmtDateFull(inst.updated_at)}</span></div>
|
if (e.field === 'created') return `
|
||||||
`;
|
<div class="tl-item tl-created">
|
||||||
|
<span class="tl-event">instance created</span>
|
||||||
|
<span class="tl-time">${fmtDateFull(e.changed_at)}</span>
|
||||||
|
</div>`;
|
||||||
|
const label = FIELD_LABELS[e.field] ?? esc(e.field);
|
||||||
|
const newCls = (e.field === 'state' || e.field === 'stack')
|
||||||
|
? `badge ${esc(e.new_value)}`
|
||||||
|
: `tl-new ${stateClass(e.field, e.new_value)}`;
|
||||||
|
return `
|
||||||
|
<div class="tl-item">
|
||||||
|
<div class="tl-event">
|
||||||
|
<span class="tl-label">${label}</span>
|
||||||
|
<span class="tl-sep">·</span>
|
||||||
|
<span class="tl-old">${fmtHistVal(e.field, e.old_value)}</span>
|
||||||
|
<span class="tl-arrow">→</span>
|
||||||
|
<span class="${newCls}">${fmtHistVal(e.field, e.new_value)}</span>
|
||||||
|
</div>
|
||||||
|
<span class="tl-time">${fmtDateFull(e.changed_at)}</span>
|
||||||
|
</div>`;
|
||||||
|
}).join('')
|
||||||
|
: '<div class="tl-empty">no history yet</div>';
|
||||||
|
|
||||||
document.getElementById('detail-edit-btn').onclick = () => openEditModal(inst.vmid);
|
document.getElementById('detail-edit-btn').onclick = () => openEditModal(inst.vmid);
|
||||||
document.getElementById('detail-delete-btn').onclick = () => confirmDeleteDialog(inst);
|
document.getElementById('detail-delete-btn').onclick = () => confirmDeleteDialog(inst);
|
||||||
@@ -207,6 +294,10 @@ async function saveInstance() {
|
|||||||
hardware_acceleration: +document.getElementById('f-hardware-accel').checked,
|
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
|
const result = editingVmid
|
||||||
? await updateInstance(editingVmid, data)
|
? await updateInstance(editingVmid, data)
|
||||||
: await createInstance(data);
|
: await createInstance(data);
|
||||||
@@ -216,6 +307,8 @@ async function saveInstance() {
|
|||||||
showToast(`${name} ${editingVmid ? 'updated' : 'created'}`, 'success');
|
showToast(`${name} ${editingVmid ? 'updated' : 'created'}`, 'success');
|
||||||
closeModal();
|
closeModal();
|
||||||
|
|
||||||
|
if (jobBaseline) await _waitForOnCreateJobs(jobBaseline);
|
||||||
|
|
||||||
if (currentVmid && document.getElementById('page-detail').classList.contains('active')) {
|
if (currentVmid && document.getElementById('page-detail').classList.contains('active')) {
|
||||||
await renderDetailPage(vmid);
|
await renderDetailPage(vmid);
|
||||||
} else {
|
} else {
|
||||||
@@ -223,6 +316,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 ────────────────────────────────────────────────────────────
|
// ── Confirm Dialog ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function confirmDeleteDialog(inst) {
|
function confirmDeleteDialog(inst) {
|
||||||
@@ -258,12 +375,74 @@ function showToast(msg, type = 'success') {
|
|||||||
toastTimer = setTimeout(() => t.classList.remove('show'), 3000);
|
toastTimer = setTimeout(() => t.classList.remove('show'), 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Settings Modal ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function openSettingsModal() {
|
||||||
|
const sel = document.getElementById('tz-select');
|
||||||
|
if (!sel.options.length) {
|
||||||
|
for (const { label, tz } of TIMEZONES) {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = tz;
|
||||||
|
opt.textContent = label;
|
||||||
|
sel.appendChild(opt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sel.value = getTimezone();
|
||||||
|
document.getElementById('settings-modal').classList.add('open');
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSettingsModal() {
|
||||||
|
document.getElementById('settings-modal').classList.remove('open');
|
||||||
|
document.getElementById('import-file').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exportDB() {
|
||||||
|
const res = await fetch('/api/export');
|
||||||
|
const blob = await res.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `catalyst-backup-${new Date().toISOString().slice(0, 10)}.json`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function importDB() {
|
||||||
|
const file = document.getElementById('import-file').files[0];
|
||||||
|
if (!file) { showToast('Select a backup file first', 'error'); return; }
|
||||||
|
document.getElementById('confirm-title').textContent = 'Replace all instances?';
|
||||||
|
document.getElementById('confirm-msg').textContent =
|
||||||
|
`This will delete all current instances and replace them with the contents of "${file.name}". This cannot be undone.`;
|
||||||
|
document.getElementById('confirm-overlay').classList.add('open');
|
||||||
|
document.getElementById('confirm-ok').onclick = async () => {
|
||||||
|
closeConfirm();
|
||||||
|
try {
|
||||||
|
const { instances, history = [], jobs, job_runs } = JSON.parse(await file.text());
|
||||||
|
const res = await fetch('/api/import', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ instances, history, jobs, job_runs }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) { showToast(data.error ?? 'Import failed', 'error'); return; }
|
||||||
|
const parts = [`${data.imported} instance${data.imported !== 1 ? 's' : ''}`];
|
||||||
|
if (data.imported_jobs != null) parts.push(`${data.imported_jobs} job${data.imported_jobs !== 1 ? 's' : ''}`);
|
||||||
|
showToast(`Imported ${parts.join(', ')}`, 'success');
|
||||||
|
closeSettingsModal();
|
||||||
|
renderDashboard();
|
||||||
|
} catch {
|
||||||
|
showToast('Invalid backup file', 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// ── Keyboard / backdrop ───────────────────────────────────────────────────────
|
// ── Keyboard / backdrop ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
document.addEventListener('keydown', e => {
|
document.addEventListener('keydown', e => {
|
||||||
if (e.key !== 'Escape') return;
|
if (e.key !== 'Escape') return;
|
||||||
if (document.getElementById('instance-modal').classList.contains('open')) { closeModal(); return; }
|
if (document.getElementById('instance-modal').classList.contains('open')) { closeModal(); return; }
|
||||||
if (document.getElementById('confirm-overlay').classList.contains('open')) { closeConfirm(); return; }
|
if (document.getElementById('confirm-overlay').classList.contains('open')) { closeConfirm(); return; }
|
||||||
|
if (document.getElementById('settings-modal').classList.contains('open')) { closeSettingsModal(); return; }
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('instance-modal').addEventListener('click', e => {
|
document.getElementById('instance-modal').addEventListener('click', e => {
|
||||||
@@ -272,3 +451,150 @@ document.getElementById('instance-modal').addEventListener('click', e => {
|
|||||||
document.getElementById('confirm-overlay').addEventListener('click', e => {
|
document.getElementById('confirm-overlay').addEventListener('click', e => {
|
||||||
if (e.target === document.getElementById('confirm-overlay')) closeConfirm();
|
if (e.target === document.getElementById('confirm-overlay')) closeConfirm();
|
||||||
});
|
});
|
||||||
|
document.getElementById('settings-modal').addEventListener('click', e => {
|
||||||
|
if (e.target === document.getElementById('settings-modal')) closeSettingsModal();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('tz-select').addEventListener('change', e => {
|
||||||
|
localStorage.setItem('catalyst_tz', e.target.value);
|
||||||
|
const m = window.location.pathname.match(/^\/instance\/(\d+)/);
|
||||||
|
if (m) renderDetailPage(parseInt(m[1], 10));
|
||||||
|
else renderDashboard();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Jobs Page ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function renderJobsPage() {
|
||||||
|
const jobs = await fetch('/api/jobs').then(r => r.json());
|
||||||
|
_updateJobsNavDot(jobs);
|
||||||
|
document.getElementById('jobs-list').innerHTML = jobs.length
|
||||||
|
? jobs.map(j => `
|
||||||
|
<div class="job-item" id="job-item-${j.id}" onclick="loadJobDetail(${j.id})">
|
||||||
|
<span class="job-dot job-dot--${j.last_status ?? 'none'}"></span>
|
||||||
|
<span class="job-item-name">${esc(j.name)}</span>
|
||||||
|
</div>`).join('')
|
||||||
|
: '<div class="jobs-placeholder">No jobs</div>';
|
||||||
|
if (jobs.length) loadJobDetail(jobs[0].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadJobDetail(jobId) {
|
||||||
|
document.querySelectorAll('.job-item').forEach(el => el.classList.remove('active'));
|
||||||
|
document.getElementById(`job-item-${jobId}`)?.classList.add('active');
|
||||||
|
const job = await fetch(`/api/jobs/${jobId}`).then(r => r.json());
|
||||||
|
const cfg = job.config ?? {};
|
||||||
|
document.getElementById('jobs-detail').innerHTML = `
|
||||||
|
<div class="jobs-detail-hd">
|
||||||
|
<div class="jobs-detail-title">${esc(job.name)}</div>
|
||||||
|
<div class="jobs-detail-desc">${esc(job.description)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label" style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||||
|
<input type="checkbox" id="job-enabled" ${job.enabled ? 'checked' : ''}
|
||||||
|
style="accent-color:var(--accent);width:13px;height:13px">
|
||||||
|
Enable scheduled runs
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<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>
|
||||||
|
<button class="btn btn-secondary" id="job-run-btn" onclick="runJobNow(${job.id})">Run Now</button>
|
||||||
|
</div>
|
||||||
|
<div class="detail-section-title" style="margin:28px 0 10px">Run History</div>
|
||||||
|
${_renderRunList(job.runs)}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _renderJobConfigFields(key, cfg) {
|
||||||
|
if (key === 'tailscale_sync') return `
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label" for="job-cfg-tailnet">Tailnet</label>
|
||||||
|
<input class="form-input" id="job-cfg-tailnet" type="text"
|
||||||
|
placeholder="e.g. Tt3Btpm6D921CNTRL" value="${esc(cfg.tailnet ?? '')}">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label" for="job-cfg-api-key">API Key</label>
|
||||||
|
<input class="form-input" id="job-cfg-api-key" type="password"
|
||||||
|
placeholder="tskey-api-…" value="${esc(cfg.api_key ?? '')}">
|
||||||
|
</div>`;
|
||||||
|
if (key === 'patchmon_sync' || key === 'semaphore_sync') {
|
||||||
|
const label = key === 'semaphore_sync' ? 'API Token (Bearer)' : 'API Token (Basic)';
|
||||||
|
return `
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label" for="job-cfg-api-url">API URL</label>
|
||||||
|
<input class="form-input" id="job-cfg-api-url" type="text"
|
||||||
|
value="${esc(cfg.api_url ?? '')}">
|
||||||
|
</div>
|
||||||
|
<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"
|
||||||
|
value="${esc(cfg.api_token ?? '')}">
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function _renderRunList(runs) {
|
||||||
|
if (!runs?.length) return '<div class="run-empty">No runs yet</div>';
|
||||||
|
return `<div class="run-list">${runs.map(r => `
|
||||||
|
<div class="run-item">
|
||||||
|
<span class="job-dot job-dot--${r.status}"></span>
|
||||||
|
<span class="run-time">${fmtDateFull(r.started_at)}</span>
|
||||||
|
<span class="run-status">${esc(r.status)}</span>
|
||||||
|
<span class="run-result">${esc(r.result)}</span>
|
||||||
|
</div>`).join('')}</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveJobDetail(jobId) {
|
||||||
|
const enabled = document.getElementById('job-enabled').checked;
|
||||||
|
const schedule = document.getElementById('job-schedule').value;
|
||||||
|
const cfg = {};
|
||||||
|
const tailnet = document.getElementById('job-cfg-tailnet');
|
||||||
|
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;
|
||||||
|
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' },
|
||||||
|
body: JSON.stringify({ enabled, schedule: parseInt(schedule, 10), config: cfg }),
|
||||||
|
});
|
||||||
|
if (res.ok) { showToast('Job saved', 'success'); loadJobDetail(jobId); }
|
||||||
|
else { showToast('Failed to save', 'error'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runJobNow(jobId) {
|
||||||
|
const btn = document.getElementById('job-run-btn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Running…';
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/jobs/${jobId}/run`, { method: 'POST' });
|
||||||
|
const data = await res.json();
|
||||||
|
if (res.ok) { showToast(`Done — ${data.summary}`, 'success'); loadJobDetail(jobId); }
|
||||||
|
else { showToast(data.error ?? 'Run failed', 'error'); }
|
||||||
|
} catch { showToast('Run failed', 'error'); }
|
||||||
|
finally { btn.disabled = false; btn.textContent = 'Run Now'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function _updateJobsNavDot(jobs) {
|
||||||
|
const dot = document.getElementById('nav-jobs-dot');
|
||||||
|
const cls = jobs.some(j => j.last_status === 'error') ? 'error'
|
||||||
|
: jobs.some(j => j.last_status === 'success') ? 'success'
|
||||||
|
: 'none';
|
||||||
|
dot.className = `nav-job-dot nav-job-dot--${cls}`;
|
||||||
|
}
|
||||||
|
|||||||
1
js/version.js
Normal file
1
js/version.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
const VERSION = "1.5.0";
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "catalyst",
|
"name": "catalyst",
|
||||||
"version": "1.2.2",
|
"version": "1.6.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server/server.js",
|
"start": "node server/server.js",
|
||||||
|
|||||||
211
server/db.js
211
server/db.js
@@ -17,7 +17,7 @@ function init(path) {
|
|||||||
db.exec('PRAGMA foreign_keys = ON');
|
db.exec('PRAGMA foreign_keys = ON');
|
||||||
db.exec('PRAGMA synchronous = NORMAL');
|
db.exec('PRAGMA synchronous = NORMAL');
|
||||||
createSchema();
|
createSchema();
|
||||||
if (path !== ':memory:') seed();
|
if (path !== ':memory:') { seed(); seedJobs(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function createSchema() {
|
function createSchema() {
|
||||||
@@ -43,6 +43,41 @@ function createSchema() {
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_instances_state ON instances(state);
|
CREATE INDEX IF NOT EXISTS idx_instances_state ON instances(state);
|
||||||
CREATE INDEX IF NOT EXISTS idx_instances_stack ON instances(stack);
|
CREATE INDEX IF NOT EXISTS idx_instances_stack ON instances(stack);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS instance_history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
vmid INTEGER NOT NULL,
|
||||||
|
field TEXT NOT NULL,
|
||||||
|
old_value TEXT,
|
||||||
|
new_value TEXT,
|
||||||
|
changed_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_history_vmid ON instance_history(vmid);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS config (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS jobs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
key TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 0 CHECK(enabled IN (0,1)),
|
||||||
|
schedule INTEGER NOT NULL DEFAULT 15,
|
||||||
|
config TEXT NOT NULL DEFAULT '{}'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS job_runs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
job_id INTEGER NOT NULL,
|
||||||
|
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
|
ended_at TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'running' CHECK(status IN ('running','success','error')),
|
||||||
|
result TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_job_runs_job_id ON job_runs(job_id);
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,6 +108,29 @@ function seed() {
|
|||||||
db.exec('COMMIT');
|
db.exec('COMMIT');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function seedJobs() {
|
||||||
|
const upsert = db.prepare(`
|
||||||
|
INSERT OR IGNORE INTO jobs (key, name, description, enabled, schedule, config)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
|
||||||
|
const apiKey = getConfig('tailscale_api_key');
|
||||||
|
const tailnet = getConfig('tailscale_tailnet');
|
||||||
|
const tsSchedule = parseInt(getConfig('tailscale_poll_minutes', '15'), 10) || 15;
|
||||||
|
const tsEnabled = getConfig('tailscale_enabled') === '1' ? 1 : 0;
|
||||||
|
upsert.run('tailscale_sync', 'Tailscale Sync',
|
||||||
|
'Syncs Tailscale device status and IPs to instances by matching hostnames.',
|
||||||
|
tsEnabled, tsSchedule, JSON.stringify({ api_key: apiKey, tailnet }));
|
||||||
|
|
||||||
|
upsert.run('patchmon_sync', 'Patchmon Sync',
|
||||||
|
'Syncs Patchmon host registration status to instances by matching hostnames.',
|
||||||
|
0, 60, JSON.stringify({ api_url: 'http://patchmon:3000/api/v1/api/hosts', api_token: '' }));
|
||||||
|
|
||||||
|
upsert.run('semaphore_sync', 'Semaphore Sync',
|
||||||
|
'Syncs Semaphore inventory membership to instances by matching hostnames.',
|
||||||
|
0, 60, JSON.stringify({ api_url: 'http://semaphore:3000/api/project/1/inventory/1', api_token: '' }));
|
||||||
|
}
|
||||||
|
|
||||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function getInstances(filters = {}) {
|
export function getInstances(filters = {}) {
|
||||||
@@ -99,8 +157,14 @@ export function getDistinctStacks() {
|
|||||||
|
|
||||||
// ── Mutations ─────────────────────────────────────────────────────────────────
|
// ── Mutations ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const HISTORY_FIELDS = [
|
||||||
|
'name', 'state', 'stack', 'vmid', 'tailscale_ip',
|
||||||
|
'atlas', 'argus', 'semaphore', 'patchmon', 'tailscale', 'andromeda',
|
||||||
|
'hardware_acceleration',
|
||||||
|
];
|
||||||
|
|
||||||
export function createInstance(data) {
|
export function createInstance(data) {
|
||||||
return db.prepare(`
|
db.prepare(`
|
||||||
INSERT INTO instances
|
INSERT INTO instances
|
||||||
(name, state, stack, vmid, atlas, argus, semaphore, patchmon,
|
(name, state, stack, vmid, atlas, argus, semaphore, patchmon,
|
||||||
tailscale, andromeda, tailscale_ip, hardware_acceleration)
|
tailscale, andromeda, tailscale_ip, hardware_acceleration)
|
||||||
@@ -108,21 +172,158 @@ export function createInstance(data) {
|
|||||||
(@name, @state, @stack, @vmid, @atlas, @argus, @semaphore, @patchmon,
|
(@name, @state, @stack, @vmid, @atlas, @argus, @semaphore, @patchmon,
|
||||||
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
|
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
|
||||||
`).run(data);
|
`).run(data);
|
||||||
|
db.prepare(
|
||||||
|
`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);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateInstance(vmid, data) {
|
export function updateInstance(vmid, data) {
|
||||||
return db.prepare(`
|
const old = getInstance(vmid);
|
||||||
|
db.prepare(`
|
||||||
UPDATE instances SET
|
UPDATE instances SET
|
||||||
name=@name, state=@state, stack=@stack, vmid=@newVmid,
|
name=@name, state=@state, stack=@stack, vmid=@newVmid,
|
||||||
atlas=@atlas, argus=@argus, semaphore=@semaphore, patchmon=@patchmon,
|
atlas=@atlas, argus=@argus, semaphore=@semaphore, patchmon=@patchmon,
|
||||||
tailscale=@tailscale, andromeda=@andromeda, tailscale_ip=@tailscale_ip,
|
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
|
WHERE vmid=@vmid
|
||||||
`).run({ ...data, newVmid: data.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, changed_at)
|
||||||
|
VALUES (?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%f', 'now'))`
|
||||||
|
);
|
||||||
|
for (const field of HISTORY_FIELDS) {
|
||||||
|
const oldVal = String(old[field] ?? '');
|
||||||
|
const newVal = String(field === 'vmid' ? newVmid : (data[field] ?? ''));
|
||||||
|
if (oldVal !== newVal) insertEvt.run(newVmid, field, oldVal, newVal);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deleteInstance(vmid) {
|
export function deleteInstance(vmid) {
|
||||||
return db.prepare('DELETE FROM instances WHERE vmid = ?').run(vmid);
|
db.prepare('DELETE FROM instance_history WHERE vmid = ?').run(vmid);
|
||||||
|
db.prepare('DELETE FROM instances WHERE vmid = ?').run(vmid);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importInstances(rows, historyRows = []) {
|
||||||
|
db.exec('BEGIN');
|
||||||
|
db.exec('DELETE FROM instance_history');
|
||||||
|
db.exec('DELETE FROM instances');
|
||||||
|
const insert = db.prepare(`
|
||||||
|
INSERT INTO instances
|
||||||
|
(name, state, stack, vmid, atlas, argus, semaphore, patchmon,
|
||||||
|
tailscale, andromeda, tailscale_ip, hardware_acceleration)
|
||||||
|
VALUES
|
||||||
|
(@name, @state, @stack, @vmid, @atlas, @argus, @semaphore, @patchmon,
|
||||||
|
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
|
||||||
|
`);
|
||||||
|
for (const row of rows) insert.run(row);
|
||||||
|
if (historyRows.length) {
|
||||||
|
const insertHist = db.prepare(
|
||||||
|
`INSERT INTO instance_history (vmid, field, old_value, new_value, changed_at) VALUES (?, ?, ?, ?, ?)`
|
||||||
|
);
|
||||||
|
for (const h of historyRows) insertHist.run(h.vmid, h.field, h.old_value ?? null, h.new_value ?? null, h.changed_at);
|
||||||
|
}
|
||||||
|
db.exec('COMMIT');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getInstanceHistory(vmid) {
|
||||||
|
return db.prepare(
|
||||||
|
'SELECT * FROM instance_history WHERE vmid = ? ORDER BY changed_at DESC, id DESC'
|
||||||
|
).all(vmid);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllHistory() {
|
||||||
|
return db.prepare('SELECT * FROM instance_history ORDER BY vmid, changed_at').all();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllJobs() {
|
||||||
|
return db.prepare('SELECT id, key, name, description, enabled, schedule, config FROM jobs ORDER BY id').all();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllJobRuns() {
|
||||||
|
return db.prepare('SELECT * FROM job_runs ORDER BY job_id, id').all();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importJobs(jobRows, jobRunRows = []) {
|
||||||
|
db.exec('BEGIN');
|
||||||
|
db.exec('DELETE FROM job_runs');
|
||||||
|
db.exec('DELETE FROM jobs');
|
||||||
|
const insertJob = db.prepare(`
|
||||||
|
INSERT INTO jobs (id, key, name, description, enabled, schedule, config)
|
||||||
|
VALUES (@id, @key, @name, @description, @enabled, @schedule, @config)
|
||||||
|
`);
|
||||||
|
for (const j of jobRows) insertJob.run(j);
|
||||||
|
if (jobRunRows.length) {
|
||||||
|
const insertRun = db.prepare(`
|
||||||
|
INSERT INTO job_runs (id, job_id, started_at, ended_at, status, result)
|
||||||
|
VALUES (@id, @job_id, @started_at, @ended_at, @status, @result)
|
||||||
|
`);
|
||||||
|
for (const r of jobRunRows) insertRun.run(r);
|
||||||
|
}
|
||||||
|
db.exec('COMMIT');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfig(key, defaultVal = '') {
|
||||||
|
const row = db.prepare('SELECT value FROM config WHERE key = ?').get(key);
|
||||||
|
return row ? row.value : defaultVal;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setConfig(key, value) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO config (key, value) VALUES (?, ?)
|
||||||
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
|
||||||
|
).run(key, String(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Jobs ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const JOB_WITH_LAST_RUN = `
|
||||||
|
SELECT j.*,
|
||||||
|
r.id AS last_run_id,
|
||||||
|
r.started_at AS last_run_at,
|
||||||
|
r.status AS last_status,
|
||||||
|
r.result AS last_result
|
||||||
|
FROM jobs j
|
||||||
|
LEFT JOIN job_runs r
|
||||||
|
ON r.id = (SELECT id FROM job_runs WHERE job_id = j.id ORDER BY id DESC LIMIT 1)
|
||||||
|
`;
|
||||||
|
|
||||||
|
export function getJobs() {
|
||||||
|
return db.prepare(JOB_WITH_LAST_RUN + ' ORDER BY j.id').all();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getJob(id) {
|
||||||
|
return db.prepare(JOB_WITH_LAST_RUN + ' WHERE j.id = ?').get(id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createJob(data) {
|
||||||
|
db.prepare(`
|
||||||
|
INSERT INTO jobs (key, name, description, enabled, schedule, config)
|
||||||
|
VALUES (@key, @name, @description, @enabled, @schedule, @config)
|
||||||
|
`).run(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateJob(id, { enabled, schedule, config }) {
|
||||||
|
db.prepare(`
|
||||||
|
UPDATE jobs SET enabled=@enabled, schedule=@schedule, config=@config WHERE id=@id
|
||||||
|
`).run({ id, enabled, schedule, config });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createJobRun(jobId) {
|
||||||
|
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=strftime('%Y-%m-%dT%H:%M:%f', 'now'), status=@status, result=@result WHERE id=@id
|
||||||
|
`).run({ id: runId, status, result });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getJobRuns(jobId) {
|
||||||
|
return db.prepare('SELECT * FROM job_runs WHERE job_id = ? ORDER BY id DESC').all(jobId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Test helpers ──────────────────────────────────────────────────────────────
|
// ── Test helpers ──────────────────────────────────────────────────────────────
|
||||||
|
|||||||
150
server/jobs.js
Normal file
150
server/jobs.js
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import { getJobs, getJob, getInstances, updateInstance, createJobRun, completeJobRun } from './db.js';
|
||||||
|
|
||||||
|
// ── Handlers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const TAILSCALE_API = 'https://api.tailscale.com/api/v2';
|
||||||
|
|
||||||
|
async function tailscaleSyncHandler(cfg) {
|
||||||
|
const { api_key, tailnet } = cfg;
|
||||||
|
if (!api_key || !tailnet) throw new Error('Tailscale not configured — set API key and tailnet');
|
||||||
|
|
||||||
|
const res = await fetch(
|
||||||
|
`${TAILSCALE_API}/tailnet/${encodeURIComponent(tailnet)}/devices`,
|
||||||
|
{ headers: { Authorization: `Bearer ${api_key}` } }
|
||||||
|
);
|
||||||
|
if (!res.ok) throw new Error(`Tailscale API ${res.status}`);
|
||||||
|
|
||||||
|
const { devices } = await res.json();
|
||||||
|
const tsMap = new Map(
|
||||||
|
devices.map(d => [d.hostname, (d.addresses ?? []).find(a => a.startsWith('100.')) ?? ''])
|
||||||
|
);
|
||||||
|
|
||||||
|
const instances = getInstances();
|
||||||
|
let updated = 0;
|
||||||
|
for (const inst of instances) {
|
||||||
|
const tsIp = tsMap.get(inst.name);
|
||||||
|
const matched = tsIp !== undefined;
|
||||||
|
const newTailscale = matched ? 1 : (inst.tailscale === 1 ? 0 : inst.tailscale);
|
||||||
|
const newIp = matched ? tsIp : (inst.tailscale === 1 ? '' : inst.tailscale_ip);
|
||||||
|
if (newTailscale !== inst.tailscale || newIp !== inst.tailscale_ip) {
|
||||||
|
const { id: _id, created_at: _ca, updated_at: _ua, ...instData } = inst;
|
||||||
|
updateInstance(inst.vmid, { ...instData, tailscale: newTailscale, tailscale_ip: newIp });
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { summary: `${updated} updated of ${instances.length}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Patchmon Sync ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
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');
|
||||||
|
|
||||||
|
const res = await fetch(api_url, {
|
||||||
|
headers: { Authorization: `Basic ${api_token}` },
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Patchmon API ${res.status}`);
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
const items = Array.isArray(data) ? data : (data.hosts ?? data.data ?? []);
|
||||||
|
const hostSet = new Set(
|
||||||
|
items.map(h => (typeof h === 'string' ? h : (h.name ?? h.hostname ?? h.host ?? '')))
|
||||||
|
.filter(Boolean)
|
||||||
|
);
|
||||||
|
|
||||||
|
const instances = getInstances();
|
||||||
|
let updated = 0;
|
||||||
|
for (const inst of instances) {
|
||||||
|
const newPatchmon = hostSet.has(inst.name) ? 1 : 0;
|
||||||
|
if (newPatchmon !== inst.patchmon) {
|
||||||
|
const { id: _id, created_at: _ca, updated_at: _ua, ...instData } = inst;
|
||||||
|
updateInstance(inst.vmid, { ...instData, patchmon: newPatchmon });
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { summary: `${updated} updated of ${instances.length}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Semaphore Sync ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function semaphoreSyncHandler(cfg) {
|
||||||
|
const { api_url, api_token } = cfg;
|
||||||
|
if (!api_url || !api_token) throw new Error('Semaphore not configured — set API URL and token');
|
||||||
|
|
||||||
|
const res = await fetch(api_url, {
|
||||||
|
headers: { Authorization: `Bearer ${api_token}` },
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Semaphore API ${res.status}`);
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
// Inventory is an Ansible INI string; extract bare hostnames
|
||||||
|
const hostSet = new Set(
|
||||||
|
(data.inventory ?? '').split('\n')
|
||||||
|
.map(l => l.trim())
|
||||||
|
.filter(l => l && !l.startsWith('[') && !l.startsWith('#') && !l.startsWith(';'))
|
||||||
|
.map(l => l.split(/[\s=]/)[0])
|
||||||
|
.filter(Boolean)
|
||||||
|
);
|
||||||
|
|
||||||
|
const instances = getInstances();
|
||||||
|
let updated = 0;
|
||||||
|
for (const inst of instances) {
|
||||||
|
const newSemaphore = hostSet.has(inst.name) ? 1 : 0;
|
||||||
|
if (newSemaphore !== inst.semaphore) {
|
||||||
|
const { id: _id, created_at: _ca, updated_at: _ua, ...instData } = inst;
|
||||||
|
updateInstance(inst.vmid, { ...instData, semaphore: newSemaphore });
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { summary: `${updated} updated of ${instances.length}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Registry ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const HANDLERS = {
|
||||||
|
tailscale_sync: tailscaleSyncHandler,
|
||||||
|
patchmon_sync: patchmonSyncHandler,
|
||||||
|
semaphore_sync: semaphoreSyncHandler,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Public API ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function runJob(jobId) {
|
||||||
|
const job = getJob(jobId);
|
||||||
|
if (!job) throw new Error('Job not found');
|
||||||
|
const handler = HANDLERS[job.key];
|
||||||
|
if (!handler) throw new Error(`No handler for '${job.key}'`);
|
||||||
|
const cfg = JSON.parse(job.config || '{}');
|
||||||
|
const runId = createJobRun(jobId);
|
||||||
|
try {
|
||||||
|
const result = await handler(cfg);
|
||||||
|
completeJobRun(runId, 'success', result.summary ?? '');
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
completeJobRun(runId, 'error', e.message);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
for (const job of getJobs()) {
|
||||||
|
if (!job.enabled) continue;
|
||||||
|
const ms = Math.max(1, job.schedule || 15) * 60_000;
|
||||||
|
const id = job.id;
|
||||||
|
_intervals.set(id, setInterval(() => runJob(id).catch(() => {}), ms));
|
||||||
|
}
|
||||||
|
}
|
||||||
128
server/routes.js
128
server/routes.js
@@ -1,8 +1,11 @@
|
|||||||
import { Router } from 'express';
|
import { Router } from 'express';
|
||||||
import {
|
import {
|
||||||
getInstances, getInstance, getDistinctStacks,
|
getInstances, getInstance, getDistinctStacks,
|
||||||
createInstance, updateInstance, deleteInstance,
|
createInstance, updateInstance, deleteInstance, importInstances, getInstanceHistory, getAllHistory,
|
||||||
|
getConfig, setConfig, getJobs, getJob, updateJob, getJobRuns,
|
||||||
|
getAllJobs, getAllJobRuns, importJobs,
|
||||||
} from './db.js';
|
} from './db.js';
|
||||||
|
import { runJob, restartJobs, runJobsOnCreate } from './jobs.js';
|
||||||
|
|
||||||
export const router = Router();
|
export const router = Router();
|
||||||
|
|
||||||
@@ -12,6 +15,15 @@ const VALID_STATES = ['deployed', 'testing', 'degraded'];
|
|||||||
const VALID_STACKS = ['production', 'development'];
|
const VALID_STACKS = ['production', 'development'];
|
||||||
const SERVICE_KEYS = ['atlas', 'argus', 'semaphore', 'patchmon', 'tailscale', 'andromeda'];
|
const SERVICE_KEYS = ['atlas', 'argus', 'semaphore', 'patchmon', 'tailscale', 'andromeda'];
|
||||||
|
|
||||||
|
const REDACTED = '**REDACTED**';
|
||||||
|
|
||||||
|
function maskJob(job) {
|
||||||
|
const cfg = JSON.parse(job.config || '{}');
|
||||||
|
if (cfg.api_key) cfg.api_key = REDACTED;
|
||||||
|
if (cfg.api_token) cfg.api_token = REDACTED;
|
||||||
|
return { ...job, config: cfg };
|
||||||
|
}
|
||||||
|
|
||||||
function validate(body) {
|
function validate(body) {
|
||||||
const errors = [];
|
const errors = [];
|
||||||
if (!body.name || typeof body.name !== 'string' || !body.name.trim())
|
if (!body.name || typeof body.name !== 'string' || !body.name.trim())
|
||||||
@@ -28,9 +40,16 @@ function validate(body) {
|
|||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleDbError(context, e, res) {
|
||||||
|
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
|
||||||
|
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
|
||||||
|
console.error(context, e);
|
||||||
|
res.status(500).json({ error: 'internal server error' });
|
||||||
|
}
|
||||||
|
|
||||||
function normalise(body) {
|
function normalise(body) {
|
||||||
const row = {
|
const row = {
|
||||||
name: body.name.trim(),
|
name: (body.name ?? '').trim(),
|
||||||
state: body.state,
|
state: body.state,
|
||||||
stack: body.stack,
|
stack: body.stack,
|
||||||
vmid: body.vmid,
|
vmid: body.vmid,
|
||||||
@@ -54,6 +73,14 @@ router.get('/instances', (req, res) => {
|
|||||||
res.json(getInstances({ search, state, stack }));
|
res.json(getInstances({ search, state, stack }));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GET /api/instances/:vmid/history
|
||||||
|
router.get('/instances/:vmid/history', (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' });
|
||||||
|
res.json(getInstanceHistory(vmid));
|
||||||
|
});
|
||||||
|
|
||||||
// GET /api/instances/:vmid
|
// GET /api/instances/:vmid
|
||||||
router.get('/instances/:vmid', (req, res) => {
|
router.get('/instances/:vmid', (req, res) => {
|
||||||
const vmid = parseInt(req.params.vmid, 10);
|
const vmid = parseInt(req.params.vmid, 10);
|
||||||
@@ -75,11 +102,9 @@ router.post('/instances', (req, res) => {
|
|||||||
createInstance(data);
|
createInstance(data);
|
||||||
const created = getInstance(data.vmid);
|
const created = getInstance(data.vmid);
|
||||||
res.status(201).json(created);
|
res.status(201).json(created);
|
||||||
|
runJobsOnCreate().catch(() => {});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
|
handleDbError('POST /api/instances', e, res);
|
||||||
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
|
|
||||||
console.error('POST /api/instances', e);
|
|
||||||
res.status(500).json({ error: 'internal server error' });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -97,9 +122,45 @@ router.put('/instances/:vmid', (req, res) => {
|
|||||||
updateInstance(vmid, data);
|
updateInstance(vmid, data);
|
||||||
res.json(getInstance(data.vmid));
|
res.json(getInstance(data.vmid));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
|
handleDbError('PUT /api/instances/:vmid', e, res);
|
||||||
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
|
}
|
||||||
console.error('PUT /api/instances/:vmid', e);
|
});
|
||||||
|
|
||||||
|
// GET /api/export
|
||||||
|
router.get('/export', (_req, res) => {
|
||||||
|
const instances = getInstances();
|
||||||
|
const history = getAllHistory();
|
||||||
|
const jobs = getAllJobs();
|
||||||
|
const job_runs = getAllJobRuns();
|
||||||
|
const date = new Date().toISOString().slice(0, 10);
|
||||||
|
res.setHeader('Content-Disposition', `attachment; filename="catalyst-backup-${date}.json"`);
|
||||||
|
res.json({ version: 3, exported_at: new Date().toISOString(), instances, history, jobs, job_runs });
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/import
|
||||||
|
router.post('/import', (req, res) => {
|
||||||
|
const { instances, history = [], jobs, job_runs } = req.body ?? {};
|
||||||
|
if (!Array.isArray(instances)) {
|
||||||
|
return res.status(400).json({ error: 'body must contain an instances array' });
|
||||||
|
}
|
||||||
|
const errors = [];
|
||||||
|
for (const [i, row] of instances.entries()) {
|
||||||
|
const errs = validate(normalise(row));
|
||||||
|
if (errs.length) errors.push({ index: i, errors: errs });
|
||||||
|
}
|
||||||
|
if (errors.length) return res.status(400).json({ errors });
|
||||||
|
try {
|
||||||
|
importInstances(instances.map(normalise), Array.isArray(history) ? history : []);
|
||||||
|
if (Array.isArray(jobs)) {
|
||||||
|
importJobs(jobs, Array.isArray(job_runs) ? job_runs : []);
|
||||||
|
try { restartJobs(); } catch (e) { console.error('POST /api/import restartJobs', e); }
|
||||||
|
}
|
||||||
|
res.json({
|
||||||
|
imported: instances.length,
|
||||||
|
imported_jobs: Array.isArray(jobs) ? jobs.length : undefined,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('POST /api/import', e);
|
||||||
res.status(500).json({ error: 'internal server error' });
|
res.status(500).json({ error: 'internal server error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -118,7 +179,52 @@ router.delete('/instances/:vmid', (req, res) => {
|
|||||||
deleteInstance(vmid);
|
deleteInstance(vmid);
|
||||||
res.status(204).end();
|
res.status(204).end();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('DELETE /api/instances/:vmid', e);
|
handleDbError('DELETE /api/instances/:vmid', e, res);
|
||||||
res.status(500).json({ error: 'internal server error' });
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/jobs
|
||||||
|
router.get('/jobs', (_req, res) => {
|
||||||
|
res.json(getJobs().map(maskJob));
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/jobs/:id
|
||||||
|
router.get('/jobs/:id', (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (!id) return res.status(400).json({ error: 'invalid id' });
|
||||||
|
const job = getJob(id);
|
||||||
|
if (!job) return res.status(404).json({ error: 'job not found' });
|
||||||
|
res.json({ ...maskJob(job), runs: getJobRuns(id) });
|
||||||
|
});
|
||||||
|
|
||||||
|
// PUT /api/jobs/:id
|
||||||
|
router.put('/jobs/:id', (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (!id) return res.status(400).json({ error: 'invalid id' });
|
||||||
|
const job = getJob(id);
|
||||||
|
if (!job) return res.status(404).json({ error: 'job not found' });
|
||||||
|
const { enabled, schedule, config: newCfg } = req.body ?? {};
|
||||||
|
const existingCfg = JSON.parse(job.config || '{}');
|
||||||
|
const mergedCfg = { ...existingCfg, ...(newCfg ?? {}) };
|
||||||
|
if (newCfg?.api_key === REDACTED) mergedCfg.api_key = existingCfg.api_key;
|
||||||
|
if (newCfg?.api_token === REDACTED) mergedCfg.api_token = existingCfg.api_token;
|
||||||
|
updateJob(id, {
|
||||||
|
enabled: enabled != null ? (enabled ? 1 : 0) : job.enabled,
|
||||||
|
schedule: schedule != null ? (parseInt(schedule, 10) || 15) : job.schedule,
|
||||||
|
config: JSON.stringify(mergedCfg),
|
||||||
|
});
|
||||||
|
try { restartJobs(); } catch (e) { console.error('PUT /api/jobs/:id restartJobs', e); }
|
||||||
|
res.json(maskJob(getJob(id)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/jobs/:id/run
|
||||||
|
router.post('/jobs/:id/run', async (req, res) => {
|
||||||
|
const id = parseInt(req.params.id, 10);
|
||||||
|
if (!id) return res.status(400).json({ error: 'invalid id' });
|
||||||
|
if (!getJob(id)) return res.status(404).json({ error: 'job not found' });
|
||||||
|
try {
|
||||||
|
res.json(await runJob(id));
|
||||||
|
} catch (e) {
|
||||||
|
handleDbError('POST /api/jobs/:id/run', e, res);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import helmet from 'helmet';
|
|||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
import { dirname, join } from 'path';
|
import { dirname, join } from 'path';
|
||||||
import { router } from './routes.js';
|
import { router } from './routes.js';
|
||||||
|
import { restartJobs } from './jobs.js';
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const PORT = process.env.PORT ?? 3000;
|
const PORT = process.env.PORT ?? 3000;
|
||||||
@@ -47,5 +48,6 @@ app.use((err, _req, res, _next) => {
|
|||||||
|
|
||||||
// Boot — only when run directly, not when imported by tests
|
// Boot — only when run directly, not when imported by tests
|
||||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||||
|
restartJobs();
|
||||||
app.listen(PORT, () => console.log(`catalyst on :${PORT}`));
|
app.listen(PORT, () => console.log(`catalyst on :${PORT}`));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||||
import request from 'supertest'
|
import request from 'supertest'
|
||||||
import { app } from '../server/server.js'
|
import { app } from '../server/server.js'
|
||||||
import { _resetForTest } from '../server/db.js'
|
import { _resetForTest, createJob } from '../server/db.js'
|
||||||
import * as dbModule from '../server/db.js'
|
import * as dbModule from '../server/db.js'
|
||||||
|
|
||||||
beforeEach(() => _resetForTest())
|
beforeEach(() => _resetForTest())
|
||||||
@@ -239,6 +239,147 @@ describe('DELETE /api/instances/:vmid', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ── GET /api/instances/:vmid/history ─────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('GET /api/instances/:vmid/history', () => {
|
||||||
|
it('returns history events for a known vmid', async () => {
|
||||||
|
await request(app).post('/api/instances').send(base)
|
||||||
|
const res = await request(app).get('/api/instances/100/history')
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body).toBeInstanceOf(Array)
|
||||||
|
expect(res.body[0].field).toBe('created')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 for unknown vmid', async () => {
|
||||||
|
expect((await request(app).get('/api/instances/999/history')).status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 for non-numeric vmid', async () => {
|
||||||
|
expect((await request(app).get('/api/instances/abc/history')).status).toBe(400)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── GET /api/export ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('GET /api/export', () => {
|
||||||
|
it('returns 200 with instances array and attachment header', async () => {
|
||||||
|
await request(app).post('/api/instances').send(base)
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.headers['content-disposition']).toMatch(/attachment/)
|
||||||
|
expect(res.body.instances).toHaveLength(1)
|
||||||
|
expect(res.body.instances[0].name).toBe('traefik')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns empty instances array when no data', async () => {
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.body.instances).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns version 3', async () => {
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.body.version).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes a history array', async () => {
|
||||||
|
await request(app).post('/api/instances').send(base)
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.body.history).toBeInstanceOf(Array)
|
||||||
|
expect(res.body.history.some(e => e.field === 'created')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes jobs and job_runs arrays', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.body.jobs).toBeInstanceOf(Array)
|
||||||
|
expect(res.body.jobs).toHaveLength(1)
|
||||||
|
expect(res.body.jobs[0].key).toBe('tailscale_sync')
|
||||||
|
expect(res.body.job_runs).toBeInstanceOf(Array)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('exports raw job config without masking', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const res = await request(app).get('/api/export')
|
||||||
|
expect(res.body.jobs[0].config).toContain('tskey-test')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── POST /api/import ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('POST /api/import', () => {
|
||||||
|
it('replaces all instances and returns imported count', async () => {
|
||||||
|
await request(app).post('/api/instances').send(base)
|
||||||
|
const res = await request(app).post('/api/import')
|
||||||
|
.send({ instances: [{ ...base, vmid: 999, name: 'imported' }] })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.imported).toBe(1)
|
||||||
|
expect((await request(app).get('/api/instances')).body[0].name).toBe('imported')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 if instances is not an array', async () => {
|
||||||
|
expect((await request(app).post('/api/import').send({ instances: 'bad' })).status).toBe(400)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 with per-row errors for invalid rows', async () => {
|
||||||
|
const res = await request(app).post('/api/import')
|
||||||
|
.send({ instances: [{ ...base, name: '', vmid: 1 }] })
|
||||||
|
expect(res.status).toBe(400)
|
||||||
|
expect(res.body.errors[0].index).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 if body has no instances key', async () => {
|
||||||
|
expect((await request(app).post('/api/import').send({})).status).toBe(400)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 (not 500) when a row is missing name', async () => {
|
||||||
|
const res = await request(app).post('/api/import')
|
||||||
|
.send({ instances: [{ ...base, name: undefined, vmid: 1 }] })
|
||||||
|
expect(res.status).toBe(400)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores history when history array is provided', async () => {
|
||||||
|
await request(app).post('/api/instances').send(base)
|
||||||
|
const exp = await request(app).get('/api/export')
|
||||||
|
await request(app).post('/api/instances').send({ ...base, vmid: 999, name: 'other' })
|
||||||
|
const res = await request(app).post('/api/import').send({
|
||||||
|
instances: exp.body.instances,
|
||||||
|
history: exp.body.history,
|
||||||
|
})
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const hist = await request(app).get('/api/instances/100/history')
|
||||||
|
expect(hist.body.some(e => e.field === 'created')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('succeeds with a v1 backup that has no history key', async () => {
|
||||||
|
const res = await request(app).post('/api/import')
|
||||||
|
.send({ instances: [{ ...base, vmid: 1, name: 'legacy' }] })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.imported).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('imports jobs and job_runs and returns imported_jobs count', async () => {
|
||||||
|
const exp = await request(app).get('/api/export')
|
||||||
|
createJob(testJob)
|
||||||
|
const fullExport = await request(app).get('/api/export')
|
||||||
|
const res = await request(app).post('/api/import').send({
|
||||||
|
instances: fullExport.body.instances,
|
||||||
|
history: fullExport.body.history,
|
||||||
|
jobs: fullExport.body.jobs,
|
||||||
|
job_runs: fullExport.body.job_runs,
|
||||||
|
})
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.imported_jobs).toBe(1)
|
||||||
|
expect((await request(app).get('/api/jobs')).body).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves jobs untouched when no jobs key in payload', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
await request(app).post('/api/import')
|
||||||
|
.send({ instances: [{ ...base, vmid: 1, name: 'x' }] })
|
||||||
|
expect((await request(app).get('/api/jobs')).body).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
// ── Static assets & SPA routing ───────────────────────────────────────────────
|
// ── Static assets & SPA routing ───────────────────────────────────────────────
|
||||||
|
|
||||||
describe('static assets and SPA routing', () => {
|
describe('static assets and SPA routing', () => {
|
||||||
@@ -349,3 +490,172 @@ describe('error handling — unexpected DB failures', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const testJob = {
|
||||||
|
key: 'tailscale_sync', name: 'Tailscale Sync', description: 'Test job',
|
||||||
|
enabled: 0, schedule: 15,
|
||||||
|
config: JSON.stringify({ api_key: 'tskey-test', tailnet: 'example.com' }),
|
||||||
|
}
|
||||||
|
|
||||||
|
const patchmonJob = {
|
||||||
|
key: 'patchmon_sync', name: 'Patchmon Sync', description: 'Test patchmon job',
|
||||||
|
enabled: 0, schedule: 60,
|
||||||
|
config: JSON.stringify({ api_url: 'http://patchmon:3000/api/v1/api/hosts', api_token: 'secret-token' }),
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── GET /api/jobs ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('GET /api/jobs', () => {
|
||||||
|
it('returns empty array when no jobs', async () => {
|
||||||
|
const res = await request(app).get('/api/jobs')
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns jobs with masked api key', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const res = await request(app).get('/api/jobs')
|
||||||
|
expect(res.body).toHaveLength(1)
|
||||||
|
expect(res.body[0].config.api_key).toBe('**REDACTED**')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns jobs with masked api_token', async () => {
|
||||||
|
createJob(patchmonJob)
|
||||||
|
const res = await request(app).get('/api/jobs')
|
||||||
|
expect(res.body[0].config.api_token).toBe('**REDACTED**')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── GET /api/jobs/:id ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('GET /api/jobs/:id', () => {
|
||||||
|
it('returns job with runs array', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
const res = await request(app).get(`/api/jobs/${id}`)
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.runs).toBeInstanceOf(Array)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 for unknown id', async () => {
|
||||||
|
expect((await request(app).get('/api/jobs/999')).status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 for non-numeric id', async () => {
|
||||||
|
expect((await request(app).get('/api/jobs/abc')).status).toBe(400)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── PUT /api/jobs/:id ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('PUT /api/jobs/:id', () => {
|
||||||
|
it('updates enabled and schedule', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
const res = await request(app).put(`/api/jobs/${id}`).send({ enabled: true, schedule: 30 })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.enabled).toBe(1)
|
||||||
|
expect(res.body.schedule).toBe(30)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not overwrite api_key when **REDACTED** is sent', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
await request(app).put(`/api/jobs/${id}`).send({ config: { api_key: '**REDACTED**' } })
|
||||||
|
expect(dbModule.getJob(id).config).toContain('tskey-test')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 for unknown id', async () => {
|
||||||
|
expect((await request(app).put('/api/jobs/999').send({})).status).toBe(404)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── POST /api/jobs/:id/run ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('POST /api/jobs/:id/run', () => {
|
||||||
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
|
it('returns 404 for unknown id', async () => {
|
||||||
|
expect((await request(app).post('/api/jobs/999/run')).status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('runs job, returns summary, and logs the run', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ devices: [] }),
|
||||||
|
}))
|
||||||
|
const res = await request(app).post(`/api/jobs/${id}/run`)
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.summary).toBeDefined()
|
||||||
|
const detail = await request(app).get(`/api/jobs/${id}`)
|
||||||
|
expect(detail.body.runs).toHaveLength(1)
|
||||||
|
expect(detail.body.runs[0].status).toBe('success')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('logs error run on failure', async () => {
|
||||||
|
createJob(testJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
vi.stubGlobal('fetch', vi.fn().mockRejectedValueOnce(new Error('network error')))
|
||||||
|
const res = await request(app).post(`/api/jobs/${id}/run`)
|
||||||
|
expect(res.status).toBe(500)
|
||||||
|
const detail = await request(app).get(`/api/jobs/${id}`)
|
||||||
|
expect(detail.body.runs[0].status).toBe('error')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('patchmon_sync: marks instances present in host list as patchmon=1', async () => {
|
||||||
|
createJob(patchmonJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => [{ name: 'plex' }, { name: 'traefik' }],
|
||||||
|
}))
|
||||||
|
const res = await request(app).post(`/api/jobs/${id}/run`)
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.summary).toMatch(/updated of/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('patchmon_sync: returns 500 when API token is missing', async () => {
|
||||||
|
createJob({ ...patchmonJob, config: JSON.stringify({ api_url: 'http://patchmon:3000/api/v1/api/hosts', api_token: '' }) })
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
const res = await request(app).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',
|
||||||
|
enabled: 0, schedule: 60,
|
||||||
|
config: JSON.stringify({ api_url: 'http://semaphore:3000/api/project/1/inventory/1', api_token: 'bearer-token' }),
|
||||||
|
}
|
||||||
|
createJob(semaphoreJob)
|
||||||
|
const id = (await request(app).get('/api/jobs')).body[0].id
|
||||||
|
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ inventory: '[production]\nplex\nhomeassistant\n' }),
|
||||||
|
}))
|
||||||
|
const res = await request(app).post(`/api/jobs/${id}/run`)
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(res.body.summary).toMatch(/updated of/)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
203
tests/db.test.js
203
tests/db.test.js
@@ -2,7 +2,9 @@ import { describe, it, expect, beforeEach } from 'vitest'
|
|||||||
import {
|
import {
|
||||||
_resetForTest,
|
_resetForTest,
|
||||||
getInstances, getInstance, getDistinctStacks,
|
getInstances, getInstance, getDistinctStacks,
|
||||||
createInstance, updateInstance, deleteInstance,
|
createInstance, updateInstance, deleteInstance, importInstances, getInstanceHistory,
|
||||||
|
getConfig, setConfig,
|
||||||
|
getJobs, getJob, createJob, updateJob, createJobRun, completeJobRun, getJobRuns,
|
||||||
} from '../server/db.js'
|
} from '../server/db.js'
|
||||||
|
|
||||||
beforeEach(() => _resetForTest());
|
beforeEach(() => _resetForTest());
|
||||||
@@ -164,6 +166,90 @@ describe('deleteInstance', () => {
|
|||||||
expect(getInstance(1)).toBeNull();
|
expect(getInstance(1)).toBeNull();
|
||||||
expect(getInstance(2)).not.toBeNull();
|
expect(getInstance(2)).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('clears history for the deleted instance', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
deleteInstance(1);
|
||||||
|
expect(getInstanceHistory(1)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not clear history for other instances', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
createInstance({ ...base, name: 'b', vmid: 2 });
|
||||||
|
deleteInstance(1);
|
||||||
|
expect(getInstanceHistory(2).length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── importInstances ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('importInstances', () => {
|
||||||
|
const base = { state: 'deployed', stack: 'production', atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 };
|
||||||
|
|
||||||
|
it('replaces all existing instances with the imported set', () => {
|
||||||
|
createInstance({ ...base, name: 'old', vmid: 1 });
|
||||||
|
importInstances([{ ...base, name: 'new', vmid: 2 }]);
|
||||||
|
expect(getInstance(1)).toBeNull();
|
||||||
|
expect(getInstance(2)).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears all instances when passed an empty array', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
importInstances([]);
|
||||||
|
expect(getInstances()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears history for all replaced instances', () => {
|
||||||
|
createInstance({ ...base, name: 'old', vmid: 1 });
|
||||||
|
importInstances([{ ...base, name: 'new', vmid: 2 }]);
|
||||||
|
expect(getInstanceHistory(1)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores history rows when provided', () => {
|
||||||
|
importInstances(
|
||||||
|
[{ ...base, name: 'a', vmid: 1 }],
|
||||||
|
[{ vmid: 1, field: 'created', old_value: null, new_value: null, changed_at: '2026-01-01 00:00:00' }]
|
||||||
|
);
|
||||||
|
const h = getInstanceHistory(1);
|
||||||
|
expect(h.some(e => e.field === 'created')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── instance history ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('instance history', () => {
|
||||||
|
const base = { state: 'deployed', stack: 'production', atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 };
|
||||||
|
|
||||||
|
it('logs a created event when an instance is created', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
const h = getInstanceHistory(1);
|
||||||
|
expect(h).toHaveLength(1);
|
||||||
|
expect(h[0].field).toBe('created');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs changed fields when an instance is updated', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
updateInstance(1, { ...base, name: 'a', vmid: 1, state: 'degraded' });
|
||||||
|
const h = getInstanceHistory(1);
|
||||||
|
const stateEvt = h.find(e => e.field === 'state');
|
||||||
|
expect(stateEvt).toBeDefined();
|
||||||
|
expect(stateEvt.old_value).toBe('deployed');
|
||||||
|
expect(stateEvt.new_value).toBe('degraded');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs no events when nothing changes on update', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
updateInstance(1, { ...base, name: 'a', vmid: 1 });
|
||||||
|
const h = getInstanceHistory(1).filter(e => e.field !== 'created');
|
||||||
|
expect(h).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records history under the new vmid when vmid changes', () => {
|
||||||
|
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||||
|
updateInstance(1, { ...base, name: 'a', vmid: 2 });
|
||||||
|
expect(getInstanceHistory(2).some(e => e.field === 'vmid')).toBe(true);
|
||||||
|
expect(getInstanceHistory(1).filter(e => e.field !== 'created')).toHaveLength(0);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Test environment boot isolation ───────────────────────────────────────────
|
// ── Test environment boot isolation ───────────────────────────────────────────
|
||||||
@@ -185,3 +271,118 @@ describe('test environment boot isolation', () => {
|
|||||||
expect(getInstances()).toEqual([]);
|
expect(getInstances()).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── getConfig / setConfig ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('getConfig / setConfig', () => {
|
||||||
|
it('returns defaultVal when key does not exist', () => {
|
||||||
|
expect(getConfig('missing', 'fallback')).toBe('fallback');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty string by default', () => {
|
||||||
|
expect(getConfig('missing')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores and retrieves a value', () => {
|
||||||
|
setConfig('tailscale_api_key', 'tskey-test');
|
||||||
|
expect(getConfig('tailscale_api_key')).toBe('tskey-test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('overwrites an existing key', () => {
|
||||||
|
setConfig('tailscale_enabled', '0');
|
||||||
|
setConfig('tailscale_enabled', '1');
|
||||||
|
expect(getConfig('tailscale_enabled')).toBe('1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('config is cleared by _resetForTest', () => {
|
||||||
|
setConfig('tailscale_api_key', 'tskey-test');
|
||||||
|
_resetForTest();
|
||||||
|
expect(getConfig('tailscale_api_key')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── jobs ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const baseJob = {
|
||||||
|
key: 'test_job', name: 'Test Job', description: 'desc',
|
||||||
|
enabled: 0, schedule: 15, config: '{}',
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('jobs', () => {
|
||||||
|
it('returns empty array when no jobs', () => {
|
||||||
|
expect(getJobs()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createJob + getJobs returns the job', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
expect(getJobs()).toHaveLength(1);
|
||||||
|
expect(getJobs()[0].name).toBe('Test Job');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getJob returns null for unknown id', () => {
|
||||||
|
expect(getJob(999)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updateJob changes enabled and schedule', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
updateJob(id, { enabled: 1, schedule: 30, config: '{}' });
|
||||||
|
expect(getJob(id).enabled).toBe(1);
|
||||||
|
expect(getJob(id).schedule).toBe(30);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getJobs includes last_status null when no runs', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
expect(getJobs()[0].last_status).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getJobs reflects last_status after a run', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
const runId = createJobRun(id);
|
||||||
|
completeJobRun(runId, 'success', 'ok');
|
||||||
|
expect(getJobs()[0].last_status).toBe('success');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── job_runs ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('job_runs', () => {
|
||||||
|
it('createJobRun returns a positive id', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
expect(createJobRun(id)).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('new run has status running and no ended_at', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
const runId = createJobRun(id);
|
||||||
|
const runs = getJobRuns(id);
|
||||||
|
expect(runs[0].status).toBe('running');
|
||||||
|
expect(runs[0].ended_at).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('completeJobRun sets status, result, and ended_at', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
const runId = createJobRun(id);
|
||||||
|
completeJobRun(runId, 'success', '2 updated of 8');
|
||||||
|
const run = getJobRuns(id)[0];
|
||||||
|
expect(run.status).toBe('success');
|
||||||
|
expect(run.result).toBe('2 updated of 8');
|
||||||
|
expect(run.ended_at).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getJobRuns returns newest first', () => {
|
||||||
|
createJob(baseJob);
|
||||||
|
const id = getJobs()[0].id;
|
||||||
|
const r1 = createJobRun(id);
|
||||||
|
const r2 = createJobRun(id);
|
||||||
|
completeJobRun(r1, 'success', 'first');
|
||||||
|
completeJobRun(r2, 'error', 'second');
|
||||||
|
const runs = getJobRuns(id);
|
||||||
|
expect(runs[0].id).toBe(r2);
|
||||||
|
expect(runs[1].id).toBe(r1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -58,16 +58,22 @@ describe('esc', () => {
|
|||||||
|
|
||||||
// ── fmtDate() ─────────────────────────────────────────────────────────────────
|
// ── fmtDate() ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function fmtDate(d) {
|
function parseUtc(d) {
|
||||||
|
if (typeof d !== 'string') return new Date(d)
|
||||||
|
const hasZone = d.endsWith('Z') || /[+-]\d{2}:\d{2}$/.test(d)
|
||||||
|
return new Date(hasZone ? d : d.replace(' ', 'T') + 'Z')
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtDate(d, tz = 'UTC') {
|
||||||
if (!d) return '—'
|
if (!d) return '—'
|
||||||
try {
|
try {
|
||||||
return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })
|
return parseUtc(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: tz })
|
||||||
} catch (e) { return d }
|
} catch (e) { return d }
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('fmtDate', () => {
|
describe('fmtDate', () => {
|
||||||
it('formats a valid ISO date string', () => {
|
it('formats a valid ISO date string', () => {
|
||||||
const result = fmtDate('2024-03-15T00:00:00')
|
const result = fmtDate('2024-03-15T12:00:00Z')
|
||||||
expect(result).toMatch(/Mar/)
|
expect(result).toMatch(/Mar/)
|
||||||
expect(result).toMatch(/15/)
|
expect(result).toMatch(/15/)
|
||||||
expect(result).toMatch(/2024/)
|
expect(result).toMatch(/2024/)
|
||||||
@@ -88,24 +94,42 @@ describe('fmtDate', () => {
|
|||||||
|
|
||||||
// ── fmtDateFull() ─────────────────────────────────────────────────────────────
|
// ── fmtDateFull() ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function fmtDateFull(d) {
|
function fmtDateFull(d, tz = 'UTC') {
|
||||||
if (!d) return '—'
|
if (!d) return '—'
|
||||||
try {
|
try {
|
||||||
return new Date(d).toLocaleString('en-US', {
|
return parseUtc(d).toLocaleString('en-US', {
|
||||||
year: 'numeric', month: 'short', day: 'numeric',
|
year: 'numeric', month: 'short', day: 'numeric',
|
||||||
hour: '2-digit', minute: '2-digit',
|
hour: '2-digit', minute: '2-digit',
|
||||||
|
timeZone: tz, timeZoneName: 'short',
|
||||||
})
|
})
|
||||||
} catch (e) { return d }
|
} catch (e) { return d }
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('fmtDateFull', () => {
|
describe('fmtDateFull', () => {
|
||||||
it('includes date and time components', () => {
|
it('includes date and time components', () => {
|
||||||
const result = fmtDateFull('2024-03-15T14:30:00')
|
const result = fmtDateFull('2024-03-15T14:30:00Z')
|
||||||
expect(result).toMatch(/Mar/)
|
expect(result).toMatch(/Mar/)
|
||||||
expect(result).toMatch(/2024/)
|
expect(result).toMatch(/2024/)
|
||||||
expect(result).toMatch(/\d{1,2}:\d{2}/)
|
expect(result).toMatch(/\d{1,2}:\d{2}/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('includes the timezone abbreviation', () => {
|
||||||
|
expect(fmtDateFull('2024-03-15T14:30:00Z', 'UTC')).toMatch(/UTC/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('converts to the given timezone', () => {
|
||||||
|
// 2024-03-15 18:30 UTC = 2024-03-15 14:30 EDT (UTC-4 in March)
|
||||||
|
const result = fmtDateFull('2024-03-15T18:30:00Z', 'America/New_York')
|
||||||
|
expect(result).toMatch(/2:30/)
|
||||||
|
expect(result).toMatch(/EDT/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats SQLite-format timestamps (space, no Z) as UTC', () => {
|
||||||
|
// SQLite datetime('now') → 'YYYY-MM-DD HH:MM:SS', no timezone marker.
|
||||||
|
// Must parse identically to the same moment expressed as ISO UTC.
|
||||||
|
expect(fmtDateFull('2024-03-15 18:30:00', 'UTC')).toBe(fmtDateFull('2024-03-15T18:30:00Z', 'UTC'))
|
||||||
|
})
|
||||||
|
|
||||||
it('returns — for null', () => {
|
it('returns — for null', () => {
|
||||||
expect(fmtDateFull(null)).toBe('—')
|
expect(fmtDateFull(null)).toBe('—')
|
||||||
})
|
})
|
||||||
@@ -133,6 +157,64 @@ describe('version label formatting', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ── fmtHistVal() ─────────────────────────────────────────────────────────────
|
||||||
|
// Mirrors the logic in ui.js — formats history field values for display.
|
||||||
|
|
||||||
|
const BOOL_FIELDS = ['atlas','argus','semaphore','patchmon','tailscale','andromeda','hardware_acceleration']
|
||||||
|
|
||||||
|
function fmtHistVal(field, val) {
|
||||||
|
if (val == null || val === '') return '—'
|
||||||
|
if (BOOL_FIELDS.includes(field)) return val === '1' ? 'on' : 'off'
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('fmtHistVal', () => {
|
||||||
|
it('returns — for null', () => {
|
||||||
|
expect(fmtHistVal('state', null)).toBe('—')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns — for empty string', () => {
|
||||||
|
expect(fmtHistVal('state', '')).toBe('—')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns on/off for boolean service fields', () => {
|
||||||
|
expect(fmtHistVal('atlas', '1')).toBe('on')
|
||||||
|
expect(fmtHistVal('atlas', '0')).toBe('off')
|
||||||
|
expect(fmtHistVal('hardware_acceleration', '1')).toBe('on')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the value as-is for non-boolean fields', () => {
|
||||||
|
expect(fmtHistVal('state', 'deployed')).toBe('deployed')
|
||||||
|
expect(fmtHistVal('name', 'plex')).toBe('plex')
|
||||||
|
expect(fmtHistVal('tailscale_ip', '100.64.0.1')).toBe('100.64.0.1')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── stateClass() ─────────────────────────────────────────────────────────────
|
||||||
|
// Mirrors the logic in ui.js — maps state values to timeline CSS classes.
|
||||||
|
|
||||||
|
function stateClass(field, val) {
|
||||||
|
if (field !== 'state') return ''
|
||||||
|
return { deployed: 'tl-deployed', testing: 'tl-testing', degraded: 'tl-degraded' }[val] ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('stateClass', () => {
|
||||||
|
it('returns empty string for non-state fields', () => {
|
||||||
|
expect(stateClass('name', 'plex')).toBe('')
|
||||||
|
expect(stateClass('stack', 'production')).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the correct colour class for each state value', () => {
|
||||||
|
expect(stateClass('state', 'deployed')).toBe('tl-deployed')
|
||||||
|
expect(stateClass('state', 'testing')).toBe('tl-testing')
|
||||||
|
expect(stateClass('state', 'degraded')).toBe('tl-degraded')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns empty string for unknown state values', () => {
|
||||||
|
expect(stateClass('state', 'unknown')).toBe('')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
// ── CSS regressions ───────────────────────────────────────────────────────────
|
// ── CSS regressions ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const css = readFileSync(join(__dirname, '../css/app.css'), 'utf8')
|
const css = readFileSync(join(__dirname, '../css/app.css'), 'utf8')
|
||||||
|
|||||||
Reference in New Issue
Block a user