Merge branch 'issue-165-account-switch' into issue-179-web-task-tags
This commit is contained in:
commit
6388ffa307
5 changed files with 109 additions and 7 deletions
|
|
@ -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,7 +26,7 @@ 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);
|
||||
}
|
||||
|
||||
|
|
@ -50,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).
|
||||
*/
|
||||
|
|
@ -65,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(),
|
||||
|
|
|
|||
|
|
@ -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 { queueOutboxEntry } from '@/src/db/repository/outbox';
|
||||
import { queueOutboxEntry, setFirstSyncInProgress } from '@/src/db/repository/outbox';
|
||||
import {
|
||||
SYNC_EPOCH,
|
||||
keepLocal,
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
isSynced,
|
||||
parseRetryAfter,
|
||||
sendInBatches,
|
||||
remapInboxEntry,
|
||||
type PostResponse,
|
||||
} from '@/src/services/syncRules';
|
||||
import {
|
||||
|
|
@ -392,10 +393,12 @@ export async function pushBeforeSignOut(): Promise<number> {
|
|||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -499,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({
|
||||
|
|
@ -525,10 +534,12 @@ async function mergeLocalData(): 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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -595,3 +595,34 @@ export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: First
|
|||
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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,29 @@ 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
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ import {
|
|||
pickInboxId,
|
||||
planInboxRepair,
|
||||
firstSyncChoice,
|
||||
remapInboxEntry,
|
||||
} from '../src/services/syncRules.ts';
|
||||
|
||||
const ID = '11111111-1111-4111-8111-111111111111';
|
||||
|
|
@ -889,3 +890,29 @@ test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)',
|
|||
'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);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue