2026-04-07 21:58:25 -04:00
|
|
|
import 'dotenv/config';
|
|
|
|
|
import express from 'express';
|
|
|
|
|
import cors from 'cors';
|
|
|
|
|
import session from 'express-session';
|
|
|
|
|
import ConnectPgSimple from 'connect-pg-simple';
|
2026-05-19 23:50:19 -04:00
|
|
|
import os from 'node:os';
|
2026-05-20 17:25:11 -04:00
|
|
|
import { exec } from 'node:child_process';
|
2026-04-07 21:58:25 -04:00
|
|
|
import pool from './db/pool.js';
|
|
|
|
|
import { errorHandler } from './middleware/errors.js';
|
2026-05-20 15:53:26 -04:00
|
|
|
import { loadS3ConfigFromDb } from './s3/client.js';
|
2026-04-07 21:58:25 -04:00
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
// Routes
|
|
|
|
|
import authRouter from './routes/auth.js';
|
2026-04-07 21:58:25 -04:00
|
|
|
import assetsRouter from './routes/assets.js';
|
|
|
|
|
import projectsRouter from './routes/projects.js';
|
|
|
|
|
import binsRouter from './routes/bins.js';
|
|
|
|
|
import jobsRouter from './routes/jobs.js';
|
|
|
|
|
import captureRouter from './routes/capture.js';
|
2026-04-07 22:05:39 -04:00
|
|
|
import uploadRouter from './routes/upload.js';
|
|
|
|
|
import recordersRouter from './routes/recorders.js';
|
2026-04-18 13:42:09 -04:00
|
|
|
import settingsRouter from './routes/settings.js';
|
|
|
|
|
import amppRouter from './routes/ampp.js';
|
2026-05-18 21:25:36 -04:00
|
|
|
import usersRouter from './routes/users.js';
|
|
|
|
|
import groupsRouter from './routes/groups.js';
|
|
|
|
|
import tokensRouter from './routes/tokens.js';
|
2026-05-18 19:54:41 -04:00
|
|
|
import sequencesRouter from './routes/sequences.js';
|
2026-05-19 23:50:19 -04:00
|
|
|
import systemRouter from './routes/system.js';
|
|
|
|
|
import clusterRouter from './routes/cluster.js';
|
feat: SDK deployment UI, proxy encoding global settings, S3 env fallback
- Settings: drop AMPP tab, rename GPU/Transcoding → Proxy encoding
with explicit 'applied to every ingested file' wording, expose
CPU codec/preset options when GPU is off
- New Capture SDKs tab (Settings): upload Blackmagic / AJA / Deltacast
SDK archives (.zip / .tar.gz) staged to /sdk/<vendor>/ inside mam-api;
BMD is fully wired into the FFmpeg build pipeline, AJA + Deltacast
staging-only pending FFmpeg patches
- mam-api: new /api/v1/sdk routes (multer upload, extract, list, delete);
Dockerfile gets unzip+tar; docker-compose mounts /mnt/NVME/MAM/sdk:/sdk
- proxy worker now reads proxy-encoding settings from DB on every job,
builds args for libx264 / NVENC / VAAPI, falls back to libx264 on
hardware-encode failure
- settings GET /s3 falls back to S3_* env vars when DB is empty so the
UI reflects what's actually wired (fixes 'not configured' false alarm)
2026-05-22 22:58:32 -04:00
|
|
|
import sdkRouter from './routes/sdk.js';
|
feat(scheduler): recorder scheduling — UI, CRUD, tick loop, recurrence
- New Ingest → Schedule page: upcoming/past/all tabs, status badges
(pending / recording / completed / cancelled / failed), 10s
auto-refresh, cancel/delete actions
- New Schedule modal: name, recorder dropdown, datetime-local start/end,
recurrence (one-shot / daily / weekly), sensible defaults (+5min / +35min)
- Backend: migration 009 (recorder_schedules), routes/schedules.js
(list/create/edit/cancel/delete), scheduler.js tick loop polling every
15s; transitions trigger /recorders/:id/start and /stop via in-process
HTTP so we reuse the full container orchestration path
- Recurring schedules: tick loop auto-queues the next occurrence on
completion (daily = +24h, weekly = +7d)
- Sidebar + app.jsx route wired in, schedule-row table style added
2026-05-22 23:19:24 -04:00
|
|
|
import schedulesRouter from './routes/schedules.js';
|
2026-05-22 23:30:10 -04:00
|
|
|
import metricsRouter from './routes/metrics.js';
|
feat(comments): persistent frame-anchored comments on asset detail
- migration 010: asset_comments table (id, asset_id, user_id, body,
frame_ms, resolved, timestamps) with index on asset_id+created_at
- new routes mounted at /api/v1/assets/:assetId/comments — GET/POST/
PATCH/DELETE with author join (display_name + initials), nullable
user_id so comments still attach when AUTH_ENABLED is off
- Asset detail loads comments from the API on mount instead of the
empty ZAMPP_DATA.COMMENTS seed; addComment POSTs and merges the
returned row; resolved-toggle and delete are wired
- CommentsList: new trash-icon delete action per comment, helpful
empty-state copy ('Add one below to mark a frame'), tooltips on
the timestamp and resolved buttons
Now editor comments survive page reload, are visible to other users
via the same API, and pin reliably to frame_ms (integer) instead of
a parsed HH:MM:SS:FF string.
2026-05-23 00:21:11 -04:00
|
|
|
import commentsRouter from './routes/comments.js';
|
2026-05-23 16:05:41 -04:00
|
|
|
import importsRouter from './routes/imports.js';
|
feat(scheduler): recorder scheduling — UI, CRUD, tick loop, recurrence
- New Ingest → Schedule page: upcoming/past/all tabs, status badges
(pending / recording / completed / cancelled / failed), 10s
auto-refresh, cancel/delete actions
- New Schedule modal: name, recorder dropdown, datetime-local start/end,
recurrence (one-shot / daily / weekly), sensible defaults (+5min / +35min)
- Backend: migration 009 (recorder_schedules), routes/schedules.js
(list/create/edit/cancel/delete), scheduler.js tick loop polling every
15s; transitions trigger /recorders/:id/start and /stop via in-process
HTTP so we reuse the full container orchestration path
- Recurring schedules: tick loop auto-queues the next occurrence on
completion (daily = +24h, weekly = +7d)
- Sidebar + app.jsx route wired in, schedule-row table style added
2026-05-22 23:19:24 -04:00
|
|
|
import { startSchedulerLoop } from './scheduler.js';
|
2026-05-24 12:43:08 -04:00
|
|
|
import { startCleanupLoop } from './tasks/cleanupTempSegments.js';
|
2026-04-07 21:58:25 -04:00
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
const app = express();
|
2026-04-07 21:58:25 -04:00
|
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
// ── Middleware ────────────────────────────────────────────────────────────────
|
|
|
|
|
app.use(cors({ origin: true, credentials: true }));
|
2026-04-07 22:05:39 -04:00
|
|
|
app.use(express.json({ limit: '50mb' }));
|
2026-04-07 21:58:25 -04:00
|
|
|
|
|
|
|
|
const PgSession = ConnectPgSimple(session);
|
|
|
|
|
|
|
|
|
|
app.use(
|
|
|
|
|
session({
|
|
|
|
|
store: new PgSession({
|
|
|
|
|
pool,
|
|
|
|
|
tableName: 'sessions',
|
2026-05-15 23:40:12 -04:00
|
|
|
pruneSessionInterval: 3600,
|
2026-04-07 21:58:25 -04:00
|
|
|
}),
|
2026-05-15 23:40:12 -04:00
|
|
|
secret: process.env.SESSION_SECRET || 'change-me-in-production',
|
|
|
|
|
resave: false,
|
2026-04-07 21:58:25 -04:00
|
|
|
saveUninitialized: false,
|
|
|
|
|
cookie: {
|
2026-05-15 23:40:12 -04:00
|
|
|
secure: process.env.NODE_ENV === 'production',
|
2026-04-07 21:58:25 -04:00
|
|
|
httpOnly: true,
|
2026-05-20 17:25:11 -04:00
|
|
|
maxAge: 1000 * 60 * 60 * 24,
|
2026-04-07 21:58:25 -04:00
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
);
|
|
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
// ── Health (no auth) ──────────────────────────────────────────────────────────
|
|
|
|
|
app.get('/health', (_req, res) => res.json({ status: 'ok' }));
|
|
|
|
|
|
|
|
|
|
// ── API Routes ────────────────────────────────────────────────────────────────
|
|
|
|
|
app.use('/api/v1/auth', authRouter);
|
|
|
|
|
app.use('/api/v1/assets', assetsRouter);
|
|
|
|
|
app.use('/api/v1/projects', projectsRouter);
|
|
|
|
|
app.use('/api/v1/bins', binsRouter);
|
|
|
|
|
app.use('/api/v1/jobs', jobsRouter);
|
|
|
|
|
app.use('/api/v1/capture', captureRouter);
|
|
|
|
|
app.use('/api/v1/upload', uploadRouter);
|
2026-04-07 22:05:39 -04:00
|
|
|
app.use('/api/v1/recorders', recordersRouter);
|
2026-05-15 23:40:12 -04:00
|
|
|
app.use('/api/v1/settings', settingsRouter);
|
|
|
|
|
app.use('/api/v1/ampp', amppRouter);
|
2026-05-18 21:25:36 -04:00
|
|
|
app.use('/api/v1/users', usersRouter);
|
|
|
|
|
app.use('/api/v1/groups', groupsRouter);
|
|
|
|
|
app.use('/api/v1/tokens', tokensRouter);
|
|
|
|
|
app.use('/api/v1/sequences', sequencesRouter);
|
2026-05-19 23:50:19 -04:00
|
|
|
app.use('/api/v1/system', systemRouter);
|
|
|
|
|
app.use('/api/v1/cluster', clusterRouter);
|
feat: SDK deployment UI, proxy encoding global settings, S3 env fallback
- Settings: drop AMPP tab, rename GPU/Transcoding → Proxy encoding
with explicit 'applied to every ingested file' wording, expose
CPU codec/preset options when GPU is off
- New Capture SDKs tab (Settings): upload Blackmagic / AJA / Deltacast
SDK archives (.zip / .tar.gz) staged to /sdk/<vendor>/ inside mam-api;
BMD is fully wired into the FFmpeg build pipeline, AJA + Deltacast
staging-only pending FFmpeg patches
- mam-api: new /api/v1/sdk routes (multer upload, extract, list, delete);
Dockerfile gets unzip+tar; docker-compose mounts /mnt/NVME/MAM/sdk:/sdk
- proxy worker now reads proxy-encoding settings from DB on every job,
builds args for libx264 / NVENC / VAAPI, falls back to libx264 on
hardware-encode failure
- settings GET /s3 falls back to S3_* env vars when DB is empty so the
UI reflects what's actually wired (fixes 'not configured' false alarm)
2026-05-22 22:58:32 -04:00
|
|
|
app.use('/api/v1/sdk', sdkRouter);
|
feat(scheduler): recorder scheduling — UI, CRUD, tick loop, recurrence
- New Ingest → Schedule page: upcoming/past/all tabs, status badges
(pending / recording / completed / cancelled / failed), 10s
auto-refresh, cancel/delete actions
- New Schedule modal: name, recorder dropdown, datetime-local start/end,
recurrence (one-shot / daily / weekly), sensible defaults (+5min / +35min)
- Backend: migration 009 (recorder_schedules), routes/schedules.js
(list/create/edit/cancel/delete), scheduler.js tick loop polling every
15s; transitions trigger /recorders/:id/start and /stop via in-process
HTTP so we reuse the full container orchestration path
- Recurring schedules: tick loop auto-queues the next occurrence on
completion (daily = +24h, weekly = +7d)
- Sidebar + app.jsx route wired in, schedule-row table style added
2026-05-22 23:19:24 -04:00
|
|
|
app.use('/api/v1/schedules', schedulesRouter);
|
2026-05-22 23:30:10 -04:00
|
|
|
app.use('/api/v1/metrics', metricsRouter);
|
feat(comments): persistent frame-anchored comments on asset detail
- migration 010: asset_comments table (id, asset_id, user_id, body,
frame_ms, resolved, timestamps) with index on asset_id+created_at
- new routes mounted at /api/v1/assets/:assetId/comments — GET/POST/
PATCH/DELETE with author join (display_name + initials), nullable
user_id so comments still attach when AUTH_ENABLED is off
- Asset detail loads comments from the API on mount instead of the
empty ZAMPP_DATA.COMMENTS seed; addComment POSTs and merges the
returned row; resolved-toggle and delete are wired
- CommentsList: new trash-icon delete action per comment, helpful
empty-state copy ('Add one below to mark a frame'), tooltips on
the timestamp and resolved buttons
Now editor comments survive page reload, are visible to other users
via the same API, and pin reliably to frame_ms (integer) instead of
a parsed HH:MM:SS:FF string.
2026-05-23 00:21:11 -04:00
|
|
|
app.use('/api/v1/assets/:assetId/comments', commentsRouter);
|
2026-05-23 16:05:41 -04:00
|
|
|
app.use('/api/v1/imports', importsRouter);
|
2026-04-07 21:58:25 -04:00
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
// ── Error handler ─────────────────────────────────────────────────────────────
|
2026-04-07 21:58:25 -04:00
|
|
|
app.use(errorHandler);
|
|
|
|
|
|
2026-05-15 23:40:12 -04:00
|
|
|
// ── Start ────────────────────────────────────────────────────────────────────
|
2026-05-18 07:29:50 -04:00
|
|
|
import { readdirSync, readFileSync } from 'node:fs';
|
|
|
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
|
import { dirname, join } from 'node:path';
|
|
|
|
|
|
|
|
|
|
const __dirnameMig = dirname(fileURLToPath(import.meta.url));
|
|
|
|
|
async function runMigrations() {
|
|
|
|
|
const dir = join(__dirnameMig, 'db', 'migrations');
|
|
|
|
|
let files = [];
|
|
|
|
|
try { files = readdirSync(dir).filter(f => f.endsWith('.sql')).sort(); } catch { return; }
|
|
|
|
|
for (const f of files) {
|
|
|
|
|
const sql = readFileSync(join(dir, f), 'utf8');
|
|
|
|
|
try {
|
|
|
|
|
await pool.query(sql);
|
|
|
|
|
console.log('[migration] applied ' + f);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[migration] failed ' + f, err.message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
await runMigrations();
|
|
|
|
|
|
2026-05-20 15:53:26 -04:00
|
|
|
// Load S3 config from DB so any settings saved via the Settings page override env vars
|
|
|
|
|
await loadS3ConfigFromDb();
|
|
|
|
|
|
2026-05-19 23:50:19 -04:00
|
|
|
// ── Cluster self-heartbeat ────────────────────────────────────────────────────
|
|
|
|
|
function getLocalIp() {
|
2026-05-20 16:16:09 -04:00
|
|
|
// Prefer an explicit override — useful when running inside Docker where
|
|
|
|
|
// os.networkInterfaces() returns container bridge IPs, not the host LAN IP.
|
|
|
|
|
if (process.env.NODE_IP) return process.env.NODE_IP;
|
|
|
|
|
|
2026-05-19 23:50:19 -04:00
|
|
|
const ifaces = os.networkInterfaces();
|
|
|
|
|
for (const name of Object.keys(ifaces)) {
|
|
|
|
|
for (const iface of (ifaces[name] || [])) {
|
|
|
|
|
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return '127.0.0.1';
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-20 17:25:11 -04:00
|
|
|
// Detect NVIDIA GPUs available to this container via nvidia-smi.
|
|
|
|
|
// Returns an array like [{ index: 0, name: 'Tesla P4', memory_mb: 7680 }, ...]
|
|
|
|
|
// or an empty array if nvidia-smi is unavailable or no GPUs found.
|
|
|
|
|
function detectGpus() {
|
|
|
|
|
return new Promise(resolve => {
|
|
|
|
|
exec(
|
|
|
|
|
'nvidia-smi --query-gpu=index,name,memory.total --format=csv,noheader,nounits',
|
|
|
|
|
{ timeout: 5000 },
|
|
|
|
|
(err, stdout) => {
|
|
|
|
|
if (err || !stdout.trim()) return resolve([]);
|
|
|
|
|
const gpus = stdout.trim().split('\n').map(line => {
|
|
|
|
|
const parts = line.split(',').map(s => s.trim());
|
|
|
|
|
return {
|
|
|
|
|
index: parseInt(parts[0], 10),
|
|
|
|
|
name: parts[1] || 'Unknown GPU',
|
|
|
|
|
memory_mb: parseInt(parts[2], 10) || 0,
|
|
|
|
|
};
|
|
|
|
|
}).filter(g => !isNaN(g.index));
|
|
|
|
|
resolve(gpus);
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function selfHeartbeat() {
|
2026-05-19 23:50:19 -04:00
|
|
|
const load = os.loadavg()[0];
|
|
|
|
|
const total = os.totalmem();
|
|
|
|
|
const used = total - os.freemem();
|
2026-05-20 17:25:11 -04:00
|
|
|
const gpus = await detectGpus();
|
|
|
|
|
|
|
|
|
|
const capabilities = { gpus, blackmagic: [] };
|
|
|
|
|
|
2026-05-19 23:50:19 -04:00
|
|
|
pool.query(
|
|
|
|
|
`INSERT INTO cluster_nodes
|
|
|
|
|
(hostname, ip_address, role, version, api_url,
|
2026-05-20 17:25:11 -04:00
|
|
|
cpu_usage, mem_used_mb, mem_total_mb, capabilities, last_seen)
|
|
|
|
|
VALUES ($1,$2,'primary',$3,$4,$5,$6,$7,$8,NOW())
|
2026-05-19 23:50:19 -04:00
|
|
|
ON CONFLICT (hostname) DO UPDATE SET
|
|
|
|
|
ip_address = EXCLUDED.ip_address,
|
|
|
|
|
cpu_usage = EXCLUDED.cpu_usage,
|
|
|
|
|
mem_used_mb = EXCLUDED.mem_used_mb,
|
|
|
|
|
mem_total_mb = EXCLUDED.mem_total_mb,
|
2026-05-20 17:25:11 -04:00
|
|
|
capabilities = EXCLUDED.capabilities,
|
2026-05-19 23:50:19 -04:00
|
|
|
last_seen = NOW()`,
|
|
|
|
|
[
|
2026-05-21 07:50:52 -04:00
|
|
|
process.env.NODE_HOSTNAME || os.hostname(),
|
2026-05-19 23:50:19 -04:00
|
|
|
getLocalIp(),
|
|
|
|
|
process.env.npm_package_version || null,
|
|
|
|
|
`http://${getLocalIp()}:${PORT}`,
|
|
|
|
|
parseFloat(load.toFixed(2)),
|
|
|
|
|
Math.round(used / 1024 / 1024),
|
|
|
|
|
Math.round(total / 1024 / 1024),
|
2026-05-20 17:25:11 -04:00
|
|
|
JSON.stringify(capabilities),
|
2026-05-19 23:50:19 -04:00
|
|
|
]
|
|
|
|
|
).catch(err => console.error('[cluster] heartbeat failed:', err.message));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setInterval(selfHeartbeat, 30_000);
|
|
|
|
|
selfHeartbeat();
|
|
|
|
|
|
2026-04-07 21:58:25 -04:00
|
|
|
app.listen(PORT, () => {
|
2026-05-15 23:40:12 -04:00
|
|
|
const authMode = process.env.AUTH_ENABLED === 'true' ? 'ENABLED' : 'DISABLED (set AUTH_ENABLED=true for production)';
|
2026-04-07 21:58:25 -04:00
|
|
|
console.log(`MAM API listening on port ${PORT}`);
|
2026-05-15 23:40:12 -04:00
|
|
|
console.log(`Authentication: ${authMode}`);
|
feat(scheduler): recorder scheduling — UI, CRUD, tick loop, recurrence
- New Ingest → Schedule page: upcoming/past/all tabs, status badges
(pending / recording / completed / cancelled / failed), 10s
auto-refresh, cancel/delete actions
- New Schedule modal: name, recorder dropdown, datetime-local start/end,
recurrence (one-shot / daily / weekly), sensible defaults (+5min / +35min)
- Backend: migration 009 (recorder_schedules), routes/schedules.js
(list/create/edit/cancel/delete), scheduler.js tick loop polling every
15s; transitions trigger /recorders/:id/start and /stop via in-process
HTTP so we reuse the full container orchestration path
- Recurring schedules: tick loop auto-queues the next occurrence on
completion (daily = +24h, weekly = +7d)
- Sidebar + app.jsx route wired in, schedule-row table style added
2026-05-22 23:19:24 -04:00
|
|
|
// Boot the recorder scheduler tick loop after the HTTP server is live so
|
|
|
|
|
// the loop's self-calls to /recorders/:id/start|stop reach a ready socket.
|
|
|
|
|
startSchedulerLoop();
|
2026-05-24 12:43:08 -04:00
|
|
|
|
|
|
|
|
// Boot the temp-segment cleanup loop (runs hourly).
|
|
|
|
|
startCleanupLoop();
|
2026-04-07 21:58:25 -04:00
|
|
|
});
|