Add optional sync: SyncClient with optimistic concurrency, settings UI, Django DELETE and 409, dev proxy, e2e with real backend

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 17:24:58 +02:00
parent aa2fd84352
commit 4689d25700
20 changed files with 949 additions and 16 deletions
+16
View File
@@ -307,6 +307,22 @@ pre {
margin: 0.25rem 0.5rem 0.25rem 0;
}
.setting.stacked {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.token-input {
width: 100%;
min-height: 2.5rem;
font-family: var(--font-code);
font-size: 0.85rem;
}
.sync-message:empty {
display: none;
}
.author-link {
display: inline-flex;
align-items: center;
+268
View File
@@ -0,0 +1,268 @@
// Client de synchronisation optionnelle de la progression avec le backend Django (même domaine).
// Aucun compte : un jeton secret généré ici identifie le profil (le serveur n'en garde que le hash).
// Cycle : GET (fusion locale) puis PUT de l'état fusionné ; la fusion se fait toujours côté client
// (ProgressStore.import), le serveur ne fait que stocker. Concurrence optimiste : si un autre
// appareil a écrit entre-temps, le serveur répond 409 avec son état, on fusionne et on réessaie.
// L'application ne dépend jamais de ce module pour fonctionner : toute erreur est un état, pas une exception.
const STORAGE_KEY = 'sync';
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{32,128}$/;
const MAX_ATTEMPTS = 4;
const REQUEST_TIMEOUT_MS = 10000;
export class SyncClient extends EventTarget {
#store;
#progress;
#fetch;
#endpoint;
#debounceMs;
#now;
#token = null;
#lastSync = null;
#status = 'off'; // 'off' | 'idle' | 'syncing' | 'error'
#error = null; // 'offline' | 'unauthorized' | 'unavailable' | 'rejected' | 'invalid'
#running = null;
#rerun = false;
#timer = null;
#applying = false;
/**
* @param {object} options
* @param {{get: Function, set: Function}} options.store Magasin clé/valeur du jeton.
* @param {import('./ProgressStore.js').ProgressStore} options.progress
* @param {string} options.endpoint URL de l'API (même domaine que l'application).
*/
constructor({ store, progress, endpoint, fetchFn = (...args) => globalThis.fetch(...args), debounceMs = 2000, now = () => new Date() }) {
super();
this.#store = store;
this.#progress = progress;
this.#endpoint = endpoint;
this.#fetch = fetchFn;
this.#debounceMs = debounceMs;
this.#now = now;
progress.addEventListener('change', () => this.#onProgressChange());
}
/** Jeton aléatoire de 256 bits, base64url (43 caractères) ; jamais dérivé d'une donnée personnelle. */
static generateToken(cryptoApi = globalThis.crypto) {
const bytes = cryptoApi.getRandomValues(new Uint8Array(32));
return btoa(String.fromCharCode(...bytes))
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll('=', '');
}
static isValidToken(token) {
return typeof token === 'string' && TOKEN_PATTERN.test(token);
}
get state() {
return { enabled: this.#token !== null, token: this.#token, status: this.#status, error: this.#error, lastSync: this.#lastSync };
}
async load() {
const saved = await this.#store.get(STORAGE_KEY);
if (saved && SyncClient.isValidToken(saved.token)) {
this.#token = saved.token;
this.#lastSync = typeof saved.lastSync === 'string' ? saved.lastSync : null;
this.#status = 'idle';
}
return this.state;
}
/** Au démarrage : si la synchronisation est active, un cycle immédiat. */
start() {
return this.#token ? this.sync() : Promise.resolve({ ok: false, code: 'disabled' });
}
/** Active la synchronisation avec un nouveau profil, puis envoie la progression locale. */
async enable() {
await this.#setToken(SyncClient.generateToken());
return this.sync();
}
/** Rejoint un profil existant (jeton copié depuis un autre appareil) : les progressions sont fusionnées. */
async link(token) {
const clean = String(token ?? '').trim();
if (!SyncClient.isValidToken(clean)) {
throw new Error('Invalid sync token');
}
await this.#setToken(clean);
return this.sync();
}
/**
* Désactive localement ; avec `eraseRemote`, supprime d'abord les données du serveur
* (si l'effacement échoue, on reste actif pour pouvoir réessayer).
*/
async disable({ eraseRemote = false } = {}) {
if (this.#timer !== null) {
clearTimeout(this.#timer);
this.#timer = null;
}
if (eraseRemote && this.#token) {
const outcome = await this.#call('DELETE');
if (outcome.code || outcome.status !== 204) {
return { ok: false, code: outcome.code ?? (outcome.status === 401 ? 'unauthorized' : 'unavailable') };
}
}
this.#token = null;
this.#lastSync = null;
this.#status = 'off';
this.#error = null;
await this.#store.set(STORAGE_KEY, { token: null, lastSync: null });
this.#emitChange();
return { ok: true };
}
/** Un cycle complet ; les appels simultanés sont regroupés (un cycle de plus au plus). Ne lève jamais. */
sync() {
if (!this.#token) {
return Promise.resolve({ ok: false, code: 'disabled' });
}
if (this.#running) {
this.#rerun = true;
return this.#running;
}
this.#running = (async () => {
let result;
do {
this.#rerun = false;
result = await this.#cycle();
} while (this.#rerun && result.ok);
return result;
})().finally(() => {
this.#running = null;
});
return this.#running;
}
async #setToken(token) {
this.#token = token;
this.#lastSync = null;
this.#status = 'idle';
this.#error = null;
await this.#persist();
this.#emitChange();
}
#onProgressChange() {
// Les changements dus à une fusion venant du serveur ne repartent pas vers le serveur.
if (!this.#token || this.#applying) {
return;
}
clearTimeout(this.#timer);
this.#timer = setTimeout(() => {
this.#timer = null;
this.sync();
}, this.#debounceMs);
}
async #cycle() {
this.#status = 'syncing';
this.#error = null;
this.#emitChange();
let base = null;
const first = await this.#call('GET');
if (first.code) {
return this.#fail(first.code);
}
if (first.status === 200) {
base = first.body.updated_at ?? null;
if (!(await this.#merge(first.body.payload))) {
return this.#fail('invalid');
}
} else if (first.status !== 404 || !first.fromApi) {
// 404 d'un serveur statique (sans Django) : la synchronisation n'est pas disponible ici.
return this.#fail(first.status === 401 ? 'unauthorized' : 'unavailable');
}
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
const put = await this.#call('PUT', { payload: JSON.parse(this.#progress.export()), base });
if (put.code) {
return this.#fail(put.code);
}
if (put.status === 200) {
this.#lastSync = this.#now().toISOString();
this.#status = 'idle';
await this.#persist();
this.#emitChange();
return { ok: true };
}
if (put.status === 409) {
// Un autre appareil a écrit entre notre lecture et notre envoi : on fusionne son état.
base = put.body.updated_at ?? null;
if (!(await this.#merge(put.body.payload))) {
return this.#fail('invalid');
}
continue;
}
return this.#fail(put.status === 401 ? 'unauthorized' : put.status === 400 || put.status === 413 ? 'rejected' : 'unavailable');
}
return this.#fail('unavailable');
}
/** Fusionne un état venant du serveur (donnée non fiable : ProgressStore la valide). */
async #merge(payload) {
const before = this.#progress.export();
this.#applying = true;
try {
await this.#progress.import(JSON.stringify(payload));
} catch {
return false;
} finally {
this.#applying = false;
}
if (this.#progress.export() !== before) {
this.dispatchEvent(new CustomEvent('merged'));
}
return true;
}
/** @returns {Promise<{status?: number, body?: any, fromApi?: boolean, code?: string}>} `code` seulement si la requête n'a pas abouti. */
async #call(method, body) {
const options = {
method,
headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json', Accept: 'application/json' },
cache: 'no-store',
};
if (body !== undefined) {
options.body = JSON.stringify(body);
}
if (typeof AbortSignal?.timeout === 'function') {
options.signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
}
let response;
try {
response = await this.#fetch(this.#endpoint, options);
} catch {
return { code: 'offline' };
}
const fromApi = (response.headers.get('content-type') ?? '').includes('application/json');
let parsed = null;
if (fromApi && response.status !== 204) {
try {
parsed = await response.json();
} catch {
parsed = null;
}
}
return { status: response.status, body: parsed ?? {}, fromApi };
}
#fail(code) {
this.#status = 'error';
this.#error = code;
this.#emitChange();
return { ok: false, code };
}
async #persist() {
await this.#store.set(STORAGE_KEY, { token: this.#token, lastSync: this.#lastSync });
}
#emitChange() {
this.dispatchEvent(new CustomEvent('change', { detail: this.state }));
}
}
+27 -1
View File
@@ -93,5 +93,31 @@
"backup.import": "Import progress",
"backup.imported": "Progress imported: {n} new level(s).",
"backup.importFailed": "This file is not a valid PyQuest progress file.",
"backup.exported": "Progress exported."
"backup.exported": "Progress exported.",
"sync.title": "Sync between devices (optional)",
"sync.help": "Find your progress on another device. No account: a secret token is enough. Needs a PyQuest server with sync; the app works fine without it.",
"sync.enable": "Turn on sync",
"sync.linkLabel": "Or paste the token from another device",
"sync.link": "Link this device",
"sync.tokenLabel": "Your secret token",
"sync.tokenHelp": "Keep it like a password: it gives access to your progress. If lost, it cannot be recovered (also use the file export).",
"sync.copy": "Copy the token",
"sync.copied": "Token copied.",
"sync.copyFailed": "Could not copy: select the token and copy it by hand.",
"sync.now": "Sync now",
"sync.disable": "Turn off (keep the server data)",
"sync.erase": "Turn off and erase the server data",
"sync.erased": "Sync turned off, server data erased.",
"sync.disabled": "Sync turned off.",
"sync.enabled": "Sync turned on.",
"sync.linked": "Device linked: progress merged.",
"sync.invalidToken": "This token is not valid (at least 32 characters: letters, digits, - and _).",
"sync.status.syncing": "Syncing…",
"sync.status.last": "Last sync: {when}.",
"sync.status.never": "Not synced yet.",
"sync.error.offline": "Offline: will retry when the connection is back. Your local progress is safe.",
"sync.error.unauthorized": "The server refuses this token.",
"sync.error.unavailable": "No sync server available here. Your local progress is safe.",
"sync.error.rejected": "The server rejected the data sent.",
"sync.error.invalid": "The data received from the server is invalid and was ignored."
}
+27 -1
View File
@@ -93,5 +93,31 @@
"backup.import": "Importer une progression",
"backup.imported": "Progression importée : {n} nouveau(x) niveau(x).",
"backup.importFailed": "Ce fichier n'est pas une progression PyQuest valide.",
"backup.exported": "Progression exportée."
"backup.exported": "Progression exportée.",
"sync.title": "Synchronisation entre appareils (facultatif)",
"sync.help": "Retrouve ta progression sur un autre appareil. Pas de compte : un jeton secret suffit. Nécessite un serveur PyQuest avec synchronisation ; l'application fonctionne très bien sans.",
"sync.enable": "Activer la synchronisation",
"sync.linkLabel": "Ou colle le jeton d'un autre appareil",
"sync.link": "Lier cet appareil",
"sync.tokenLabel": "Ton jeton secret",
"sync.tokenHelp": "Garde-le comme un mot de passe : il donne accès à ta progression. S'il est perdu, il ne peut pas être récupéré (utilise aussi l'export en fichier).",
"sync.copy": "Copier le jeton",
"sync.copied": "Jeton copié.",
"sync.copyFailed": "Copie impossible : sélectionne le jeton et copie-le à la main.",
"sync.now": "Synchroniser maintenant",
"sync.disable": "Désactiver (garder les données du serveur)",
"sync.erase": "Désactiver et effacer les données du serveur",
"sync.erased": "Synchronisation désactivée, données du serveur effacées.",
"sync.disabled": "Synchronisation désactivée.",
"sync.enabled": "Synchronisation activée.",
"sync.linked": "Appareil lié : progressions fusionnées.",
"sync.invalidToken": "Ce jeton n'est pas valide (au moins 32 caractères : lettres, chiffres, - et _).",
"sync.status.syncing": "Synchronisation en cours…",
"sync.status.last": "Dernière synchronisation : {when}.",
"sync.status.never": "Pas encore synchronisé.",
"sync.error.offline": "Hors ligne : nouvel essai dès que la connexion revient. Ta progression locale est intacte.",
"sync.error.unauthorized": "Le serveur refuse ce jeton.",
"sync.error.unavailable": "Pas de serveur de synchronisation disponible ici. Ta progression locale est intacte.",
"sync.error.rejected": "Le serveur a refusé les données envoyées.",
"sync.error.invalid": "Les données reçues du serveur sont invalides et ont été ignorées."
}
+51
View File
@@ -8,6 +8,7 @@ import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStor
import { ProgressStore } from './core/ProgressStore.js';
import { PyodideWorkerClient } from './core/PyodideWorkerClient.js';
import { SettingsStore } from './core/SettingsStore.js';
import { SyncClient } from './core/SyncClient.js';
import { ValidationEngine } from './core/ValidationEngine.js';
import { VoiceEngine } from './core/VoiceEngine.js';
import { I18n } from './i18n/i18n.js';
@@ -58,6 +59,7 @@ class App {
#i18n;
#settings;
#progress;
#sync;
#lessons;
#audio;
#voice;
@@ -88,6 +90,9 @@ class App {
this.#progress = new ProgressStore(store);
await this.#progress.load();
// Synchronisation facultative : l'API est sur le même domaine (nginx), sinon l'état « indisponible » s'affiche.
this.#sync = new SyncClient({ store, progress: this.#progress, endpoint: new URL('api/sync/', document.baseURI).href });
await this.#sync.load();
this.#lessons = new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href });
this.#audio = new AudioEngine({ enabled: settings.soundEnabled, volume: settings.volume });
this.#voice = new VoiceEngine({ enabled: settings.voiceEnabled, rate: settings.voiceRate });
@@ -120,8 +125,12 @@ class App {
this.#goTo(event.detail.id);
});
this.#panel = new SettingsPanel(this.#i18n);
this.#panel.setSync(this.#sync.state);
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
this.#panel.addEventListener('sync', (event) => this.#onSync(event.detail));
this.#sync.addEventListener('change', (event) => this.#panel.setSync(event.detail));
this.#sync.addEventListener('merged', () => this.#renderMap());
this.#panel.addEventListener('export', () => this.#exportProgress());
this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file));
@@ -142,6 +151,14 @@ class App {
// Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche.
await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
this.#registerServiceWorker();
// Synchronisation (si activée) : au démarrage, au retour du réseau et quand l'onglet redevient visible.
this.#sync.start();
window.addEventListener('online', () => this.#sync.sync());
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
this.#sync.sync();
}
});
}
/** Vrai si l'apprenant a déjà de l'activité mais pas depuis au moins deux jours. */
@@ -269,6 +286,40 @@ class App {
}
}
async #onSync({ action, token }) {
const t = (key) => this.#i18n.t(key);
const say = (key) => this.#panel.setSync(this.#sync.state, key ? t(key) : '');
if (action === 'enable') {
const result = await this.#sync.enable();
say(result.ok ? 'sync.enabled' : '');
} else if (action === 'link') {
try {
const result = await this.#sync.link(token);
say(result.ok ? 'sync.linked' : '');
} catch {
say('sync.invalidToken');
}
} else if (action === 'now') {
await this.#sync.sync();
say('');
} else if (action === 'disable' || action === 'erase') {
const result = await this.#sync.disable({ eraseRemote: action === 'erase' });
if (result.ok) {
say(action === 'erase' ? 'sync.erased' : 'sync.disabled');
} else {
this.#panel.setSync(this.#sync.state, t(`sync.error.${result.code}`));
}
} else if (action === 'copy') {
try {
await navigator.clipboard.writeText(this.#sync.state.token);
say('sync.copied');
} catch {
// Pas d'API presse-papiers (http, autorisation refusée) : la copie manuelle reste possible.
say('sync.copyFailed');
}
}
}
/** Télécharge la progression en JSON (Blob + lien temporaire : API standard, sans serveur). */
#exportProgress() {
const blob = new Blob([this.#progress.export()], { type: 'application/json' });
+58
View File
@@ -7,6 +7,9 @@ import { el, uniqueId } from './dom.js';
export class SettingsPanel extends EventTarget {
#i18n;
#root;
#syncRoot = el('fieldset', { class: 'setting-group sync-group' });
#syncState = { enabled: false, token: null, status: 'off', error: null, lastSync: null };
#syncMessage = '';
/** @param {import('../i18n/i18n.js').I18n} i18n */
constructor(i18n) {
@@ -43,8 +46,17 @@ export class SettingsPanel extends EventTarget {
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
this.#backupSection(),
this.#syncRoot,
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
);
this.#renderSync();
}
/** Met à jour la section de synchronisation (état du SyncClient ; `message` : résultat d'une action). */
setSync(state, message = this.#syncMessage) {
this.#syncState = state;
this.#syncMessage = message;
this.#renderSync();
}
/** Redonne le focus à un réglage après un nouveau rendu (ex. changement de langue). */
@@ -80,6 +92,52 @@ export class SettingsPanel extends EventTarget {
);
}
#renderSync() {
const t = (key, params) => this.#i18n.t(key, params);
const state = this.#syncState;
const emit = (action, extra = {}) => this.dispatchEvent(new CustomEvent('sync', { detail: { action, ...extra } }));
const button = (key, action, extra) => el('button', { type: 'button', class: 'btn', 'data-action': action, text: t(key), onclick: () => emit(action, extra) });
const activeAction = this.#syncRoot.contains(document.activeElement) ? (document.activeElement.dataset.action ?? 'token') : null;
const children = [el('legend', { text: t('sync.title') }), el('p', { class: 'hint', text: t('sync.help') })];
if (!state.enabled) {
const id = uniqueId('sync-token');
const input = el('input', { id, type: 'text', autocomplete: 'off', spellcheck: 'false', class: 'token-input' });
children.push(
button('sync.enable', 'enable'),
el('div', { class: 'setting stacked' }, el('label', { for: id, text: t('sync.linkLabel') }), input),
el('button', { type: 'button', class: 'btn', 'data-action': 'link', text: t('sync.link'), onclick: () => emit('link', { token: input.value }) }),
);
} else {
const id = uniqueId('sync-mytoken');
const when = state.lastSync ? new Date(state.lastSync).toLocaleString(this.#i18n.lang) : null;
const status =
state.status === 'syncing'
? t('sync.status.syncing')
: state.status === 'error'
? t(`sync.error.${state.error}`)
: when
? t('sync.status.last', { when })
: t('sync.status.never');
children.push(
el('p', { class: 'sync-status', role: 'status', 'data-status': state.status, text: status }),
el('div', { class: 'setting stacked' }, el('label', { for: id, text: t('sync.tokenLabel') }), el('input', { id, type: 'text', readonly: true, class: 'token-input', value: state.token })),
el('p', { class: 'hint', text: t('sync.tokenHelp') }),
button('sync.copy', 'copy'),
button('sync.now', 'now'),
button('sync.disable', 'disable'),
button('sync.erase', 'erase'),
);
}
// Résultat de la dernière action (copie, jeton invalide…) : annoncé aux lecteurs d'écran.
children.push(el('p', { class: 'sync-message', role: 'status', text: this.#syncMessage }));
this.#syncRoot.replaceChildren(...children);
// Le rendu remplace les boutons : on redonne le focus à l'équivalent (ou au jeton) pour le clavier.
if (activeAction) {
(this.#syncRoot.querySelector(`[data-action="${activeAction}"]`) ?? this.#syncRoot.querySelector('.token-input'))?.focus();
}
}
#testButton(labelKey, kind) {
const button = el('button', {
type: 'button',