diff --git a/app/native.test.js b/app/native.test.js index 7c7e16e..e180f4a 100644 --- a/app/native.test.js +++ b/app/native.test.js @@ -8,6 +8,7 @@ import assert from 'node:assert/strict' import { readFileSync, readdirSync, statSync } from 'node:fs' import { join } from 'node:path' import { keyboardEvents, showFoot, canSwipe, showActs } from '../mobile/src/ui/sheetPolicy.ts' +import { pullRefresh, wantsPull, FRESH_MS } from '../mobile/src/shell/pullRefresh.ts' const ROOT = new URL('../mobile/src/', import.meta.url).pathname const read = (f) => readFileSync(join(ROOT, f), 'utf8') @@ -88,6 +89,74 @@ test('the coach is gone from the dock too (#31, F F8)', () => { if (/coach/i.test(read('lib/foreground.ts'))) throw new Error('foreground.ts still names a coach provider') }) +/* + * Pull down on a tab: the log syncs AND WHOOP and Strava are pulled. + * Their GETs only serve the server's cache, so without a pull the ride that + * just synced showed up one refresh late. + */ +const NOW = Date.parse('2026-11-11T12:00:00Z') +const ago = (ms) => new Date(NOW - ms).toISOString() +const calls = () => { + const log = [] + const later = (name, ms = 0, value) => () => new Promise(r => setTimeout(() => { log.push(name); r(value) }, ms)) + const svc = (name, cache, pull = later(name)) => ({ cache, pull }) + const base = { refresh: later('log', 0, true), reloadPlan: () => log.push('plan'), now: NOW } + return { log, later, svc, base } +} +const on = (fetchedAt = ago(10 * 60_000)) => ({ configured: true, fetchedAt }) + +test('pull to refresh pulls WHOOP and Strava along with the log', async () => { + const { log, svc, base } = calls() + await pullRefresh({ ...base, whoop: svc('whoop', on()), strava: svc('strava', on(null)) }) + assert.deepEqual([...log].sort(), ['log', 'plan', 'strava', 'whoop'], 'a cache never fetched is pulled too') +}) + +test('pull to refresh never pulls a service its cache says is not connected', async () => { + const { log, svc, base } = calls() + await pullRefresh({ ...base, whoop: svc('whoop', { configured: false, fetchedAt: null }), strava: svc('strava', null) }) + assert.deepEqual([...log].sort(), ['log', 'plan'], 'not connected, or no answer yet: only the log') +}) + +test('pull to refresh leaves a copy fetched in the last minute alone', async () => { + const { log, svc, base } = calls() + await pullRefresh({ ...base, whoop: svc('whoop', on(ago(FRESH_MS - 1000))), strava: svc('strava', on(ago(FRESH_MS + 1000))) }) + assert.deepEqual([...log].sort(), ['log', 'plan', 'strava']) + assert.equal(wantsPull(on('not a date'), NOW), true, 'an unreadable fetchedAt is not fresh') +}) + +test('offline, the log is retried and the services are not touched', async () => { + const { log, later, svc, base } = calls() + await pullRefresh({ ...base, refresh: later('log', 0, false), whoop: svc('whoop', on()), strava: svc('strava', on()) }) + assert.deepEqual(log, ['plan', 'log'], 'an offline pull would leave a network error on every block') + log.length = 0 + await pullRefresh({ ...base, refresh: () => Promise.reject(new Error('offline')), whoop: svc('whoop', on()), strava: svc('strava', on()) }) + assert.deepEqual(log, ['plan'], 'a log sync that throws counts as offline') +}) + +test('a failed or slow service never holds the spinner past the log and the cap', async () => { + const { log, later, svc, base } = calls() + const t0 = Date.now() + await pullRefresh({ ...base, refresh: later('log', 5, true), waitMs: 30, + whoop: svc('whoop', on(), () => new Promise(() => {})), strava: svc('strava', on(), () => Promise.reject(new Error('down'))) }) + assert.deepEqual(log, ['plan', 'log']) + assert.ok(Date.now() - t0 < 500, 'a hung WHOOP pull let the spinner go at the cap') +}) + +test('the services are pulled once the log has reached the server, and the spinner waits for both', async () => { + const { log, later, svc, base } = calls() + await pullRefresh({ ...base, refresh: later('log', 20, true), reloadPlan: () => {}, whoop: svc('whoop', on(), later('whoop', 10)), strava: svc('strava', null) }) + assert.deepEqual(log, ['log', 'whoop']) + log.length = 0 + await pullRefresh({ ...base, refresh: later('log', 0, undefined), reloadPlan: () => {}, whoop: svc('whoop', on()), strava: svc('strava', null) }) + assert.deepEqual(log, ['log'], 'a log sync skipped behind a push in flight has not said the server is there') +}) + +test('Screen is the only pull to refresh, so none skips the services', () => { + if (!/pullRefresh\(/.test(read('shell/Screen.tsx'))) throw new Error('Screen.tsx no longer refreshes through pullRefresh') + const others = walk('.').filter(f => f !== 'shell/Screen.tsx' && / { if (inFlight.current) return try { @@ -214,8 +216,10 @@ export function useStore() { setLastSync(new Date()) if (dirtyRef.current) push() else handoffIfSynced(() => dirtyRef.current) + return true } catch { setStatus('offline') + return false } }, [push]) diff --git a/mobile/src/lib/store.js b/mobile/src/lib/store.js index bc49dae..c0a5cb8 100644 --- a/mobile/src/lib/store.js +++ b/mobile/src/lib/store.js @@ -197,6 +197,8 @@ export function useStore() { const pushRef = useRef(null) pushRef.current = push + // Resolves true once the server answered, false when it could not be + // reached, undefined when a push was already in flight. const pull = useCallback(async () => { if (inFlight.current) return try { @@ -213,8 +215,10 @@ export function useStore() { setStatus(dirtyRef.current ? 'syncing' : 'synced') setLastSync(new Date()) if (dirtyRef.current) push() + return true } catch { setStatus('offline') + return false } }, [push]) diff --git a/mobile/src/shell/Screen.tsx b/mobile/src/shell/Screen.tsx index 7217796..d9e7859 100644 --- a/mobile/src/shell/Screen.tsx +++ b/mobile/src/shell/Screen.tsx @@ -1,7 +1,7 @@ // Every tab's frame: the web's header (.hdr: the mark, "Bushido", the streak, // the profile button), the acting banner, and a scrolling body that clears the -// floating tab bar (--dock-clear). Pull down to sync, the native form of the -// store re-reading on focus. +// floating tab bar (--dock-clear). Pull down to sync the log and pull WHOOP +// and Strava (pullRefresh.ts). import React, { useState } from 'react' import { RefreshControl, ScrollView, StyleSheet, View, type ScrollViewProps } from 'react-native' import { Image } from 'expo-image' @@ -11,6 +11,9 @@ import { T } from '../ui/Text' import { Icon } from '../lib/icons' import { streakDays } from '../lib/streak.js' import { useApp } from './AppData' +import { pullRefresh } from './pullRefresh' +import { useWhoop } from '../lib/whoop.jsx' +import { useStrava } from '../lib/strava.jsx' import { ActingBanner, tabsFor } from '../features/app' import { ProfileMenu } from '../features/profile' @@ -73,11 +76,14 @@ export function Screen({ children, scroll = true, fabs = true, contentStyle, scr }) { const insets = useSafeAreaInsets() const { store, me, reloadPlan } = useApp() + const whoop = useWhoop() + const strava = useStrava() const [refreshing, setRefreshing] = useState(false) const refresh = async () => { setRefreshing(true) - reloadPlan() - try { await store.refresh() } finally { setRefreshing(false) } + try { + await pullRefresh({ refresh: store.refresh, reloadPlan, whoop, strava }) + } finally { setRefreshing(false) } } const foot = (fabs && !compactDock(me) ? FAB_CLEAR : DOCK_CLEAR) + insets.bottom return ( diff --git a/mobile/src/shell/pullRefresh.ts b/mobile/src/shell/pullRefresh.ts new file mode 100644 index 0000000..14e853d --- /dev/null +++ b/mobile/src/shell/pullRefresh.ts @@ -0,0 +1,65 @@ +// Pull down on a tab: re-read the log and the plan, and ask WHOOP and Strava +// for what they have now. Their GETs (load on mount and on foreground) only +// serve the server's cache and start a refresh nobody waits for, so without +// the pull a ride that just synced shows on the second pull, not the first. +// Each pull is the same one the block's Refresh button makes, so a failure +// lands in that block's own error line, never in the log's sync state. + +type Pull = () => Promise + +/** A service's provider, as `useWhoop()` / `useStrava()` return it. */ +export type Service = { cache: unknown; pull: Pull } + +export type PullRefreshDeps = { + /** + * The log's own sync (the store's pull): true once the server answered, + * false when it could not be reached, undefined when it was skipped behind + * a push in flight. The spinner always waits for it. + */ + refresh: () => Promise + reloadPlan: () => void + whoop: Service + strava: Service + now?: number + /** How long the spinner waits for a slow service before letting go; its pull still lands. */ + waitMs?: number +} + +export const SERVICE_WAIT_MS = 8000 +/** A copy the server fetched this recently is current: pulling again only spends Strava's shared rate limit. */ +export const FRESH_MS = 60_000 + +/** + * Whether to pull a service: its cache says it is connected (the server's own + * answer on every GET, for whoever's log this is, so it is never staler than + * the last foreground) and it was not fetched within FRESH_MS. + */ +export function wantsPull(cache: unknown, now: number) { + const c = cache as { configured?: boolean; fetchedAt?: string | null } | null + if (c?.configured !== true) return false + const at = c.fetchedAt ? Date.parse(c.fetchedAt) : NaN + return !(now - at < FRESH_MS) +} + +export async function pullRefresh({ refresh, reloadPlan, whoop, strava, now = Date.now(), waitMs = SERVICE_WAIT_MS }: PullRefreshDeps) { + reloadPlan() + // The services only once the log reached the server: offline, a pull would + // leave "Network request failed" on every WHOOP and Strava block, where + // nothing clears it but another pull. A sync skipped behind a push still in + // flight has not said, so it waits for the next pull too. + // So the spinner can run up to SERVICE_WAIT_MS past the log: one after the + // other is the point, not an accident to make parallel again. + const reached = await refresh().catch(() => false) + if (reached !== true) return + const services = [whoop, strava].filter(s => wantsPull(s.cache, now)).map(s => s.pull()) + if (!services.length) return + let timer: ReturnType | undefined + try { + await Promise.race([ + Promise.allSettled(services), + new Promise(resolve => { timer = setTimeout(resolve, waitMs) }), + ]) + } finally { + clearTimeout(timer) + } +} diff --git a/server/http.test.js b/server/http.test.js index 83456a6..209e592 100644 --- a/server/http.test.js +++ b/server/http.test.js @@ -1247,6 +1247,8 @@ async function waitFor(fn, label, ms = 8000) { const cache = await (await get(`${sv.base}/api/strava`, as('sam@example.com'))).json() eq([cache.configured, cache.activities.map(a => a.id)], [true, [99]]) ok(!fs.existsSync(path.join(sv.dataDir, 'strava.json')), 'Sam\'s pull wrote the owner\'s cache') + const pulled = await (await samPost('/api/strava/pull')).json() + eq([pulled.configured, pulled.activities.map(a => a.id)], [true, [99]], 'the app keeps a pull\'s reply as its cache, so it says configured as the GET does') }) await step('own Strava: a callback with a state nobody started is refused', async () => { diff --git a/server/server.js b/server/server.js index 7ca05ff..d9a2198 100644 --- a/server/server.js +++ b/server/server.js @@ -2191,7 +2191,8 @@ const server = http.createServer(async (req, res) => { const status = stravaStateOf(space) if (!result.ok) return send(res, 502, { error: result.error, status }) const cache = readStravaCache(space) - return send(res, 200, { ...(cache || {}), status }) + // `configured` as the GET says it: the app keeps this reply as its cache. + return send(res, 200, { ...(cache || {}), configured: true, status }) } // One activity in full, for the moment the user attaches it. Live; not cached here. @@ -2237,7 +2238,7 @@ const server = http.createServer(async (req, res) => { }) if (!result.ok) return send(res, 502, { error: result.error, status: whoopState }) const cache = readWhoopCache() - return send(res, 200, { ...(cache || {}), status: whoopState }) + return send(res, 200, { ...(cache || {}), configured: true, status: whoopState }) } if (p === '/api/content' && req.method === 'GET') {