From 0318ccb6858f06b4898a04b962f7413e4bce9d9f Mon Sep 17 00:00:00 2001 From: Michael Hall Date: Thu, 13 Aug 2026 09:56:37 +1000 Subject: [PATCH] feat: add an opt-in Galaxy CoDex Provider for tool-execution usage (#79) Galaxy is the first optional Provider, disabled by default and enabled via --enable-provider/a Manifest's enable_providers: it matches a repo's GitHub URL against Galaxy CoDex's tools.json to report cumulative runs, a max unique-user-account figure, and public-instance availability under a new Usage Category, aggregating correctly across a tool's several Galaxy wrappers. Adds ADR-0011 recording why CoDex was chosen over the live Galaxy Europe dashboard and ToolShed downloads, and a user guide. --- CONTEXT.md | 8 +- ...erational-notes-are-not-licence-notices.md | 2 +- ...ers-and-galaxy-codex-as-source-of-truth.md | 37 ++ docs/site/src/SUMMARY.md | 2 + ...ers-and-galaxy-codex-as-source-of-truth.md | 1 + docs/site/src/guides/galaxy-usage.md | 114 ++++ docs/site/src/reference/cli.md | 7 +- docs/site/src/reference/providers.md | 1 + src/cli.rs | 184 +++++- src/manifest.rs | 50 +- src/model.rs | 39 +- src/providers/galaxy.rs | 550 ++++++++++++++++++ src/providers/mod.rs | 165 ++++-- src/report.rs | 6 +- tests/cassettes/galaxy_codex_tools.json | 74 +++ tests/galaxy.rs | 200 +++++++ 16 files changed, 1376 insertions(+), 64 deletions(-) create mode 100644 docs/adr/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md create mode 100644 docs/site/src/design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md create mode 100644 docs/site/src/guides/galaxy-usage.md create mode 100644 src/providers/galaxy.rs create mode 100644 tests/cassettes/galaxy_codex_tools.json create mode 100644 tests/galaxy.rs diff --git a/CONTEXT.md b/CONTEXT.md index 12159b3..e3e285f 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -23,7 +23,7 @@ The span of time a Metric's value covers. Either **cumulative** (all-time, e.g. _Avoid_: Period, timeframe, range **Manifest**: -An optional file listing one or more Projects, their Identities, and any chosen or prioritised Cohort topics for repeatable or batch runs. Never required: a single Project can be given inline via CLI flags, and a bare paper (DOI/PMID) needs neither. The tool can generate a Manifest from a run, so it is a save-file, not a hand-authored prerequisite. Holds no secrets. +An optional file listing one or more Projects, their Identities, any chosen or prioritised Cohort topics, and optional Providers to enable for repeatable or batch runs. Never required: a single Project can be given inline via CLI flags, and a bare paper (DOI/PMID) needs neither. The tool can generate a Manifest from a run, so it is a save-file, not a hand-authored prerequisite. Holds no secrets. _Avoid_: Config, spec, input file **Snapshot**: @@ -39,7 +39,7 @@ A Provider's licence or terms text, recorded on the Metric it accompanies and sh _Avoid_: Disclaimer, licence blurb, footnote, attribution **Provider Note**: -An operational explanation carried by a Provider×Identity Outcome — why a fetch yielded no value, failed, or returned only part of the requested data ("no API key configured", "rate limited after five of twenty Cohort ranks"). Not a Notice: it describes collection status rather than the terms behind a Metric, so it appears in its own Report section keyed by Provider and Outcome kind (ADR-0008). +An explanation carried by a Provider×Identity Outcome that doesn't belong on any single Metric: why a fetch yielded no value, failed, or returned only part of the requested data ("no API key configured", "rate limited after five of twenty Cohort ranks"), or — for a fully successful fetch — provenance detail about how several inputs were aggregated into the reported Metrics ("matched 23 Galaxy CoDex suites: ..."). Not a Notice: it describes collection status or provenance rather than the terms behind a Metric, so it appears in its own Report section keyed by Provider and Outcome kind (ADR-0008). _Avoid_: Error message, warning, notice, detail **Cohort**: @@ -51,11 +51,11 @@ A derived Metric produced by combining compatible Metrics — e.g. a total downl _Avoid_: Total, sum, aggregate **Category**: -The family a Metric belongs to, used to group the Report. Four in v1: **Code** (stars, forks, contributors, release downloads, cohort rank…), **Downloads** (per-channel package/install counts + Rollup), **Citations** (counts + field-normalized FWCI/percentile/FCR/RCR), and **Attention** (open-access status, Wikipedia mentions, and indexed scholarly repository mentions keyless by default; full news/blog/policy/patent/social breakdown via Altmetric when a key is present). +The family a Metric belongs to, used to group the Report. Five: **Code** (stars, forks, contributors, release downloads, Cohort rank…), **Downloads** (per-channel package/install counts + Rollup), **Usage** (tool executions, server-scoped user accounts, and public-instance availability), **Citations** (counts + field-normalized FWCI/percentile/FCR/RCR), and **Attention** (open-access status, Wikipedia mentions, and indexed scholarly repository mentions keyless by default; full news/blog/policy/patent/social breakdown via Altmetric when a key is present). _Avoid_: Kind, group, type, section **Provider**: -A component for one source that, given an Identity, fetches zero or more Metrics from one external service (GitHub, Bioconda, OpenAlex, …). Providers are pluggable; the system ships a curated default set. +A component for one source that, given an Identity, fetches zero or more Metrics from one external service (GitHub, Bioconda, OpenAlex, …). Providers are pluggable; the system ships a curated default set and may offer others that a user explicitly enables. _Avoid_: Source, backend, connector, adapter **Identity**: diff --git a/docs/adr/0008-operational-notes-are-not-licence-notices.md b/docs/adr/0008-operational-notes-are-not-licence-notices.md index 18236d1..1cbea3c 100644 --- a/docs/adr/0008-operational-notes-are-not-licence-notices.md +++ b/docs/adr/0008-operational-notes-are-not-licence-notices.md @@ -2,7 +2,7 @@ ## Status -accepted — the prose carve-out in Considered options is refined by ADR-0009: what travels into prose is any `Metric.note` attached to a headline number, not only a licence notice. Extended during #83 so a successful `Values` Outcome may also carry Provider Notes when requested secondary Metrics were only partly collected; operational messages still stay out of prose. +accepted — the prose carve-out in Considered options is refined by ADR-0009: what travels into prose is any `Metric.note` attached to a headline number, not only a licence notice. Extended during #83 so a successful `Values` Outcome may also carry Provider Notes when requested secondary Metrics were only partly collected; operational messages still stay out of prose. Extended again during #79 (ADR-0011) so a fully successful `Values` Outcome may also carry a Provider Note recording audit/provenance detail — which CoDex suites a multi-suite aggregation matched — that belongs to the whole fetch rather than any single Metric; this is a third, distinct reason a Provider Note exists (why nothing was collected, why collection was partial, or what a successful aggregation actually drew from), not a widening of "operational." ## Context and decision diff --git a/docs/adr/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md b/docs/adr/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md new file mode 100644 index 0000000..12de682 --- /dev/null +++ b/docs/adr/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md @@ -0,0 +1,37 @@ +# Optional Providers, and Galaxy CoDex over live per-tool dashboards + +## Status + +accepted + +## Context and decision + +Issue #79 asked for Galaxy usage — tool executions, unique-user accounts, and public-instance availability. The v1 spec already anticipated this shape (`docs/spec/0001-boast-v1.md`: "further Providers are optional and enabled via Manifest/flags"), but no non-default registry existed yet: `providers/mod.rs`'s `render_providers` DEFAULT column read "yes" throughout "for want of a contrast" (ADR-0009), and ADR-0009 itself considered making Docker Hub opt-in and rejected it only "for now", explicitly flagging "revisit if an opt-in tier is built for other reasons." Galaxy is that reason: most Projects have no Galaxy wrapper at all, so fetching it by default would add a mostly-empty request to every run rather than a useful one, in a way Docker Hub and Quay (most bioinformatics tools *do* have a container) do not share. + +Two decisions follow from that, both settled in the issue's own long triage thread before any code was written. + +**1. Providers can now be optional, disabled by default.** `providers::optional_providers()` is a second registry, disjoint from `default_providers()`; a user opts a Provider in with `--enable-provider ` (repeatable, unknown name is a CLI usage error) or a Manifest's `enable_providers` list. `boast providers` renders both registries in one table, default rows marked "yes", optional rows "no" — the exact contrast ADR-0009 was waiting for. An explicit CLI `--enable-provider` overrides a Project's Manifest selection entirely (never merges), the same override rule `--topic` already applies to Cohort selection, so the two stay consistent for a reader who already knows one of them. + +**2. Galaxy CoDex's `communities/all/resources/tools.json` is the source of truth — not the Galaxy Europe Grafana dashboard, and not ToolShed download counts.** Both alternatives were live options in the issue thread and both were ruled out on evidence, not preference: + +- The **Galaxy Europe Grafana dashboard** (`stats.galaxyproject.eu`) reports numbers roughly an order of magnitude higher than CoDex for the same tool (267 vs. 104 runs for rasusa) — "something is different about how the two collect stats," never fully diagnosed. It also only covers one server (`usegalaxy.eu`), not the cross-server picture the issue asked for, and it's a live query interface rather than a bulk-fetchable dataset. +- **ToolShed downloads** count wrapper-bundle fetches — an installation/update event, not a tool execution. It measures how many Galaxy admins installed a wrapper, not how many researchers ran it, which is the opposite of what "Galaxy usage" was asked to mean. + +CoDex republishes one JSON file cross-server, keyless, and reflects the recommended metric shape the issue settled on (execution counts and account counts, not installs). Its own known weakness — the published figures can lag the live servers by an unpublished amount — is disclosed on every Metric via a note long enough to reach the Notices footer (ADR-0005), rather than silently presented as current. + +A second wrinkle CoDex forces: one upstream tool can have several Galaxy wrappers, one per subcommand ("suites" in CoDex's vocabulary — vcflib alone maps to 23). The issue's own resolution: sum `runs` across every matched suite, but take the *maximum* `user_accounts` across them rather than summing, since the same account can run more than one subcommand and summing would inflate a "how many people" figure into "how many (person, subcommand) pairs." `public_instances` unions availability across the matched suites, naming which of the four major public servers (UseGalaxy.org, .org.au, .eu, .fr) matched. Every matched suite ID is recorded in a Provider Note so the aggregation is auditable, and every repository CoDex's `Homepage` field doesn't exactly match is `NotApplicable`, never a real zero (ADR-0002) — `Homepage` is deliberately the only field compared; CoDex's `Suite source` names the wrapper repository (typically under `galaxyproject/tools-iuc`), not the upstream Project being measured, and using it would misattribute one repo's Galaxy usage to a completely different upstream. + +## Considered options + +- **Keep every Provider in one always-fetched registry, and make Galaxy request-cheap enough not to matter.** No new architecture. Rejected: the cost isn't request count, it's relevance — a `NotApplicable` on every run for the ~99% of Projects with no Galaxy wrapper is noise in every default Report, not a performance question a cheaper request would fix. +- **Query the Galaxy Europe Grafana dashboard instead of CoDex, since it's the most current data.** Rejected on the evidence above: an unexplained order-of-magnitude discrepancy against CoDex, single-server-only coverage, and no bulk endpoint — a live dashboard built for humans clicking through a UI, not a source `boast about` can fetch once and record provenance for. +- **Sum `user_accounts` across every matched suite, matching how `runs` aggregates.** Simpler, one code path for both figures. Rejected: the issue's own domain expert flagged this would double-count one account using several subcommands of the same underlying tool — the max is the honest "at least this many distinct accounts" figure; the note says so explicitly rather than letting the number imply more precision than it has. +- **Treat `Suite source` (the wrapper repo) as an acceptable secondary match when `Homepage` is absent.** Would raise the match rate. Rejected: it would attribute usage to whichever team happens to maintain the Galaxy wrapper (often `galaxyproject/tools-iuc`, a shared multi-tool repo) rather than the upstream Project actually being measured — a wrong answer is worse than `NotApplicable` here (ADR-0002). + +## Consequences + +- **`providers::optional_providers()` and `resolve_optional_providers()` are the durable extension point for every future non-default Provider**, not a Galaxy-specific mechanism — the next opt-in Provider (Altmetric already asks for a key, but stays default/keyless-degraded rather than opt-in; a genuinely optional source like a paid API tier would fit this registry instead) adds one entry to `optional_providers()` and is done. +- **`enable_providers` joins `topics`/`priority_topics` as a Manifest field with the same override shape**: CLI-given always replaces a Project's Manifest value, never merges with it. A reader who understands one already understands the other. +- **A Category gained a fifth member, Usage**, sitting between Downloads and Citations in every Report format and `boast providers`' grouping — `CATEGORY_ORDER` is the one place this ordering is declared, shared by `report.rs` and `diff.rs`. The Snapshot schema version advanced (2 → 3) for the new Category, though nothing about deserialising an older Snapshot changes: it simply never contained a `"usage"`-tagged row. +- **Galaxy's `runs` and `user_accounts` — the two cumulative counts CoDex's own snapshot can go stale on — each carry the lag caveat on the Metric itself, not just a one-time warning**, because Snapshots are re-rendered offline later (ADR-0001) with no re-fetch — the same reasoning ADR-0005 already established for Provider licence notices applies to a data-freshness caveat just as much as a legal one. `public_instances` doesn't carry it: installation is a current-state fact CoDex derives the same way regardless of refresh timing, not a count that accumulates staleness. +- **A future Provider facing the same "several wrappers, one upstream" shape has a worked precedent**: sum what genuinely aggregates (executions), take the maximum of what would double-count under naive summation (accounts), and say which rule applied to which number in the Metric's own note rather than leaving a reader to guess. diff --git a/docs/site/src/SUMMARY.md b/docs/site/src/SUMMARY.md index 5406fc3..06fb079 100644 --- a/docs/site/src/SUMMARY.md +++ b/docs/site/src/SUMMARY.md @@ -9,6 +9,7 @@ - [A tool with a repo and packages](./guides/repo-and-packages.md) - [A researcher's whole publication record](./guides/orcid.md) - [Automating snapshots in CI](./guides/ci-snapshots.md) + - [Galaxy tool-execution usage](./guides/galaxy-usage.md) - [Providers reference](./reference/providers.md) - [CLI reference](./reference/cli.md) - [Design decisions](./design/index.md) @@ -22,3 +23,4 @@ - [0008 — Operational Provider notes are not licence notices](./design/0008-operational-notes-are-not-licence-notices.md) - [0009 — Container pulls roll up, with the caveat travelling](./design/0009-container-pulls-roll-up-with-a-travelling-caveat.md) - [0010 — An unreadable channel is NotApplicable, not Failed](./design/0010-unreadable-is-not-unretrieved.md) + - [0011 — Optional Providers, and Galaxy CoDex over live dashboards](./design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md) diff --git a/docs/site/src/design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md b/docs/site/src/design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md new file mode 100644 index 0000000..ebf356e --- /dev/null +++ b/docs/site/src/design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md @@ -0,0 +1 @@ +{{#include ../../../adr/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md}} diff --git a/docs/site/src/guides/galaxy-usage.md b/docs/site/src/guides/galaxy-usage.md new file mode 100644 index 0000000..0f5fa5f --- /dev/null +++ b/docs/site/src/guides/galaxy-usage.md @@ -0,0 +1,114 @@ +# Galaxy tool-execution usage + +[Galaxy](https://galaxyproject.org/) is a web platform for running bioinformatics tools +without writing code. Many command-line tools also ship as a Galaxy wrapper, and the +[Galaxy Tool CoDex](https://github.com/galaxyproject/galaxy_codex) project publishes +cross-server execution and user-account totals for every wrapper it knows about — real +evidence of use beyond stars and downloads, if your tool has one. + +Galaxy is **optional and off by default**. Most Projects have no Galaxy wrapper at all, +so fetching it on every run would add a mostly-empty request rather than a useful one. +Check `boast providers` to see it listed under Usage with `DEFAULT` set to `no`. + +## Enabling it + +``` +boast about --repo mbhall88/rasusa --enable-provider galaxy +``` + +`--enable-provider` is repeatable and generic — it isn't Galaxy-specific — so a future +optional Provider uses the same flag. An unknown name is a usage error: + +``` +$ boast about --repo owner/name --enable-provider not-a-real-provider +error: unknown optional provider 'not-a-real-provider' (available: galaxy) +``` + +Galaxy only understands repository Identities (`--repo`, a GitHub URL, or the bare +`owner/name` positional); it has no package- or paper-level presence to report on. + +## What each Metric means + +``` +━━ github:mbhall88/rasusa ━━ +── Usage ── + runs 104 all-time galaxy + user_accounts 24 all-time galaxy + public_instances 2 all-time galaxy available on UseGalaxy.eu, UseGalaxy.fr + +── Notices ── + Galaxy CoDex republishes cumulative tool-execution counts on its own refresh schedule, so this figure may lag the underlying Galaxy servers + Runs: aggregated sum. Users: max unique per wrapper (to prevent over-counting) — not a count of distinct people, since CoDex's per-server totals can count one account once per server. Both are cumulative CoDex figures that may lag the underlying Galaxy servers. +``` + +`runs` and `user_accounts` each carry a caveat long enough to be shown once in the +Notices footer rather than repeated inline on every row — see +[Concepts](../concepts.md) for how boast decides between the two. + +- **`runs`** — cumulative tool executions across every Galaxy wrapper CoDex has matched + to this repository, summed across CoDex's tracked servers. +- **`user_accounts`** — the *maximum* per-wrapper account count, not a sum (see below). + This is not a count of distinct people: CoDex's own figures can count one account + separately per server, so treat it as "at least this many accounts," never as a + headcount. +- **`public_instances`** — how many of the four major public Galaxy servers + (UseGalaxy.org, UseGalaxy.org.au, UseGalaxy.eu, UseGalaxy.fr) have the tool installed, + regardless of whether it's actually been run there. The Metric's note names which ones + matched. + +A repository with no matching CoDex entry is `NotApplicable`, never a real zero — most +repositories simply have no Galaxy wrapper. + +## Multi-suite aggregation + +One upstream tool can have several Galaxy wrappers, one per subcommand — CoDex calls +each a "suite." `vcflib` alone maps to 23. When more than one suite matches a +repository: + +- **`runs` is summed** across every matched suite — it's a genuine execution count, and + summing doesn't over-count anything. +- **`user_accounts` is *not* summed** — the maximum across the matched suites is used + instead, since the same account can run more than one subcommand of the same tool. + Summing would inflate "how many accounts used this tool" into "how many + (account, subcommand) pairs were used." +- **`public_instances` is a union** — available if *any* matched suite is installed + there. + +Every matched suite ID is recorded in a Provider Note so the aggregation is auditable: + +``` +── Provider Notes ── + galaxy: Matched 23 Galaxy CoDex suites: vcf2tsv, vcfaddinfo, vcfallelicprimitives, ... — github:vcflib/vcflib +``` + +Matching is exact, on CoDex's `Homepage` field only (normalised the same way boast +normalises any GitHub URL) — never on CoDex's `Suite source`, which names the wrapper +repository (typically a shared multi-tool repo like `galaxyproject/tools-iuc`), not the +upstream Project actually being measured. + +## Why the numbers may lag + +CoDex republishes its dataset on its own refresh schedule, independent of the live +Galaxy servers — `runs` and `user_accounts` both carry a note saying so, since they're +cumulative counts CoDex derives from its own snapshot. Treat these figures as "at least +this much use, as of whenever CoDex last refreshed," not a live server query. +`public_instances` doesn't carry the same caveat: installation is a current-state fact, +not a count that accumulates staleness the same way. See +[ADR-0011](../design/0011-optional-providers-and-galaxy-codex-as-source-of-truth.md) for +why CoDex was chosen over the live Galaxy Europe dashboard and ToolShed's install counts. + +## Persisting the choice in a Manifest + +`--save`/`boast init` persist an explicit `--enable-provider` into the Manifest's +`enable_providers`, so a scheduled run doesn't need to repeat the flag: + +```toml +[[project]] +identities = ["github:mbhall88/rasusa"] +enable_providers = ["galaxy"] +``` + +`boast about manifest.toml` then fetches Galaxy for that Project automatically. An +explicit `--enable-provider` on the command line overrides a Manifest's own selection +entirely for that run, the same override rule `--topic` already applies to Cohort +selection. diff --git a/docs/site/src/reference/cli.md b/docs/site/src/reference/cli.md index ec412ee..91a3fe4 100644 --- a/docs/site/src/reference/cli.md +++ b/docs/site/src/reference/cli.md @@ -62,6 +62,8 @@ Options: Print the report but do not write a Snapshot file -s, --save After fetching, also write a Manifest reflecting the identities and Cohort selection used in this run, so a future run can `boast about ` instead of re-typing them. Not available when the input is itself a Manifest — use `boast init` to build one up front instead + -e, --enable-provider + Enable an optional Provider by name (repeatable), e.g. `galaxy`. Off by default (see `boast providers`' DEFAULT column) — an unknown name is a usage error. Overrides, rather than adds to, a Manifest input's own `enable_providers` for every Project it runs -j, --threads Maximum number of distinct hosts fetched from concurrently. Never more than one request is in flight against the *same* host no matter how high this is set (ADR-0007). Raising it past the number of hosts a Project actually touches (at most the Provider registry's size, ~13 by default) buys nothing; lower it to open fewer simultaneous connections [default: 8] -h, --help @@ -145,10 +147,11 @@ Options: -f, --from-file Read identifiers from a file (one per line; `#` comments and blank lines ignored). Use `-` for stdin. Repeatable -t, --topic Exact GitHub Cohorts to record in the Manifest, in argument order --priority-topic Declared GitHub Cohorts to prioritise in the Manifest, in argument order - -o, --output Where to write the Manifest [default: manifest.toml] + -e, --enable-provider Optional Providers to record in the Manifest's `enable_providers` (repeatable), e.g. `galaxy`. An unknown name is a usage error -v, --verbose... Increase logging verbosity (-v info, -vv debug, -vvv trace) - -O, --orcid Expand a researcher's ORCID iD (bare, `orcid:`-prefixed, or an orcid.org URL) into a Manifest of every work with a DOI or PMID, one Project per work (ADR-0006; repeatable). **Performs a network fetch** — unlike the rest of `init`, which is otherwise offline. Exclusive with positionals/`--repo`/`--package`/`--from-file`: an ORCID expansion has no defensible answer to "which of these works does that repo belong to?" + -o, --output Where to write the Manifest [default: manifest.toml] -q, --quiet Silence all logging except errors + -O, --orcid Expand a researcher's ORCID iD (bare, `orcid:`-prefixed, or an orcid.org URL) into a Manifest of every work with a DOI or PMID, one Project per work (ADR-0006; repeatable). **Performs a network fetch** — unlike the rest of `init`, which is otherwise offline. Exclusive with positionals/`--repo`/`--package`/`--from-file`: an ORCID expansion has no defensible answer to "which of these works does that repo belong to?" -u, --include-unidentified With `--orcid`, also list works with neither a DOI nor a PMID (and so were skipped) as commented-out `[[project]]` blocks you can fill in by hand. Off by default: most ORCID records carry many such works -h, --help Print help ``` diff --git a/docs/site/src/reference/providers.md b/docs/site/src/reference/providers.md index cf0e1a3..ec218f7 100644 --- a/docs/site/src/reference/providers.md +++ b/docs/site/src/reference/providers.md @@ -19,6 +19,7 @@ pypi Downloads yes none homebrew Downloads yes none dockerhub Downloads yes none quay Downloads yes none +galaxy Usage no none openalex Citations yes none crossref Citations yes none dimensions Citations yes none diff --git a/src/cli.rs b/src/cli.rs index 56f4f77..32dbc44 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -16,9 +16,11 @@ use crate::model::{ }; use crate::orchestrator; use crate::orcid::{self, OrcidWork}; +use crate::provider::Provider; use crate::providers::github::GitHub; use crate::providers::{ - default_providers, default_providers_with_github, paper_provider_count, render_providers, + default_providers, default_providers_with_github, optional_providers, paper_provider_count, + render_providers, resolve_optional_providers, }; use crate::report::{render_markdown, render_prose, render_terminal}; use crate::transport::{RetryingTransport, Transport, UreqTransport}; @@ -189,6 +191,13 @@ pub struct AboutArgs { #[arg(short = 's', long = "save", value_name = "FILE")] pub save: Option, + /// Enable an optional Provider by name (repeatable), e.g. `galaxy`. Off + /// by default (see `boast providers`' DEFAULT column) — an unknown name + /// is a usage error. Overrides, rather than adds to, a Manifest input's + /// own `enable_providers` for every Project it runs. + #[arg(short = 'e', long = "enable-provider", value_name = "NAME")] + pub enable_providers: Vec, + /// Maximum number of distinct hosts fetched from concurrently. Never /// more than one request is in flight against the *same* host no matter /// how high this is set (ADR-0007). Raising it past the number @@ -235,6 +244,35 @@ fn parse_positive_duration(value: &str) -> Result { Ok(Duration::from_secs(seconds)) } +/// Resolve `--enable-provider`/Manifest `enable_providers` names into +/// concrete optional Providers, or log and return the usage-error exit code +/// (2) on an unknown name — shared by every entry point that accepts +/// `enable_providers`, so the same names are validated the same way whether +/// they came from the CLI or a Manifest. +fn resolve_enabled_providers(names: &[String]) -> Result>, i32> { + resolve_optional_providers(names).map_err(|e| { + tracing::error!("{e}"); + 2 + }) +} + +/// Build the full Provider registry for one fetch: the default set (with the +/// given GitHub Cohort selection) plus whichever optional Providers +/// `enable_providers` names. Shared by `run_about` and `run_about_manifest` +/// so the CLI-enable/Manifest-enable path is one real piece of code — not +/// duplicated per call site, and directly unit-testable without a network +/// transport (unlike `run_about`/`run_about_manifest` themselves, which +/// always build a real `runtime_transport()`). +fn build_providers( + selection: CohortSelection, + wait_limit: Option, + enable_providers: &[String], +) -> Result>, i32> { + let mut providers = default_providers_with_github(selection, wait_limit); + providers.extend(resolve_enabled_providers(enable_providers)?); + Ok(providers) +} + fn cohort_selection(topics: &[String], priority_topics: &[String]) -> CohortSelection { if !topics.is_empty() { CohortSelection::Exact(topics.to_vec()) @@ -267,6 +305,11 @@ pub struct InitArgs { )] pub priority_topic: Vec, + /// Optional Providers to record in the Manifest's `enable_providers` + /// (repeatable), e.g. `galaxy`. An unknown name is a usage error. + #[arg(short = 'e', long = "enable-provider", value_name = "NAME")] + pub enable_providers: Vec, + /// Where to write the Manifest. #[arg( short = 'o', @@ -426,7 +469,14 @@ fn run_about(args: AboutArgs) -> i32 { if let Err(code) = validate_cohort_selection(&project, &selection, &transport) { return code; } - let providers = default_providers_with_github(selection.clone(), args.wait_for_cohort_ranks); + let providers = match build_providers( + selection.clone(), + args.wait_for_cohort_ranks, + &args.enable_providers, + ) { + Ok(p) => p, + Err(code) => return code, + }; let snapshot = orchestrator::run_with_concurrency(&project, &providers, &transport, args.threads); @@ -436,7 +486,12 @@ fn run_about(args: AboutArgs) -> i32 { } if let Some(save_path) = &args.save { - if let Err(code) = save_manifest(&project.identities, selection, save_path) { + if let Err(code) = save_manifest( + &project.identities, + selection, + &args.enable_providers, + save_path, + ) { return code; } } @@ -507,7 +562,18 @@ fn run_about_manifest(path: &std::path::Path, args: &AboutArgs) -> i32 { if let Err(code) = validate_cohort_selection(&project, &selection, &transport) { return code; } - let providers = default_providers_with_github(selection, args.wait_for_cohort_ranks); + // An explicit `--enable-provider` overrides every Project's own + // Manifest selection entirely, the same override rule `--topic` + // already applies just above. + let enable_names = if !args.enable_providers.is_empty() { + &args.enable_providers + } else { + &entry.enable_providers + }; + let providers = match build_providers(selection, args.wait_for_cohort_ranks, enable_names) { + Ok(p) => p, + Err(code) => return code, + }; let snapshot = orchestrator::run_with_concurrency(&project, &providers, &transport, args.threads); @@ -648,9 +714,11 @@ fn warn_if_missing_github_token(identities: &[Identity]) { fn save_manifest( identities: &[Identity], selection: CohortSelection, + enable_providers: &[String], path: &std::path::Path, ) -> Result<(), i32> { - let manifest = Manifest::from_identities_with_selection(identities, selection); + let manifest = + Manifest::from_identities_with_selection(identities, selection, enable_providers); let toml_str = manifest.to_toml_string().map_err(|e| { tracing::error!("could not serialise manifest: {e}"); 2 @@ -683,9 +751,14 @@ fn run_init(args: InitArgs) -> i32 { return 2; } + if let Err(code) = resolve_enabled_providers(&args.enable_providers) { + return code; + } + match save_manifest( &identities, cohort_selection(&args.topic, &args.priority_topic), + &args.enable_providers, &args.output, ) { Ok(()) => 0, @@ -721,6 +794,10 @@ fn run_init_orcid(args: &InitArgs) -> i32 { } } + if let Err(code) = resolve_enabled_providers(&args.enable_providers) { + return code; + } + let transport = RetryingTransport::new(UreqTransport::new()); let provider_count = paper_provider_count(); @@ -774,6 +851,7 @@ fn run_init_orcid(args: &InitArgs) -> i32 { let manifest = Manifest::from_orcid_works_with_selection( &identified, cohort_selection(&args.topic, &args.priority_topic), + &args.enable_providers, ); let toml_str = match manifest.to_toml_string() { Ok(s) => s, @@ -870,13 +948,14 @@ fn run_diff(args: DiffArgs) -> i32 { /// List the registered Providers. Never touches the network — the registry /// itself, not any live data, is what's being reported on. fn run_providers() -> i32 { - let providers = default_providers(); print!( "{}", - render_providers(&providers, |env_var| std::env::var(env_var) - .ok() - .filter(|s| !s.is_empty()) - .is_some()) + render_providers(&default_providers(), &optional_providers(), |env_var| { + std::env::var(env_var) + .ok() + .filter(|s| !s.is_empty()) + .is_some() + }) ); 0 } @@ -1416,4 +1495,89 @@ pmid:31234567 )); assert_eq!(run_about(a), 2); } + + #[test] + fn enable_provider_flag_accepts_short_and_long_form_and_is_repeatable() { + let cli = Cli::try_parse_from(norm(&[ + "boast", + "owner/repo", + "-e", + "galaxy", + "--enable-provider", + "galaxy", + ])) + .unwrap(); + let Command::About(a) = cli.command else { + panic!("expected About") + }; + assert_eq!(a.enable_providers, vec!["galaxy", "galaxy"]); + + let cli = Cli::try_parse_from(norm(&["boast", "init", "10.1/x", "-e", "galaxy"])).unwrap(); + let Command::Init(i) = cli.command else { + panic!("expected Init") + }; + assert_eq!(i.enable_providers, vec!["galaxy"]); + } + + #[test] + fn an_unknown_enable_provider_name_is_a_usage_error() { + let cli = Cli::try_parse_from(norm(&[ + "boast", + "owner/repo", + "--enable-provider", + "not-a-real-provider", + ])) + .unwrap(); + let Command::About(a) = cli.command else { + panic!("expected About") + }; + // No network call happens before this validation runs, so this is + // safe to call directly (same pattern as + // `about_save_combined_with_a_manifest_input_is_rejected` above). + assert_eq!(run_about(a), 2); + } + + #[test] + fn init_rejects_an_unknown_enable_provider_name() { + let cli = Cli::try_parse_from(norm(&[ + "boast", + "init", + "10.1/x", + "--enable-provider", + "not-a-real-provider", + ])) + .unwrap(); + let Command::Init(i) = cli.command else { + panic!("expected Init") + }; + assert_eq!(run_init(i), 2); + } + + /// `build_providers` is the one real function both `run_about` and + /// `run_about_manifest` call to turn `enable_providers` into a fetched + /// Provider — so this is the CLI-enable *and* Manifest-enable path + /// itself, not a proxy for it, exercised without any network transport. + #[test] + fn build_providers_enables_galaxy_only_when_named() { + let without = build_providers(CohortSelection::Declared, None, &[]).unwrap(); + assert!(!without.iter().any(|p| p.name() == "galaxy")); + + let with = + build_providers(CohortSelection::Declared, None, &["galaxy".to_string()]).unwrap(); + assert!(with.iter().any(|p| p.name() == "galaxy")); + // The default registry is still present alongside it. + assert!(with.iter().any(|p| p.name() == "github")); + } + + #[test] + fn build_providers_rejects_an_unknown_enable_provider_name() { + assert!(matches!( + build_providers( + CohortSelection::Declared, + None, + &["not-a-real-provider".to_string()] + ), + Err(2) + )); + } } diff --git a/src/manifest.rs b/src/manifest.rs index 924c30c..b298ef9 100644 --- a/src/manifest.rs +++ b/src/manifest.rs @@ -38,6 +38,13 @@ pub struct ManifestProject { /// Declared Cohorts to attempt first, in order, before the remainder. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub priority_topics: Vec, + /// Optional Providers to fetch for this Project, by name (e.g. + /// `"galaxy"`), on top of the default registry (issue #79). An explicit + /// `--enable-provider` on the command line overrides this list entirely + /// rather than adding to it, the same override rule `about`'s `--topic` + /// already applies to a Project's declared Cohort selection. + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub enable_providers: Vec, } #[derive(Debug, thiserror::Error)] @@ -89,12 +96,13 @@ impl Manifest { let selection = topic .map(|topic| CohortSelection::Exact(vec![topic.to_string()])) .unwrap_or(CohortSelection::Declared); - Self::from_identities_with_selection(identities, selection) + Self::from_identities_with_selection(identities, selection, &[]) } pub fn from_identities_with_selection( identities: &[Identity], selection: CohortSelection, + enable_providers: &[String], ) -> Manifest { let (topics, priority_topics) = selection_fields(selection); Manifest { @@ -103,6 +111,7 @@ impl Manifest { topic: None, topics, priority_topics, + enable_providers: enable_providers.to_vec(), }], } } @@ -114,12 +123,13 @@ impl Manifest { let selection = topic .map(|topic| CohortSelection::Exact(vec![topic.to_string()])) .unwrap_or(CohortSelection::Declared); - Self::from_orcid_works_with_selection(works, selection) + Self::from_orcid_works_with_selection(works, selection, &[]) } pub fn from_orcid_works_with_selection( works: &[PaperId], selection: CohortSelection, + enable_providers: &[String], ) -> Manifest { let (topics, priority_topics) = selection_fields(selection); Manifest { @@ -130,6 +140,7 @@ impl Manifest { topic: None, topics: topics.clone(), priority_topics: priority_topics.clone(), + enable_providers: enable_providers.to_vec(), }) .collect(), } @@ -319,6 +330,40 @@ mod tests { assert!(!toml_str.contains("topic")); } + #[test] + fn enable_providers_round_trips_through_toml_and_is_omitted_when_empty() { + let identities = vec![Identity::parse("github:owner/repo").unwrap()]; + let manifest = Manifest::from_identities_with_selection( + &identities, + CohortSelection::Declared, + &["galaxy".to_string()], + ); + let toml_str = manifest.to_toml_string().unwrap(); + assert!(toml_str.contains("enable_providers")); + + let parsed = Manifest::parse(&toml_str).unwrap(); + assert_eq!(parsed, manifest); + assert_eq!(parsed.projects[0].enable_providers, ["galaxy"]); + + let without = Manifest::from_identities(&identities, None); + assert!(!without + .to_toml_string() + .unwrap() + .contains("enable_providers")); + assert!(without.projects[0].enable_providers.is_empty()); + } + + #[test] + fn parses_an_explicit_enable_providers_field() { + let toml_str = r#" + [[project]] + identities = ["github:owner/repo"] + enable_providers = ["galaxy"] + "#; + let manifest = Manifest::parse(toml_str).unwrap(); + assert_eq!(manifest.projects[0].enable_providers, ["galaxy"]); + } + #[test] fn legacy_topic_parses_while_plural_exact_and_priority_fields_round_trip() { let legacy = Manifest::parse( @@ -340,6 +385,7 @@ topic = "legacy" let manifest = Manifest::from_identities_with_selection( &[Identity::parse("github:owner/repo").unwrap()], selection.clone(), + &[], ); let toml = manifest.to_toml_string().unwrap(); let parsed = Manifest::parse(&toml).unwrap(); diff --git a/src/model.rs b/src/model.rs index df2a0a3..50d2873 100644 --- a/src/model.rs +++ b/src/model.rs @@ -13,6 +13,7 @@ use time::OffsetDateTime; pub enum Category { Code, Downloads, + Usage, Citations, Attention, } @@ -79,6 +80,7 @@ impl Category { match self { Category::Code => "Code", Category::Downloads => "Downloads", + Category::Usage => "Usage", Category::Citations => "Citations", Category::Attention => "Attention", } @@ -240,7 +242,7 @@ pub struct Snapshot { } impl Snapshot { - pub const SCHEMA_VERSION: u32 = 2; + pub const SCHEMA_VERSION: u32 = 3; /// True if any fetch is still in the `Failed` state (drives the exit code). pub fn has_failures(&self) -> bool { @@ -1148,4 +1150,39 @@ mod tests { }; assert!(provider_notes.is_empty()); } + + /// A schema-v2 Snapshot predates `Category::Usage` (issue #79) and so can + /// only ever carry the four older Categories — it must still parse under + /// the current schema version rather than being rejected as stale. + #[test] + fn schema_v2_snapshots_without_a_usage_category_remain_readable() { + let json = r#"{ + "schema_version": 2, + "tool": "boast", + "tool_version": "0.5.0", + "created_at": "2026-08-07T00:00:00Z", + "identities": ["github:owner/repo"], + "results": [{ + "provider": "github", + "identity": "github:owner/repo", + "category": "downloads", + "outcome": {"status": "values", "metrics": [], "metadata": null, "provider_notes": []} + }] + }"#; + + let snapshot: Snapshot = serde_json::from_str(json).unwrap(); + assert_eq!(snapshot.results[0].category, Category::Downloads); + } + + #[test] + fn category_usage_round_trips_as_the_snake_case_tag() { + assert_eq!( + serde_json::to_string(&Category::Usage).unwrap(), + "\"usage\"" + ); + assert_eq!( + serde_json::from_str::("\"usage\"").unwrap(), + Category::Usage + ); + } } diff --git a/src/providers/galaxy.rs b/src/providers/galaxy.rs new file mode 100644 index 0000000..72be9f6 --- /dev/null +++ b/src/providers/galaxy.rs @@ -0,0 +1,550 @@ +//! Galaxy CoDex Provider for tool-execution usage stats (issue #79): matches +//! a GitHub repository Identity against the wrapper "suites" published by +//! the Galaxy Tool CoDex project and aggregates cumulative execution counts, +//! a max unique-user-account figure, and public-instance availability into +//! the Usage Category. +//! +//! **Optional, disabled by default** — this is the first non-default +//! Provider (see [`crate::providers::optional_providers`]): enable it with +//! `--enable-provider galaxy` or a Manifest's `enable_providers`. One tool +//! can have several Galaxy wrappers, one per subcommand (a "suite" in +//! CoDex's own vocabulary) — vcflib alone maps to 23 — so every matched +//! suite's `Homepage` is compared, never `Suite source` (the wrapper +//! repository under `galaxyproject/tools-iuc` or similar, not the upstream +//! Project being measured). +//! +//! Fetches the one file CoDex republishes independently of its dated +//! per-server SQL exports, `communities/all/resources/tools.json`, and +//! treats it as the authoritative published dataset. `Metric.as_of` is +//! always when boast fetched it, never CoDex's own regeneration date — the +//! file's cumulative figures may lag the underlying Galaxy servers by an +//! amount CoDex does not itself publish, which is why both cumulative-count +//! Metrics (`runs` via [`RUNS_LAG_NOTE`], `user_accounts` via +//! [`USER_ACCOUNTS_CAVEAT_NOTE`]) carry that caveat. `public_instances` +//! doesn't: availability is a current-state fact CoDex derives the same way +//! either way, not a count that can drift stale in the same sense. + +use serde::Deserialize; +use time::OffsetDateTime; + +use crate::model::{Category, Identity, Metric, MetricValue, Outcome, RepoId, Window}; +use crate::provider::Provider; +use crate::transport::{is_transient_status, Transport}; + +pub const NAME: &str = "galaxy"; + +const TOOLS_JSON_URL: &str = "https://raw.githubusercontent.com/galaxyproject/galaxy_codex/main/communities/all/resources/tools.json"; + +const MAJOR_INSTANCES: [&str; 4] = [ + "UseGalaxy.org", + "UseGalaxy.org.au", + "UseGalaxy.eu", + "UseGalaxy.fr", +]; + +/// Why a cumulative CoDex figure isn't a live count. Deliberately longer +/// than [`crate::report::INLINE_DETAIL_LIMIT`] so it reaches the Notices +/// footer (ADR-0005) rather than being silently dropped from every row. +pub const RUNS_LAG_NOTE: &str = "Galaxy CoDex republishes cumulative tool-execution counts \ + on its own refresh schedule, so this figure may lag the underlying Galaxy servers"; + +/// The multi-suite aggregation rule, close to the issue's own suggested +/// wording ("Runs: aggregated sum. Users: max unique per wrapper (to prevent +/// over-counting)."), plus the "not distinct people" caveat the issue's +/// triage thread insisted on (a main-server user total can count one account +/// once per server) and the same lag caveat [`RUNS_LAG_NOTE`] carries, since +/// `user_accounts` is drawn from the same cumulative CoDex snapshot as +/// `runs`. Also deliberately over [`crate::report::INLINE_DETAIL_LIMIT`]. +pub const USER_ACCOUNTS_CAVEAT_NOTE: &str = + "Runs: aggregated sum. Users: max unique per wrapper (to prevent over-counting) — not a \ + count of distinct people, since CoDex's per-server totals can count one account once per \ + server. Both are cumulative CoDex figures that may lag the underlying Galaxy servers."; + +#[derive(Debug, Deserialize)] +struct CodexSuite { + #[serde(rename = "Suite ID")] + suite_id: String, + #[serde(rename = "Homepage")] + homepage: Option, + #[serde(rename = "Suite runs on main servers")] + runs: u64, + #[serde(rename = "Suite users on main servers")] + users: u64, + #[serde(rename = "Number of tools on UseGalaxy.org (Main)")] + tools_usegalaxy_org: u64, + #[serde(rename = "Number of tools on UseGalaxy.org.au")] + tools_usegalaxy_org_au: u64, + #[serde(rename = "Number of tools on UseGalaxy.eu")] + tools_usegalaxy_eu: u64, + #[serde(rename = "Number of tools on UseGalaxy.fr")] + tools_usegalaxy_fr: u64, +} + +pub struct Galaxy; + +impl Galaxy { + fn repo(identity: &Identity) -> Option<&RepoId> { + match identity { + Identity::Repo(r) => Some(r), + _ => None, + } + } + + /// A CoDex `Homepage` matches `repo` only when it's recognisably a + /// GitHub URL — the same discipline `Identity::parse` applies to a + /// positional GitHub URL (only `github.com/`/`git@github.com:` counts), + /// and the same prefix-stripping shape `RepoId::parse` itself uses, so a + /// look-alike host (`not-github.com/owner/name`) can't slip past a bare + /// substring check. Without this guard, `RepoId::parse`'s bare + /// `owner/name` fallback (meant for the CLI's explicit `--repo` + /// shorthand) would treat an arbitrary non-GitHub Homepage's first two + /// path segments as if they were a repository, risking a false match — + /// CoDex has hundreds of non-GitHub Homepage values (lab websites, + /// ReadTheDocs, Bioconductor). + fn matches(repo: &RepoId, homepage: &str) -> bool { + let mut rest = homepage.trim(); + for scheme in ["https://", "http://"] { + rest = rest.strip_prefix(scheme).unwrap_or(rest); + } + let lower = rest.to_ascii_lowercase(); + let is_github_url = lower.starts_with("github.com/") + || lower.starts_with("www.github.com/") + || homepage.starts_with("git@github.com:"); + if !is_github_url { + return false; + } + RepoId::parse(homepage).is_ok_and(|h| { + h.owner.eq_ignore_ascii_case(&repo.owner) && h.name.eq_ignore_ascii_case(&repo.name) + }) + } + + /// The union of major public instances any matched suite is available + /// on, in [`MAJOR_INSTANCES`] order — "available" means CoDex counts at + /// least one tool installed there, independent of whether it has ever + /// been run. + fn matched_instances(matched: &[&CodexSuite]) -> Vec<&'static str> { + let mut names = Vec::new(); + if matched.iter().any(|s| s.tools_usegalaxy_org > 0) { + names.push(MAJOR_INSTANCES[0]); + } + if matched.iter().any(|s| s.tools_usegalaxy_org_au > 0) { + names.push(MAJOR_INSTANCES[1]); + } + if matched.iter().any(|s| s.tools_usegalaxy_eu > 0) { + names.push(MAJOR_INSTANCES[2]); + } + if matched.iter().any(|s| s.tools_usegalaxy_fr > 0) { + names.push(MAJOR_INSTANCES[3]); + } + names + } + + fn classify(body: &str, repo: &RepoId, url: &str, canonical: &str) -> Outcome { + let suites: Vec = match serde_json::from_str(body) { + Ok(s) => s, + Err(e) => { + return Outcome::Failed { + error: format!("unexpected Galaxy CoDex response: {e}"), + } + } + }; + + let matched: Vec<&CodexSuite> = suites + .iter() + .filter(|s| { + s.homepage + .as_deref() + .is_some_and(|h| Self::matches(repo, h)) + }) + .collect(); + + // No exact CoDex match is NotApplicable, never a real zero (ADR-0002) + // — most repositories simply have no Galaxy wrapper at all. + if matched.is_empty() { + return Outcome::NotApplicable { + note: "no Galaxy CoDex suite's Homepage matches this repository".into(), + }; + } + + let total_runs: u64 = matched.iter().map(|s| s.runs).sum(); + let max_users: u64 = matched.iter().map(|s| s.users).max().unwrap_or(0); + let instances = Self::matched_instances(&matched); + let as_of = OffsetDateTime::now_utc(); + + let mut suite_ids: Vec<&str> = matched.iter().map(|s| s.suite_id.as_str()).collect(); + suite_ids.sort_unstable(); + let plural = if suite_ids.len() == 1 { "" } else { "s" }; + let audit_note = format!( + "Matched {} Galaxy CoDex suite{plural}: {}", + suite_ids.len(), + suite_ids.join(", "), + ); + + let instances_note = if instances.is_empty() { + format!( + "not available on any of the four major public Galaxy instances ({})", + MAJOR_INSTANCES.join(", ") + ) + } else { + format!("available on {}", instances.join(", ")) + }; + + Outcome::Values { + provider_notes: vec![audit_note], + metrics: vec![ + Metric { + name: "runs".into(), + category: Category::Usage, + value: MetricValue::Count(total_runs), + window: Window::Cumulative, + provider: NAME.into(), + identity: canonical.into(), + as_of, + source: url.into(), + note: Some(RUNS_LAG_NOTE.into()), + }, + Metric { + name: "user_accounts".into(), + category: Category::Usage, + value: MetricValue::Count(max_users), + window: Window::Cumulative, + provider: NAME.into(), + identity: canonical.into(), + as_of, + source: url.into(), + note: Some(USER_ACCOUNTS_CAVEAT_NOTE.into()), + }, + Metric { + name: "public_instances".into(), + category: Category::Usage, + value: MetricValue::Count(instances.len() as u64), + window: Window::Cumulative, + provider: NAME.into(), + identity: canonical.into(), + as_of, + source: url.into(), + note: Some(instances_note), + }, + ], + metadata: None, + } + } + + /// `tools.json` is one fixed URL shared by every Identity, unlike a + /// per-repo endpoint — so a non-200 here means the *fetch* failed, never + /// that this repository has no Galaxy presence. Deliberately not named + /// or shaped like `provider::classify_status`, and deliberately not + /// calling it: that helper's 404-is-NotApplicable default assumes a + /// per-Identity URL, but a 404 on this shared file means the file moved, + /// which is `Failed`, not evidence about any one repository. + fn classify_shared_file_status(status: u16) -> Option { + if status == 200 { + return None; + } + let error = if status == 429 { + "rate limited by Galaxy CoDex (429)".to_string() + } else if is_transient_status(status) { + format!("Galaxy CoDex server error ({status})") + } else { + format!("unexpected Galaxy CoDex status ({status})") + }; + Some(Outcome::Failed { error }) + } +} + +impl Provider for Galaxy { + fn name(&self) -> &'static str { + NAME + } + + fn category(&self) -> Category { + Category::Usage + } + + fn supports(&self, identity: &Identity) -> bool { + Self::repo(identity).is_some() + } + + fn fetch(&self, identity: &Identity, transport: &dyn Transport) -> Outcome { + let Some(repo) = Self::repo(identity) else { + return Outcome::NotApplicable { + note: "Galaxy CoDex only supports GitHub repository identities".into(), + }; + }; + let canonical = identity.canonical(); + + let resp = match transport.get(TOOLS_JSON_URL) { + Ok(r) => r, + Err(e) => { + return Outcome::Failed { + error: e.to_string(), + } + } + }; + + match Self::classify_shared_file_status(resp.status) { + Some(outcome) => outcome, + None => Self::classify(&resp.body, repo, TOOLS_JSON_URL, &canonical), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{PackageId, PaperId, Registry, RepoHost}; + use crate::transport::{MockTransport, TransportError}; + + const CASSETTE: &str = include_str!("../../tests/cassettes/galaxy_codex_tools.json"); + + fn repo(owner: &str, name: &str) -> Identity { + Identity::Repo(RepoId { + host: RepoHost::GitHub, + owner: owner.into(), + name: name.into(), + }) + } + + fn values(outcome: Outcome) -> (Vec, Vec) { + match outcome { + Outcome::Values { + metrics, + provider_notes, + .. + } => (metrics, provider_notes), + other => panic!("expected Values, got {other:?}"), + } + } + + fn metric<'a>(metrics: &'a [Metric], name: &str) -> &'a Metric { + metrics + .iter() + .find(|m| m.name == name) + .unwrap_or_else(|| panic!("no '{name}' metric among {metrics:?}")) + } + + #[test] + fn a_single_matched_suite_emits_cumulative_usage_metrics() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + + let (metrics, notes) = values(Galaxy.fetch(&repo("mbhall88", "rasusa"), &t)); + + assert_eq!(metrics.len(), 3); + for m in &metrics { + assert_eq!(m.category, Category::Usage); + assert_eq!(m.window, Window::Cumulative); + assert_eq!(m.provider, "galaxy"); + assert_eq!(m.identity, "github:mbhall88/rasusa"); + } + assert_eq!(metric(&metrics, "runs").value, MetricValue::Count(104)); + assert_eq!( + metric(&metrics, "user_accounts").value, + MetricValue::Count(24) + ); + // rasusa is available on eu + fr only (2 of the 4 major instances). + assert_eq!( + metric(&metrics, "public_instances").value, + MetricValue::Count(2) + ); + assert!(metric(&metrics, "public_instances") + .note + .as_deref() + .unwrap() + .contains("UseGalaxy.eu, UseGalaxy.fr")); + + assert_eq!(notes, vec!["Matched 1 Galaxy CoDex suite: rasusa"]); + } + + #[test] + fn a_suite_available_everywhere_reports_all_four_major_instances() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + let (metrics, _) = values(Galaxy.fetch(&repo("tseemann", "shovill"), &t)); + assert_eq!( + metric(&metrics, "public_instances").value, + MetricValue::Count(4) + ); + } + + #[test] + fn multiple_matched_suites_sum_runs_and_take_the_maximum_users() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + + let (metrics, notes) = values(Galaxy.fetch(&repo("owner", "toolx"), &t)); + + // toolx-align (100 runs, 10 users) + toolx-call (50 runs, 40 users). + assert_eq!(metric(&metrics, "runs").value, MetricValue::Count(150)); + // Users are the maximum across wrappers, never summed (10 + 40 would + // over-count one account using both subcommands). + assert_eq!( + metric(&metrics, "user_accounts").value, + MetricValue::Count(40) + ); + // Union of instances: toolx-align is on org+eu, toolx-call is on fr. + assert_eq!( + metric(&metrics, "public_instances").value, + MetricValue::Count(3) + ); + + assert_eq!( + notes, + vec!["Matched 2 Galaxy CoDex suites: toolx-align, toolx-call"] + ); + } + + #[test] + fn every_metric_carries_a_caveat_long_enough_for_the_notices_footer() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + let (metrics, _) = values(Galaxy.fetch(&repo("mbhall88", "rasusa"), &t)); + + for name in ["runs", "user_accounts"] { + let note = metric(&metrics, name).note.clone().unwrap(); + assert!( + note.len() > crate::report::INLINE_DETAIL_LIMIT, + "{name}'s note must reach the Notices footer, not be squeezed inline" + ); + } + } + + #[test] + fn no_matching_suite_is_not_applicable_never_zero() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + + match Galaxy.fetch(&repo("someone", "not-on-galaxy"), &t) { + Outcome::NotApplicable { note } => assert!(note.contains("no Galaxy CoDex suite")), + other => panic!("expected NotApplicable, got {other:?}"), + } + } + + /// The wrapper repository named in `Suite source` (`galaxyproject/tools-iuc` + /// in the fixture) must never be treated as a match — only `Homepage` (the + /// upstream Project) is compared. + #[test] + fn the_suite_source_wrapper_repository_is_never_matched() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + + match Galaxy.fetch(&repo("galaxyproject", "tools-iuc"), &t) { + Outcome::NotApplicable { .. } => {} + other => panic!("expected NotApplicable, got {other:?}"), + } + } + + /// A non-GitHub Homepage (hundreds exist in the real dataset — lab + /// sites, ReadTheDocs, Bioconductor) must never be coerced into a repo + /// match via `RepoId::parse`'s bare `owner/name` fallback. The fixture's + /// "unrelated-tool" entry has `Homepage: "https://etetoolkit.org/docs/latest"` + /// — without the github.com guard, `RepoId::parse` would happily read + /// that as owner `etetoolkit.org`, name `docs`, and falsely match here. + #[test] + fn a_non_github_homepage_never_false_matches() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + + match Galaxy.fetch(&repo("etetoolkit.org", "docs"), &t) { + Outcome::NotApplicable { .. } => {} + other => panic!("expected NotApplicable, got {other:?}"), + } + } + + /// A look-alike host is not GitHub, even though it contains the literal + /// substring "github.com/" — `"not-github.com/"` ends with exactly that + /// substring, so a naive `.contains("github.com/")` guard would have + /// wrongly treated this as a GitHub URL and gone on to `RepoId::parse` + /// it. The real guard checks the string *starts with* the host (after + /// stripping a scheme), the same way `RepoId::parse` itself does. + #[test] + fn a_look_alike_host_containing_github_com_as_a_substring_never_matches() { + let body = r#"[{ + "Suite ID": "lookalike", + "Homepage": "https://not-github.com/owner/toolx", + "Suite runs on main servers": 1, + "Suite users on main servers": 1, + "Number of tools on UseGalaxy.org (Main)": 0, + "Number of tools on UseGalaxy.org.au": 0, + "Number of tools on UseGalaxy.eu": 0, + "Number of tools on UseGalaxy.fr": 0 + }]"#; + let t = MockTransport::new().on("raw.githubusercontent.com", 200, body); + + match Galaxy.fetch(&repo("owner", "toolx"), &t) { + Outcome::NotApplicable { .. } => {} + other => panic!("expected NotApplicable, got {other:?}"), + } + } + + /// A suite with no Homepage at all must be skipped, not panic or match. + #[test] + fn a_null_homepage_suite_never_matches_anything() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + match Galaxy.fetch(&repo("example", "no-homepage-tool"), &t) { + Outcome::NotApplicable { .. } => {} + other => panic!("expected NotApplicable, got {other:?}"), + } + } + + #[test] + fn malformed_json_fails_rather_than_reporting_a_value() { + let t = MockTransport::new().on("raw.githubusercontent.com", 200, "not json"); + + match Galaxy.fetch(&repo("mbhall88", "rasusa"), &t) { + Outcome::Failed { error } => assert!(error.contains("unexpected Galaxy CoDex")), + other => panic!("expected Failed, got {other:?}"), + } + } + + /// Unlike a per-Identity endpoint, a 404 on this single shared file means + /// the fetch itself failed — never that one repository lacks a match. + #[test] + fn a_404_on_the_shared_file_is_failed_not_not_applicable() { + let t = MockTransport::new().on("raw.githubusercontent.com", 404, ""); + + match Galaxy.fetch(&repo("mbhall88", "rasusa"), &t) { + Outcome::Failed { error } => assert!(error.contains("404")), + other => panic!("expected Failed, got {other:?}"), + } + } + + #[test] + fn rate_limit_and_server_error_are_failed() { + for status in [429, 503] { + let t = MockTransport::new().on("raw.githubusercontent.com", status, ""); + assert!( + matches!( + Galaxy.fetch(&repo("mbhall88", "rasusa"), &t), + Outcome::Failed { .. } + ), + "status {status} should be Failed" + ); + } + } + + #[test] + fn a_transport_error_fails_rather_than_reporting_a_value() { + let t = MockTransport::new().on_error( + "raw.githubusercontent.com", + TransportError::ConnectionFailed, + ); + + match Galaxy.fetch(&repo("mbhall88", "rasusa"), &t) { + Outcome::Failed { error } => assert!(error.contains("connection failed")), + other => panic!("expected Failed, got {other:?}"), + } + } + + #[test] + fn supports_only_repo_identities() { + assert!(Galaxy.supports(&repo("mbhall88", "rasusa"))); + assert!(!Galaxy.supports(&Identity::Package(PackageId { + registry: Registry::Crates, + name: "boast".into(), + }))); + assert!(!Galaxy.supports(&Identity::Paper(PaperId::Doi("10.0/0".into())))); + } + + #[test] + fn fetch_on_an_unsupported_identity_is_not_applicable() { + let t = MockTransport::new(); + match Galaxy.fetch(&Identity::Paper(PaperId::Doi("10.0/0".into())), &t) { + Outcome::NotApplicable { .. } => {} + other => panic!("expected NotApplicable, got {other:?}"), + } + } +} diff --git a/src/providers/mod.rs b/src/providers/mod.rs index 1bd2e07..791a03e 100644 --- a/src/providers/mod.rs +++ b/src/providers/mod.rs @@ -7,6 +7,7 @@ pub mod crossref; pub mod dimensions; pub mod docker_hub; pub mod europe_pmc; +pub mod galaxy; pub mod github; pub mod homebrew; pub mod openalex; @@ -70,6 +71,36 @@ pub fn default_providers_with_github( ] } +/// Providers that exist but are never fetched by a default run — a user +/// must explicitly opt in, via `--enable-provider ` or a Manifest's +/// `enable_providers` (issue #79). Galaxy is the first: a repository-level +/// CoDex lookup that most Projects have no presence in, so it would add a +/// mostly-empty request to every default run rather than a useful one. +pub fn optional_providers() -> Vec> { + vec![Box::new(galaxy::Galaxy)] +} + +/// Resolve `--enable-provider`/Manifest `enable_providers` names into the +/// optional Providers they name. An unknown name is an error listing every +/// recognised optional Provider, since every caller treats it as a CLI usage +/// error (exit code 2) — there is no silent partial-enable. +pub fn resolve_optional_providers(names: &[String]) -> Result>, String> { + let all = optional_providers(); + let known: Vec<&str> = all.iter().map(|p| p.name()).collect(); + for name in names { + if !known.contains(&name.as_str()) { + return Err(format!( + "unknown optional provider '{name}' (available: {})", + known.join(", ") + )); + } + } + Ok(all + .into_iter() + .filter(|p| names.iter().any(|n| n == p.name())) + .collect()) +} + /// How many default Providers fetch metrics for a Paper Identity — the /// per-work request cost `boast init --orcid` warns about before expanding a /// large record. Computed from the real registry (never hard-coded), so the @@ -83,16 +114,18 @@ pub fn paper_provider_count() -> usize { .count() } -/// Render the given registry (usually [`default_providers`]) as a table for -/// `boast providers`: name, Category, default-enabled status, and key -/// requirement (issue #16). Grouped in [`CATEGORY_ORDER`], the same display -/// order every other Report uses. +/// Render `default` plus `optional` as a table for `boast providers`: name, +/// Category, default-enabled status, and key requirement (issue #16). +/// Grouped in [`CATEGORY_ORDER`], the same display order every other Report +/// uses. /// -/// Every Provider passed in is, by construction, part of the default set — -/// there's no separate optional/non-default registry yet (see the spec's -/// Out-of-Scope list) — so the DEFAULT column reads "yes" throughout; the -/// column exists so the answer stays visible once a non-default Provider -/// exists to contrast it with. +/// Every Provider in `default` reads "yes" in the DEFAULT column and every +/// Provider in `optional` reads "no" (issue #79 — Galaxy is the first +/// non-default Provider, enabled only via `--enable-provider`/a Manifest's +/// `enable_providers`). A Provider named in both would be listed twice; the +/// two registries are disjoint by construction (see +/// [`crate::providers::optional_providers`]'s doc comment), so callers don't +/// need to de-duplicate here. /// /// `key_is_set` looks up whether a named environment variable currently has /// a non-empty value. Taking it as a parameter — the same seam pattern as @@ -100,23 +133,34 @@ pub fn paper_provider_count() -> usize { /// instead of mutating the real process environment, which is global and /// shared across every test running in this process. pub fn render_providers( - providers: &[Box], + default: &[Box], + optional: &[Box], key_is_set: impl Fn(&str) -> bool, ) -> String { struct Row { name: &'static str, category: Category, + is_default: bool, key: String, } - let mut rows: Vec = providers - .iter() - .map(|p| Row { - name: p.name(), - category: p.category(), - key: describe_key(p.key_requirement(), &key_is_set), - }) - .collect(); + let rows_from = |providers: &[Box], + is_default: bool, + key_is_set: &dyn Fn(&str) -> bool| + -> Vec { + providers + .iter() + .map(|p| Row { + name: p.name(), + category: p.category(), + is_default, + key: describe_key(p.key_requirement(), key_is_set), + }) + .collect() + }; + + let mut rows: Vec = rows_from(default, true, &key_is_set); + rows.extend(rows_from(optional, false, &key_is_set)); rows.sort_by_key(|r| { CATEGORY_ORDER .iter() @@ -124,11 +168,8 @@ pub fn render_providers( .unwrap_or(usize::MAX) }); - // Every row's DEFAULT column reads "yes" (see the doc comment above), but - // its width is still computed rather than hand-padded to a literal, so a - // future non-"yes" value can't silently fall out of alignment with the - // header. - const DEFAULT_COL: &str = "yes"; + const YES: &str = "yes"; + const NO: &str = "no"; let w_name = "PROVIDER" .len() .max(rows.iter().map(|r| r.name.len()).max().unwrap_or(0)); @@ -138,7 +179,7 @@ pub fn render_providers( .max() .unwrap_or(0), ); - let w_default = "DEFAULT".len().max(DEFAULT_COL.len()); + let w_default = "DEFAULT".len().max(YES.len()).max(NO.len()); let mut out = String::new(); out.push_str(&format!( @@ -146,8 +187,9 @@ pub fn render_providers( "PROVIDER", "CATEGORY", "DEFAULT", )); for r in rows { + let default_col = if r.is_default { YES } else { NO }; out.push_str(&format!( - "{: bool) -> String { +fn describe_key(requirement: KeyRequirement, key_is_set: &dyn Fn(&str) -> bool) -> String { let (label, env_var) = match requirement { KeyRequirement::None => return "none".to_string(), KeyRequirement::Optional { env_var } => ("optional", env_var), @@ -226,7 +268,7 @@ mod tests { fake("a_code", Category::Code, KeyRequirement::None), fake("m_attention", Category::Attention, KeyRequirement::None), ]; - let out = render_providers(&providers, |_| false); + let out = render_providers(&providers, &[], |_| false); let code_pos = out.find("a_code").unwrap(); let downloads_pos = out.find("z_downloads").unwrap(); let attention_pos = out.find("m_attention").unwrap(); @@ -251,7 +293,7 @@ mod tests { KeyRequirement::Required { env_var: "REQ_KEY" }, ), ]; - let out = render_providers(&providers, |name| name == "OPT_TOKEN"); + let out = render_providers(&providers, &[], |name| name == "OPT_TOKEN"); let row = |needle: &str| out.lines().find(|l| l.contains(needle)).unwrap(); assert!(row("keyless").contains("none")); @@ -260,15 +302,15 @@ mod tests { } #[test] - fn every_row_is_marked_default_enabled() { - let providers: Vec> = - vec![fake("x", Category::Code, KeyRequirement::None)]; - let out = render_providers(&providers, |_| false); - assert!(out - .lines() - .find(|l| l.contains("x")) - .unwrap() - .contains("yes")); + fn a_default_provider_is_marked_yes_and_an_optional_one_is_marked_no() { + let default: Vec> = vec![fake("d", Category::Code, KeyRequirement::None)]; + let optional: Vec> = + vec![fake("o", Category::Usage, KeyRequirement::None)]; + let out = render_providers(&default, &optional, |_| false); + + let row = |needle: &str| out.lines().find(|l| l.contains(needle)).unwrap(); + assert!(row("d").contains("yes")); + assert!(row("o").contains("no")); } #[test] @@ -279,15 +321,54 @@ mod tests { #[test] fn reflects_the_real_registry_with_no_hard_coded_drift() { - let providers = default_providers(); - let out = render_providers(&providers, |_| false); + let default = default_providers(); + let optional = optional_providers(); + let out = render_providers(&default, &optional, |_| false); - for p in &providers { + for p in default.iter().chain(&optional) { assert!(out.contains(p.name()), "missing {} in output", p.name()); } - // Header plus exactly one row per registered Provider. - assert_eq!(out.lines().count(), providers.len() + 1); + // Header plus exactly one row per registered Provider, default or optional. + assert_eq!(out.lines().count(), default.len() + optional.len() + 1); assert!(out.contains("required: ALTMETRIC_KEY")); assert!(out.contains("optional: GITHUB_TOKEN")); } + + #[test] + fn the_real_registrys_galaxy_row_is_under_usage_and_marked_not_default() { + let out = render_providers(&default_providers(), &optional_providers(), |_| false); + let row = out.lines().find(|l| l.starts_with("galaxy ")).unwrap(); + assert!(row.contains("Usage")); + assert!(row.contains(" no ")); + assert!(row.contains("none")); + } + + #[test] + fn galaxy_is_optional_never_part_of_the_default_registry() { + assert!(!default_providers().iter().any(|p| p.name() == galaxy::NAME)); + assert!(optional_providers() + .iter() + .any(|p| p.name() == galaxy::NAME)); + } + + #[test] + fn resolve_optional_providers_finds_a_known_name() { + let resolved = resolve_optional_providers(&["galaxy".to_string()]).unwrap(); + assert_eq!(resolved.len(), 1); + assert_eq!(resolved[0].name(), galaxy::NAME); + } + + #[test] + fn resolve_optional_providers_rejects_an_unknown_name_naming_the_known_ones() { + let Err(err) = resolve_optional_providers(&["not-a-real-provider".to_string()]) else { + panic!("expected an error"); + }; + assert!(err.contains("not-a-real-provider")); + assert!(err.contains("galaxy")); + } + + #[test] + fn resolve_optional_providers_of_an_empty_list_is_empty() { + assert!(resolve_optional_providers(&[]).unwrap().is_empty()); + } } diff --git a/src/report.rs b/src/report.rs index 498068a..6daccfc 100644 --- a/src/report.rs +++ b/src/report.rs @@ -9,10 +9,12 @@ use crate::model::{Category, Metric, MetricValue, Outcome, Snapshot, Window}; use crate::rollup; /// Display order for Categories, shared with [`crate::diff`]'s renderer so -/// both group Metrics identically. -pub(crate) const CATEGORY_ORDER: [Category; 4] = [ +/// both group Metrics identically. Usage sits after Downloads and before +/// Citations, matching CONTEXT.md's Category glossary order (issue #79). +pub(crate) const CATEGORY_ORDER: [Category; 5] = [ Category::Code, Category::Downloads, + Category::Usage, Category::Citations, Category::Attention, ]; diff --git a/tests/cassettes/galaxy_codex_tools.json b/tests/cassettes/galaxy_codex_tools.json new file mode 100644 index 0000000..212948a --- /dev/null +++ b/tests/cassettes/galaxy_codex_tools.json @@ -0,0 +1,74 @@ +[ + { + "Suite ID": "rasusa", + "Homepage": "https://github.com/mbhall88/rasusa", + "Suite owner": "iuc", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/rasusa", + "Number of tools on UseGalaxy.org (Main)": 0, + "Number of tools on UseGalaxy.org.au": 0, + "Number of tools on UseGalaxy.eu": 1, + "Number of tools on UseGalaxy.fr": 1, + "Suite runs on main servers": 104, + "Suite users on main servers": 24 + }, + { + "Suite ID": "shovill", + "Homepage": "https://github.com/tseemann/shovill", + "Suite owner": "iuc", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/shovill", + "Number of tools on UseGalaxy.org (Main)": 1, + "Number of tools on UseGalaxy.org.au": 1, + "Number of tools on UseGalaxy.eu": 1, + "Number of tools on UseGalaxy.fr": 1, + "Suite runs on main servers": 176227, + "Suite users on main servers": 10455 + }, + { + "Suite ID": "toolx-align", + "Homepage": "https://github.com/owner/toolx", + "Suite owner": "example", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/toolx-align", + "Number of tools on UseGalaxy.org (Main)": 1, + "Number of tools on UseGalaxy.org.au": 0, + "Number of tools on UseGalaxy.eu": 1, + "Number of tools on UseGalaxy.fr": 0, + "Suite runs on main servers": 100, + "Suite users on main servers": 10 + }, + { + "Suite ID": "toolx-call", + "Homepage": "https://github.com/owner/toolx", + "Suite owner": "example", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/toolx-call", + "Number of tools on UseGalaxy.org (Main)": 0, + "Number of tools on UseGalaxy.org.au": 0, + "Number of tools on UseGalaxy.eu": 0, + "Number of tools on UseGalaxy.fr": 1, + "Suite runs on main servers": 50, + "Suite users on main servers": 40 + }, + { + "Suite ID": "unrelated-tool", + "Homepage": "https://etetoolkit.org/docs/latest", + "Suite owner": "example", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/unrelated", + "Number of tools on UseGalaxy.org (Main)": 1, + "Number of tools on UseGalaxy.org.au": 1, + "Number of tools on UseGalaxy.eu": 1, + "Number of tools on UseGalaxy.fr": 1, + "Suite runs on main servers": 999, + "Suite users on main servers": 999 + }, + { + "Suite ID": "no-homepage-tool", + "Homepage": null, + "Suite owner": "example", + "Suite source": "https://github.com/galaxyproject/tools-iuc/tree/main/tools/no-homepage", + "Number of tools on UseGalaxy.org (Main)": 1, + "Number of tools on UseGalaxy.org.au": 0, + "Number of tools on UseGalaxy.eu": 0, + "Number of tools on UseGalaxy.fr": 0, + "Suite runs on main servers": 1, + "Suite users on main servers": 1 + } +] diff --git a/tests/galaxy.rs b/tests/galaxy.rs new file mode 100644 index 0000000..dc62d7b --- /dev/null +++ b/tests/galaxy.rs @@ -0,0 +1,200 @@ +//! End-to-end tests for the Galaxy CoDex Provider (issue #79), driven from a +//! recorded `tools.json` fixture through the real orchestrator, terminal +//! Report, and CLI's optional-Provider registry. +//! +//! Galaxy is the first Provider that is never part of a default run — the +//! load-bearing case here is negative, same shape as Quay's Rollup test: +//! `default_providers()` must never include it, and even when it *is* +//! enabled alongside real Downloads channels, its Usage-Category Metrics +//! must never be swept into the Downloads Rollup despite sharing the exact +//! same Cumulative Window (the thing that would otherwise make `rollup::compute` +//! merge them). + +use boast::model::{Identity, PackageId, Project, Registry, RepoHost, RepoId, Snapshot}; +use boast::orchestrator; +use boast::providers::{crates_io::CratesIo, default_providers, docker_hub::DockerHub, galaxy}; +use boast::report::{render_markdown, render_terminal}; +use boast::transport::MockTransport; +use boast::Category; + +const CASSETTE: &str = include_str!("cassettes/galaxy_codex_tools.json"); + +fn repo(owner: &str, name: &str) -> Identity { + Identity::Repo(RepoId { + host: RepoHost::GitHub, + owner: owner.into(), + name: name.into(), + }) +} + +#[test] +fn galaxy_is_absent_from_the_default_registry_and_never_fetched_by_a_default_run() { + assert!(!default_providers().iter().any(|p| p.name() == galaxy::NAME)); + + // A `MockTransport` panics on any unmatched URL (see + // `transport::tests::mock_panics_on_unmatched`), so if Galaxy were ever + // accidentally wired into `default_providers()`, this run would panic on + // the unstubbed `raw.githubusercontent.com` request rather than silently + // passing. Only GitHub's own endpoints are stubbed. + let transport = MockTransport::new() + .on("api.github.com/repos/mbhall88/rasusa", 200, "{}") + .on("api.github.com/repos/mbhall88/rasusa/releases", 200, "[]") + .on( + "api.github.com/search/repositories", + 200, + r#"{"items": []}"#, + ) + .on("api.openalex.org/works", 200, r#"{"meta": {"count": 0}}"#) + .on("www.ebi.ac.uk/europepmc", 200, r#"{"hitCount": 0}"#); + let project = Project::new(vec![repo("mbhall88", "rasusa")]); + orchestrator::run(&project, &default_providers(), &transport); +} + +#[test] +fn a_matched_repo_flows_into_the_usage_category_between_downloads_and_citations() { + let transport = MockTransport::new().on("raw.githubusercontent.com", 200, CASSETTE); + let project = Project::new(vec![repo("mbhall88", "rasusa")]); + let providers: Vec> = vec![Box::new(galaxy::Galaxy)]; + let snapshot = orchestrator::run(&project, &providers, &transport); + + assert!(!snapshot.has_failures()); + let usage: Vec<_> = snapshot + .metrics() + .filter(|m| m.category == Category::Usage) + .collect(); + assert_eq!(usage.len(), 3); + + let report = render_terminal(&snapshot); + assert!(report.contains("── Usage ──")); + let usage_pos = report.find("── Usage ──").unwrap(); + // No Downloads/Citations section exists in this single-Provider run, so + // this only pins that the section itself renders under the right title + // (the shared CATEGORY_ORDER placement is covered at the unit level in + // report.rs); the ordering claim is asserted below, with all sections + // present. + assert!(usage_pos > 0); + + let markdown = render_markdown(&snapshot); + assert!(markdown.contains("### Usage")); + assert!(markdown.contains("| runs | 104 |")); + + // Round-trip the whole Snapshot through JSON, the same durable form + // `about` writes to disk — a Usage Metric must survive it exactly. + let json = serde_json::to_string(&snapshot).unwrap(); + let back: Snapshot = serde_json::from_str(&json).unwrap(); + assert_eq!(snapshot, back); + assert!(back + .metrics() + .any(|m| m.category == Category::Usage && m.name == "runs")); +} + +#[test] +fn category_order_places_usage_between_downloads_and_citations() { + // Combine a Downloads Provider (crates.io) and Galaxy in one run so both + // sections render, and assert their relative order in the terminal + // Report — the concrete, user-visible form of CONTEXT.md's Category + // glossary ordering (Code, Downloads, Usage, Citations, Attention). + let crates_cassette = include_str!("cassettes/crates_boast.json"); + let transport = MockTransport::new() + .on("crates.io/api/v1/crates/boast", 200, crates_cassette) + .on("raw.githubusercontent.com", 200, CASSETTE); + + let project = Project::new(vec![ + Identity::Package(PackageId { + registry: Registry::Crates, + name: "boast".into(), + }), + repo("mbhall88", "rasusa"), + ]); + let providers: Vec> = + vec![Box::new(CratesIo), Box::new(galaxy::Galaxy)]; + let snapshot = orchestrator::run(&project, &providers, &transport); + assert!(!snapshot.has_failures()); + + let report = render_terminal(&snapshot); + let downloads_pos = report.find("── Downloads ──").unwrap(); + let usage_pos = report.find("── Usage ──").unwrap(); + assert!( + downloads_pos < usage_pos, + "Downloads must render before Usage:\n{report}" + ); +} + +/// The regression this Provider is riskiest for: Galaxy's `runs` Metric is +/// `Window::Cumulative`, the exact same Window real Downloads channels use — +/// `rollup::compute` groups purely by Window equality, so without the +/// Category-based `counts_as_download` filter upstream of it, Galaxy's count +/// would silently inflate the Downloads Rollup total. +#[test] +fn galaxy_usage_metrics_never_join_the_downloads_rollup_despite_sharing_its_window() { + let crates_cassette = include_str!("cassettes/crates_boast.json"); + let docker_cassette = include_str!("cassettes/docker_biocontainers_samtools.json"); + let transport = MockTransport::new() + .on("crates.io/api/v1/crates/boast", 200, crates_cassette) + .on( + "hub.docker.com/v2/repositories/biocontainers/samtools/", + 200, + docker_cassette, + ) + .on("raw.githubusercontent.com", 200, CASSETTE); + + let project = Project::new(vec![ + Identity::Package(PackageId { + registry: Registry::Crates, + name: "boast".into(), + }), + Identity::Package(PackageId { + registry: Registry::Docker, + name: "biocontainers/samtools".into(), + }), + // rasusa matches the fixture's single "rasusa" suite: 104 cumulative + // runs — if it ever leaked into the Rollup, 842617 + 596335 + 104 = + // 1439056 would replace the correct 1438952 total below. + repo("mbhall88", "rasusa"), + ]); + let providers: Vec> = vec![ + Box::new(CratesIo), + Box::new(DockerHub), + Box::new(galaxy::Galaxy), + ]; + let snapshot = orchestrator::run(&project, &providers, &transport); + assert!(!snapshot.has_failures()); + + let report = render_terminal(&snapshot); + assert!(report.contains("── Usage ──")); + assert!(report.contains("═══ Downloads Rollup")); + + let rollup_start = report.find("═══ Downloads Rollup").unwrap(); + let rollup_end = report[rollup_start..] + .find("── Notices ──") + .map(|i| rollup_start + i) + .unwrap_or(report.len()); + let rollup_section = &report[rollup_start..rollup_end]; + assert!( + rollup_section.contains("1438952"), + "expected the crates.io + docker total only:\n{rollup_section}" + ); + assert!( + !rollup_section.contains("galaxy"), + "Galaxy must never be named as a Downloads Rollup channel:\n{rollup_section}" + ); + assert!( + !rollup_section.contains("1439056"), + "Galaxy's 104 runs must not have been summed into the Downloads total:\n{rollup_section}" + ); +} + +#[test] +fn cli_enable_provider_selects_galaxy_alongside_the_default_registry() { + let mut providers = default_providers(); + providers + .extend(boast::providers::resolve_optional_providers(&["galaxy".to_string()]).unwrap()); + assert!(providers.iter().any(|p| p.name() == galaxy::NAME)); + assert_eq!( + providers + .iter() + .filter(|p| p.name() == galaxy::NAME) + .count(), + 1 + ); +}