Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach: der Server-Fetch wartet so lange wie der Job, nicht 300 s wie undici
Duarte Santos0d38bc07f018
diff --git a/api/coach/jobs.js b/api/coach/jobs.jsindex 92d4b9711..fe1b187e0 100644--- a/api/coach/jobs.js+++ b/api/coach/jobs.js@@ -23,6 +23,7 @@ import { extractJSON } from './core/parse.js';import { hashPlan } from './core/plan-hash.js';import { buildPrompt } from './core/prompt.js';import { handleFor } from './handle.js';+import { fetchFor } from './node-fetch.js';import { canDropPrivileges, unprivilegedIds } from './adapters/spawn.js';// The prompt assembly, the plan fingerprint and the invoke→parse→validate→repair loop all@@ -266,7 +267,8 @@ async function execute(job) {const attempt = await runPipeline({adapter, cfg, kind: job.kind, payload, model: cfgStore.modelFor(cfg), timeoutMs: TIMEOUT_MS,- invokeOpts: { jobDir, env }+ // The HTTP adapters take the fetch they are given; the runtime adapters ignore it.+ invokeOpts: { jobDir, env, fetch: fetchFor(TIMEOUT_MS) }});if (!attempt.ok) {return finish(job, { outcome: 'failed', errorClass: attempt.errorClass, detail: attempt.detail });@@ -323,7 +325,7 @@ export async function testRun() {const check = await adapter.check(cfg, env);if (!check.ok) return { ok: false, error: check.error || 'the provider runtime could not be run' };const r = await adapter.invoke({- cfg, jobDir, env, model: cfgStore.modelFor(cfg), timeoutMs: 90000,+ cfg, jobDir, env, model: cfgStore.modelFor(cfg), timeoutMs: 90000, fetch: fetchFor(90000),prompt: 'Reply with exactly this JSON object and nothing else: {"coach_contract":1,"ok":true}'});if (r.timedOut) return { ok: false, version: check.version, error: 'the provider did not answer in time' };diff --git a/api/coach/node-fetch.js b/api/coach/node-fetch.jsnew file mode 100644index 000000000..90696aaeb--- /dev/null+++ b/api/coach/node-fetch.js@@ -0,0 +1,33 @@+/* A fetch for the server that waits as long as a job may.+ *+ * Node's global fetch is undici with its defaults, and one of those defaults is a hard+ * 300-second headers timeout — the connection is torn down and the adapter sees a generic+ * "fetch failed", however long the job's own timeout was. A cloud API answers well inside+ * that; a local model on a small box legitimately does not, and COACH_JOB_TIMEOUT_MS exists+ * precisely for it. So the job runner hands the HTTP adapters this fetch instead, with the+ * transport timeouts derived from the job timeout rather than from undici's idea of patience.+ *+ * Node-only by design: the phone's transport is capacitor-fetch.js, and the core adapters+ * take whichever fetch they are given. */+// undici's own fetch alongside its Agent, so the dispatcher option is honoured by the same+// undici version on every Node the image or a dev box happens to run.+import { fetch as undiciFetch, Agent } from 'undici';++const GRACE_MS = 15000;++let agent = null;+/** The dispatcher, built once for the job timeout in force. */+export function dispatcherFor(timeoutMs) {+ const budget = Math.max(60000, +timeoutMs || 0) + GRACE_MS;+ if (!agent || agent._coachBudget !== budget) {+ agent = new Agent({ headersTimeout: budget, bodyTimeout: budget, connectTimeout: 30000 });+ agent._coachBudget = budget;+ }+ return agent;+}++/** fetch(url, init) that will wait `timeoutMs` for the provider; AbortController still wins. */+export function fetchFor(timeoutMs) {+ const dispatcher = dispatcherFor(timeoutMs);+ return (url, init = {}) => undiciFetch(url, { ...init, dispatcher });+}diff --git a/api/package-lock.json b/api/package-lock.jsonindex 42010db9d..223065cd9 100644--- a/api/package-lock.json+++ b/api/package-lock.json@@ -1,15 +1,16 @@{"name": "gym-api",- "version": "1.2.4",+ "version": "1.2.11","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "gym-api",- "version": "1.2.4",+ "version": "1.2.11","license": "AGPL-3.0-or-later","dependencies": {"@simplewebauthn/server": "^13.1.1",+ "undici": "^7.29.0","web-push": "^3.6.7"},"optionalDependencies": {@@ -74,9 +75,6 @@"cpu": ["arm64"],- "libc": [- "glibc"- ],"license": "SEE LICENSE IN LICENSE.md","optional": true,"os": [@@ -90,9 +88,6 @@"cpu": ["arm64"],- "libc": [- "musl"- ],"license": "SEE LICENSE IN LICENSE.md","optional": true,"os": [@@ -106,9 +101,6 @@"cpu": ["x64"],- "libc": [- "glibc"- ],"license": "SEE LICENSE IN LICENSE.md","optional": true,"os": [@@ -122,9 +114,6 @@"cpu": ["x64"],- "libc": [- "musl"- ],"license": "SEE LICENSE IN LICENSE.md","optional": true,"os": [@@ -1856,6 +1845,14 @@"url": "https://opencollective.com/express"}},+ "node_modules/undici": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "engines": {+ "node": ">=20.18.1"+ }+ },"node_modules/unpipe": {"version": "1.0.0","resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",diff --git a/api/package.json b/api/package.jsonindex 09211dc5a..8e7f7d652 100644--- a/api/package.json+++ b/api/package.json@@ -11,6 +11,7 @@},"dependencies": {"@simplewebauthn/server": "^13.1.1",+ "undici": "^7.29.0","web-push": "^3.6.7"},"optionalDependencies": {diff --git a/api/test/node-fetch.test.js b/api/test/node-fetch.test.jsnew file mode 100644index 000000000..6d7e0554d--- /dev/null+++ b/api/test/node-fetch.test.js@@ -0,0 +1,42 @@+/* The server-side fetch must outlast undici's default 300-second headers timeout, or a local+ * model that needs six minutes fails as "could not reach" at five — which is exactly how the+ * first staging run died. Asserted with a server that answers slower than a short dispatcher+ * allows: undici's own limit fires, ours does not. */+import test from 'node:test';+import assert from 'node:assert/strict';+import http from 'node:http';+import { fetch as undiciFetch, Agent } from 'undici';++const { fetchFor, dispatcherFor } = await import('../coach/node-fetch.js');++function slowServer(delayMs) {+ const server = http.createServer((req, res) => setTimeout(() => { res.setHeader('content-type', 'application/json'); res.end('{"ok":true}'); }, delayMs));+ return new Promise(r => server.listen(0, '127.0.0.1', () => r({ url: `http://127.0.0.1:${server.address().port}/`, close: () => server.close() })));+}++test('the job fetch waits as long as the job timeout, where a short-headers dispatcher gives up', async () => {+ const s = await slowServer(2500);+ try {+ // A dispatcher with a 300 ms headers timeout is "undici's default, only smaller" — its timers+ // are second-granular, hence the 2.5 s server. The transport error is what the adapter+ // reports as "could not reach", which is the message the staging run died with.+ await assert.rejects(undiciFetch(s.url, { dispatcher: new Agent({ headersTimeout: 300, bodyTimeout: 300 }) }), /fetch failed/);+ const r = await fetchFor(60000)(s.url);+ assert.equal((await r.json()).ok, true);+ } finally { s.close(); }+});++test('the dispatcher budget follows the job timeout and never drops below a minute plus grace', () => {+ assert.ok(dispatcherFor(25 * 60000)._coachBudget >= 25 * 60000);+ assert.ok(dispatcherFor(1000)._coachBudget >= 60000);+ assert.equal(dispatcherFor(300000), dispatcherFor(300000), 'one agent per budget, not one per call');+});++test('an AbortController still wins over the transport budget', async () => {+ const s = await slowServer(1500);+ try {+ const ctl = new AbortController();+ setTimeout(() => ctl.abort(), 100);+ await assert.rejects(fetchFor(60000)(s.url, { signal: ctl.signal }), e => e.name === 'AbortError');+ } finally { s.close(); }+});