sync: pushes are conditional on the revision this device last saw and a refused push merges both copies (lib/sync-merge.js — no workout, routine or weigh-in is dropped, the newer copy decides settings); the store pulls when the tab, window, app or network comes back, one push and one pull at a time, and nothing pushes before boot has pulled

This commit is contained in:
Duarte Santos committed 2026-09-12 13:15:48 +02:00
1 parent 5276f9714a
commit c92cfc372a
8 files changed
+757 -31

No files matched your search

+2 -1
View File
@@ -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
}
+13
View File
@@ -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 }
})
})
+10
View File
@@ -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) {
+88
View File
@@ -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
}
+133
View File
@@ -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)
})
})