From b33e6ff001d1919f6f7839bb5982938a1223f331 Mon Sep 17 00:00:00 2001 From: Noel Sabia Date: Sat, 14 Nov 2026 06:13:00 +0100 Subject: [PATCH] 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 --- .gitea/workflows/ci.yml | 25 ++++ Dockerfile | 14 +- Makefile | 28 ++++ README.md | 170 ++++++++++++++-------- app/app.vue | 11 +- app/components/TrainModelCard.vue | 63 ++++++--- app/pages/about.vue | 23 ++- app/pages/forecast.vue | 18 ++- app/pages/index.vue | 16 ++- app/pages/plan.vue | 225 +++++++++++++++++++++++------- app/pages/simulate.vue | 129 ++++++++++------- nuxt.config.ts | 20 +++ scripts/smoke-api.mjs | 133 ++++++++++++++++++ server/api/context.get.ts | 7 +- server/api/forecast.get.ts | 48 +++---- server/api/healthz.get.ts | 7 +- server/api/meta.get.ts | 7 +- server/api/readyz.get.ts | 7 +- server/api/scenario.get.ts | 7 +- server/api/scenario.post.ts | 24 +++- server/api/scenarios.get.ts | 6 +- server/api/sensors.get.ts | 7 +- server/api/series.get.ts | 31 +++- server/api/staffing.get.ts | 53 +++---- server/api/train.post.ts | 70 ++++++---- server/api/train/[jobId].get.ts | 19 ++- server/utils/api.ts | 178 +++++++++++++++++++++++ server/utils/mock-data.ts | 3 - shared/scenarios.ts | 39 ++++++ shared/staffing.ts | 8 +- test/api-parity.test.ts | 39 ++++++ test/fixtures/go-staffing.json | 1 + test/staffing.test.ts | 28 ++++ 33 files changed, 1147 insertions(+), 317 deletions(-) create mode 100644 .gitea/workflows/ci.yml create mode 100644 Makefile create mode 100644 scripts/smoke-api.mjs create mode 100644 server/utils/api.ts create mode 100644 shared/scenarios.ts create mode 100644 test/api-parity.test.ts create mode 100644 test/fixtures/go-staffing.json diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..abe1343 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,25 @@ +name: ci + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + + - name: Check + run: make check diff --git a/Dockerfile b/Dockerfile index a17d994..328711d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,6 @@ # Multi-stage production build for the Nuxt SSR server. -# The runtime image runs as the unprivileged `node` user. +# The runtime image runs as numeric UID/GID 10001:10001 so Kubernetes can +# verify runAsNonRoot without a named user lookup. FROM node:22-alpine AS build WORKDIR /app @@ -16,10 +17,17 @@ WORKDIR /app ENV NODE_ENV=production ENV HOST=0.0.0.0 ENV PORT=3000 +ENV HOME=/tmp +ENV NITRO_TEMP_DIR=/tmp -COPY --from=build --chown=node:node /app/.output ./.output +# Create a numeric runtime identity. Keep the literal numbers in USER/COPY: +# the kubelet cannot resolve names such as "app" reliably. +RUN addgroup -g 10001 -S app \ + && adduser -u 10001 -S app -G app -USER node +COPY --from=build --chown=10001:10001 /app/.output ./.output + +USER 10001:10001 EXPOSE 3000 CMD ["node", ".output/server/index.mjs"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7dd6469 --- /dev/null +++ b/Makefile @@ -0,0 +1,28 @@ +NPM ?= npm + +.PHONY: install dev build test check preview docker-build smoke + +install: + $(NPM) ci + +dev: + $(NPM) run dev + +build: + $(NPM) run build + +test: + $(NPM) test + +# Local equivalent of .gitea/workflows/ci.yml. +check: install build test + +preview: + $(NPM) run preview + +docker-build: + docker build -t pulsecast-web:local . + +# Requires a running web server (npm run preview or node .output/server/index.mjs). +smoke: + node scripts/smoke-api.mjs diff --git a/README.md b/README.md index 4c34aee..e1cd1b2 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,9 @@ evidence; the decision is the weekly plan. - Nuxt `4.6.4`, `ssr: true`, Nitro `node-server` - `@sit-onyx/nuxt` `1.2.0` + `sit-onyx` `1.22.0` for the entire shell and UI -- Mock JSON in `mock/`, mirrored by Nitro routes in `server/api/` -- Shared plan heuristic in `shared/staffing.ts` +- Nitro server routes proxy to the Go API; the browser only talks to this origin +- Shared plan heuristic in `shared/staffing.ts`, used for the mock fallback and + for the labeled local preview on `/plan` Onyx is used for the navigation/app shell, page layout, cards, tables, buttons, badges, tags, selects, segmented control, slider, stepper, accordion and file @@ -21,56 +22,99 @@ upload. The app does not ship a parallel component design system. ```bash npm ci -npm run dev # http://localhost:3000 +npm run dev # http://localhost:3000, expects Go at http://localhost:8080 npm run build # production SSR build in .output/ npm run preview # preview the built app -npm test # heuristic unit tests -npm run mock # regenerate deterministic mock JSON +npm test # heuristic + Go parity tests ``` The built SSR server can also be started directly: ```bash -PORT=3000 node .output/server/index.mjs +NUXT_API_INTERNAL_BASE=http://localhost:8080 \ + PORT=3000 node .output/server/index.mjs ``` +## API wiring + +Every route in `server/api/` is a proxy to the Go service. The default is the +real API; mock JSON is an explicit dev fallback only. + +| Nitro route | Upstream | +| --- | --- | +| `GET /api/healthz` | `GET /api/healthz` | +| `GET /api/readyz` | `GET /api/readyz` | +| `GET /api/meta` | `GET /api/meta` | +| `GET /api/sensors` | `GET /api/sensors` | +| `GET /api/context` | `GET /api/context` | +| `GET /api/series` | `GET /api/series` | +| `GET /api/forecast` | `GET /api/forecast` | +| `GET /api/staffing` | `GET /api/staffing` | +| `GET /api/scenario` | `GET /api/scenario` | +| `POST /api/scenario` | `POST /api/scenario` with server-side control auth | +| `POST /api/train` | `POST /api/train` with server-side control auth | +| `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth | +| `GET /api/scenarios` | Local UI metadata only (labels/descriptions) | + +`/plan` reads Go `/api/staffing` directly. The four local assumption controls +(safety factor, minimum staff, shift length, labour cost) are not query inputs +of the Go contract, so changing them renders an explicit **local preview** from +the API’s forecast hours; “Use API plan” restores the server values. The shared +heuristic is tested against a captured Go response in +`test/fixtures/go-staffing.json`. + +### Environment + +| Variable | Default | Purpose | +| --- | --- | --- | +| `NUXT_API_INTERNAL_BASE` | — | Preferred server-side Go base (`http://api:8080` in K8s) | +| `NUXT_API_BASE` | — | Alias for the server-side base | +| `NUXT_PUBLIC_API_BASE` | — | Fallback base; also exposed to the browser | +| `NUXT_API_TIMEOUT_MS` | `8000` | Upstream request timeout | +| `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback | +| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/api/scenario` and `/api/train` | +| `CONTROL_TOKEN` | unset | Optional Bearer token for future control auth | +| `NUXT_PUBLIC_DEMO_NOW` | `2026-11-14T08:12:00Z` | Replay clock used for labels | + +Control credentials are read only in the Nitro process. They are never placed +in `runtimeConfig.public` and never reach the browser bundle. If they are +unset, Go returns `503 control_auth_unconfigured` / `401`; the UI surfaces that +error instead of exposing anything. + +The K8s web Deployment must mount the same `control-auth` secret as the API +Deployment: + +```yaml +env: + - name: CONTROL_USER + valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_USER } } + - name: CONTROL_PASS + valueFrom: { secretKeyRef: { name: control-auth, key: CONTROL_PASS } } +``` + +### Mock fallback + +```bash +NUXT_PUBLIC_USE_MOCK=1 npm run dev +``` + +Mock mode serves deterministic JSON from `mock/` and completes training +immediately. It is for developing the UI without Go; the default and the +deployed path are the real API. + ## Screens -| Route | Purpose | -| ----------- | ----------------------------------------------------------------------- | -| `/` | Now: replay reading, 8-sensor schematic, weather, holiday, data versions | -| `/forecast` | 7-day daily forecast, uncertainty band, weather strip | -| `/plan` | **Hero.** Peak decision, shift blocks, coverage, cost, why, assumptions | -| `/simulate` | Scenario comparison (base vs sunny/rainy/Wednesday event) | -| `/about` | Method, metrics, limits, privacy, mock training form | +| Route | Purpose | +| --- | --- | +| `/` | Now: replay reading, 8-sensor schematic, weather, holiday, data versions | +| `/forecast` | 7-day daily forecast, uncertainty band, weather strip | +| `/plan` | **Hero.** Peak decision, shift blocks, coverage, cost, why, assumptions | +| `/simulate` | Base vs scenario plan, both read from Go `/api/staffing` | +| `/about` | Method, metrics, limits, privacy, train form | The layout is checked at **390 px** (single column, mobile Onyx nav, day cards) and **1440 px** (Onyx horizontal nav, two-column plan with tables). -## Mock API - -All mock routes return shapes from -`/home/noel/Documents/Hackathon_2026/CONTRACT.md` and are bundled into the Nitro -output, so the UI renders before the Go API exists: - -```text -GET /api/healthz -GET /api/readyz -GET /api/meta -GET /api/sensors -GET /api/context -GET /api/series?sensor=&step= -GET /api/forecast?sensor=&horizon=&scenario= -GET /api/staffing?sensor=&scenario=&standard= -GET /api/scenario -POST /api/scenario -POST /api/train -GET /api/train/:job_id -``` - -`NUXT_PUBLIC_API_BASE` and `NUXT_PUBLIC_DEMO_NOW` are runtime config hooks for -the next integration slice. The current pages call the Nitro mock routes. - ## Plan logic `shared/staffing.ts` is the single implementation of the contract heuristic: @@ -81,32 +125,44 @@ required = max(required, min_staff) ``` Store hours are 10:00–20:00 Europe/Berlin; default blocks are 4 h; labour cost is -€16/h; the default service standard is 25 visitors per staff-hour. Coverage is -at or above requirement by construction because each block is sized to its local -peak — the UI shows the resulting overstaffed hours instead of hiding them. +€16/h; the default service standard is 25 visitors per staff-hour. The flat +schedule applies the global peak requirement to every store hour, matching Go +and CONTRACT.md §5. Coverage is at or above requirement by construction because +each block is sized to its local peak — the UI shows the resulting overstaffed +hours instead of hiding them. -## What is still mocked +## Checks and CI -- Forecast, series, weather, holidays, sensor metadata, model metrics and - versions are deterministic JSON in `mock/`. Only `7d` has a full hourly mock; - `15m`, `1h` and `48h` are slices of that hourly series so the contract shape - is available to the next integration step. -- `POST /api/train` and `GET /api/train/:job_id` return an immediate success with - sample metrics. There is no real training run in the web tier. -- The sensor map is a **schematic** of relative positions. It does not yet - overlay the static MapLibre/basemap asset and makes no city-wide heatmap claim. -- Scenario changes are local; SSE (`/api/stream`) and the 5 s polling fallback - are not wired yet. The plan recomputes from the same deterministic heuristic. -- Approve/Export CSV are client-side actions; the CSV is real, the approval is - demo state only. -- No auth, no POS/sales/queue/payroll data, no live sensor feed. +```bash +make check # npm ci, npm run build, npm test +make smoke # against a running web server (WEB_URL=...) +``` + +The same `make check` runs in Gitea Actions (`.gitea/workflows/ci.yml`). The +workflow needs no secrets, no registry push and no cluster access. + +`scripts/smoke-api.mjs` exercises the Nitro → Go chain: health, sensors, +context, meta, series, base and scenario forecasts, standard and premium +staffing, local presets, and 404/400 propagation. ## Docker ```bash docker build -t pulsecast-web . -docker run --rm -p 3000:3000 pulsecast-web +docker run --rm -p 3000:3000 \ + -e NUXT_API_INTERNAL_BASE=http://host.docker.internal:8080 \ + pulsecast-web ``` -The runtime stage is `node:22-alpine`, copies only `.output/`, and runs as the -non-root `node` user. +The multi-stage image copies only `.output/` into `node:22-alpine`. It creates +numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs +`USER 10001:10001`. Kubernetes should set `runAsUser: 10001`, +`runAsGroup: 10001` (never a named user such as `node`). + +## Limits + +- No POS, sales, queue or payroll data. Cost is an assumption. +- Forecast is model output; the plan is decision support, not an optimizer. +- Eight sensors in a 580 m cluster; no city-wide heatmap claim. +- SSE (`/api/stream`), `/live` and `/stage` are the next worktree. +- Raw CSV, secrets and kubeconfig never enter this repository. diff --git a/app/app.vue b/app/app.vue index f40ca41..c3adce4 100644 --- a/app/app.vue +++ b/app/app.vue @@ -8,6 +8,13 @@ import { } from '@sit-onyx/icons' const route = useRoute() +const config = useRuntimeConfig() +const usingMock = computed( + () => + config.public.useMock === true || + config.public.useMock === '1' || + config.public.useMock === 'true', +) const navigation = [ { to: '/', label: 'Now', icon: iconHome }, @@ -34,7 +41,7 @@ const activeLabel = computed( :icon="item.icon" /> @@ -46,7 +53,7 @@ const activeLabel = computed( diff --git a/app/components/TrainModelCard.vue b/app/components/TrainModelCard.vue index b8d1e76..c462d9a 100644 --- a/app/components/TrainModelCard.vue +++ b/app/components/TrainModelCard.vue @@ -6,7 +6,6 @@ interface TrainResponse { status: string model: 'small' | 'forecast' submitted_at: string - mock?: boolean } interface TrainJob { @@ -44,70 +43,87 @@ const statusColor = computed(() => { } }) +function apiErrorMessage(error: unknown, fallback: string): string { + const data = ( + error as { + data?: { error?: { message?: string }; message?: string; statusMessage?: string } + } + )?.data + return data?.error?.message ?? data?.message ?? data?.statusMessage ?? fallback +} + +function stopPolling() { + if (pollTimer) clearInterval(pollTimer) + pollTimer = undefined + polling.value = false +} + async function poll(jobId: string) { + stopPolling() polling.value = true let attempts = 0 pollTimer = setInterval(async () => { attempts += 1 try { - const result = await $fetch(`/api/train/${jobId}`) + const result = await $fetch(`/api/train/${encodeURIComponent(jobId)}`) job.value = result - if (result.status === 'succeeded' || result.status === 'failed') { - clearInterval(pollTimer) - polling.value = false - } - } catch { - if (attempts >= 12) { - clearInterval(pollTimer) - polling.value = false - errorMessage.value = 'Could not read the mock training job status.' + if (result.status === 'succeeded' || result.status === 'failed') stopPolling() + } catch (error) { + if (attempts >= 30) { + stopPolling() + errorMessage.value = apiErrorMessage(error, 'Could not read the training job status.') } } - }, 700) + }, 1000) } async function submit() { errorMessage.value = '' job.value = null + if (!file.value) { + errorMessage.value = 'Choose a CSV file first.' + return + } + submitting.value = true try { const formData = new FormData() formData.append('model', model.value) - if (file.value) formData.append('file', file.value) + formData.append('file', file.value) const response = await $fetch('/api/train', { method: 'POST', body: formData }) await poll(response.job_id) - } catch { - errorMessage.value = 'Training submission failed. The mock endpoint expects a CSV or model selection.' + } catch (error) { + errorMessage.value = apiErrorMessage( + error, + 'Training submission failed. Check the Go API and its FastAPI training upstream.', + ) } finally { submitting.value = false } } -onBeforeUnmount(() => { - if (pollTimer) clearInterval(pollTimer) -}) +onBeforeUnmount(stopPolling)