Skip to content

Suno-style web UI for a self-hosted MiniMax-Music3 inference server

Bound and share upstream health probes

Adam B.4386d9d36552
diff --git a/server/src/upstream.ts b/server/src/upstream.ts
index de0e242..fa5d83c 100644
--- a/server/src/upstream.ts
+++ b/server/src/upstream.ts
@@ -15,6 +15,8 @@ const FRAMES_PER_SECOND = 25;
const MAX_FRAMES = 9000;
const EXT: Record<string, string> = { wav: 'wav' };
+const HEALTH_PROBE_TIMEOUT_MS = 5_000;
+const HEALTH_CACHE_TTL_MS = 3_000;
/** Model id in the official model card's example; used when /v1/models doesn't tell us otherwise. */
export const DEFAULT_MODEL = 'MiniMaxAI/MiniMax-Music3';
export const extFor = (format: string) => EXT[format] ?? format;
@@ -25,6 +27,21 @@ export class UpstreamError extends Error {
}
}
+async function withProbeTimeout<T>(path: string, probe: (signal: AbortSignal) => Promise<T>): Promise<T> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), HEALTH_PROBE_TIMEOUT_MS);
+ try {
+ return await probe(controller.signal);
+ } catch (err) {
+ if (controller.signal.aborted) {
+ throw new UpstreamError(`upstream probe timed out after ${HEALTH_PROBE_TIMEOUT_MS / 1000}s waiting for ${path}`);
+ }
+ throw err;
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
export interface SpeechBody {
prompt: string;
lyrics: string;
@@ -41,6 +58,10 @@ export interface UpstreamHealth {
capabilities: string[];
}
+type HealthCacheEntry =
+ | { expiresAt: number; result: UpstreamHealth }
+ | { expiresAt: number; error: UpstreamError };
+
export type StreamEvent =
| { type: 'progress'; stage: 'semantic' | 'denoise'; done: number; total: number }
| { type: 'audio'; secondsRendered: number };
@@ -54,6 +75,9 @@ export class UpstreamClient {
private modelId: string | null = null;
private capabilities: string[] = [];
private probed = false;
+ private healthGeneration = 0;
+ private healthPromise: Promise<UpstreamHealth> | null = null;
+ private healthCache: HealthCacheEntry | null = null;
/**
* `compat`: pretend the server is stock sgl-omni — skip GET /health, so no loading state and no extras.
@@ -69,6 +93,9 @@ export class UpstreamClient {
}
configure(baseUrl: string, apiKey: string | null, compat = false): void {
+ this.healthGeneration++;
+ this.healthPromise = null;
+ this.healthCache = null;
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.apiKey = apiKey;
this.compat = compat;
@@ -96,9 +123,9 @@ export class UpstreamClient {
return this.baseUrl;
}
- private headers(extra: Record<string, string> = {}): Record<string, string> {
+ private headers(extra: Record<string, string> = {}, apiKey: string | null = this.apiKey): Record<string, string> {
const h: Record<string, string> = { ...extra };
- if (this.apiKey) h.Authorization = `Bearer ${this.apiKey}`;
+ if (apiKey) h.Authorization = `Bearer ${apiKey}`;
return h;
}
@@ -109,34 +136,84 @@ export class UpstreamClient {
* `ready` comes from an optional GET /health: a 503 means the model is still loading; anything
* else (404 on stock sgl-omni, timeouts) counts as ready. Its JSON may list `capabilities`.
*/
- async health(): Promise<UpstreamHealth> {
- let res: Response;
- try {
- res = await fetch(`${this.baseUrl}/v1/models`, { headers: this.headers() });
- } catch (err) {
- throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);
+ health(): Promise<UpstreamHealth> {
+ const now = Date.now();
+ if (this.healthCache && this.healthCache.expiresAt > now) {
+ if ('error' in this.healthCache) return Promise.reject(this.healthCache.error);
+ return Promise.resolve(this.copyHealth(this.healthCache.result));
}
- if (res.status === 401 || res.status === 403) throw new UpstreamError(`upstream ${res.status} on /v1/models — check the API key`, res.status);
- let models: string[] = [];
- if (res.ok) {
- const json = (await res.json().catch(() => ({}))) as { data?: { id?: string }[] };
- models = (json.data ?? []).map((m) => m.id ?? '').filter(Boolean);
+ if (this.healthPromise) return this.healthPromise.then((health) => this.copyHealth(health));
+
+ const generation = this.healthGeneration;
+ const baseUrl = this.baseUrl;
+ const apiKey = this.apiKey;
+ const compat = this.compat;
+ const probe = this.probeHealthNow(baseUrl, apiKey, compat, generation).catch((err: unknown) => {
+ if (err instanceof UpstreamError) throw err;
+ throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);
+ });
+ this.healthPromise = probe;
+ void probe.then((result) => {
+ if (generation !== this.healthGeneration || this.healthPromise !== probe) return;
+ this.healthCache = { expiresAt: Date.now() + HEALTH_CACHE_TTL_MS, result: this.copyHealth(result) };
+ this.healthPromise = null;
+ }, (err: UpstreamError) => {
+ if (generation !== this.healthGeneration || this.healthPromise !== probe) return;
+ this.healthCache = { expiresAt: Date.now() + HEALTH_CACHE_TTL_MS, error: err };
+ this.healthPromise = null;
+ });
+ return probe.then((health) => this.copyHealth(health));
+ }
+
+ private copyHealth(health: UpstreamHealth): UpstreamHealth {
+ return { ready: health.ready, models: [...health.models], capabilities: [...health.capabilities] };
+ }
+
+ private async probeHealthNow(baseUrl: string, apiKey: string | null, compat: boolean, generation: number): Promise<UpstreamHealth> {
+ const models = await withProbeTimeout('/v1/models', async (signal) => {
+ let res: Response;
+ try {
+ res = await fetch(`${baseUrl}/v1/models`, { headers: this.headers({}, apiKey), signal });
+ } catch (err) {
+ if (signal.aborted) throw err;
+ throw new UpstreamError(`upstream unreachable: ${(err as Error).message}`);
+ }
+ if (res.status === 401 || res.status === 403) throw new UpstreamError(`upstream ${res.status} on /v1/models — check the API key`, res.status);
+ if (!res.ok) return [];
+ let json: { data?: { id?: string }[] };
+ try {
+ json = await res.json() as { data?: { id?: string }[] };
+ } catch (err) {
+ if (signal.aborted) throw err;
+ json = {};
+ }
+ return (json.data ?? []).map((m) => m.id ?? '').filter(Boolean);
+ });
+ const h = compat ? { ready: true, capabilities: [] } : await this.probeHealth(baseUrl, apiKey);
+ if (generation === this.healthGeneration) {
if (models.length) this.modelId = models[0];
+ this.capabilities = h.capabilities;
+ this.probed = true;
}
- const h = this.compat ? { ready: true, capabilities: [] } : await this.probeHealth();
- this.capabilities = h.capabilities;
- this.probed = true;
return { ready: h.ready, models, capabilities: h.capabilities };
}
/** GET /health is optional: 503 = model still loading; its JSON may list `capabilities`. */
- private async probeHealth(): Promise<{ ready: boolean; capabilities: string[] }> {
+ private async probeHealth(baseUrl: string, apiKey: string | null): Promise<{ ready: boolean; capabilities: string[] }> {
try {
- const res = await fetch(`${this.baseUrl}/health`, { headers: this.headers() });
- if (res.status === 503) return { ready: false, capabilities: [] };
- const json = (await res.json().catch(() => ({}))) as { capabilities?: unknown };
- const caps = Array.isArray(json.capabilities) ? json.capabilities.filter((c): c is string => typeof c === 'string') : [];
- return { ready: true, capabilities: caps };
+ return await withProbeTimeout('/health', async (signal) => {
+ const res = await fetch(`${baseUrl}/health`, { headers: this.headers({}, apiKey), signal });
+ if (res.status === 503) return { ready: false, capabilities: [] };
+ let json: { capabilities?: unknown };
+ try {
+ json = await res.json() as { capabilities?: unknown };
+ } catch (err) {
+ if (signal.aborted) throw err;
+ json = {};
+ }
+ const caps = Array.isArray(json.capabilities) ? json.capabilities.filter((c): c is string => typeof c === 'string') : [];
+ return { ready: true, capabilities: caps };
+ });
} catch {
return { ready: true, capabilities: [] };
}
diff --git a/server/test/app.test.ts b/server/test/app.test.ts
index 259019b..a27ace2 100644
--- a/server/test/app.test.ts
+++ b/server/test/app.test.ts
@@ -43,7 +43,7 @@ async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey:
const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill, log });
if (previousUiToken === undefined) delete process.env.UI_TOKEN;
else process.env.UI_TOKEN = previousUiToken;
- return { app, lib, tracksDir, dir, upstream, queue };
+ return { app, lib, tracksDir, dir, settings, upstream, queue };
}
const seedSkill = async (dir: string) => {
@@ -66,12 +66,52 @@ describe('app', () => {
expect(res.body).toMatchObject({ upstreamReachable: true, ready: true, busy: false, queued: 0, formats: ['wav'], models: ['minimax_ttm'], capabilities: [] });
expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);
await fake!.close(); fake = null;
- const down = await request(app).get('/api/health');
- expect(down.body.upstreamReachable).toBe(false);
- expect(down.body.error).toMatch(/unreachable/);
- expect(down.body.formats).toEqual(['wav']);
+ const cached = await request(app).get('/api/health');
+ expect(cached.body).toMatchObject({ upstreamReachable: true, models: ['minimax_ttm'], formats: ['wav'] });
});
+ it('coalesces concurrent health probes and reuses a completed result briefly', async () => {
+ const { app } = await setup({ stream: { windows: 1 }, modelsResponseDelayMs: 100, healthResponseDelayMs: 100 });
+ const responses = await Promise.all(Array.from({ length: 10 }, () => request(app).get('/api/health')));
+ expect(responses.every((res) => res.body.upstreamReachable && res.body.ready)).toBe(true);
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
+
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ const followup = await request(app).get('/api/health');
+ expect(followup.body).toMatchObject({ upstreamReachable: true, capabilities: ['stream'] });
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
+ });
+
+ it('times out a stalled /v1/models probe and caches its failed result for concurrent pollers', async () => {
+ const { app } = await setup({ modelsResponseDelayMs: 8000 });
+ const startedAt = Date.now();
+ const responses = await Promise.all(Array.from({ length: 10 }, () => request(app).get('/api/health')));
+ const elapsedMs = Date.now() - startedAt;
+
+ expect(elapsedMs).toBeGreaterThanOrEqual(4500);
+ expect(elapsedMs).toBeLessThan(7500);
+ expect(responses.every((res) => res.body.upstreamReachable === false && /probe timed out/i.test(res.body.error))).toBe(true);
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ const cached = await request(app).get('/api/health');
+ expect(cached.body).toMatchObject({ upstreamReachable: false, ready: false });
+ expect(cached.body.error).toMatch(/probe timed out/i);
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);
+ }, 15000);
+
+ it('treats a stalled optional /health probe as ready after its timeout', async () => {
+ const { app } = await setup({ healthResponseDelayMs: 8000 });
+ const startedAt = Date.now();
+ const result = await request(app).get('/api/health');
+ const elapsedMs = Date.now() - startedAt;
+
+ expect(elapsedMs).toBeGreaterThanOrEqual(4500);
+ expect(elapsedMs).toBeLessThan(7500);
+ expect(result.body).toMatchObject({ upstreamReachable: true, ready: true, models: ['minimax_ttm'] });
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
+ }, 15000);
+
it('generate → queue → speech → file: maps fields, serialises takes, forwards bearer', async () => {
const { app, lib } = await setup({ renderMs: 120 }, 'sekrit');
const res = await writeRequest(app).post('/api/generate').send({ prompt: 'ambient', lyrics: '', duration: 10, takes: 2, seed: 5 });
@@ -110,12 +150,13 @@ describe('app', () => {
});
it('reports ready:false while an optional /health answers 503, true once it recovers', async () => {
- const { app } = await setup({ loading: true });
+ const { app, upstream } = await setup({ loading: true });
const loading = await request(app).get('/api/health');
expect(loading.body).toMatchObject({ upstreamReachable: true, ready: false, models: ['minimax_ttm'] });
expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
await fake!.close();
fake = await startFakeUpstream({ loading: false, port: Number(new URL(fake!.url).port) });
+ upstream.configure(fake!.url);
const ready = await request(app).get('/api/health');
expect(ready.body).toMatchObject({ upstreamReachable: true, ready: true });
});
@@ -241,6 +282,44 @@ describe('app', () => {
expect((await writeRequest(app).put('/api/settings').send({ apiKey: '' })).body.apiKeySet).toBe(false);
});
+ it('settings changes to URL, key, or compat invalidate the cached upstream probe', async () => {
+ const { app } = await setup({ stream: { windows: 1 } }, null, { musicApi: null, apiKey: null });
+ expect((await request(app).get('/api/health')).body.capabilities).toEqual(['stream']);
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
+
+ const next = await startFakeUpstream({ stream: { windows: 1 } });
+ try {
+ const switched = await writeRequest(app).put('/api/settings').send({ musicApi: next.url, apiKey: 'fresh-key' });
+ expect(switched.status).toBe(200);
+ const newTarget = await request(app).get('/api/health');
+ expect(newTarget.body).toMatchObject({ upstreamReachable: true, capabilities: ['stream'] });
+ expect(next.requests.map((r) => r.path)).toEqual(['/v1/models', '/health']);
+ expect(next.requests[0]?.auth).toBe('Bearer fresh-key');
+
+ const changedCompat = await writeRequest(app).put('/api/settings').send({ compat: true });
+ expect(changedCompat.status).toBe(200);
+ const compatible = await request(app).get('/api/health');
+ expect(compatible.body).toMatchObject({ upstreamReachable: true, ready: true, capabilities: [] });
+ expect(next.requests.map((r) => r.path)).toEqual(['/v1/models', '/health', '/v1/models']);
+ expect(next.requests.at(-1)?.auth).toBe('Bearer fresh-key');
+ } finally {
+ await next.close();
+ }
+ });
+
+ it('keeps queue and enhancement fields live while reusing cached upstream health', async () => {
+ const { app, lib, queue, settings } = await setup({ renderMs: 150 });
+ await request(app).get('/api/health');
+ const generated = await writeRequest(app).post('/api/generate').send({ prompt: 'x', takes: 2 });
+ await until(() => queue.busy && queue.queued === 1);
+ await settings.update({ llmApi: 'http://127.0.0.1:9999/v1', llmModel: 'test-model' });
+
+ const live = await request(app).get('/api/health');
+ expect(live.body).toMatchObject({ busy: true, queued: 1, formats: ['wav'], enhance: true });
+ expect(fake!.requests.filter((r) => r.path === '/v1/models')).toHaveLength(1);
+ await until(() => lib.get(generated.body[0].id)?.status === 'done' && lib.get(generated.body[1].id)?.status === 'done');
+ });
+
it('settings/test probes a candidate URL without saving', async () => {
const { app } = await setup({}, null, { musicApi: null, apiKey: null });
const ok = await writeRequest(app).post('/api/settings/test').send({ musicApi: fake!.url });
@@ -250,6 +329,31 @@ describe('app', () => {
expect((await request(app).get('/api/settings')).body.musicApi).toBe('http://127.0.0.1:7862');
});
+ it('settings/test probes a stalled candidate live with the health timeout, outside the shared cache', async () => {
+ const { app } = await setup({}, null, { musicApi: null, apiKey: null });
+ await request(app).get('/api/health');
+ const candidate = await startFakeUpstream({ modelsResponseDelayMs: 8000 });
+ try {
+ const startedAt = Date.now();
+ const probe = writeRequest(app).post('/api/settings/test').send({ musicApi: candidate.url }).then((result) => result);
+ await until(() => candidate.requests.length === 1);
+ const configured = await request(app).get('/api/health');
+ expect(configured.body.upstreamReachable).toBe(true);
+ expect(fake!.requests.map((r) => r.path)).toEqual(['/v1/models']);
+
+ const result = await probe;
+ const elapsedMs = Date.now() - startedAt;
+
+ expect(elapsedMs).toBeGreaterThanOrEqual(4500);
+ expect(elapsedMs).toBeLessThan(7500);
+ expect(result.body.ok).toBe(false);
+ expect(result.body.error).toMatch(/probe timed out/i);
+ expect(candidate.requests.map((r) => r.path)).toEqual(['/v1/models']);
+ } finally {
+ await candidate.close();
+ }
+ }, 15000);
+
it('settings/test only reuses a saved music key for the same origin', async () => {
const { app } = await setup({}, null, { musicApi: null, apiKey: null });
await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'saved-key' });
diff --git a/server/test/fakeUpstream.ts b/server/test/fakeUpstream.ts
index 4545a9e..e458740 100644
--- a/server/test/fakeUpstream.ts
+++ b/server/test/fakeUpstream.ts
@@ -16,6 +16,9 @@ export interface FakeUpstreamOptions {
strictModel?: boolean;
/** expose GET /health answering 503 (model loading) — like inference/server.py; default: no /health route (stock sgl-omni) */
loading?: boolean;
+ /** delay probe responses, for exercising concurrent callers and client timeouts */
+ modelsResponseDelayMs?: number;
+ healthResponseDelayMs?: number;
/** advertise capabilities:["stream"] on /health and answer stream:true with SSE progress + PCM windows */
stream?: { windows: number; windowMs?: number; sampleRate?: number; secondsPerWindow?: number };
}
@@ -37,6 +40,18 @@ export interface FakeUpstream {
close(): Promise<void>;
}
+function waitForProbeResponse(res: express.Response, delayMs: number): Promise<void> {
+ return new Promise((resolve) => {
+ const finish = () => {
+ clearTimeout(timer);
+ res.off('close', finish);
+ resolve();
+ };
+ const timer = setTimeout(finish, delayMs);
+ res.once('close', finish);
+ });
+}
+
export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promise<FakeUpstream> {
const root = express();
const app = express();
@@ -47,15 +62,19 @@ export async function startFakeUpstream(opts: FakeUpstreamOptions = {}): Promise
const renderMs = opts.renderMs ?? 30;
const modelId = opts.modelId === undefined ? 'minimax_ttm' : opts.modelId;
- app.get('/v1/models', (req, res) => {
+ app.get('/v1/models', async (req, res) => {
requests.push({ method: 'GET', path: req.path, auth: req.header('authorization') ?? undefined });
+ if (opts.modelsResponseDelayMs) await waitForProbeResponse(res, opts.modelsResponseDelayMs);
+ if (res.destroyed) return;
if (modelId === null) return res.status(404).json({ detail: 'Not Found' });
res.json({ object: 'list', data: [{ id: modelId, object: 'model' }] });
});
- if (opts.loading !== undefined || opts.stream) {
- app.get('/health', (req, res) => {
+ if (opts.loading !== undefined || opts.stream || opts.healthResponseDelayMs !== undefined) {
+ app.get('/health', async (req, res) => {
requests.push({ method: 'GET', path: req.path });
+ if (opts.healthResponseDelayMs) await waitForProbeResponse(res, opts.healthResponseDelayMs);
+ if (res.destroyed) return;
if (opts.loading) return res.status(503).json({ detail: 'loading model' });
res.json({ status: 'ready', ...(opts.stream ? { capabilities: ['stream'] } : {}) });
});