api: /api/data carries a server revision — GET hands it out, a PUT with a stale baseRev answers 409 with the current document instead of overwriting another device's write; clients without baseRev keep overwriting as before

This commit is contained in:
Duarte Santos committed 2026-09-12 13:15:48 +02:00
1 parent d58a98e768
commit 5276f9714a
3 files changed
+177 -9

No files matched your search

+46 -4
View File
@@ -474,11 +474,13 @@ paths:
summary: Pull the account's app state
description: >-
Returns the caller's entire app state as one JSON blob, or `{"state": null}`
if nothing has been synced yet. Sync conflict resolution happens client-side
(last-writer-wins by the client-set `_ts` timestamp).
if nothing has been synced yet, together with `rev`, the server's revision of
that document (0 when there is none). A client keeps the `rev` it last read or
wrote and sends it back as `baseRev` on the next push, which lets the server
refuse a write over a document the client never saw (see the 409 on PUT).
responses:
'200':
description: The stored state, or null.
description: The stored state, or null, and its revision.
content:
application/json:
schema:
@@ -488,6 +490,9 @@ paths:
oneOf:
- $ref: '#/components/schemas/State'
- type: 'null'
rev:
type: integer
description: Server revision of the stored document; 0 when there is none.
'401': { $ref: '#/components/responses/Unauthorized' }
put:
tags: [data]
@@ -497,6 +502,14 @@ paths:
Replaces the stored state wholesale (atomic write; there is no merge on the
server). The `active` field — an in-progress workout — is stripped before
saving: a running session belongs to the device running it. Body limit 5 MiB.
With `baseRev` the write is conditional: it goes through only when `baseRev`
equals the document's current revision, and answers 409 with the current
document otherwise — the client merges the two and pushes again with the
revision it was given. Without `baseRev` the write is unconditional (clients
from before revisions, and deliberate replaces such as a backup import). The
server stamps the new revision into the document as `_rev`; a `_rev` sent by
the client is ignored.
requestBody:
required: true
content:
@@ -506,6 +519,11 @@ paths:
required: [state]
properties:
state: { $ref: '#/components/schemas/State' }
baseRev:
oneOf: [{ type: integer }, { type: 'null' }]
description: >-
The revision this client last read or wrote. Omit or null for an
unconditional overwrite.
responses:
'200':
description: Saved.
@@ -518,6 +536,24 @@ paths:
ts:
oneOf: [{ type: number }, { type: 'null' }]
description: Echo of the pushed state's `_ts`, if present.
rev:
type: integer
description: The revision the write produced.
'409':
description: >-
`baseRev` is not the current revision — another client wrote since this one
last read. Carries the current document so the client can merge and retry.
content:
application/json:
schema:
type: object
properties:
error: { type: string, const: conflict }
rev: { type: integer }
state:
oneOf:
- $ref: '#/components/schemas/State'
- type: 'null'
'400':
description: >-
`state` missing or not an object, or `workouts`/`routines` set to anything
@@ -1142,11 +1178,17 @@ components:
strips `active` on save and reads a few fields for reminders and the admin
dashboard) — the schema below is **representative, not enforced** (except
`workouts` and `routines`, which must be arrays (or null) when present), and grows
with the app. Conflict resolution is client-side via `_ts`.
with the app. Concurrent writes are caught by the server's revision (`_rev`,
see PUT /api/data); the client merges the two documents and decides by `_ts`
which side's settings win.
properties:
_ts:
type: number
description: Client-set last-write timestamp (ms since epoch); drives sync.
_rev:
type: integer
readOnly: true
description: Server-set revision, incremented on every accepted PUT. Ignored when sent by a client.
unit: { type: string, enum: [kg, lb] }
lang:
type: string
+19 -5
View File
@@ -797,13 +797,14 @@ const routes = {
json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } });
},
// `rev` is the server's own count of writes to this profile (also stored inside the document as
// `_rev`, so every other reader of the file — reminder tick, admin, Coach, MCP — is unaffected).
// A client pushes it back as `baseRev`, and a write over a document it never saw is refused.
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
try {
const state = JSON.parse(fs.readFileSync(stateFile(user.id), 'utf8'));
json(res, 200, { state });
} catch { json(res, 200, { state: null }); }
const state = readState(user.id);
json(res, 200, { state, rev: state?._rev || 0 });
},
'PUT /api/data': async (req, res) => {
@@ -816,9 +817,22 @@ const routes = {
// fine — every client fills its own defaults.
const list = v => v == null || Array.isArray(v);
if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
// Conditional write: a `baseRev` that is not the current revision means this client last
// read an older document — another device has written since — and the copy it is about to
// push would silently drop that write. The current document travels back with the 409, so
// the client can merge and try again without a second request. No `baseRev` (a client from
// before revisions, or a deliberate replace such as a backup import) overwrites, as before.
// readState and atomicWrite are synchronous with nothing awaited between them, so the
// compare-and-write is atomic for this process.
const cur = readState(user.id);
const curRev = cur?._rev || 0;
if (body.baseRev != null && body.baseRev !== curRev) {
return json(res, 409, { error: 'conflict', rev: curRev, state: cur });
}
delete body.state.active; // in-progress workouts stay device-local
body.state._rev = curRev + 1; // server-owned; whatever the client sent is ignored
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
json(res, 200, { ok: true, ts: body.state._ts || null });
json(res, 200, { ok: true, ts: body.state._ts || null, rev: body.state._rev });
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
+112
View File
@@ -0,0 +1,112 @@
/* /api/data carries a server revision: GET hands it out, PUT with `baseRev` is refused (409, with
the current document) when another write landed in between, PUT without `baseRev` overwrites
as clients from before revisions always did. Real server.js in a child. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
function mintSession(uid, sv = 0) {
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const headers = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json' });
const freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-rev-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_rev_1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []
}));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
test('GET/PUT /api/data: revisions, conditional writes and the legacy overwrite', async t => {
const h = await startServer(t);
const uid = 'u_rev_1';
const get = async () => { const r = await fetch(`${h.api}/api/data`, { headers: headers(uid) }); return { status: r.status, body: await r.json() }; };
const put = async body => { const r = await fetch(`${h.api}/api/data`, { method: 'PUT', headers: headers(uid), body: JSON.stringify(body) }); return { status: r.status, body: await r.json() }; };
const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${uid}.json`), 'utf8'));
// nothing synced yet
let r = await get();
assert.equal(r.status, 200);
assert.deepEqual(r.body, { state: null, rev: 0 });
// first write against rev 0
r = await put({ state: { _ts: 100, workouts: [{ id: 'w1', d: '2026-09-01' }], routines: [], active: { id: 'running' } }, baseRev: 0 });
assert.equal(r.status, 200);
assert.equal(r.body.ok, true);
assert.equal(r.body.rev, 1);
assert.equal(r.body.ts, 100);
assert.equal(onDisk()._rev, 1);
assert.equal('active' in onDisk(), false, 'active is stripped');
r = await get();
assert.equal(r.body.rev, 1);
assert.equal(r.body.state._rev, 1);
assert.deepEqual(r.body.state.workouts.map(w => w.id), ['w1']);
// the same baseRev again — someone else already wrote rev 1 — is a conflict, and the current
// document comes back with it
r = await put({ state: { _ts: 200, workouts: [], routines: [] }, baseRev: 0 });
assert.equal(r.status, 409);
assert.equal(r.body.error, 'conflict');
assert.equal(r.body.rev, 1);
assert.deepEqual(r.body.state.workouts.map(w => w.id), ['w1']);
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w1'], 'a refused write changes nothing');
// a client from before revisions sends no baseRev and overwrites, as it always did
r = await put({ state: { _ts: 300, workouts: [{ id: 'w2', d: '2026-09-02' }], routines: [] } });
assert.equal(r.status, 200);
assert.equal(r.body.rev, 2);
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w2']);
// a matching baseRev goes through; a client-supplied _rev is ignored
r = await put({ state: { _ts: 400, _rev: 99, workouts: [{ id: 'w3', d: '2026-09-03' }], routines: [] }, baseRev: 2 });
assert.equal(r.status, 200);
assert.equal(r.body.rev, 3);
assert.equal(onDisk()._rev, 3);
// an explicit null is "no baseRev", not "rev null"
r = await put({ state: { _ts: 500, workouts: [], routines: [] }, baseRev: null });
assert.equal(r.status, 200);
assert.equal(r.body.rev, 4);
// a baseRev that is a string never matches (no coercion)
r = await put({ state: { _ts: 600, workouts: [], routines: [] }, baseRev: '4' });
assert.equal(r.status, 409);
// the shape check still comes first
r = await put({ state: { workouts: 'nope' }, baseRev: 4 });
assert.equal(r.status, 400);
assert.equal(r.body.error, 'invalid state');
assert.equal(onDisk()._rev, 4);
});