feat(sync): listen to the companion WebSocket for instant web-to-app sync (#175)

The app opens the companion WebSocket in the foreground (ticket from
POST /api/ws-ticket, then wss://.../ws derived from SYNC_API_BASE). A sync
notice asks the scheduler at once; later notices within 20 s fold into one
sync at the end of the window. The fixed 30 s tick skips while the socket is
open and the last sync is under 2 min old.

Reconnection: 1 s doubled, capped at 60 s, +-20 % jitter, reset after 30 s
open; auth_expired takes a new ticket at once; ticket 401 stops until the
next start; ticket 429 waits for the bounded Retry-After. The socket closes
in the background, on sign-out, sync off and canSync false.

syncSocket.ts is pure and import-free (tests/syncSocket.test.mjs under node);
syncSocketClient.ts wires fetch, WebSocket and timers and only calls
scheduleSync. REVIEW.md Haut Sync line and review-levels.py include both.

Refs #175

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-07 21:13:16 -05:00 • committed by maximus
commit 6fd234af8e
9 changed files with 1008 additions and 19 deletions

View file

@ -28,7 +28,7 @@ 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,syncSchedule,syncTrigger}.ts`, `src/db/repository/outbox.ts` | toujours | Sync |
| `src/services/{syncClient,syncRules,syncSchedule,syncTrigger,syncSocket,syncSocketClient}.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`, `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 |
@ -117,12 +117,13 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/app/api/sync/route.test.ts`, #181
- 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`). `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
- `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`, et `src/services/syncSocket.ts` pour `tests/syncSocket.test.mjs` (check smoke `syncSchedule.ts, syncTrigger.ts and syncSocket.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, `tests/syncSocket.test.mjs`, #149, #178, #175
- 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 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
- Toute sync passe par le planificateur (`scheduleSync`) : lancement, tic d'intervalle au premier plan, retour au premier plan, écriture locale, avis du WebSocket 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
- L'app ouverte écoute le WebSocket du companion (`POST /api/ws-ticket` avec le Bearer, puis `wss://liste.lacompagniemaximus.com/ws?ticket=…`, URL dérivée de `SYNC_API_BASE`), au premier plan seulement : socket neuve à chaque retour au premier plan, fermée en arrière-plan, à la déconnexion, sync coupée ou `canSync` faux (abonnement au store de réglages). Un avis `sync` lance `scheduleSync()` tout de suite, les avis suivants dans les 20 s (`NOTICE_WINDOW_MS`) se replient en une sync à la fin de la fenêtre, jamais plus d'une sync par 20 s venue de la socket ; l'écho de son propre envoi n'est pas filtré, la fenêtre et le budget l'absorbent. Le tic fixe de 30 s saute tant que la socket est ouverte et que la dernière sync qu'il ou la socket a lancée date de moins de 2 min (`shouldTick`), sinon il synchronise toutes les 30 s comme avant. Reconnexion 1 s doublée, plafonnée à 60 s, gigue ±20 %, remise à zéro après 30 s ouverte ; `auth_expired` reprend un ticket tout de suite sans compter d'échec ; ticket 401 (ou pas de jeton) arrête la socket jusqu'au prochain démarrage ; ticket 429 attend le `Retry-After` (600 s au plus, 60 s illisible). Seul `type` est lu dans un message, et ni le ticket ni l'URL de `/ws` ne sont journalisés. Une montée de la fenêtre ou de l'intervalle se juge contre la limite `sync` partagée par les appareils. — `src/services/syncSocket.ts`, `src/services/syncSocketClient.ts`, `app/_layout.tsx`, `tests/syncSocket.test.mjs`, `tests/smoke.test.cjs`, #175
- 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`
@ -135,7 +136,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
### Vie privée
- L'app n'appelle que quatre hôtes : `liste.lacompagniemaximus.com` (sync, seulement la session ouverte, et la sync activée ou la première sync choisie par l'utilisateur), `auth.lacompagniemaximus.com` (Logto), `feedback.lacompagniemaximus.com` (rétroaction envoyée par l'utilisateur) et `git.lacompagniemaximus.com` (vérification des mises à jour, sans authentification). Un hôte ajouté se justifie dans la PR. — `src/services/syncClient.ts`, `src/lib/logtoConfig.ts`, `src/services/feedback.ts`, `app/(tabs)/settings.tsx`
- L'app n'appelle que quatre hôtes : `liste.lacompagniemaximus.com` (sync et WebSocket du companion, seulement la session ouverte, et la sync activée ou la première sync choisie par l'utilisateur), `auth.lacompagniemaximus.com` (Logto), `feedback.lacompagniemaximus.com` (rétroaction envoyée par l'utilisateur) et `git.lacompagniemaximus.com` (vérification des mises à jour, sans authentification). Un hôte ajouté se justifie dans la PR. — `src/services/syncClient.ts`, `src/services/syncSocketClient.ts`, `src/lib/logtoConfig.ts`, `src/services/feedback.ts`, `app/(tabs)/settings.tsx`
- Le Feedback Hub reçoit le texte saisi (2000 caractères au plus), un `user_id` facultatif et un contexte limité à la liste blanche `CONTEXT_KEYS` (page, langue, thème, viewport, user-agent, horodatage). Une clé ajoutée élargit ce qui part (Loi 25) ; le module reste sans import, pour que `tests/feedback.test.mjs` le charge. — `src/services/feedback.ts`, `tests/feedback.test.mjs`, PR #101
- Calendrier, notifications et export `.ics` restent sur l'appareil. — `src/services/{calendar,notifications,icsExport}.ts`

View file

@ -17,6 +17,7 @@ import { initNotifications } from '@/src/services/notifications';
import { syncWidgetData } from '@/src/services/widgetSync';
import { scheduleSync } from '@/src/services/syncClient';
import { setSyncSubscriber } from '@/src/services/syncTrigger';
import { startSyncSocket, stopSyncSocket, syncTickDue } from '@/src/services/syncSocketClient';
import { logtoConfig } from '@/src/lib/logtoConfig';
import { setTokenGetter, clearTokenGetter } from '@/src/lib/authToken';
import '@/src/i18n';
@ -24,8 +25,9 @@ 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.
// Fixed foreground tick: a sync every 30 s while the companion WebSocket is
// not open (#167), every 2 min while it is (syncTickDue, decision of Max,
// 2026-11-07, #175).
const SYNC_INTERVAL_MS = 30 * 1000;
SplashScreen.preventAutoHideAsync();
@ -126,9 +128,11 @@ function AppContent() {
return () => clearTokenGetter();
}, [isAuthenticated, getAccessToken]);
// 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).
// Sync (#178): on launch, on the foreground tick, 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). The companion WebSocket
// (#175) lives in the foreground only: opened once the Inbox is set up,
// fresh on each return to the foreground, closed in the background.
useEffect(() => {
if (!syncEnabled) return;
let active = true;
@ -140,19 +144,28 @@ function AppContent() {
setSyncSubscriber(() => {
scheduleSync().catch(() => {});
});
if (AppState.currentState === 'active') startSyncSocket();
return scheduleSync();
}).catch(() => {});
// 30-second interval, foreground only
// Fixed 30-second tick, foreground only; skipped while the socket is open
const interval = setInterval(() => {
if (AppState.currentState !== 'active') return;
if (!syncTickDue()) return;
prepareInbox().then(() => scheduleSync()).catch(() => {});
}, SYNC_INTERVAL_MS);
// AppState listener: sync when returning from background
// AppState listener: sync and a fresh socket when returning from
// background, no socket in the background
const subscription = AppState.addEventListener('change', (nextState: AppStateStatus) => {
if (appState.current.match(/inactive|background/) && nextState === 'active') {
prepareInbox().then(() => scheduleSync()).catch(() => {});
prepareInbox().then(() => {
if (!active) return;
if (AppState.currentState === 'active') startSyncSocket();
return scheduleSync();
}).catch(() => {});
} else if (nextState === 'background') {
stopSyncSocket();
}
appState.current = nextState;
});
@ -160,6 +173,7 @@ function AppContent() {
return () => {
active = false;
setSyncSubscriber(null);
stopSyncSocket();
clearInterval(interval);
subscription.remove();
};

View file

@ -4,7 +4,7 @@
"version": "1.8.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 tests/syncSchedule.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 tests/syncSocket.test.mjs",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",

View file

@ -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,syncSchedule,syncTrigger}.ts", "src/db/repository/outbox.ts",
"src/services/{syncClient,syncRules,syncSchedule,syncTrigger,syncSocket,syncSocketClient}.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",

View file

@ -34,7 +34,7 @@ import {
type SyncRun,
} from '@/src/services/syncSchedule';
const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com';
export const SYNC_API_BASE = 'https://liste.lacompagniemaximus.com';
const INBOX_ID = '00000000-0000-0000-0000-000000000001';
interface SyncOperation {

329
src/services/syncSocket.ts Normal file
View file

@ -0,0 +1,329 @@
// Companion WebSocket, connection logic (#175): the states of the socket, the
// reconnection delays, the 20 s window of the notices and the decision of the
// foreground tick. Pure and import-free, like syncSchedule.ts, so that
// tests/syncSocket.test.mjs loads it through node's type stripping
// (zero-import guard in smoke.test.cjs). The clock, the timers, the ticket
// request and the WebSocket are injected; syncSocketClient.ts wires the real
// ones.
//
// The server sends `{ type: 'sync' }` to every socket of the account after a
// change (coalesced 1 s, the app's own pushes included), and
// `{ type: 'auth_expired' }` before it closes a socket 15 min after its
// opening (web/src/lib/ws.ts).
//
// Known limit: a socket that dies without a close event (half-open after a
// network change) looks open until the next return to the foreground, which
// always opens a fresh one. Meanwhile the foreground tick still syncs every
// OPEN_TICK_INTERVAL_MS, so a missed change waits 2 min at worst.
/** Notices received within this window after a socket-triggered sync fold into one sync at its end. */
export const NOTICE_WINDOW_MS = 20_000;
/** First reconnection delay, doubled after each failure. */
export const RECONNECT_BASE_MS = 1_000;
/** Upper bound of the reconnection delay, before the jitter. */
export const RECONNECT_MAX_MS = 60_000;
/** Jitter of a reconnection delay: ±20 %. */
export const RECONNECT_JITTER = 0.2;
/** A socket open this long resets the failure count. */
export const STABLE_OPEN_MS = 30_000;
/** Foreground tick period: the interval sync while the socket is not open. */
export const TICK_INTERVAL_MS = 30_000;
/** With the socket open, the tick syncs only when the last sync is this old. */
export const OPEN_TICK_INTERVAL_MS = 120_000;
/** Wait after a ticket 429 without a readable Retry-After, in seconds. */
export const TICKET_DEFAULT_RETRY_AFTER_S = 60;
/** Upper bound of a ticket Retry-After, in seconds. */
export const TICKET_MAX_RETRY_AFTER_S = 600;
export type SocketState = 'closed' | 'ticket' | 'connecting' | 'open' | 'waiting' | 'stopped';
/** Outcome of `POST /api/ws-ticket`, as the connection logic sees it. */
export type TicketResult =
| { kind: 'ok'; ticket: string }
/** 401, or no access token: stop until the next start. */
| { kind: 'unauthorized' }
/** 429: wait for the Retry-After (seconds, null when unreadable). */
| { kind: 'rate_limited'; retryAfterS: number | null }
/** Network error, 5xx or unexpected answer: reconnect with backoff. */
| { kind: 'failed' };
/**
* Classify the answer of `POST /api/ws-ticket`. Only `ticket` is read from
* the body, and only when it is a non-empty string.
*/
export function ticketResult(status: number, retryAfterS: number | null, body: unknown): TicketResult {
if (status === 401) return { kind: 'unauthorized' };
if (status === 429) return { kind: 'rate_limited', retryAfterS };
if (status < 200 || status >= 300) return { kind: 'failed' };
const ticket = body && typeof body === 'object' ? (body as { ticket?: unknown }).ticket : undefined;
return typeof ticket === 'string' && ticket !== '' ? { kind: 'ok', ticket } : { kind: 'failed' };
}
/** `wss://<host>/ws` derived from the https base of the sync API (no second host constant). */
export function socketUrl(apiBase: string): string {
return `${apiBase.replace(/^https:\/\//, 'wss://').replace(/\/+$/, '')}/ws`;
}
/**
* Reconnection delay after `failures` consecutive failures (1 or more): 1 s
* doubled each time, capped at RECONNECT_MAX_MS, then a jitter of ±20 %.
* `random` is in [0, 1).
*/
export function reconnectDelay(failures: number, random: number): number {
const n = Math.max(1, failures);
const base = Math.min(RECONNECT_BASE_MS * 2 ** (n - 1), RECONNECT_MAX_MS);
return Math.round(base * (1 + (random * 2 - 1) * RECONNECT_JITTER));
}
/** Wait after a ticket 429, in ms: the Retry-After bounded to [0, 600] s, 60 s when unreadable. */
export function ticketRetryDelay(retryAfterS: number | null): number {
const s =
retryAfterS == null || !Number.isFinite(retryAfterS)
? TICKET_DEFAULT_RETRY_AFTER_S
: Math.min(Math.max(retryAfterS, 0), TICKET_MAX_RETRY_AFTER_S);
return s * 1000;
}
/**
* Decision of the fixed foreground tick: skip it when the socket is open and
* the last sync was launched less than OPEN_TICK_INTERVAL_MS ago; otherwise
* sync, every TICK_INTERVAL_MS as before the socket.
*/
export function shouldTick(socketOpen: boolean, lastSyncAt: number | null, now: number): boolean {
if (!socketOpen || lastSyncAt == null) return true;
return now - lastSyncAt >= OPEN_TICK_INTERVAL_MS;
}
/** Type of a server message; null for anything unreadable. Nothing else is read. */
export function messageType(data: unknown): string | null {
if (typeof data !== 'string') return null;
try {
const msg = JSON.parse(data);
return msg && typeof msg === 'object' && typeof msg.type === 'string' ? msg.type : null;
} catch {
return null;
}
}
/** Events of one socket, wired by the adapter. */
export interface SocketHandlers {
open(): void;
message(data: unknown): void;
/** Closed or failed, before or after opening. */
close(): void;
}
export interface SocketHandle {
/** Close the socket; its later events must not reach the handlers. */
close(): void;
}
export interface SyncSocketDeps {
now(): number;
setTimer(fn: () => void, ms: number): unknown;
clearTimer(handle: unknown): void;
/** In [0, 1), for the jitter. */
random(): number;
/** canSync of the settings (sync on, data of the signed-in account). */
canOpen(): boolean;
/** `POST /api/ws-ticket`; a rejection counts as a failure. */
requestTicket(): Promise<TicketResult>;
connect(ticket: string, handlers: SocketHandlers): SocketHandle;
/** Ask for one sync (scheduleSync), never more. */
sync(): void;
/** Optional trace, without ticket nor URL. */
log?(event: string): void;
}
export interface SyncSocket {
/** Open a fresh socket (any current one is dropped), failure count reset. */
start(): void;
/** Close the socket and cancel every timer: reconnection, ticket wait, notice window. */
stop(): void;
/** The guard may have changed: stop when canOpen is false. */
check(): void;
/** Foreground tick: true when it should sync (counted as a launched sync). */
tick(): boolean;
isOpen(): boolean;
state(): SocketState;
}
export function createSyncSocket(deps: SyncSocketDeps): SyncSocket {
let state: SocketState = 'closed';
// Bumped on every new attempt and on stop: events of an older ticket or socket are ignored
let gen = 0;
let failures = 0;
let openedAt = 0;
let socket: SocketHandle | null = null;
let retryTimer: unknown = null;
let windowTimer: unknown = null;
let windowEnd = 0;
let noticePending = false;
let lastSyncAt: number | null = null;
const log = (event: string) => deps.log?.(event);
function clearRetry() {
if (retryTimer !== null) deps.clearTimer(retryTimer);
retryTimer = null;
}
function dropSocket() {
const s = socket;
socket = null;
if (s) {
try {
s.close();
} catch {
// Already closed
}
}
}
function clearWindow() {
if (windowTimer !== null) deps.clearTimer(windowTimer);
windowTimer = null;
windowEnd = 0;
noticePending = false;
}
function launchSync() {
lastSyncAt = deps.now();
deps.sync();
}
function halt(next: SocketState) {
gen++;
clearRetry();
dropSocket();
clearWindow();
state = next;
}
function wait(ms: number) {
state = 'waiting';
const g = gen;
retryTimer = deps.setTimer(() => {
retryTimer = null;
if (g !== gen) return;
attempt();
}, ms);
}
function fail() {
failures++;
const ms = reconnectDelay(failures, deps.random());
log(`reconnect in ${ms} ms`);
wait(ms);
}
// Window of the notices: the first one syncs at once, the next ones within
// NOTICE_WINDOW_MS fold into one sync at its end, which opens a new window.
function armWindow() {
windowEnd = deps.now() + NOTICE_WINDOW_MS;
windowTimer = deps.setTimer(() => {
windowTimer = null;
if (noticePending) {
noticePending = false;
launchSync();
armWindow();
} else {
windowEnd = 0;
}
}, NOTICE_WINDOW_MS);
}
function notice() {
if (windowTimer !== null && deps.now() < windowEnd) {
noticePending = true;
return;
}
launchSync();
armWindow();
}
function attempt() {
if (!deps.canOpen()) {
halt('closed');
return;
}
gen++;
const g = gen;
dropSocket();
state = 'ticket';
Promise.resolve()
.then(() => deps.requestTicket())
.then(
(r) => r,
(): TicketResult => ({ kind: 'failed' }),
)
.then((r) => {
if (g !== gen) return;
if (!deps.canOpen()) {
halt('closed');
return;
}
if (r.kind === 'unauthorized') {
log('unauthorized, stopped');
halt('stopped');
return;
}
if (r.kind === 'rate_limited') {
wait(ticketRetryDelay(r.retryAfterS));
return;
}
if (r.kind !== 'ok') {
fail();
return;
}
state = 'connecting';
socket = deps.connect(r.ticket, {
open() {
if (g !== gen) return;
state = 'open';
openedAt = deps.now();
log('open');
},
message(data) {
if (g !== gen) return;
const type = messageType(data);
if (type === 'sync') {
notice();
} else if (type === 'auth_expired') {
// Planned end of the socket: a new ticket at once, not a failure
log('auth expired, reconnect');
attempt();
}
},
close() {
if (g !== gen) return;
socket = null;
if (state === 'open' && deps.now() - openedAt >= STABLE_OPEN_MS) failures = 0;
log('closed');
fail();
},
});
});
}
return {
start() {
halt('closed');
failures = 0;
attempt();
},
stop() {
halt('closed');
},
check() {
if (state !== 'closed' && state !== 'stopped' && !deps.canOpen()) halt('closed');
},
tick() {
if (!shouldTick(state === 'open', lastSyncAt, deps.now())) return false;
lastSyncAt = deps.now();
return true;
},
isOpen: () => state === 'open',
state: () => state,
};
}

View file

@ -0,0 +1,91 @@
// Companion WebSocket, adapter (#175): the ticket request, the React Native
// WebSocket and the real timers, wired on the pure logic of syncSocket.ts. A
// notice only asks the scheduler for a sync (scheduleSync), within its request
// budget. App open only: _layout.tsx starts the socket in the foreground and
// stops it in the background.
import { useSettingsStore } from '@/src/stores/useSettingsStore';
import { getAccessToken } from '@/src/lib/authToken';
import { SYNC_API_BASE, scheduleSync } from '@/src/services/syncClient';
import { canSync } from '@/src/services/syncSchedule';
import { parseRetryAfter } from '@/src/services/syncRules';
import { createSyncSocket, socketUrl, ticketResult, type TicketResult } from '@/src/services/syncSocket';
const SOCKET_URL = socketUrl(SYNC_API_BASE);
// The ticket is single use and valid 30 s: never logged, nor the /ws URL that carries it
async function requestTicket(): Promise<TicketResult> {
const token = await getAccessToken();
if (!token) return { kind: 'unauthorized' };
let res: Response;
try {
res = await fetch(`${SYNC_API_BASE}/api/ws-ticket`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
} catch {
return { kind: 'failed' };
}
const body = res.ok ? await res.json().catch(() => null) : null;
return ticketResult(res.status, parseRetryAfter(res.headers.get('Retry-After')), body);
}
const socket = createSyncSocket({
now: () => Date.now(),
setTimer: (fn, ms) => setTimeout(fn, ms),
clearTimer: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
random: () => Math.random(),
canOpen: () => canSync(useSettingsStore.getState()),
requestTicket,
connect(ticket, handlers) {
const ws = new WebSocket(`${SOCKET_URL}?ticket=${encodeURIComponent(ticket)}`);
ws.onopen = () => handlers.open();
ws.onmessage = (event) => handlers.message(event.data);
// An error is followed by a close event, which reconnects
ws.onerror = () => {};
ws.onclose = () => handlers.close();
return {
close() {
ws.onopen = null;
ws.onmessage = null;
ws.onerror = null;
ws.onclose = null;
ws.close();
},
};
},
sync: () => {
scheduleSync().catch(() => {});
},
log: (event) => {
if (__DEV__) console.log(`[sync] socket ${event}`);
},
});
// Sign-out, sync off or data of another account (#165) close the socket at once
let unsubscribe: (() => void) | null = null;
/** Open a fresh socket (foreground). Without canSync or a token, nothing opens. */
export function startSyncSocket(): void {
if (!unsubscribe) unsubscribe = useSettingsStore.subscribe(() => socket.check());
socket.start();
}
/** Close the socket and cancel any reconnection (background, sync off, unmount). */
export function stopSyncSocket(): void {
unsubscribe?.();
unsubscribe = null;
socket.stop();
}
export function isSyncSocketOpen(): boolean {
return socket.isOpen();
}
/**
* Foreground tick (every 30 s): true when the interval sync is due, false
* while the socket is open and a sync was launched less than 2 min ago.
*/
export function syncTickDue(): boolean {
return socket.tick();
}

View file

@ -184,9 +184,10 @@ 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']) {
// sync module, no dynamic import either). The connection logic of the
// companion WebSocket (#175) follows the same rule for tests/syncSocket.test.mjs.
check('syncSchedule.ts, syncTrigger.ts and syncSocket.ts stay import-free (#178, #175)', () => {
for (const file of ['src/services/syncSchedule.ts', 'src/services/syncTrigger.ts', 'src/services/syncSocket.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`);
@ -221,10 +222,30 @@ check('sync on write and every sync go through the scheduler (#178)', () => {
// _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');
// Fixed 30 s tick (#175): it syncs only when syncTickDue says so (2 min
// while the WebSocket is open, 30 s otherwise, decision of Max, 2026-11-07)
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, /setInterval\(\(\) => \{\s*if \(AppState\.currentState !== 'active'\) return;\s*if \(!syncTickDue\(\)\) return;\s*prepareInbox\(\)\.then\(\(\) => scheduleSync\(\)\)/);
assert.match(layout, /setSyncSubscriber\(\(\) => \{\s*scheduleSync\(\)/);
assert.match(layout, /setSyncSubscriber\(null\);/);
// Companion WebSocket (#175): foreground only, a fresh socket on each return
// to the foreground, closed in the background and when the effect ends
// (sync off, sign-out). A notice only asks the scheduler, never fullSync.
assert.equal((layout.match(/if \(AppState\.currentState === 'active'\) startSyncSocket\(\);/g) || []).length, 2, 'the socket opens at launch and on return to the foreground, foreground only');
assert.match(layout, /\} else if \(nextState === 'background'\) \{\s*stopSyncSocket\(\);/);
assert.match(layout, /setSyncSubscriber\(null\);\s*stopSyncSocket\(\);/);
const socketClient = read('src/services/syncSocketClient.ts');
assert.ok(!/\bfullSync\b|pushChanges|pullChanges/.test(socketClient), 'syncSocketClient.ts must not call fullSync');
assert.match(socketClient, /sync: \(\) => \{\s*scheduleSync\(\)\.catch\(\(\) => \{\}\);\s*\},/);
assert.match(socketClient, /canOpen: \(\) => canSync\(useSettingsStore\.getState\(\)\),/);
assert.match(socketClient, /useSettingsStore\.subscribe\(\(\) => socket\.check\(\)\)/, 'a settings change (sync off, other account) closes the socket');
// Neither the ticket nor the /ws URL is ever logged: one trace, dev only, event name only
assert.equal((socketClient.match(/console\./g) || []).length, 1, 'syncSocketClient.ts logs only through the dev trace');
assert.match(socketClient, /if \(__DEV__\) console\.log\(`\[sync\] socket \$\{event\}`\);/);
assert.ok(!/(log|console)[^\n]*ticket/i.test(read('src/services/syncSocket.ts')), 'syncSocket.ts never logs the ticket');
// No second host constant: the wss URL derives from SYNC_API_BASE
assert.match(socketClient, /const SOCKET_URL = socketUrl\(SYNC_API_BASE\);/);
assert.ok(!/lacompagniemaximus/.test(socketClient), 'syncSocketClient.ts must not name a host');
// 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');

533
tests/syncSocket.test.mjs Normal file
View file

@ -0,0 +1,533 @@
// Execution tests for the connection logic of the companion WebSocket (#175).
// Runs on plain node via the built-in test runner + native TS type-stripping:
//
// node --test tests/syncSocket.test.mjs
//
// syncSocket.ts stays import-free so that node loads it (zero-import guard in
// smoke.test.cjs). The clock, the timers, the ticket request and the sockets
// are fakes driven by the tests.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
NOTICE_WINDOW_MS,
OPEN_TICK_INTERVAL_MS,
RECONNECT_MAX_MS,
STABLE_OPEN_MS,
TICKET_DEFAULT_RETRY_AFTER_S,
TICKET_MAX_RETRY_AFTER_S,
createSyncSocket,
messageType,
reconnectDelay,
shouldTick,
socketUrl,
ticketResult,
} from '../src/services/syncSocket.ts';
// Fake clock: timers fire in time order when the clock advances.
function fakeClock() {
let now = 0;
let nextId = 1;
let timers = [];
return {
now: () => now,
setTimer: (fn, ms) => {
const id = nextId++;
timers.push({ id, at: now + ms, fn });
return id;
},
clearTimer: (id) => {
timers = timers.filter((t) => t.id !== id);
},
pending: () => timers.length,
async advance(ms) {
const end = now + ms;
for (;;) {
await flush();
timers.sort((a, b) => a.at - b.at || a.id - b.id);
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 harness around createSyncSocket: records ticket requests, sockets and syncs.
// `tickets` answers each ticket request (default: a valid ticket).
function harness({ tickets = () => ({ kind: 'ok', ticket: 't' }), random = 0.5 } = {}) {
const clock = fakeClock();
const h = {
clock,
allowed: true,
ticketTimes: [],
sockets: [],
syncs: [],
get last() {
return h.sockets[h.sockets.length - 1];
},
};
h.socket = createSyncSocket({
now: clock.now,
setTimer: clock.setTimer,
clearTimer: clock.clearTimer,
random: () => random,
canOpen: () => h.allowed,
requestTicket: async () => {
h.ticketTimes.push(clock.now());
return tickets(h.ticketTimes.length);
},
connect(ticket, handlers) {
const s = { ticket, handlers, closed: false, close: () => (s.closed = true) };
h.sockets.push(s);
return s;
},
sync: () => h.syncs.push(clock.now()),
});
return h;
}
// Open the last socket, wait `openMs`, then close it from the server side.
async function openThenDrop(h, openMs = 0) {
h.last.handlers.open();
await h.clock.advance(openMs);
h.last.handlers.close();
await flush();
}
const gaps = (times) => times.slice(1).map((t, i) => t - times[i]);
// --- Pure helpers ---
test('reconnectDelay: 1 s doubled per failure, capped at 60 s', () => {
const delays = [1, 2, 3, 4, 5, 6, 7, 8, 12].map((n) => reconnectDelay(n, 0.5));
assert.deepEqual(delays, [1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000]);
});
test('reconnectDelay: jitter stays within ±20 % of the capped delay', () => {
for (const n of [1, 3, 7, 20]) {
const base = Math.min(1000 * 2 ** (n - 1), RECONNECT_MAX_MS);
for (const r of [0, 0.1, 0.5, 0.9, 0.999999]) {
const d = reconnectDelay(n, r);
assert.ok(d >= base * 0.8 && d <= base * 1.2, `n=${n} r=${r}: ${d} outside ±20 % of ${base}`);
}
assert.equal(reconnectDelay(n, 0), Math.round(base * 0.8));
}
assert.ok(reconnectDelay(50, 0.999999) <= RECONNECT_MAX_MS * 1.2);
});
test('shouldTick: skip only while the socket is open and the last sync is under 2 min old', () => {
assert.equal(shouldTick(false, null, 0), true);
assert.equal(shouldTick(false, 1000, 1000), true, 'socket closed: every tick syncs');
assert.equal(shouldTick(true, null, 5000), true, 'open but no sync yet');
assert.equal(shouldTick(true, 0, OPEN_TICK_INTERVAL_MS - 1), false);
assert.equal(shouldTick(true, 0, OPEN_TICK_INTERVAL_MS), true);
});
test('messageType reads only the type; unreadable messages give null', () => {
assert.equal(messageType('{"type":"sync"}'), 'sync');
assert.equal(messageType('{"type":"auth_expired","x":1}'), 'auth_expired');
for (const bad of ['not json', '', 'null', '42', '"sync"', '{"type":3}', '{}', null, undefined, new ArrayBuffer(2)]) {
assert.equal(messageType(bad), null, `${String(bad)} must be ignored`);
}
});
test('ticketResult: 201 with a ticket, 401, 429, 5xx and malformed answers', () => {
assert.deepEqual(ticketResult(201, null, { ticket: 'abc' }), { kind: 'ok', ticket: 'abc' });
assert.deepEqual(ticketResult(401, null, null), { kind: 'unauthorized' });
assert.deepEqual(ticketResult(429, 12, null), { kind: 'rate_limited', retryAfterS: 12 });
assert.deepEqual(ticketResult(429, null, null), { kind: 'rate_limited', retryAfterS: null });
for (const [status, body] of [[500, null], [503, { ticket: 'x' }], [201, null], [201, { ticket: '' }], [201, { ticket: 5 }], [403, null]]) {
assert.deepEqual(ticketResult(status, null, body), { kind: 'failed' }, `${status} ${JSON.stringify(body)}`);
}
});
test('socketUrl derives wss from the https base', () => {
assert.equal(socketUrl('https://liste.lacompagniemaximus.com'), 'wss://liste.lacompagniemaximus.com/ws');
assert.equal(socketUrl('https://liste.lacompagniemaximus.com/'), 'wss://liste.lacompagniemaximus.com/ws');
});
// --- Connection ---
test('start opens a socket with the ticket', async () => {
const h = harness({ tickets: () => ({ kind: 'ok', ticket: 'abc' }) });
h.socket.start();
await flush();
assert.equal(h.socket.state(), 'connecting');
assert.equal(h.last.ticket, 'abc');
h.last.handlers.open();
assert.equal(h.socket.isOpen(), true);
});
test('no socket without canSync', async () => {
const h = harness();
h.allowed = false;
h.socket.start();
await h.clock.advance(600_000);
assert.equal(h.ticketTimes.length, 0);
assert.equal(h.socket.state(), 'closed');
});
test('reconnection delays: 1, 2, 4 … s, capped at 60 s', async () => {
const h = harness();
h.socket.start();
await flush();
const delays = [];
for (let i = 0; i < 10; i++) {
const n = h.ticketTimes.length;
h.last.handlers.close();
const dropAt = h.clock.now();
while (h.ticketTimes.length === n) await h.clock.advance(500);
delays.push(h.ticketTimes[n] - dropAt);
}
assert.deepEqual(delays, [1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000, 60000]);
});
test('a failed ticket (network, 5xx) reconnects with backoff too', async () => {
const h = harness({ tickets: () => ({ kind: 'failed' }) });
h.socket.start();
await h.clock.advance(1000 + 2000 + 4000);
assert.deepEqual(gaps(h.ticketTimes), [1000, 2000, 4000]);
assert.equal(h.socket.state(), 'waiting');
});
test('a rejected ticket request counts as a failure', async () => {
const h = harness();
let calls = 0;
const s = createSyncSocket({
now: h.clock.now, setTimer: h.clock.setTimer, clearTimer: h.clock.clearTimer, random: () => 0.5,
canOpen: () => true,
requestTicket: async () => {
calls++;
throw new Error('offline');
},
connect: () => assert.fail('no socket without a ticket'),
sync: () => {},
});
s.start();
await h.clock.advance(3000);
assert.equal(calls, 3);
});
test('the failure count resets after 30 s of open socket', async () => {
const h = harness();
h.socket.start();
await flush();
// Three quick failures (open 1 s each): 1, 2 then 4 s
const delays = [];
for (let i = 0; i < 3; i++) {
const n = h.ticketTimes.length;
await openThenDrop(h, 1000);
const dropAt = h.clock.now();
while (h.ticketTimes.length === n) await h.clock.advance(500);
delays.push(h.ticketTimes[n] - dropAt);
}
assert.deepEqual(delays, [1000, 2000, 4000]);
// Open 30 s, then dropped: back to 1 s
const before = h.ticketTimes.length;
await openThenDrop(h, STABLE_OPEN_MS);
const dropAt = h.clock.now();
await h.clock.advance(RECONNECT_MAX_MS);
assert.equal(h.ticketTimes[before] - dropAt, 1000);
});
test('a socket open under 30 s keeps the count', async () => {
const h = harness();
h.socket.start();
await flush();
await openThenDrop(h, STABLE_OPEN_MS - 1);
await h.clock.advance(RECONNECT_MAX_MS);
await openThenDrop(h, STABLE_OPEN_MS - 1);
const dropAt = h.clock.now();
await h.clock.advance(RECONNECT_MAX_MS);
assert.equal(h.ticketTimes[2] - dropAt, 2000);
});
test('auth_expired: a new ticket at once, without counting a failure', async () => {
const h = harness();
h.socket.start();
await flush();
// Two failures first: the next one would wait 4 s, a counted one 8 s
h.last.handlers.close();
await h.clock.advance(1000);
h.last.handlers.close();
await h.clock.advance(2000);
assert.equal(h.ticketTimes.length, 3);
const old = h.last;
old.handlers.open();
await h.clock.advance(5000);
old.handlers.message('{"type":"auth_expired"}');
await flush();
assert.equal(h.ticketTimes.length, 4, 'new ticket requested');
assert.equal(h.ticketTimes[3], h.clock.now(), 'at once');
assert.equal(old.closed, true, 'the expired socket is dropped');
// The server terminates the old socket: its close event changes nothing
old.handlers.close();
await flush();
assert.equal(h.socket.state(), 'connecting');
// The new socket fails: third failure, 4 s
h.last.handlers.close();
const dropAt = h.clock.now();
await h.clock.advance(RECONNECT_MAX_MS);
assert.equal(h.ticketTimes[4] - dropAt, 4000);
});
test('ticket 401: stopped, no reconnection until the next start', async () => {
let status = 'unauthorized';
const h = harness({ tickets: () => (status === 'unauthorized' ? { kind: 'unauthorized' } : { kind: 'ok', ticket: 't' }) });
h.socket.start();
await h.clock.advance(TICKET_MAX_RETRY_AFTER_S * 1000 * 2);
assert.equal(h.ticketTimes.length, 1);
assert.equal(h.socket.state(), 'stopped');
assert.equal(h.clock.pending(), 0, 'no timer left');
h.socket.check();
await h.clock.advance(60_000);
assert.equal(h.ticketTimes.length, 1, 'check does not restart');
status = 'ok';
h.socket.start();
await flush();
assert.equal(h.ticketTimes.length, 2);
assert.equal(h.socket.state(), 'connecting');
});
test('ticket 401: the tick keeps syncing every 30 s', async () => {
const h = harness({ tickets: () => ({ kind: 'unauthorized' }) });
h.socket.start();
await flush();
assert.equal(h.socket.tick(), true);
await h.clock.advance(30_000);
assert.equal(h.socket.tick(), true);
});
test('ticket 429: wait for the Retry-After, bounded to 600 s, 60 s when unreadable', async () => {
for (const [retryAfterS, waitMs] of [
[5, 5000],
[0, 0],
[100_000, TICKET_MAX_RETRY_AFTER_S * 1000],
[-3, 0],
[null, TICKET_DEFAULT_RETRY_AFTER_S * 1000],
[Number.NaN, TICKET_DEFAULT_RETRY_AFTER_S * 1000],
]) {
const h = harness({ tickets: (n) => (n === 1 ? { kind: 'rate_limited', retryAfterS } : { kind: 'ok', ticket: 't' }) });
h.socket.start();
await flush();
if (waitMs > 0) {
await h.clock.advance(waitMs - 1);
assert.equal(h.ticketTimes.length, 1, `retryAfter ${retryAfterS}: too early`);
}
await h.clock.advance(waitMs > 0 ? 1 : 0);
assert.equal(h.ticketTimes.length, 2, `retryAfter ${retryAfterS}: retried after ${waitMs} ms`);
}
});
test('ticket 429 does not raise the backoff', async () => {
const h = harness({ tickets: (n) => (n === 1 ? { kind: 'rate_limited', retryAfterS: 2 } : { kind: 'ok', ticket: 't' }) });
h.socket.start();
await h.clock.advance(2000);
h.last.handlers.close();
const dropAt = h.clock.now();
await h.clock.advance(RECONNECT_MAX_MS);
assert.equal(h.ticketTimes[2] - dropAt, 1000);
});
test('stop (background, sync off, sign-out) closes and never reconnects', async () => {
const h = harness();
h.socket.start();
await flush();
h.last.handlers.open();
const s = h.last;
h.socket.stop();
assert.equal(s.closed, true);
assert.equal(h.socket.state(), 'closed');
s.handlers.close();
await h.clock.advance(600_000);
assert.equal(h.ticketTimes.length, 1);
assert.equal(h.clock.pending(), 0);
});
test('stop during a reconnection wait cancels it', async () => {
const h = harness();
h.socket.start();
await flush();
h.last.handlers.close();
await flush();
assert.equal(h.socket.state(), 'waiting');
h.socket.stop();
await h.clock.advance(600_000);
assert.equal(h.ticketTimes.length, 1);
});
test('stop while the ticket is in flight: no socket opens', async () => {
let release;
const h = harness();
const s = createSyncSocket({
now: h.clock.now, setTimer: h.clock.setTimer, clearTimer: h.clock.clearTimer, random: () => 0.5,
canOpen: () => true,
requestTicket: () => new Promise((resolve) => (release = resolve)),
connect: () => assert.fail('stopped: no socket'),
sync: () => {},
});
s.start();
await flush();
s.stop();
release({ kind: 'ok', ticket: 't' });
await h.clock.advance(60_000);
assert.equal(s.state(), 'closed');
});
test('canSync false (sync off, other account): check closes, no reconnection', async () => {
const h = harness();
h.socket.start();
await flush();
h.last.handlers.open();
h.allowed = false;
h.socket.check();
assert.equal(h.last.closed, true);
assert.equal(h.socket.state(), 'closed');
await h.clock.advance(600_000);
assert.equal(h.ticketTimes.length, 1);
});
test('canSync false at reconnection time: closed, no ticket', async () => {
const h = harness();
h.socket.start();
await flush();
h.last.handlers.close();
h.allowed = false;
await h.clock.advance(600_000);
assert.equal(h.ticketTimes.length, 1);
assert.equal(h.socket.state(), 'closed');
});
test('start again (return to foreground): always a fresh socket', async () => {
const h = harness();
h.socket.start();
await flush();
h.last.handlers.open();
const old = h.last;
h.socket.start();
await flush();
assert.equal(old.closed, true);
assert.equal(h.sockets.length, 2);
// Late events of the dropped socket are ignored
old.handlers.message('{"type":"sync"}');
old.handlers.close();
await flush();
assert.equal(h.syncs.length, 0);
assert.equal(h.socket.state(), 'connecting');
});
// --- Notices ---
async function openSocket(h) {
h.socket.start();
await flush();
h.last.handlers.open();
}
const SYNC = '{"type":"sync"}';
test('one notice: one sync at once', async () => {
const h = harness();
await openSocket(h);
await h.clock.advance(5000);
h.last.handlers.message(SYNC);
assert.deepEqual(h.syncs, [5000]);
await h.clock.advance(60_000);
assert.deepEqual(h.syncs, [5000], 'nothing more without notice');
});
test('N notices within 20 s: one more sync at the end of the window', async () => {
const h = harness();
await openSocket(h);
h.last.handlers.message(SYNC);
for (let i = 0; i < 5; i++) {
await h.clock.advance(3000);
h.last.handlers.message(SYNC);
}
assert.deepEqual(h.syncs, [0]);
await h.clock.advance(60_000);
assert.deepEqual(h.syncs, [0, NOTICE_WINDOW_MS]);
});
test('a notice after the window syncs at once again', async () => {
const h = harness();
await openSocket(h);
h.last.handlers.message(SYNC);
await h.clock.advance(NOTICE_WINDOW_MS);
h.last.handlers.message(SYNC);
assert.deepEqual(h.syncs, [0, NOTICE_WINDOW_MS]);
});
test('a steady stream of notices: never more than one sync per 20 s', async () => {
const h = harness();
await openSocket(h);
for (let t = 0; t < 200_000; t += 1000) {
h.last.handlers.message(SYNC);
await h.clock.advance(1000);
}
await h.clock.advance(60_000);
assert.ok(h.syncs.length >= 10 && h.syncs.length <= 11, `${h.syncs.length} syncs in 200 s`);
for (const g of gaps(h.syncs)) assert.ok(g >= NOTICE_WINDOW_MS, `gap ${g} under 20 s`);
});
test('unknown or unreadable messages are ignored', async () => {
const h = harness();
await openSocket(h);
for (const m of ['nope', '{"type":"other"}', '{"kind":"sync"}', null]) h.last.handlers.message(m);
await h.clock.advance(60_000);
assert.deepEqual(h.syncs, []);
assert.equal(h.socket.isOpen(), true);
assert.equal(h.ticketTimes.length, 1);
});
test('stop drops the pending end-of-window sync', async () => {
const h = harness();
await openSocket(h);
h.last.handlers.message(SYNC);
h.last.handlers.message(SYNC);
h.socket.stop();
await h.clock.advance(60_000);
assert.deepEqual(h.syncs, [0]);
});
// --- Foreground tick ---
test('tick: 30 s while the socket is not open, 2 min while it is', async () => {
const h = harness({ tickets: () => ({ kind: 'failed' }) });
h.socket.start();
let synced = 0;
for (let i = 0; i < 8; i++) {
await h.clock.advance(30_000);
if (h.socket.tick()) synced++;
}
assert.equal(synced, 8, 'socket down: every tick syncs');
const o = harness();
await openSocket(o);
synced = 0;
for (let i = 0; i < 8; i++) {
await o.clock.advance(30_000);
if (o.socket.tick()) synced++;
}
assert.equal(synced, 2, 'socket open: one sync per 2 min over 4 min');
});
test('tick: a socket-triggered sync postpones the tick', async () => {
const h = harness();
await openSocket(h);
await h.clock.advance(10_000);
h.last.handlers.message(SYNC);
await h.clock.advance(20_000);
assert.equal(h.socket.tick(), false, '20 s after a socket sync');
await h.clock.advance(OPEN_TICK_INTERVAL_MS - 20_000);
assert.equal(h.socket.tick(), true);
});