From 7265c6cad4c0866862472629d448145bd97ac906 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 20:54:33 -0500 Subject: [PATCH] fix(sync): sync on write with a request-budget scheduler and a 30 s interval Every sync now goes through one scheduler (src/services/syncSchedule.ts, pure and import-free): one sync at a time, a request during a sync gives a single relaunch, a sliding budget of 6 real HTTP requests per 60 s (each POST batch and each GET counted, initialMerge and initialReset included), pushChanges sends the batches the budget allows (MAX_PUSH_BATCHES becomes a ceiling) and the rest of the queue follows once the window frees, a 429 suspends the scheduler until Retry-After, and no sync starts during initialMerge / initialReset. The repositories call requestSync() (src/services/syncTrigger.ts, 2 s debounce, single subscriber registered by _layout.tsx) after each outbox write and after the Inbox repair transaction; outbox.ts and syncClient.ts never do. _layout.tsx syncs on launch, every 30 s in the foreground, on return to the foreground and on write through scheduleSync(); the Settings button too. REVIEW.md and scripts/review-levels.py list the two new files in the Sync row. test: reproduces #178 (tests/syncSchedule.test.mjs, smoke guards) Refs #178 Refs #167 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 12 +- app/(tabs)/settings.tsx | 5 +- app/_layout.tsx | 34 +++- package.json | 2 +- scripts/review-levels.py | 4 +- src/db/repository/lists.ts | 9 +- src/db/repository/tags.ts | 9 +- src/db/repository/tasks.ts | 9 +- src/services/syncClient.ts | 111 +++++++++--- src/services/syncRules.ts | 7 +- src/services/syncSchedule.ts | 188 +++++++++++++++++++ src/services/syncTrigger.ts | 38 ++++ tests/smoke.test.cjs | 89 ++++++++- tests/syncSchedule.test.mjs | 338 +++++++++++++++++++++++++++++++++++ 14 files changed, 791 insertions(+), 64 deletions(-) create mode 100644 src/services/syncSchedule.ts create mode 100644 src/services/syncTrigger.ts create mode 100644 tests/syncSchedule.test.mjs diff --git a/REVIEW.md b/REVIEW.md index d78e342..5fb156c 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -28,9 +28,9 @@ Motifs : chemins depuis la racine. `*` ne traverse jamais un `/` ; `**/` vaut z |---|---|---| | `src/lib/{authToken,logtoConfig,validation}.ts`, `web/src/lib/{auth,logto,api}.ts`, `web/src/middleware.ts`, `web/src/app/api/logto/**`, `web/src/app/auth/**` | toujours | Authentification | | `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts`, `web/server.ts` | toujours | API et isolation des comptes | -| `src/services/{syncClient,syncRules}.ts`, `src/db/repository/outbox.ts` | toujours | Sync | +| `src/services/{syncClient,syncRules,syncSchedule,syncTrigger}.ts`, `src/db/repository/outbox.ts` | toujours | Sync | | `src/db/{schema,client}.ts`, `src/db/migrations/**`, `web/src/db/{schema,client,seed}.ts`, `web/src/db/migrations/**`, `drizzle.config.ts`, `web/drizzle.config.ts`, `sql-transformer.js` | toujours | Migrations et données | -| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`) | Migrations et données, Authentification, Sync | +| `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`, `scheduleSync`, `setSyncSubscriber`) | Migrations et données, Authentification, Sync | | `app/(tabs)/settings.tsx` | le diff touche la connexion, l'activation de la sync (`initialMerge`, `initialReset`, `setSyncEnabled`) ou la vérification des mises à jour (`releases/latest`, asset `.apk`) | Sync, Release | | `src/services/feedback.ts`, `src/components/FeedbackModal.tsx`, `src/hooks/useFeedback.ts` | toujours | Vie privée | | code livré : `app/**`, `src/**`, `web/src/**` | le diff ajoute un appel réseau vers une URL absolue (un `fetch`, ou une URL de base dans une constante ou un champ de configuration), ou change ce qu'un appel existant envoie | Vie privée | @@ -115,11 +115,13 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`writeOutboxEntry`, action `update`). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 - Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`) - Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149 -- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, #149 +- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs` (check smoke `syncSchedule.ts and syncTrigger.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, #149, #178 - Contrat des résultats d'un push : `applied` = opération écrite, `skipped` sans `error` = clé déjà vue, donc doublon déjà appliqué, `skipped` avec `error` = refus. L'app marque les deux premiers comme synchronisés et rejoue le troisième : le serveur garde cette distinction. — `src/services/syncRules.ts` (`parseResults`, `isSynced`), `web/src/app/api/sync/route.ts`, `web/src/app/api/sync/route.test.ts`, #151 - Un refus est rejoué à chaque push, 30 jours (`REJECTED_RETENTION_DAYS`) et 100 refus (`MAX_KEPT_REFUSALS`, les plus récents) au plus, et abandonné dès qu'une entrée plus récente de la même entité (`entityType` + `entityId`, plus `tagId` pour `taskTag`) passe dans le même push. Cette règle de remplacement tient parce que les refus repartent à chaque push, dans l'ordre de création, avant les entrées plus récentes : un espacement des rejeux la remet en cause. Une entrée sans résultat (lot non envoyé ou en échec) n'est pas marquée. — `src/services/syncRules.ts` (`classifyOutbox`), `src/services/syncClient.ts`, #151 -- `pushChanges` envoie 8 lots au plus (`MAX_PUSH_BATCHES`) et s'arrête au premier 429, et `initialMerge` envoie tous les lots en attendant le `Retry-After` d'un 429 (borné à 60 s, 3 renvois du même lot au plus). — `src/services/syncRules.ts` (`sendInBatches`), `src/services/syncClient.ts`, `tests/smoke.test.cjs`, #151 -- La limite `sync` (10 requêtes par minute et par compte, GET et POST confondus) est le budget d'un `fullSync` : 8 lots de push laissent la place du pull. Un lot ou une requête ajoutés se jugent contre elle. — `web/src/lib/rateLimit.ts`, `src/services/syncRules.ts`, #151 +- `pushChanges` envoie les lots que le planificateur autorise (budget restant moins la place du GET du pull, 8 au plus, `MAX_PUSH_BATCHES`) et s'arrête au premier 429, et `initialMerge` envoie tous les lots en attendant le `Retry-After` d'un 429 (borné à 60 s, 3 renvois du même lot au plus). — `src/services/syncRules.ts` (`sendInBatches`), `src/services/syncClient.ts`, `tests/smoke.test.cjs`, #151, #178 +- La limite `sync` du serveur (10 requêtes par minute et par compte, GET et POST confondus, tous appareils confondus) est partagée : l'app s'en tient à 6 requêtes HTTP réelles par 60 s glissantes (`REQUEST_BUDGET`), chaque POST de lot et chaque GET comptés, `initialMerge` et `initialReset` compris. Une requête ajoutée vers `/api/sync` passe par `RequestTracker` (`request()` avant l'envoi, `rateLimited()` sur un 429), sinon le budget ment. — `web/src/lib/rateLimit.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, #151, #178 +- Toute sync passe par le planificateur (`scheduleSync`) : lancement, intervalle de 30 s au premier plan, retour au premier plan, écriture locale et bouton « Synchroniser maintenant ». Une sync à la fois, une demande pendant une sync donne une seule relance, un 429 suspend jusqu'au `Retry-After`, et aucune sync ne part pendant `initialMerge` / `initialReset`. `fullSync` reste privé à `syncClient.ts`. — `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/_layout.tsx`, `app/(tabs)/settings.tsx`, `tests/syncSchedule.test.mjs`, #178 +- Les repositories (`lists`, `tasks`, `tags`) appellent `requestSync()` (anti-rebond de 2 s) après chaque écriture d'outbox et après le commit d'une transaction ; `outbox.ts` et `syncClient.ts` ne l'appellent jamais, pour que les écritures de la sync elle-même (`keepLocal`, `initialReset`) ne relancent rien. Sans abonné (widget headless, sync coupée), une demande ne fait rien. — `src/services/syncTrigger.ts`, `src/db/repository/{lists,tasks,tags}.ts`, `tests/smoke.test.cjs`, #178 - Après un push ou un pull qui applique des changements, le widget est rafraîchi (`syncWidgetData`). — PR #66, `src/services/syncClient.ts` ### Migrations et données diff --git a/app/(tabs)/settings.tsx b/app/(tabs)/settings.tsx index 653908d..7ea22e1 100644 --- a/app/(tabs)/settings.tsx +++ b/app/(tabs)/settings.tsx @@ -12,7 +12,7 @@ import { redirectUri, postSignOutRedirectUri } from '@/src/lib/logtoConfig'; import { getAllTags, createTag, updateTag, deleteTag } from '@/src/db/repository/tags'; import { initCalendar } from '@/src/services/calendar'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { fullSync, initialMerge, initialReset } from '@/src/services/syncClient'; +import { scheduleSync, initialMerge, initialReset } from '@/src/services/syncClient'; import i18n from '@/src/i18n'; import FeedbackModal from '@/src/components/FeedbackModal'; @@ -215,7 +215,8 @@ export default function SettingsScreen() { setIsSyncing(true); try { - await fullSync(); + // Through the scheduler (#178): may wait for the request budget + await scheduleSync(); } catch { // Sync errors are logged internally } finally { diff --git a/app/_layout.tsx b/app/_layout.tsx index c0ffc41..f0bbc74 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -15,7 +15,8 @@ import { ensureInbox, repairInbox } from '@/src/db/repository/lists'; import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { initNotifications } from '@/src/services/notifications'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { fullSync, cleanOutbox } from '@/src/services/syncClient'; +import { scheduleSync } from '@/src/services/syncClient'; +import { setSyncSubscriber } from '@/src/services/syncTrigger'; import { logtoConfig } from '@/src/lib/logtoConfig'; import { setTokenGetter, clearTokenGetter } from '@/src/lib/authToken'; import '@/src/i18n'; @@ -23,6 +24,10 @@ import '@/src/global.css'; export { ErrorBoundary } from 'expo-router'; +// Foreground sync interval (decision of Max, 2026-10-29, #167); back to 2 min +// once the WebSocket of #175 replaces the polling. +const SYNC_INTERVAL_MS = 30 * 1000; + SplashScreen.preventAutoHideAsync(); const SimplLightTheme = { @@ -119,27 +124,40 @@ function AppContent() { return () => clearTokenGetter(); }, [isAuthenticated, syncEnabled, getAccessToken]); - // Sync polling: run on launch, every 2 min, and on return from background + // Sync (#178): on launch, every 30 s in the foreground, on return from + // background and after a local write, always through the scheduler (one + // sync at a time, request budget, Retry-After of a 429). useEffect(() => { if (!syncEnabled) return; + let active = true; - // Initial sync, once the Inbox is set up - prepareInbox().then(() => fullSync()).then(() => cleanOutbox()).catch(() => {}); + // Initial sync and sync on write, once the Inbox is set up: a push during + // the repair would replay the entries it rewrites + prepareInbox().then(() => { + if (!active) return; + setSyncSubscriber(() => { + scheduleSync().catch(() => {}); + }); + return scheduleSync(); + }).catch(() => {}); - // 2-minute interval + // 30-second interval, foreground only const interval = setInterval(() => { - fullSync().then(() => cleanOutbox()).catch(() => {}); - }, 2 * 60 * 1000); + if (AppState.currentState !== 'active') return; + prepareInbox().then(() => scheduleSync()).catch(() => {}); + }, SYNC_INTERVAL_MS); // AppState listener: sync when returning from background const subscription = AppState.addEventListener('change', (nextState: AppStateStatus) => { if (appState.current.match(/inactive|background/) && nextState === 'active') { - fullSync().catch(() => {}); + prepareInbox().then(() => scheduleSync()).catch(() => {}); } appState.current = nextState; }); return () => { + active = false; + setSyncSubscriber(null); clearInterval(interval); subscription.remove(); }; diff --git a/package.json b/package.json index ca1600f..45cbf22 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "version": "1.7.0", "scripts": { "start": "expo start", - "test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs tests/hydration.test.mjs", + "test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs tests/hydration.test.mjs tests/syncSchedule.test.mjs", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", diff --git a/scripts/review-levels.py b/scripts/review-levels.py index ce8a980..7913b2e 100755 --- a/scripts/review-levels.py +++ b/scripts/review-levels.py @@ -46,7 +46,7 @@ HIGH_ALWAYS = [ "web/src/lib/{auth,logto,api}.ts", "web/src/middleware.ts", "web/src/app/api/logto/**", "web/src/app/auth/**", "web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts", "web/server.ts", - "src/services/{syncClient,syncRules}.ts", "src/db/repository/outbox.ts", + "src/services/{syncClient,syncRules,syncSchedule,syncTrigger}.ts", "src/db/repository/outbox.ts", "src/db/{schema,client}.ts", "src/db/migrations/**", "web/src/db/{schema,client,seed}.ts", "web/src/db/migrations/**", "drizzle.config.ts", "web/drizzle.config.ts", "sql-transformer.js", @@ -56,7 +56,7 @@ HIGH_ALWAYS = [ ".claude/settings.json", ".mcp.json", ] LAYOUT = "app/_layout.tsx" -LAYOUT_RE = re.compile(r"useMigrations|migrations|Logto|TokenGetter|fullSync|cleanOutbox|syncClient") +LAYOUT_RE = re.compile(r"useMigrations|migrations|Logto|TokenGetter|fullSync|cleanOutbox|syncClient|scheduleSync|SyncSubscriber") SETTINGS = "app/(tabs)/settings.tsx" SETTINGS_RE = re.compile(r"initialMerge|initialReset|setSyncEnabled|syncEnabled|logtoSign|signIn|signOut|" r"releases/latest|\.apk|tag_name|checkForUpdate") diff --git a/src/db/repository/lists.ts b/src/db/repository/lists.ts index 244f2c8..98a3f68 100644 --- a/src/db/repository/lists.ts +++ b/src/db/repository/lists.ts @@ -5,6 +5,7 @@ import { randomUUID } from '@/src/lib/uuid'; import { truncate } from '@/src/lib/validation'; import { whenSettingsHydrated } from '@/src/stores/useSettingsStore'; import { LOCAL_INBOX_ID, pickInboxId, planInboxRepair } from '@/src/services/syncRules'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntries, writeOutboxEntry } from './outbox'; /** @@ -93,6 +94,8 @@ export async function repairInbox(): Promise { await writeOutboxEntries(tx, plan.ops); await tx.delete(lists).where(eq(lists.id, LOCAL_INBOX_ID)); }); + // After the commit: the repaired entries go out with the next sync + requestSync(); console.warn( `[inbox] repaired: ${plan.movedTaskIds.length} task(s) moved, ` + @@ -135,7 +138,7 @@ export async function createList(name: string, color?: string, icon?: string) { icon: icon ?? null, position: maxPosition + 1, isInbox: false, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); return id; } @@ -148,7 +151,7 @@ export async function updateList(id: string, data: { name?: string; color?: stri .set({ ...sanitized, updatedAt: new Date() }) .where(eq(lists.id, id)); - writeOutboxEntry('list', id, 'update', { id, ...sanitized }).catch(() => {}); + writeOutboxEntry('list', id, 'update', { id, ...sanitized }).then(requestSync).catch(() => {}); } export async function reorderLists(updates: { id: string; position: number }[]) { @@ -161,5 +164,5 @@ export async function reorderLists(updates: { id: string; position: number }[]) export async function deleteList(id: string) { await db.delete(lists).where(eq(lists.id, id)); - writeOutboxEntry('list', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('list', id, 'delete', { id }).then(requestSync).catch(() => {}); } diff --git a/src/db/repository/tags.ts b/src/db/repository/tags.ts index 00edcd6..12b2f42 100644 --- a/src/db/repository/tags.ts +++ b/src/db/repository/tags.ts @@ -3,6 +3,7 @@ import { db } from '../client'; import { tags, taskTags } from '../schema'; import { randomUUID } from '@/src/lib/uuid'; import { truncate } from '@/src/lib/validation'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntry } from './outbox'; export async function getAllTags() { @@ -20,20 +21,20 @@ export async function createTag(name: string, color: string) { updatedAt: now, }); - writeOutboxEntry('tag', id, 'create', { id, name, color }).catch(() => {}); + writeOutboxEntry('tag', id, 'create', { id, name, color }).then(requestSync).catch(() => {}); return id; } export async function updateTag(id: string, name: string, color: string) { await db.update(tags).set({ name: truncate(name, 100), color, updatedAt: new Date() }).where(eq(tags.id, id)); - writeOutboxEntry('tag', id, 'update', { id, name, color }).catch(() => {}); + writeOutboxEntry('tag', id, 'update', { id, name, color }).then(requestSync).catch(() => {}); } export async function deleteTag(id: string) { await db.delete(taskTags).where(eq(taskTags.tagId, id)); await db.delete(tags).where(eq(tags.id, id)); - writeOutboxEntry('tag', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('tag', id, 'delete', { id }).then(requestSync).catch(() => {}); } export async function getTagsForTask(taskId: string) { @@ -54,7 +55,7 @@ export async function setTagsForTask(taskId: string, tagIds: string[]) { } // Send individual taskTag create operations (server expects entityId=taskId, data.tagId) for (const tagId of tagIds) { - writeOutboxEntry('taskTag', taskId, 'create', { tagId }).catch(() => {}); + writeOutboxEntry('taskTag', taskId, 'create', { tagId }).then(requestSync).catch(() => {}); } } diff --git a/src/db/repository/tasks.ts b/src/db/repository/tasks.ts index 8d9ceec..bf0e06e 100644 --- a/src/db/repository/tasks.ts +++ b/src/db/repository/tasks.ts @@ -11,6 +11,7 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { syncWidgetData } from '@/src/services/widgetSync'; import { clamp, truncate } from '@/src/lib/validation'; import { RECURRENCE_OPTIONS } from '@/src/lib/recurrence'; +import { requestSync } from '@/src/services/syncTrigger'; import { writeOutboxEntry } from './outbox'; export type { TaskFilters } from '@/src/shared/types'; @@ -183,7 +184,7 @@ export async function createTask(data: { listId: data.listId, parentId: data.parentId ?? null, recurrence: sanitizedRecurrence, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); syncWidgetData().catch(() => {}); @@ -263,7 +264,7 @@ export async function updateTask( listId: task.listId, parentId: task.parentId, recurrence: task.recurrence, - }).catch(() => {}); + }).then(requestSync).catch(() => {}); } syncWidgetData().catch(() => {}); @@ -334,7 +335,7 @@ export async function deleteTask(id: string) { // Delete subtasks first const subtasks = await getSubtasks(id); for (const sub of subtasks) { - writeOutboxEntry('task', sub.id, 'delete', { id: sub.id }).catch(() => {}); + writeOutboxEntry('task', sub.id, 'delete', { id: sub.id }).then(requestSync).catch(() => {}); await db.delete(taskTags).where(eq(taskTags.taskId, sub.id)); await db.delete(tasks).where(eq(tasks.id, sub.id)); } @@ -342,7 +343,7 @@ export async function deleteTask(id: string) { await db.delete(tasks).where(eq(tasks.id, id)); // Sync outbox - writeOutboxEntry('task', id, 'delete', { id }).catch(() => {}); + writeOutboxEntry('task', id, 'delete', { id }).then(requestSync).catch(() => {}); syncWidgetData().catch(() => {}); } diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index 4230ad9..4500c70 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -23,6 +23,12 @@ import { sendInBatches, type PostResponse, } from '@/src/services/syncRules'; +import { + createSyncScheduler, + type RequestTracker, + type RunOutcome, + type SyncRun, +} from '@/src/services/syncSchedule'; const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com'; const INBOX_ID = '00000000-0000-0000-0000-000000000001'; @@ -59,10 +65,16 @@ async function getAuthHeaders(): Promise> { /** * POST one batch of operations to the server sync endpoint. Retry-After is - * read in seconds; the body is parsed only on a 2xx. + * read in seconds; the body is parsed only on a 2xx. Every request and every + * 429 is reported to the scheduler (#178). */ -async function postBatch(batch: SyncOperation[], headers: Record): Promise { +async function postBatch( + batch: SyncOperation[], + headers: Record, + tracker: RequestTracker, +): Promise { try { + tracker.request(); const res = await fetch(`${SYNC_API_BASE}/api/sync`, { method: 'POST', headers, @@ -70,7 +82,9 @@ async function postBatch(batch: SyncOperation[], headers: Record }); if (!res.ok) { console.warn(`[sync] push failed with status ${res.status}`); - return { status: res.status, retryAfter: parseRetryAfter(res.headers.get('Retry-After')), body: null }; + const failed = { status: res.status, retryAfter: parseRetryAfter(res.headers.get('Retry-After')), body: null }; + if (res.status === 429) tracker.rateLimited(failed.retryAfter); + return failed; } const body = await res.json().catch(() => null); return { status: res.status, retryAfter: null, body }; @@ -85,14 +99,15 @@ function sleep(ms: number): Promise { } /** - * Push unsynced outbox entries to the server, oldest first, MAX_PUSH_BATCHES - * batches at most. Marks the entries the server holds (applied or duplicate) - * and the refusals classifyOutbox drops; the other refusals are replayed by - * the next push (#151). + * Push unsynced outbox entries to the server, oldest first, as many batches + * as the scheduler allows (run.pushBatches, MAX_PUSH_BATCHES at most, #178). + * Marks the entries the server holds (applied or duplicate) and the refusals + * classifyOutbox drops; the other refusals are replayed by the next push + * (#151). `more` is true when the budget left entries unsent. */ -export async function pushChanges(): Promise { +export async function pushChanges(run: SyncRun): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) return {}; const unsynced = await db .select() @@ -101,7 +116,7 @@ export async function pushChanges(): Promise { // Creation order: replayed refusals go before the entries that replace them .orderBy(asc(syncOutbox.createdAt)); - if (unsynced.length === 0) return; + if (unsynced.length === 0) return {}; const operations: SyncOperation[] = unsynced.map((entry) => { const data = JSON.parse(entry.payload); @@ -114,11 +129,12 @@ export async function pushChanges(): Promise { }; }); - const { results } = await sendInBatches(operations, { + const maxBatches = Math.max(0, Math.min(run.pushBatches, MAX_PUSH_BATCHES)); + const { results, ok } = await sendInBatches(operations, { size: BATCH_SIZE, - maxBatches: MAX_PUSH_BATCHES, + maxBatches, retryOn429: false, - post: (batch) => postBatch(batch, headers), + post: (batch) => postBatch(batch, headers, run), sleep, }); @@ -135,21 +151,25 @@ export async function pushChanges(): Promise { // Refresh widget after a push that synced entries syncWidgetData().catch(() => {}); } + return { more: ok && operations.length > maxBatches * BATCH_SIZE }; } /** - * Pull changes from the server since the last sync timestamp. + * Pull changes from the server since the last sync timestamp. The GET and a + * 429 are reported to the scheduler (#178). */ -export async function pullChanges(since: string): Promise { +export async function pullChanges(since: string, tracker: RequestTracker): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; try { const url = `${SYNC_API_BASE}/api/sync?since=${encodeURIComponent(since)}`; + tracker.request(); const res = await fetch(url, { method: 'GET', headers }); if (!res.ok) { console.warn(`[sync] pull failed with status ${res.status}`); + if (res.status === 429) tracker.rateLimited(parseRetryAfter(res.headers.get('Retry-After'))); return; } @@ -284,22 +304,49 @@ async function applyTaskTagChange(id: string, action: string, payload: Record { +async function fullSync(run: SyncRun): Promise { const { syncEnabled } = useSettingsStore.getState(); - if (!syncEnabled) return; + if (!syncEnabled) return {}; try { - await pushChanges(); + const outcome = await pushChanges(run); + // A 429 on the push: nothing more until its Retry-After + if (run.isSuspended()) return outcome; const since = useSettingsStore.getState().lastSyncAt ?? SYNC_EPOCH; - await pullChanges(since); + await pullChanges(since, run); + return outcome; } catch (err) { console.warn('[sync] fullSync error:', err); + return {}; } } +// One scheduler per process: launch, the 30 s interval, the return to the +// foreground, local writes and the Settings button all go through it. +const scheduler = createSyncScheduler({ + now: () => Date.now(), + setTimer: (fn, ms) => setTimeout(fn, ms), + canRun: () => useSettingsStore.getState().syncEnabled, + run: async (run) => { + const outcome = await fullSync(run); + await cleanOutbox().catch(() => {}); + return outcome; + }, +}); + +/** + * Ask the scheduler for a sync (push then pull). Resolves when the sync that + * serves the request has ended; it may wait for the request budget or the + * Retry-After of a 429. + */ +export function scheduleSync(): Promise { + return scheduler.request(); +} + /** * First-time sync: merge all local data to server. * Creates an Inbox on the server, remaps the local hardcoded Inbox ID, @@ -307,6 +354,15 @@ export async function fullSync(): Promise { * pulls the whole account from SYNC_EPOCH. */ export async function initialMerge(): Promise { + await scheduler.beginInitialSync(); + try { + await mergeLocalData(); + } finally { + scheduler.endInitialSync(); + } +} + +async function mergeLocalData(): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; @@ -388,7 +444,7 @@ export async function initialMerge(): Promise { size: BATCH_SIZE, maxBatches: Infinity, retryOn429: true, - post: (batch) => postBatch(batch, headers), + post: (batch) => postBatch(batch, headers, scheduler.tracker), sleep, }); if (!ok) { @@ -419,13 +475,22 @@ export async function initialMerge(): Promise { // lastSyncAt is set to the epoch first, so that a failed pull is replayed // from the epoch by the next fullSync. useSettingsStore.getState().setLastSyncAt(SYNC_EPOCH); - await pullChanges(SYNC_EPOCH); + await pullChanges(SYNC_EPOCH, scheduler.tracker); } /** * First-time sync: discard local data and pull everything from server. */ export async function initialReset(): Promise { + await scheduler.beginInitialSync(); + try { + await resetFromServer(); + } finally { + scheduler.endInitialSync(); + } +} + +async function resetFromServer(): Promise { const headers = await getAuthHeaders(); if (!headers['Authorization']) return; @@ -437,7 +502,7 @@ export async function initialReset(): Promise { await db.delete(syncOutbox); // 2. Pull everything from server - await pullChanges(SYNC_EPOCH); + await pullChanges(SYNC_EPOCH, scheduler.tracker); // 3. An account without Inbox (the server never creates one for a new // account): create it under a new UUID and push it. Not the fixed local diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index 8e65ff6..3209a08 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -194,9 +194,10 @@ export function tagUpdatePayload(tag: TagRow): Payload { /** Operations per POST /api/sync (the server accepts 200 at most). */ export const BATCH_SIZE = 50; /** - * Batches sent by one pushChanges. The `sync` rate limit (10 requests per - * minute and per account, GET and POST together) is the budget of a whole - * fullSync: 8 POST batches leave room for its pull. + * Upper bound of the batches sent by one pushChanges. The actual count comes + * from the request budget of the scheduler (syncSchedule.ts, #178), always + * lower: the `sync` rate limit (10 requests per minute and per account, GET + * and POST together) is shared by every device of the account. */ export const MAX_PUSH_BATCHES = 8; /** Refused operations kept in the outbox for a replay, the most recent first. */ diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts new file mode 100644 index 0000000..e71fc4a --- /dev/null +++ b/src/services/syncSchedule.ts @@ -0,0 +1,188 @@ +// Sync scheduler (#178): one sync at a time, a sliding budget of real HTTP +// requests, the Retry-After of a 429 and the first-sync state. Pure and +// import-free, like syncRules.ts, so that tests/syncSchedule.test.mjs loads +// it through node's type stripping (zero-import guard in smoke.test.cjs). +// The clock and the timers are injected; syncClient.ts wires the real ones. + +/** + * Real HTTP requests (each POST batch and each GET) a device sends per + * BUDGET_WINDOW_MS. The server allows 10 per minute and per account, every + * device together (web/src/lib/rateLimit.ts): 6 leave room for a second + * device and the companion (decision of Max, 2026-11-02). + */ +export const REQUEST_BUDGET = 6; +/** Length of the sliding budget window, in ms. */ +export const BUDGET_WINDOW_MS = 60_000; +/** Suspension after a 429 without a readable Retry-After, in seconds. */ +export const DEFAULT_RETRY_AFTER_S = 60; +/** Upper bound of a Retry-After, in seconds: a bogus header never stops sync for good. */ +export const MAX_RETRY_AFTER_S = 600; + +/** What a code path that sends requests to the sync server reports. */ +export interface RequestTracker { + /** Count one HTTP request, just before it is sent. */ + request(): void; + /** The server answered 429: no request until Retry-After (seconds, null when unreadable). */ + rateLimited(retryAfterS: number | null): void; +} + +/** Handed to one run of the scheduler. */ +export interface SyncRun extends RequestTracker { + /** + * POST batches this run may send: the remaining budget minus one place for + * the GET of the pull. The rest of the queue goes to the next run. + */ + readonly pushBatches: number; + /** True once a 429 suspended the scheduler: the run sends nothing more. */ + isSuspended(): boolean; +} + +export interface RunOutcome { + /** The push left entries unsent (budget): the scheduler runs again when the budget allows. */ + more?: boolean; +} + +export interface SchedulerDeps { + now(): number; + setTimer(fn: () => void, ms: number): unknown; + /** One sync (push then pull). Its errors are swallowed by the scheduler. */ + run(ctx: SyncRun): Promise; + /** + * Checked before each run: false drops the pending requests (sync off, and + * later other guards such as the account check of #165). + */ + canRun?(): boolean; +} + +export interface SyncScheduler { + /** + * Ask for a sync. Resolves when the run that serves this request ends, or + * at once when the guard drops it. A request during a run gives exactly one + * more run, after it. + */ + request(): Promise; + /** Tracker for the requests sent outside a run (initialMerge, initialReset). */ + tracker: RequestTracker; + /** + * Enter the first-sync state: no run starts until endInitialSync, the + * requests made meanwhile wait for its end. Resolves once the run in flight, + * if any, has ended. + */ + beginInitialSync(): Promise; + endInitialSync(): void; +} + +export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { + // Send times of the requests still inside the window, oldest first + let sent: number[] = []; + let suspendedUntil = 0; + let running = false; + let pending = false; + let initial = 0; + let timerArmed = false; + let waiters: (() => void)[] = []; + let idleWaiters: (() => void)[] = []; + + function remaining(now: number): number { + sent = sent.filter((t) => t > now - BUDGET_WINDOW_MS); + return REQUEST_BUDGET - sent.length; + } + + function arm(ms: number) { + timerArmed = true; + deps.setTimer(() => { + timerArmed = false; + pump(); + }, Math.max(0, ms)); + } + + function settle(list: (() => void)[]) { + for (const resolve of list) resolve(); + } + + const tracker: RequestTracker = { + request() { + sent.push(deps.now()); + }, + rateLimited(retryAfterS) { + const s = retryAfterS == null ? DEFAULT_RETRY_AFTER_S : Math.min(Math.max(retryAfterS, 0), MAX_RETRY_AFTER_S); + suspendedUntil = Math.max(suspendedUntil, deps.now() + s * 1000); + }, + }; + + function pump() { + if (running || initial > 0 || timerArmed || !pending) return; + if (deps.canRun && !deps.canRun()) { + pending = false; + const dropped = waiters; + waiters = []; + settle(dropped); + return; + } + const now = deps.now(); + if (now < suspendedUntil) { + arm(suspendedUntil - now); + return; + } + const left = remaining(now); + if (left < 1) { + // The oldest request leaves the window first + arm(sent[0] + BUDGET_WINDOW_MS - now); + return; + } + start(left); + } + + function start(left: number) { + running = true; + pending = false; + const served = waiters; + waiters = []; + const startedAt = deps.now(); + const ctx: SyncRun = { + pushBatches: left - 1, + request: tracker.request, + rateLimited: tracker.rateLimited, + isSuspended: () => deps.now() < suspendedUntil, + }; + let outcome: RunOutcome | void = undefined; + Promise.resolve() + .then(() => deps.run(ctx)) + .then( + (o) => { + outcome = o; + }, + () => {}, + ) + .then(() => { + running = false; + // Unsent queue, or a 429 in this run: go on once budget or Retry-After allow + if ((outcome && outcome.more) || suspendedUntil > startedAt) pending = true; + settle(served); + const idle = idleWaiters; + idleWaiters = []; + settle(idle); + pump(); + }); + } + + return { + request() { + return new Promise((resolve) => { + waiters.push(resolve); + pending = true; + pump(); + }); + }, + tracker, + beginInitialSync() { + initial++; + if (!running) return Promise.resolve(); + return new Promise((resolve) => idleWaiters.push(resolve)); + }, + endInitialSync() { + initial = Math.max(0, initial - 1); + pump(); + }, + }; +} diff --git a/src/services/syncTrigger.ts b/src/services/syncTrigger.ts new file mode 100644 index 0000000..5fa8c29 --- /dev/null +++ b/src/services/syncTrigger.ts @@ -0,0 +1,38 @@ +// Sync on write (#178). The repositories (lists, tasks, tags) call +// requestSync() after a local write that reached the outbox; the single +// subscriber, registered by app/_layout.tsx while sync is on, hands it to the +// scheduler. Import-free: the repositories load it without any sync or DB +// module, and without a subscriber (headless widget handler, sync off) a +// request does nothing. outbox.ts never calls it, so the outbox writes of the +// sync itself (keepLocal, initialReset) trigger nothing. + +/** Writes closer than this make one sync, sent this long after the last one. */ +export const SYNC_DEBOUNCE_MS = 2000; + +let subscriber: (() => void) | null = null; +let timer: ReturnType | null = null; + +/** Register the single subscriber, or remove it with null (pending request dropped). */ +export function setSyncSubscriber(fn: (() => void) | null): void { + subscriber = fn; + if (!fn && timer) { + clearTimeout(timer); + timer = null; + } +} + +/** Ask for a sync after a local write, debounced by SYNC_DEBOUNCE_MS. */ +export function requestSync(): void { + if (!subscriber) return; + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + timer = null; + const fn = subscriber; + if (!fn) return; + try { + fn(); + } catch { + // The scheduler logs its own failures + } + }, SYNC_DEBOUNCE_MS); +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 9c50960..b51ac94 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -181,6 +181,70 @@ check('syncRules.ts stays import-free (protects type-stripping test path)', () = ); }); +// The sync scheduler and the sync-on-write trigger (#178) are executed by +// tests/syncSchedule.test.mjs through node's type stripping, and the +// repositories load syncTrigger.ts: both stay free of any import (no DB, no +// sync module, no dynamic import either). +check('syncSchedule.ts and syncTrigger.ts stay import-free (#178)', () => { + for (const file of ['src/services/syncSchedule.ts', 'src/services/syncTrigger.ts']) { + assert.deepEqual(staticImportsOf(file), [], `${file} must have zero imports`); + const src = fs.readFileSync(path.join(__dirname, '..', file), 'utf8'); + assert.ok(!/\bimport\s*\(|\brequire\s*\(|^\s*import\s/m.test(src), `${file} must not import anything`); + } +}); + +// Wiring of the scheduler (#178) in files node cannot load: the repositories +// request a sync after each outbox write, the sync's own outbox writes never +// do, and every sync goes through the scheduler. +check('sync on write and every sync go through the scheduler (#178)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + for (const rel of ['src/db/repository/lists.ts', 'src/db/repository/tasks.ts', 'src/db/repository/tags.ts']) { + const src = read(rel); + assert.match(src, /^import \{ requestSync \} from '@\/src\/services\/syncTrigger';$/m, `${rel} must import requestSync`); + // Every single outbox write is followed by a sync request, once written + const writes = src.match(/writeOutboxEntry\([^;]*?;/g) || []; + assert.ok(writes.length > 0, `${rel} writes no outbox entry`); + for (const w of writes) { + assert.match(w, /\)\.then\(requestSync\)\.catch\(\(\) => \{\}\);$/, `${rel}: ${w.slice(0, 60)}... must request a sync after the write`); + } + } + // repairInbox requests a sync after its transaction is committed + const lists = read('src/db/repository/lists.ts'); + const repair = lists.slice(lists.indexOf('export async function repairInbox('), lists.indexOf('function chunks(')); + const tx = repair.indexOf('await db.transaction('); + const req = repair.indexOf('requestSync();'); + assert.ok(tx >= 0 && req > repair.indexOf('\n });', tx), 'repairInbox must call requestSync() after its transaction'); + // The sync's own outbox writes (keepLocal, initialReset) never trigger a sync + for (const rel of ['src/db/repository/outbox.ts', 'src/services/syncClient.ts']) { + assert.ok(!/requestSync|syncTrigger/.test(read(rel)), `${rel} must not request a sync`); + } + // _layout.tsx: launch, interval, foreground and writes through the scheduler + const layout = read('app/_layout.tsx'); + assert.ok(!/\bfullSync\b|pushChanges|pullChanges/.test(layout), '_layout.tsx must not call fullSync directly'); + assert.match(layout, /const SYNC_INTERVAL_MS = 30 \* 1000;/); + assert.match(layout, /setInterval\(\(\) => \{\s*if \(AppState\.currentState !== 'active'\) return;\s*prepareInbox\(\)\.then\(\(\) => scheduleSync\(\)\)/); + assert.match(layout, /setSyncSubscriber\(\(\) => \{\s*scheduleSync\(\)/); + assert.match(layout, /setSyncSubscriber\(null\);/); + // Settings: « Synchroniser maintenant » through the scheduler + const settings = read('app/(tabs)/settings.tsx'); + assert.ok(!/\bfullSync\b/.test(settings), 'settings.tsx must not call fullSync directly'); + assert.match(settings, /await scheduleSync\(\);/); + // syncClient.ts: fullSync is private, every request and 429 is reported + const client = read('src/services/syncClient.ts'); + assert.ok(!/export async function fullSync/.test(client), 'fullSync must stay private to the scheduler'); + assert.match(client, /tracker\.request\(\);\s*const res = await fetch\(`\$\{SYNC_API_BASE\}\/api\/sync`, \{/, 'postBatch must count its request'); + assert.match(client, /tracker\.request\(\);\s*const res = await fetch\(url, \{ method: 'GET', headers \}\);/, 'pullChanges must count its request'); + assert.equal((client.match(/if \(res\.status === 429\) tracker\.rateLimited\(/g) || []).length, 2, 'push and pull must report a 429'); + assert.match(client, /if \(run\.isSuspended\(\)\) return outcome;\s*const since/, 'no pull after a 429 on the push'); + for (const name of ['initialMerge', 'initialReset']) { + const start = client.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + const body = client.slice(start, client.indexOf('\n}\n', start)); + assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); + } + assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); +}); + // Tags must not go through keepLocal: the server's tag updated_at is its // created_at (no updatedAt column), so a local rename would always look newer // (PR #157 review). syncClient.ts cannot load under node, hence a source check. @@ -195,9 +259,10 @@ check('applyTagChange never keeps a local tag (no keepLocal)', () => { // The push bounds of #151 are executed by tests/syncRules.test.mjs, but the // options each caller passes to sendInBatches live in syncClient.ts, which -// node cannot load. Lock them by source: pushChanges sends 8 batches at most -// and never waits on a 429 (the rate limit is the budget of a fullSync), -// initialMerge sends every batch and waits for the Retry-After. +// node cannot load. Lock them by source: pushChanges sends the batches the +// scheduler allows, 8 at most, and never waits on a 429 (the scheduler is +// suspended instead, #178), initialMerge sends every batch and waits for the +// Retry-After. check('syncClient.ts passes the #151 push bounds to sendInBatches', () => { const src = fs.readFileSync(path.join(__dirname, '..', 'src/services/syncClient.ts'), 'utf8'); const body = (name) => { @@ -212,10 +277,13 @@ check('syncClient.ts passes the #151 push bounds to sendInBatches', () => { return m[0]; }; const push = call('pushChanges'); - assert.match(push, /maxBatches: MAX_PUSH_BATCHES,/); + // #178: the scheduler's budget, MAX_PUSH_BATCHES as a ceiling + assert.match(body('pushChanges'), /const maxBatches = Math\.max\(0, Math\.min\(run\.pushBatches, MAX_PUSH_BATCHES\)\);/); + assert.match(push, /\n\s*maxBatches,\n/); assert.match(push, /retryOn429: false,/); assert.match(push, /size: BATCH_SIZE,/); const merge = call('initialMerge'); + assert.match(body('initialMerge'), /await mergeLocalData\(\);/); assert.match(merge, /maxBatches: Infinity,/); assert.match(merge, /retryOn429: true,/); assert.match(merge, /size: BATCH_SIZE,/); @@ -262,14 +330,15 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { assert.match(tag, /pulledTagValues\(id, payload, local\)/); assert.ok(!/\bkeepLocal\b|writeOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); // #150: lastSyncAt goes back to SYNC_EPOCH before the full pull, never after - const merge = fn('initialMerge'); + const merge = fn('mergeLocalData'); const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)'); - const pull = merge.indexOf('await pullChanges(SYNC_EPOCH)'); + const pull = merge.indexOf('await pullChanges(SYNC_EPOCH, scheduler.tracker)'); assert.ok(stamp >= 0 && pull >= 0 && stamp < pull, 'initialMerge: setLastSyncAt(SYNC_EPOCH) then await pullChanges(SYNC_EPOCH)'); assert.ok(!/setLastSyncAt\(new Date\(/.test(merge), 'initialMerge must not stamp the device time'); // #151: the push marks the batches that succeeded even when a later one failed const push = fn('pushChanges'); - assert.match(push, /const \{ results \} = await sendInBatches\(/); + // #178: `ok` only tells whether the budget left entries unsent, after the marking + assert.match(push, /const \{ results, ok \} = await sendInBatches\(/); const between = push.slice(push.indexOf('await sendInBatches('), push.indexOf('classifyOutbox(unsynced, results,')); assert.ok(!/\breturn\b|results\.length|\bok\b/.test(between), 'pushChanges must classify the results of every successful batch'); assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/); @@ -354,8 +423,10 @@ check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => { assert.ok(r >= 0 && e > r, '_layout.tsx must call repairInbox() before ensureInbox()'); assert.match(layout.slice(r, e), /\.catch\(/, 'a failed repair must not stop the startup'); assert.match(layout, /if \(!inboxSetup\) \{\s*inboxSetup = repairInbox\(\)/, 'the Inbox setup runs once per process'); - assert.match(layout, /prepareInbox\(\)\.then\(\(\) => fullSync\(\)\)/, 'the first sync must wait for the Inbox setup'); - assert.ok(!/\n\s*fullSync\(\)\.then\(\(\) => cleanOutbox\(\)\)\.catch\(\(\) => \{\}\);\n\n\s*\/\/ 2-minute/.test(layout), 'no ungated initial sync'); + // #178: the first sync and the sync on write wait for the Inbox setup + assert.match(layout, /prepareInbox\(\)\.then\(\(\) => \{\s*if \(!active\) return;\s*setSyncSubscriber\([^]*?return scheduleSync\(\);/, 'the first sync must wait for the Inbox setup'); + const content = layout.slice(layout.indexOf('function AppContent(')); + assert.equal((content.match(/scheduleSync\(\)/g) || []).length, (content.match(/prepareInbox\(\)\.then\(/g) || []).length + 1, 'no ungated sync'); // initialReset on an account without Inbox pushes a new one, never the fixed id const client = read('src/services/syncClient.ts'); const reset = client.slice(client.indexOf('export async function initialReset('), client.indexOf('export async function cleanOutbox(')); diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs new file mode 100644 index 0000000..0a3af67 --- /dev/null +++ b/tests/syncSchedule.test.mjs @@ -0,0 +1,338 @@ +// Execution tests for the sync scheduler and the sync-on-write trigger (#178). +// Runs on plain node via the built-in test runner + native TS type-stripping: +// +// node --test tests/syncSchedule.test.mjs +// +// syncSchedule.ts and syncTrigger.ts stay import-free so that node loads them +// (zero-import guards in smoke.test.cjs). The scheduler gets a fake clock; +// the trigger runs on node's mocked timers. + +import { test, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import { + BUDGET_WINDOW_MS, + DEFAULT_RETRY_AFTER_S, + REQUEST_BUDGET, + createSyncScheduler, +} from '../src/services/syncSchedule.ts'; +import { SYNC_DEBOUNCE_MS, requestSync, setSyncSubscriber } from '../src/services/syncTrigger.ts'; + +// Fake clock: timers fire in time order when the clock advances. +function fakeClock() { + let now = 0; + let timers = []; + return { + now: () => now, + setTimer: (fn, ms) => { + timers.push({ at: now + ms, fn }); + }, + pending: () => timers.length, + async advance(ms) { + const end = now + ms; + for (;;) { + await flush(); + timers.sort((a, b) => a.at - b.at); + const next = timers[0]; + if (!next || next.at > end) break; + timers.shift(); + now = next.at; + next.fn(); + } + now = end; + await flush(); + }, + }; +} + +async function flush() { + for (let i = 0; i < 20; i++) await Promise.resolve(); +} + +// A server stand-in: a queue of POST batches, each run pushes up to +// ctx.pushBatches of them then pulls once. Records every request time. +function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {}) { + const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [] }; + state.run = async (ctx) => { + state.runs++; + state.starts.push(clock.now()); + state.active++; + state.maxActive = Math.max(state.maxActive, state.active); + try { + if (duration) await new Promise((resolve) => clock.setTimer(resolve, duration)); + let sent = 0; + while (state.queue > 0 && sent < ctx.pushBatches) { + ctx.request(); + state.requests.push(clock.now()); + sent++; + const s = status('POST'); + if (s === 429) { + ctx.rateLimited(20); + return { more: true }; + } + state.queue--; + } + if (ctx.isSuspended()) return { more: state.queue > 0 }; + ctx.request(); + state.requests.push(clock.now()); + const s = status('GET'); + if (s === 429) ctx.rateLimited(20); + return { more: state.queue > 0 }; + } finally { + state.active--; + } + }; + return state; +} + +function maxInAnyWindow(times) { + let max = 0; + for (const t of times) { + const n = times.filter((u) => u >= t && u < t + BUDGET_WINDOW_MS).length; + max = Math.max(max, n); + } + return max; +} + +test('a burst of 10 requestSync() in 2 s gives a single sync', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + let syncs = 0; + setSyncSubscriber(() => { + syncs++; + }); + for (let i = 0; i < 10; i++) { + requestSync(); + mock.timers.tick(200); + } + assert.equal(syncs, 0, 'nothing before the debounce delay'); + mock.timers.tick(SYNC_DEBOUNCE_MS); + assert.equal(syncs, 1); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 1); + } finally { + setSyncSubscriber(null); + mock.timers.reset(); + } +}); + +test('requestSync without a subscriber does nothing (headless widget, sync off)', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + let syncs = 0; + requestSync(); + setSyncSubscriber(() => { + syncs++; + }); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 0, 'a request made before the subscription is not kept'); + requestSync(); + setSyncSubscriber(null); + mock.timers.tick(10 * SYNC_DEBOUNCE_MS); + assert.equal(syncs, 0, 'removing the subscriber drops the pending request'); + } finally { + setSyncSubscriber(null); + mock.timers.reset(); + } +}); + +test('never two syncs at once; a request during a sync gives exactly one more run', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.equal(server.runs, 1); + // Three requests while the first run is in flight + s.request(); + s.request(); + s.request(); + await clock.advance(500); + assert.equal(server.runs, 1, 'no second run while the first one is in flight'); + await clock.advance(10_000); + assert.equal(server.runs, 2, 'exactly one relaunch'); + assert.equal(server.maxActive, 1); + await clock.advance(120_000); + assert.equal(server.runs, 2, 'no run without a request'); +}); + +test('request() resolves when the run that serves it ends', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + let first = false; + let second = false; + s.request().then(() => (first = true)); + await flush(); + s.request().then(() => (second = true)); + await clock.advance(1000); + assert.equal(first, true); + assert.equal(second, false, 'a request made during a run waits for the next one'); + await clock.advance(1000); + assert.equal(second, true); +}); + +test('at most REQUEST_BUDGET requests in any 60 s window; 9 batches spread over several syncs', async () => { + assert.equal(REQUEST_BUDGET, 6); + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await clock.advance(1000); + assert.equal(server.runs, 1); + assert.equal(server.queue, 4, 'the first sync sends 5 batches and keeps a place for its GET'); + // Requests keep coming every 5 s (writes, interval) + for (let i = 0; i < 60; i++) { + s.request(); + await clock.advance(5000); + } + assert.equal(server.queue, 0, 'the rest of the queue left with later syncs'); + assert.ok(server.runs >= 2); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); +}); + +test('an unsent queue is resumed without a new request once the budget allows', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 1, 'the second run waits for the window'); + await clock.advance(2); + assert.equal(server.runs, 2); + assert.equal(server.queue, 0); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET); +}); + +test('after a 429 with Retry-After: 20, no request before 20 s', async () => { + const clock = fakeClock(); + let first = true; + const server = fakeServer(clock, { + batches: 2, + status: () => { + if (first) { + first = false; + return 429; + } + return 200; + }, + }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.deepEqual(server.requests, [0], 'the run stops at the 429, no pull after it'); + for (let t = 1000; t < 20_000; t += 1000) { + s.request(); + await clock.advance(1000); + } + assert.ok(server.requests.every((t) => t === 0 || t >= 20_000), `requests at ${server.requests}`); + await clock.advance(2000); + assert.ok(server.requests.some((t) => t >= 20_000), 'the scheduler resumes after Retry-After'); + assert.equal(server.queue, 0); +}); + +test('a 429 without a readable Retry-After suspends for the default delay', async () => { + const clock = fakeClock(); + let starts = 0; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: async (ctx) => { + starts++; + ctx.request(); + ctx.rateLimited(null); + }, + }); + s.request(); + await clock.advance(DEFAULT_RETRY_AFTER_S * 1000 - 1); + assert.equal(starts, 1); + await clock.advance(1); + assert.equal(starts, 2); +}); + +test('a 429 reported outside a run (initial sync) also suspends the scheduler', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.request(); + s.tracker.rateLimited(20); + s.request(); + await clock.advance(19_999); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('requests sent outside a run (initial sync) count against the budget', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + for (let i = 0; i < REQUEST_BUDGET; i++) s.tracker.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('a request during the first-sync state runs after its end, not before', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + await s.beginInitialSync(); + let done = false; + s.request().then(() => (done = true)); + await clock.advance(5 * BUDGET_WINDOW_MS); + assert.equal(server.runs, 0, 'no sync during initialMerge / initialReset'); + assert.equal(done, false); + s.endInitialSync(); + await flush(); + assert.equal(server.runs, 1); + assert.equal(done, true); +}); + +test('beginInitialSync waits for the run in flight', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + let entered = false; + s.beginInitialSync().then(() => (entered = true)); + await flush(); + assert.equal(entered, false); + await clock.advance(1000); + assert.equal(entered, true); + s.endInitialSync(); +}); + +test('the guard drops requests and resolves them', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + let allowed = false; + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run, canRun: () => allowed }); + let done = false; + s.request().then(() => (done = true)); + await clock.advance(BUDGET_WINDOW_MS); + assert.equal(server.runs, 0); + assert.equal(done, true); + allowed = true; + s.request(); + await flush(); + assert.equal(server.runs, 1); +}); + +test('a failing run releases the scheduler', async () => { + const clock = fakeClock(); + let runs = 0; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: async () => { + runs++; + throw new Error('boom'); + }, + }); + await s.request(); + await s.request(); + assert.equal(runs, 2); +});