feat(sync): carry reading speed in page events' ext (owner: Can we sync the raw data, and make every device calculate the speed?)

Replaces the stat_speeds table and /api/sync/speeds route from 119bf2801
and b08db6c10. Reading speed now syncs with the page events it was read in,
so no server change is needed.

- A speed sample waits for the next page event the tracker saves. The page
  turn that ends a sample also saves that page, so the sample goes with it.
  When an idle pause has already saved the page, the next page carries it.
  The event keeps the samples summed per language and unit as
  `{ speed: [{ lang, unit, count, durationMs }] }`.
- Locally, the event's ext goes in the existing readest_page_ext table. The
  speed queries read rows built from it, starting where the event starts.
  Every device builds them the same way for every event it holds, so a
  device's own events coming back from the server meet the same keys and
  change nothing. That removes the remote flag, the speed cursors and the
  dedup guard.
- Push sends ext with each event. /api/sync already stores and returns it,
  and the archive keeps it. Pull reads it, dropping entries it can't
  read. Merges carry ext under the target, and deletions remove it.
- Speed saved before this change stays on its device, and is still merged
  and deleted with its book.

Verified:
- New and converted tests fail without the change, each on an assertion,
  e.g. pageSpeedSync "expected null to deeply equal { speed: [...] }" and
  ReadingStatsTracker "expected [] to deeply equal [[{ lang: 'en', ... }]]"
  (12 failing tests across 5 files); all pass with it.
- 828 tests in the 93 related files (statistics, stats components,
  api routes, libs, database) and pnpm lint pass.
- dev-web on a local self-hosted Supabase whose schema is main's
  (stat_speeds dropped), two fresh browser devices on one account. The
  server rows carry each page's speed in ext. Both devices show English
  398 words/min and Chinese 454 characters/min, the totals of those rows.
  After the second device read more English, both show the combined 327
  words/min. The first device's own events coming back left its numbers
  unchanged.
- Not run: the Tauri app (native Turso). The SQL ran on the Node build
  (tests) and the web WASM build (dev-web).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-29 02:04:49 +08:00
parent 8d95bfebf3
commit 2d91afea89
No known key found for this signature in database
GPG key ID: FEB86D637D085E7D
22 changed files with 359 additions and 1119 deletions

View file

@ -23,7 +23,6 @@ vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: sync.user }) }
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => true }));
vi.mock('@/services/statistics/statsSync', () => ({
pullStats: sync.pullStats,
pullSpeeds: async () => {},
deleteBookStats: sync.deleteBookStats,
}));
vi.mock('@/libs/sync', () => ({ SyncClient: class SyncClient {} }));

View file

@ -24,7 +24,6 @@ vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: sync.user }) }
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => true }));
vi.mock('@/services/statistics/statsSync', () => ({
pullStats: sync.pullStats,
pullSpeeds: async () => {},
deleteBookStats: sync.deleteBookStats,
mergeBookStats: sync.mergeBookStats,
}));

View file

@ -17,17 +17,10 @@ vi.mock('@/utils/misc', async (importOriginal) => ({
getLocale: () => 'de-DE',
}));
vi.mock('@/services/statistics/statisticsDb', () => ({ StatisticsDb: db }));
const sync = vi.hoisted(() => ({
user: null as object | null,
pullStats: vi.fn(),
pullSpeeds: vi.fn(async () => {}),
}));
const sync = vi.hoisted(() => ({ user: null as object | null, pullStats: vi.fn() }));
vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: sync.user }) }));
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => true }));
vi.mock('@/services/statistics/statsSync', () => ({
pullStats: sync.pullStats,
pullSpeeds: sync.pullSpeeds,
}));
vi.mock('@/services/statistics/statsSync', () => ({ pullStats: sync.pullStats }));
vi.mock('@/libs/sync', () => ({ SyncClient: class {} }));
afterEach(() => {
@ -286,26 +279,6 @@ describe('ReadingStatsDialog', () => {
sync.user = null;
});
it('pulls reading speed from other devices too, and still shows pages when it fails', async () => {
let pulled = false;
sync.user = { id: 'u' };
sync.pullStats.mockImplementation(async () => {
pulled = true;
});
sync.pullSpeeds.mockRejectedValue(new Error('Failed to pull speeds: Not Found'));
vi.spyOn(console, 'warn').mockImplementation(() => {});
db.open.mockResolvedValue({
...emptySpeeds,
getQuarterHourDurations: async () => [],
getBookQuarterHourDurations: async () => [],
getReadingTotals: async () => ({ seconds: 0, books: pulled ? 40 : 3, pages: 0 }),
});
await openDialog();
expect(await screen.findByText('40')).toBeTruthy();
expect(sync.pullSpeeds).toHaveBeenCalled();
sync.user = null;
});
it('says so when the statistics fail to load', async () => {
db.open.mockRejectedValue(new Error('locked'));
vi.spyOn(console, 'error').mockImplementation(() => {});

View file

@ -1,36 +0,0 @@
// @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

@ -15,7 +15,6 @@ describe('hot sync API routes', () => {
['/api/sync', () => import('@/pages/api/sync')],
['/api/sync/replicas', () => import('@/pages/api/sync/replicas')],
['/api/sync/vocabulary', () => import('@/pages/api/sync/vocabulary')],
['/api/sync/speeds', () => import('@/pages/api/sync/speeds')],
['/api/send/inbox/claim', () => import('@/pages/api/send/inbox/claim')],
])('%s does not load language detection or DOMPurify', async (_route, load) => {
const loaded: string[] = [];

View file

@ -1,153 +0,0 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { NextRequest } from 'next/server';
import type { StatSpeedRecord } from '@/libs/sync';
// /api/sync/speeds (#8023): keyset-paged pull on the server-stamped
// (updated_at, book_hash, start_time_ms), with rows of a book whose statistics
// were deleted after them flagged; a push that keeps the longer row.
type Call = { method: string; args: unknown[] };
const queries: Call[][] = [];
const responses: Array<{ data: unknown; error: { message: string } | null }> = [];
const makeBuilder = () => {
const chain: Call[] = [];
queries.push(chain);
const builder: Record<string, unknown> = {};
const rec =
(method: string) =>
(...args: unknown[]) => {
chain.push({ method, args });
return builder;
};
for (const m of ['select', 'eq', 'or', 'in', 'not', 'order', 'limit']) builder[m] = rec(m);
// biome-ignore lint/suspicious/noThenProperty: mock PostgREST builder is intentionally thenable
(builder as { then: unknown }).then = (resolve: (v: unknown) => void) =>
resolve(responses.shift() ?? { data: [], error: null });
return builder;
};
const fromMock = vi.fn((_table: string) => makeBuilder());
const rpcMock = vi.fn(async (_fn: string, _args: unknown) => ({ data: 1, error: null }));
let authed = true;
vi.mock('@/utils/supabase', () => ({
createSupabaseClient: () => ({ from: fromMock, rpc: rpcMock }),
}));
vi.mock('@/utils/access', () => ({
validateUserAndToken: async () =>
authed ? { user: { id: 'u1' }, token: 'tok' } : { user: null, token: null },
}));
import { GET, POST } from '@/pages/api/sync/speeds';
const URL_BASE = 'https://web.readest.com/api/sync/speeds';
const get = (qs: string) =>
GET(
new Request(`${URL_BASE}?${qs}`, {
headers: { authorization: 'Bearer tok' },
}) as unknown as NextRequest,
);
const post = (body: unknown) =>
POST(
new Request(URL_BASE, {
method: 'POST',
headers: { authorization: 'Bearer tok', 'content-type': 'application/json' },
body: JSON.stringify(body),
}) as unknown as NextRequest,
);
const row = (patch: Partial<StatSpeedRecord> = {}): StatSpeedRecord => ({
book_hash: 'x',
start_time_ms: 1_000,
lang: 'en',
unit: 'words',
count: 100,
duration_ms: 30_000,
...patch,
});
beforeEach(() => {
authed = true;
queries.length = 0;
responses.length = 0;
fromMock.mockClear();
rpcMock.mockClear();
});
describe('GET /api/sync/speeds', () => {
it('needs a signed-in user', async () => {
authed = false;
expect((await get('')).status).toBe(401);
expect((await post({ rows: [] })).status).toBe(401);
});
it('pages after the given row on the (updated_at, book_hash, start_time_ms) keyset', async () => {
await get('since_ts=2026-11-28T10:00:00.5%2B00:00&since_book=b&since_start=42&limit=50');
const [rows] = queries;
expect(fromMock).toHaveBeenCalledWith('stat_speeds');
expect(rows).toContainEqual({ method: 'eq', args: ['user_id', 'u1'] });
const ts = '"2026-11-28T10:00:00.5+00:00"';
expect(rows).toContainEqual({
method: 'or',
args: [
`updated_at.gt.${ts},and(updated_at.eq.${ts},book_hash.gt."b"),` +
`and(updated_at.eq.${ts},book_hash.eq."b",start_time_ms.gt.42)`,
],
});
expect(rows!.filter((c) => c.method === 'order').map((c) => c.args[0])).toEqual([
'updated_at',
'book_hash',
'start_time_ms',
]);
expect(rows).toContainEqual({ method: 'limit', args: [50] });
});
it('flags rows of a book whose statistics were deleted after them', async () => {
responses.push(
{
data: [
row({ start_time_ms: 1_000 }),
row({ start_time_ms: 5_000 }),
row({ book_hash: 'y' }),
],
error: null,
},
{ data: [{ book_hash: 'x', deleted_at: new Date(3_000).toISOString() }], error: null },
);
const res = await get('');
const { rows } = (await res.json()) as { rows: StatSpeedRecord[] };
expect(rows.map((r) => [r.book_hash, r.start_time_ms, !!r.deleted])).toEqual([
['x', 1_000, true],
['x', 5_000, false],
['y', 1_000, false],
]);
expect(fromMock.mock.calls.map((c) => c[0])).toEqual(['stat_speeds', 'stat_books']);
expect(queries[1]).toContainEqual({ method: 'in', args: ['book_hash', ['x', 'y']] });
});
});
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 }),
row({ book_hash: '' }),
row({ start_time_ms: 1.5 }),
],
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ rejected: [':', 'x:1000', 'x:1000', ':1000', 'x:1.5'] });
expect(rpcMock).toHaveBeenCalledWith('upsert_stat_speeds', { p_rows: [row()] });
});
it('refuses a batch over the cap', async () => {
const res = await post({ rows: Array.from({ length: 1001 }, () => row()) });
expect(res.status).toBe(413);
expect(rpcMock).not.toHaveBeenCalled();
});
});

View file

@ -5,21 +5,17 @@ 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,
playbackState: null as 'playing' | 'paused' | null,
db: {
recordEvents: vi.fn(),
insertReadingSpeed: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/context/EnvContext', () => ({ useEnv: () => ({ appService: {} }) }));
vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: mocks.user }) }));
vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: null }) }));
vi.mock('@/store/readerProgressStore', () => ({
useBookProgress: () => mocks.progress,
getBookProgress: () => mocks.progress,
@ -32,11 +28,9 @@ vi.mock('@/services/statistics/statisticsDb', () => ({
}));
vi.mock('@/services/statistics/statsSync', () => ({
pushStats: vi.fn(),
pullStats: mocks.pullStats,
pushSpeeds: vi.fn(),
pullSpeeds: mocks.pullSpeeds,
pullStats: vi.fn(),
}));
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => !!mocks.user }));
vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => false }));
vi.mock('@/store/settingsStore', () => ({
useSettingsStore: { getState: () => ({ settings: { bookorbit: {}, grimmory: {} } }) },
}));
@ -75,27 +69,6 @@ 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';
@ -167,25 +140,24 @@ describe('ReadingStatsTracker while TTS plays', () => {
it.each([
[80, 20_000],
// A desktop two-page spread read at 250 words/min outlasts the idle timeout.
// A desktop two-page spread read at 250 words/min outlasts the idle timeout,
// which has already saved that page: the next page carries it.
[750, 180_000],
])('records the %i words passed during a forward turn after %i ms', async (words, ms) => {
])('saves the %i words passed during a forward turn after %i ms with a page event', async (words, ms) => {
const openPage = pageOf(words);
const startTimeMs = Date.now();
openPage(0);
const { rerender } = mount();
const { rerender, unmount } = mount();
await settle(ms);
openPage(1);
rerender(<ReadingStatsTracker bookKey={BOOK_KEY} />);
await settle(5_000);
unmount();
await settle();
expect(mocks.db.insertReadingSpeed).toHaveBeenCalledWith('md5-1', {
unit: 'words',
count: words,
startTimeMs,
durationMs: ms,
lang: 'en',
});
const saved = mocks.db.recordEvents.mock.calls.flatMap(([, events]) => events);
expect(saved.filter((e) => e.speed).map((e) => e.speed)).toEqual([
[{ lang: 'en', unit: 'words', count: words, durationMs: ms }],
]);
});
it('stops recording page dwell while TTS is playing', async () => {

View file

@ -0,0 +1,142 @@
// @vitest-environment node
import { describe, it, expect } from 'vitest';
import { NodeDatabaseService } from '@/services/database/nodeDatabaseService';
import { migrate } from '@/services/database/migrate';
import { getMigrations } from '@/services/database/migrations';
import { StatisticsDb } from '@/services/statistics/statisticsDb';
import { mergeBookStats, pullStats, pushStats } from '@/services/statistics/statsSync';
import type { StatBookRecord, StatPageRecord, SyncData } from '@/libs/sync';
import type { PageSpeed } from '@/types/statistics';
// Reading speed syncs with the page events (#8023): each event carries the
// speed read while it was open in `ext`, and every device works speed out
// from the events it holds.
async function device() {
const d = await NodeDatabaseService.open(':memory:');
await migrate(d, getMigrations('statistics'));
return StatisticsDb.from(d);
}
// One account on /api/sync: a page event it already holds is replaced only by
// a longer copy (upsert_stat_pages), and `ext` goes through as JSON.
function server() {
const books = new Map<string, StatBookRecord>();
const pages = new Map<string, StatPageRecord>();
let clock = 0;
return {
pages,
pushChanges: async ({ statBooks = [], statPages = [] }: SyncData) => {
for (const b of statBooks) books.set(b.book_hash, { ...b, updated_at_ms: ++clock });
for (const p of JSON.parse(JSON.stringify(statPages)) as StatPageRecord[]) {
const key = `${p.book_hash}:${p.page}:${p.start_time}`;
const held = pages.get(key);
if (!held || p.duration > held.duration) {
pages.set(key, { ...p, ext: p.ext ?? null, updated_at_ms: ++clock });
}
}
return { books: null, notes: null, configs: null };
},
pullChanges: async (since: number) => ({
books: null,
notes: null,
configs: null,
statBooks: [...books.values()].filter((b) => b.updated_at_ms! > since),
statPages: [...pages.values()].filter((p) => p.updated_at_ms! > since),
}),
};
}
const BOOK = { bookMd5: 'm1', title: 'Book', authors: 'A' };
const en: PageSpeed = { lang: 'en', unit: 'words', count: 250, durationMs: 60_000 };
const fr: PageSpeed = { lang: 'fr', unit: 'words', count: 40, durationMs: 15_000 };
describe('reading speed in page events', () => {
it('counts on another device, and once when a device pulls its own events', async () => {
const cloud = server();
const a = await device();
await a.recordEvents(BOOK, [
{ page: 1, startTime: 100, duration: 75, totalPages: 9, speed: [en, fr] },
{ page: 2, startTime: 175, duration: 30, totalPages: 9 },
]);
await pushStats(a, cloud);
expect(cloud.pages.get('m1:1:100')!.ext).toEqual({ speed: [en, fr] });
expect(cloud.pages.get('m1:2:175')!.ext).toBeNull();
const b = await device();
await pullStats(b, cloud);
await pullStats(a, cloud);
for (const d of [a, b]) {
expect(await d.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 290, durationMs: 75_000 },
]);
expect(
(await d.getBookReadingSpeeds()).map((s) => [s.title, s.lang, s.count, s.durationMs]),
).toEqual(
expect.arrayContaining([
['Book', 'en', 250, 60_000],
['Book', 'fr', 40, 15_000],
]),
);
}
});
it('keeps the speed on events a merge moves, on the server too', async () => {
const cloud = server();
const a = await device();
await a.recordEvents(BOOK, [
{ page: 1, startTime: 100, duration: 60, totalPages: 9, speed: [en] },
]);
await pushStats(a, cloud);
const target = { bookMd5: 'm2', title: 'Book', authors: 'A' };
await mergeBookStats(a, cloud, [BOOK], target);
expect(cloud.pages.get('m2:1:100')!.ext).toEqual({ speed: [en] });
expect(await a.getBookReadingSpeeds()).toEqual([
expect.objectContaining({ md5: 'm2', count: 250, durationMs: 60_000 }),
]);
// the merged book's speed goes with it when its statistics are deleted
await a.deleteBook('m2');
expect(await a.getReadingSpeedTotals()).toEqual([]);
});
it('ignores speed it cannot read and still applies the event', async () => {
const b = await device();
const page = (start_time: number, ext: unknown): StatPageRecord => ({
book_hash: 'm1',
page: 1,
start_time,
duration: 60,
total_pages: 9,
ext,
updated_at_ms: start_time,
});
let served = false;
await pullStats(b, {
pullChanges: async () => {
const statPages = served
? []
: [
page(100, 'speed'),
page(200, { speed: { ...en } }),
page(300, {
speed: [
{ ...en, unit: 'pages' },
{ ...en, count: -1 },
{ ...en, durationMs: 1.5 },
{ ...en, lang: 7 },
null,
en,
],
}),
];
served = true;
return { books: null, notes: null, configs: null, statBooks: [], statPages };
},
});
expect((await b.getBookStats('m1'))[0]).toMatchObject({ seconds: 180 });
expect(await b.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 250, durationMs: 60_000 },
]);
});
});

View file

@ -1,251 +0,0 @@
// @vitest-environment node
import { describe, it, expect, vi } from 'vitest';
import { NodeDatabaseService } from '@/services/database/nodeDatabaseService';
import { migrate } from '@/services/database/migrate';
import { getMigrations } from '@/services/database/migrations';
import { StatisticsDb } from '@/services/statistics/statisticsDb';
import { mergeBookStats, pullSpeeds, pushSpeeds } from '@/services/statistics/statsSync';
import type { StatSpeedRecord } from '@/libs/sync';
// Reading speed sync (#8023): each device pushes one row per book, language
// and unit for every quarter hour it read in, keyed by its first sample there,
// and keeps the rows it pulls apart from its own samples.
async function db() {
const d = await NodeDatabaseService.open(':memory:');
await migrate(d, getMigrations('statistics'));
return StatisticsDb.from(d);
}
const Q = 1_800_000_000_000; // a quarter hour boundary (Unix ms)
const QUARTER = 900_000;
const words = (startTimeMs: number, count = 100, lang = 'en') => ({
unit: 'words' as const,
count,
durationMs: 30_000,
startTimeMs,
lang,
});
const row = (patch: Partial<StatSpeedRecord> = {}): StatSpeedRecord => ({
book_hash: 'a',
start_time_ms: Q + 60_000,
lang: 'en',
unit: 'words',
count: 100,
duration_ms: 30_000,
updated_at: '2026-11-28T10:00:00.000000+00:00',
...patch,
});
/** A row as this device keeps it once pulled. */
const pulled = (r: StatSpeedRecord) => ({
bookMd5: r.book_hash,
startTimeMs: r.start_time_ms,
lang: r.lang,
unit: r.unit,
count: r.count,
durationMs: r.duration_ms,
});
const speedClient = () => ({
pushSpeeds: vi.fn().mockResolvedValue(true),
pullSpeeds: vi.fn().mockResolvedValue([]),
});
describe('pushSpeeds', () => {
it('pushes each quarter hour once, and again only when it grows', async () => {
const stats = await db();
await stats.insertReadingSpeed('a', words(Q + 1_000));
await stats.insertReadingSpeed('a', words(Q + 40_000, 80));
await stats.insertReadingSpeed('a', { ...words(Q + 70_000, 300, 'zh'), unit: 'characters' });
await stats.insertReadingSpeed('a', words(Q + QUARTER + 5_000, 90));
// pulled from another device: never pushed back
await stats.applyRemoteSpeeds([pulled(row({ start_time_ms: Q + 2_000, count: 999 }))]);
const client = speedClient();
await pushSpeeds(stats, client as never);
expect(client.pushSpeeds).toHaveBeenCalledTimes(1);
expect(client.pushSpeeds.mock.calls[0]![0]).toEqual([
{
book_hash: 'a',
start_time_ms: Q + 1_000,
lang: 'en',
unit: 'words',
count: 180,
duration_ms: 60_000,
},
{
book_hash: 'a',
start_time_ms: Q + 70_000,
lang: 'zh',
unit: 'characters',
count: 300,
duration_ms: 30_000,
},
{
book_hash: 'a',
start_time_ms: Q + QUARTER + 5_000,
lang: 'en',
unit: 'words',
count: 90,
duration_ms: 30_000,
},
]);
expect(await stats.getCursor('speed-push')).toBe(Q + QUARTER + 5_000);
await pushSpeeds(stats, client as never);
expect(client.pushSpeeds).toHaveBeenCalledTimes(1);
// Reading on in the same quarter hour resends that row, grown, under its key.
await stats.insertReadingSpeed('a', words(Q + QUARTER + 50_000, 110));
await pushSpeeds(stats, client as never);
expect(client.pushSpeeds.mock.calls[1]![0]).toEqual([
{
book_hash: 'a',
start_time_ms: Q + QUARTER + 5_000,
lang: 'en',
unit: 'words',
count: 200,
duration_ms: 60_000,
},
]);
});
});
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 }),
]);
await pullSpeeds(stats, client as never);
expect(await stats.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 270, durationMs: 105_000 },
]);
expect(await stats.getCursor('speed-pull')).toBe(Date.parse('2026-11-28T10:00:00Z'));
// A shorter copy of a row already held changes nothing.
client.pullSpeeds.mockResolvedValueOnce([
row({ book_hash: 'b', start_time_ms: Q + 5_000, count: 10, duration_ms: 1_000 }),
]);
await pullSpeeds(stats, client as never);
expect(await stats.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 270, durationMs: 105_000 },
]);
});
it('pages on the last row it got, and resumes a minute before its cursor', async () => {
const stats = await db();
const client = speedClient();
const page = Array.from({ length: 1000 }, (_, i) =>
row({ book_hash: 'b', start_time_ms: Q + i * 1_000 }),
);
client.pullSpeeds.mockResolvedValueOnce(page).mockResolvedValueOnce([]);
await pullSpeeds(stats, client as never);
expect(client.pullSpeeds.mock.calls.map((c) => c[0])).toEqual([
null,
{ ts: '2026-11-28T10:00:00.000000+00:00', book: 'b', start: Q + 999_000 },
]);
await pullSpeeds(stats, client as never);
expect(client.pullSpeeds.mock.calls[2]![0]).toEqual({
ts: '2026-11-28T09:59:00.000Z',
book: '',
start: 0,
});
});
});
describe('mergeBookStats', () => {
const pages = () => ({
pushChanges: vi.fn().mockResolvedValue({}),
pullChanges: vi.fn().mockResolvedValue({}),
});
it('pushes the source’s speed, its own and pulled, under the target', 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));
await stats.insertReadingSpeed('old', words(Q + 2_000));
await stats.applyRemoteSpeeds([pulled(row({ book_hash: 'old', start_time_ms: Q + 3_000 }))]);
const client = { ...pages(), ...speedClient() };
await mergeBookStats(stats, client as never, [{ bookMd5: 'old', title: 'OLD', authors: '' }], {
bookMd5: 'new',
title: 'NEW',
authors: '',
});
expect(client.pushSpeeds).toHaveBeenCalledWith([
{
book_hash: 'new',
start_time_ms: Q + 1_000,
lang: 'en',
unit: 'words',
count: 200,
duration_ms: 60_000,
},
{
book_hash: 'new',
start_time_ms: Q + 3_000,
lang: 'en',
unit: 'words',
count: 100,
duration_ms: 30_000,
},
]);
});
it('still merges when the server has no speed sync', 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.pullSpeeds.mockResolvedValue(null);
await mergeBookStats(stats, client as never, [{ bookMd5: 'old', title: 'OLD', authors: '' }], {
bookMd5: 'new',
title: 'NEW',
authors: '',
});
expect((await stats.getBookStats()).map((b) => b.md5)).toEqual(['new']);
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

@ -114,46 +114,60 @@ describe('StatisticsDb', () => {
stats = StatisticsDb.from(await freshStatsDb());
});
it('keeps local speed samples idempotent and queries intervals that start before the boundary', async () => {
const sample = { unit: 'words' as const, count: 30, startTimeMs: 50_000, durationMs: 20_000 };
await stats.insertReadingSpeed('m1', sample);
await stats.insertReadingSpeed('m1', sample);
await stats.insertReadingSpeed('m2', { ...sample, unit: 'characters', count: 80 });
// Speed is saved with the page event it rode on, and its rows start there.
const readAt = (
md5: string,
startTime: number,
speed: { lang: string; unit: 'words' | 'characters'; count: number; durationMs: number },
title = md5,
) =>
stats.recordEvents({ bookMd5: md5, title, authors: '' }, [
{ page: 1, startTime, duration: speed.durationMs / 1000, totalPages: 9, speed: [speed] },
]);
it('keeps speed idempotent and queries intervals that start before the boundary', async () => {
const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 };
await readAt('m1', 50, speed);
await readAt('m1', 50, speed);
await readAt('m2', 50, { ...speed, lang: 'zh', unit: 'characters', count: 80 });
expect(await stats.getReadingSpeedSamples(60_000, 90_000)).toHaveLength(2);
expect(await stats.getReadingSpeedSamples(70_000, 90_000)).toEqual([]);
expect(await stats.getReadingSpeedTotals()).toEqual([
{ unit: 'characters', count: 80, durationMs: 20_000 },
{ unit: 'words', count: 30, durationMs: 20_000 },
]);
expect(await stats.getReadingTotals()).toEqual({ seconds: 0, books: 0, pages: 0 });
});
it('sums speed by quarter hour and language, and by book', async () => {
await stats.upsertBook({ bookMd5: 'm1', title: 'English Book', authors: 'Author' });
const at = (minute: number) => minute * 60_000;
const sample = (minute: number, lang: string, count: number) => ({
unit: lang === 'zh' ? ('characters' as const) : ('words' as const),
lang,
count,
startTimeMs: at(minute),
durationMs: 20_000,
});
await stats.insertReadingSpeed('m1', sample(1, 'en', 60));
await stats.insertReadingSpeed('m1', sample(2, 'en', 80));
await stats.insertReadingSpeed('m1', sample(16, 'en', 70));
await stats.insertReadingSpeed('m2', sample(2, 'zh', 200));
const read = (md5: string, title: string, minute: number, lang: string, count: number) =>
readAt(
md5,
minute * 60,
{
unit: lang === 'zh' ? ('characters' as const) : ('words' as const),
lang,
count,
durationMs: 20_000,
},
title,
);
await read('m1', 'English Book', 1, 'en', 60);
await read('m1', 'English Book', 2, 'en', 80);
await read('m1', 'English Book', 16, 'en', 70);
await read('m2', 'Chinese Book', 2, 'zh', 200);
expect(await stats.getReadingSpeedQuarters()).toEqual([
{ quarter: 0, lang: 'en', unit: 'words', count: 140, durationMs: 40_000 },
{ quarter: 0, lang: 'zh', unit: 'characters', count: 200, durationMs: 20_000 },
{ quarter: 1, lang: 'en', unit: 'words', count: 70, durationMs: 20_000 },
]);
// Most recently read first; a book without statistics keeps its hash as the title.
// Most recently read first.
expect(await stats.getBookReadingSpeeds()).toEqual([
{
md5: 'm1',
title: 'English Book',
authors: 'Author',
authors: '',
lang: 'en',
unit: 'words',
count: 210,
@ -162,7 +176,7 @@ describe('StatisticsDb', () => {
},
{
md5: 'm2',
title: 'm2',
title: 'Chinese Book',
authors: '',
lang: 'zh',
unit: 'characters',
@ -175,18 +189,9 @@ describe('StatisticsDb', () => {
it('counts a book’s speed once when the book has two metadata rows', async () => {
// KOReader keys book rows on (title, authors, md5), so one md5 can have two.
await stats.upsertBook({ bookMd5: 'm1', title: 'Title', authors: 'Author' });
await readAt('m1', 0, { unit: 'words', lang: 'en', count: 60, durationMs: 20_000 }, 'Title');
const db = (stats as unknown as { db: DatabaseService }).db;
await db.execute(
`INSERT INTO book (title, authors, md5) VALUES ('Other Title', 'Author', 'm1')`,
);
await stats.insertReadingSpeed('m1', {
unit: 'words',
lang: 'en',
count: 60,
startTimeMs: 0,
durationMs: 20_000,
});
await db.execute(`INSERT INTO book (title, authors, md5) VALUES ('Other Title', '', 'm1')`);
expect(await stats.getBookReadingSpeeds()).toEqual([
expect.objectContaining({ md5: 'm1', title: 'Title', count: 60, durationMs: 20_000 }),
]);
@ -213,15 +218,19 @@ describe('StatisticsDb', () => {
).rejects.toThrow('sync failed');
await pullStarted;
const sample = { unit: 'words' as const, count: 30, startTimeMs: 50_000, durationMs: 20_000 };
const write = shared.insertReadingSpeed('local', sample);
const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 };
const write = shared.recordEvents({ bookMd5: 'local', title: 'Local', authors: '' }, [
{ page: 1, startTime: 50, duration: 20, totalPages: 9, speed: [speed] },
]);
// If the insert bypasses the transaction queue, let it finish before rollback.
if (execute.mock.calls.some(([sql]) => sql.includes('INSERT INTO readest_reading_speed'))) {
await write;
}
failPull(new Error('sync failed'));
await Promise.all([pull, write]);
expect(await shared.getReadingSpeedSamples(0, 100_000)).toEqual([sample]);
expect(await shared.getReadingSpeedSamples(0, 100_000)).toEqual([
{ startTimeMs: 50_000, unit: 'words', count: 30, durationMs: 20_000 },
]);
});
it('upserts a book by md5 and returns a stable id_book', async () => {

View file

@ -4,6 +4,7 @@ import { NodeDatabaseService } from '@/services/database/nodeDatabaseService';
import { migrate } from '@/services/database/migrate';
import { getMigrations } from '@/services/database/migrations';
import { StatisticsDb } from '@/services/statistics/statisticsDb';
import type { DatabaseService } from '@/types/database';
import { deleteBookStats, pullStats } from '@/services/statistics/statsSync';
// Deleting a book's reading statistics (#7494): locally, on the sync server,
@ -23,6 +24,16 @@ async function seed(stats: StatisticsDb, md5: string, startTimes: number[]) {
await stats.recomputeBookTotals(id);
}
const book = (md5: string) => ({ bookMd5: md5, title: md5.toUpperCase(), authors: 'A' });
// A page event carrying `count` words read in its 10 s.
const event = (page: number, startTime: number, count: number) => ({
page,
startTime,
duration: 10,
totalPages: 50,
speed: [{ lang: 'en', unit: 'words' as const, count, durationMs: 10_000 }],
});
const wirePage = (book_hash: string, start_time: number, extra: object = {}) => ({
book_hash,
page: 1,
@ -59,15 +70,16 @@ describe('deleteBook', () => {
it('removes the book’s reading speed samples too', async () => {
const stats = await db();
await seed(stats, 'a', [100]);
await seed(stats, 'b', [300]);
const sample = { unit: 'words' as const, count: 30, durationMs: 10_000 };
await stats.insertReadingSpeed('a', { ...sample, startTimeMs: 100_000 });
await stats.insertReadingSpeed('b', { ...sample, startTimeMs: 300_000, count: 50 });
await stats.recordEvents(book('a'), [event(1, 100, 30)]);
await stats.recordEvents(book('b'), [event(1, 300, 50)]);
await stats.deleteBook('a');
expect(await stats.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 50, durationMs: 10_000 },
]);
const raw = (stats as unknown as { db: DatabaseService }).db;
expect(await raw.select(`SELECT book_hash FROM readest_page_ext`)).toEqual([
{ book_hash: 'b' },
]);
});
});
@ -75,10 +87,8 @@ describe('pullStats with a deleted book', () => {
it('deletes the events read before the deletion and keeps later ones', async () => {
const stats = await db();
// a local event at 2000 s, inside the deletion's fractional second
await seed(stats, 'a', [100, 2000, 2500]);
const sample = { unit: 'words' as const, count: 30, durationMs: 10_000 };
await stats.insertReadingSpeed('a', { ...sample, startTimeMs: 2_000_400 });
await stats.insertReadingSpeed('a', { ...sample, startTimeMs: 2_500_000, count: 40 });
await seed(stats, 'a', [100]);
await stats.recordEvents(book('a'), [event(2, 2000, 30), event(3, 2500, 40)]);
const client = {
pullChanges: vi
.fn()

View file

@ -51,21 +51,26 @@ describe('mergeBook', () => {
expect((await stats.getBookStats()).map((b) => b.md5).sort()).toEqual(['new', 'other']);
});
it('moves the source’s reading speed samples onto the target', async () => {
it('moves the source’s reading speed onto the target', async () => {
const stats = await db();
await seed(stats, 'old', [{ page: 1, startTime: 100, duration: 30 }]);
await seed(stats, 'new', [{ page: 1, startTime: 300, duration: 30 }]);
// split view can start both books' samples on the same millisecond
const sample = { unit: 'words' as const, count: 30, startTimeMs: 100_000, durationMs: 10_000 };
await stats.insertReadingSpeed('old', sample);
await stats.insertReadingSpeed('new', sample);
await stats.insertReadingSpeed('old', { ...sample, startTimeMs: 200_000, count: 20 });
const event = (page: number, startTime: number, count: number) => ({
page,
startTime,
duration: 10,
totalPages: 50,
speed: [{ lang: 'en', unit: 'words' as const, count, durationMs: 10_000 }],
});
// split view can open page 1 of both books in the same second: after the
// merge it is one event, and its speed counts once
await stats.recordEvents(OLD, [event(1, 100, 30), event(2, 200, 20)]);
await stats.recordEvents(NEW, [event(1, 100, 30)]);
await stats.mergeBook('old', NEW);
expect(await stats.getReadingSpeedTotals()).toEqual([
{ unit: 'words', count: 50, durationMs: 20_000 },
]);
// deleting the merged book now removes every sample it took over
expect((await stats.getBookEvents('new')).map((e) => e.speed?.[0]?.count)).toEqual([30, 20]);
// deleting the merged book now removes all the speed it took over
await stats.deleteBook('new');
expect(await stats.getReadingSpeedTotals()).toEqual([]);
});
@ -99,8 +104,6 @@ describe('mergeBookStats', () => {
const client = () => ({
pullChanges: vi.fn().mockResolvedValue({ statBooks: [], statPages: [] }),
pushChanges: vi.fn().mockResolvedValue({}),
pullSpeeds: vi.fn().mockResolvedValue([]),
pushSpeeds: vi.fn().mockResolvedValue(true),
});
it('pulls, pushes the events under the target in chunks, then deletes the source', async () => {

View file

@ -8,16 +8,16 @@ import { useEnv } from '@/context/EnvContext';
import { useAuth } from '@/context/AuthContext';
import { StatisticsDb } from '@/services/statistics/statisticsDb';
import { TrackerCore, type FlushedEvent } from '@/services/statistics/trackerCore';
import { ReadingSpeedTracker } from '@/services/statistics/readingSpeed';
import { ReadingSpeedTracker, sumPageSpeed } from '@/services/statistics/readingSpeed';
import { getBookHashFromKey, ttsSessionManager } from '@/services/tts/TTSSessionManager';
import { DEFAULT_STATS_TRACKING_CONFIG } from '@/types/statistics';
import { DEFAULT_STATS_TRACKING_CONFIG, type ReadingSpeedSample } from '@/types/statistics';
import { SyncClient } from '@/libs/sync';
import { BookOrbitClient } from '@/services/bookorbit/BookOrbitClient';
import { pushStatsToBookOrbit } from '@/services/bookorbit/statsPush';
import { GrimmoryClient, grimmoryAccountKey } from '@/services/grimmory/GrimmoryClient';
import { GrimmorySyncStore } from '@/services/grimmory/GrimmorySyncStore';
import { pushStatsToGrimmory } from '@/services/grimmory/statsPush';
import { pushStats, pullStats, pushSpeeds, pullSpeeds } from '@/services/statistics/statsSync';
import { pushStats, pullStats } from '@/services/statistics/statsSync';
import { isSyncCategoryEnabled } from '@/services/sync/syncCategories';
import { useSettingsStore } from '@/store/settingsStore';
import { eventDispatcher } from '@/utils/event';
@ -42,6 +42,8 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
const { user } = useAuth();
const coreRef = useRef(new TrackerCore(DEFAULT_STATS_TRACKING_CONFIG));
const [speedTracker] = useState(() => new ReadingSpeedTracker());
// Speed samples wait here for the next page event saved, which syncs them.
const speedRef = useRef<ReadingSpeedSample[]>([]);
const dbRef = useRef<StatisticsDb | null>(null);
const idleRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@ -107,10 +109,7 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
};
const pushToAllTargets = (db: StatisticsDb, closing = false) => {
if (syncEnabled()) {
runBestEffort(pushStats(db, new SyncClient()));
runBestEffort(pushSpeeds(db, new SyncClient()));
}
if (syncEnabled()) runBestEffort(pushStats(db, new SyncClient()));
const bookOrbitPush = bookOrbitStatsPush(db);
if (bookOrbitPush) runBestEffort(bookOrbitPush);
const grimmoryPush = grimmoryStatsPush(db, closing);
@ -132,15 +131,7 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
StatisticsDb.open(appService).then((db) => {
if (cancelled) return;
dbRef.current = db;
if (syncEnabled()) {
// 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())),
),
);
}
if (syncEnabled()) runBestEffort(pullStats(db, new SyncClient()));
}),
);
return () => {
@ -153,8 +144,13 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
const persist = async (events: FlushedEvent[]): Promise<void> => {
const db = dbRef.current;
if (!db || !bookMd5 || events.length === 0) return;
const speed = sumPageSpeed(speedRef.current.splice(0));
const last = events.length - 1;
try {
await db.recordEvents({ bookMd5, title, authors }, events);
await db.recordEvents(
{ bookMd5, title, authors },
speed.length ? events.map((e, i) => (i === last ? { ...e, speed } : e)) : events,
);
schedulePush();
} catch (err) {
// The statistics DB can be closed mid-write on app/tab teardown
@ -180,21 +176,18 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) {
};
const trackSpeed = (position: BookProgress | null) => {
if (!appService || !bookMd5 || document.visibilityState === 'hidden') return;
if (!bookMd5 || document.visibilityState === 'hidden') return;
const scrolled = !!useReaderStore.getState().getViewSettings(bookKey)?.scrolled;
const sample = speedTracker.onPosition(position, Date.now(), scrolled, bookLanguage);
if (sample) {
runBestEffort(
StatisticsDb.open(appService).then((db) => db.insertReadingSpeed(bookMd5, sample)),
);
}
if (sample) speedRef.current.push(sample);
};
// Page changes drive the tracker.
// Page changes drive the tracker. Speed first: a page turn ends the sample
// and saves the page, which carries it.
useEffect(() => {
if (ttsPlayingRef.current) return;
openPageAt(progress?.pageinfo);
trackSpeed(progress);
openPageAt(progress?.pageinfo);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [progress?.pageinfo]);

View file

@ -130,16 +130,13 @@ const ReadingStatsContent: React.FC<ReadingStatsContentProps> = ({ page, onPage
if (user && isSyncCategoryEnabled('stats')) {
// Loaded here so the menus that import this dialog don't pull the
// sync client (and its API base URL) into their module graph.
const [{ SyncClient }, { pullStats, pullSpeeds }] = await Promise.all([
const [{ SyncClient }, { pullStats }] = await Promise.all([
import('@/libs/sync'),
import('@/services/statistics/statsSync'),
]);
await pullStats(db, new SyncClient()).catch((err) =>
console.warn('Failed to pull reading stats:', err),
);
await pullSpeeds(db, new SyncClient()).catch((err) =>
console.warn('Failed to pull reading speed:', err),
);
await load(db);
}
})

View file

@ -2,7 +2,6 @@ import { Book, BookConfig, BookNote, BookDataRecord } from '@/types/book';
import { getAPIBaseUrl } from '@/services/environment';
import { getAccessToken } from '@/utils/access';
import { fetchWithTimeout } from '@/utils/fetch';
import type { ReadingSpeedUnit } from '@/types/statistics';
const SYNC_API_ENDPOINT = getAPIBaseUrl() + '/sync';
@ -47,28 +46,6 @@ export interface StatPageRecord {
deleted_at_ms?: number; // set by the GET response when the book's statistics were deleted
}
/**
* Reading speed in one book, language and unit over a quarter hour on one
* device, keyed by that device's first sample in it (#8023). /api/sync/speeds.
*/
export interface StatSpeedRecord {
book_hash: string;
start_time_ms: number;
lang: string;
unit: ReadingSpeedUnit;
count: number;
duration_ms: number;
updated_at?: string; // server-stamped, the pull cursor
deleted?: boolean; // set by the pull when the book's statistics were deleted after it
}
/** The last row a speed pull got, to page after it. */
export interface SpeedCursor {
ts: string;
book: string;
start: number;
}
export interface SyncResult {
books: BookRecord[] | null;
notes: BookNoteRecord[] | null;
@ -141,47 +118,6 @@ export class SyncClient {
return result;
}
/**
* 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) });
if (since) {
params.set('since_ts', since.ts);
params.set('since_book', since.book);
params.set('since_start', String(since.start));
}
const res = await fetchWithTimeout(
`${SYNC_API_ENDPOINT}/speeds?${params}`,
{ 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;
}
/** 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(
`${SYNC_API_ENDPOINT}/speeds`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ rows }),
},
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> {
const token = await getAccessToken();
if (!token) throw new Error('Not authenticated');

View file

@ -1,178 +0,0 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { NextRequest, NextResponse } from 'next/server';
import { createSupabaseClient } from '@/utils/supabase';
import { validateUserAndToken } from '@/utils/access';
import { runMiddleware, corsAllMethods } from '@/utils/cors';
import type { StatSpeedRecord } from '@/libs/sync';
// Reading speed sync (#8023). One row per book, language and unit for each
// quarter hour a device read in, keyed by that device's first sample there, in
// `public.stat_speeds` (migration 036). The pull is keyset-paged on the
// server-stamped (updated_at, book_hash, start_time_ms); the push goes through
// upsert_stat_speeds, which keeps the longer of two copies of a row.
const MAX_ROWS = 1000;
const MAX_INT = 2 ** 31 - 1;
const COLUMNS = 'book_hash,start_time_ms,lang,unit,count,duration_ms,updated_at';
const errorResponse = (status: number, message: string) =>
NextResponse.json({ error: message }, { status });
// PostgREST filter values: quote so a book hash or a timestamp holding `+`
// can't break the `or=(…)` grammar.
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> | null) =>
typeof r === 'object' &&
r !== null &&
typeof r.book_hash === 'string' &&
r.book_hash.length > 0 &&
r.book_hash.length <= 128 &&
isPositive(r.start_time_ms, Number.MAX_SAFE_INTEGER) &&
typeof r.lang === 'string' &&
r.lang.length <= 35 &&
(r.unit === 'words' || r.unit === 'characters') &&
isPositive(r.count, MAX_INT) &&
isPositive(r.duration_ms, MAX_INT);
export async function GET(req: NextRequest) {
const { user, token } = await validateUserAndToken(req.headers.get('authorization'));
if (!user || !token) return errorResponse(401, 'Not authenticated');
const supabase = createSupabaseClient(token);
const params = new URL(req.url).searchParams;
const sinceTs = params.get('since_ts');
const sinceStart = Number(params.get('since_start') ?? 0);
if (sinceTs && Number.isNaN(Date.parse(sinceTs))) return errorResponse(400, 'Invalid since_ts');
if (!Number.isSafeInteger(sinceStart)) return errorResponse(400, 'Invalid since_start');
const requested = Math.floor(Number(params.get('limit')));
const limit = requested > 0 ? Math.min(requested, MAX_ROWS) : MAX_ROWS;
let query = supabase.from('stat_speeds').select(COLUMNS).eq('user_id', user.id);
if (sinceTs) {
const ts = quote(sinceTs);
const book = quote(params.get('since_book') ?? '');
query = query.or(
`updated_at.gt.${ts},and(updated_at.eq.${ts},book_hash.gt.${book}),` +
`and(updated_at.eq.${ts},book_hash.eq.${book},start_time_ms.gt.${sinceStart})`,
);
}
const { data, error } = await query
.order('updated_at', { ascending: true })
.order('book_hash', { ascending: true })
.order('start_time_ms', { ascending: true })
.limit(limit);
if (error) {
console.error('pull stat_speeds failed', error);
return errorResponse(500, 'Failed to pull reading speed');
}
// A book's statistics are deleted (#7494) by setting deleted_at on its
// stat_books row: its speed read before then is gone too.
const rows = (data ?? []) as StatSpeedRecord[];
const books = [...new Set(rows.map((r) => r.book_hash))];
if (books.length) {
const { data: deletions, error: deletionsError } = await supabase
.from('stat_books')
.select('book_hash,deleted_at')
.eq('user_id', user.id)
.in('book_hash', books)
.not('deleted_at', 'is', null);
if (deletionsError) {
console.error('read stat_books deletions failed', deletionsError);
return errorResponse(500, 'Failed to pull reading speed');
}
const deletedAt = new Map(
((deletions ?? []) as { book_hash: string; deleted_at: string }[]).map((b) => [
b.book_hash,
Date.parse(b.deleted_at),
]),
);
for (const r of rows) {
if (r.start_time_ms < (deletedAt.get(r.book_hash) ?? -Infinity)) r.deleted = true;
}
}
return NextResponse.json({ rows }, { status: 200 });
}
export async function POST(req: NextRequest) {
const { user, token } = await validateUserAndToken(req.headers.get('authorization'));
if (!user || !token) return errorResponse(401, 'Not authenticated');
let rows: unknown;
try {
rows = ((await req.json()) as { rows?: unknown }).rows;
} catch {
return errorResponse(400, 'Invalid JSON body');
}
if (!Array.isArray(rows)) return errorResponse(400, '"rows" must be an array');
if (rows.length > MAX_ROWS) return errorResponse(413, `at most ${MAX_ROWS} rows`);
// A malformed row is skipped and reported rather than failing the batch:
// 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> | 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 });
} else {
rejected.push(`${r?.book_hash ?? ''}:${r?.start_time_ms ?? ''}`);
}
}
if (valid.length) {
const { error } = await createSupabaseClient(token).rpc('upsert_stat_speeds', {
p_rows: valid,
});
if (error) {
console.error('upsert stat_speeds failed', error);
return errorResponse(500, 'Failed to save reading speed');
}
}
return NextResponse.json({ rejected }, { status: 200 });
}
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (!req.url) {
return res.status(400).json({ error: 'Invalid request URL' });
}
const protocol = process.env['PROTOCOL'] || 'http';
const host = process.env['HOST'] || 'localhost:3000';
const url = new URL(req.url, `${protocol}://${host}`);
await runMiddleware(req, res, corsAllMethods);
try {
let response: Response;
if (req.method === 'GET') {
const nextReq = new NextRequest(url.toString(), {
headers: new Headers(req.headers as Record<string, string>),
method: 'GET',
});
response = await GET(nextReq);
} else if (req.method === 'POST') {
const nextReq = new NextRequest(url.toString(), {
headers: new Headers(req.headers as Record<string, string>),
method: 'POST',
body: JSON.stringify(req.body),
});
response = await POST(nextReq);
} else {
res.setHeader('Allow', ['GET', 'POST']);
return res.status(405).json({ error: 'Method Not Allowed' });
}
res.status(response.status);
response.headers.forEach((value, key) => {
res.setHeader(key, value);
});
res.send(Buffer.from(await response.arrayBuffer()));
} catch (error) {
console.error('Error processing /api/sync/speeds request:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
export default handler;

View file

@ -226,12 +226,6 @@ const migrations: Record<SchemaType, MigrationEntry[]> = {
name: '2026112801_statistics_reading_speed_lang',
sql: `ALTER TABLE readest_reading_speed ADD COLUMN lang text NOT NULL DEFAULT ''`,
},
{
// 1 for speed pulled from another device: one row per book, language and
// unit for a quarter hour it read in. This device pushes only its own.
name: '2026112802_statistics_reading_speed_remote',
sql: `ALTER TABLE readest_reading_speed ADD COLUMN remote integer NOT NULL DEFAULT 0`,
},
],
// Per-book search index/cache: one search.db in each book's directory
// (beside cover.png), holding extracted section text so library full-text

View file

@ -1,6 +1,7 @@
import {
DEFAULT_STATS_TRACKING_CONFIG,
MAX_READING_SPEED_SAMPLE_MS,
type PageSpeed,
type ReadingSpeedSample,
type ReadingSpeedUnit,
} from '@/types/statistics';
@ -142,6 +143,21 @@ const countPassedUnits = (passed: Range, language: string) => {
};
};
/** Sum samples per language and unit, as a page event carries them. */
export const sumPageSpeed = (samples: ReadingSpeedSample[]): PageSpeed[] => {
const sums = new Map<string, PageSpeed>();
for (const { lang = '', unit, count, durationMs } of samples) {
const sum = sums.get(`${lang}:${unit}`);
if (sum) {
sum.count += count;
sum.durationMs += durationMs;
} else {
sums.set(`${lang}:${unit}`, { lang, unit, count, durationMs });
}
}
return [...sums.values()];
};
/**
* Measures forward reading from renderer ranges, independently of book page
* numbering. A sample is one page: a page turn, or while scrolling, the screen

View file

@ -3,6 +3,7 @@ import type { DatabaseService, DatabaseRow } from '@/types/database';
import { DEFAULT_STATS_TRACKING_CONFIG, MAX_READING_SPEED_SAMPLE_MS } from '@/types/statistics';
import type {
BookStats,
PageSpeed,
PageStatEvent,
ReadingSpeed,
ReadingSpeedSample,
@ -22,23 +23,40 @@ interface BookRow extends DatabaseRow {
pages: number;
}
type CursorKey =
| 'push'
| 'pull'
| 'speed-push'
| 'speed-pull'
| 'bookorbit-push'
| `grimmory-push:${string}`;
/** Speed in one book, language and unit over a quarter hour, keyed by its first sample. */
export type SpeedBucket = ReadingSpeedSample & { bookMd5: string; lang: string };
const QUARTER_MS = 900_000;
type CursorKey = 'push' | 'pull' | 'bookorbit-push' | `grimmory-push:${string}`;
// Readest caps one page visit at this, so a longer event spans several pages
// (a CrossPoint session recorded in whole percents) and says nothing about pace.
const MAX_PAGE_SECONDS = DEFAULT_STATS_TRACKING_CONFIG.maxEventSeconds;
const isPositiveInt = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
const isPageSpeed = (s: unknown): s is PageSpeed => {
const { lang, unit, count, durationMs } = (s ?? {}) as Partial<PageSpeed>;
return (
typeof lang === 'string' &&
(unit === 'words' || unit === 'characters') &&
isPositiveInt(count) &&
isPositiveInt(durationMs)
);
};
/**
* The speed in a page event's `ext` (#8023). Other devices and clients write
* it, so an entry this can't read is dropped.
*/
export const readPageSpeed = (ext: unknown): PageSpeed[] | undefined => {
const speed = (ext as { speed?: unknown } | null)?.speed;
if (!Array.isArray(speed)) return undefined;
const valid = speed
.filter(isPageSpeed)
.map(({ lang, unit, count, durationMs }) => ({ lang, unit, count, durationMs }));
return valid.length ? valid : undefined;
};
const speedOf = (ext: unknown) =>
typeof ext === 'string' ? readPageSpeed(JSON.parse(ext)) : undefined;
/**
* Per-tab singleton open promise. OPFS permits only ONE access handle per file
* across the whole origin, so a second `connect()` to statistics.db throws
@ -254,23 +272,30 @@ export class StatisticsDb {
return rows[0] ?? { seconds: 0, books: 0, pages: 0 };
}
// Local samples extend the stats DB without changing KOReader page events or
// the sync protocol. Queued so the write can't land inside a pull's open BEGIN.
async insertReadingSpeed(bookMd5: string, sample: ReadingSpeedSample): Promise<void> {
await this.exclusive(async () => {
/**
* Keep the speed a page event carries: as the event's ext, and as rows for
* the speed queries, starting where the event does. Every device does this
* for every event it holds, so one it already has, such as its own coming
* back from the server, meets the same keys and changes nothing.
*/
private async insertPageSpeed(
md5: string,
e: { page: number; startTime: number; speed?: PageSpeed[] },
): Promise<void> {
if (!e.speed?.length) return;
await this.db.execute(
`INSERT INTO readest_page_ext (book_hash, page, start_time, ext) VALUES (?, ?, ?, ?)
ON CONFLICT DO NOTHING`,
[md5, e.page, e.startTime, JSON.stringify({ speed: e.speed })],
);
for (const [i, speed] of e.speed.entries()) {
// A millisecond apart: two languages in one event don't share a key.
await this.db.execute(
`INSERT INTO readest_reading_speed (start_time_ms, book_md5, unit, count, duration_ms, lang)
VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`,
[
sample.startTimeMs,
bookMd5,
sample.unit,
sample.count,
sample.durationMs,
sample.lang ?? '',
],
[e.startTime * 1000 + i, md5, speed.unit, speed.count, speed.durationMs, speed.lang],
);
});
}
}
async getReadingSpeedSamples(startMs: number, endMs: number): Promise<ReadingSpeedSample[]> {
@ -333,80 +358,17 @@ export class StatisticsDb {
return this.upsertBook({ bookMd5, title: bookMd5, authors: '' });
}
/**
* This device's speed in each book, language and unit for every quarter hour
* holding a sample newer than `since` (Unix ms), oldest change first: a
* quarter hour still being read is sent again, grown, under the same key.
*/
async getSpeedBucketsForPush(since: number): Promise<(SpeedBucket & { lastMs: number })[]> {
return this.db.select<SpeedBucket & { lastMs: number }>(
`SELECT book_md5 AS bookMd5, MIN(start_time_ms) AS startTimeMs, lang, unit,
SUM(count) AS count, SUM(duration_ms) AS durationMs, MAX(start_time_ms) AS lastMs
FROM readest_reading_speed
WHERE remote = 0 AND start_time_ms >= ?
GROUP BY book_md5, start_time_ms / ${QUARTER_MS}, lang, unit
HAVING MAX(start_time_ms) > ?
ORDER BY lastMs`,
[Math.floor(since / QUARTER_MS) * QUARTER_MS, since],
);
}
/** All of a book's speed as pushed rows: this device's by quarter hour, and the pulled ones. */
async getBookSpeedBuckets(md5: string): Promise<SpeedBucket[]> {
const own = await this.db.select<SpeedBucket>(
`SELECT book_md5 AS bookMd5, MIN(start_time_ms) AS startTimeMs, lang, unit,
SUM(count) AS count, SUM(duration_ms) AS durationMs
FROM readest_reading_speed WHERE book_md5 = ? AND remote = 0
GROUP BY book_md5, start_time_ms / ${QUARTER_MS}, lang, unit`,
[md5],
);
const pulled = await this.db.select<SpeedBucket>(
`SELECT book_md5 AS bookMd5, start_time_ms AS startTimeMs, lang, unit,
count, duration_ms AS durationMs
FROM readest_reading_speed WHERE book_md5 = ? AND remote = 1`,
[md5],
);
return [...own, ...pulled].sort((a, b) => a.startTimeMs - b.startTimeMs);
}
/**
* Keep speed pulled from other devices. A row only grows while its quarter
* hour lasts, so the longer copy wins; this device's own row coming back
* meets its first sample's key and is ignored, its samples already count.
*/
async applyRemoteSpeeds(rows: SpeedBucket[]): Promise<void> {
if (rows.length === 0) return;
await this.exclusive(async () => {
await this.db.execute('BEGIN');
try {
for (const r of rows) {
await this.db.execute(
`INSERT INTO readest_reading_speed
(start_time_ms, book_md5, unit, count, duration_ms, lang, remote)
VALUES (?, ?, ?, ?, ?, ?, 1)
ON CONFLICT (start_time_ms, book_md5, unit) DO UPDATE
SET count = excluded.count, duration_ms = excluded.duration_ms, lang = excluded.lang
WHERE readest_reading_speed.remote = 1
AND excluded.duration_ms > readest_reading_speed.duration_ms`,
[r.startTimeMs, r.bookMd5, r.unit, r.count, r.durationMs, r.lang],
);
}
await this.db.execute('COMMIT');
} catch (err) {
await this.db.execute('ROLLBACK');
throw err;
}
});
}
/** Events with start_time > cursor, joined to their md5, for pushing. */
async getEventsForPush(
sinceStartTime: number,
): Promise<{ events: PageStatEvent[]; books: StatBook[] }> {
const rows = await this.db.select<DatabaseRow>(
`SELECT b.md5 AS bookMd5, b.title AS title, b.authors AS authors,
p.page AS page, p.start_time AS startTime, p.duration AS duration, p.total_pages AS totalPages
p.page AS page, p.start_time AS startTime, p.duration AS duration,
p.total_pages AS totalPages, x.ext AS ext
FROM page_stat_data p JOIN book b ON b.id = p.id_book
LEFT JOIN readest_page_ext x
ON x.book_hash = b.md5 AND x.page = p.page AND x.start_time = p.start_time
WHERE p.start_time > ?
ORDER BY p.start_time ASC`,
[sinceStartTime],
@ -417,6 +379,7 @@ export class StatisticsDb {
startTime: Number(r['startTime']),
duration: Number(r['duration']),
totalPages: Number(r['totalPages']),
speed: speedOf(r['ext']),
}));
const bookMap = new Map<string, StatBook>();
for (const r of rows) {
@ -474,14 +437,17 @@ export class StatisticsDb {
startTime: number;
duration: number;
totalPages: number;
ext: string | null;
}>(
`SELECT p.page AS page, p.start_time AS startTime, p.duration AS duration,
p.total_pages AS totalPages
p.total_pages AS totalPages, x.ext AS ext
FROM page_stat_data p JOIN book b ON b.id = p.id_book
LEFT JOIN readest_page_ext x
ON x.book_hash = b.md5 AND x.page = p.page AND x.start_time = p.start_time
WHERE b.md5 = ? ORDER BY p.start_time, p.page`,
[md5],
);
return rows.map((r) => ({ bookMd5: md5, ...r }));
return rows.map(({ ext, ...r }) => ({ bookMd5: md5, ...r, speed: speedOf(ext) }));
}
/**
@ -493,13 +459,13 @@ export class StatisticsDb {
* deletion or pull in progress: run between them, the events could go to a
* row that is then deleted, or be deleted without being merged.
*/
async recordEvents(
book: StatBook,
events: { page: number; startTime: number; duration: number; totalPages: number }[],
): Promise<void> {
async recordEvents(book: StatBook, events: Omit<PageStatEvent, 'bookMd5'>[]): Promise<void> {
await this.exclusive(async () => {
const id = await this.upsertBook(book);
for (const e of events) await this.insertPageEvent(id, e);
for (const e of events) {
await this.insertPageEvent(id, e);
await this.insertPageSpeed(book.bookMd5, e);
}
await this.recomputeBookTotals(id);
});
}
@ -510,14 +476,17 @@ export class StatisticsDb {
try {
const events = await this.getBookEvents(source);
const id = await this.upsertBook(target);
for (const e of events) await this.insertPageEvent(id, e);
for (const e of events) {
await this.insertPageEvent(id, e);
await this.insertPageSpeed(target.bookMd5, e);
}
await this.recomputeBookTotals(id);
// A sample both hold at the same moment stays once, like a page event.
// Speed saved before it rode on page events (#8023), and a sample both
// hold at the same moment stays once, like a page event.
await this.db.execute(
`INSERT INTO readest_reading_speed
(start_time_ms, book_md5, unit, count, duration_ms, lang, remote)
SELECT start_time_ms, ?, unit, count, duration_ms, lang, remote
FROM readest_reading_speed WHERE book_md5 = ? ON CONFLICT DO NOTHING`,
`INSERT INTO readest_reading_speed (start_time_ms, book_md5, unit, count, duration_ms, lang)
SELECT start_time_ms, ?, unit, count, duration_ms, lang FROM readest_reading_speed
WHERE book_md5 = ? ON CONFLICT DO NOTHING`,
[target.bookMd5, source],
);
await this.deleteEventsBefore(source, Number.MAX_SAFE_INTEGER);
@ -538,6 +507,10 @@ export class StatisticsDb {
`DELETE FROM readest_reading_speed WHERE book_md5 = ? AND start_time_ms < ?`,
[md5, Math.min(before * 1000, Number.MAX_SAFE_INTEGER)],
);
await this.db.execute(`DELETE FROM readest_page_ext WHERE book_hash = ? AND start_time < ?`, [
md5,
before,
]);
const rows = await this.db.select<BookRow>(`SELECT id FROM book WHERE md5 = ?`, [md5]);
for (const { id } of rows) {
await this.db.execute(`DELETE FROM page_stat_data WHERE id_book = ? AND start_time < ?`, [
@ -572,6 +545,7 @@ export class StatisticsDb {
idByMd5.set(e.bookMd5, id);
}
await this.insertPageEvent(id, e);
await this.insertPageSpeed(e.bookMd5, e);
touched.add(id);
}
for (const id of touched) await this.recomputeBookTotals(id);

View file

@ -1,16 +1,9 @@
import type { SpeedBucket, StatisticsDb } from './statisticsDb';
import type {
SyncClient,
SpeedCursor,
StatPageRecord,
StatBookRecord,
StatSpeedRecord,
} from '@/libs/sync';
import { readPageSpeed, type StatisticsDb } from './statisticsDb';
import type { SyncClient, StatPageRecord, StatBookRecord } from '@/libs/sync';
import type { PageStatEvent, StatBook } from '@/types/statistics';
type PushClient = Pick<SyncClient, 'pushChanges'>;
type PullClient = Pick<SyncClient, 'pullChanges'>;
type SpeedClient = Pick<SyncClient, 'pushSpeeds' | 'pullSpeeds'>;
const toWirePage = (e: PageStatEvent): StatPageRecord => ({
book_hash: e.bookMd5,
@ -18,6 +11,8 @@ const toWirePage = (e: PageStatEvent): StatPageRecord => ({
start_time: e.startTime,
duration: e.duration,
total_pages: e.totalPages,
// Other devices work reading speed out from it (#8023).
...(e.speed ? { ext: { speed: e.speed } } : {}),
});
const toWireBook = (b: StatBook): StatBookRecord => ({
@ -26,15 +21,6 @@ const toWireBook = (b: StatBook): StatBookRecord => ({
authors: b.authors,
});
const toWireSpeed = (b: SpeedBucket): StatSpeedRecord => ({
book_hash: b.bookMd5,
start_time_ms: b.startTimeMs,
lang: b.lang,
unit: b.unit,
count: b.count,
duration_ms: b.durationMs,
});
/** Events per push request — bounds request size for a large offline backlog. */
const PUSH_CHUNK = 500;
/** Page events per pull request — bounds the receiving device's memory. */
@ -104,6 +90,7 @@ export async function pullStats(stats: StatisticsDb, client: PullClient): Promis
startTime: p.start_time,
duration: p.duration,
totalPages: p.total_pages,
speed: readPageSpeed(p.ext),
}));
await stats.applyRemoteEvents(books, events);
// Advance the cursor to the newest page-event updated_at_ms. Stop when a
@ -115,66 +102,6 @@ export async function pullStats(stats: StatisticsDb, client: PullClient): Promis
}
}
/** Speed rows per request, both ways. */
const SPEED_PAGE = 1000;
const SPEED_PUSH_CHUNK = 500;
/**
* The server stamps updated_at before its write commits, so a slow write can
* land behind a cursor already handed out. Re-reading the last minute catches
* it; applying a row again changes nothing.
*/
const SPEED_PULL_OVERLAP_MS = 60_000;
/**
* Push this device's reading speed (#8023): one row per book, language and
* unit for each quarter hour with a sample past the push cursor.
*/
export async function pushSpeeds(stats: StatisticsDb, client: SpeedClient): Promise<void> {
const cursor = await stats.getCursor('speed-push');
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);
// 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. 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
.filter((r) => !r.deleted)
.map((r) => ({
bookMd5: r.book_hash,
startTimeMs: r.start_time_ms,
lang: r.lang,
unit: r.unit,
count: r.count,
durationMs: r.duration_ms,
})),
);
const last = rows[rows.length - 1]!;
since = { ts: last.updated_at!, book: last.book_hash, start: last.start_time_ms };
const newest = Date.parse(last.updated_at!);
if (newest > (await stats.getCursor('speed-pull'))) await stats.setCursor('speed-pull', newest);
if (rows.length < SPEED_PAGE) break;
}
return true;
}
/**
* Delete books' reading statistics (#7494). With a sync client the server
* records the deletions first, in one request, so every device drops the
@ -204,26 +131,12 @@ const pushDeletions = (client: PushClient, books: StatBook[]) =>
*/
export async function mergeBookStats(
stats: StatisticsDb,
client: (PushClient & PullClient & SpeedClient) | null,
client: (PushClient & PullClient) | null,
sources: StatBook[],
target: StatBook,
): Promise<void> {
if (client) {
await pullStats(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) {
await client.pushSpeeds(
buckets
.slice(i, i + SPEED_PUSH_CHUNK)
.map((b) => toWireSpeed({ ...b, bookMd5: target.bookMd5 })),
);
}
}
}
for (const source of sources) {
const events = await stats.getBookEvents(source.bookMd5);
for (let i = 0; i < events.length; i += PUSH_CHUNK) {

View file

@ -11,6 +11,8 @@ export interface PageStatEvent {
startTime: number; // Unix seconds
duration: number; // seconds
totalPages: number;
/** Speed read while the page was open; syncs in the event's `ext`. */
speed?: PageSpeed[];
}
/** KOReader book identity — the only book metadata that syncs. */
@ -43,6 +45,9 @@ export type ReadingSpeed = {
/** `lang` is the base language the text was counted in ('en', 'zh'), or '' when unknown. */
export type ReadingSpeedSample = ReadingSpeed & { startTimeMs: number; lang?: string };
/** The speed samples a page event carries, summed per language and unit. */
export type PageSpeed = ReadingSpeed & { lang: string };
/** Tunables for the tracker's flush/idle behavior. KOReader-aligned defaults. */
export interface StatsTrackingConfig {
/** Seconds of inactivity before the current page event is flushed + paused. */

View file

@ -1,76 +0,0 @@
-- Migration 036: reading speed sync (#8023).
-- Deploy this migration and the /api/sync/speeds route before releasing
-- clients that push reading speed.
--
-- One row per book, language and unit for each quarter hour a device read in,
-- keyed by the start of that device's first speed sample there (epoch ms), so
-- two devices never share a key. A row only grows while its quarter hour lasts:
-- the push keeps the longer copy. About four rows per hour of reading, against
-- one stat_pages row per page, so the table needs no archive.
--
-- updated_at is stamped by the server on every write and is the pull cursor,
-- paged by the (updated_at, book_hash, start_time_ms) keyset. A book's speed is
-- deleted with its statistics through stat_books.deleted_at: the pull flags
-- rows that started before it.
CREATE TABLE IF NOT EXISTS public.stat_speeds (
user_id uuid NOT NULL,
book_hash text NOT NULL,
start_time_ms bigint NOT NULL,
lang text NOT NULL DEFAULT '',
unit text NOT NULL,
count integer NOT NULL,
duration_ms integer NOT NULL,
updated_at timestamp with time zone NOT NULL DEFAULT now(),
CONSTRAINT stat_speeds_pkey PRIMARY KEY (user_id, book_hash, start_time_ms),
CONSTRAINT stat_speeds_unit_check CHECK (unit IN ('characters', 'words')),
CONSTRAINT stat_speeds_positive_check CHECK (count > 0 AND duration_ms > 0),
CONSTRAINT stat_speeds_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_stat_speeds_user_updated
ON public.stat_speeds (user_id, updated_at, book_hash, start_time_ms);
ALTER TABLE public.stat_speeds ENABLE ROW LEVEL SECURITY;
CREATE POLICY stat_speeds_select ON public.stat_speeds FOR SELECT TO authenticated USING ((SELECT auth.uid()) = user_id);
CREATE POLICY stat_speeds_insert ON public.stat_speeds FOR INSERT TO authenticated WITH CHECK ((SELECT auth.uid()) = user_id);
CREATE POLICY stat_speeds_update ON public.stat_speeds FOR UPDATE TO authenticated USING ((SELECT auth.uid()) = user_id);
CREATE POLICY stat_speeds_delete ON public.stat_speeds FOR DELETE TO authenticated USING ((SELECT auth.uid()) = user_id);
-- New keys are inserted; an existing key is overwritten only when the incoming
-- duration is strictly longer. Duplicate keys inside one batch collapse to the
-- longest so the statement never affects a row twice. user_id and updated_at
-- are stamped here, never taken from the payload. SECURITY INVOKER keeps the
-- RLS policies above in force.
CREATE OR REPLACE FUNCTION public.upsert_stat_speeds(p_rows jsonb)
RETURNS integer
LANGUAGE plpgsql
SECURITY INVOKER
SET search_path = public
AS $$
DECLARE
v_count integer;
BEGIN
INSERT INTO public.stat_speeds
(user_id, book_hash, start_time_ms, lang, unit, count, duration_ms, updated_at)
SELECT DISTINCT ON (r.book_hash, r.start_time_ms)
auth.uid(), r.book_hash, r.start_time_ms, coalesce(r.lang, ''), r.unit,
r.count, r.duration_ms, now()
FROM jsonb_to_recordset(p_rows) AS r(
book_hash text, start_time_ms bigint, lang text, unit text, count integer,
duration_ms integer)
ORDER BY r.book_hash, r.start_time_ms, r.duration_ms DESC
ON CONFLICT (user_id, book_hash, start_time_ms) DO UPDATE
SET lang = EXCLUDED.lang,
unit = EXCLUDED.unit,
count = EXCLUDED.count,
duration_ms = EXCLUDED.duration_ms,
updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.duration_ms > stat_speeds.duration_ms;
GET DIAGNOSTICS v_count = ROW_COUNT;
RETURN v_count;
END;
$$;
REVOKE EXECUTE ON FUNCTION public.upsert_stat_speeds(jsonb) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.upsert_stat_speeds(jsonb) TO authenticated;