fix(sync): order the speed pull after pages, keep merges retryable

From CodeRabbit's review of #8070:

- The reader started the page pull and the speed pull together. Speed
  fetched just before another device deleted a book could be applied
  after the page pull removed it, bringing its rows back. The speed
  pull now starts once the page pull settles, as the dialog already did.
- A merge carried on after any failure to move the speed, then deleted
  the source on the server, so speed this device had already pushed
  never reached other devices under the target. Only a server without
  speed sync lets it carry on now; any other failure stops before the
  deletion, so the merge can be retried. SyncClient tells the two apart:
  a 404 (no /api/sync/speeds) reads as "no speed sync" (null / false)
  instead of an error, which also stops the reader warning on every
  push against such a server.
- The push route read fields of a null row and failed the batch with a
  500; it now rejects that row and stores the rest.
- The pull test's leftover empty response was consumed by its second
  pull, so the shorter-row check never ran. It runs now: without the
  longer-wins rule it fails with count 130 for 270.

Tests: before the fix the new ReadingStatsTracker case failed with
"expected not to be called at all, but actually been called 1 times"
(speed pulled while the page pull was pending); the merge case with
"promise resolved undefined instead of rejecting"; the client case
threw "Failed to pull speeds" on a 404; the push-cursor case with
"expected 1800000001000 to be +0"; the route case with "Cannot read
properties of null". The related suites (55 files, 651 tests), lint
and format pass.

On the self-hosted stack with dev-web: device B read three pages of the
Chinese book; the server log shows its stats pull, then its speed pull,
then three speed pushes; device A then showed the server's total, 276
characters/min. With the route removed (404), A's statistics still
showed its local speed, and the app logged no speed warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-29 01:10:58 +08:00
parent 119bf28011
commit b08db6c101
No known key found for this signature in database
GPG key ID: FEB86D637D085E7D
9 changed files with 140 additions and 35 deletions

View file

@ -0,0 +1,36 @@
// @vitest-environment node
import { beforeEach, describe, expect, test, vi } from 'vitest';
vi.mock('@/utils/access', () => ({ getAccessToken: vi.fn(async () => 'token') }));
vi.mock('@/services/environment', () => ({ getAPIBaseUrl: () => 'https://example.test/api' }));
import { SyncClient } from '@/libs/sync';
// A server without /api/sync/speeds (older self-hosted builds, or before the
// route is deployed) answers 404: the client reports "no speed sync" instead
// of failing, so callers can tell it from a transient error.
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
vi.stubGlobal('fetch', fetchMock);
});
describe('SyncClient speed sync', () => {
test('a server without the route has no speed sync', async () => {
fetchMock.mockResolvedValue(new Response('Not Found', { status: 404 }));
expect(await new SyncClient().pullSpeeds(null, 1000)).toBeNull();
expect(await new SyncClient().pushSpeeds([])).toBe(false);
});
test('any other failure throws', async () => {
fetchMock.mockResolvedValue(Response.json({ error: 'x' }, { status: 500 }));
await expect(new SyncClient().pullSpeeds(null, 1000)).rejects.toThrow('Failed to pull speeds');
await expect(new SyncClient().pushSpeeds([])).rejects.toThrow('Failed to push speeds');
});
test('a stored push reports success', async () => {
fetchMock.mockResolvedValue(Response.json({ rejected: [] }));
expect(await new SyncClient().pushSpeeds([])).toBe(true);
});
});

View file

@ -132,6 +132,7 @@ describe('POST /api/sync/speeds', () => {
it('stores valid rows through the merge RPC and reports the rest', async () => {
const res = await post({
rows: [
null,
row(),
row({ unit: 'pages' as never }),
row({ count: 0 }),
@ -140,7 +141,7 @@ describe('POST /api/sync/speeds', () => {
],
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ rejected: ['x:1000', 'x:1000', ':1000', 'x:1.5'] });
expect(await res.json()).toEqual({ rejected: [':', 'x:1000', 'x:1000', ':1000', 'x:1.5'] });
expect(rpcMock).toHaveBeenCalledWith('upsert_stat_speeds', { p_rows: [row()] });
});

View file

@ -5,6 +5,9 @@ import { Window } from 'happy-dom';
import type { BookProgress } from '@/types/book';
const mocks = vi.hoisted(() => ({
user: null as object | null,
pullStats: vi.fn(),
pullSpeeds: vi.fn(),
open: vi.fn(),
getBookData: vi.fn(() => null as unknown),
progress: null as BookProgress | null,
@ -16,7 +19,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@/context/EnvContext', () => ({ useEnv: () => ({ appService: {} }) }));
vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: null }) }));
vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: mocks.user }) }));
vi.mock('@/store/readerProgressStore', () => ({
useBookProgress: () => mocks.progress,
getBookProgress: () => mocks.progress,
@ -29,11 +32,11 @@ vi.mock('@/services/statistics/statisticsDb', () => ({
}));
vi.mock('@/services/statistics/statsSync', () => ({
pushStats: vi.fn(),
pullStats: vi.fn(),
pullStats: mocks.pullStats,
pushSpeeds: vi.fn(),
pullSpeeds: vi.fn(),
pullSpeeds: mocks.pullSpeeds,
}));
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => false }));
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => !!mocks.user }));
vi.mock('@/store/settingsStore', () => ({
useSettingsStore: { getState: () => ({ settings: { bookorbit: {}, grimmory: {} } }) },
}));
@ -72,6 +75,27 @@ describe('ReadingStatsTracker', () => {
});
});
describe('ReadingStatsTracker sync', () => {
afterEach(() => {
cleanup();
mocks.user = null;
});
it('pulls reading speed only once the page pull has applied deletions', async () => {
mocks.user = { id: 'u' };
let finishStats!: () => void;
mocks.pullStats.mockReturnValue(new Promise<void>((resolve) => (finishStats = resolve)));
mocks.pullSpeeds.mockResolvedValue(true);
mocks.open.mockResolvedValue(mocks.db);
render(<ReadingStatsTracker bookKey='book-1' />);
await waitFor(() => expect(mocks.pullStats).toHaveBeenCalled());
expect(mocks.pullSpeeds).not.toHaveBeenCalled();
finishStats();
await waitFor(() => expect(mocks.pullSpeeds).toHaveBeenCalled());
});
});
describe('ReadingStatsTracker while TTS plays', () => {
const BOOK_KEY = 'hash1-view1';

View file

@ -46,7 +46,7 @@ const pulled = (r: StatSpeedRecord) => ({
durationMs: r.duration_ms,
});
const speedClient = () => ({
pushSpeeds: vi.fn().mockResolvedValue(undefined),
pushSpeeds: vi.fn().mockResolvedValue(true),
pullSpeeds: vi.fn().mockResolvedValue([]),
});
@ -110,21 +110,30 @@ describe('pushSpeeds', () => {
});
});
describe('pushSpeeds on a server without speed sync', () => {
it('stops quietly and keeps the cursor, to push everything once it has', async () => {
const stats = await db();
await stats.insertReadingSpeed('a', words(Q + 1_000));
const client = speedClient();
client.pushSpeeds.mockResolvedValue(false);
await pushSpeeds(stats, client as never);
expect(await stats.getCursor('speed-push')).toBe(0);
});
});
describe('pullSpeeds', () => {
it('counts other devices’ speed once, skips deleted books’ and its own rows', async () => {
const stats = await db();
await stats.insertReadingSpeed('a', words(Q + 1_000, 50));
await stats.insertReadingSpeed('a', words(Q + 40_000, 70));
const client = speedClient();
client.pullSpeeds
.mockResolvedValueOnce([
// this device's own row coming back: its samples already count
row({ start_time_ms: Q + 1_000, count: 120, duration_ms: 60_000 }),
row({ book_hash: 'b', start_time_ms: Q + 5_000, count: 120 }),
row({ book_hash: 'gone', start_time_ms: Q + 9_000, deleted: true }),
row({ book_hash: 'b', start_time_ms: Q + 5_000, count: 150, duration_ms: 45_000 }),
])
.mockResolvedValueOnce([]);
client.pullSpeeds.mockResolvedValueOnce([
// this device's own row coming back: its samples already count
row({ start_time_ms: Q + 1_000, count: 120, duration_ms: 60_000 }),
row({ book_hash: 'b', start_time_ms: Q + 5_000, count: 120 }),
row({ book_hash: 'gone', start_time_ms: Q + 9_000, deleted: true }),
row({ book_hash: 'b', start_time_ms: Q + 5_000, count: 150, duration_ms: 45_000 }),
]);
await pullSpeeds(stats, client as never);
expect(await stats.getReadingSpeedTotals()).toEqual([
@ -210,8 +219,7 @@ describe('mergeBookStats', () => {
await stats.insertPageEvent(id, { page: 1, startTime: 100, duration: 30, totalPages: 9 });
await stats.insertReadingSpeed('old', words(Q + 1_000));
const client = { ...pages(), ...speedClient() };
client.pullSpeeds.mockRejectedValue(new Error('Failed to pull speeds: Not Found'));
vi.spyOn(console, 'warn').mockImplementation(() => {});
client.pullSpeeds.mockResolvedValue(null);
await mergeBookStats(stats, client as never, [{ bookMd5: 'old', title: 'OLD', authors: '' }], {
bookMd5: 'new',
@ -219,6 +227,25 @@ describe('mergeBookStats', () => {
authors: '',
});
expect((await stats.getBookStats()).map((b) => b.md5)).toEqual(['new']);
expect(client.pushChanges).toHaveBeenCalled();
expect(client.pushSpeeds).not.toHaveBeenCalled();
});
it('changes nothing when moving the speed fails, so the merge can be retried', async () => {
const stats = await db();
const id = await stats.upsertBook({ bookMd5: 'old', title: 'OLD', authors: '' });
await stats.insertPageEvent(id, { page: 1, startTime: 100, duration: 30, totalPages: 9 });
await stats.insertReadingSpeed('old', words(Q + 1_000));
const client = { ...pages(), ...speedClient() };
client.pushSpeeds.mockRejectedValue(new TypeError('Failed to fetch'));
await expect(
mergeBookStats(stats, client as never, [{ bookMd5: 'old', title: 'OLD', authors: '' }], {
bookMd5: 'new',
title: 'NEW',
authors: '',
}),
).rejects.toThrow('Failed to fetch');
expect(client.pushChanges).not.toHaveBeenCalled();
expect((await stats.getBookStats()).map((b) => b.md5)).toEqual(['old']);
});
});

View file

@ -100,7 +100,7 @@ describe('mergeBookStats', () => {
pullChanges: vi.fn().mockResolvedValue({ statBooks: [], statPages: [] }),
pushChanges: vi.fn().mockResolvedValue({}),
pullSpeeds: vi.fn().mockResolvedValue([]),
pushSpeeds: vi.fn().mockResolvedValue(undefined),
pushSpeeds: vi.fn().mockResolvedValue(true),
});
it('pulls, pushes the events under the target in chunks, then deletes the source', async () => {

View file

@ -133,8 +133,13 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
if (cancelled) return;
dbRef.current = db;
if (syncEnabled()) {
runBestEffort(pullStats(db, new SyncClient()));
runBestEffort(pullSpeeds(db, new SyncClient()));
// Speed after pages: a book deleted on another device must be gone
// first, or speed fetched before the deletion could bring it back.
runBestEffort(
pullStats(db, new SyncClient()).finally(() =>
runBestEffort(pullSpeeds(db, new SyncClient())),
),
);
}
}),
);

View file

@ -141,8 +141,11 @@ export class SyncClient {
return result;
}
/** Speed rows changed after `since`, oldest first, at most `limit`. */
async pullSpeeds(since: SpeedCursor | null, limit: number): Promise<StatSpeedRecord[]> {
/**
* Speed rows changed after `since`, oldest first, at most `limit`; null when
* the server has no speed sync (a server without the route answers 404).
*/
async pullSpeeds(since: SpeedCursor | null, limit: number): Promise<StatSpeedRecord[] | null> {
const token = await getAccessToken();
if (!token) throw new Error('Not authenticated');
const params = new URLSearchParams({ limit: String(limit) });
@ -156,11 +159,13 @@ export class SyncClient {
{ headers: { Authorization: `Bearer ${token}` } },
15000,
);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Failed to pull speeds: ${res.statusText}`);
return ((await res.json()) as { rows: StatSpeedRecord[] }).rows;
}
async pushSpeeds(rows: StatSpeedRecord[]): Promise<void> {
/** Whether the rows were stored: false when the server has no speed sync. */
async pushSpeeds(rows: StatSpeedRecord[]): Promise<boolean> {
const token = await getAccessToken();
if (!token) throw new Error('Not authenticated');
const res = await fetchWithTimeout(
@ -172,7 +177,9 @@ export class SyncClient {
},
15000,
);
if (res.status === 404) return false;
if (!res.ok) throw new Error(`Failed to push speeds: ${res.statusText}`);
return true;
}
private async pushRequest(payload: SyncData): Promise<SyncResult> {

View file

@ -25,7 +25,9 @@ const quote = (v: string) => `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"
const isPositive = (v: unknown, max: number): v is number =>
Number.isSafeInteger(v) && (v as number) > 0 && (v as number) <= max;
const isValid = (r: Partial<StatSpeedRecord>) =>
const isValid = (r: Partial<StatSpeedRecord> | null) =>
typeof r === 'object' &&
r !== null &&
typeof r.book_hash === 'string' &&
r.book_hash.length > 0 &&
r.book_hash.length <= 128 &&
@ -112,7 +114,7 @@ export async function POST(req: NextRequest) {
// otherwise one bad row would block every later push from that device.
const valid: StatSpeedRecord[] = [];
const rejected: string[] = [];
for (const r of rows as Partial<StatSpeedRecord>[]) {
for (const r of rows as (Partial<StatSpeedRecord> | null)[]) {
if (isValid(r)) {
const { book_hash, start_time_ms, lang, unit, count, duration_ms } = r as StatSpeedRecord;
valid.push({ book_hash, start_time_ms, lang, unit, count, duration_ms });

View file

@ -134,20 +134,25 @@ export async function pushSpeeds(stats: StatisticsDb, client: SpeedClient): Prom
const buckets = await stats.getSpeedBucketsForPush(cursor);
for (let i = 0; i < buckets.length; i += SPEED_PUSH_CHUNK) {
const chunk = buckets.slice(i, i + SPEED_PUSH_CHUNK);
await client.pushSpeeds(chunk.map(toWireSpeed));
// A server without speed sync: keep the cursor, so all of it goes once it has.
if (!(await client.pushSpeeds(chunk.map(toWireSpeed)))) return;
// Oldest change first, so a chunk's last row is the newest sample sent.
await stats.setCursor('speed-push', chunk[chunk.length - 1]!.lastMs);
}
}
/** Pull other devices' reading speed changed since the pull cursor, a page at a time. */
export async function pullSpeeds(stats: StatisticsDb, client: SpeedClient): Promise<void> {
/**
* Pull other devices' reading speed changed since the pull cursor, a page at a
* time. False when the server has no speed sync.
*/
export async function pullSpeeds(stats: StatisticsDb, client: SpeedClient): Promise<boolean> {
const saved = await stats.getCursor('speed-pull');
let since: SpeedCursor | null = saved
? { ts: new Date(saved - SPEED_PULL_OVERLAP_MS).toISOString(), book: '', start: 0 }
: null;
for (;;) {
const rows = await client.pullSpeeds(since, SPEED_PAGE);
if (!rows) return false;
if (rows.length === 0) break;
await stats.applyRemoteSpeeds(
rows
@ -167,6 +172,7 @@ export async function pullSpeeds(stats: StatisticsDb, client: SpeedClient): Prom
if (newest > (await stats.getCursor('speed-pull'))) await stats.setCursor('speed-pull', newest);
if (rows.length < SPEED_PAGE) break;
}
return true;
}
/**
@ -204,10 +210,9 @@ export async function mergeBookStats(
): Promise<void> {
if (client) {
await pullStats(stats, client);
// Reading speed follows the pages to the target where the server syncs it;
// a server without speed sync still merges the pages.
try {
await pullSpeeds(stats, client);
// Reading speed follows the pages to the target; a server without speed
// sync still merges the pages. Like theirs, a failure stops before deletion.
if (await pullSpeeds(stats, client)) {
for (const source of sources) {
const buckets = await stats.getBookSpeedBuckets(source.bookMd5);
for (let i = 0; i < buckets.length; i += SPEED_PUSH_CHUNK) {
@ -218,8 +223,6 @@ export async function mergeBookStats(
);
}
}
} catch (err) {
console.warn('[stats] reading speed not merged on the server:', err);
}
for (const source of sources) {
const events = await stats.getBookEvents(source.bookMd5);