diff --git a/README.md b/README.md index 5179cb4..4e4a246 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ and filed by a GitHub App. Reporters never need a GitHub account. - **GitHub issues:** search every issue, open and closed, across your connected repositories, including the ones opened directly on GitHub. Kept up to date every 2 minutes, no webhooks needed. - **Repo status (optional):** every repository at a glance, like a team status board: open PRs and issues and the oldest open PR, the last commit, issue and PR, what happened in a window you pick (10 minutes to a week, since the last build, or all time: commits, PRs opened and merged, issues, people), and each latest build with its unreleased commits and downloads. Sort by any column; a totals row sums them up. Fix first ranks the open issues across the repositories by what they say (crash, hang, data loss beats "doesn't work"), who filed them, how many people pile on and how fresh they are, with the reasons beside each score. Most reported ranks the issues by how many Discord tickets are about them (a duplicate counts for its original; ones Claude suggested and nobody has reviewed yet are shown as waiting for review), over the last 7, 30 or 90 days or all time, with the tickets one click away, and says when an issue closed as fixed keeps being reported. Pull requests lists the open ones (the ones fixing the most reported issues first, with how many Discord tickets are about them), the merged ones waiting for a release, and the ones merged in the last 90 days; Fix first and Most reported show when someone's working on an issue or it's already fixed. Read in the background every 5 to 60 minutes with GitHub's GraphQL API, which has its own budget, so filing isn't affected. Off until you turn it on; you pick the repositories (your apps' ones to start with). -- **Analytics (optional):** downloads recorded every 30 minutes from when you turn it on (GitHub only keeps running totals), per app, platform, processor, format and version, from 30 minutes to 12 months at a time (today in 30-minute steps by default; steps of 30m, 1h, 3h, 6h, 12h or a day), in your own time zone, or All: lifetime totals (GitHub's own download and star counts) with the same breakdowns. The main chart switches between downloads and stars: new stars over time (back to each repository's first star) and each app's star total, read every 30 minutes with the downloads. Next to them: tickets, issues opened and closed, pull requests merged and stars over the same time, each compared with the period before, and release health: Discord tickets while each release was the latest, per 1,000 of its downloads. Every chart has a table view. +- **Analytics (optional):** downloads recorded every 30 minutes from when you turn it on (GitHub only keeps running totals), per app, platform, processor, format and version, from 30 minutes to 12 months at a time (today in 30-minute steps by default; steps of 30m, 1h, 3h, 6h, 12h or a day), in your own time zone, or All: lifetime totals (GitHub's own download and star counts) with the same breakdowns. The main chart switches between downloads and stars: stars gained over time (the change in GitHub's star count, read every 30 minutes with the downloads from when you turn it on; a star taken back counts -1) and each app's star total. Next to them: tickets, issues opened and closed, pull requests merged and stars over the same time, each compared with the period before, and release health: Discord tickets while each release was the latest, per 1,000 of its downloads. Every chart has a table view. - **AI triage (optional):** Claude flags priority, duplicates, regressions, spam and more, and sorts tickets with your own label groups. Each action can be off, a suggestion, or automatic above a confidence threshold, with separate settings for issues opened directly on GitHub. - AI triage › Review lists everything with suggestions waiting, from Discord tickets and GitHub issues. Every ticket shows its triage state (To review, Partly applied, Applied…), and suggestions say exactly what applying them does. - Apply or dismiss in bulk, e.g. all duplicates at 80%+ confidence. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fa986b6..e0614e5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -121,14 +121,19 @@ Discord endpoint, OAuth), one or more queue workers, and an optional triage work - **Analytics** (`src/analytics/`, off by default per workspace in `analytics_settings`): GitHub only keeps each release file's running download total, so the worker's index loop reads every repository Repo status watches once per 30-minute slot (GraphQL: its releases and their files, - and new stars) and keeps how much each file grew since the read before (`download_counts`, per + and its star count) and keeps how much each file grew since the read before (`download_counts`, per slot; a short gap is spread evenly over its slots, a gap over a day starts recording again rather than inventing it; the first read is only a starting point, and a file that appears later counts from its release's publication). Files are classified by name (`assets.ts`: platform, architecture, format; checksums, signatures and update metadata aren't downloads). Detail is kept - 32 days, then added up per UTC day (`download_days`). Stars come with when each was given, so - their history goes back to the first (`repo_stars`); the same read keeps GitHub's own star total - per 30-minute slot (`repo_star_counts`, exact even when a star is taken back). The page buckets everything in the + 32 days, then added up per UTC day (`download_days`). Stars work the same way: GitHub won't list + who starred for the app (the stargazers need more than its permissions), so each read keeps the + repository's star count (`download_sync.stars_total`) and how much it changed since the read + before (`repo_star_changes`, per slot; a star taken back counts -1). A star count GitHub refuses + is kept per repository (`stars_error`) and said on the page; it doesn't stop the downloads. The + recorder's GraphQL reads are strict: an answer with data and errors together (a field the app + may not read comes back null) counts as a failure, where Repo status keeps the partial answer + and logs it. The page buckets everything in the viewer's time zone (a `tr_tz` cookie app.js sets): ranges from today to 12 months, steps from 30 minutes to a day (a step that would make over 400 buckets, or finer than a day beyond the 30-minute detail, isn't offered). Charts are drawn by app.js from the numbers on the page. @@ -233,7 +238,7 @@ stable user ID are recorded in the body. | `submissions` | Tickets, routing snapshot, queue state, lease, reconcile counters, encrypted payload | | `submission_events` | Append-only timeline for investigation | | `contributor_settings`, `contributor_panels`, `contributor_tiers` | On/off, panel channel, published panel, and role tiers (role + minimum contributions) per workspace | -| `analytics_settings`, `download_assets`, `download_counts`, `download_days`, `download_sync`, `repo_stars`, `repo_star_counts` | Analytics: on/off; each release file and its total; downloads per 30 minutes (then per day); per repository, when recording began and the last slot read; stars with when each was given; star totals per 30 minutes | +| `analytics_settings`, `download_assets`, `download_counts`, `download_days`, `download_sync`, `repo_star_changes` | Analytics: on/off; each release file and its total; downloads per 30 minutes (then per day); per repository, when recording began, the last slot read, the star count and any error; the change in the star count per 30 minutes | | `pull_index` | Pull requests of the indexed repositories (open, and closed for 90 days), with the issues each is for | | `repo_status_settings`, `repo_status` | Repo status: on/off, the repositories and how often per workspace; what was last read per repository (stats, the kept activity, the icon, the error and the GraphQL budget left) | | `contributor_links`, `contributor_verifications` | One GitHub account ↔ one Discord member per workspace; audit trail of every verification | diff --git a/src/analytics/queries.ts b/src/analytics/queries.ts index 8b78ad4..ac0900e 100644 --- a/src/analytics/queries.ts +++ b/src/analytics/queries.ts @@ -1,8 +1,9 @@ /** * Analytics: what the page shows for a window (a range, a step, a time zone) and a set of * repositories: downloads per bucket and their breakdowns (app, platform, architecture, format, - * version), tickets, issues opened and closed, pull requests merged and stars over the same - * buckets, each with the period before, and release health (tickets per 1,000 downloads). + * version), tickets, issues opened and closed, pull requests merged and stars (the change in each + * repository's star count) over the same buckets, each with the period before, and release health + * (tickets per 1,000 downloads). */ import type { Queryable } from '../db/database.js'; import type { RepoRef } from '../repo-status/tracker.js'; @@ -62,9 +63,13 @@ export interface AnalyticsData { issuesOpened: Metric & { fromDiscord: number }; issuesClosed: Metric; pullsMerged: Metric; + /** The change in the star count (stars given less stars taken back), known from when the star count was first read. */ stars: Metric; - /** Per app: its star total as GitHub last counted it (every 30 minutes), and the stars given in the period. */ + starsSince: Date | null; + /** Per app: its star total as GitHub last counted it (every 30 minutes), and how much it changed in the period. */ starsByApp: { label: string; total: number | null; gained: number }[]; + /** Repositories whose star count couldn't be read last time, and why. */ + starErrors: { app: string; error: string }[]; releases: ReleaseHealth[]; } @@ -181,17 +186,31 @@ export async function analyticsData(q: Queryable, workspaceId: string, repos: Re SELECT repo_id, CAST(ref AS INTEGER), merged_at FROM repo_changes WHERE repo_id IN (SELECT value FROM json_each($1)) AND kind = 'pr' AND noise IS NULL AND merged_at >= $2 AND merged_at < $3 ) GROUP BY 1`, [repoIds, span[0], span[1]])); - const stars = await metric(await perSlot(q, - `SELECT ${slot('starred_at')} AS at, count(*) AS n FROM repo_stars WHERE repo_id IN (SELECT value FROM json_each($1)) AND starred_at >= $2 AND starred_at < $3 GROUP BY 1`, - [repoIds, span[0], span[1]])); - - const { rows: totals } = await q.query<{ repo_id: number; stars_total: number | null }>('SELECT repo_id, stars_total FROM download_sync WHERE repo_id IN (SELECT value FROM json_each($1))', [repoIds]); - const { rows: given } = await q.query<{ repo_id: number; n: number }>( - 'SELECT repo_id, count(*) AS n FROM repo_stars WHERE repo_id IN (SELECT value FROM json_each($1)) AND starred_at >= $2 AND starred_at < $3 GROUP BY repo_id', - [repoIds, new Date(w.start), new Date(w.end)], + // Stars: the change in each repository's star count per 30-minute slot, known from the slot after the first read. + const { rows: starSync } = await q.query<{ repo_id: number; stars_total: number | null; stars_started_at: Date | null; stars_error: string | null }>( + 'SELECT repo_id, stars_total, stars_started_at, stars_error FROM download_sync WHERE repo_id IN (SELECT value FROM json_each($1))', + [repoIds], ); - const totalOf = new Map(totals.map((t) => [t.repo_id, t.stars_total === null ? null : Number(t.stars_total)])); - const gainedOf = new Map(given.map((g) => [g.repo_id, Number(g.n)])); + const starsStarted = starSync.map((r) => r.stars_started_at?.getTime()).filter((t): t is number => t !== undefined); + const starsSince = starsStarted.length ? new Date(Math.min(...starsStarted)) : null; + const starsKnownFrom = starsSince ? Math.floor(starsSince.getTime() / SLOT_MS) * SLOT_MS + SLOT_MS : Infinity; + const { rows: starRows } = await q.query<{ at: number; repo_id: number; n: number }>( + 'SELECT slot_at AS at, repo_id, change AS n FROM repo_star_changes WHERE repo_id IN (SELECT value FROM json_each($1)) AND slot_at >= $2 AND slot_at < $3', + [repoIds, span[0], span[1]], + ); + const starCur = starRows.map((r) => ({ at: Number(r.at), repo_id: r.repo_id, n: Number(r.n) })).filter((r) => r.at >= w.start && r.at < w.end); + const stars: Metric = { + total: sum(starCur), + prev: !lifetime && starsSince !== null && starsKnownFrom <= w.prevStart ? sum(starRows.filter((r) => Number(r.at) >= w.prevStart && Number(r.at) < w.prevEnd)) : null, + values: bucketed(w, starCur, starsKnownFrom), + }; + const totalOf = new Map(starSync.map((t) => [t.repo_id, t.stars_total === null ? null : Number(t.stars_total)])); + const gainedOf = new Map(); + for (const r of starCur) gainedOf.set(r.repo_id, (gainedOf.get(r.repo_id) ?? 0) + r.n); + const starErrors = repos.flatMap((r) => { + const e = starSync.find((x) => x.repo_id === r.id)?.stars_error; + return e ? [{ app: appNames.get(r.id) ?? r.name, error: e }] : []; + }); const starsByApp = repos .map((r) => ({ label: appNames.get(r.id) ?? r.name, total: totalOf.get(r.id) ?? null, gained: gainedOf.get(r.id) ?? 0 })) .sort((a, b) => (b.total ?? -1) - (a.total ?? -1) || b.gained - a.gained); @@ -223,10 +242,10 @@ export async function analyticsData(q: Queryable, workspaceId: string, repos: Re } releases.sort((a, b) => (b.publishedAt?.getTime() ?? 0) - (a.publishedAt?.getTime() ?? 0)); - // All: the star total is GitHub's own count (the history leaves out stars taken back). + // All: the star total is GitHub's own count. const starTotal = starsByApp.reduce((t, r) => t + (r.total ?? 0), 0); const starsOut = lifetime && starsByApp.some((r) => r.total !== null) ? { ...stars, total: starTotal } : stars; - return { recordingSince, lastRead: lastReadMs ? new Date(lastReadMs) : null, downloads, tickets, issuesOpened: issuesOpenedAll, issuesClosed, pullsMerged, stars: starsOut, starsByApp, releases: releases.slice(0, 15) }; + return { recordingSince, lastRead: lastReadMs ? new Date(lastReadMs) : null, downloads, tickets, issuesOpened: issuesOpenedAll, issuesClosed, pullsMerged, stars: starsOut, starsSince, starsByApp, starErrors, releases: releases.slice(0, 15) }; } export { PLATFORM_NAMES }; diff --git a/src/analytics/recorder.ts b/src/analytics/recorder.ts index 1110b63..38ee489 100644 --- a/src/analytics/recorder.ts +++ b/src/analytics/recorder.ts @@ -1,9 +1,10 @@ /** - * Analytics: records downloads every 30 minutes, and stars. GitHub only keeps each release file's - * running total, so each read keeps how much every file grew since the read before, per 30-minute - * slot; nothing is known from before recording began. Runs in the triage worker's polling loop - * (next to the issue index and Repo status), with GitHub's GraphQL API: two small queries per - * repository every 30 minutes (releases, and new stars), on the budget filing doesn't use. + * Analytics: records downloads and stars every 30 minutes. GitHub only keeps running totals (each + * release file's downloads, the repository's stars), so each read keeps how much they changed since + * the read before, per 30-minute slot; nothing is known from before recording began. Runs in the + * triage worker's polling loop (next to the issue index and Repo status), with GitHub's GraphQL + * API: two small queries per repository every 30 minutes (releases, and the star count), on the + * budget filing doesn't use. * * Which repositories: the ones Repo status watches (its own list, else every app's), for every * workspace with Analytics on. @@ -23,7 +24,6 @@ const PER_ROUND = 4; /** Past this gap (the process was off, or Analytics was), growth isn't spread over the gap: recording starts again. */ const MAX_GAP_MS = 24 * 3_600_000; const RELEASE_PAGES = 4; -const STAR_PAGES = 100; const ROLLUP_EVERY_MS = 6 * 3_600_000; const RELEASES_QUERY = ` @@ -36,15 +36,10 @@ query AnalyticsReleases($owner: String!, $name: String!, $after: String) { } }`; +// Only the count: who starred (stargazers) is more than the app's permissions let it read. const STARS_QUERY = ` -query AnalyticsStars($owner: String!, $name: String!, $after: String) { - repository(owner: $owner, name: $name) { - stargazerCount - stargazers(first: 100, after: $after, orderBy: {field: STARRED_AT, direction: DESC}) { - pageInfo { hasNextPage endCursor } - edges { starredAt node { login } } - } - } +query AnalyticsStars($owner: String!, $name: String!) { + repository(owner: $owner, name: $name) { stargazerCount } }`; export interface AnalyticsSettings { @@ -81,8 +76,10 @@ export interface SyncRow { last_slot_at: Date | null; checked_at: Date | null; error: string | null; - stars_loaded_at: Date | null; - stars_until_at: Date | null; + stars_started_at: Date | null; + stars_slot_at: Date | null; + stars_total: number | null; + stars_error: string | null; lease_until_at: Date | null; } @@ -162,20 +159,24 @@ export class AnalyticsRecorder { startedAt = now; } await this.recordDownloads(sync, lastSlot, slot, now); - await this.recordStars(sync, now); lastSlot = slot; } catch (err) { - const e = err as Error; - error = err instanceof GitHubApiError - ? err.isRateLimit ? 'GitHub’s hourly budget ran out: reading again when it resets.' - : err.status === 404 || err.status === 403 ? 'GitHub didn’t let the app read this repository’s releases.' - : `GitHub returned ${err.status}.` - : `GitHub couldn’t be reached (${e.message.slice(0, 120)}).`; - this.deps.log.warn({ repo: `${sync.owner}/${sync.name}`, err: e.message }, 'download recording failed'); + error = readError(err, 'this repository’s releases'); + this.deps.log.warn({ repo: `${sync.owner}/${sync.name}`, err: (err as Error).message }, 'download recording failed'); + } + // Stars on their own: a refusal there doesn't stop the downloads (skipped when the budget ran out). + let starsError: string | null = null; + if (!error?.startsWith('GitHub’s hourly budget')) { + try { + await this.recordStars(sync, now); + } catch (err) { + starsError = readError(err, 'the star count'); + this.deps.log.warn({ repo: `${sync.owner}/${sync.name}`, err: (err as Error).message }, 'star count read failed'); + } } await db.query( - 'UPDATE download_sync SET last_slot_at = $2, started_at = $3, checked_at = $4, error = $5, lease_until_at = NULL WHERE repo_id = $1', - [repoId, lastSlot === null ? null : new Date(lastSlot), new Date(startedAt), new Date(now), error], + 'UPDATE download_sync SET last_slot_at = $2, started_at = $3, checked_at = $4, error = $5, stars_error = $6, lease_until_at = NULL WHERE repo_id = $1', + [repoId, lastSlot === null ? null : new Date(lastSlot), new Date(startedAt), new Date(now), error, starsError], ); } @@ -189,7 +190,7 @@ export class AnalyticsRecorder { const files: { release: string; name: string; publishedAt: Date | null; prerelease: boolean; downloads: number }[] = []; let after: string | null = null; for (let page = 0; page < RELEASE_PAGES; page++) { - const d: any = await github!.graphql(sync.installation_id, RELEASES_QUERY, { owner: sync.owner, name: sync.name, after }); + const d: any = await github!.graphql(sync.installation_id, RELEASES_QUERY, { owner: sync.owner, name: sync.name, after }, { strict: true }); if (!d?.repository) throw new GitHubApiError(404, 'Repository not found', null, false, null); const conn = d.repository.releases; for (const r of conn?.nodes ?? []) { @@ -239,51 +240,52 @@ export class AnalyticsRecorder { } /** - * The star history once (back to the first), then each time the stars added since; and the - * repository's star total as GitHub counts it, kept per 30-minute slot like the downloads. + * The repository's star total as GitHub counts it, and how much it changed since the last read in + * the slots in between (like the downloads; a star taken back counts -1). The first read, and the + * first after a long gap, is only a starting point. */ private async recordStars(sync: SyncRow, now: number): Promise { const { db, github } = this.deps; - const since = sync.stars_loaded_at ? (sync.stars_until_at?.getTime() ?? 0) - 60_000 : null; - let newest = sync.stars_until_at?.getTime() ?? 0; - let after: string | null = null; - let complete = false; - let total: number | null = null; - for (let page = 0; page < (since === null ? STAR_PAGES : 5); page++) { - const d: any = await github!.graphql(sync.installation_id, STARS_QUERY, { owner: sync.owner, name: sync.name, after }); - if (total === null && Number.isFinite(Number(d?.repository?.stargazerCount))) total = Number(d.repository.stargazerCount); - const conn = d?.repository?.stargazers; - let older = false; - for (const e of conn?.edges ?? []) { - const at = e?.starredAt ? new Date(e.starredAt).getTime() : NaN; - const login = e?.node?.login; - if (!Number.isFinite(at) || !login) continue; - if (since !== null && at < since) { - older = true; - continue; + const d: any = await github!.graphql(sync.installation_id, STARS_QUERY, { owner: sync.owner, name: sync.name }, { strict: true }); + if (!d?.repository) throw new GitHubApiError(404, 'Repository not found', null, false, null); + const total = Number(d.repository.stargazerCount); + if (!Number.isInteger(total) || total < 0) throw new Error('GitHub gave no star count'); + const slot = slotOf(now); + const last = sync.stars_slot_at?.getTime() ?? null; + if (last !== null && sync.stars_total !== null && slot - last <= MAX_GAP_MS && total !== Number(sync.stars_total)) { + // The slots since the last read (a second read in the same slot adds to that slot). + const slots: number[] = []; + for (let s = last; s < slot; s += SLOT_MS) slots.push(s); + if (!slots.length) slots.push(last); + const change = total - Number(sync.stars_total); + const each = Math.trunc(change / slots.length); + const rest = change - each * slots.length; + for (let i = 0; i < slots.length; i++) { + const n = each + (i >= slots.length - Math.abs(rest) ? Math.sign(rest) : 0); + if (n !== 0) { + await db.query( + `INSERT INTO repo_star_changes (repo_id, slot_at, change) VALUES ($1, $2, $3) + ON CONFLICT (repo_id, slot_at) DO UPDATE SET change = repo_star_changes.change + excluded.change`, + [sync.repo_id, new Date(slots[i]!), n], + ); } - newest = Math.max(newest, at); - await db.query('INSERT INTO repo_stars (repo_id, login, starred_at) VALUES ($1, $2, $3) ON CONFLICT (repo_id, login) DO UPDATE SET starred_at = excluded.starred_at', [sync.repo_id, String(login), new Date(at)]); } - if (older || !conn?.pageInfo?.hasNextPage) { - complete = true; - break; - } - after = conn.pageInfo.endCursor; } await db.query( - 'UPDATE download_sync SET stars_loaded_at = CASE WHEN $2 = 1 THEN COALESCE(stars_loaded_at, $4) ELSE stars_loaded_at END, stars_until_at = $3, stars_total = COALESCE($5, stars_total) WHERE repo_id = $1', - [sync.repo_id, complete ? 1 : 0, newest ? new Date(newest) : null, new Date(now), total], + 'UPDATE download_sync SET stars_total = $2, stars_slot_at = $3, stars_started_at = COALESCE(stars_started_at, $4) WHERE repo_id = $1', + [sync.repo_id, total, new Date(slot), new Date(now)], ); - if (total !== null) { - await db.query( - 'INSERT INTO repo_star_counts (repo_id, slot_at, total) VALUES ($1, $2, $3) ON CONFLICT (repo_id, slot_at) DO UPDATE SET total = excluded.total', - [sync.repo_id, new Date(slotOf(now)), total], - ); - } } } +/** What went wrong reading something from GitHub, for the page. */ +function readError(err: unknown, what: string): string { + if (!(err instanceof GitHubApiError)) return `GitHub couldn’t be reached (${(err as Error).message.slice(0, 120)}).`; + if (err.isRateLimit) return 'GitHub’s hourly budget ran out: reading again when it resets.'; + if (err.status === 404 || err.status === 403) return `GitHub didn’t let the app read ${what}.`; + return `GitHub returned ${err.status}.`; +} + /** 30-minute detail older than DETAIL_DAYS is added up per UTC day. */ export async function rollUp(q: Queryable, now = Date.now()): Promise { const cutoff = Math.floor((now - DETAIL_DAYS * 86_400_000) / 86_400_000) * 86_400_000; diff --git a/src/db/migrations/038_star_changes.sql b/src/db/migrations/038_star_changes.sql new file mode 100644 index 0000000..cf8b8a0 --- /dev/null +++ b/src/db/migrations/038_star_changes.sql @@ -0,0 +1,17 @@ +-- Analytics stars: GitHub won't list who starred a repository for the app (that needs more than +-- its permissions), so the star history (repo_stars) never filled and its reads were marked done. +-- Stars now come from the repository's star total, read every 30 minutes with the downloads: each +-- read keeps how much the total changed since the read before, per 30-minute slot (a star taken +-- back counts -1). Nothing is known from before this starts. +DROP TABLE IF EXISTS repo_stars; +DROP TABLE IF EXISTS repo_star_counts; +CREATE TABLE repo_star_changes ( + repo_id INTEGER NOT NULL, + slot_at INTEGER NOT NULL, + change INTEGER NOT NULL, + PRIMARY KEY (repo_id, slot_at) +); +ALTER TABLE download_sync RENAME COLUMN stars_loaded_at TO stars_started_at; -- the first star count read +ALTER TABLE download_sync RENAME COLUMN stars_until_at TO stars_slot_at; -- the slot of the last one +ALTER TABLE download_sync ADD COLUMN stars_error TEXT; +UPDATE download_sync SET stars_started_at = NULL, stars_slot_at = NULL, stars_total = NULL; diff --git a/src/github/client.ts b/src/github/client.ts index 4f0e871..0a6d3bc 100644 --- a/src/github/client.ts +++ b/src/github/client.ts @@ -378,13 +378,20 @@ export class GitHubClient { * A GraphQL query as the installation. GraphQL has its own hourly budget, apart from the REST * one that filing uses. Missing objects come back as null; errors with no data throw. */ - async graphql(installationId: number, query: string, variables: Record = {}): Promise { + /** + * A GraphQL query as the installation. GitHub can answer with data and errors together (a field + * the app may not read comes back null, and can take its parent with it): `strict` treats that + * as an error; otherwise `onErrors` hears about it and the partial data is returned. + */ + async graphql(installationId: number, query: string, variables: Record = {}, o: { strict?: boolean; onErrors?: (errors: any[]) => void } = {}): Promise { const { data } = await this.request('POST', '/graphql', await this.asInstallation(installationId), { query, variables }); const errors = Array.isArray(data?.errors) ? data.errors : []; - if (errors.length && !data?.data) { + if (errors.length && (!data?.data || o.strict)) { const limited = errors.some((e: any) => e?.type === 'RATE_LIMITED'); - throw new GitHubApiError(limited ? 403 : 502, String(errors[0]?.message ?? 'GraphQL error'), limited ? 300 : null, limited, errors); + const refused = errors.some((e: any) => e?.type === 'FORBIDDEN' || /not accessible by integration/i.test(String(e?.message ?? ''))); + throw new GitHubApiError(limited || refused ? 403 : 502, String(errors[0]?.message ?? 'GraphQL error'), limited ? 300 : null, limited, errors); } + if (errors.length) o.onErrors?.(errors); return data?.data ?? null; } diff --git a/src/repo-status/tracker.ts b/src/repo-status/tracker.ts index 9714a1f..135450e 100644 --- a/src/repo-status/tracker.ts +++ b/src/repo-status/tracker.ts @@ -393,13 +393,16 @@ export class RepoStatusTracker { /** Reads one repository (exposed for tests through tick). */ private async fetch(installationId: number, repo: RepoRef, prev: Raw | null, iconOid: string | null, now: number) { const gh = this.deps.github!; + // A partial answer (a field GitHub won't give the app) is kept, but logged. + const onErrors = (errors: any[]) => this.deps.log.warn({ repo: `${repo.owner}/${repo.name}`, errors: errors.slice(0, 3).map((e) => String(e?.message ?? e)) }, 'repo status: GitHub left part of the answer out'); + const ask = (query: string, variables: Record) => gh.graphql(installationId, query, variables, { onErrors }); const vars = { owner: repo.owner, name: repo.name }; // Releases and their downloads. const releases: Release[] = []; let after: string | null = null; for (let page = 0; page < 4; page++) { - const d: any = await gh.graphql(installationId, RELEASES_QUERY, { ...vars, after }); + const d: any = await ask(RELEASES_QUERY, { ...vars, after }); if (!d?.repository) throw new GitHubApiError(404, 'Repository not found', null, false, null); const conn = d.repository.releases; for (const r of conn?.nodes ?? []) { @@ -418,7 +421,7 @@ export class RepoStatusTracker { // Counts, dates, each window's commits and the open issues to score. const starts = windowStarts(now, buildAt); const history = starts.map((w) => `${w.key}: history(since: "${iso(w.since)}") { totalCount }`).join('\n '); - const main: any = await gh.graphql(installationId, MAIN_QUERY.replace('{HISTORY}', history), vars); + const main: any = await ask(MAIN_QUERY.replace('{HISTORY}', history), vars); const r = main?.repository; if (!r) throw new GitHubApiError(404, 'Repository not found', null, false, null); const budget = main?.rateLimit ? { remaining: Number(main.rateLimit.remaining), resetAt: new Date(main.rateLimit.resetAt) } : null; @@ -432,7 +435,7 @@ export class RepoStatusTracker { const latest = rel.latest; if (latest && branch) { const at = latest.commitAt ?? buildAt ?? new Date(now); - const b: any = await gh.graphql(installationId, BUILD_QUERY, { ...vars, tag: `refs/tags/${latest.tag}`, branch, at: iso(at) }); + const b: any = await ask(BUILD_QUERY, { ...vars, tag: `refs/tags/${latest.tag}`, branch, at: iso(at) }); const cmp = b?.repository?.ref?.compare; if (cmp && typeof cmp.aheadBy === 'number') { unreleased = cmp.aheadBy; @@ -453,7 +456,7 @@ export class RepoStatusTracker { if (head) { after = null; for (let page = 0; page < MAX_PAGES; page++) { - const d: any = await gh.graphql(installationId, AUTHORS_QUERY, { ...vars, since: iso(since), after }); + const d: any = await ask(AUTHORS_QUERY, { ...vars, since: iso(since), after }); const conn = d?.repository?.defaultBranchRef?.target?.history; for (const c of conn?.nodes ?? []) { const who = c.author?.user?.login ?? c.author?.email ?? c.author?.name ?? 'someone'; @@ -466,7 +469,7 @@ export class RepoStatusTracker { const cursors: Record<'opened' | 'merged' | 'issues', string | null> = { opened: null, merged: null, issues: null }; const walking = { opened: true, merged: true, issues: true }; for (let page = 0; page < MAX_PAGES && (walking.opened || walking.merged || walking.issues); page++) { - const d: any = await gh.graphql(installationId, EVENTS_QUERY, { + const d: any = await ask(EVENTS_QUERY, { ...vars, opened: walking.opened, merged: walking.merged, issues: walking.issues, openedAfter: cursors.opened, mergedAfter: cursors.merged, issuesAfter: cursors.issues, }); diff --git a/src/web/public/app.js b/src/web/public/app.js index f3d9cce..e88a5df 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -2016,9 +2016,18 @@ d.series.forEach(function (s) { var v = s.values[i]; if (v !== null && v !== undefined) { known = true; t += v; } }); return known ? t : null; }); - var ticks = niceTicks(Math.max.apply(null, totals.map(function (t) { return t || 0; })), small ? 2 : 4); - var top = ticks[ticks.length - 1]; - var y = function (v) { return padT + plotH - (v / top) * plotH; }; + var hi = Math.max.apply(null, totals.map(function (t) { return t || 0; })); + var lo = Math.min(0, Math.min.apply(null, totals.map(function (t) { return t || 0; }))); + var ticks = niceTicks(hi - lo, small ? 2 : 4); + if (lo < 0) { + // A change that can go down (stars taken back): the same round steps, below zero too. + var st = ticks[1] - ticks[0], from = Math.floor(lo / st) * st; + ticks = []; + for (var tv = from; tv <= Math.max(hi, 0) + st * 0.999; tv += st) ticks.push(tv); + if (ticks[ticks.length - 1] < hi) ticks.push(ticks[ticks.length - 1] + st); + } + var top = ticks[ticks.length - 1], bot = ticks[0]; + var y = function (v) { return padT + plotH - ((v - bot) / (top - bot)) * plotH; }; var band = plotW / n; var barW = band >= 6 ? Math.min(24, Math.max(2, band * 0.7)) : Math.max(1, band - 1); box.textContent = ''; @@ -2055,6 +2064,11 @@ var path = 'M' + x + ',' + (yTop + h) + ' V' + (yTop + r) + (r ? ' Q' + x + ',' + yTop + ' ' + (x + r) + ',' + yTop : '') + ' H' + (x + barW - r) + (r ? ' Q' + (x + barW) + ',' + yTop + ' ' + (x + barW) + ',' + (yTop + r) : '') + ' V' + (yTop + h) + ' Z'; el('path', { d: path, class: 'an-bar-s s' + p.s.slot }, marks); }); + if (totals[i] !== null && totals[i] < 0 && d.series.length === 1) { + // Below zero: hangs from the baseline, rounded at the bottom. + var nh = Math.max(1, y(totals[i]) - base), nr = Math.min(4, barW / 2, nh); + el('path', { d: 'M' + x + ',' + base + ' V' + (base + nh - nr) + (nr ? ' Q' + x + ',' + (base + nh) + ' ' + (x + nr) + ',' + (base + nh) : '') + ' H' + (x + barW - nr) + (nr ? ' Q' + (x + barW) + ',' + (base + nh) + ' ' + (x + barW) + ',' + (base + nh - nr) : '') + ' V' + base + ' Z', class: 'an-bar-s s' + d.series[0].slot }, marks); + } if (totals[i] === null && i * band + padL < W) { // Nothing known (before recording, or still to come): a faint baseline only. el('line', { x1: x, x2: x + barW, y1: base - 0.5, y2: base - 0.5, class: 'an-unknown' }, marks); @@ -2115,7 +2129,7 @@ var cx = padL + i * band + band / 2; var left = Math.min(Math.max(cx - tip.offsetWidth / 2, 0), W - tip.offsetWidth); tip.style.left = left + 'px'; - tip.style.top = Math.max(0, y(totals[i] || 0) - tip.offsetHeight - 10) + 'px'; + tip.style.top = Math.max(0, y(Math.max(0, totals[i] || 0)) - tip.offsetHeight - 10) + 'px'; } function hide() { active = -1; tip.hidden = true; hover.setAttribute('visibility', 'hidden'); } svg.addEventListener('pointermove', function (e) { diff --git a/src/web/routes/analytics.ts b/src/web/routes/analytics.ts index 309f964..a2c8234 100644 --- a/src/web/routes/analytics.ts +++ b/src/web/routes/analytics.ts @@ -23,6 +23,8 @@ function compact(x: number): string { if (x < 1_000_000) return `${(x / 1000).toFixed(x < 100_000 ? 1 : 0).replace(/\.0$/, '')}K`; return `${(x / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`; } +/** A change: +12 · −3 · 0 */ +const signed = (x: number) => (x > 0 ? `+${compact(x)}` : x < 0 ? `−${compact(-x)}` : '0'); /** Up is good, down is good, or neither (the delta stays neutral). */ type Better = 'up' | 'down' | null; @@ -91,10 +93,10 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void { return hbars(items, o); } - /** Each app's star total (GitHub's count) and the stars it was given in the period. */ + /** Each app's star total (GitHub's count) and how much it changed in the period. */ function starList(rows: AnalyticsData['starsByApp'], o: { gained?: boolean } = { gained: true }): SafeHtml { if (!rows.some((r) => r.total !== null || r.gained)) return html`

Star totals show up after the first read.

`; - return hbars(rows.map((r) => ({ label: r.label, value: r.total ?? 0, note: o.gained ? `+${n(r.gained)}` : null, noteUp: r.gained > 0 })), { empty: 'No stars yet.', share: false, max: 30 }); + return hbars(rows.map((r) => ({ label: r.label, value: r.total ?? 0, note: o.gained ? signed(r.gained) : null, noteUp: r.gained > 0 })), { empty: 'No stars yet.', share: false, max: 30 }); } function tile(label: string, value: string, d: SafeHtml, title?: string, sub?: SafeHtml | string): SafeHtml { @@ -123,6 +125,7 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void { // One repository (picked, or the only one): downloads by platform; several: all of them together. const single = d.downloads.series.length > 1; const noDownloads = !lifetime && metric === 'downloads' && (!d.recordingSince || (d.downloads.total === 0 && d.recordingSince.getTime() > w.start)); + const noStars = !lifetime && metric === 'stars' && !d.starErrors.length && (!d.starsSince || (d.stars.total === 0 && d.starsSince.getTime() > w.start)); const per = `per ${w.step.id === '1d' ? 'day' : w.step.label}`; const switcher = html``; const appLabel = single ? apps.find((a) => String(a.id) === repoChoice)?.name ?? apps[0]?.name ?? 'this app' : 'all apps'; @@ -142,6 +145,10 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void { ${noDownloads ? html`
${notice('info', d.recordingSince ? 'Downloads are being recorded' : 'Downloads start recording in a minute', d.recordingSince ? html`Recording began ${localTime(d.recordingSince)}: GitHub only keeps running totals, so nothing is known from before. The first numbers show up after the next half hour.` : 'The first read of each repository is a starting point; downloads show up from the half hour after.')}
` : ''} + ${metric === 'stars' && d.starErrors.length ? html`
${notice('warn', 'Stars couldn’t be read', html`${d.starErrors.length === 1 ? html`${d.starErrors[0]!.app}: ${d.starErrors[0]!.error}` : html`For ${d.starErrors.map((e) => e.app).join(', ')}. ${d.starErrors[0]!.error}`} Trying again every 30 minutes; downloads aren’t affected.`)}
` : ''} + ${noStars ? html`
${notice('info', d.starsSince ? 'Stars are being recorded' : 'Stars start recording in a minute', d.starsSince + ? html`Counting began ${localTime(d.starsSince)}: GitHub gives the app each repository’s star count, so stars are counted from how it changes, every 30 minutes. Nothing is known from before.` + : 'The first read of each repository’s star count is a starting point; changes show up from the half hour after.')}
` : ''}
${tile('Downloads', compact(d.downloads.total), vs(d.downloads.total, d.downloads.prev, 'up'), lifetime ? 'GitHub’s own totals for every release file (checksums and update data left out)' : 'Release files downloaded from GitHub (checksums and update data left out)')} @@ -150,27 +157,27 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void { ${tile('Issues opened', compact(d.issuesOpened.total), vs(d.issuesOpened.total, d.issuesOpened.prev, null), 'Every new GitHub issue in these repositories: the ones filed from Discord tickets, and the ones opened on GitHub', `${n(d.issuesOpened.fromDiscord)} from Discord · ${n(Math.max(0, d.issuesOpened.total - d.issuesOpened.fromDiscord))} on GitHub`)} ${tile('Issues closed', compact(d.issuesClosed.total), vs(d.issuesClosed.total, d.issuesClosed.prev, 'up'))} ${tile('PRs merged', compact(d.pullsMerged.total), vs(d.pullsMerged.total, d.pullsMerged.prev, 'up'))} - ${tile('Stars', compact(d.stars.total), vs(d.stars.total, d.stars.prev, 'up'), lifetime ? 'GitHub’s own star count' : undefined)} + ${tile('Stars', lifetime ? compact(d.stars.total) : signed(d.stars.total), vs(d.stars.total, d.stars.prev, 'up'), lifetime ? 'GitHub’s own star count' : 'How much GitHub’s star count changed: stars given, less stars taken back')}

${metric === 'stars' ? 'Stars' : 'Downloads'}

${switcher}${lifetime ? metric === 'stars' ? 'all time · by app · GitHub’s count' : `all time · ${single ? 'by version' : 'by app'} · GitHub’s totals` : metric === 'stars' - ? `new stars · ${appLabel} · ${per} · back to the first star` + ? `stars gained · ${appLabel} · ${per}` : `${single ? 'by platform' : 'all apps'} · ${per}`}
${lifetime ? metric === 'stars' ? starList(d.starsByApp, { gained: false }) : bars(single ? d.downloads.versions : d.downloads.byApp, { empty: 'Downloads show up after the first read.' }) : metric === 'stars' - ? chart(w, tz, { id: 'stars', title: 'New stars', unit: 'New stars', series: [{ key: 'stars', name: 'New stars', values: d.stars.values, slot: 1 }] }) + ? chart(w, tz, { id: 'stars', title: 'Stars gained', unit: 'Stars gained', series: [{ key: 'stars', name: 'Stars gained', values: d.stars.values, slot: 1 }] }) : chart(w, tz, { id: 'downloads', title: 'Downloads', unit: 'Downloads', series: single ? d.downloads.series.map((s, i) => ({ ...s, slot: i + 1 })) : [{ ...d.downloads.series[0]!, slot: 1 }] })}
${metric === 'stars' ? (lifetime ? '' : html`
-

Stars by app

total, and new in this period
${starList(d.starsByApp)} -

Totals are GitHub’s own count, read every 30 minutes with the downloads, so a star taken back is counted out. New stars are the ones given in this period.

+

Stars by app

total, and change in this period
${starList(d.starsByApp, { gained: Boolean(d.starsSince) })} +

Totals are GitHub’s own count, read every 30 minutes with the downloads. The change is how much each total moved in this period: a star taken back counts −1.

`) : html`
${single || lifetime ? '' : html`

By app

${bars(d.downloads.byApp, { empty: 'No downloads in this period.' })}
`}

Platforms

${bars(d.downloads.platforms, { empty: 'No downloads in this period.', colored: true })}
@@ -205,7 +212,7 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void { : html`

Releases show up after the first read.

`} -

${lifetime ? html`All: GitHub’s own totals for downloads and stars, and every Discord ticket, issue and merged pull request kept. ` : ''}${d.recordingSince ? html`Downloads recorded every 30 minutes since ${localTime(d.recordingSince)}${d.lastRead ? html`, last read ${timeAgo(d.lastRead)}` : ''}.` : 'Downloads start recording within a minute.'} Times are in your time zone (${tz}). Tickets, issues and pull requests go back as far as they’re kept; stars go back to the first one.

`; +

${lifetime ? html`All: GitHub’s own totals for downloads and stars, and every Discord ticket, issue and merged pull request kept. ` : ''}${d.recordingSince ? html`Downloads recorded every 30 minutes since ${localTime(d.recordingSince)}${d.lastRead ? html`, last read ${timeAgo(d.lastRead)}` : ''}.` : 'Downloads start recording within a minute.'} ${d.starsSince ? html` Stars counted since ${localTime(d.starsSince)}.` : ''} Times are in your time zone (${tz}). Tickets, issues and pull requests go back as far as they’re kept.

`; } app.get('/w/:wid/analytics', async (req, reply) => { @@ -232,7 +239,7 @@ export function registerAnalyticsRoutes(app: FastifyInstance, web: Web): void {

See downloads every half hour, and what comes with them

Downloads per app, platform, processor, format and version, from 30 minutes to 12 months at a time, next to tickets, issues, pull requests and stars. Release health shows tickets per 1,000 downloads, so a bad build stands out.

-

GitHub only keeps running totals, so downloads are recorded from when you turn this on: every 30 minutes, for the ${plural(repos.length, 'repository', 'repositories')} Repo status watches. It reads releases and stars with GitHub’s GraphQL API (two small calls per repository each half hour); filing isn’t affected. Tickets, issues, pull requests and stars go back as far as they’re kept.

+

GitHub only keeps running totals, so downloads are recorded from when you turn this on: every 30 minutes, for the ${plural(repos.length, 'repository', 'repositories')} Repo status watches. It reads releases and star counts with GitHub’s GraphQL API (two small calls per repository each half hour); filing isn’t affected. Stars are counted from then too; tickets, issues and pull requests go back as far as they’re kept.

${edit ? html`
${postBtn(`${base(ctx)}/enabled`, 'Turn on', ctx.csrf, { variant: 'primary', icon: 'chart-line', fields: { enabled: '1' } })}
` : html`

An admin can turn it on.

`}
`; diff --git a/src/web/routes/workspace.ts b/src/web/routes/workspace.ts index ad61cac..57b0308 100644 --- a/src/web/routes/workspace.ts +++ b/src/web/routes/workspace.ts @@ -287,15 +287,16 @@ async function analyticsCard({ web, ctx }: Shared): Promise { WHERE a.repo_id IN (SELECT value FROM json_each($1)) AND a.kind <> 'meta' AND c.slot_at >= $2`, [ids, since(ms)])).rows[0]?.n ?? 0); const day = s.enabled ? await downloads(86_400_000) : 0; const week = s.enabled ? await downloads(7 * 86_400_000) : 0; - const stars = s.enabled ? Number((await db.query<{ n: number }>('SELECT count(*) AS n FROM repo_stars WHERE repo_id IN (SELECT value FROM json_each($1)) AND starred_at >= $2', [ids, since(7 * 86_400_000)])).rows[0]?.n ?? 0) : 0; + // Stars gained: the change in GitHub's star count (a star taken back counts -1). + const stars = s.enabled ? Number((await db.query<{ n: number }>('SELECT COALESCE(sum(change), 0) AS n FROM repo_star_changes WHERE repo_id IN (SELECT value FROM json_each($1)) AND slot_at >= $2', [ids, since(7 * 86_400_000)])).rows[0]?.n ?? 0) : 0; return { tool: 'analytics', - meta: s.enabled ? `Downloads every 30 minutes${s.enabledAt ? ` · started ${timeAgo(s.enabledAt)}` : ''}` : 'Off', + meta: s.enabled ? `Downloads and stars every 30 minutes${s.enabledAt ? ` · started ${timeAgo(s.enabledAt)}` : ''}` : 'Off', status: s.enabled ? pill('Recording', 'ok') : pill('Off', 'neutral'), stats: [ { label: 'Downloads, last 24 h', value: day, area: 'analytics', href: `${b}/analytics` }, { label: 'Last 7 days', value: week, area: 'analytics', href: `${b}/analytics?range=7d` }, - { label: 'Stars, last 7 days', value: stars, area: 'analytics', href: `${b}/analytics?range=7d` }, + { label: 'Stars gained, last 7 days', value: stars, area: 'analytics', href: `${b}/analytics?range=7d&metric=stars` }, ], go: [{ area: 'analytics', label: s.enabled ? 'Open Analytics' : 'Set up Analytics', primary: !s.enabled && can(ctx.membership, 'analytics.edit') }], }; diff --git a/test/analytics.test.ts b/test/analytics.test.ts index 1eb8b8f..13eebcd 100644 --- a/test/analytics.test.ts +++ b/test/analytics.test.ts @@ -124,20 +124,37 @@ describe('Analytics: recording downloads', () => { expect(sync.started_at.getTime()).toBe(later); }); - it('reads the star history once, then only new stars; old detail is kept per day', async () => { + it('counts stars from how GitHub’s star count changes; a refused read shows and doesn’t stop downloads; old detail is kept per day', async () => { seed(); await post('/analytics/enabled', { enabled: '1' }); - const t0 = Date.now(); + const t0 = slotOf(Date.now()) - 6 * SLOT_MS; await tick(t0); - const stars = async () => (await env.db.query('SELECT login FROM repo_stars ORDER BY login')).rows.map((r) => r.login); - expect(await stars()).toEqual(['ana', 'ben']); - // GitHub's own total, per 30-minute slot, with the downloads. - expect((await env.db.query('SELECT slot_at, total FROM repo_star_counts')).rows).toEqual([{ slot_at: new Date(slotOf(t0)), total: 2 }]); + const sync = async () => (await env.db.query('SELECT stars_total, stars_started_at, stars_error, last_slot_at, error FROM download_sync')).rows[0]; + const changes = async () => (await env.db.query('SELECT slot_at, change FROM repo_star_changes ORDER BY slot_at')).rows.map((r) => [r.slot_at.getTime() - t0, r.change]); + // The first read is a starting point: GitHub's count, no change yet. + expect(await sync()).toMatchObject({ stars_total: 2, stars_started_at: new Date(t0), stars_error: null }); + expect(await changes()).toEqual([]); repo().stars!.push({ login: 'cy', at: new Date().toISOString() }); await tick(t0 + SLOT_MS); - expect(await stars()).toEqual(['ana', 'ben', 'cy']); - expect((await env.db.query('SELECT total FROM repo_star_counts ORDER BY slot_at')).rows.map((r) => r.total)).toEqual([2, 3]); - expect((await env.db.query('SELECT stars_total FROM download_sync')).rows[0].stars_total).toBe(3); + expect(await changes()).toEqual([[0, 1]]); + // Two taken back over a missed half hour: spread over both, each -1. + repo().stars = repo().stars!.filter((x) => x.login === 'cy'); + await tick(t0 + 3 * SLOT_MS); + expect(await changes()).toEqual([[0, 1], [SLOT_MS, -1], [2 * SLOT_MS, -1]]); + expect((await sync()).stars_total).toBe(1); + // GitHub refuses the count: said on the page, and downloads still record. + env.github.starCountForbidden = true; + asset('photocraft-0.11.1-windows-x64.msi').downloads += 7; + await tick(t0 + 4 * SLOT_MS); + expect(await sync()).toMatchObject({ stars_total: 1, stars_error: 'GitHub didn’t let the app read the star count.', last_slot_at: new Date(t0 + 4 * SLOT_MS), error: null }); + expect((await counts()).at(-1)).toMatchObject({ slot: t0 + 3 * SLOT_MS, n: 7 }); + const refused = (await page('/analytics?range=7d&metric=stars')).body; + expect(refused).toContain('Stars couldn’t be read'); + expect(refused).toContain('PhotoCraft: GitHub didn’t let the app read the star count.'); + expect((await page('/analytics?range=7d')).body).not.toContain('Stars couldn’t be read'); + env.github.starCountForbidden = false; + await tick(t0 + 5 * SLOT_MS); + expect((await sync()).stars_error).toBeNull(); // 30-minute rows older than 32 days are added up per UTC day. const old = Date.parse('2026-08-01T10:30:00Z'); const { rows } = await env.db.query('SELECT id FROM download_assets LIMIT 1'); @@ -149,7 +166,7 @@ describe('Analytics: recording downloads', () => { }); describe('Analytics: the page', () => { - async function recorded() { + async function recorded(): Promise { seed(); await post('/analytics/enabled', { enabled: '1' }); const t0 = slotOf(Date.now()) - 10 * SLOT_MS; @@ -158,6 +175,7 @@ describe('Analytics: the page', () => { asset('photocraft-0.11.1-macos-universal.dmg').downloads += 100; asset('photocraft-0.11.1-linux-x86_64.AppImage').downloads += 100; await tick(t0 + SLOT_MS); + return t0; } async function ticket(title: string) { const r = await acceptSubmission(env.deps, { @@ -222,14 +240,18 @@ describe('Analytics: the page', () => { expect(starsAll).toContain('data-an-hbar=\'{"items":[{"label":"PhotoCraft","value":2,'); }); - it('switches the main chart to stars: new stars over time, and each app’s total', async () => { - await recorded(); + it('switches the main chart to stars: stars gained over time, and each app’s total', async () => { + const t0 = await recorded(); + repo().stars!.push({ login: 'cy', at: new Date().toISOString() }); + await tick(t0 + 2 * SLOT_MS); const body = (await page('/analytics?range=7d&metric=stars')).body; expect(body).toMatch(/aria-label="Chart">Downloads<\/a>Stars<\/a>/); - expect(body).toContain('new stars · PhotoCraft'); - expect(body).toMatch(/data-an-chart='[^']*"name":"New stars"/); - // Total 2 (GitHub's count), 1 given in the last 7 days. - expect(body).toMatch(/Stars by app[\s\S]*?
  • PhotoCraft<\/span>2 \+1<\/span><\/span><\/li>/); + expect(body).toContain('stars gained · PhotoCraft'); + expect(body).toMatch(/data-an-chart='[^']*"name":"Stars gained"/); + expect(body).toContain('
    Stars
    +1
    '); + // Total 3 (GitHub's count), up 1 in the last 7 days. + expect(body).toMatch(/Stars by app[\s\S]*?
  • PhotoCraft<\/span>3 \+1<\/span><\/span><\/li>/); + expect(body).not.toContain('Stars couldn’t be read'); // The download breakdowns aren't shown; the app picker keeps the stars view. expect(body).not.toContain('id="an-pl-h"'); expect(body).toContain(''); diff --git a/test/fakes.ts b/test/fakes.ts index 7f7925c..8ab07ab 100644 --- a/test/fakes.ts +++ b/test/fakes.ts @@ -27,7 +27,7 @@ export interface FakeRepo { branchCommits?: { sha: string; message: string; user?: string | null; date: string; parents?: number }[]; /** The app icon (a PNG under assets/app-icon/…), for Repo status. */ icon?: Buffer; - /** Who starred it and when (Analytics). */ + /** Who starred it (Analytics reads only the count: GitHub won't list them for the app). */ stars?: { login: string; at: string }[]; } @@ -89,6 +89,8 @@ export class FakeGitHub { graphqlCalls = 0; graphqlBudget = 4800; graphqlLimited = false; + /** GitHub refuses the star count (answers with the repository nulled and a FORBIDDEN error, as it does for fields the app may not read). */ + starCountForbidden = false; appSlug = 'ticket-relay'; addInstallation(id: number, login: string, repos: Partial[], type = 'Organization') { @@ -157,11 +159,7 @@ export class FakeGitHub { number: i.number, title: i.title, url: `https://github.com/${r.owner}/${r.name}/issues/${i.number}`, createdAt: i.created_at, updatedAt: i.updated_at ?? i.created_at, authorAssociation: i.association ?? 'NONE', comments: { totalCount: i.comments?.length ?? 0 }, reactions: { totalCount: i.reactions ?? 0 }, labels: { nodes: i.labels.map((name) => ({ name })) }, }); - if (query.includes('stargazers(')) { - const list = [...(r.stars ?? [])].sort((a, b) => at(b.at) - at(a.at)); - const p = page(list, v.after, 100); - return { repository: { stargazerCount: list.length, stargazers: { pageInfo: p.pageInfo, edges: p.nodes.map((x) => ({ starredAt: x.at, node: { login: x.login } })) } } }; - } + if (query.includes('stargazerCount') && !query.includes('openPrs')) return { repository: { stargazerCount: (r.stars ?? []).length } }; if (query.includes('releases(')) { const p = page(newestFirst(r.releases ?? [], (x) => x.published_at), v.after, 50); return { repository: { releases: { pageInfo: p.pageInfo, nodes: p.nodes.map((x) => ({ @@ -285,6 +283,10 @@ export class FakeGitHub { if (path === '/graphql' && method === 'POST') { this.graphqlCalls++; if (this.graphqlLimited) return json(200, { errors: [{ type: 'RATE_LIMITED', message: 'API rate limit exceeded for installation.' }] }); + // Who starred is more than the app may read; GitHub answers with data and errors together. + if (String(body.query).includes('stargazers(') || (this.starCountForbidden && String(body.query).includes('stargazerCount'))) { + return json(200, { data: { repository: null }, errors: [{ type: 'FORBIDDEN', path: ['repository', 'stargazers'], message: 'Resource not accessible by integration' }] }); + } return json(200, { data: this.graphqlData(String(body.query), body.variables ?? {}, accessible) }); } if ((m = /^\/repos\/([^/]+)\/([^/]+)\/contributors$/.exec(path)) && method === 'GET') { diff --git a/test/helpers.ts b/test/helpers.ts index 7ca8f0e..20bf5cd 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -53,7 +53,7 @@ export function testDb(): Db { export async function resetDb(db: Db = testDb()): Promise { db.exec('DELETE FROM sessions; DELETE FROM oauth_states; DELETE FROM workspaces; DELETE FROM users; DELETE FROM issue_index; DELETE FROM issue_index_repos; DELETE FROM process_status;'); - db.exec('DELETE FROM pull_index; DELETE FROM repo_status; DELETE FROM download_counts; DELETE FROM download_days; DELETE FROM download_assets; DELETE FROM download_sync; DELETE FROM repo_stars; DELETE FROM repo_star_counts;'); + db.exec('DELETE FROM pull_index; DELETE FROM repo_status; DELETE FROM download_counts; DELETE FROM download_days; DELETE FROM download_assets; DELETE FROM download_sync; DELETE FROM repo_star_changes;'); db.exec('UPDATE server_settings SET dev_mode_on_at = NULL, dev_mode_by = NULL, dev_mode_off_at = NULL;'); }