fix(sync): push marks only applied or duplicate operations and replays refusals within bounds #159
10 changed files with 766 additions and 42 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
@ -15,6 +15,13 @@ import {
|
|||
listUpdatePayload,
|
||||
taskUpdatePayload,
|
||||
mergeTaskData,
|
||||
BATCH_SIZE,
|
||||
MAX_PUSH_BATCHES,
|
||||
classifyOutbox,
|
||||
isSynced,
|
||||
parseRetryAfter,
|
||||
sendInBatches,
|
||||
type PostResponse,
|
||||
} from '@/src/services/syncRules';
|
||||
|
||||
const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com';
|
||||
|
|
@ -51,32 +58,37 @@ async function getAuthHeaders(): Promise<Record<string, string>> {
|
|||
}
|
||||
|
||||
/**
|
||||
* 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<string, string>): Promise<boolean> {
|
||||
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<string, string>): Promise<PostResponse> {
|
||||
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 { status: res.status, retryAfter: parseRetryAfter(res.headers.get('Retry-After')), 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<void> {
|
||||
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<void> {
|
||||
const headers = await getAuthHeaders();
|
||||
|
|
@ -85,7 +97,9 @@ export async function pushChanges(): Promise<void> {
|
|||
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;
|
||||
|
||||
|
|
@ -100,16 +114,25 @@ export async function pushChanges(): Promise<void> {
|
|||
};
|
||||
});
|
||||
|
||||
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(() => {});
|
||||
}
|
||||
}
|
||||
|
|
@ -360,11 +383,23 @@ export async function initialMerge(): Promise<void> {
|
|||
});
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
|
|
|||
|
|
@ -186,3 +186,233 @@ 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<string, unknown>;
|
||||
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<string, number>;
|
||||
}
|
||||
|
||||
// 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<string, PushResult>();
|
||||
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<string, number>();
|
||||
|
||||
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<string, number> = {};
|
||||
for (const entry of dropped) {
|
||||
markIds.push(entry.id);
|
||||
droppedByType[entry.entityType] = (droppedByType[entry.entityType] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return { markIds, keptRefusals, droppedRefusals: dropped.length, droppedByType };
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry-After header in seconds, or null when absent, empty, negative or not
|
||||
* a number of seconds (an HTTP date included). Number(null) and Number('')
|
||||
* are 0, hence the explicit checks: a missing header must mean null (wait
|
||||
* RETRY_AFTER_MAX_S), not 0.
|
||||
*/
|
||||
export function parseRetryAfter(header: string | null | undefined): number | null {
|
||||
if (header == null || header.trim() === '') return null;
|
||||
const seconds = Number(header);
|
||||
return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
|
||||
}
|
||||
|
||||
/** 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<T> {
|
||||
size: number;
|
||||
maxBatches: number;
|
||||
retryOn429: boolean;
|
||||
post: (batch: T[]) => Promise<PostResponse>;
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<T>(
|
||||
ops: T[],
|
||||
{ size, maxBatches, retryOn429, post, sleep }: SendOptions<T>,
|
||||
): 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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -193,6 +193,88 @@ check('applyTagChange never keeps a local tag (no keepLocal)', () => {
|
|||
assert.ok(!/keepLocal\s*\(/.test(body), 'applyTagChange must not call 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.
|
||||
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,/);
|
||||
// Only the ids kept by classifyOutbox are marked, never the whole outbox.
|
||||
assert.match(body('pushChanges'), /\.where\(inArray\(syncOutbox\.id, markIds\)\)/);
|
||||
// Number(null) is 0: a missing Retry-After must go through parseRetryAfter
|
||||
assert.match(src, /retryAfter: parseRetryAfter\(res\.headers\.get\('Retry-After'\)\)/);
|
||||
});
|
||||
|
||||
// Wiring of the pull (#149), the end of initialMerge (#150) and the push
|
||||
// (#151) in syncClient.ts, which node cannot load: the pure rules are tested
|
||||
// in tests/syncRules.test.mjs, this check locks how syncClient.ts calls them
|
||||
// (reviewer mutations of PRs #157, #158 and #159 stayed green without it).
|
||||
check('syncClient.ts wires the #149-#151 sync rules', () => {
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'src/services/syncClient.ts'), 'utf8');
|
||||
const fn = (name) => {
|
||||
const m = new RegExp(`\\n(export )?async function ${name}\\(`).exec(src);
|
||||
assert.ok(m, `${name} not found`);
|
||||
const rest = src.slice(m.index + 1);
|
||||
const end = rest.search(/\n(export )?async function /);
|
||||
return end < 0 ? rest : rest.slice(0, end);
|
||||
};
|
||||
// #149: the pull forwards its `since`, and keeps or rewrites each row
|
||||
assert.match(fn('pullChanges'), /applyChange\(change, since\)/);
|
||||
const apply = fn('applyChange');
|
||||
assert.match(apply, /applyListChange\(entity_id, action, payload, since\)/);
|
||||
assert.match(apply, /applyTaskChange\(entity_id, action, payload, since\)/);
|
||||
for (const [name, type, values, snapshot] of [
|
||||
['applyListChange', 'list', 'pulledListValues', 'listUpdatePayload'],
|
||||
['applyTaskChange', 'task', 'pulledTaskValues', 'taskUpdatePayload'],
|
||||
]) {
|
||||
const body = fn(name);
|
||||
assert.match(
|
||||
body,
|
||||
new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await writeOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`),
|
||||
`${name}: a kept row must be re-queued, then left untouched`
|
||||
);
|
||||
assert.match(body, new RegExp(`${values}\\(id, payload, local\\)`), `${name} must pass the local row`);
|
||||
}
|
||||
// Tags always take the server version (decision of Max, PR #157)
|
||||
const tag = fn('applyTagChange');
|
||||
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 stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)');
|
||||
const pull = merge.indexOf('await pullChanges(SYNC_EPOCH)');
|
||||
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\(/);
|
||||
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\(\)/);
|
||||
});
|
||||
|
||||
// --- 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
|
||||
|
|
|
|||
|
|
@ -19,6 +19,17 @@ import {
|
|||
taskUpdatePayload,
|
||||
tagUpdatePayload,
|
||||
mergeTaskData,
|
||||
BATCH_SIZE,
|
||||
MAX_PUSH_BATCHES,
|
||||
MAX_KEPT_REFUSALS,
|
||||
REJECTED_RETENTION_DAYS,
|
||||
RETRY_AFTER_MAX_S,
|
||||
MAX_429_RETRIES,
|
||||
parseResults,
|
||||
parseRetryAfter,
|
||||
isSynced,
|
||||
classifyOutbox,
|
||||
sendInBatches,
|
||||
} from '../src/services/syncRules.ts';
|
||||
|
||||
const ID = '11111111-1111-4111-8111-111111111111';
|
||||
|
|
@ -239,3 +250,255 @@ 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 unknown status is neither marked nor counted as a refusal', () => {
|
||||
const e = entry();
|
||||
const c = classifyOutbox([e], [{ idempotencyKey: e.id, status: 'queued' }], NOW);
|
||||
assert.deepEqual(c.markIds, []);
|
||||
assert.equal(c.keptRefusals, 0);
|
||||
assert.equal(c.droppedRefusals, 0);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
test('parseRetryAfter: seconds, or null when absent, empty, negative or a date', () => {
|
||||
assert.equal(parseRetryAfter('7'), 7);
|
||||
assert.equal(parseRetryAfter('0'), 0);
|
||||
assert.equal(parseRetryAfter(null), null);
|
||||
assert.equal(parseRetryAfter(undefined), null);
|
||||
assert.equal(parseRetryAfter(''), null);
|
||||
assert.equal(parseRetryAfter(' '), null);
|
||||
assert.equal(parseRetryAfter('-5'), null);
|
||||
assert.equal(parseRetryAfter('Wed, 21 Oct 2026 07:28:00 GMT'), 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 }]);
|
||||
// Guard: without the bound the loop never yields to a timer, so a test
|
||||
// timeout would hang the suite instead of failing it (PR #159 review).
|
||||
const post = t.post;
|
||||
t.post = async (batch) => {
|
||||
if (t.calls.length >= 10) throw new Error('unbounded 429 retries');
|
||||
return post(batch);
|
||||
};
|
||||
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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import type { PGlite } from 'electric-sql-pglite';
|
|||
|
||||
const h = await vi.hoisted(async () => {
|
||||
const { PGlite } = await import('electric-sql-pglite');
|
||||
return { pg: new PGlite() as PGlite, userId: '' };
|
||||
return { pg: new PGlite() as PGlite, userId: '', cleanups: 0 };
|
||||
});
|
||||
|
||||
vi.mock('@/db/client', async () => {
|
||||
|
|
@ -28,6 +28,18 @@ vi.mock('@/lib/api', async (importOriginal) => ({
|
|||
|
||||
vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null }));
|
||||
|
||||
// Real idempotency store, with its cleanup counted: the route must call it (#147).
|
||||
vi.mock('@/lib/idempotency', async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import('@/lib/idempotency')>();
|
||||
return {
|
||||
...mod,
|
||||
createIdempotencyStore: (opts: Parameters<typeof mod.createIdempotencyStore>[0]) => {
|
||||
const store = mod.createIdempotencyStore(opts);
|
||||
return { ...store, cleanup: (now: number) => { h.cleanups++; store.cleanup(now); } };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { POST } = await import('./route');
|
||||
|
||||
type Op = [entityType: string, action: string, entityId: string, data?: Record<string, unknown>];
|
||||
|
|
@ -373,6 +385,31 @@ describe('POST /api/sync: inbox merge', () => {
|
|||
expect(await row('select count(*)::int c from sl_tasks where list_id=$1', [otherInbox])).toEqual({ c: 0 });
|
||||
});
|
||||
|
||||
it('keeps a task sent to an archived regular list in that list (only an archived inbox redirects)', async () => {
|
||||
const { B, N } = await merged();
|
||||
await h.pg.query('update sl_lists set deleted_at = now() where id=$1', [B.list]);
|
||||
const id = u();
|
||||
expect(await push(B.userId, [
|
||||
['task', 'create', id, { title: 'late', listId: B.list }],
|
||||
['task', 'update', B.task, { listId: B.list }],
|
||||
])).toEqual(['applied', 'applied']);
|
||||
expect(await listOf(id)).toBe(B.list);
|
||||
expect(await listOf(B.task)).toBe(B.list);
|
||||
expect(await listOf(B.task)).not.toBe(N);
|
||||
});
|
||||
|
||||
it('redirects to the most recently created active inbox when there are several', async () => {
|
||||
const { B, N } = await merged();
|
||||
const X = u();
|
||||
await h.pg.query(
|
||||
"insert into sl_lists (id, user_id, name, is_inbox, created_at) values ($1, $2, 'Inbox', true, now() + interval '1 hour')",
|
||||
[X, B.userId]);
|
||||
const id = u();
|
||||
expect(await push(B.userId, [['task', 'create', id, { title: 'late', listId: B.inbox }]])).toEqual(['applied']);
|
||||
expect(await listOf(id)).toBe(X);
|
||||
expect(await listOf(id)).not.toBe(N);
|
||||
});
|
||||
|
||||
it('(g) creates only one new inbox per request', async () => {
|
||||
const { B } = await seed();
|
||||
const N1 = u();
|
||||
|
|
@ -476,6 +513,12 @@ describe('POST /api/sync: bounded batches (#147)', () => {
|
|||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('cleans the idempotency store on every POST', async () => {
|
||||
const before = h.cleanups;
|
||||
expect(await push(`user-${u()}`, [['list', 'create', u(), { name: 'L', position: 0, isInbox: false }]])).toEqual(['applied']);
|
||||
expect(h.cleanups).toBe(before + 1);
|
||||
});
|
||||
|
||||
it('skips a replayed key without an error, for its account only', async () => {
|
||||
const userId = `user-${u()}`;
|
||||
const [op] = listOps(1);
|
||||
|
|
@ -488,3 +531,56 @@ 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<Record<string, unknown>[]> {
|
||||
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<string, unknown>[] }).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);
|
||||
});
|
||||
|
||||
it('answers a refused operation replayed with the same key skipped with an error again', async () => {
|
||||
// The app replays a refusal with its outbox id as key. If the server
|
||||
// remembered the key of a refused operation, the replay would come back
|
||||
// `skipped` without `error` and the app would mark it synced: lost.
|
||||
const { A, B } = await seed();
|
||||
const op = { idempotencyKey: u(), entityType: 'taskTag', action: 'create', entityId: A.task, data: { tagId: B.tag } };
|
||||
const [first] = await raw(B.userId, [op]);
|
||||
expect(first.status).toBe('skipped');
|
||||
expect(typeof first.error).toBe('string');
|
||||
const [replay] = await raw(B.userId, [op]);
|
||||
expect(replay.status).toBe('skipped');
|
||||
expect(typeof replay.error).toBe('string');
|
||||
expect((replay.error as string).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,17 @@ describe('createIdempotencyStore', () => {
|
|||
expect(s.seen('a', 'k', T0 + 1)).toBe(true);
|
||||
});
|
||||
|
||||
it('moves a refreshed key to the newest end, so it is evicted last', () => {
|
||||
const s = createIdempotencyStore({ ttlMs: TTL, maxPerAccount: 3 });
|
||||
s.remember('a', 'k1', T0);
|
||||
s.remember('a', 'k2', T0);
|
||||
s.remember('a', 'k3', T0);
|
||||
s.remember('a', 'k1', T0 + 1);
|
||||
s.remember('a', 'k4', T0 + 2);
|
||||
expect(s.seen('a', 'k1', T0 + 3)).toBe(true);
|
||||
expect(s.seen('a', 'k2', T0 + 3)).toBe(false);
|
||||
});
|
||||
|
||||
it('forgets a key after the TTL', () => {
|
||||
const s = store();
|
||||
s.remember('a', 'k', T0);
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue