From c92cfc372aac344cb836d187c54fb77700f4622c Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Sat, 12 Sep 2026 13:15:02 +0200 Subject: [PATCH] =?UTF-8?q?sync:=20pushes=20are=20conditional=20on=20the?= =?UTF-8?q?=20revision=20this=20device=20last=20saw=20and=20a=20refused=20?= =?UTF-8?q?push=20merges=20both=20copies=20(lib/sync-merge.js=20=E2=80=94?= =?UTF-8?q?=20no=20workout,=20routine=20or=20weigh-in=20is=20dropped,=20th?= =?UTF-8?q?e=20newer=20copy=20decides=20settings);=20the=20store=20pulls?= =?UTF-8?q?=20when=20the=20tab,=20window,=20app=20or=20network=20comes=20b?= =?UTF-8?q?ack,=20one=20push=20and=20one=20pull=20at=20a=20time,=20and=20n?= =?UTF-8?q?othing=20pushes=20before=20boot=20has=20pulled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/lib/api.js | 3 +- frontend/src/lib/api.test.js | 13 + frontend/src/lib/mobile.js | 10 + frontend/src/lib/sync-merge.js | 88 +++++ frontend/src/lib/sync-merge.test.js | 133 ++++++++ frontend/src/store/useStore.js | 191 +++++++++-- frontend/src/store/useStore.restore.test.jsx | 24 +- frontend/src/store/useStore.sync.test.jsx | 326 +++++++++++++++++++ 8 files changed, 757 insertions(+), 31 deletions(-) create mode 100644 frontend/src/lib/sync-merge.js create mode 100644 frontend/src/lib/sync-merge.test.js create mode 100644 frontend/src/store/useStore.sync.test.jsx diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index ec1c3d8..dc15c65 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -20,7 +20,8 @@ export async function api(path, opts) { if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers })) const data = await r.json().catch(() => ({})) - if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e } + // The body rides along on the error: a 409 from /api/data carries the server's document. + if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; e.data = data; throw e } return data } diff --git a/frontend/src/lib/api.test.js b/frontend/src/lib/api.test.js index 53360dc..30618a7 100644 --- a/frontend/src/lib/api.test.js +++ b/frontend/src/lib/api.test.js @@ -33,3 +33,16 @@ describe('webauthnOK', () => { expect(webauthnOK()).toBe(false) }) }) + +describe('api()', () => { + it('a failed request throws with the status and the parsed body attached', async () => { + const { api } = await import('./api.js') + const original = globalThis.fetch + globalThis.fetch = async () => ({ ok: false, status: 409, json: async () => ({ error: 'conflict', rev: 3, state: { _rev: 3 } }) }) + try { + await expect(api('/api/data', { method: 'PUT', body: '{}' })).rejects.toMatchObject({ + message: 'conflict', status: 409, data: { error: 'conflict', rev: 3, state: { _rev: 3 } } + }) + } finally { globalThis.fetch = original } + }) +}) diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js index f2cc584..fa89aa5 100644 --- a/frontend/src/lib/mobile.js +++ b/frontend/src/lib/mobile.js @@ -163,6 +163,16 @@ export function initReminderSync(getState) { }).catch(() => {}) } +// Runs cb whenever the native shell returns to the foreground — the store pulls the account's +// state then, so a phone that sat in a pocket all afternoon shows what the desktop did. No-op +// off mobile; the store's own visibility/focus listeners cover the browser. +export function onAppActive(cb) { + if (!MOBILE) return + import('@capacitor/app').then(({ App }) => { + App.addListener('appStateChange', ({ isActive }) => { if (isActive) cb() }) + }).catch(() => {}) +} + // WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet // (Files, AirDrop, mail, …) from a temp file instead. export async function shareExport(json, filename) { diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js new file mode 100644 index 0000000..4ce2740 --- /dev/null +++ b/frontend/src/lib/sync-merge.js @@ -0,0 +1,88 @@ +/* Two copies of the account state, one merged copy. + * + * The server refuses a push over a document the device never saw (PUT /api/data with a stale + * `baseRev` answers 409 and hands back the current document). Before revisions the newer `_ts` + * simply replaced the other copy wholesale — which is exactly how a desktop tab that sat open + * all day dropped the workout the phone logged in the meantime. The merge keeps both sides' + * entries and lets the newer copy decide everything that has no natural union. + * + * Rules, by field: + * - scalars and settings, `week`, `dayPlan`, `wc`, `reminder`, …: from the copy with the newer `_ts` + * - workouts, routines, customEx, equipProfiles, gymCards: union by id, the newer copy's version + * of an id that both have; workouts sorted by day and start like every other writer + * - bodyweight: union by day, the later-edited (`t`) entry of a day that both have + * - favEx: ordered set union, the newer copy first + * - exWeights: union by exercise, the larger `w` (the app itself only ever raises it — a PR + * logged on the other device must not be forgotten); exNotes, barWeights: key union + * - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller + * + * Known limit: with no record of what each side deleted, an entry removed on one device inside + * the conflict window comes back from the other. The window is a few seconds now (the store pulls + * on resume and every push is conditional), and a resurrected entry beats a lost one. Tombstones + * would close it. + */ +const clone = o => JSON.parse(JSON.stringify(o)) +const list = v => (Array.isArray(v) ? v : []) + +/** The copy with the later `_ts`; on a tie the first argument (callers pass local first). */ +export const newerOf = (a, b) => ((b?._ts || 0) > (a?._ts || 0) ? b : a) + +/** + * Entries of `newer` in their order, then those of `older` whose key nothing in `newer` has. + * Same key → `newer`'s entry. Duplicate keys within one list are dropped (first wins). + */ +export function unionById(newer = [], older = [], key = x => x?.id) { + const seen = new Set() + const out = [] + for (const x of [...list(newer), ...list(older)]) { + const k = key(x) + if (k == null) { out.push(x); continue } + if (seen.has(k)) continue + seen.add(k) + out.push(x) + } + return out +} + +const workoutKey = w => (w?.id != null ? w.id : `${w?.d}|${w?.start}`) +const byDayStart = (a, b) => (a.d === b.d ? (a.start || 0) - (b.start || 0) : a.d < b.d ? -1 : 1) + +/** One entry per day; where both have a day, the one edited later (`t`); sorted by day. */ +export function mergeBodyweight(a = [], b = []) { + const byDay = new Map() + for (const e of [...list(a), ...list(b)]) { + if (!e || e.d == null) continue + const cur = byDay.get(e.d) + if (!cur || (e.t || 0) > (cur.t || 0)) byDay.set(e.d, e) + } + return [...byDay.values()].sort((x, y) => (x.d < y.d ? -1 : 1)) +} + +function mergeExWeights(n = {}, o = {}) { + const out = { ...(o || {}), ...(n || {}) } + for (const k of Object.keys(o || {})) { + if (n && n[k] && o[k] && (o[k].w || 0) > (n[k].w || 0)) out[k] = o[k] + } + return out +} + +export function mergeStates(a, b) { + if (!a) return b ? clone(b) : b + if (!b) return clone(a) + const n = newerOf(a, b) + const o = n === a ? b : a + const out = clone(n) + out.workouts = unionById(n.workouts, o.workouts, workoutKey).map(clone).sort(byDayStart) + for (const f of ['routines', 'customEx', 'equipProfiles', 'gymCards']) { + if (list(n[f]).length || list(o[f]).length) out[f] = unionById(n[f], o[f]).map(clone) + } + out.bodyweight = mergeBodyweight(n.bodyweight, o.bodyweight).map(clone) + if (list(n.favEx).length || list(o.favEx).length) out.favEx = [...new Set([...list(n.favEx), ...list(o.favEx)])] + out.exWeights = clone(mergeExWeights(n.exWeights, o.exWeights)) + for (const f of ['exNotes', 'barWeights']) { + if (n[f] || o[f]) out[f] = clone({ ...(o[f] || {}), ...(n[f] || {}) }) + } + out._ts = Math.max(a._ts || 0, b._ts || 0) + delete out._rev + return out +} diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.js new file mode 100644 index 0000000..608da77 --- /dev/null +++ b/frontend/src/lib/sync-merge.test.js @@ -0,0 +1,133 @@ +import { describe, expect, it } from 'vitest' +import { mergeBodyweight, mergeStates, newerOf, unionById } from './sync-merge.js' + +const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] }) +const routine = (id, name = id) => ({ id, name, ex: [] }) +const base = (over = {}) => ({ + unit: 'kg', restSec: 90, lang: 'en', week: { 1: ['r1'] }, dayPlan: {}, + workouts: [], routines: [], bodyweight: [], customEx: [], favEx: [], exWeights: {}, exNotes: {}, barWeights: {}, + equipProfiles: [], gymCards: [], _ts: 0, ...over +}) +const ids = xs => (xs || []).map(x => x.id) + +describe('newerOf / unionById / mergeBodyweight', () => { + it('picks the later _ts, first argument on a tie or missing stamps', () => { + const a = { _ts: 5 }, b = { _ts: 9 } + expect(newerOf(a, b)).toBe(b) + expect(newerOf(b, a)).toBe(b) + expect(newerOf({ _ts: 5 }, { _ts: 5 })).toEqual({ _ts: 5 }) + expect(newerOf({}, { })).toEqual({}) + }) + it('unions by id in the newer order, newer wins a shared id, dupes dropped', () => { + const out = unionById([routine('a', 'A2'), routine('b'), routine('b')], [routine('c'), routine('a', 'A1')]) + expect(ids(out)).toEqual(['a', 'b', 'c']) + expect(out[0].name).toBe('A2') + expect(unionById(undefined, null)).toEqual([]) + }) + it('bodyweight: one entry per day, the later-edited one, sorted', () => { + const out = mergeBodyweight([{ d: '2026-09-02', w: 80, t: 5 }], [{ d: '2026-09-01', w: 81, t: 1 }, { d: '2026-09-02', w: 79, t: 9 }]) + expect(out).toEqual([{ d: '2026-09-01', w: 81, t: 1 }, { d: '2026-09-02', w: 79, t: 9 }]) + }) +}) + +describe('mergeStates', () => { + const A = () => base({ + _ts: 200, restSec: 120, week: { 1: ['rA'] }, + workouts: [workout('w1'), workout('wA', '2026-09-03')], + routines: [routine('shared', 'from A'), routine('onlyA')], + bodyweight: [{ d: '2026-09-01', w: 80, t: 10 }], + customEx: [{ id: 'cA', name: 'A ex' }], favEx: ['x', 'y'], + exWeights: { sq: { w: 100 }, bp: { w: 60 } }, exNotes: { sq: 'A note' }, barWeights: { sq: 20 }, + gymCards: [{ id: 'g1', value: '1' }], _rev: 7 + }) + const B = () => base({ + _ts: 100, restSec: 60, week: { 1: ['rB'] }, + workouts: [workout('w1'), workout('wB', '2026-09-02')], + routines: [routine('shared', 'from B'), routine('onlyB')], + bodyweight: [{ d: '2026-09-01', w: 79, t: 20 }, { d: '2026-08-30', w: 82, t: 1 }], + customEx: [{ id: 'cB', name: 'B ex' }], favEx: ['y', 'z'], + exWeights: { sq: { w: 110 }, dl: { w: 140 } }, exNotes: { dl: 'B note' }, barWeights: { dl: 15 }, + gymCards: [{ id: 'g2', value: '2' }], _rev: 8 + }) + + it('no entity of either side disappears, ids stay unique', () => { + const m = mergeStates(A(), B()) + expect(ids(m.workouts).sort()).toEqual(['w1', 'wA', 'wB']) + expect(ids(m.routines).sort()).toEqual(['onlyA', 'onlyB', 'shared']) + expect(ids(m.customEx).sort()).toEqual(['cA', 'cB']) + expect(ids(m.gymCards).sort()).toEqual(['g1', 'g2']) + expect(m.bodyweight.map(b => b.d)).toEqual(['2026-08-30', '2026-09-01']) + expect(m.favEx).toEqual(['x', 'y', 'z']) + expect(new Set(ids(m.workouts)).size).toBe(m.workouts.length) + }) + + it('the newer copy decides settings, week, and a shared id; the other way round too', () => { + const m = mergeStates(A(), B()) + expect(m.restSec).toBe(120) + expect(m.week).toEqual({ 1: ['rA'] }) + expect(m.routines.find(r => r.id === 'shared').name).toBe('from A') + const m2 = mergeStates(B(), { ...A(), _ts: 50 }) + expect(m2.restSec).toBe(60) + expect(m2.week).toEqual({ 1: ['rB'] }) + expect(m2.routines.find(r => r.id === 'shared').name).toBe('from B') + }) + + it('bodyweight keeps the later-edited entry of a day, exWeights the larger weight, notes union', () => { + const m = mergeStates(A(), B()) + expect(m.bodyweight.find(b => b.d === '2026-09-01')).toEqual({ d: '2026-09-01', w: 79, t: 20 }) + expect(m.exWeights).toEqual({ sq: { w: 110 }, bp: { w: 60 }, dl: { w: 140 } }) + expect(m.exNotes).toEqual({ sq: 'A note', dl: 'B note' }) + expect(m.barWeights).toEqual({ sq: 20, dl: 15 }) + }) + + it('is commutative on the union fields and idempotent', () => { + const ab = mergeStates(A(), B()), ba = mergeStates(B(), A()) + for (const f of ['workouts', 'routines', 'customEx', 'gymCards']) expect(ids(ab[f]).sort()).toEqual(ids(ba[f]).sort()) + expect(ab.bodyweight).toEqual(ba.bodyweight) + expect([...ab.favEx].sort()).toEqual([...ba.favEx].sort()) + expect(ab.exWeights).toEqual(ba.exWeights) + const again = mergeStates(A(), ab) + expect(ids(again.workouts)).toEqual(ids(ab.workouts)) + expect(ids(again.routines)).toEqual(ids(ab.routines)) + expect(mergeStates(A(), A()).workouts).toEqual(A().workouts) + }) + + it('sorts workouts by day and start, takes the later _ts, drops _rev, does not touch inputs', () => { + const a = A(), b = B() + const m = mergeStates(a, b) + expect(m.workouts.map(w => w.d)).toEqual(['2026-09-01', '2026-09-02', '2026-09-03']) + expect(m._ts).toBe(200) + expect('_rev' in m).toBe(false) + expect(a).toEqual(A()) + expect(b).toEqual(B()) + m.workouts[0].entries.push('x') + expect(a.workouts[0].entries).toEqual([]) + }) + + it('tolerates a missing side and missing lists', () => { + expect(mergeStates(A(), null)).toEqual(A()) + expect(mergeStates(null, B())).toEqual(B()) + const sparse = { _ts: 5, workouts: null, routines: undefined } + const m = mergeStates(sparse, { _ts: 1, workouts: [workout('w')], bodyweight: undefined }) + expect(ids(m.workouts)).toEqual(['w']) + expect(m.bodyweight).toEqual([]) + }) + + it('a workout without an id is kept once by day and start', () => { + const legacy = { d: '2026-09-01', start: 5, entries: [] } + const m = mergeStates({ _ts: 2, workouts: [legacy] }, { _ts: 1, workouts: [{ ...legacy }, { d: '2026-09-01', start: 6, entries: [] }] }) + expect(m.workouts).toHaveLength(2) + }) + + // The report that started this: desktop adopted the server copy at T0, the phone logged a + // workout at T1, the desktop then changed one setting at T2 and pushed its whole document. + it('the desktop setting and the phone workout both survive', () => { + const t0 = base({ _ts: 1000, workouts: [workout('w1')], restSec: 90 }) + const server = { ...t0, _ts: 1001, workouts: [workout('w1'), workout('from-phone', '2026-09-05')], _rev: 4 } + const desktop = { ...t0, _ts: 1002, restSec: 75 } + const m = mergeStates(desktop, server) + expect(ids(m.workouts)).toEqual(['w1', 'from-phone']) + expect(m.restSec).toBe(75) + expect(m._ts).toBe(1002) + }) +}) diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index f38f35a..c8a3cd8 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -5,13 +5,20 @@ import { t } from '../lib/i18n.js' import { registerCustom } from '../lib/exercises.js' import { DEMO, DEMO_SEEDED } from '../lib/demo.js' import { guestAllowed } from '../lib/guest.js' -import { MOBILE, initReminderSync, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js' +import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, syncReminder, writeAutoBackup } from '../lib/mobile.js' +import { mergeStates } from '../lib/sync-merge.js' import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js' import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js' import { WC_DEFAULT } from '../lib/workout-controls.js' const KEY = 'gym_state_v1' +// Where this device stands with the server: the revision it last adopted or pushed, and its own +// `_ts` at that moment. `rev` goes back to the server as `baseRev` on every push, so a write over +// a document this device never saw is refused (409) instead of dropping another device's work; +// `ts` tells a pull whether anything changed here since. See pushState/pullState. +const SYNC_KEY = 'gym_sync' +const PULL_MIN_MS = 15000 // resume pulls closer together than this are noise, not news export const DEF = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en', theme: 'dark', accent: 'lime', body: 'male', targetW: null, @@ -94,6 +101,15 @@ export const useStore = create((set, get) => { let pushTm = null let saveTm = null let toldTooLarge = false + let pushing = null // the PUT in flight, so a second push waits for it instead of racing it + let pushAgain = false // a push asked for while one was in flight — run once more after it + let pulling = null // the GET in flight, so two resume signals make one request + let pushPending = false // a change made before boot's pull — pushed once boot is through + let forceNext = false // the next push replaces the server copy outright (import, reset) + let lastPull = 0 + + const readSync = () => { try { return JSON.parse(localStorage.getItem(SYNC_KEY)) || null } catch { return null } } + const writeSync = (rev, ts) => localStorage.setItem(SYNC_KEY, JSON.stringify({ rev, ts: ts || 0 })) initReminderSync(() => get().S) @@ -115,10 +131,90 @@ export const useStore = create((set, get) => { set({ S }) if (MOBILE) nativePersist() if (push && get().user) { + // Before boot has pulled, the copy in hand may be older than the server's: a push now + // would carry it with a stale (or no) baseRev. It waits for finishBoot. + if (!get().ready) { pushPending = true; return } clearTimeout(pushTm) pushTm = setTimeout(() => get().pushState(), 1500) } } + // Boot's last step: from here on changes push, and one made during boot goes now. + const finishBoot = (extra = {}) => { + set({ ready: true, ...extra }) + if (pushPending && get().user) { + clearTimeout(pushTm) + pushTm = setTimeout(() => get().pushState(), 1500) + } + pushPending = false + } + + // The other side of the hidden-tab flush below: coming back — to the tab, the window, the app, + // the network — asks the server what happened meanwhile. A phone that sat in a pocket all + // afternoon and a desktop tab left open all week used to show, and then push, whatever they + // last had; now they catch up first. Throttled, since focus and visibility fire together. + const resumePull = (force = false) => { + if (!get().user || !get().ready || document.visibilityState === 'hidden') return + if (!force && Date.now() - lastPull < PULL_MIN_MS) return + get().pullState() + } + document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') resumePull() }) + window.addEventListener('focus', () => resumePull()) + window.addEventListener('pageshow', e => { if (e.persisted) resumePull() }) + window.addEventListener('online', () => resumePull(true)) // also retries a push that failed offline + onAppActive(() => resumePull()) + + // Both copies changed: keep both sides' entries, let the newer copy decide the rest + // (lib/sync-merge.js), and remember the server's revision so the push that follows is + // conditional on exactly the document that was merged. The merged copy is stamped — it is a + // real change this device now holds — while `ts` in the marker stays old, so a pull that + // happens before the push lands still sees it as unsent. + const mergeInto = (local, remote, rev) => { + const merged = Object.assign(clone(DEF), mergeStates(local, remote)) + merged.active = local.active || null + persist(merged, false) + writeSync(rev, readSync()?.ts || 0) + } + // Take the server's copy as this device's own, timestamp and all (see persist). + const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts) } + + const doPush = async (attempt = 0) => { + const S = get().S + const sync = readSync() + const force = forceNext + const body = { state: S } + if (!force && sync) body.baseRev = sync.rev + try { + const r = await api('/api/data', { method: 'PUT', body: JSON.stringify(body) }) + if (force) forceNext = false + // A server from before revisions answers without one — then there is nothing to hold the + // next push to, and the marker must not pretend otherwise. + if (r.rev == null) localStorage.removeItem(SYNC_KEY) + else writeSync(r.rev, S._ts) + localStorage.removeItem('gym_dirty') + toldTooLarge = false + } catch (e) { + // A session that is gone is boot's business (/api/me); the copy stays owed to the server. + if (e.status === 401) { localStorage.setItem('gym_dirty', '1'); return } + if (e.status === 409 && e.data && attempt < 2) { + // Another device wrote since this one last read. The server sent its document along; + // merge and push once more against that revision. A second refusal in a row leaves the + // copy dirty and the next resume pull takes it from there. + mergeInto(get().S, e.data.state, e.data.rev || 0) + return doPush(attempt + 1) + } + localStorage.setItem('gym_dirty', '1') + // A 413 comes from the proxy in front of the API (nginx: client_max_body_size), which + // caps the request body. Every later push is at least as big, so nothing reaches the + // server until the limit is raised — said once per refusal streak; gym_dirty keeps the + // retries going. useUI imports this store, hence the lazy import. + if (e.status === 413 && !toldTooLarge) { + toldTooLarge = true + import('./useUI.js') + .then(({ useUI }) => useUI.getState().toast(t('Sync failed: the server refused the upload as too large. Your changes have not reached the server.'))) + .catch(() => {}) + } + } + } // A setting changed right before switching away/closing the tab must not get lost mid-debounce // (e.g. setting the reminder time then immediately backgrounding to test it). On mobile the @@ -161,6 +257,7 @@ export const useStore = create((set, get) => { get().setUser(null) localStorage.removeItem('gym_guest') localStorage.removeItem('gym_dirty') + localStorage.removeItem(SYNC_KEY) localStorage.removeItem(KEY) persist(clone(DEF), false) localStorage.removeItem('gym_owner') @@ -189,7 +286,9 @@ export const useStore = create((set, get) => { mut(S) persist(S, push) }, - replaceState(S, push = false) { persist(clone(S), push) }, + // A replace that is meant to reach the server (backup import, reset) is a deliberate + // overwrite, not a change to merge: the push it arms goes without a baseRev. + replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) }, // Fires after the moments where losing local data would actually hurt — a workout just // logged, a routine just edited — not on every keystroke. No-op off mobile or with the @@ -227,6 +326,7 @@ export const useStore = create((set, get) => { const owner = localStorage.getItem('gym_owner') if (owner && owner !== u.id) { localStorage.removeItem('gym_dirty') + localStorage.removeItem(SYNC_KEY) localStorage.removeItem(KEY) persist(clone(DEF), false) } @@ -236,34 +336,67 @@ export const useStore = create((set, get) => { set({ user: u }) }, + // One PUT at a time: a push asked for while one is in flight runs after it (once, however + // many asked), and the promise returned covers that follow-up too, so a caller that awaits + // before signing out knows the last change is on the server. async pushState() { if (!get().user) return clearTimeout(pushTm) - try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty'); toldTooLarge = false } - catch (e) { - localStorage.setItem('gym_dirty', '1') - // A 413 comes from the proxy in front of the API (nginx: client_max_body_size), which - // caps the request body. Every later push is at least as big, so nothing reaches the - // server until the limit is raised — said once per refusal streak; gym_dirty keeps the - // retries going. useUI imports this store, hence the lazy import. - if (e.status === 413 && !toldTooLarge) { - toldTooLarge = true - import('./useUI.js') - .then(({ useUI }) => useUI.getState().toast(t('Sync failed: the server refused the upload as too large. Your changes have not reached the server.'))) - .catch(() => {}) - } - } + pushTm = null + if (pushing) { pushAgain = true; return pushing.then(() => pushing) } + pushing = doPush().finally(() => { + pushing = null + if (pushAgain) { pushAgain = false; get().pushState() } + }) + return pushing }, + // Ask the server for its copy and settle the difference. Coalesced, and a push still waiting + // in the debounce goes first — the server's answer is then the one that already includes it, + // and the push itself is what catches a conflict. async pullState() { - try { - const { state } = await api('/api/data') - const S = get().S - const dirty = localStorage.getItem('gym_dirty') === '1' - const restored = restoredStateFor(S, state, dirty) - if (restored) { - persist(restored, false, false) - } else if (hasData(S)) { await get().pushState() } - } catch (e) { /* offline — keep local */ } + if (pulling) return pulling + pulling = (async () => { + try { + if (pushTm) { clearTimeout(pushTm); pushTm = null; await get().pushState() } + else if (pushing) await pushing + const res = await api('/api/data') + lastPull = Date.now() + const { state, rev } = res + const S = get().S + // Owed to the server: a push that failed, or a change made while boot was still pulling. + const dirty = localStorage.getItem('gym_dirty') === '1' || pushPending + const sync = readSync() + // A server from before revisions: the old rule, newer `_ts` wins outright. + if (rev == null) { + localStorage.removeItem(SYNC_KEY) + const restored = restoredStateFor(S, state, dirty) + if (restored) persist(restored, false, false) + else if (hasData(S)) await get().pushState() + return + } + // No marker yet — first pull on this device, or a client that just learned about + // revisions. The newer copy wins as before, except that a copy still owed to the + // server (dirty) is merged instead of pushed over whatever is there. + if (!sync) { + if (dirty && state) { mergeInto(S, state, rev); pushPending = false; await get().pushState(); return } + const restored = restoredStateFor(S, state, false) + if (restored) adopt(restored, rev) + else if (hasData(S)) { writeSync(rev, 0); await get().pushState() } + else writeSync(rev, state?._ts || 0) + return + } + const serverMoved = rev !== sync.rev + const localChanged = dirty || (S._ts || 0) > (sync.ts || 0) + if (!serverMoved) { if (localChanged) await get().pushState(); return } + if (!state) { writeSync(rev, 0); if (hasData(S)) await get().pushState(); return } + if (!localChanged) { adopt(Object.assign(clone(DEF), state, { active: S.active || null }), rev); return } + mergeInto(S, state, rev) + pushPending = false + await get().pushState() + } catch (e) { /* offline — keep local */ } + finally { pulling = null } + })() + return pulling }, async signOut() { @@ -340,7 +473,7 @@ export const useStore = create((set, get) => { else get().setUser(remote.user) // offline — keep going from the last-synced local copy } syncReminder(get().S) - set({ ready: true }) + finishBoot() return } const saved = await nativeLoad() @@ -355,7 +488,7 @@ export const useStore = create((set, get) => { // Only a genuinely first launch — nothing chosen yet and nothing to lose either — offers // the choice. Picking local (even with no data yet) persists that choice below and this // never asks again. - set({ ready: true, needsMobileOnboarding: !remote && !hasData(get().S) }) + finishBoot({ needsMobileOnboarding: !remote && !hasData(get().S) }) return } // Demo build (GitHub Pages): no backend at all — seed once, stay in guest mode. @@ -365,7 +498,7 @@ export const useStore = create((set, get) => { await get().resetDemo() } get().setGuest(true) - set({ ready: true }) + finishBoot() return } // Guests never authenticate, so an instance that turned guest mode off has no request to @@ -387,7 +520,7 @@ export const useStore = create((set, get) => { } catch (e) { if (e.status === 401) get().setUser(null) } - set({ ready: true }) + finishBoot() } } }) diff --git a/frontend/src/store/useStore.restore.test.jsx b/frontend/src/store/useStore.restore.test.jsx index 149ac48..abf28a2 100644 --- a/frontend/src/store/useStore.restore.test.jsx +++ b/frontend/src/store/useStore.restore.test.jsx @@ -75,7 +75,29 @@ describe('saved workout state sync and restore', () => { expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local']) }) - it('pushes local data instead of overwriting a dirty local state', async () => { + // A dirty copy is one the server has not seen yet — not one that outranks the server's. With a + // revision in the answer the two are merged and the merge is pushed against that revision. + it('merges a dirty local state with the server copy and pushes the merge', async () => { + const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] } + const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')], _rev: 3 } + localStorage.setItem('gym_dirty', '1') + useStore.setState({ S: local, user: { id: 'user-1' }, ready: true }) + api.mockResolvedValueOnce({ state: remote, rev: 3 }).mockResolvedValueOnce({ ok: true, rev: 4 }) + + await useStore.getState().pullState() + + expect(api).toHaveBeenCalledTimes(2) + const put = JSON.parse(api.mock.calls[1][1].body) + expect(put.baseRev).toBe(3) + expect(put.state.routines.map(r => r.id).sort()).toEqual(['local', 'remote']) + expect(useStore.getState().S.routines.map(r => r.id).sort()).toEqual(['local', 'remote']) + expect(localStorage.getItem('gym_dirty')).toBeNull() + expect(JSON.parse(localStorage.getItem('gym_sync'))).toEqual({ rev: 4, ts: useStore.getState().S._ts }) + }) + + // A server from before revisions answers without one; then the old rule holds and the dirty + // copy is pushed as it is. + it('pushes a dirty local state as-is to a server without revisions', async () => { const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] } const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')] } localStorage.setItem('gym_dirty', '1') diff --git a/frontend/src/store/useStore.sync.test.jsx b/frontend/src/store/useStore.sync.test.jsx new file mode 100644 index 0000000..b3c2a42 --- /dev/null +++ b/frontend/src/store/useStore.sync.test.jsx @@ -0,0 +1,326 @@ +// @vitest-environment happy-dom + +/* Two devices, one account: the server refuses a push over a document this device never saw + (409 with the current copy), the store merges and pushes again; a pull adopts, pushes or + merges by comparing the server revision and its own marker; nothing pushes before boot has + pulled; coming back to the tab pulls. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../lib/api.js', () => ({ api: vi.fn() })) +const { toast } = vi.hoisted(() => ({ toast: vi.fn() })) +vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } })) + +import { api } from '../lib/api.js' +import { DEF, useStore } from './useStore.js' + +const clone = value => JSON.parse(JSON.stringify(value)) +const routine = id => ({ id, name: id, ex: [] }) +const workout = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] }) +const httpError = (status, data) => Object.assign(new Error(data?.error || 'HTTP ' + status), { status, data }) +const sync = () => JSON.parse(localStorage.getItem('gym_sync')) +const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body)) +const gets = () => api.mock.calls.filter(([, o]) => !o) +const signedIn = (S, extra = {}) => useStore.setState({ S, user: { id: 'user-1' }, ready: true, ...extra }) + +beforeEach(() => { + localStorage.clear() + api.mockReset() + useStore.setState({ S: clone(DEF), user: null, ready: false }) +}) +afterEach(() => { + vi.useRealTimers() + localStorage.clear() + useStore.setState({ S: clone(DEF), user: null, ready: false }) +}) + +describe('pull against a revisioned server', () => { + it('adopts the server copy when only the server moved, and records its revision', async () => { + const local = { ...clone(DEF), _ts: 100, workouts: [workout('w1')], active: { id: 'running' } } + signedIn(local) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('w2')], _rev: 2 }, rev: 2 }) + + await useStore.getState().pullState() + + expect(puts()).toHaveLength(0) + expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2']) + expect(useStore.getState().S._ts).toBe(200) + expect(useStore.getState().S.active).toEqual({ id: 'running' }) + expect(sync()).toEqual({ rev: 2, ts: 200 }) + }) + + it('does nothing when neither side moved', async () => { + signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 100, workouts: [workout('w1')], _rev: 1 }, rev: 1 }) + + await useStore.getState().pullState() + + expect(api).toHaveBeenCalledTimes(1) + expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1']) + }) + + it('pushes when only this device changed', async () => { + signedIn({ ...clone(DEF), _ts: 150, workouts: [workout('w1')], restSec: 75 }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 100, workouts: [workout('w1')], _rev: 1 }, rev: 1 }) + api.mockResolvedValueOnce({ ok: true, rev: 2 }) + + await useStore.getState().pullState() + + expect(puts()).toHaveLength(1) + expect(puts()[0].baseRev).toBe(1) + expect(puts()[0].state.restSec).toBe(75) + expect(sync()).toEqual({ rev: 2, ts: 150 }) + }) + + // The report: desktop adopted rev 1, the phone logged a workout (rev 2), the desktop changed a + // setting. One PUT, against rev 2, carrying both. + it('merges and pushes once against the server revision when both sides changed', async () => { + signedIn({ ...clone(DEF), _ts: 300, workouts: [workout('w1')], restSec: 75 }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('from-phone', '2026-09-02')], _rev: 2 }, rev: 2 }) + api.mockResolvedValueOnce({ ok: true, rev: 3 }) + + await useStore.getState().pullState() + + expect(gets()).toHaveLength(1) + expect(puts()).toHaveLength(1) + expect(puts()[0].baseRev).toBe(2) + expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w1', 'from-phone']) + expect(puts()[0].state.restSec).toBe(75) + expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'from-phone']) + expect(sync().rev).toBe(3) + expect(sync().ts).toBe(useStore.getState().S._ts) + expect(localStorage.getItem('gym_dirty')).toBeNull() + }) + + it('a first pull with a newer server copy adopts it and starts the marker', async () => { + signedIn(clone(DEF)) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 50, routines: [routine('r')], _rev: 5 }, rev: 5 }) + + await useStore.getState().pullState() + + expect(puts()).toHaveLength(0) + expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['r']) + expect(sync()).toEqual({ rev: 5, ts: 50 }) + }) + + it('a first pull with a newer local copy pushes it against the server revision', async () => { + signedIn({ ...clone(DEF), _ts: 500, routines: [routine('local')] }) + api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 50, routines: [routine('remote')], _rev: 5 }, rev: 5 }) + api.mockResolvedValueOnce({ ok: true, rev: 6 }) + + await useStore.getState().pullState() + + expect(puts()).toHaveLength(1) + expect(puts()[0].baseRev).toBe(5) + expect(sync()).toEqual({ rev: 6, ts: 500 }) + }) + + it('a 401 on pull leaves the copy, the marker and the user alone', async () => { + signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockRejectedValueOnce(httpError(401, { error: 'not signed in' })) + + await useStore.getState().pullState() + + expect(useStore.getState().user).toEqual({ id: 'user-1' }) + expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1']) + expect(sync()).toEqual({ rev: 1, ts: 100 }) + expect(localStorage.getItem('gym_dirty')).toBeNull() + }) +}) + +describe('push against a revisioned server', () => { + it('sends the marker revision as baseRev and records the one it gets back', async () => { + signedIn({ ...clone(DEF), _ts: 120, routines: [routine('r')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 4, ts: 100 })) + api.mockResolvedValueOnce({ ok: true, rev: 5 }) + + await useStore.getState().pushState() + + expect(puts()[0].baseRev).toBe(4) + expect(sync()).toEqual({ rev: 5, ts: 120 }) + }) + + it('a 409 merges the server copy it carries and pushes again against that revision', async () => { + signedIn({ ...clone(DEF), _ts: 300, workouts: [workout('w1')], restSec: 75 }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockRejectedValueOnce(httpError(409, { error: 'conflict', rev: 2, state: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('w2')], _rev: 2 } })) + api.mockResolvedValueOnce({ ok: true, rev: 3 }) + + await useStore.getState().pushState() + + expect(puts()).toHaveLength(2) + expect(puts()[0].baseRev).toBe(1) + expect(puts()[1].baseRev).toBe(2) + expect(puts()[1].state.workouts.map(w => w.id)).toEqual(['w1', 'w2']) + expect(puts()[1].state.restSec).toBe(75) + expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2']) + expect(sync().rev).toBe(3) + expect(localStorage.getItem('gym_dirty')).toBeNull() + }) + + it('gives up after two conflicts in a row and leaves the copy dirty for the next pull', async () => { + signedIn({ ...clone(DEF), _ts: 300, workouts: [workout('w1')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + const conflict = rev => httpError(409, { error: 'conflict', rev, state: { ...clone(DEF), _ts: 200, workouts: [workout('w' + rev)], _rev: rev } }) + api.mockRejectedValueOnce(conflict(2)).mockRejectedValueOnce(conflict(3)).mockRejectedValueOnce(conflict(4)) + + await useStore.getState().pushState() + + expect(puts()).toHaveLength(3) + expect(localStorage.getItem('gym_dirty')).toBe('1') + expect(useStore.getState().S.workouts.map(w => w.id).sort()).toEqual(['w1', 'w2', 'w3']) + }) + + it('a replace meant for the server goes without a baseRev, the change after it with one', async () => { + vi.useFakeTimers() + signedIn({ ...clone(DEF), _ts: 100, routines: [routine('old')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 4, ts: 100 })) + api.mockResolvedValueOnce({ ok: true, rev: 5 }).mockResolvedValueOnce({ ok: true, rev: 6 }) + + useStore.getState().replaceState({ ...clone(DEF), routines: [routine('imported')] }, true) + await vi.advanceTimersByTimeAsync(2000) + expect(puts()).toHaveLength(1) + expect('baseRev' in puts()[0]).toBe(false) + expect(sync().rev).toBe(5) + + useStore.getState().update(s => { s.restSec = 45 }) + await vi.advanceTimersByTimeAsync(2000) + expect(puts()).toHaveLength(2) + expect(puts()[1].baseRev).toBe(5) + }) + + it('a push asked for during a push runs once after it, and the caller waits for it', async () => { + signedIn({ ...clone(DEF), _ts: 100, routines: [routine('r')] }) + let release + api.mockImplementationOnce(() => new Promise(r => { release = () => r({ ok: true, rev: 1 }) })) + api.mockResolvedValue({ ok: true, rev: 2 }) + + const first = useStore.getState().pushState() + useStore.getState().update(s => { s.restSec = 30 }, false) + const second = useStore.getState().pushState() + const third = useStore.getState().pushState() + expect(puts()).toHaveLength(1) + release() + await Promise.all([first, second, third]) + + expect(puts()).toHaveLength(2) + expect(puts()[1].state.restSec).toBe(30) + expect(sync().rev).toBe(2) + }) + + it('a server without revisions drops the marker', async () => { + signedIn({ ...clone(DEF), _ts: 100, routines: [routine('r')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 4, ts: 100 })) + api.mockResolvedValueOnce({ ok: true }) + + await useStore.getState().pushState() + + expect(localStorage.getItem('gym_sync')).toBeNull() + }) +}) + +describe('ordering', () => { + it('a change made before boot is through does not push until it is', async () => { + vi.useFakeTimers() + useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: false }) + api.mockResolvedValue({ ok: true, rev: 1 }) + + useStore.getState().update(s => { s.restSec = 30 }) + await vi.advanceTimersByTimeAsync(5000) + expect(puts()).toHaveLength(0) + + // what boot does last, on every path + useStore.setState({ ready: true }) + useStore.getState().update(s => { s.restSec = 45 }) + await vi.advanceTimersByTimeAsync(2000) + expect(puts()).toHaveLength(1) + expect(puts()[0].state.restSec).toBe(45) + }) + + // The change lands while the server copy is still on its way: it is merged into that copy + // rather than overwritten by it, and the merge is what boot pushes. + it('boot keeps a change made during its pull and pushes the merge', async () => { + vi.useFakeTimers() + useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: false }) + localStorage.setItem('gym_user', JSON.stringify({ id: 'user-1' })) + api.mockImplementation(async (path, opts) => { + if (path === '/api/config') return { allow_guest: true } + if (path === '/api/me') return { user: { id: 'user-1', name: 'One' } } + if (path === '/api/data' && !opts) { + useStore.getState().update(s => { s.restSec = 30 }) // a change while the pull is in flight + return { state: { ...clone(DEF), _ts: 10, routines: [routine('r')], _rev: 1 }, rev: 1 } + } + return { ok: true, rev: 2 } + }) + + const boot = useStore.getState().boot() + await vi.advanceTimersByTimeAsync(10) + await boot + await vi.advanceTimersByTimeAsync(2000) + + expect(puts()).toHaveLength(1) + expect(puts()[0].baseRev).toBe(1) + expect(puts()[0].state.restSec).toBe(30) + expect(puts()[0].state.routines.map(r => r.id)).toEqual(['r']) + expect(useStore.getState().S.restSec).toBe(30) + expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['r']) + expect(useStore.getState().ready).toBe(true) + }) + + it('a pull sends a push still waiting in the debounce first', async () => { + vi.useFakeTimers() + signedIn({ ...clone(DEF), _ts: 100, routines: [routine('r')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockImplementation(async (path, opts) => opts ? { ok: true, rev: 2 } : { state: { ...clone(DEF), _ts: 100, routines: [routine('r')], _rev: 2 }, rev: 2 }) + + useStore.getState().update(s => { s.restSec = 30 }) // arms the 1.5 s push + const pull = useStore.getState().pullState() + await vi.advanceTimersByTimeAsync(10) + await pull + + expect(api.mock.calls[0][1]?.method).toBe('PUT') + expect(api.mock.calls[1][1]).toBeUndefined() + expect(puts()).toHaveLength(1) + expect(sync().rev).toBe(2) + }) + + it('coming back to the tab pulls, not twice within 15 s, and going online always does', async () => { + vi.useFakeTimers() + signedIn({ ...clone(DEF), _ts: 100, routines: [routine('r')] }) + localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 })) + api.mockResolvedValue({ state: { ...clone(DEF), _ts: 100, routines: [routine('r')], _rev: 1 }, rev: 1 }) + const visible = () => { + Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' }) + document.dispatchEvent(new Event('visibilitychange')) + } + + await vi.advanceTimersByTimeAsync(16000) // clear of any pull an earlier test made + visible() + await vi.advanceTimersByTimeAsync(10) + expect(gets()).toHaveLength(1) + + window.dispatchEvent(new Event('focus')) + visible() + await vi.advanceTimersByTimeAsync(10) + expect(gets()).toHaveLength(1) + + window.dispatchEvent(new Event('online')) + await vi.advanceTimersByTimeAsync(10) + expect(gets()).toHaveLength(2) + + await vi.advanceTimersByTimeAsync(16000) + window.dispatchEvent(new Event('focus')) + await vi.advanceTimersByTimeAsync(10) + expect(gets()).toHaveLength(3) + + useStore.setState({ user: null }) + await vi.advanceTimersByTimeAsync(16000) + window.dispatchEvent(new Event('focus')) + await vi.advanceTimersByTimeAsync(10) + expect(gets()).toHaveLength(3) + }) +})