La app avisa cuando la api es más vieja que ella
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Validado desde afuera, y era esto: **el frontend desplegado es el nuevo y la api no**. Los hashes que
sirve producción coinciden byte a byte con mi build de HEAD, y el bundle contiene las novedades
("What arrived last", "one total an hour"); pero `/api/vitals/hours`, `/api/insights` y
`/api/music/lookup` responden **404** donde esta versión responde 401. O sea: el número de cada
tarjeta lo calcula la api — y la api que corre es la de antes de las horas, la que lee el total del
día como si fuera la hora 00 y suma 840 donde el reloj dice 499.
Eso explica el reporte completo sin ninguna otra suposición: las actualizaciones llegan, se guardan,
y la pantalla nueva pide cosas que ese servidor no tiene (de ahí que el detalle por hora y el recibo
no aparezcan nunca) mientras muestra el número que el servidor viejo le manda.
La causa de fondo es de despliegue: `web` se reconstruye desde el código en cada deploy, pero el
código de la api se copia *dentro* de su contenedor, y Dokploy no recrea un servicio que ya está
Running. Un deploy entonces refresca la mitad de la aplicación.
Arreglar eso no puede depender de que alguien se acuerde, así que la app ahora lo pregunta:
`GET /api/config` publica `features` — una lista de capacidades, nunca configuración ni credenciales —
y Salud muestra una línea ámbar cuando esa lista falta o no llega hasta `vitals.hours`. Un servidor
viejo ya no puede parecer una pantalla rota.
Tests: el config contra el servidor real (la lista existe, nombra las rutas nuevas, y esas rutas
contestan 401 y no 404, sin claves adentro), y el aviso en la pantalla para los dos casos — api sin
lista y api al día. Mutation-check: si el aviso deja de dispararse con una api sin lista, falla.
This commit is contained in:
1 parent
407d7c47c9
commit
4ba9e29d1e
6 files changed
+84
-2
No files matched your search
+20
-1
@@ -28,6 +28,17 @@ import {
|
||||
import { readInsight, writeInsight, clearInsight } from './insights.js';
|
||||
import { LIB_BY_ID } from './coach/core/library.js';
|
||||
|
||||
/* What this build of the api offers, for `GET /api/config` (see the note there). Add to this list
|
||||
when a route or a response shape a client depends on lands, and check for it in the client that
|
||||
needs it: a screen that degrades silently is a screen nobody can debug. */
|
||||
export const API_FEATURES = Object.freeze([
|
||||
'vitals', // POST /api/vitals/ingest, GET /api/vitals
|
||||
'vitals.hours', // hourly buckets, and GET /api/vitals/hours
|
||||
'vitals.receipt', // per-metric `shape`, and per-day `own` / `hours_sum`
|
||||
'music.lookup', // POST /api/music/lookup
|
||||
'insights' // GET/POST /api/insights (the second opinion)
|
||||
]);
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
const RP_ID = process.env.RP_ID || 'localhost';
|
||||
@@ -803,9 +814,17 @@ const routes = {
|
||||
// the instance has both switched the Coach on and successfully connected a provider — the
|
||||
// single flag every piece of Coach UI hangs off, so an unconfigured instance is byte-for-byte
|
||||
// the app it was before the feature existed.
|
||||
// The public instance config, and the list of what this build of the *api* can do.
|
||||
//
|
||||
// `features` exists because the app and the api are deployed separately: `web` is rebuilt from
|
||||
// source on every deploy, while the api's code is copied *into* its container, so a deploy that
|
||||
// does not recreate that container leaves the newest frontend talking to an older server. The
|
||||
// result looks like a broken screen — numbers that do not move, a screen asking for a route that
|
||||
// answers 404 — and the person looking at it has no way to tell that from a bug. Now the app can
|
||||
// ask, and say which it is. The list is capabilities, never configuration or credentials.
|
||||
'GET /api/config': async (req, res) => {
|
||||
const coach = coachConfig.publicConfig();
|
||||
json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, ...(coach ? { coach } : {}) });
|
||||
json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, features: API_FEATURES, ...(coach ? { coach } : {}) });
|
||||
},
|
||||
|
||||
'GET /api/me': async (req, res) => {
|
||||
|
||||
@@ -106,6 +106,25 @@ async function seed(h, uid) {
|
||||
const ask = (h, uid) => fetch(`${h.api}/api/insights`, { method: 'POST', headers: { ...cookie(uid), 'Sec-Fetch-Site': 'same-origin' } });
|
||||
const read = (h, uid, q = '') => fetch(`${h.api}/api/insights${q}`, { headers: cookie(uid) });
|
||||
|
||||
/* The app and the api are deployed separately — `web` is rebuilt from source on every deploy, the
|
||||
api's code is copied into a container that a deploy does not have to recreate — so the newest
|
||||
screen can end up talking to an older server. `/api/config` is how the screen finds out, which
|
||||
only works if the list is actually there and actually names the new routes. */
|
||||
test('the public config lists what this build of the api can do', async t => {
|
||||
const h = await startServer(t);
|
||||
const cfg = await (await fetch(`${h.api}/api/config`)).json();
|
||||
assert.equal(typeof cfg.invite_only, 'boolean');
|
||||
assert.ok(Array.isArray(cfg.features), 'a client cannot detect a stale api without the list');
|
||||
assert.ok(cfg.features.includes('vitals.hours'));
|
||||
assert.ok(cfg.features.includes('insights'));
|
||||
// ...and the routes those names promise are the ones this server actually answers.
|
||||
assert.equal((await fetch(`${h.api}/api/vitals/hours`)).status, 401, 'a route that exists refuses without a session');
|
||||
assert.equal((await fetch(`${h.api}/api/insights`)).status, 401);
|
||||
assert.equal((await fetch(`${h.api}/api/music/lookup`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status, 401);
|
||||
// Nothing in it is configuration or a credential.
|
||||
assert.equal(JSON.stringify(cfg).includes('key'), false);
|
||||
});
|
||||
|
||||
test('an instance with no key has no second opinion, and says so instead of failing', async t => {
|
||||
const h = await startServer(t);
|
||||
await seed(h, 'u_j1');
|
||||
|
||||
@@ -1374,6 +1374,12 @@ body.chips-dragging *{cursor:inherit}
|
||||
.vh-note{margin:10px 0 0;padding:9px 11px;border-radius:var(--r-sm);font-size:12.5px;line-height:1.5;
|
||||
color:var(--label-2);background:color-mix(in srgb,var(--orange) 12%,transparent);
|
||||
border:var(--hair) solid color-mix(in srgb,var(--orange) 30%,transparent)}
|
||||
/* The app and the api are on different versions: an amber line, because nothing is lost — it is a
|
||||
deployment that did not finish, and the fix is one container. */
|
||||
.vh-stale{display:flex;gap:9px;align-items:flex-start;margin-bottom:12px;padding:11px 13px;line-height:1.5;
|
||||
font-size:12.5px;color:var(--label-2);background:color-mix(in srgb,var(--orange) 12%,var(--glass));
|
||||
border:var(--hair) solid color-mix(in srgb,var(--orange) 34%,transparent)}
|
||||
.vh-stale .icn{color:var(--orange);font-size:16px;flex:0 0 auto;margin-top:1px}
|
||||
.ins-card{--tint:var(--acc);padding:12px 14px 14px;margin-bottom:12px}
|
||||
.ins-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px}
|
||||
.ins-t{display:flex;align-items:center;gap:6px;font-size:14px;font-weight:600;color:var(--tint)}
|
||||
|
||||
@@ -1406,6 +1406,7 @@ export default {
|
||||
// resetting one measurement, from its own detail sheet
|
||||
'Reset this measurement': 'Reiniciar esta medición',
|
||||
// segunda opinión (Jev)
|
||||
'The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.': 'El servidor está corriendo una api más vieja que esta pantalla: los números pueden no coincidir con Apple Health, y el detalle por hora y el recibo del último envío no van a aparecer hasta que se actualice el contenedor de la api.',
|
||||
'What arrived last': 'Qué llegó en el último envío',
|
||||
'Datapoints in the last sync': 'Datos en el último envío',
|
||||
'How they were stamped': 'Cómo vienen marcados',
|
||||
|
||||
@@ -400,6 +400,19 @@ export default function Health() {
|
||||
const openSheet = useUI(s => s.openSheet)
|
||||
const toast = useUI(s => s.toast)
|
||||
const isGuest = useStore(s => s.isGuest())
|
||||
/* Whether the server this app is talking to is as new as the app.
|
||||
*
|
||||
* They ship separately: `web` is rebuilt from source on every deploy, while the api's code lives
|
||||
* *inside* its container, so a deploy that does not recreate that container leaves the newest
|
||||
* frontend on top of an older api. Everything still renders — the numbers just never move and the
|
||||
* hourly detail has nothing behind it — which is indistinguishable from a bug from this side of
|
||||
* the screen. `GET /api/config` says what the api can do, so the screen can say which it is
|
||||
* instead of leaving somebody to guess.
|
||||
*
|
||||
* Deliberately quiet in every uncertain case: no config yet, or a config from an instance whose
|
||||
* api is old enough to have no `features` at all, which is the one case worth mentioning. */
|
||||
const cfg = useStore(s => s.config)
|
||||
const staleApi = !!cfg && (!Array.isArray(cfg.features) || !cfg.features.includes('vitals.hours'))
|
||||
const [data, setData] = useState(null)
|
||||
const [err, setErr] = useState('')
|
||||
const [days, setDays] = useState(1)
|
||||
@@ -566,6 +579,11 @@ export default function Health() {
|
||||
{!err && data && !hasVitals(data) && <Empty onSetup={setup} />}
|
||||
|
||||
{!err && hasVitals(data) && <>
|
||||
{staleApi && <div className="card vh-stale">
|
||||
<Icon name="warning" />
|
||||
<div>{t('The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.')}</div>
|
||||
</div>}
|
||||
|
||||
{ins?.configured && <InsightCard
|
||||
insight={ins.insight ? { ...ins.insight, fresh: ins.freshness?.fresh !== false } : null}
|
||||
view={view} sent={ins.sent} budget={ins.budget} busy={asking}
|
||||
|
||||
@@ -55,7 +55,7 @@ beforeEach(() => {
|
||||
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
|
||||
api.mockReset()
|
||||
localStorage.removeItem('gym_guest')
|
||||
useStore.setState({ user: { id: 'u1', name: 'Test' } })
|
||||
useStore.setState({ user: { id: 'u1', name: 'Test' }, config: null })
|
||||
})
|
||||
/* A sheet lives in the UI store, not in the screen, so it outlives the screen's root: without
|
||||
clearing it the next test remounts yesterday's sheet, which is both a stray element in the DOM
|
||||
@@ -170,6 +170,25 @@ describe('Salud', () => {
|
||||
expect(host.querySelector('.vh-sync').textContent).toContain('No sync has arrived yet')
|
||||
})
|
||||
|
||||
/* The app and the api ship separately, and a deploy that does not recreate the api container
|
||||
leaves the newest screen on top of an older server: the numbers stop matching Apple Health and
|
||||
the new panels have nothing behind them, which from this side is indistinguishable from a bug.
|
||||
The api advertises what it can do in /api/config; when that list is missing or too old, the
|
||||
screen says which it is. */
|
||||
it('says so when the server is an older api than this screen', async () => {
|
||||
api.mockResolvedValue(VITALS)
|
||||
// An api old enough to predate the feature list: no `features` key at all.
|
||||
await act(async () => { useStore.setState({ config: { invite_only: false, allow_guest: true } }) })
|
||||
await mount()
|
||||
expect(host.querySelector('.vh-stale').textContent).toContain('older API')
|
||||
|
||||
// A current one: the list is there and the screen stays quiet.
|
||||
await act(async () => { useStore.setState({ config: { invite_only: false, allow_guest: true, features: ['vitals', 'vitals.hours', 'vitals.receipt'] } }) })
|
||||
await act(async () => { host.querySelector('button[aria-label="Refresh"]').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
await act(async () => {})
|
||||
expect(host.querySelector('.vh-stale')).toBe(null)
|
||||
})
|
||||
|
||||
it('offers the setup steps instead of a blank screen when nothing has arrived', async () => {
|
||||
api.mockResolvedValue({ ok: true, days: 30, key: null, updatedAt: 0, last: null, metrics: {}, workouts: [] })
|
||||
await mount()
|
||||
|
||||
Reference in new issue
Block a user