diff --git a/apps/readest-app/src/__tests__/components/stats/BookStatsDelete.test.tsx b/apps/readest-app/src/__tests__/components/stats/BookStatsDelete.test.tsx index 5cac61b21..adb17de0e 100644 --- a/apps/readest-app/src/__tests__/components/stats/BookStatsDelete.test.tsx +++ b/apps/readest-app/src/__tests__/components/stats/BookStatsDelete.test.tsx @@ -23,6 +23,7 @@ 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 {} })); diff --git a/apps/readest-app/src/__tests__/components/stats/BookStatsMerge.test.tsx b/apps/readest-app/src/__tests__/components/stats/BookStatsMerge.test.tsx index f33b46962..e968001ba 100644 --- a/apps/readest-app/src/__tests__/components/stats/BookStatsMerge.test.tsx +++ b/apps/readest-app/src/__tests__/components/stats/BookStatsMerge.test.tsx @@ -24,6 +24,7 @@ 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, })); diff --git a/apps/readest-app/src/__tests__/components/stats/ReadingStats.test.tsx b/apps/readest-app/src/__tests__/components/stats/ReadingStats.test.tsx index c2b9e4d6f..d95387c19 100644 --- a/apps/readest-app/src/__tests__/components/stats/ReadingStats.test.tsx +++ b/apps/readest-app/src/__tests__/components/stats/ReadingStats.test.tsx @@ -17,10 +17,17 @@ 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() })); +const sync = vi.hoisted(() => ({ + user: null as object | null, + pullStats: vi.fn(), + pullSpeeds: vi.fn(async () => {}), +})); vi.mock('@/context/AuthContext', () => ({ useAuth: () => ({ user: sync.user }) })); vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => true })); -vi.mock('@/services/statistics/statsSync', () => ({ pullStats: sync.pullStats })); +vi.mock('@/services/statistics/statsSync', () => ({ + pullStats: sync.pullStats, + pullSpeeds: sync.pullSpeeds, +})); vi.mock('@/libs/sync', () => ({ SyncClient: class {} })); afterEach(() => { @@ -279,6 +286,26 @@ 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(() => {}); diff --git a/apps/readest-app/src/__tests__/pages/api/sync-route-light-imports.test.ts b/apps/readest-app/src/__tests__/pages/api/sync-route-light-imports.test.ts index 43abd1792..837336ce1 100644 --- a/apps/readest-app/src/__tests__/pages/api/sync-route-light-imports.test.ts +++ b/apps/readest-app/src/__tests__/pages/api/sync-route-light-imports.test.ts @@ -15,6 +15,7 @@ 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[] = []; diff --git a/apps/readest-app/src/__tests__/pages/api/sync-speeds.test.ts b/apps/readest-app/src/__tests__/pages/api/sync-speeds.test.ts new file mode 100644 index 000000000..7464c0230 --- /dev/null +++ b/apps/readest-app/src/__tests__/pages/api/sync-speeds.test.ts @@ -0,0 +1,152 @@ +// @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 = {}; + 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 => ({ + 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: [ + 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(); + }); +}); diff --git a/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx b/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx index 34a173e23..d90ee0a4b 100644 --- a/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx +++ b/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx @@ -30,6 +30,8 @@ vi.mock('@/services/statistics/statisticsDb', () => ({ vi.mock('@/services/statistics/statsSync', () => ({ pushStats: vi.fn(), pullStats: vi.fn(), + pushSpeeds: vi.fn(), + pullSpeeds: vi.fn(), })); vi.mock('@/services/sync/syncCategories', () => ({ isSyncCategoryEnabled: () => false })); vi.mock('@/store/settingsStore', () => ({ diff --git a/apps/readest-app/src/__tests__/statistics/speedSync.test.ts b/apps/readest-app/src/__tests__/statistics/speedSync.test.ts new file mode 100644 index 000000000..c1215594d --- /dev/null +++ b/apps/readest-app/src/__tests__/statistics/speedSync.test.ts @@ -0,0 +1,224 @@ +// @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 => ({ + 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(undefined), + 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('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([]); + + 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.mockRejectedValue(new Error('Failed to pull speeds: Not Found')); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + 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.pushChanges).toHaveBeenCalled(); + }); +}); diff --git a/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts b/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts index da7556d70..1cc607e08 100644 --- a/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts +++ b/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts @@ -99,6 +99,8 @@ describe('mergeBookStats', () => { const client = () => ({ pullChanges: vi.fn().mockResolvedValue({ statBooks: [], statPages: [] }), pushChanges: vi.fn().mockResolvedValue({}), + pullSpeeds: vi.fn().mockResolvedValue([]), + pushSpeeds: vi.fn().mockResolvedValue(undefined), }); it('pulls, pushes the events under the target in chunks, then deletes the source', async () => { diff --git a/apps/readest-app/src/app/reader/components/ReadingStatsTracker.tsx b/apps/readest-app/src/app/reader/components/ReadingStatsTracker.tsx index 5a8115b25..71aef9a63 100644 --- a/apps/readest-app/src/app/reader/components/ReadingStatsTracker.tsx +++ b/apps/readest-app/src/app/reader/components/ReadingStatsTracker.tsx @@ -17,7 +17,7 @@ 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 } from '@/services/statistics/statsSync'; +import { pushStats, pullStats, pushSpeeds, pullSpeeds } from '@/services/statistics/statsSync'; import { isSyncCategoryEnabled } from '@/services/sync/syncCategories'; import { useSettingsStore } from '@/store/settingsStore'; import { eventDispatcher } from '@/utils/event'; @@ -107,7 +107,10 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) { }; const pushToAllTargets = (db: StatisticsDb, closing = false) => { - if (syncEnabled()) runBestEffort(pushStats(db, new SyncClient())); + if (syncEnabled()) { + runBestEffort(pushStats(db, new SyncClient())); + runBestEffort(pushSpeeds(db, new SyncClient())); + } const bookOrbitPush = bookOrbitStatsPush(db); if (bookOrbitPush) runBestEffort(bookOrbitPush); const grimmoryPush = grimmoryStatsPush(db, closing); @@ -129,7 +132,10 @@ export default function ReadingStatsTracker({ bookKey }: { bookKey: string }) { StatisticsDb.open(appService).then((db) => { if (cancelled) return; dbRef.current = db; - if (syncEnabled()) runBestEffort(pullStats(db, new SyncClient())); + if (syncEnabled()) { + runBestEffort(pullStats(db, new SyncClient())); + runBestEffort(pullSpeeds(db, new SyncClient())); + } }), ); return () => { diff --git a/apps/readest-app/src/components/stats/ReadingStatsDialog.tsx b/apps/readest-app/src/components/stats/ReadingStatsDialog.tsx index f5e1c32e9..680b9d57a 100644 --- a/apps/readest-app/src/components/stats/ReadingStatsDialog.tsx +++ b/apps/readest-app/src/components/stats/ReadingStatsDialog.tsx @@ -130,13 +130,16 @@ const ReadingStatsContent: React.FC = ({ 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 }] = await Promise.all([ + const [{ SyncClient }, { pullStats, pullSpeeds }] = 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); } }) diff --git a/apps/readest-app/src/libs/sync.ts b/apps/readest-app/src/libs/sync.ts index 94bff7424..5127bc8f3 100644 --- a/apps/readest-app/src/libs/sync.ts +++ b/apps/readest-app/src/libs/sync.ts @@ -2,6 +2,7 @@ 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'; @@ -46,6 +47,28 @@ 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; @@ -118,6 +141,40 @@ export class SyncClient { return result; } + /** Speed rows changed after `since`, oldest first, at most `limit`. */ + async pullSpeeds(since: SpeedCursor | null, limit: number): Promise { + 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.ok) throw new Error(`Failed to pull speeds: ${res.statusText}`); + return ((await res.json()) as { rows: StatSpeedRecord[] }).rows; + } + + async pushSpeeds(rows: StatSpeedRecord[]): Promise { + 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.ok) throw new Error(`Failed to push speeds: ${res.statusText}`); + } + private async pushRequest(payload: SyncData): Promise { const token = await getAccessToken(); if (!token) throw new Error('Not authenticated'); diff --git a/apps/readest-app/src/pages/api/sync/speeds.ts b/apps/readest-app/src/pages/api/sync/speeds.ts new file mode 100644 index 000000000..1828ab0b9 --- /dev/null +++ b/apps/readest-app/src/pages/api/sync/speeds.ts @@ -0,0 +1,176 @@ +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) => + 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[]) { + 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), + method: 'GET', + }); + response = await GET(nextReq); + } else if (req.method === 'POST') { + const nextReq = new NextRequest(url.toString(), { + headers: new Headers(req.headers as Record), + 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; diff --git a/apps/readest-app/src/services/database/migrations/index.ts b/apps/readest-app/src/services/database/migrations/index.ts index 7f14acd5f..2ea8b8ddc 100644 --- a/apps/readest-app/src/services/database/migrations/index.ts +++ b/apps/readest-app/src/services/database/migrations/index.ts @@ -226,6 +226,12 @@ const migrations: Record = { 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 diff --git a/apps/readest-app/src/services/statistics/statisticsDb.ts b/apps/readest-app/src/services/statistics/statisticsDb.ts index c34e441e4..74a1d0ae2 100644 --- a/apps/readest-app/src/services/statistics/statisticsDb.ts +++ b/apps/readest-app/src/services/statistics/statisticsDb.ts @@ -22,7 +22,18 @@ interface BookRow extends DatabaseRow { pages: number; } -type CursorKey = 'push' | 'pull' | 'bookorbit-push' | `grimmory-push:${string}`; +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; // 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. @@ -322,6 +333,72 @@ 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( + `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 { + const own = await this.db.select( + `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( + `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 { + 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, @@ -437,9 +514,10 @@ export class StatisticsDb { await this.recomputeBookTotals(id); // 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) - SELECT start_time_ms, ?, unit, count, duration_ms, lang 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, remote) + SELECT start_time_ms, ?, unit, count, duration_ms, lang, remote + FROM readest_reading_speed WHERE book_md5 = ? ON CONFLICT DO NOTHING`, [target.bookMd5, source], ); await this.deleteEventsBefore(source, Number.MAX_SAFE_INTEGER); diff --git a/apps/readest-app/src/services/statistics/statsSync.ts b/apps/readest-app/src/services/statistics/statsSync.ts index 0232da319..4a7d1fc9d 100644 --- a/apps/readest-app/src/services/statistics/statsSync.ts +++ b/apps/readest-app/src/services/statistics/statsSync.ts @@ -1,9 +1,16 @@ -import type { StatisticsDb } from './statisticsDb'; -import type { SyncClient, StatPageRecord, StatBookRecord } from '@/libs/sync'; +import type { SpeedBucket, StatisticsDb } from './statisticsDb'; +import type { + SyncClient, + SpeedCursor, + StatPageRecord, + StatBookRecord, + StatSpeedRecord, +} from '@/libs/sync'; import type { PageStatEvent, StatBook } from '@/types/statistics'; type PushClient = Pick; type PullClient = Pick; +type SpeedClient = Pick; const toWirePage = (e: PageStatEvent): StatPageRecord => ({ book_hash: e.bookMd5, @@ -19,6 +26,15 @@ 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. */ @@ -99,6 +115,60 @@ 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 { + 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); + await client.pushSpeeds(chunk.map(toWireSpeed)); + // 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 { + 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.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; + } +} + /** * Delete books' reading statistics (#7494). With a sync client the server * records the deletions first, in one request, so every device drops the @@ -128,12 +198,29 @@ const pushDeletions = (client: PushClient, books: StatBook[]) => */ export async function mergeBookStats( stats: StatisticsDb, - client: (PushClient & PullClient) | null, + client: (PushClient & PullClient & SpeedClient) | null, sources: StatBook[], target: StatBook, ): Promise { 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); + 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 })), + ); + } + } + } 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); for (let i = 0; i < events.length; i += PUSH_CHUNK) { diff --git a/docker/volumes/db/migrations/036_add_stat_speeds.sql b/docker/volumes/db/migrations/036_add_stat_speeds.sql new file mode 100644 index 000000000..1408387b6 --- /dev/null +++ b/docker/volumes/db/migrations/036_add_stat_speeds.sql @@ -0,0 +1,76 @@ +-- 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;