// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * AKM Desktop's own usage counts, per UTC day, in the usage store (`metrics.db`, `desktop_usage_daily`): how many * times each of its pages was opened (`page library/search`) and each of its API routes was called * (`GET search`, `POST proposals/:id/accept`). Desktop names them from its own page list and route table, so a name * never holds anything a person typed or chose; a name of any other shape is not counted. Counts are kept in memory and * written at most once a minute, before the daily report reads them, and when the process exits. `usage.capture: false` turns it off, and every * failure is swallowed: counting never changes what Desktop answers. */ import { captureDisabledByConfig, openUsage } from "./usage"; const NAME = /^(page [a-z-]+(\/[a-z-]+)?|(GET|POST) [a-z][a-z0-9_-]*(\/:?[a-z][a-z0-9_-]*)*)$/; const FLUSH_MS = 60_000; /** The usage store, with Desktop's table in it. */ function openDesktopUsage() { const db = openUsage(); db.exec( "CREATE TABLE IF NOT EXISTS desktop_usage_daily (day TEXT NOT NULL, name TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, name))", ); return db; } type Count = { day: string; name: string; count: number; failures: number }; const pending = new Map(); let flushedAt = 0; let flushOnExit = false; /** Count one use of `name` on `now`'s UTC day; `failed` when it ended in an error. */ export function countDesktopUse(name: string, failed = false, now = new Date()): void { if (!NAME.test(name)) return; const day = now.toISOString().slice(0, 10); const key = `${day} ${name}`; const entry = pending.get(key) ?? { day, name, count: 0, failures: 0 }; entry.count += 1; if (failed) entry.failures += 1; pending.set(key, entry); if (!flushOnExit) { flushOnExit = true; process.once("exit", () => flushDesktopUse()); } if (now.getTime() - flushedAt >= FLUSH_MS) flushDesktopUse(now); } /** Write the counts kept in memory to the usage store. */ export function flushDesktopUse(now = new Date()): void { flushedAt = now.getTime(); const rows = [...pending.values()]; pending.clear(); if (rows.length === 0 || captureDisabledByConfig()) return; try { const db = openDesktopUsage(); try { const add = db.prepare( "INSERT INTO desktop_usage_daily(day,name,count,failures) VALUES (?,?,?,?) ON CONFLICT(day,name) DO UPDATE SET count=count+excluded.count, failures=failures+excluded.failures", ); db.exec("BEGIN IMMEDIATE"); for (const row of rows) add.run(row.day, row.name, row.count, row.failures); db.exec("COMMIT"); } finally { db.close(); } } catch { // A locked or unwritable store loses these counts, as a CLI invocation's capture would. } } /** The counts of the UTC days `since`..`until`, summed per name. */ export function readDesktopUse(since: string, until: string): Array<{ name: string; count: number; failures: number }> { const db = openDesktopUsage(); try { return db .prepare( "SELECT name, SUM(count) AS count, SUM(failures) AS failures FROM desktop_usage_daily WHERE day >= ? AND day <= ? GROUP BY name ORDER BY name", ) .all(since, until) as Array<{ name: string; count: number; failures: number }>; } finally { db.close(); } }