fix(sync): no merge across accounts, sync off until the first-sync choice #185
13 changed files with 606 additions and 102 deletions
|
|
@ -110,9 +110,10 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
|
|||
- L'Inbox locale a l'identifiant fixe `00000000-0000-0000-0000-000000000001`, remappé vers un UUID serveur à la première sync (`initialMerge`). Une Inbox créée par la sync absorbe toutes les autres Inbox actives du compte (tâches déplacées, Inbox archivées), et elle est insérée avant le déplacement, car la clé étrangère `sl_tasks.list_id` n'est pas différable. Un id déjà présent dans le compte ne fusionne rien. Une seule Inbox est créée par POST, la suivante revient `skipped`. Une tâche envoyée vers une Inbox archivée, à la création comme à la mise à jour, va dans l'Inbox active. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts`, PR #58, #64, #145, `web/src/db/migrations/0002_cleanup_duplicate_inboxes.sql`
|
||||
- `task create` écrit `completed` et `completedAt` ; une tâche terminée sans date reçoit la date du serveur, une tâche non terminée n'a pas de date (#146). — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts`
|
||||
- `initialReset` efface toutes les données locales avant de tirer celles du serveur : un appel ajouté se justifie, et il reste derrière une confirmation de l'utilisateur. — `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`
|
||||
- Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165
|
||||
- Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts`
|
||||
- Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149
|
||||
- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`writeOutboxEntry`, action `update`). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149
|
||||
- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149
|
||||
- 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
|
||||
|
|
@ -133,7 +134,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 si la sync est activée et la session ouverte), `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, 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`
|
||||
- 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`
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ import { redirectUri, postSignOutRedirectUri } from '@/src/lib/logtoConfig';
|
|||
import { getAllTags, createTag, updateTag, deleteTag } from '@/src/db/repository/tags';
|
||||
import { initCalendar } from '@/src/services/calendar';
|
||||
import { syncWidgetData } from '@/src/services/widgetSync';
|
||||
import { scheduleSync, initialMerge, initialReset } from '@/src/services/syncClient';
|
||||
import { scheduleSync, initialMerge, initialReset, pushBeforeSignOut } from '@/src/services/syncClient';
|
||||
import { firstSyncChoice } from '@/src/services/syncRules';
|
||||
import { getInboxId } from '@/src/db/repository/lists';
|
||||
import i18n from '@/src/i18n';
|
||||
import FeedbackModal from '@/src/components/FeedbackModal';
|
||||
|
||||
|
|
@ -104,54 +106,109 @@ export default function SettingsScreen() {
|
|||
]);
|
||||
};
|
||||
|
||||
// First sync (#165): sync stays off until initialMerge or initialReset has
|
||||
// succeeded. Switched on before the choice, it would push the outbox left
|
||||
// by another account under the account just signed in.
|
||||
const runFirstSync = async (kind: 'merge' | 'reset') => {
|
||||
const accountId = useSettingsStore.getState().userId;
|
||||
if (!accountId) return;
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
if (kind === 'merge') {
|
||||
await initialMerge(accountId);
|
||||
} else {
|
||||
await initialReset(accountId);
|
||||
}
|
||||
setSyncEnabled(true);
|
||||
Alert.alert(t('sync.firstSyncTitle'), t(kind === 'merge' ? 'sync.mergeDone' : 'sync.resetDone'));
|
||||
} catch {
|
||||
Alert.alert(t('sync.syncError'));
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Sign out of Logto and forget the account. Local data and dataOwnerId stay
|
||||
// on the device: nothing is pushed nor deleted here.
|
||||
const finishSignOut = async () => {
|
||||
try {
|
||||
await logtoSignOut(postSignOutRedirectUri);
|
||||
} catch {
|
||||
// Sign-out may fail if session expired, that's OK
|
||||
}
|
||||
setSyncEnabled(false);
|
||||
setUserId(null);
|
||||
setLastSyncAt(null);
|
||||
};
|
||||
|
||||
// The first-sync choice, at sign-in and on « Synchroniser » before the
|
||||
// first sync. A device holding another account's data only offers to load
|
||||
// the signed-in account; « Annuler » signs out (#165).
|
||||
const offerFirstSync = async () => {
|
||||
const { dataOwnerId, userId: signedInId } = useSettingsStore.getState();
|
||||
if (!signedInId) return;
|
||||
const localInboxId = await getInboxId();
|
||||
const choice = firstSyncChoice({ dataOwnerId, signedInId, localInboxId });
|
||||
|
||||
if (choice === 'reset-only') {
|
||||
Alert.alert(
|
||||
t('sync.firstSyncTitle'),
|
||||
t('sync.accountSwitchMessage'),
|
||||
[
|
||||
{
|
||||
text: t('common.cancel'),
|
||||
style: 'cancel',
|
||||
onPress: () => {
|
||||
finishSignOut();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: t('sync.loadAccount'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
runFirstSync('reset');
|
||||
},
|
||||
},
|
||||
],
|
||||
{ cancelable: false },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
Alert.alert(
|
||||
t('sync.firstSyncTitle'),
|
||||
t('sync.firstSyncMessage'),
|
||||
[
|
||||
{
|
||||
text: t('sync.mergeLocal'),
|
||||
onPress: () => {
|
||||
runFirstSync('merge');
|
||||
},
|
||||
},
|
||||
{
|
||||
text: t('sync.resetFromServer'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
runFirstSync('reset');
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
const handleSignIn = async () => {
|
||||
try {
|
||||
await logtoSignIn({ redirectUri });
|
||||
const claims = await getIdTokenClaims();
|
||||
setUserId(claims.sub);
|
||||
setSyncEnabled(true);
|
||||
|
||||
// First sync: show merge/reset choice
|
||||
Alert.alert(
|
||||
t('sync.firstSyncTitle'),
|
||||
t('sync.firstSyncMessage'),
|
||||
[
|
||||
{
|
||||
text: t('sync.mergeLocal'),
|
||||
onPress: async () => {
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
await initialMerge();
|
||||
Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone'));
|
||||
} catch {
|
||||
Alert.alert(t('sync.syncError'));
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
text: t('sync.resetFromServer'),
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
await initialReset();
|
||||
Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone'));
|
||||
} catch {
|
||||
Alert.alert(t('sync.syncError'));
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
await offerFirstSync();
|
||||
} catch (err) {
|
||||
console.warn('[auth] sign-in error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Sign-out pushes the pending changes to the account first (#165). Those
|
||||
// still unsent (offline) are counted, and the user may cancel.
|
||||
const handleSignOut = () => {
|
||||
Alert.alert(t('sync.signOutConfirm'), '', [
|
||||
{ text: t('common.cancel'), style: 'cancel' },
|
||||
|
|
@ -159,57 +216,38 @@ export default function SettingsScreen() {
|
|||
text: t('sync.signOut'),
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
setIsSyncing(true);
|
||||
let unsent = 0;
|
||||
try {
|
||||
await logtoSignOut(postSignOutRedirectUri);
|
||||
unsent = await pushBeforeSignOut();
|
||||
} catch {
|
||||
// Sign-out may fail if session expired, that's OK
|
||||
// Counted as nothing unsent: the push logs its own errors
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
setSyncEnabled(false);
|
||||
setUserId(null);
|
||||
setLastSyncAt(null);
|
||||
if (unsent > 0) {
|
||||
Alert.alert(t('sync.unsentWarning', { count: unsent }), '', [
|
||||
{ text: t('common.cancel'), style: 'cancel' },
|
||||
{
|
||||
text: t('sync.signOutAnyway'),
|
||||
style: 'destructive',
|
||||
onPress: () => {
|
||||
finishSignOut();
|
||||
},
|
||||
},
|
||||
]);
|
||||
return;
|
||||
}
|
||||
await finishSignOut();
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const handleSyncNow = async () => {
|
||||
// If never synced before, show first-sync choice
|
||||
if (!lastSyncAt) {
|
||||
Alert.alert(
|
||||
t('sync.firstSyncTitle'),
|
||||
t('sync.firstSyncMessage'),
|
||||
[
|
||||
{
|
||||
text: t('sync.mergeLocal'),
|
||||
onPress: async () => {
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
await initialMerge();
|
||||
Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone'));
|
||||
} catch {
|
||||
Alert.alert(t('sync.syncError'));
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
text: t('sync.resetFromServer'),
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
await initialReset();
|
||||
Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone'));
|
||||
} catch {
|
||||
Alert.alert(t('sync.syncError'));
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
// First sync not done yet (sync still off): offer the choice
|
||||
if (!syncEnabled || !lastSyncAt) {
|
||||
await offerFirstSync();
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -114,15 +114,17 @@ function AppContent() {
|
|||
const appState = useRef(AppState.currentState);
|
||||
const { getAccessToken, isAuthenticated } = useLogto();
|
||||
|
||||
// Register the token getter for syncClient when authenticated
|
||||
// Register the token getter for syncClient when authenticated, sync on or
|
||||
// off: the first sync (initialMerge, initialReset) runs before sync is
|
||||
// switched on (#165). Scheduled syncs stay behind canSync (syncEnabled).
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && syncEnabled) {
|
||||
if (isAuthenticated) {
|
||||
setTokenGetter(getAccessToken);
|
||||
} else {
|
||||
clearTokenGetter();
|
||||
}
|
||||
return () => clearTokenGetter();
|
||||
}, [isAuthenticated, syncEnabled, getAccessToken]);
|
||||
}, [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
|
||||
|
|
|
|||
|
|
@ -6,9 +6,18 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore';
|
|||
type EntityType = 'task' | 'list' | 'tag' | 'taskTag';
|
||||
type Action = 'create' | 'update' | 'delete';
|
||||
|
||||
// Set by initialMerge / initialReset while they run (#165). They run while
|
||||
// sync is still off; a write the user makes meanwhile is queued all the same,
|
||||
// so that it reaches the server once sync is switched on.
|
||||
let firstSyncInProgress = false;
|
||||
|
||||
export function setFirstSyncInProgress(on: boolean): void {
|
||||
firstSyncInProgress = on;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write an entry to the sync outbox if sync is enabled.
|
||||
* The entry id serves as the idempotency key.
|
||||
* Write an entry to the sync outbox if sync is enabled, or while the first
|
||||
* sync runs. The entry id serves as the idempotency key.
|
||||
*/
|
||||
export async function writeOutboxEntry(
|
||||
entityType: EntityType,
|
||||
|
|
@ -17,8 +26,22 @@ export async function writeOutboxEntry(
|
|||
payload: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
const { syncEnabled } = useSettingsStore.getState();
|
||||
if (!syncEnabled) return;
|
||||
if (!syncEnabled && !firstSyncInProgress) return;
|
||||
await queueOutboxEntry(entityType, entityId, action, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write an entry to the sync outbox whatever the setting: for the sync's own
|
||||
* writes (a newer local row kept by the pull, the Inbox created by
|
||||
* initialReset). The first sync runs while sync is still off (#165), and
|
||||
* these entries must reach the server once it is switched on.
|
||||
*/
|
||||
export async function queueOutboxEntry(
|
||||
entityType: EntityType,
|
||||
entityId: string,
|
||||
action: Action,
|
||||
payload: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await db.insert(syncOutbox).values({
|
||||
id: randomUUID(),
|
||||
entityType,
|
||||
|
|
@ -36,7 +59,8 @@ const INSERT_CHUNK = 100;
|
|||
type Executor = Pick<typeof db, 'insert'>;
|
||||
|
||||
/**
|
||||
* Write several entries with an explicit createdAt if sync is enabled: the
|
||||
* Write several entries with an explicit createdAt if sync is enabled (or
|
||||
* while the first sync runs): the
|
||||
* push sends in createdAt order, writeOutboxEntry dates entries by the clock
|
||||
* and two writes in the same millisecond tie. Used by the Inbox repair (#152).
|
||||
*/
|
||||
|
|
@ -51,7 +75,7 @@ export async function writeOutboxEntries(
|
|||
}[]
|
||||
): Promise<void> {
|
||||
const { syncEnabled } = useSettingsStore.getState();
|
||||
if (!syncEnabled || entries.length === 0) return;
|
||||
if ((!syncEnabled && !firstSyncInProgress) || entries.length === 0) return;
|
||||
|
||||
const rows = entries.map((e) => ({
|
||||
id: randomUUID(),
|
||||
|
|
|
|||
|
|
@ -167,7 +167,12 @@
|
|||
"merging": "Merging...",
|
||||
"mergeDone": "Tasks merged successfully!",
|
||||
"resetDone": "Data synced from server.",
|
||||
"syncError": "Sync error"
|
||||
"syncError": "Sync error",
|
||||
"accountSwitchMessage": "This phone holds the data of another account. They stay on that other account; they will be removed from the phone to load the data of this account. What was created on this phone since signing out will be removed too.",
|
||||
"loadAccount": "Load this account",
|
||||
"unsentWarning_one": "{{count}} change has not been sent yet. It will be lost if you switch accounts.",
|
||||
"unsentWarning_other": "{{count}} changes have not been sent yet. They will be lost if you switch accounts.",
|
||||
"signOutAnyway": "Sign out anyway"
|
||||
},
|
||||
"widget": {
|
||||
"title": "Simpl-Liste",
|
||||
|
|
|
|||
|
|
@ -167,7 +167,12 @@
|
|||
"merging": "Fusion en cours...",
|
||||
"mergeDone": "Tâches fusionnées avec succès !",
|
||||
"resetDone": "Données synchronisées depuis le serveur.",
|
||||
"syncError": "Erreur de synchronisation"
|
||||
"syncError": "Erreur de synchronisation",
|
||||
"accountSwitchMessage": "Ce téléphone contient les données d'un autre compte. Elles restent sur cet autre compte ; elles vont être retirées du téléphone pour charger celles de ce compte. Ce qui a été créé sur ce téléphone depuis la déconnexion sera aussi retiré.",
|
||||
"loadAccount": "Charger ce compte",
|
||||
"unsentWarning_one": "{{count}} modification n'est pas encore envoyée. Elle sera perdue si vous changez de compte.",
|
||||
"unsentWarning_other": "{{count}} modifications ne sont pas encore envoyées. Elles seront perdues si vous changez de compte.",
|
||||
"signOutAnyway": "Se déconnecter quand même"
|
||||
},
|
||||
"widget": {
|
||||
"title": "Simpl-Liste",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore';
|
|||
import { getAccessToken } from '@/src/lib/authToken';
|
||||
import { randomUUID } from '@/src/lib/uuid';
|
||||
import { syncWidgetData } from '@/src/services/widgetSync';
|
||||
import { writeOutboxEntry } from '@/src/db/repository/outbox';
|
||||
import { queueOutboxEntry, setFirstSyncInProgress } from '@/src/db/repository/outbox';
|
||||
import {
|
||||
SYNC_EPOCH,
|
||||
keepLocal,
|
||||
|
|
@ -21,9 +21,11 @@ import {
|
|||
isSynced,
|
||||
parseRetryAfter,
|
||||
sendInBatches,
|
||||
remapInboxEntry,
|
||||
type PostResponse,
|
||||
} from '@/src/services/syncRules';
|
||||
import {
|
||||
canSync,
|
||||
createSyncScheduler,
|
||||
type RequestTracker,
|
||||
type RunOutcome,
|
||||
|
|
@ -227,7 +229,7 @@ async function applyListChange(id: string, action: string, payload: Record<strin
|
|||
const [local] = await db.select().from(lists).where(eq(lists.id, id));
|
||||
if (keepLocal(local, payload, since)) {
|
||||
// Newer offline edit: keep it and push it back to the server
|
||||
await writeOutboxEntry('list', id, 'update', listUpdatePayload(local));
|
||||
await queueOutboxEntry('list', id, 'update', listUpdatePayload(local));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -249,7 +251,7 @@ async function applyTaskChange(id: string, action: string, payload: Record<strin
|
|||
const [local] = await db.select().from(tasks).where(eq(tasks.id, id));
|
||||
if (keepLocal(local, payload, since)) {
|
||||
// Newer offline edit: keep it and push it back to the server
|
||||
await writeOutboxEntry('task', id, 'update', taskUpdatePayload(local));
|
||||
await queueOutboxEntry('task', id, 'update', taskUpdatePayload(local));
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -326,11 +328,12 @@ async function fullSync(run: SyncRun): Promise<RunOutcome> {
|
|||
}
|
||||
|
||||
// One scheduler per process: launch, the 30 s interval, the return to the
|
||||
// foreground, local writes and the Settings button all go through it.
|
||||
// foreground, local writes and the Settings button all go through it. No run
|
||||
// while sync is off or the local data belong to another account (#165).
|
||||
const scheduler = createSyncScheduler({
|
||||
now: () => Date.now(),
|
||||
setTimer: (fn, ms) => setTimeout(fn, ms),
|
||||
canRun: () => useSettingsStore.getState().syncEnabled,
|
||||
canRun: () => canSync(useSettingsStore.getState()),
|
||||
run: async (run) => {
|
||||
const outcome = await fullSync(run);
|
||||
await cleanOutbox().catch(() => {});
|
||||
|
|
@ -347,24 +350,62 @@ export function scheduleSync(): Promise<void> {
|
|||
return scheduler.request();
|
||||
}
|
||||
|
||||
/** Wait for the sign-out push, in ms (#165). */
|
||||
const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Last push before sign-out (#165): the pending outbox goes to the account
|
||||
* still signed in. Held in the first-sync state of the scheduler, so never
|
||||
* alongside a sync, with a request reserved outside its budget. Waits
|
||||
* SIGN_OUT_PUSH_TIMEOUT_MS at most (a push still in flight goes on, the
|
||||
* first-sync state ends with it). Pushes nothing when the scheduler could
|
||||
* not run (sync off, data of another account). Returns the number of outbox
|
||||
* entries still unsent.
|
||||
*/
|
||||
export async function pushBeforeSignOut(): Promise<number> {
|
||||
if (canSync(useSettingsStore.getState())) {
|
||||
const push = (async () => {
|
||||
await scheduler.beginInitialSync();
|
||||
try {
|
||||
await pushChanges(scheduler.reserve());
|
||||
} catch (err) {
|
||||
console.warn('[sync] sign-out push error:', err);
|
||||
} finally {
|
||||
scheduler.endInitialSync();
|
||||
}
|
||||
})();
|
||||
await Promise.race([push, sleep(SIGN_OUT_PUSH_TIMEOUT_MS)]);
|
||||
}
|
||||
const unsent = await db
|
||||
.select({ id: syncOutbox.id })
|
||||
.from(syncOutbox)
|
||||
.where(isNull(syncOutbox.syncedAt));
|
||||
return unsent.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* First-time sync: merge all local data to server.
|
||||
* Creates an Inbox on the server, remaps the local hardcoded Inbox ID,
|
||||
* then pushes all lists, tasks, tags, and task-tag relations, and finally
|
||||
* pulls the whole account from SYNC_EPOCH.
|
||||
* pulls the whole account from SYNC_EPOCH. Runs while sync is still off
|
||||
* (#165): `accountId` (the signed-in `sub`) becomes the owner of the local
|
||||
* data once done. Throws when it could not run, so that sync stays off.
|
||||
*/
|
||||
export async function initialMerge(): Promise<void> {
|
||||
export async function initialMerge(accountId: string): Promise<void> {
|
||||
await scheduler.beginInitialSync();
|
||||
setFirstSyncInProgress(true);
|
||||
try {
|
||||
await mergeLocalData();
|
||||
useSettingsStore.getState().setDataOwnerId(accountId);
|
||||
} finally {
|
||||
setFirstSyncInProgress(false);
|
||||
scheduler.endInitialSync();
|
||||
}
|
||||
}
|
||||
|
||||
async function mergeLocalData(): Promise<void> {
|
||||
const headers = await getAuthHeaders();
|
||||
if (!headers['Authorization']) return;
|
||||
if (!headers['Authorization']) throw new Error('Not signed in');
|
||||
|
||||
const operations: SyncOperation[] = [];
|
||||
|
||||
|
|
@ -461,6 +502,12 @@ async function mergeLocalData(): Promise<void> {
|
|||
if (localInbox) {
|
||||
// Update all tasks pointing to the old inbox
|
||||
await db.update(tasks).set({ listId: serverInboxId }).where(eq(tasks.listId, INBOX_ID));
|
||||
// Writes made during the merge still name the fixed local Inbox (#165)
|
||||
const pending = await db.select().from(syncOutbox).where(isNull(syncOutbox.syncedAt));
|
||||
for (const entry of pending) {
|
||||
const remapped = remapInboxEntry(entry, serverInboxId);
|
||||
if (remapped) await db.update(syncOutbox).set(remapped).where(eq(syncOutbox.id, entry.id));
|
||||
}
|
||||
// Delete old inbox and insert with new ID
|
||||
await db.delete(lists).where(eq(lists.id, INBOX_ID));
|
||||
await db.insert(lists).values({
|
||||
|
|
@ -479,27 +526,35 @@ async function mergeLocalData(): Promise<void> {
|
|||
}
|
||||
|
||||
/**
|
||||
* First-time sync: discard local data and pull everything from server.
|
||||
* First-time sync: discard local data and pull everything from server. Also
|
||||
* « Charger ce compte » on a device holding another account's data (#165):
|
||||
* the outbox of that account is deleted with the rest. Runs while sync is
|
||||
* still off: `accountId` (the signed-in `sub`) becomes the owner of the local
|
||||
* data once done. Throws when it could not run, so that sync stays off.
|
||||
*/
|
||||
export async function initialReset(): Promise<void> {
|
||||
export async function initialReset(accountId: string): Promise<void> {
|
||||
await scheduler.beginInitialSync();
|
||||
setFirstSyncInProgress(true);
|
||||
try {
|
||||
await resetFromServer();
|
||||
useSettingsStore.getState().setDataOwnerId(accountId);
|
||||
} finally {
|
||||
setFirstSyncInProgress(false);
|
||||
scheduler.endInitialSync();
|
||||
}
|
||||
}
|
||||
|
||||
async function resetFromServer(): Promise<void> {
|
||||
const headers = await getAuthHeaders();
|
||||
if (!headers['Authorization']) return;
|
||||
if (!headers['Authorization']) throw new Error('Not signed in');
|
||||
|
||||
// 1. Delete all local data
|
||||
// 1. Delete all local data: the device holds nobody's data any more
|
||||
await db.delete(taskTags);
|
||||
await db.delete(tasks);
|
||||
await db.delete(tags);
|
||||
await db.delete(lists);
|
||||
await db.delete(syncOutbox);
|
||||
useSettingsStore.getState().setDataOwnerId(null);
|
||||
|
||||
// 2. Pull everything from server
|
||||
await pullChanges(SYNC_EPOCH, scheduler.tracker);
|
||||
|
|
@ -514,7 +569,7 @@ async function resetFromServer(): Promise<void> {
|
|||
const now = new Date();
|
||||
const inbox = { id, name: 'Inbox', color: null, icon: null, position: 0, isInbox: true };
|
||||
await db.insert(lists).values({ ...inbox, createdAt: now, updatedAt: now });
|
||||
await writeOutboxEntry('list', id, 'create', inbox);
|
||||
await queueOutboxEntry('list', id, 'create', inbox);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -561,3 +561,68 @@ export function planInboxRepair(
|
|||
|
||||
return { inboxId, movedTaskIds: moved.map((t) => t.id), ops, rewrites, discardIds };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// First sync after a sign-in: no merge across accounts (#165)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Choice offered by the first sync: `merge-or-reset` (Fusionner / Remplacer)
|
||||
* or `reset-only` (« Charger ce compte » alone, which empties the device).
|
||||
*/
|
||||
export type FirstSyncChoice = 'merge-or-reset' | 'reset-only';
|
||||
|
||||
export interface FirstSyncInput {
|
||||
/** Account the local data come from (settings store), null when unknown. */
|
||||
dataOwnerId: string | null;
|
||||
/** `sub` of the account just signed in. */
|
||||
signedInId: string;
|
||||
/** Id of the local Inbox (pickInboxId), null when there is none. */
|
||||
localInboxId: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server refuses every local row of another account (ids taken, lists
|
||||
* not owned), so a device holding another account's data only offers to load
|
||||
* the new one: nothing passes from one account to the other (decision of Max,
|
||||
* 2026-10-25). A known owner decides alone. An unknown owner (device signed
|
||||
* out before #165) is told by the Inbox: the fixed id means the device has
|
||||
* never synced, a server id means it has, under an account that may be
|
||||
* another one, so it is treated as one.
|
||||
*/
|
||||
export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: FirstSyncInput): FirstSyncChoice {
|
||||
if (dataOwnerId !== null) return dataOwnerId === signedInId ? 'merge-or-reset' : 'reset-only';
|
||||
if (localInboxId === null || localInboxId === LOCAL_INBOX_ID) return 'merge-or-reset';
|
||||
return 'reset-only';
|
||||
}
|
||||
|
||||
/**
|
||||
* A pending outbox entry that names the fixed local Inbox, rewritten under the
|
||||
* server Inbox id that initialMerge gives it (#165): a task created or moved
|
||||
* in the Inbox during « Fusionner », or an update of the Inbox itself. Null
|
||||
* when the entry does not name the local Inbox (or cannot be read).
|
||||
*/
|
||||
export function remapInboxEntry(
|
||||
entry: { entityType: string; entityId: string; payload: string },
|
||||
inboxId: string,
|
||||
): { entityId: string; payload: string } | null {
|
||||
let data: Record<string, unknown>;
|
||||
try {
|
||||
data = JSON.parse(entry.payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!data || typeof data !== 'object') return null;
|
||||
let entityId = entry.entityId;
|
||||
let changed = false;
|
||||
if (entry.entityType === 'list' && entityId === LOCAL_INBOX_ID) {
|
||||
entityId = inboxId;
|
||||
if (data.id === LOCAL_INBOX_ID) data.id = inboxId;
|
||||
changed = true;
|
||||
}
|
||||
if (entry.entityType === 'task' && data.listId === LOCAL_INBOX_ID) {
|
||||
data.listId = inboxId;
|
||||
changed = true;
|
||||
}
|
||||
return changed ? { entityId, payload: JSON.stringify(data) } : null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,12 +48,33 @@ export interface SchedulerDeps {
|
|||
/** One sync (push then pull). Its errors are swallowed by the scheduler. */
|
||||
run(ctx: SyncRun): Promise<RunOutcome | void>;
|
||||
/**
|
||||
* Checked before each run: false drops the pending requests (sync off, and
|
||||
* later other guards such as the account check of #165).
|
||||
* Checked before each run: false drops the pending requests (canSync: sync
|
||||
* off, or local data of another account, #165).
|
||||
*/
|
||||
canRun?(): boolean;
|
||||
}
|
||||
|
||||
/** Settings read by canSync (#165). */
|
||||
export interface SyncGuardState {
|
||||
syncEnabled: boolean;
|
||||
/** Account the local data come from, null when unknown. */
|
||||
dataOwnerId: string | null;
|
||||
/** `sub` of the signed-in account. */
|
||||
userId: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a scheduled sync may run: sync on, and no local data of another
|
||||
* account (#165). A known owner other than the signed-in account blocks every
|
||||
* sync: its outbox would be pushed under the wrong account. An unknown owner
|
||||
* (device synced before #165) does not block: sync is only switched on once
|
||||
* the first-sync choice has succeeded.
|
||||
*/
|
||||
export function canSync(state: SyncGuardState): boolean {
|
||||
if (!state.syncEnabled) return false;
|
||||
return state.dataOwnerId === null || state.dataOwnerId === state.userId;
|
||||
}
|
||||
|
||||
export interface SyncScheduler {
|
||||
/**
|
||||
* Ask for a sync. Resolves when the run that serves this request ends, or
|
||||
|
|
@ -70,6 +91,14 @@ export interface SyncScheduler {
|
|||
*/
|
||||
beginInitialSync(): Promise<void>;
|
||||
endInitialSync(): void;
|
||||
/**
|
||||
* Run for the push before sign-out (#165), to call inside the first-sync
|
||||
* state: its request is reserved outside the budget. It may send the
|
||||
* remaining budget, and at least one POST even when the budget is spent;
|
||||
* none while a 429 suspends the scheduler. Its requests count in the budget
|
||||
* of the next runs.
|
||||
*/
|
||||
reserve(): SyncRun;
|
||||
}
|
||||
|
||||
export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler {
|
||||
|
|
@ -187,5 +216,14 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler {
|
|||
initial = Math.max(0, initial - 1);
|
||||
pump();
|
||||
},
|
||||
reserve() {
|
||||
const now = deps.now();
|
||||
return {
|
||||
pushBatches: now < suspendedUntil ? 0 : Math.max(1, remaining(now)),
|
||||
request: tracker.request,
|
||||
rateLimited: tracker.rateLimited,
|
||||
isSuspended: () => deps.now() < suspendedUntil,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ interface SettingsState {
|
|||
syncEnabled: boolean;
|
||||
lastSyncAt: string | null; // ISO timestamp
|
||||
userId: string | null;
|
||||
// Account the local data come from (#165): set by initialMerge and
|
||||
// initialReset once done, kept at sign-out, null when the app empties the
|
||||
// device or before any sync (also on a device synced before #165).
|
||||
dataOwnerId: string | null;
|
||||
setTheme: (theme: ThemeMode) => void;
|
||||
setLocale: (locale: 'fr' | 'en') => void;
|
||||
setNotificationsEnabled: (enabled: boolean) => void;
|
||||
|
|
@ -24,6 +28,7 @@ interface SettingsState {
|
|||
setSyncEnabled: (enabled: boolean) => void;
|
||||
setLastSyncAt: (timestamp: string | null) => void;
|
||||
setUserId: (userId: string | null) => void;
|
||||
setDataOwnerId: (dataOwnerId: string | null) => void;
|
||||
}
|
||||
|
||||
// Error of a failed settings load, and who waits for it (whenSettingsHydrated)
|
||||
|
|
@ -42,6 +47,7 @@ export const useSettingsStore = create<SettingsState>()(
|
|||
syncEnabled: false,
|
||||
lastSyncAt: null,
|
||||
userId: null,
|
||||
dataOwnerId: null,
|
||||
setTheme: (theme) => set({ theme }),
|
||||
setLocale: (locale) => set({ locale }),
|
||||
setNotificationsEnabled: (notificationsEnabled) => set({ notificationsEnabled }),
|
||||
|
|
@ -51,6 +57,7 @@ export const useSettingsStore = create<SettingsState>()(
|
|||
setSyncEnabled: (syncEnabled) => set({ syncEnabled }),
|
||||
setLastSyncAt: (lastSyncAt) => set({ lastSyncAt }),
|
||||
setUserId: (userId) => set({ userId }),
|
||||
setDataOwnerId: (dataOwnerId) => set({ dataOwnerId }),
|
||||
}),
|
||||
{
|
||||
name: 'simpl-liste-settings',
|
||||
|
|
|
|||
|
|
@ -240,7 +240,7 @@ check('sync on write and every sync go through the scheduler (#178)', () => {
|
|||
const start = client.indexOf(`export async function ${name}(`);
|
||||
assert.ok(start >= 0, `${name} not found`);
|
||||
const body = client.slice(start, client.indexOf('\n}\n', start));
|
||||
assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`);
|
||||
assert.match(body, /await scheduler\.beginInitialSync\(\);\s*(?:setFirstSyncInProgress\(true\);\s*)?try \{[^]*\} finally \{\s*(?:setFirstSyncInProgress\(false\);\s*)?scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`);
|
||||
}
|
||||
assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted');
|
||||
// Review of PR #184: initialMerge's POST batches count against the budget,
|
||||
|
|
@ -250,6 +250,107 @@ check('sync on write and every sync go through the scheduler (#178)', () => {
|
|||
assert.match(client, /return \{ more: ok && operations\.length > maxBatches \* BATCH_SIZE \};\n\}/, 'pushChanges must report an unsent queue');
|
||||
});
|
||||
|
||||
// A write made during « Fusionner » or « Charger ce compte » (sync still off)
|
||||
// is queued, and the merge points the pending entries at the server Inbox
|
||||
// (/pr-brief 185, Max 2026-11-03). remapInboxEntry is executed by
|
||||
// tests/syncRules.test.mjs; this check locks its wiring.
|
||||
check('writes made during the first sync are queued and follow the server Inbox (#165)', () => {
|
||||
const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
|
||||
const outbox = read('src/db/repository/outbox.ts');
|
||||
assert.equal((outbox.match(/if \(!syncEnabled && !firstSyncInProgress\) return;/g) || []).length, 1, 'writeOutboxEntry queues during the first sync');
|
||||
assert.match(outbox, /if \(\(!syncEnabled && !firstSyncInProgress\) \|\| entries\.length === 0\) return;/, 'writeOutboxEntries queues during the first sync');
|
||||
const client = read('src/services/syncClient.ts');
|
||||
for (const [name, inner] of [['initialMerge', 'mergeLocalData'], ['initialReset', 'resetFromServer']]) {
|
||||
const start = client.indexOf(`export async function ${name}(`);
|
||||
const body = client.slice(start, client.indexOf('\n}\n', start));
|
||||
assert.match(body, new RegExp(`await scheduler\\.beginInitialSync\\(\\);\\s*setFirstSyncInProgress\\(true\\);\\s*try \\{\\s*await ${inner}\\(\\);[^]*\\} finally \\{\\s*setFirstSyncInProgress\\(false\\);\\s*scheduler\\.endInitialSync\\(\\);`), `${name} must queue the user's writes while it runs`);
|
||||
}
|
||||
const merge = client.slice(client.indexOf('async function mergeLocalData('), client.indexOf('export async function initialReset('));
|
||||
const remap = merge.indexOf('await db.update(tasks).set({ listId: serverInboxId }).where(eq(tasks.listId, INBOX_ID));');
|
||||
const pending = merge.indexOf('remapInboxEntry(entry, serverInboxId)');
|
||||
assert.ok(remap >= 0 && pending > remap, 'the pending entries follow the server Inbox after the local remap');
|
||||
assert.match(merge, /const remapped = remapInboxEntry\(entry, serverInboxId\);\s*if \(remapped\) await db\.update\(syncOutbox\)\.set\(remapped\)\.where\(eq\(syncOutbox\.id, entry\.id\)\);/, 'the remapped entry is written back');
|
||||
assert.match(merge, /const pending = await db\.select\(\)\.from\(syncOutbox\)\.where\(isNull\(syncOutbox\.syncedAt\)\);\s*for \(const entry of pending\) \{/, 'every unsent entry is remapped');
|
||||
});
|
||||
|
||||
// No merge across accounts (#165). firstSyncChoice and canSync are executed
|
||||
// by tests/syncRules.test.mjs and tests/syncSchedule.test.mjs; this check
|
||||
// locks their wiring in files node cannot load: sync stays off until the
|
||||
// first-sync choice has succeeded, the owner of the local data is recorded,
|
||||
// « Annuler » touches no data, and sign-out pushes first.
|
||||
check('account switch: sync off until the choice, owner recorded, sign-out pushes first (#165)', () => {
|
||||
const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8');
|
||||
const body = (src, head) => {
|
||||
const start = src.indexOf(head);
|
||||
assert.ok(start >= 0, `${head} not found`);
|
||||
const end = src.indexOf('\n };\n', start);
|
||||
return src.slice(start, end < 0 ? undefined : end);
|
||||
};
|
||||
const settings = read('app/(tabs)/settings.tsx');
|
||||
// setSyncEnabled(true) only once, after a successful initialMerge / initialReset
|
||||
assert.equal((settings.match(/setSyncEnabled\(true\)/g) || []).length, 1, 'one setSyncEnabled(true), in runFirstSync');
|
||||
const run = body(settings, 'const runFirstSync = async (');
|
||||
assert.match(run, /await initialMerge\(accountId\);\s*\} else \{\s*await initialReset\(accountId\);\s*\}\s*setSyncEnabled\(true\);/, 'sync on only after the first sync succeeded');
|
||||
const signIn = body(settings, 'const handleSignIn = async (');
|
||||
assert.ok(!/setSyncEnabled/.test(signIn), 'handleSignIn must not switch sync on before the choice');
|
||||
assert.match(signIn, /setUserId\(claims\.sub\);\s*await offerFirstSync\(\);/);
|
||||
const syncNow = body(settings, 'const handleSyncNow = async (');
|
||||
assert.match(syncNow, /if \(!syncEnabled \|\| !lastSyncAt\) \{\s*await offerFirstSync\(\);\s*return;/);
|
||||
// Both sites go through firstSyncChoice, fed by the persisted owner
|
||||
const offer = body(settings, 'const offerFirstSync = async (');
|
||||
assert.match(offer, /const \{ dataOwnerId, userId: signedInId \} = useSettingsStore\.getState\(\);/);
|
||||
assert.match(offer, /firstSyncChoice\(\{ dataOwnerId, signedInId, localInboxId \}\)/);
|
||||
const onlyStart = offer.indexOf("if (choice === 'reset-only')");
|
||||
assert.ok(onlyStart >= 0, 'reset-only branch not found');
|
||||
const only = offer.slice(onlyStart, offer.indexOf('return;', onlyStart));
|
||||
assert.ok(!/initialMerge|runFirstSync\('merge'\)/.test(only), 'reset-only offers no merge');
|
||||
assert.match(only, /text: t\('common\.cancel'\),\s*style: 'cancel',\s*onPress: \(\) => \{\s*finishSignOut\(\);/, '« Annuler » signs out');
|
||||
assert.match(only, /text: t\('sync\.loadAccount'\),[^]*?runFirstSync\('reset'\);/, '« Charger ce compte » goes through initialReset');
|
||||
// « Annuler » touches no data: neither push, nor reset, nor database
|
||||
const finish = body(settings, 'const finishSignOut = async (');
|
||||
assert.ok(!/initialReset|initialMerge|pushBeforeSignOut|setDataOwnerId|\bdb\b|delete/.test(finish), 'finishSignOut must touch no data');
|
||||
// Sign-out pushes first, then counts what is left
|
||||
const signOut = body(settings, 'const handleSignOut = (');
|
||||
assert.match(signOut, /unsent = await pushBeforeSignOut\(\);[^]*if \(unsent > 0\) \{\s*Alert\.alert\(t\('sync\.unsentWarning', \{ count: unsent \}\)/);
|
||||
assert.ok(signOut.indexOf('pushBeforeSignOut()') < signOut.indexOf('await finishSignOut();'), 'push before the sign-out');
|
||||
|
||||
const client = read('src/services/syncClient.ts');
|
||||
// The scheduler's guard reads the owner of the data
|
||||
assert.match(client, /canRun: \(\) => canSync\(useSettingsStore\.getState\(\)\),/);
|
||||
const fnBody = (name) => {
|
||||
const start = client.indexOf(`export async function ${name}(`);
|
||||
assert.ok(start >= 0, `${name} not found`);
|
||||
return client.slice(start, client.indexOf('\n}\n', start));
|
||||
};
|
||||
// The owner is recorded once the first sync is done, cleared with the data
|
||||
assert.match(fnBody('initialMerge'), /await mergeLocalData\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/);
|
||||
assert.match(fnBody('initialReset'), /await resetFromServer\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/);
|
||||
const reset = client.slice(client.indexOf('async function resetFromServer('));
|
||||
assert.match(reset, /await db\.delete\(syncOutbox\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(null\);/, 'the outbox of the other account is deleted, owner cleared');
|
||||
// Neither first sync runs silently without a session: sync would stay off
|
||||
for (const name of ['mergeLocalData', 'resetFromServer']) {
|
||||
const start = client.indexOf(`async function ${name}(`);
|
||||
assert.match(client.slice(start, start + 300), /if \(!headers\['Authorization'\]\) throw new Error\(/, `${name} must throw without a session`);
|
||||
}
|
||||
// Sign-out push: guarded, in the first-sync state, reserved run, bounded
|
||||
const push = fnBody('pushBeforeSignOut');
|
||||
assert.match(client, /const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000;/);
|
||||
assert.match(push, /if \(canSync\(useSettingsStore\.getState\(\)\)\) \{/);
|
||||
assert.match(push, /await scheduler\.beginInitialSync\(\);\s*try \{\s*await pushChanges\(scheduler\.reserve\(\)\);[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/);
|
||||
assert.match(push, /await Promise\.race\(\[push, sleep\(SIGN_OUT_PUSH_TIMEOUT_MS\)\]\);/);
|
||||
assert.match(push, /\.where\(isNull\(syncOutbox\.syncedAt\)\);\s*return unsent\.length;/);
|
||||
assert.ok(!/pullChanges|fullSync/.test(push), 'the sign-out push does not pull');
|
||||
|
||||
// dataOwnerId is persisted with the settings and never cleared at sign-out
|
||||
const store = read('src/stores/useSettingsStore.ts');
|
||||
assert.match(store, /dataOwnerId: null,/);
|
||||
assert.ok(!/partialize/.test(store), 'every setting is persisted, dataOwnerId included');
|
||||
|
||||
// The token getter follows the session, not syncEnabled: the first sync runs sync off
|
||||
const layout = read('app/_layout.tsx');
|
||||
assert.match(layout, /if \(isAuthenticated\) \{\s*setTokenGetter\(getAccessToken\);/);
|
||||
});
|
||||
|
||||
// Tags must not go through keepLocal: the server's tag updated_at is its
|
||||
// created_at (no updatedAt column), so a local rename would always look newer
|
||||
// (PR #157 review). syncClient.ts cannot load under node, hence a source check.
|
||||
|
|
@ -325,7 +426,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => {
|
|||
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*\\}`),
|
||||
new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await queueOutboxEntry\\('${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`);
|
||||
|
|
@ -333,7 +434,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => {
|
|||
// 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');
|
||||
assert.ok(!/\bkeepLocal\b|writeOutboxEntry|queueOutboxEntry|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('mergeLocalData');
|
||||
const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)');
|
||||
|
|
@ -437,7 +538,8 @@ check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => {
|
|||
const reset = client.slice(client.indexOf('export async function initialReset('), client.indexOf('export async function cleanOutbox('));
|
||||
assert.ok(!/ensureInbox/.test(reset), 'initialReset must not fall back to the fixed Inbox');
|
||||
assert.match(reset, /if \(!hasInbox\) \{\s*(\/\/[^\n]*\s*)*const id = randomUUID\(\);/);
|
||||
assert.match(reset, /await writeOutboxEntry\('list', id, 'create', inbox\);/);
|
||||
// #165: written whatever syncEnabled, since initialReset runs before sync is on
|
||||
assert.match(reset, /await queueOutboxEntry\('list', id, 'create', inbox\);/);
|
||||
assert.match(reset, /const inbox = \{[^}]*isInbox: true \}/);
|
||||
// Callers await the Inbox read from the database
|
||||
assert.match(read('app/(tabs)/index.tsx'), /await getInboxId\(\)/);
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ import {
|
|||
LOCAL_INBOX_ID,
|
||||
pickInboxId,
|
||||
planInboxRepair,
|
||||
firstSyncChoice,
|
||||
remapInboxEntry,
|
||||
} from '../src/services/syncRules.ts';
|
||||
|
||||
const ID = '11111111-1111-4111-8111-111111111111';
|
||||
|
|
@ -845,3 +847,72 @@ test('planInboxRepair: the repaired outbox of a split device is pushed without a
|
|||
assert.deepEqual(server.state.tasks.get(T4), { listId: SERVER_INBOX, deleted: true });
|
||||
assert.deepEqual([...server.state.links], [`${T1}:${TAG_A}`]);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// firstSyncChoice: no merge across accounts (#165)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ACCOUNT_A = 'logto-sub-account-a';
|
||||
const ACCOUNT_B = 'logto-sub-account-b';
|
||||
const SERVER_INBOX_ID = '33333333-3333-4333-8333-333333333333';
|
||||
|
||||
test('firstSyncChoice: table of the first-sync choice', () => {
|
||||
const rows = [
|
||||
// [case, dataOwnerId, signedInId, localInboxId, expected]
|
||||
['never synced, fixed Inbox', null, ACCOUNT_B, LOCAL_INBOX_ID, 'merge-or-reset'],
|
||||
['never synced, no Inbox yet', null, ACCOUNT_B, null, 'merge-or-reset'],
|
||||
['same account', ACCOUNT_A, ACCOUNT_A, SERVER_INBOX_ID, 'merge-or-reset'],
|
||||
['other account', ACCOUNT_A, ACCOUNT_B, SERVER_INBOX_ID, 'reset-only'],
|
||||
['unknown owner, fixed Inbox', null, ACCOUNT_A, LOCAL_INBOX_ID, 'merge-or-reset'],
|
||||
['unknown owner, server Inbox', null, ACCOUNT_A, SERVER_INBOX_ID, 'reset-only'],
|
||||
];
|
||||
for (const [name, dataOwnerId, signedInId, localInboxId, expected] of rows) {
|
||||
assert.equal(firstSyncChoice({ dataOwnerId, signedInId, localInboxId }), expected, name);
|
||||
}
|
||||
});
|
||||
|
||||
// Regression (#165): sign-out resets userId to null but keeps dataOwnerId.
|
||||
// A device holding A's data, signed in to B, only offers to load B, whatever
|
||||
// its Inbox says: comparing to the userId of before the sign-in (null) would
|
||||
// offer the merge again.
|
||||
test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)', () => {
|
||||
const afterSignOut = { dataOwnerId: ACCOUNT_A, userId: null };
|
||||
for (const localInboxId of [SERVER_INBOX_ID, LOCAL_INBOX_ID, null]) {
|
||||
assert.equal(
|
||||
firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_B, localInboxId }),
|
||||
'reset-only',
|
||||
String(localInboxId),
|
||||
);
|
||||
}
|
||||
// Back to A: the choice is offered again
|
||||
assert.equal(
|
||||
firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_A, localInboxId: SERVER_INBOX_ID }),
|
||||
'merge-or-reset',
|
||||
);
|
||||
});
|
||||
|
||||
// remapInboxEntry: writes made during « Fusionner » (/pr-brief 185, Max
|
||||
// 2026-11-03) still name the fixed local Inbox, which the merge replaces by a
|
||||
// server id; the pending entries follow it.
|
||||
test('remapInboxEntry: a task created in the local Inbox during the merge moves to the server Inbox', () => {
|
||||
const entry = { entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, title: 't', listId: LOCAL_INBOX_ID }) };
|
||||
const out = remapInboxEntry(entry, LIST_ID);
|
||||
assert.equal(out.entityId, ID);
|
||||
assert.deepEqual(JSON.parse(out.payload), { id: ID, title: 't', listId: LIST_ID });
|
||||
});
|
||||
|
||||
test('remapInboxEntry: an update of the local Inbox itself takes the server id', () => {
|
||||
const entry = { entityType: 'list', entityId: LOCAL_INBOX_ID, payload: JSON.stringify({ id: LOCAL_INBOX_ID, name: 'Boite' }) };
|
||||
const out = remapInboxEntry(entry, LIST_ID);
|
||||
assert.equal(out.entityId, LIST_ID);
|
||||
assert.deepEqual(JSON.parse(out.payload), { id: LIST_ID, name: 'Boite' });
|
||||
});
|
||||
|
||||
test('remapInboxEntry: entries that do not name the local Inbox are left alone', () => {
|
||||
const other = '33333333-3333-4333-8333-333333333333';
|
||||
assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, listId: other }) }, LIST_ID), null);
|
||||
assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: JSON.stringify({ id: ID, title: 'x' }) }, LIST_ID), null);
|
||||
assert.equal(remapInboxEntry({ entityType: 'list', entityId: other, payload: JSON.stringify({ id: other }) }, LIST_ID), null);
|
||||
assert.equal(remapInboxEntry({ entityType: 'taskTag', entityId: ID, payload: JSON.stringify({ tagId: other }) }, LIST_ID), null);
|
||||
assert.equal(remapInboxEntry({ entityType: 'task', entityId: ID, payload: 'not json' }, LIST_ID), null);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
DEFAULT_RETRY_AFTER_S,
|
||||
MAX_RETRY_AFTER_S,
|
||||
REQUEST_BUDGET,
|
||||
canSync,
|
||||
createSyncScheduler,
|
||||
} from '../src/services/syncSchedule.ts';
|
||||
import { SYNC_DEBOUNCE_MS, requestSync, setSyncSubscriber } from '../src/services/syncTrigger.ts';
|
||||
|
|
@ -386,3 +387,93 @@ test('a failing run releases the scheduler', async () => {
|
|||
await s.request();
|
||||
assert.equal(runs, 2);
|
||||
});
|
||||
|
||||
// --- Account guard and sign-out push (#165) ---
|
||||
|
||||
const A = 'logto-sub-account-a';
|
||||
const B = 'logto-sub-account-b';
|
||||
|
||||
test('canSync: sync on, and local data of the signed-in account or of an unknown owner', () => {
|
||||
assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: A }), true);
|
||||
assert.equal(canSync({ syncEnabled: true, dataOwnerId: null, userId: A }), true, 'device synced before #165');
|
||||
assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: B }), false, 'data of another account');
|
||||
assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: null }), false, 'signed out');
|
||||
assert.equal(canSync({ syncEnabled: false, dataOwnerId: A, userId: A }), false, 'sync off');
|
||||
assert.equal(canSync({ syncEnabled: false, dataOwnerId: null, userId: null }), false);
|
||||
});
|
||||
|
||||
test('data owner other than the signed-in account: the scheduler refuses every sync', async () => {
|
||||
const clock = fakeClock();
|
||||
const server = fakeServer(clock, { batches: 3 });
|
||||
// Even with sync on: the guard reads the owner, not only syncEnabled
|
||||
const settings = { syncEnabled: true, dataOwnerId: A, userId: B };
|
||||
const s = createSyncScheduler({
|
||||
now: clock.now,
|
||||
setTimer: clock.setTimer,
|
||||
run: server.run,
|
||||
canRun: () => canSync(settings),
|
||||
});
|
||||
for (let i = 0; i < 5; i++) s.request();
|
||||
await clock.advance(5 * BUDGET_WINDOW_MS);
|
||||
assert.equal(server.runs, 0);
|
||||
assert.deepEqual(server.requests, [], 'not one request sent under the other account');
|
||||
// « Charger ce compte » done: B owns the data
|
||||
settings.dataOwnerId = B;
|
||||
s.request();
|
||||
await flush();
|
||||
assert.equal(server.runs, 1);
|
||||
});
|
||||
|
||||
test('reserve: the sign-out push gets one request outside a spent budget', async () => {
|
||||
const clock = fakeClock();
|
||||
const server = fakeServer(clock);
|
||||
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run });
|
||||
assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the whole budget when nothing was sent');
|
||||
for (let i = 0; i < REQUEST_BUDGET; i++) s.tracker.request();
|
||||
const run = s.reserve();
|
||||
assert.equal(run.pushBatches, 1, 'one request outside the spent budget');
|
||||
// Its request counts in the budget of the next runs
|
||||
run.request();
|
||||
s.request();
|
||||
await clock.advance(BUDGET_WINDOW_MS - 1);
|
||||
assert.equal(server.runs, 0);
|
||||
await clock.advance(1);
|
||||
assert.equal(server.runs, 1);
|
||||
});
|
||||
|
||||
test('reserve: nothing while a 429 suspends the scheduler', async () => {
|
||||
const clock = fakeClock();
|
||||
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: async () => {} });
|
||||
s.tracker.rateLimited(20);
|
||||
const run = s.reserve();
|
||||
assert.equal(run.pushBatches, 0);
|
||||
assert.equal(run.isSuspended(), true);
|
||||
await clock.advance(20_000);
|
||||
assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the budget once the Retry-After has passed');
|
||||
assert.equal(run.isSuspended(), false);
|
||||
});
|
||||
|
||||
test('the sign-out push never runs alongside a sync, and a sync waits for its end', async () => {
|
||||
const clock = fakeClock();
|
||||
const server = fakeServer(clock, { duration: 1000 });
|
||||
const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run });
|
||||
s.request();
|
||||
await flush();
|
||||
assert.equal(server.runs, 1);
|
||||
// pushBeforeSignOut: first-sync state, then a reserved run
|
||||
let pushing = false;
|
||||
s.beginInitialSync().then(() => {
|
||||
pushing = true;
|
||||
});
|
||||
await flush();
|
||||
assert.equal(pushing, false, 'waits for the sync in flight');
|
||||
await clock.advance(1000);
|
||||
assert.equal(pushing, true);
|
||||
assert.equal(server.active, 0, 'no sync during the sign-out push');
|
||||
s.request();
|
||||
await clock.advance(BUDGET_WINDOW_MS);
|
||||
assert.equal(server.runs, 1, 'no sync before the push ends');
|
||||
s.endInitialSync();
|
||||
await flush();
|
||||
assert.equal(server.runs, 2);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue