feat: wire Nitro API to Go, real staffing plan and train proxy
- Replace mock Nitro routes with server-side proxies to the Go API - /plan reads Go /api/staffing; local assumption edits are a labeled preview - /simulate reads base and scenario staffing from Go instead of local multipliers - Route train upload and scenario POST through Nitro with server-only credentials - Keep NUXT_PUBLIC_USE_MOCK=1 as an explicit dev fallback only - Match Go's global-peak flat schedule and add a captured Go parity fixture - Run the web runtime as numeric UID/GID 10001:10001 - Add make check, Gitea CI workflow and a proxy smoke script
This commit is contained in:
1 parent
e8d141ca43
commit
b33e6ff001
33 files changed
+1147
-317
No files matched your search
@@ -0,0 +1,178 @@
|
||||
// Server-side Go API client. Every Nitro route uses this module so the browser
|
||||
// only ever talks to the Nuxt origin: the Go base URL and the control
|
||||
// credentials stay in the Node process.
|
||||
|
||||
interface ApiErrorEnvelope {
|
||||
error?: { code?: string; message?: string }
|
||||
message?: string
|
||||
statusMessage?: string
|
||||
}
|
||||
|
||||
export interface ApiRequestOptions {
|
||||
query?: Record<string, unknown>
|
||||
method?: 'GET' | 'POST'
|
||||
/** Raw request body, forwarded unchanged (multipart training uploads). */
|
||||
body?: any
|
||||
headers?: Record<string, string>
|
||||
/** Attach CONTROL_USER/CONTROL_PASS as Basic auth. */
|
||||
control?: boolean
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
const DEFAULT_API_BASE = 'http://localhost:8080'
|
||||
|
||||
function envValue(...names: string[]): string {
|
||||
for (const name of names) {
|
||||
const value = process.env[name]
|
||||
if (value !== undefined && value !== '') return value
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** Runtime Go base URL. Reads the env directly so K8s can override the build. */
|
||||
export function apiBaseUrl(): string {
|
||||
const config = useRuntimeConfig()
|
||||
return (
|
||||
envValue('NUXT_API_INTERNAL_BASE', 'NUXT_API_BASE', 'NUXT_PUBLIC_API_BASE') ||
|
||||
String(config.apiBase ?? '') ||
|
||||
DEFAULT_API_BASE
|
||||
).replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
/** True only when NUXT_USE_MOCK=1 / NUXT_PUBLIC_USE_MOCK=1 is set. */
|
||||
export function isMockMode(): boolean {
|
||||
const config = useRuntimeConfig()
|
||||
const raw =
|
||||
envValue('NUXT_USE_MOCK', 'NUXT_PUBLIC_USE_MOCK') || String(config.useMock ?? '')
|
||||
return raw === '1' || raw.toLowerCase() === 'true'
|
||||
}
|
||||
|
||||
function controlAuthorization(): string | undefined {
|
||||
const config = useRuntimeConfig()
|
||||
const user = envValue('CONTROL_USER', 'NUXT_CONTROL_USER') || String(config.controlUser ?? '')
|
||||
const pass = envValue('CONTROL_PASS', 'NUXT_CONTROL_PASS') || String(config.controlPass ?? '')
|
||||
if (user && pass) return `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`
|
||||
|
||||
const token = envValue('CONTROL_TOKEN', 'NUXT_CONTROL_TOKEN') || String(config.controlToken ?? '')
|
||||
// Go currently validates Basic auth; Bearer is accepted here for the future
|
||||
// token-based control surface without exposing the token to the browser.
|
||||
if (token) return `Bearer ${token}`
|
||||
return undefined
|
||||
}
|
||||
|
||||
function timeoutMs(override?: number): number {
|
||||
if (override && Number.isFinite(override)) return override
|
||||
const configured = Number(
|
||||
envValue('NUXT_API_TIMEOUT_MS') || useRuntimeConfig().apiTimeoutMs,
|
||||
)
|
||||
return Number.isFinite(configured) && configured > 0 ? configured : 8000
|
||||
}
|
||||
|
||||
function upstreamError(error: unknown): never {
|
||||
const err = error as {
|
||||
status?: number
|
||||
statusCode?: number
|
||||
data?: ApiErrorEnvelope
|
||||
message?: string
|
||||
code?: string
|
||||
}
|
||||
|
||||
const status = err.status ?? err.statusCode
|
||||
if (status && status >= 400 && status < 600) {
|
||||
const message =
|
||||
err.data?.error?.message ?? err.data?.message ?? err.message ?? 'Go API request failed'
|
||||
throw createError({ statusCode: status, statusMessage: message, data: err.data })
|
||||
}
|
||||
|
||||
const reason = err.code === 'ETIMEDOUT' ? 'timed out' : 'unreachable'
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: `Go API ${reason} at ${apiBaseUrl()}`,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the Go API and return its JSON body. Non-2xx responses are converted to
|
||||
* H3 errors carrying the upstream status, so the UI sees a real 400/404/503.
|
||||
*/
|
||||
export async function apiRequest<T>(path: string, options: ApiRequestOptions = {}): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
|
||||
if (options.control) {
|
||||
const authorization = controlAuthorization()
|
||||
if (authorization) headers.authorization = authorization
|
||||
}
|
||||
|
||||
const response = await $fetch
|
||||
.raw<T>(`${apiBaseUrl()}${path}`, {
|
||||
method: options.method ?? 'GET',
|
||||
query: options.query,
|
||||
body: options.body,
|
||||
headers,
|
||||
timeout: timeoutMs(options.timeoutMs),
|
||||
})
|
||||
.catch((error) => upstreamError(error))
|
||||
|
||||
if (response.status >= 400) {
|
||||
const body = response._data as ApiErrorEnvelope | undefined
|
||||
const message =
|
||||
body?.error?.message ?? body?.message ?? `Go API returned ${response.status}`
|
||||
throw createError({ statusCode: response.status, statusMessage: message, data: body })
|
||||
}
|
||||
return response._data as T
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward a request body (training upload) and preserve Go's status code and
|
||||
* JSON body, including 202/400/409/502 responses that are part of the flow.
|
||||
*/
|
||||
export async function apiForward<T>(
|
||||
event: import('h3').H3Event,
|
||||
path: string,
|
||||
options: ApiRequestOptions = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', ...options.headers }
|
||||
if (options.control) {
|
||||
const authorization = controlAuthorization()
|
||||
if (authorization) headers.authorization = authorization
|
||||
}
|
||||
|
||||
const response = await $fetch
|
||||
.raw<T>(`${apiBaseUrl()}${path}`, {
|
||||
method: options.method ?? 'POST',
|
||||
query: options.query,
|
||||
body: options.body,
|
||||
headers,
|
||||
timeout: timeoutMs(options.timeoutMs),
|
||||
})
|
||||
.catch((error) => upstreamError(error))
|
||||
|
||||
setResponseStatus(event, response.status)
|
||||
return response._data as T
|
||||
}
|
||||
|
||||
/** Validate an enum-like query value before it reaches the Go API. */
|
||||
export function enumParam<T extends string>(
|
||||
value: unknown,
|
||||
allowed: readonly T[],
|
||||
name: string,
|
||||
fallback?: T,
|
||||
): T {
|
||||
if (value === undefined || value === '') {
|
||||
if (fallback !== undefined) return fallback
|
||||
throw createError({ statusCode: 400, statusMessage: `${name} is required` })
|
||||
}
|
||||
const candidate = String(value) as T
|
||||
if (!allowed.includes(candidate)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Invalid ${name}: ${candidate}. Expected ${allowed.join(' | ')}.`,
|
||||
})
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
export function sensorParam(value: unknown, fallback = 'hn-stadtgalerie-01'): string {
|
||||
const sensor = value === undefined || value === '' ? fallback : String(value)
|
||||
if (!sensor) throw createError({ statusCode: 400, statusMessage: 'sensor is required' })
|
||||
return sensor
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import context from '../../mock/context.json'
|
||||
import demo from '../../mock/demo.json'
|
||||
import meta from '../../mock/meta.json'
|
||||
import scenario from '../../mock/scenario.json'
|
||||
import scenarios from '../../mock/scenarios.json'
|
||||
import sensors from '../../mock/sensors.json'
|
||||
|
||||
import forecast01 from '../../mock/forecast/hn-stadtgalerie-01.json'
|
||||
@@ -30,7 +29,6 @@ import type {
|
||||
ContextResponse,
|
||||
ForecastResponse,
|
||||
MetaResponse,
|
||||
ScenarioPreset,
|
||||
ScenarioState,
|
||||
Sensor,
|
||||
SeriesResponse,
|
||||
@@ -39,7 +37,6 @@ import type {
|
||||
export const mockMeta = meta as MetaResponse
|
||||
export const mockContext = context as ContextResponse
|
||||
export const mockSensors = sensors as Sensor[]
|
||||
export const mockScenarios = scenarios as ScenarioPreset[]
|
||||
export const mockScenario = scenario as ScenarioState
|
||||
export const mockDemo = demo as {
|
||||
now: string
|
||||
|
||||
Reference in new issue
Block a user