diff --git a/REVIEW.md b/REVIEW.md index df3c3d7..a607416 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -90,9 +90,9 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm ### API et isolation des comptes - Toute lecture et toute écriture filtrent sur `userId = auth.userId` ; une mise à jour ou une suppression vérifie d'abord la propriété (`verifyOwnership`). Une jointure (étiquettes d'une tâche) vérifie la propriété des deux côtés. — `web/src/app/api/sync/route.ts`, `web/src/app/api/tasks/[id]/route.ts` -- Le corps est validé par un schéma zod `.strict()`. Exception : `data` d'une opération de sync passe par un schéma par entité et par action (`web/src/lib/syncData.ts`), sans `.strict()` : les clés hors liste sont retirées, pas rejetées, parce que l'app marque son outbox comme synchronisée dès que le push répond 200 et qu'une opération `skipped` serait perdue. Ces schémas ne nomment jamais `id`, `userId`, `createdAt`, `updatedAt` ni `deletedAt`, et `processOperation` n'écrit que leur sortie. Une colonne ajoutée côté app l'est aussi dans le schéma, sinon elle est ignorée en silence. — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts`, #142 +- Le corps est validé par un schéma zod `.strict()`. Exception : `data` d'une opération de sync passe par un schéma par entité et par action (`web/src/lib/syncData.ts`), sans `.strict()` : les clés hors liste sont retirées, pas rejetées, parce que les versions de l'app antérieures à #151 marquent leur outbox comme synchronisée dès que le push répond 200 et qu'une opération `skipped` y serait perdue ; depuis #151, l'app ne marque que les opérations appliquées ou en doublon. Ces schémas ne nomment jamais `id`, `userId`, `createdAt`, `updatedAt` ni `deletedAt`, et `processOperation` n'écrit que leur sortie. Une colonne ajoutée côté app l'est aussi dans le schéma, sinon elle est ignorée en silence. — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts`, #142 - Une référence reçue du client (`listId`, `parentId`, `tagId`, l'id d'une liste créée) est vérifiée contre le compte de l'appelant avant l'écriture. `parentId` et l'id d'une création refusent seulement un id pris par un autre compte, sans exiger que la ligne existe : `initialMerge` pousse tout en un lot, une sous-tâche peut arriver avant son parent. — `web/src/app/api/sync/route.ts`, #142 -- Un lot de sync compte au plus 200 opérations (`SYNC_MAX_OPERATIONS`) et l'app en envoie 50 (`batchSize`) : une montée de `batchSize` se juge contre cette borne et contre la limite `sync` (10 requêtes par minute, GET et POST confondus), et le companion se déploie avant l'app. — `web/src/lib/validators.ts`, `src/services/syncClient.ts`, #147 +- Un lot de sync compte au plus 200 opérations (`SYNC_MAX_OPERATIONS`) et l'app en envoie 50 (`BATCH_SIZE`) : une montée de `BATCH_SIZE` se juge contre cette borne et contre la limite `sync` (10 requêtes par minute, GET et POST confondus), et le companion se déploie avant l'app. — `web/src/lib/validators.ts`, `src/services/syncRules.ts`, #147 - Tout tableau d'un schéma de requête a sa longueur contrôlée avant ses éléments (`z.array(z.unknown()).max(n).pipe(…)`) : zod valide chaque élément avant la longueur, et un tableau hostile produit un issue par élément. — `web/src/lib/validators.ts`, #147 - `parseBody` ne renvoie que le premier issue d'une erreur zod, et au plus 200 caractères. — `web/src/lib/api.ts`, #147 - Les clés d'idempotence sont des UUID, 5 000 au plus par compte, la plus ancienne évincée au-delà (`idempotency.ts`) : une clé évincée rejouée réapplique son opération. — `web/src/lib/idempotency.ts`, `web/src/app/api/sync/route.ts`, #147 @@ -114,6 +114,10 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - 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 +- 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 - 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/src/services/syncClient.ts b/src/services/syncClient.ts index f053d20..20b5144 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -1,4 +1,4 @@ -import { eq, isNull, not } from 'drizzle-orm'; +import { asc, eq, inArray, isNull, not } from 'drizzle-orm'; import { db } from '@/src/db/client'; import { syncOutbox, lists, tasks, tags, taskTags } from '@/src/db/schema'; import { useSettingsStore } from '@/src/stores/useSettingsStore'; @@ -16,6 +16,12 @@ import { taskUpdatePayload, tagUpdatePayload, mergeTaskData, + BATCH_SIZE, + MAX_PUSH_BATCHES, + classifyOutbox, + isSynced, + sendInBatches, + type PostResponse, } from '@/src/services/syncRules'; const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com'; @@ -52,32 +58,38 @@ async function getAuthHeaders(): Promise> { } /** - * Send a batch of operations to the server sync endpoint. + * POST one batch of operations to the server sync endpoint. Retry-After is + * read in seconds; the body is parsed only on a 2xx. */ -async function sendOperations(operations: SyncOperation[], headers: Record): Promise { - const batchSize = 50; - for (let i = 0; i < operations.length; i += batchSize) { - const batch = operations.slice(i, i + batchSize); - try { - const res = await fetch(`${SYNC_API_BASE}/api/sync`, { - method: 'POST', - headers, - body: JSON.stringify({ operations: batch }), - }); - if (!res.ok) { - console.warn(`[sync] push failed with status ${res.status}`); - return false; - } - } catch (err) { - console.warn('[sync] push error:', err); - return false; +async function postBatch(batch: SyncOperation[], headers: Record): Promise { + try { + const res = await fetch(`${SYNC_API_BASE}/api/sync`, { + method: 'POST', + headers, + body: JSON.stringify({ operations: batch }), + }); + if (!res.ok) { + console.warn(`[sync] push failed with status ${res.status}`); + const header = Number(res.headers.get('Retry-After')); + return { status: res.status, retryAfter: Number.isFinite(header) && header >= 0 ? header : null, body: null }; } + const body = await res.json().catch(() => null); + return { status: res.status, retryAfter: null, body }; + } catch (err) { + console.warn('[sync] push error:', err); + throw err; } - return true; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); } /** - * Push unsynced outbox entries to the server. + * 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). */ export async function pushChanges(): Promise { const headers = await getAuthHeaders(); @@ -86,7 +98,9 @@ export async function pushChanges(): Promise { const unsynced = await db .select() .from(syncOutbox) - .where(isNull(syncOutbox.syncedAt)); + .where(isNull(syncOutbox.syncedAt)) + // Creation order: replayed refusals go before the entries that replace them + .orderBy(asc(syncOutbox.createdAt)); if (unsynced.length === 0) return; @@ -101,16 +115,25 @@ export async function pushChanges(): Promise { }; }); - const ok = await sendOperations(operations, headers); - if (ok) { - const now = new Date().toISOString(); - for (const entry of unsynced) { - await db - .update(syncOutbox) - .set({ syncedAt: now }) - .where(eq(syncOutbox.id, entry.id)); - } - // Refresh widget after a successful push to reflect the synced state + const { results } = await sendInBatches(operations, { + size: BATCH_SIZE, + maxBatches: MAX_PUSH_BATCHES, + retryOn429: false, + post: (batch) => postBatch(batch, headers), + sleep, + }); + + const now = new Date(); + const { markIds, droppedRefusals, droppedByType } = classifyOutbox(unsynced, results, now); + if (droppedRefusals > 0) { + console.warn(`[sync] dropped ${droppedRefusals} refused operation(s):`, JSON.stringify(droppedByType)); + } + if (markIds.length > 0) { + await db + .update(syncOutbox) + .set({ syncedAt: now.toISOString() }) + .where(inArray(syncOutbox.id, markIds)); + // Refresh widget after a push that synced entries syncWidgetData().catch(() => {}); } } @@ -361,11 +384,23 @@ export async function initialMerge(): Promise { }); } - // 7. Send to server - const ok = await sendOperations(operations, headers); + // 7. Send to server, every batch, waiting for the Retry-After of a 429 + const { ok, results } = await sendInBatches(operations, { + size: BATCH_SIZE, + maxBatches: Infinity, + retryOn429: true, + post: (batch) => postBatch(batch, headers), + sleep, + }); if (!ok) { throw new Error('Failed to push local data to server'); } + // Refused operations are not retried: the merge goes on, the pull below + // brings down the server state. + const refused = results.filter((r) => !isSynced(r)).length; + if (refused > 0) { + console.warn(`[sync] initial merge: ${refused} operation(s) refused by the server`); + } // 8. Remap local Inbox ID to match the server if (localInbox) { diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index 7fca806..2f1e893 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -186,3 +186,221 @@ export function tagUpdatePayload(tag: TagRow): Payload { color: tag.color, }; } + +// --------------------------------------------------------------------------- +// Push: batching, server results and outbox classification (#151) +// --------------------------------------------------------------------------- + +/** 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. + */ +export const MAX_PUSH_BATCHES = 8; +/** Refused operations kept in the outbox for a replay, the most recent first. */ +export const MAX_KEPT_REFUSALS = 100; +/** Age after which a refused operation is dropped from the outbox. */ +export const REJECTED_RETENTION_DAYS = 30; +/** Upper bound of the Retry-After wait of a 429, in seconds. */ +export const RETRY_AFTER_MAX_S = 60; +/** Resends of the same batch after a 429 (initialMerge only). */ +export const MAX_429_RETRIES = 3; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** One element of the `results` array returned by POST /api/sync. */ +export interface PushResult { + idempotencyKey: string; + status: string; + error?: string; +} + +/** + * The `results` array of a POST /api/sync response, or null when the body + * has another shape (no array, or an element without string idempotencyKey + * and status, or with a non-string error). + */ +export function parseResults(body: unknown): PushResult[] | null { + if (!body || typeof body !== 'object') return null; + const results = (body as { results?: unknown }).results; + if (!Array.isArray(results)) return null; + const out: PushResult[] = []; + for (const item of results) { + if (!item || typeof item !== 'object') return null; + const { idempotencyKey, status, error } = item as Record; + if (typeof idempotencyKey !== 'string' || typeof status !== 'string') return null; + if (error !== undefined && typeof error !== 'string') return null; + out.push(error === undefined ? { idempotencyKey, status } : { idempotencyKey, status, error }); + } + return out; +} + +/** + * True when the server holds the operation: written (`applied`), or a key it + * has already seen (`skipped` without `error`). A `skipped` with an `error` + * is a refusal. + */ +export function isSynced(result: PushResult): boolean { + return result.status === 'applied' || (result.status === 'skipped' && result.error === undefined); +} + +function isRefusal(result: PushResult): boolean { + return result.status === 'skipped' && result.error !== undefined; +} + +/** Outbox row fields read by classifyOutbox. */ +export interface OutboxEntry { + id: string; + createdAt: string; + entityType: string; + entityId: string; + payload: string; +} + +export interface OutboxClassification { + /** Entries to mark as synced: synced ones and dropped refusals. */ + markIds: string[]; + /** Refusals left unmarked, replayed by the next push. */ + keptRefusals: number; + /** Refusals marked without having been applied. */ + droppedRefusals: number; + /** Dropped refusals counted by entity type, for the log. */ + droppedByType: Record; +} + +// Entity a outbox entry writes: a task-tag link is one tag of one task. +function entityKey(entry: OutboxEntry): string { + const base = `${entry.entityType}:${entry.entityId}`; + if (entry.entityType !== 'taskTag') return base; + let tagId: unknown; + try { + tagId = (JSON.parse(entry.payload) as Payload | null)?.tagId; + } catch { + tagId = undefined; + } + return `${base}:${String(tagId)}`; +} + +/** + * Split the entries of one push by the server results. Marked: every synced + * entry, and every refusal that is older than REJECTED_RETENTION_DAYS, or + * replaced by a more recent entry of the same entity synced in this push, or + * outside the MAX_KEPT_REFUSALS most recent remaining refusals. An entry + * without a result (batch not sent or failed) is left unmarked. + * + * The replacement rule holds because refusals are replayed at every push, in + * creation order, before the more recent entries: do not space the replays + * out without revisiting it. + */ +export function classifyOutbox( + entries: OutboxEntry[], + results: PushResult[], + now: Date | number, +): OutboxClassification { + const nowMs = new Date(now).getTime(); + const byKey = new Map(); + for (const r of results) byKey.set(r.idempotencyKey, r); + + const markIds: string[] = []; + const refusals: { entry: OutboxEntry; time: number; key: string }[] = []; + // Most recent createdAt of a synced entry, per entity + const latestSynced = new Map(); + + for (const entry of entries) { + const result = byKey.get(entry.id); + if (!result) continue; + const time = new Date(entry.createdAt).getTime(); + const key = entityKey(entry); + if (isSynced(result)) { + markIds.push(entry.id); + const prev = latestSynced.get(key); + if (prev === undefined || time > prev) latestSynced.set(key, time); + } else if (isRefusal(result)) { + refusals.push({ entry, time, key }); + } + } + + const dropped: OutboxEntry[] = []; + const remaining: { entry: OutboxEntry; time: number }[] = []; + for (const r of refusals) { + const expired = nowMs - r.time > REJECTED_RETENTION_DAYS * DAY_MS; + const replacedAt = latestSynced.get(r.key); + const replaced = replacedAt !== undefined && replacedAt > r.time; + if (expired || replaced) dropped.push(r.entry); + else remaining.push(r); + } + + // Keep the most recent refusals only + remaining.sort((a, b) => b.time - a.time); + for (const r of remaining.slice(MAX_KEPT_REFUSALS)) dropped.push(r.entry); + const keptRefusals = Math.min(remaining.length, MAX_KEPT_REFUSALS); + + const droppedByType: Record = {}; + for (const entry of dropped) { + markIds.push(entry.id); + droppedByType[entry.entityType] = (droppedByType[entry.entityType] ?? 0) + 1; + } + + return { markIds, keptRefusals, droppedRefusals: dropped.length, droppedByType }; +} + +/** Response of one POST, as seen by sendInBatches. */ +export interface PostResponse { + status: number; + /** Retry-After header in seconds, null when absent or unreadable. */ + retryAfter: number | null; + body: unknown; +} + +export interface SendOptions { + size: number; + maxBatches: number; + retryOn429: boolean; + post: (batch: T[]) => Promise; + sleep: (ms: number) => Promise; +} + +/** + * Send `ops` in batches of `size`, `maxBatches` batches at most. Stops at + * the first failure: a thrown post, a non-2xx response (a 429 is waited for + * and the same batch resent, MAX_429_RETRIES times at most, only with + * retryOn429), or a 2xx body without a valid `results` array. `ok` is false + * after a failure, true otherwise (also when maxBatches left ops unsent). + * `results` gathers the results of the successful batches. + */ +export async function sendInBatches( + ops: T[], + { size, maxBatches, retryOn429, post, sleep }: SendOptions, +): Promise<{ ok: boolean; results: PushResult[] }> { + const results: PushResult[] = []; + let sent = 0; + for (let i = 0; i < ops.length && sent < maxBatches; i += size) { + sent++; + const batch = ops.slice(i, i + size); + let retries = 0; + for (;;) { + let res: PostResponse; + try { + res = await post(batch); + } catch { + return { ok: false, results }; + } + if (res.status >= 200 && res.status < 300) { + const parsed = parseResults(res.body); + if (!parsed) return { ok: false, results }; + results.push(...parsed); + break; + } + if (res.status === 429 && retryOn429 && retries < MAX_429_RETRIES) { + retries++; + const waitS = Math.max(0, Math.min(res.retryAfter ?? RETRY_AFTER_MAX_S, RETRY_AFTER_MAX_S)); + await sleep(waitS * 1000); + continue; + } + return { ok: false, results }; + } + } + return { ok: true, results }; +} diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index a8a68a9..b01c88a 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -181,6 +181,36 @@ check('syncRules.ts stays import-free (protects type-stripping test path)', () = ); }); +// 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. +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) => { + const start = src.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + const end = src.indexOf('\nexport ', start + 1); + return src.slice(start, end < 0 ? undefined : end); + }; + const call = (name) => { + const m = body(name).match(/sendInBatches\([^]*?\}\);/); + assert.ok(m, `${name} does not call sendInBatches`); + return m[0]; + }; + const push = call('pushChanges'); + assert.match(push, /maxBatches: MAX_PUSH_BATCHES,/); + assert.match(push, /retryOn429: false,/); + assert.match(push, /size: BATCH_SIZE,/); + const merge = call('initialMerge'); + assert.match(merge, /maxBatches: Infinity,/); + assert.match(merge, /retryOn429: true,/); + assert.match(merge, /size: BATCH_SIZE,/); + assert.match(body('pushChanges'), /\.orderBy\(asc\(syncOutbox\.createdAt\)\)/); + assert.match(body('pushChanges'), /classifyOutbox\(unsynced, results,/); +}); + // --- Build toolchain guards --- // A blanket `npm audit fix` (PR #118) once rewrote hundreds of lock entries: // babel-preset-expo and @expo/metro-config lost their root hoisting and a diff --git a/tests/syncRules.test.mjs b/tests/syncRules.test.mjs index c3943fd..c128a42 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -19,6 +19,16 @@ import { taskUpdatePayload, tagUpdatePayload, mergeTaskData, + BATCH_SIZE, + MAX_PUSH_BATCHES, + MAX_KEPT_REFUSALS, + REJECTED_RETENTION_DAYS, + RETRY_AFTER_MAX_S, + MAX_429_RETRIES, + parseResults, + isSynced, + classifyOutbox, + sendInBatches, } from '../src/services/syncRules.ts'; const ID = '11111111-1111-4111-8111-111111111111'; @@ -239,3 +249,229 @@ test('mergeTaskData takes listId from its parameter and keeps parentId', () => { assert.notEqual(data.listId, task.listId); assert.equal(data.parentId, LIST_ID); }); + +// --------------------------------------------------------------------------- +// Push results and outbox classification (#151) +// --------------------------------------------------------------------------- + +const NOW = new Date('2026-10-24T12:00:00.000Z'); +const DAY = 24 * 60 * 60 * 1000; +const ago = (ms) => new Date(NOW.getTime() - ms).toISOString(); +const REFUSED = 'Entity not found or access denied'; + +let seq = 0; +const entry = (over = {}) => { + seq++; + return { + id: `e${seq}`, + createdAt: ago(60_000), + entityType: 'task', + entityId: `task-${seq}`, + payload: '{}', + ...over, + }; +}; +const applied = (e) => ({ idempotencyKey: e.id, status: 'applied' }); +const duplicate = (e) => ({ idempotencyKey: e.id, status: 'skipped' }); +const refused = (e) => ({ idempotencyKey: e.id, status: 'skipped', error: REFUSED }); + +test('push constants match the planned bounds', () => { + assert.deepEqual( + [BATCH_SIZE, MAX_PUSH_BATCHES, MAX_KEPT_REFUSALS, REJECTED_RETENTION_DAYS, RETRY_AFTER_MAX_S, MAX_429_RETRIES], + [50, 8, 100, 30, 60, 3], + ); +}); + +test('isSynced: applied and skipped without error, not skipped with error', () => { + assert.equal(isSynced({ idempotencyKey: 'k', status: 'applied' }), true); + assert.equal(isSynced({ idempotencyKey: 'k', status: 'skipped' }), true); + assert.equal(isSynced({ idempotencyKey: 'k', status: 'skipped', error: REFUSED }), false); + assert.equal(isSynced({ idempotencyKey: 'k', status: 'skipped', error: '' }), false); +}); + +test('classifyOutbox: applied and duplicate marked, recent refusal kept, old refusal dropped', () => { + const a = entry(); + const d = entry(); + const recent = entry({ createdAt: ago(29 * DAY) }); + const old = entry({ createdAt: ago(31 * DAY) }); + const c = classifyOutbox([a, d, recent, old], [applied(a), duplicate(d), refused(recent), refused(old)], NOW); + assert.deepEqual([...c.markIds].sort(), [a.id, d.id, old.id].sort()); + assert.equal(c.keptRefusals, 1); + assert.equal(c.droppedRefusals, 1); + assert.deepEqual(c.droppedByType, { task: 1 }); +}); + +test('classifyOutbox: an entry without a result is not marked', () => { + const sent = entry(); + const unsent = entry(); + const c = classifyOutbox([sent, unsent], [applied(sent)], NOW); + assert.deepEqual(c.markIds, [sent.id]); + assert.equal(c.keptRefusals, 0); + assert.equal(c.droppedRefusals, 0); +}); + +test('classifyOutbox: a refusal replaced by a newer synced entry of the same entity is dropped', () => { + const r = entry({ entityId: 'T', createdAt: ago(2 * DAY) }); + const newer = entry({ entityId: 'T', createdAt: ago(DAY) }); + const c = classifyOutbox([r, newer], [refused(r), applied(newer)], NOW); + assert.deepEqual([...c.markIds].sort(), [r.id, newer.id].sort()); + assert.equal(c.droppedRefusals, 1); + assert.equal(c.keptRefusals, 0); +}); + +test('classifyOutbox: replacement needs the same entity, a newer entry and a synced one', () => { + const r = entry({ entityId: 'T', createdAt: ago(2 * DAY) }); + // Other entity, same type + const other = entry({ entityId: 'U', createdAt: ago(DAY) }); + // Same id, other type + const otherType = entry({ entityType: 'list', entityId: 'T', createdAt: ago(DAY) }); + // Same entity, but older than the refusal + const older = entry({ entityId: 'T', createdAt: ago(3 * DAY) }); + // Same entity, newer, but refused too + const refusedNewer = entry({ entityId: 'T', createdAt: ago(DAY) }); + const c = classifyOutbox( + [older, r, other, otherType, refusedNewer], + [applied(older), refused(r), applied(other), applied(otherType), refused(refusedNewer)], + NOW, + ); + assert.deepEqual([...c.markIds].sort(), [older.id, other.id, otherType.id].sort()); + assert.equal(c.keptRefusals, 2); +}); + +test('classifyOutbox: a task-tag refusal is replaced only by the same tagId', () => { + const r = entry({ entityType: 'taskTag', entityId: 'T', payload: '{"tagId":"g1"}', createdAt: ago(2 * DAY) }); + const otherTag = entry({ entityType: 'taskTag', entityId: 'T', payload: '{"tagId":"g2"}', createdAt: ago(DAY) }); + let c = classifyOutbox([r, otherTag], [refused(r), applied(otherTag)], NOW); + assert.deepEqual(c.markIds, [otherTag.id]); + assert.equal(c.keptRefusals, 1); + + const sameTag = entry({ entityType: 'taskTag', entityId: 'T', payload: '{"tagId":"g1"}', createdAt: ago(DAY) }); + c = classifyOutbox([r, sameTag], [refused(r), applied(sameTag)], NOW); + assert.deepEqual([...c.markIds].sort(), [r.id, sameTag.id].sort()); + assert.deepEqual(c.droppedByType, { taskTag: 1 }); +}); + +test('classifyOutbox: 500 refusals keep the 100 most recent and drop 400', () => { + const entries = Array.from({ length: 500 }, (_, i) => entry({ createdAt: ago((i + 1) * 60_000) })); + const c = classifyOutbox(entries, entries.map(refused), NOW); + assert.equal(c.keptRefusals, 100); + assert.equal(c.droppedRefusals, 400); + // entries[0..99] are the most recent: none of them is marked + const marked = new Set(c.markIds); + assert.equal(entries.slice(0, 100).some((e) => marked.has(e.id)), false); + assert.equal(entries.slice(100).every((e) => marked.has(e.id)), true); +}); + +test('parseResults: the results array, or null for another shape', () => { + const ok = { results: [ + { idempotencyKey: 'a', status: 'applied' }, + { idempotencyKey: 'b', status: 'skipped', error: REFUSED }, + ], syncedAt: NOW.toISOString() }; + assert.deepEqual(parseResults(ok), ok.results); + assert.deepEqual(parseResults({ results: [] }), []); + assert.equal(parseResults(null), null); + assert.equal(parseResults({}), null); + assert.equal(parseResults({ results: 'x' }), null); + assert.equal(parseResults({ results: [{ idempotencyKey: 'a' }] }), null); + assert.equal(parseResults({ results: [{ status: 'applied' }] }), null); + assert.equal(parseResults({ results: [{ idempotencyKey: 1, status: 'applied' }] }), null); + assert.equal(parseResults({ results: [{ idempotencyKey: 'a', status: 'skipped', error: 42 }] }), null); + assert.equal(parseResults({ results: [{ idempotencyKey: 'a', status: 'applied' }, null] }), null); +}); + +// Fake transport: one response (or thrown error) per call, in order. +function transport(responses) { + const calls = []; + const sleeps = []; + return { + calls, + sleeps, + post: async (batch) => { + calls.push(batch); + const next = responses.length > 1 ? responses.shift() : responses[0]; + if (next instanceof Error) throw next; + return typeof next === 'function' ? next(batch) : next; + }, + sleep: async (ms) => { sleeps.push(ms); }, + }; +} +const okFor = (batch) => ({ + status: 200, + retryAfter: null, + body: { results: batch.map((k) => ({ idempotencyKey: k, status: 'applied' })) }, +}); +const keys = (n) => Array.from({ length: n }, (_, i) => `k${i}`); +const opts = (t, over = {}) => ({ size: 50, maxBatches: Infinity, retryOn429: false, post: t.post, sleep: t.sleep, ...over }); + +test('sendInBatches: batches of size, results of every batch', async () => { + const t = transport([okFor]); + const r = await sendInBatches(keys(120), opts(t)); + assert.equal(r.ok, true); + assert.deepEqual(t.calls.map((b) => b.length), [50, 50, 20]); + assert.equal(r.results.length, 120); +}); + +test('sendInBatches: batch 2 fails, the results of batch 1 are returned and ok is false', async () => { + const t = transport([okFor, { status: 500, retryAfter: null, body: null }, okFor]); + const r = await sendInBatches(keys(150), opts(t)); + assert.equal(r.ok, false); + assert.equal(t.calls.length, 2); + assert.deepEqual(r.results.map((x) => x.idempotencyKey), keys(50)); +}); + +test('sendInBatches: a thrown post stops the send', async () => { + const t = transport([okFor, new Error('network'), okFor]); + const r = await sendInBatches(keys(150), opts(t)); + assert.equal(r.ok, false); + assert.equal(t.calls.length, 2); + assert.equal(r.results.length, 50); +}); + +test('sendInBatches: a 200 with an unexpected body stops the send', async () => { + const t = transport([{ status: 200, retryAfter: null, body: { ok: true } }, okFor]); + const r = await sendInBatches(keys(100), opts(t)); + assert.equal(r.ok, false); + assert.equal(t.calls.length, 1); + assert.deepEqual(r.results, []); +}); + +test('sendInBatches: a 429 with retryOn429 sleeps the bounded Retry-After and resends the same batch', async () => { + const t = transport([ + okFor, + { status: 429, retryAfter: 7, body: null }, + { status: 429, retryAfter: 600, body: null }, + { status: 429, retryAfter: null, body: null }, + okFor, + ]); + const r = await sendInBatches(keys(100), opts(t, { retryOn429: true })); + assert.equal(r.ok, true); + assert.deepEqual(t.sleeps, [7000, 60_000, 60_000]); + assert.equal(t.calls.length, 5); + for (const b of t.calls.slice(1)) assert.deepEqual(b, keys(100).slice(50)); + assert.equal(r.results.length, 100); +}); + +test('sendInBatches: a 429 is resent three times at most', async () => { + const t = transport([{ status: 429, retryAfter: 1, body: null }]); + const r = await sendInBatches(keys(10), opts(t, { retryOn429: true })); + assert.equal(r.ok, false); + assert.equal(t.calls.length, 1 + MAX_429_RETRIES); + assert.deepEqual(t.sleeps, [1000, 1000, 1000]); +}); + +test('sendInBatches: a 429 without retryOn429 stops at once', async () => { + const t = transport([okFor, { status: 429, retryAfter: 1, body: null }, okFor]); + const r = await sendInBatches(keys(150), opts(t)); + assert.equal(r.ok, false); + assert.equal(t.calls.length, 2); + assert.deepEqual(t.sleeps, []); + assert.equal(r.results.length, 50); +}); + +test('sendInBatches: maxBatches 8 sends 8 batches at most', async () => { + const t = transport([okFor]); + const r = await sendInBatches(keys(1000), opts(t, { maxBatches: MAX_PUSH_BATCHES })); + assert.equal(r.ok, true); + assert.equal(t.calls.length, 8); + assert.equal(r.results.length, 400); +}); diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 35b6c17..46f9c43 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -488,3 +488,41 @@ describe('POST /api/sync: bounded batches (#147)', () => { expect(await results(`user-${u()}`)).toEqual([{ status: 'skipped', error: 'Entity not found or access denied' }]); }); }); + +// The app marks `applied` and `skipped` without `error` as synced, and replays +// a `skipped` with an `error` (src/services/syncRules.ts, #151). +describe('POST /api/sync: results contract (#151)', () => { + async function raw(userId: string, operations: unknown[]): Promise[]> { + h.userId = userId; + const res = await POST(new Request('http://localhost/api/sync', { + method: 'POST', + body: JSON.stringify({ operations }), + })); + expect(res.status).toBe(200); + return ((await res.json()) as { results: Record[] }).results; + } + + it('answers the same idempotency key twice: the second is skipped without an error key', async () => { + const userId = `user-${u()}`; + const op = { + idempotencyKey: u(), entityType: 'list', action: 'create', entityId: u(), + data: { name: 'L', position: 0, isInbox: false }, + }; + expect(await raw(userId, [op])).toEqual([{ idempotencyKey: op.idempotencyKey, status: 'applied' }]); + const [second] = await raw(userId, [op]); + expect(second).toEqual({ idempotencyKey: op.idempotencyKey, status: 'skipped' }); + expect('error' in second).toBe(false); + }); + + it('answers a refused operation (link to another account\'s task) skipped with an error', async () => { + const { A, B } = await seed(); + const key = u(); + const [result] = await raw(B.userId, [ + { idempotencyKey: key, entityType: 'taskTag', action: 'create', entityId: A.task, data: { tagId: B.tag } }, + ]); + expect(result.idempotencyKey).toBe(key); + expect(result.status).toBe('skipped'); + expect(typeof result.error).toBe('string'); + expect((result.error as string).length).toBeGreaterThan(0); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index 64a4533..df799f0 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -160,7 +160,9 @@ export async function POST(request: Request) { const ctx: RequestContext = { inboxCreated: false }; for (const op of body.data.operations) { - // Check idempotency + // Check idempotency. The app reads a `skipped` without `error` as already + // applied and marks it synced, and a `skipped` with an `error` as a + // refusal it replays (src/services/syncRules.ts, #151): keep the two apart. if (idempotency.seen(auth.userId, op.idempotencyKey, Date.now())) { results.push({ idempotencyKey: op.idempotencyKey, status: 'skipped' }); continue; diff --git a/web/src/lib/syncData.ts b/web/src/lib/syncData.ts index 85d67e7..b0686be 100644 --- a/web/src/lib/syncData.ts +++ b/web/src/lib/syncData.ts @@ -4,9 +4,10 @@ import { z } from 'zod'; // // Each schema lists the columns a client may write for one entity and action. // Objects are NOT strict: unknown keys (userId, id, deletedAt, createdAt...) -// are stripped instead of rejected. The mobile app marks its whole outbox as -// synced once the push returns 200, so a rejected operation is lost silently; -// stripping keeps older app versions working while never writing those keys. +// are stripped instead of rejected. App versions before #151 mark their whole +// outbox as synced once the push returns 200, so a rejected operation is lost +// silently for them (since #151 the app replays a refusal, within bounds); +// stripping keeps those versions working while never writing those keys. // // Strings are truncated rather than rejected for the same reason. Limits // follow the mobile app (notes go up to 10000 there, unlike the REST schema). diff --git a/web/src/lib/validators.ts b/web/src/lib/validators.ts index 3ac9a6d..02f148b 100644 --- a/web/src/lib/validators.ts +++ b/web/src/lib/validators.ts @@ -63,7 +63,7 @@ export const assignTagsSchema = z.object({ // Sync // Maximum operations in one POST /api/sync. The app sends batches of 50 -// (`batchSize` in src/services/syncClient.ts): raising `batchSize` above this +// (`BATCH_SIZE` in src/services/syncRules.ts): raising `BATCH_SIZE` above this // bound requires deploying the companion first. The request body itself is // only cut at 10 MB by Next when web/src/middleware.ts covers the route // (see middleware.test.ts).