Fix the audit's concurrency, stale state and delivery findings
Share uploads now reserve their slot, bytes and per-IP count before the disk check, so simultaneous uploads can no longer exceed the limits. Writes to a share's metadata run one after another, and a revocation can no longer be undone by a pending read count. The TCG page ignores a state reload that started before or during a mutation, the last mutation wins, and returning to the page triggers a single reload. The card cache confirms writes only once the IndexedDB transaction completes and shows only the current player's copy. The administration panel loads on demand, which shrinks the TCG chunk from 311.6 to 191.8 kB. A new /api/health route answers 503 when the cards or shares API failed to start. The deploy script ships the commit's production dependencies with the build, waits up to 30 s for a healthy server instead of trusting systemctl is-active, and restores node_modules on rollback. Both Forgejo workflows check the route on the public site. The updated script applies once reinstalled on the server. Unused helpers, the ignored join role and duplicate button selectors are removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0571a935d6
commit
067a4a8fd6
20 changed files with 391 additions and 73 deletions
|
|
@ -1,7 +1,6 @@
|
|||
// Rôle : assemble l'authentification, les sections adressables et le cache local de Sokko TCG.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { navigate } from "../../router/hashRouter.js";
|
||||
import { AdminPanel } from "./admin/AdminPanel.jsx";
|
||||
import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js";
|
||||
import { AccountPanel } from "./AccountPanel.jsx";
|
||||
import { deleteCardsAccount, devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js";
|
||||
|
|
@ -28,12 +27,19 @@ const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUB
|
|||
const PLAYER_SECTION_ALIASES = { recycling: "collection" };
|
||||
|
||||
const DISCORD_AUTH_PARAM = "cardsAuth";
|
||||
// Réservée aux administrateurs : les joueurs ne téléchargent pas son code.
|
||||
const AdminPanel = lazy(() => import("./admin/AdminPanel.jsx").then((module) => ({ default: module.AdminPanel })));
|
||||
|
||||
// React peut abandonner un rendu ou remonter la page : l'initialiseur ne fait que lire, le nettoyage attend un écran affiché.
|
||||
function readDiscordAuthFailure() {
|
||||
return new URLSearchParams(window.location.search).get(DISCORD_AUTH_PARAM) || "";
|
||||
}
|
||||
|
||||
// Le cache est un confort hors connexion : un refus du stockage ne doit ni bloquer le jeu ni laisser une promesse rejetée.
|
||||
function saveCardsCache(state, catalog) {
|
||||
void writeCardsCache(state, catalog).catch(() => {});
|
||||
}
|
||||
|
||||
function clearDiscordAuthFailure() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (!params.has(DISCORD_AUTH_PARAM)) return;
|
||||
|
|
@ -63,11 +69,24 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
// Le catalogue peut être remplacé par l'administration : le chargement initial ne doit pas se relancer pour autant.
|
||||
const configCatalogRef = useRef(cardsConfig.catalog);
|
||||
useEffect(() => { configCatalogRef.current = cardsConfig.catalog; }, [cardsConfig.catalog]);
|
||||
// Une relecture de l'état ne s'applique que si rien de plus récent ne l'a dépassée : chaque mutation, déconnexion ou
|
||||
// nouvelle lecture change la génération, et une réponse partie avant ce changement est ignorée.
|
||||
const stateGeneration = useRef(0);
|
||||
const latestMutation = useRef(0);
|
||||
const refreshInFlight = useRef(null);
|
||||
const reloadState = useCallback(async () => {
|
||||
const generation = ++stateGeneration.current;
|
||||
const next = await loadCardsState();
|
||||
if (generation !== stateGeneration.current) return null;
|
||||
setState(next);
|
||||
return next;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
async function load() {
|
||||
if (configLoading) return;
|
||||
let playerId = null;
|
||||
try {
|
||||
if (!configEnabled) throw new Error(configError || content.disabled);
|
||||
const session = await loadCardsSession();
|
||||
|
|
@ -77,14 +96,16 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
setStatus("anonymous");
|
||||
return;
|
||||
}
|
||||
playerId = session.player.id;
|
||||
const next = await loadCardsState();
|
||||
if (!active) return;
|
||||
setState(next);
|
||||
setStatus("ready");
|
||||
setOffline(false);
|
||||
void writeCardsCache(next, configCatalogRef.current);
|
||||
saveCardsCache(next, configCatalogRef.current);
|
||||
} catch (loadError) {
|
||||
const cached = await readLatestCardsCache().catch(() => null);
|
||||
// Session reconnue : seule la copie de ce joueur peut s'afficher. Serveur injoignable : la dernière copie enregistrée.
|
||||
const cached = await readLatestCardsCache(playerId).catch(() => null);
|
||||
if (!active) return;
|
||||
if (cached?.state && cached?.catalog) {
|
||||
setState(cached.state);
|
||||
|
|
@ -122,26 +143,26 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
if (status !== "ready" || offline || !nextOpeningAt) return undefined;
|
||||
const timeout = window.setTimeout(async () => {
|
||||
try {
|
||||
const next = await loadCardsState();
|
||||
setState(next);
|
||||
void writeCardsCache(next, catalog);
|
||||
const next = await reloadState();
|
||||
if (next) saveCardsCache(next, catalog);
|
||||
} catch {
|
||||
// Le prochain chargement ou une mutation resynchronisera l'état serveur.
|
||||
}
|
||||
}, Math.max(0, nextOpeningAt - Date.now()) + 250);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [catalog, offline, state?.recharge?.nextOpeningAt, status]);
|
||||
}, [catalog, offline, reloadState, state?.recharge?.nextOpeningAt, status]);
|
||||
|
||||
// Les propositions arrivent sans notification : l'état se resynchronise au retour sur la page.
|
||||
useEffect(() => {
|
||||
if (status !== "ready" || offline) return undefined;
|
||||
async function refresh() {
|
||||
if (globalThis.document.visibilityState !== "visible") return;
|
||||
try {
|
||||
setState(await loadCardsState());
|
||||
} catch {
|
||||
// Le prochain retour ou la prochaine action resynchronisera l'état serveur.
|
||||
}
|
||||
// Le focus et visibilitychange arrivent ensemble au retour sur l'onglet : une seule lecture part.
|
||||
function refresh() {
|
||||
if (globalThis.document.visibilityState !== "visible" || refreshInFlight.current) return;
|
||||
refreshInFlight.current = reloadState()
|
||||
.catch(() => {
|
||||
// Le prochain retour ou la prochaine action resynchronisera l'état serveur.
|
||||
})
|
||||
.finally(() => { refreshInFlight.current = null; });
|
||||
}
|
||||
window.addEventListener("focus", refresh);
|
||||
globalThis.document.addEventListener("visibilitychange", refresh);
|
||||
|
|
@ -149,24 +170,29 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
window.removeEventListener("focus", refresh);
|
||||
globalThis.document.removeEventListener("visibilitychange", refresh);
|
||||
};
|
||||
}, [offline, status]);
|
||||
}, [offline, reloadState, status]);
|
||||
|
||||
async function runMutation(action) {
|
||||
if (offline) return null;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
// Une lecture partie avant ou pendant la mutation décrit un état que la mutation a peut-être déjà remplacé :
|
||||
// la génération change au début et à la fin, et seule la dernière mutation lancée applique son résultat.
|
||||
const mutation = ++latestMutation.current;
|
||||
stateGeneration.current += 1;
|
||||
try {
|
||||
const result = await action();
|
||||
const next = result?.state || result;
|
||||
if (next?.player) {
|
||||
if (next?.player && mutation === latestMutation.current) {
|
||||
setState(next);
|
||||
void writeCardsCache(next, catalog);
|
||||
saveCardsCache(next, catalog);
|
||||
}
|
||||
return result;
|
||||
} catch (mutationError) {
|
||||
setError(mutationError.message);
|
||||
return null;
|
||||
} finally {
|
||||
stateGeneration.current += 1;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
|
@ -176,10 +202,10 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
setError("");
|
||||
try {
|
||||
await devLogin();
|
||||
const next = await loadCardsState();
|
||||
setState(next);
|
||||
const next = await reloadState();
|
||||
if (!next) return;
|
||||
setStatus("ready");
|
||||
void writeCardsCache(next, catalog);
|
||||
saveCardsCache(next, catalog);
|
||||
} catch (loginError) {
|
||||
setError(loginError.message);
|
||||
} finally {
|
||||
|
|
@ -225,6 +251,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
}
|
||||
|
||||
async function logout() {
|
||||
stateGeneration.current += 1;
|
||||
await logoutCards();
|
||||
await clearCardsCache().catch(() => {});
|
||||
setState(null);
|
||||
|
|
@ -239,7 +266,9 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
|
|||
// L'administration a son propre en-tête compact (titre, actualisation, joueur).
|
||||
if (adminMode && state.player.isAdmin) return <div className="nebula-cards-page">
|
||||
{notices}
|
||||
<AdminPanel catalog={catalog} state={state} runMutation={runMutation} busy={busy || offline} section={adminSection} subsection={adminSubsection} onCatalogChange={cardsConfig.replaceCatalog} backLabel={content.admin.backToGame} onLogout={offline ? null : logout} />
|
||||
<Suspense fallback={<section className="empty nds-empty-state" aria-busy="true"><h1>{content.loadingTitle}</h1><p>{content.loadingText}</p></section>}>
|
||||
<AdminPanel catalog={catalog} state={state} runMutation={runMutation} busy={busy || offline} section={adminSection} subsection={adminSubsection} onCatalogChange={cardsConfig.replaceCatalog} backLabel={content.admin.backToGame} onLogout={offline ? null : logout} />
|
||||
</Suspense>
|
||||
</div>;
|
||||
|
||||
const openPacks = () => navigate("/cards/packs");
|
||||
|
|
|
|||
|
|
@ -13,16 +13,27 @@ function openCache() {
|
|||
});
|
||||
}
|
||||
|
||||
// La promesse ne se résout qu'une fois la transaction validée : une transaction annulée après sa requête la fait échouer.
|
||||
async function transact(mode, callback) {
|
||||
const database = await openCache();
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = database.transaction(STORE, mode);
|
||||
const request = callback(transaction.objectStore(STORE));
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
transaction.oncomplete = () => database.close();
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
});
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const transaction = database.transaction(STORE, mode);
|
||||
let result;
|
||||
transaction.oncomplete = () => resolve(result);
|
||||
transaction.onerror = () => reject(transaction.error);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
try {
|
||||
const request = callback(transaction.objectStore(STORE));
|
||||
request.onsuccess = () => { result = request.result; };
|
||||
} catch (error) {
|
||||
transaction.abort();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function writeCardsCache(state, catalog) {
|
||||
|
|
@ -35,7 +46,10 @@ export function clearCardsCache() {
|
|||
return transact("readwrite", (store) => store.clear());
|
||||
}
|
||||
|
||||
export async function readLatestCardsCache() {
|
||||
// Avec un joueur connu, seule sa propre copie peut servir ; sans lui (serveur injoignable), la plus récente.
|
||||
export async function readLatestCardsCache(playerId = null) {
|
||||
const entries = await transact("readonly", (store) => store.getAll());
|
||||
return entries.filter((entry) => entry.format === SNAPSHOT_FORMAT).sort((left, right) => right.savedAt - left.savedAt)[0] || null;
|
||||
return entries
|
||||
.filter((entry) => entry.format === SNAPSHOT_FORMAT && (playerId == null || entry.playerId === playerId))
|
||||
.sort((left, right) => right.savedAt - left.savedAt)[0] || null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -202,8 +202,8 @@ export function cancelExpedition(expeditionId) {
|
|||
return request(`/admin/expeditions/${encodeURIComponent(expeditionId)}/cancel`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function joinExpedition(expeditionId, { editionId, role }) {
|
||||
return request(`/expeditions/${encodeURIComponent(expeditionId)}/join`, { method: "POST", body: JSON.stringify({ editionId, role }) });
|
||||
export function joinExpedition(expeditionId, { editionId }) {
|
||||
return request(`/expeditions/${encodeURIComponent(expeditionId)}/join`, { method: "POST", body: JSON.stringify({ editionId }) });
|
||||
}
|
||||
|
||||
// Joueur inscrit à un groupe : change de carte (`editionId`) ou se dit prêt (`ready`).
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
// Palette d'ouverture spéciale : reprend les couleurs de la palette holographique de la variation.
|
||||
export const MATCH_HOLO_PALETTE_ID = "match-holo";
|
||||
export const MATCH_HOLO_PALETTE_LABEL = "Comme la palette holo";
|
||||
export const OPENING_SOURCE_LABELS = { card: "carte", collection: "collection", default: "défaut" };
|
||||
|
||||
function setting(catalog, scope, targetId) {
|
||||
return catalog?.mythicOpeningSettings?.find((item) => item.scope === scope && item.targetId === targetId) || null;
|
||||
|
|
@ -28,15 +27,6 @@ export function resolveMythicOpeningStyle(catalog, cardId, collectionId) {
|
|||
return { effect, basePreset, shape: pick("particleShapeId", "shapeId"), palette: pick("particlePaletteId", "paletteId") };
|
||||
}
|
||||
|
||||
export function particlePaletteLabel(catalog, paletteId) {
|
||||
if (paletteId === MATCH_HOLO_PALETTE_ID) return MATCH_HOLO_PALETTE_LABEL;
|
||||
return catalog?.particlePalettes?.find((palette) => palette.id === paletteId)?.label || paletteId;
|
||||
}
|
||||
|
||||
export function particleShapeLabel(catalog, shapeId) {
|
||||
return catalog?.particleShapes?.find((shape) => shape.id === shapeId)?.label || shapeId;
|
||||
}
|
||||
|
||||
// Catalogue d'aperçu où la carte reçoit un réglage d'ouverture précis, sans toucher aux autres réglages.
|
||||
export function withCardOpeningSetting(catalog, cardId, { particleShapeId = null, particlePaletteId = null }) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
// Rôle : regroupe les calculs hebdomadaires/mensuels, occurrences et alertes du calendrier.
|
||||
export const CALENDAR_VIEW_MODES = ["week", "month"];
|
||||
export const CALENDAR_MONTHLY_REPEAT_BY = ["monthDay", "weekday"];
|
||||
export const CALENDAR_REPEAT_MODES = ["none", "daily", "weekly", "monthly"];
|
||||
export const CALENDAR_MONTH_REPEAT_MODES = ["none", "weekly", "monthly"];
|
||||
export const CALENDAR_ALERT_MODES = ["off", "visible", "site"];
|
||||
export const CALENDAR_ALERT_OFFSETS = [10, 5, 0];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue