From 4626822a2e3e3daa70e5d4290b633ce2e2399561 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:05:17 +0100 Subject: [PATCH 01/31] feat: --include asks a source beside the rest, opt-in ones included -s asks only the sources it names, and a bare run asks none of the opt-in ones, so Google Dataset Search and Mendeley Data could not join either. --include adds them to whatever the selection picks, and dsk mcp --include gives that list to every search a call leaves to the defaults. --- README.md | 6 +-- docs/reference/contract.md | 3 +- examples/relevance/record.rs | 7 +-- src/bench.rs | 8 ++- src/cli.rs | 25 +++++++-- src/find.rs | 1 + src/lib.rs | 5 +- src/mcp.rs | 83 ++++++++++++++++++++++++++---- src/mcp/tools.rs | 2 + src/sources.rs | 38 +++++++++++--- tests/cli.rs | 99 ++++++++++++++++++++++++++++++++++-- 11 files changed, 242 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 8ea15c6..f9b7333 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Search for datasets from the terminal Datasets sit in dozens of archives: Hugging Face and Kaggle, Zenodo and Dataverse, data.gov and data.europa.eu, the IMF and the ECB, NASA and Copernicus. Each has its own search box and its own idea of relevance, and many host the same dataset under different names. dataseek queries them all at once and returns one deduplicated, ranked list, naming every archive that holds each result. Datasets carried by more archives, and matching more of your query, rank higher. -Most sources need no key and nothing to set up. Results come back in the terminal, as JSON for scripts, or to an AI client over MCP. Google Dataset Search and Mendeley Data are the exception: neither permits automated searches, so dataseek asks them only when you name them with `-s` ([ADR 0013](docs/adr/0013-opt-in-sources.md)). `dsk` is the same program under a shorter name. +Most sources need no key and nothing to set up. Results come back in the terminal, as JSON for scripts, or to an AI client over MCP. Google Dataset Search and Mendeley Data are the exception: neither permits automated searches, so dataseek asks them only when you name them, `-s google,mendeley` for those alone or `--include google,mendeley` beside the rest ([ADR 0013](docs/adr/0013-opt-in-sources.md)). `dsk` is the same program under a shorter name. ## Install ```sh @@ -60,7 +60,7 @@ dsk inspect https://zenodo.org/records/13135140 # a page's metadata and the f While, most of the sources don't require an API-key FRED, Roboflow and Data Commons are skipped without one; keys for Hugging Face, Kaggle, Data.gov, GitHub and NCBI raise download limits. See: [`docs/reference/keys-and-cache.md`](docs/reference/keys-and-cache.md). ## MCP -Use it in the terminal, pipe its JSON into scripts, or use dataseek via MCP (`dsk mcp`), so Claude, Cursor or any other MCP client can search and inspect datasets for you. Most sources need no API key. Google Dataset Search and Mendeley Data don't permit automated searches, so dataseek only queries them when named with `-s` ([ADR 0013](docs/adr/0013-opt-in-sources.md)). Register it in the client's MCP server configuration: +Use it in the terminal, pipe its JSON into scripts, or use dataseek via MCP (`dsk mcp`), so Claude, Cursor or any other MCP client can search and inspect datasets for you. Most sources need no API key. Google Dataset Search and Mendeley Data don't permit automated searches, so dataseek only queries them when named, `-s` for those alone or `--include` beside the rest ([ADR 0013](docs/adr/0013-opt-in-sources.md)). Register it in the client's MCP server configuration: ```json { @@ -70,7 +70,7 @@ Use it in the terminal, pipe its JSON into scripts, or use dataseek via MCP (`ds } ``` -Each tool returns what its command prints with `--json`; keys are read from the environment the client starts it in, or from `credentials.toml`. Google Dataset Search and Mendeley Data stay opt-in here too; the model asks for them by naming them in the search tool's `source` argument. See: [`docs/reference/contract.md`](docs/reference/contract.md#mcp-mode). +Each tool returns what its command prints with `--json`; keys are read from the environment the client starts it in, or from `credentials.toml`. Google Dataset Search and Mendeley Data stay opt-in here too: the model asks for them by naming them in the search tool's `source` argument, and a client can ask for them on every search with `"args": ["mcp", "--include", "google,mendeley"]`. See: [`docs/reference/contract.md`](docs/reference/contract.md#mcp-mode). ## Contributing & Development Docs - [`CONTRIBUTING.md`](CONTRIBUTING.md) covers setup, the commit prefixes that decide each release, the test rules and how to add a source. Report vulnerabilities privately, as [`SECURITY.md`](docs/SECURITY.md) describes. diff --git a/docs/reference/contract.md b/docs/reference/contract.md index e358e8a..3cf7c04 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -13,7 +13,7 @@ The version lives only in `Cargo.toml`. Clap reads it via `#[command(version)]`, - `--json`, `--color=auto|always|never`, `--no-color`, `--plain`, `--no-progress` - `--cache-dir DIR` and `--connect-timeout SECS`, each with a `DATASEEK_*` variable; the cache size budget has only its variable, `DATASEEK_CACHE_MAX_MB` -`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). +`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` or `--include` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). `-v` is verbose, never version. `--color` follows the ecosystem standard used by git, ripgrep, and fd: @@ -68,6 +68,7 @@ Every `--json` output is one object with a `schema` tag naming its shape and ver - **Protocol.** Requests naming revision `2026-07-28` in `_meta` are served statelessly, with `server/discover`; clients that open with `initialize` get revision `2025-11-25` or `2025-06-18`. A request naming any other revision gets `-32022` with the supported list. - **stdout** carries one JSON-RPC message per line and nothing else. stderr carries the server's own status line, as plain text, and its calls' narration, as `dataseek-events/1` lines. `-q`, `-v`, `--cache-dir` and `--connect-timeout` given to `dataseek mcp` reach every call. +- **Include.** `--include IDS` given to `dataseek mcp` asks those sources, opt-in ones included, in every search that names no sources of its own; a call that names `source` or `include` is left alone. - **Tools.** Each tool's input schema is its command's `help --json` entry: one property per flag, named by its long form, typed, with its possible values and default; `search`'s words are one `query` string. A call runs `dataseek --json` with those flags, and the result carries the object that prints as `structuredContent` and again as text. - **Failures.** A failed call is a result with `isError: true`: the text is the `Error:`, `Cause:` and `Try:` lines the command line prints, and `structuredContent` the error event. A bad or missing argument is such a failure too, since the model can fix it, and so is a call made while four are already running. A JSON-RPC error answers the rest: a line that is not JSON in UTF-8 gets `-32700`, and the session goes on; a request without a string method, or reusing the id of a call still running, `-32600`; an unknown method `-32601`; an unknown tool or `arguments` that is not an object `-32602`; a server fault `-32603`, whose message says what the command left. A notification is never answered. - **Deadline.** Every search runs with `--timeout`, the argument or its default of 20 seconds, and with the command line's rule for stragglers: past 90% of the sources asked, the rest get one more second unless `source` names them ([ADR 0019](../adr/0019-stop-waiting-past-a-quorum.md)). A `timeout` outside 1 to 300 seconds is refused, so every call ends in a time a client waits for; the schema says so with `minimum` and `maximum`, as it does for every ranged integer. diff --git a/examples/relevance/record.rs b/examples/relevance/record.rs index 12abca4..815ed75 100644 --- a/examples/relevance/record.rs +++ b/examples/relevance/record.rs @@ -37,9 +37,10 @@ pub fn run(queries: &[Query], args: &[String]) -> Result<()> { // Sources whose terms bar storing their results are never written down. let sources: Vec<_> = match spliced { Some(source) => vec![source], - None => { - select(&[], &[], &[]).into_iter().filter(|s| s.persist).collect() - } + None => select(&[], &[], &[], &[]) + .into_iter() + .filter(|s| s.persist) + .collect(), }; let mut err = std::io::stderr().lock(); let mut kept = Vec::new(); diff --git a/src/bench.rs b/src/bench.rs index 56ffdc2..8db872f 100644 --- a/src/bench.rs +++ b/src/bench.rs @@ -55,8 +55,12 @@ pub fn run( out: &Out, ) -> Result<()> { let services = Arc::new(Services::load()?); - let sources = - select(&selection.only, &selection.exclude, &selection.categories); + let sources = select( + &selection.only, + &selection.include, + &selection.exclude, + &selection.categories, + ); let queries: Vec = if queries.is_empty() { DEFAULT_QUERIES.iter().map(|q| (*q).to_owned()).collect() } else { diff --git a/src/cli.rs b/src/cli.rs index 8fee9ee..e2c49cc 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -129,8 +129,7 @@ pub struct Cli { /// Which sources to ask, shared by `search` and `bench`. #[derive(Args, Clone, Debug, Default)] pub struct Selection { - /// Only these sources, comma-separated (see `dataseek sources`). Naming - /// a source is the only way to ask an opt-in one. + /// Only these sources, comma-separated (see `dataseek sources`). #[arg( short = 's', long = "source", @@ -141,6 +140,16 @@ pub struct Selection { )] pub only: Vec, + /// Also ask these sources, comma-separated, opt-in ones included. + #[arg( + long, + value_name = "IDS", + value_delimiter = ',', + value_parser = source_ids(), + hide_possible_values = true + )] + pub include: Vec, + /// Leave these sources out, comma-separated. #[arg( short = 'x', @@ -319,7 +328,17 @@ pub enum Command { --json prints. stdout carries protocol messages only; narration \ goes to stderr." )] - Mcp, + Mcp { + /// Also ask these sources, opt-in ones included, in every search + /// that names no sources of its own. + #[arg( + long, + value_name = "IDS", + value_delimiter = ',', + value_parser = source_ids() + )] + include: Vec, + }, /// Time every source on real queries and measure their overlap. #[command( diff --git a/src/find.rs b/src/find.rs index 3ac2a81..7996253 100644 --- a/src/find.rs +++ b/src/find.rs @@ -83,6 +83,7 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { query: query.clone(), sources: select( &selection.only, + &selection.include, &selection.exclude, &selection.categories, ), diff --git a/src/lib.rs b/src/lib.rs index 81900ea..f88a25e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -113,7 +113,7 @@ pub fn main() -> ExitCode { Err(err) => return usage(&err, &early), }; - if matches!(cli.command, Some(Command::Mcp)) { + if matches!(cli.command, Some(Command::Mcp { .. })) { sigpipe_kills.store(false, Ordering::Relaxed); } let out = Out::resolve(&cli); @@ -266,12 +266,13 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { } inspect::run(&url, out)?; } - Command::Mcp => mcp::run( + Command::Mcp { include } => mcp::run( &mcp::Globals { quiet: cli.quiet, verbose: cli.verbose, cache_dir: cli.cache_dir, connect_timeout: cli.connect_timeout, + include, }, out, )?, diff --git a/src/mcp.rs b/src/mcp.rs index 31759c4..e5430e4 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -111,7 +111,7 @@ impl Server<'_> { if stdin.read_until(b'\n', &mut line)? == 0 { return Ok(()); } - match handle(&line) { + match handle(&line, &self.globals.include) { Reply::Now(response) => self.send(&response)?, Reply::Call { id, argv } => match self.start(&id, &argv) { Ok(serial) => { @@ -242,7 +242,7 @@ fn end(mut call: Call) { /// Decide what one line asks for. Pure, so every protocol rule is a unit /// test. -fn handle(line: &[u8]) -> Reply { +fn handle(line: &[u8], include: &[String]) -> Reply { if line.trim_ascii().is_empty() { return Reply::Nothing; } @@ -297,11 +297,16 @@ fn handle(line: &[u8]) -> Reply { None, )); } - respond(id, method, params) + respond(id, method, params, include) } /// Answer a well-formed request. -fn respond(id: &Value, method: &str, params: &Map) -> Reply { +fn respond( + id: &Value, + method: &str, + params: &Map, + include: &[String], +) -> Reply { if let Some(refusal) = check_meta(id, params) { return Reply::Now(refusal); } @@ -320,7 +325,7 @@ fn respond(id: &Value, method: &str, params: &Map) -> Reply { ), Err(e) => error(id, INTERNAL_ERROR, &e.to_string(), None), }), - "tools/call" => call(id, params), + "tools/call" => call(id, params, include), other => Reply::Now(error( id, METHOD_NOT_FOUND, @@ -357,7 +362,7 @@ fn check_meta(id: &Value, params: &Map) -> Option { None } -fn call(id: &Value, params: &Map) -> Reply { +fn call(id: &Value, params: &Map, include: &[String]) -> Reply { let Some(name) = params.get("name").and_then(Value::as_str) else { return Reply::Now(error( id, @@ -387,12 +392,31 @@ fn call(id: &Value, params: &Map) -> Reply { )); } }; - match tools::argv(tool, arguments) { + let arguments = defaults(tool, arguments, include); + match tools::argv(tool, &arguments) { Ok(argv) => Reply::Call { id: id.clone(), argv }, Err(e) => Reply::Now(complete(id, tools::failed(&Failure::of(&e)))), } } +/// A search that names no sources of its own gets the `--include` sources +/// the server was started with, so a client can register an opt-in one once. +fn defaults( + tool: &str, + arguments: &Map, + include: &[String], +) -> Map { + let mut arguments = arguments.clone(); + if tool == "search" + && !include.is_empty() + && !arguments.contains_key("source") + && !arguments.contains_key("include") + { + arguments.insert("include".into(), json!(include)); + } + arguments +} + fn supported() -> Vec<&'static str> { std::iter::once(CURRENT).chain(HANDSHAKE).collect() } @@ -463,7 +487,7 @@ mod tests { use super::*; fn now(line: &str) -> Value { - match handle(line.as_bytes()) { + match handle(line.as_bytes(), &[]) { Reply::Now(response) => response, other => panic!("expected an answer, got {other:?}"), } @@ -488,6 +512,7 @@ mod tests { verbose: 0, cache_dir: None, connect_timeout: 1, + include: Vec::new(), }; let server = Server { stdout: Mutex::new(AutoStream::never(io::stdout())), @@ -513,7 +538,10 @@ mod tests { fn malformed_messages_get_the_json_rpc_codes() { assert_eq!(now("{not json")["error"]["code"], PARSE_ERROR); assert!(matches!( - handle(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"\xff\"}"), + handle( + b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"\xff\"}", + &[], + ), Reply::Now(response) if response["error"]["code"] == PARSE_ERROR )); for nameless in [ @@ -552,12 +580,13 @@ mod tests { ]; for line in silent { assert!( - matches!(handle(line.as_bytes()), Reply::Nothing), + matches!(handle(line.as_bytes(), &[]), Reply::Nothing), "{line}" ); } let cancel = handle( br#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"a"}}"#, + &[], ); assert!(matches!(cancel, Reply::Cancel(id) if id == "a")); } @@ -641,8 +670,40 @@ mod tests { let text = refused["result"]["content"][0]["text"].as_str().unwrap(); assert!(text.contains("always has a deadline"), "{text}"); assert!(matches!( - handle(request("tools/call", &json!({"name": "sources"})).as_bytes()), + handle( + request("tools/call", &json!({"name": "sources"})).as_bytes(), + &[] + ), Reply::Call { argv, .. } if argv == ["sources", "--json"] )); } + + #[test] + fn a_search_that_names_no_sources_gets_the_servers_include() { + let include = ["google".to_owned(), "mendeley".to_owned()]; + let call = |arguments: Value| { + let params = json!({"name": "search", "arguments": arguments}); + match handle(request("tools/call", ¶ms).as_bytes(), &include) { + Reply::Call { argv, .. } => argv, + other => panic!("expected a call, got {other:?}"), + } + }; + let default = call(json!({"query": "rainfall"})); + assert!( + default.contains(&"--include=google".to_owned()), + "{default:?}" + ); + assert!( + default.contains(&"--include=mendeley".to_owned()), + "{default:?}" + ); + let chosen = call(json!({"query": "rainfall", "source": ["zenodo"]})); + assert!( + chosen.iter().all(|word| !word.starts_with("--include")), + "{chosen:?}" + ); + let own = call(json!({"query": "rainfall", "include": ["kaggle"]})); + assert!(own.contains(&"--include=kaggle".to_owned()), "{own:?}"); + assert!(own.iter().all(|word| word != "--include=google"), "{own:?}"); + } } diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index 61fdadf..e9fa713 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -42,6 +42,8 @@ pub struct Globals { pub verbose: u8, pub cache_dir: Option, pub connect_timeout: u64, + /// `--include`: what a search that names no sources of its own gets. + pub include: Vec, } #[derive(Debug, thiserror::Error)] diff --git a/src/sources.rs b/src/sources.rs index a0829c5..156c2d6 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -292,17 +292,20 @@ impl Source { } /// The registry rows to ask: the named ones (or all but the opt-in ones), -/// narrowed to the given categories, minus exclusions, in registry order. An -/// opt-in source is asked only when named. Ids were validated by clap. +/// narrowed to the given categories, minus exclusions, in registry order. A +/// source is named by `-s` or by `--include`, and an opt-in source is asked +/// only when named. Ids were validated by clap. pub fn select( only: &[String], + include: &[String], exclude: &[String], categories: &[Category], ) -> Vec<&'static Source> { SOURCES .iter() .filter(|s| { - let named = only.iter().any(|id| id == s.id); + let named = only.iter().any(|id| id == s.id) + || include.iter().any(|id| id == s.id); named || (only.is_empty() && s.opt_in.is_none()) }) .filter(|s| categories.is_empty() || categories.contains(&s.category)) @@ -1191,16 +1194,39 @@ mod tests { #[test] fn an_opt_in_source_is_asked_only_when_named() { - let everyone = select(&[], &[], &[]); + let everyone = select(&[], &[], &[], &[]); assert!(everyone.iter().all(|s| s.opt_in.is_none())); for id in ["google", "mendeley"] { assert!(everyone.iter().all(|s| s.id != id), "{id}"); - assert_eq!(select(&[id.to_owned()], &[], &[]).len(), 1, "{id}"); + assert_eq!( + select(&[id.to_owned()], &[], &[], &[]).len(), + 1, + "{id}" + ); + let included = select(&[], &[id.to_owned()], &[], &[]); + assert_eq!(included.len(), everyone.len() + 1, "{id}"); + assert!(included.iter().any(|s| s.id == id), "{id}"); } - let aggregators = select(&[], &[], &[Category::Aggregator]); + let aggregators = select(&[], &[], &[], &[Category::Aggregator]); assert!(aggregators.iter().all(|s| s.id != "google")); } + /// `--include` adds to whatever the selection says, and the filters the + /// rest of the command applies still narrow it. + #[test] + fn an_included_source_joins_the_selection() { + let with_zenodo = + select(&["zenodo".to_owned()], &["google".to_owned()], &[], &[]); + let ids: Vec<&str> = with_zenodo.iter().map(|s| s.id).collect(); + assert_eq!(ids, ["google", "zenodo"]); + let excluded = + select(&[], &["google".to_owned()], &["google".to_owned()], &[]); + assert!(excluded.iter().all(|s| s.id != "google")); + let research = + select(&[], &["google".to_owned()], &[], &[Category::Research]); + assert!(research.iter().all(|s| s.id != "google")); + } + fn catalog(list: Listing) -> Source { listed("fake", "Fake", Research, "test", "https://x.org", list) } diff --git a/tests/cli.rs b/tests/cli.rs index 719b5c7..8624120 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -126,6 +126,16 @@ fn result_titles(stdout: &[u8]) -> Vec { .collect() } +/// The sources a `search --json` report says it asked, in order. +fn source_ids(report: &Value) -> Vec<&str> { + report["sources"] + .as_array() + .unwrap() + .iter() + .map(|s| s["id"].as_str().unwrap()) + .collect() +} + #[test] fn version_matches_manifest() { bin() @@ -592,6 +602,43 @@ fn opt_in_sources_are_marked_in_the_listing_and_doctor() { assert!(doctor.contains("opt-in mendeley"), "{doctor}"); } +// `--include` asks an opt-in source beside the rest; without it, ADR 0013 +// keeps the source out of the run. +#[test] +fn include_asks_an_opt_in_source_beside_the_others() { + let mut with = bin(); + seed_rainfall(&with.cache()); + let out = with + .args([ + "search", + "rainfall", + "--offline", + "--json", + "--include", + "google,mendeley", + ]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let ids = source_ids(&report); + assert!(ids.contains(&"google"), "{ids:?}"); + assert!(ids.contains(&"mendeley"), "{ids:?}"); + + let mut without = bin(); + seed_rainfall(&without.cache()); + let out = without + .args(["search", "rainfall", "--offline", "--json"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let ids = source_ids(&report); + assert!(!ids.contains(&"google"), "{ids:?}"); + assert!(!ids.contains(&"mendeley"), "{ids:?}"); + assert!(ids.contains(&"openml"), "{ids:?}"); +} + #[test] fn sources_shows_the_notices_fred_and_census_require() { let text = stdout_text(&["sources"]); @@ -1617,11 +1664,22 @@ struct Mcp { impl Mcp { /// Every request the server or its children send goes to `proxy`. fn start(dir: &Path, proxy: &str) -> Self { - Self::start_as(Path::new(env!("CARGO_BIN_EXE_dataseek")), dir, proxy) + Self::start_as( + Path::new(env!("CARGO_BIN_EXE_dataseek")), + dir, + proxy, + &[], + ) } - /// The server as `program`, a copy of the binary under test. - fn start_as(program: &Path, dir: &Path, proxy: &str) -> Self { + /// The server as `program`, a copy of the binary under test, started + /// with `args` after `mcp`. + fn start_as( + program: &Path, + dir: &Path, + proxy: &str, + args: &[&str], + ) -> Self { use std::io::BufRead; use std::process::Stdio; @@ -1629,6 +1687,7 @@ impl Mcp { .env("HTTPS_PROXY", proxy) .env("HTTP_PROXY", proxy) .arg("mcp") + .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -1867,6 +1926,37 @@ fn an_mcp_client_drives_a_whole_session_over_stdio() { assert!(stderr.contains("searching 1 source"), "{stderr}"); } +// A server started with `--include` asks those sources in every search a +// call leaves to the defaults, and leaves a call that names its own alone. +#[test] +fn a_server_wide_include_reaches_searches_that_do_not_choose() { + let dir = tempfile::tempdir().unwrap(); + seed_rainfall(&dir.path().join("cache").join("dataseek")); + let mut mcp = Mcp::start_as( + Path::new(env!("CARGO_BIN_EXE_dataseek")), + dir.path(), + "http://127.0.0.1:9", + &["--include", "google,mendeley"], + ); + + let search = + mcp.call(1, "search", json!({ "query": "rainfall", "offline": true })); + assert_eq!(search["isError"], false, "{search}"); + let ids = source_ids(&search["structuredContent"]); + assert!(ids.contains(&"google"), "{ids:?}"); + assert!(ids.contains(&"mendeley"), "{ids:?}"); + + let chosen = mcp.call( + 2, + "search", + json!({ "query": "rainfall", "source": ["openml"], "offline": true }), + ); + assert_eq!(chosen["isError"], false, "{chosen}"); + assert_eq!(source_ids(&chosen["structuredContent"]), ["openml"]); + + mcp.close(); +} + // The stateless revision: no handshake, every request names its version. #[test] fn an_mcp_client_on_the_current_revision_needs_no_handshake() { @@ -1985,7 +2075,8 @@ fn an_mcp_server_keeps_working_after_its_binary_is_replaced() { let dir = tempfile::tempdir().unwrap(); let program = dir.path().join("dataseek"); std::fs::copy(env!("CARGO_BIN_EXE_dataseek"), &program).unwrap(); - let mut mcp = Mcp::start_as(&program, dir.path(), "http://127.0.0.1:9"); + let mut mcp = + Mcp::start_as(&program, dir.path(), "http://127.0.0.1:9", &[]); assert_eq!( mcp.ask(1, "ping", json!({}))["result"]["resultType"], "complete" From 386ff88c8922cd316b7416c72b8e5df244d950a1 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:48:36 +0100 Subject: [PATCH 02/31] doc: add a dataseek agent skill for searching, inspecting and setting up over MCP or the CLI --- README.md | 7 + docs/reference/contract.md | 2 +- skills/dataseek/SKILL.md | 124 +++++++++++++++++ skills/dataseek/references/cli.md | 103 +++++++++++++++ skills/dataseek/references/inspect.md | 67 ++++++++++ skills/dataseek/references/search.md | 146 +++++++++++++++++++++ skills/dataseek/references/setup.md | 102 ++++++++++++++ skills/dataseek/references/troubleshoot.md | 95 ++++++++++++++ 8 files changed, 645 insertions(+), 1 deletion(-) create mode 100644 skills/dataseek/SKILL.md create mode 100644 skills/dataseek/references/cli.md create mode 100644 skills/dataseek/references/inspect.md create mode 100644 skills/dataseek/references/search.md create mode 100644 skills/dataseek/references/setup.md create mode 100644 skills/dataseek/references/troubleshoot.md diff --git a/README.md b/README.md index f9b7333..f8776f1 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,13 @@ Use it in the terminal, pipe its JSON into scripts, or use dataseek via MCP (`ds Each tool returns what its command prints with `--json`; keys are read from the environment the client starts it in, or from `credentials.toml`. Google Dataset Search and Mendeley Data stay opt-in here too: the model asks for them by naming them in the search tool's `source` argument, and a client can ask for them on every search with `"args": ["mcp", "--include", "google,mendeley"]`. See: [`docs/reference/contract.md`](docs/reference/contract.md#mcp-mode). +## Agent skill +[`skills/dataseek`](skills/dataseek/SKILL.md) teaches a coding agent to use dataseek over MCP or the CLI: writing queries the sources match, reading coverage and source statuses, inspecting a dataset's files, registering the server and its keys, and recovering from each error. Install it with the [skills CLI](https://github.com/vercel-labs/skills): + +```sh +pnpm dlx skills add lmarkmann/dataseek +``` + ## Contributing & Development Docs - [`CONTRIBUTING.md`](CONTRIBUTING.md) covers setup, the commit prefixes that decide each release, the test rules and how to add a source. Report vulnerabilities privately, as [`SECURITY.md`](docs/SECURITY.md) describes. - [`docs/CHANGELOG.md`](docs/CHANGELOG.md): what shipped, written by release-plz. diff --git a/docs/reference/contract.md b/docs/reference/contract.md index 3cf7c04..6adfe8e 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -148,7 +148,7 @@ indicatif parses its color token with `console::Style::from_dotted_str`, which u ## Extending the CLI -Add a subcommand by adding a variant to `Command` in `src/cli.rs`, a match arm in `run()` in `src/lib.rs`, its name in `COMMANDS` and, unless it is hidden like `man`, a line in `GROUPS` in `src/help.rs`. Keep one domain per tool; prefer support subcommands (`doctor`, `cache`) over piling flags onto the root. Add a test in `tests/cli.rs` for every behavior you add, and give a command that takes arguments people get wrong at most three examples, and add its `-h` to the list `every_example_in_help_and_readme_parses` reads. +Add a subcommand by adding a variant to `Command` in `src/cli.rs`, a match arm in `run()` in `src/lib.rs`, its name in `COMMANDS` and, unless it is hidden like `man`, a line in `GROUPS` in `src/help.rs`. Keep one domain per tool; prefer support subcommands (`doctor`, `cache`) over piling flags onto the root. Add a test in `tests/cli.rs` for every behavior you add, and give a command that takes arguments people get wrong at most three examples, and add its `-h` to the list `every_example_in_help_and_readme_parses` reads. A change to a flag, a tool argument, a status label, an error message or a `--json` key also changes what `skills/dataseek/references/` teaches agents; update the file that names it in the same change. A flag that takes one of a fixed set of values names them in its own help, as `Colorize output (auto, always, or never)` does, because `-h` does not list them. Build the command through `cli::command()`, never `Cli::command()` directly: it hides clap's `[possible values: ...]` list from `-h` and moves each value's meaning, taken from the `ValueEnum` doc comments, into the long help `--help` shows. The man page alone builds from the plain definition, so roff draws its own list of values. diff --git a/skills/dataseek/SKILL.md b/skills/dataseek/SKILL.md new file mode 100644 index 0000000..8c5c0fc --- /dev/null +++ b/skills/dataseek/SKILL.md @@ -0,0 +1,124 @@ +--- +name: dataseek +description: > + Not for papers or citations, not for reading rows inside one dataset, not + for downloading or converting data files, and not for changing dataseek's + own code or source adapters. Finds datasets across 76 archives at once + (Hugging Face, Kaggle, Zenodo, Dataverse, data.gov, data.europa.eu, IMF, + OECD, ECB, NASA, Copernicus, GEO and more) through dataseek: its MCP + server's search, sources and inspect tools, or the dsk CLI with --json. + Use on "find a dataset on", "is there open data about", "where can I get + data for", "search Kaggle and Hugging Face for", "what files and license + does this dataset have", "add dataseek to my MCP client", "which API keys + does dataseek need", and when a dsk command or dataseek tool call fails, + skips a source or returns nothing. +compatibility: needs the dataseek binary (dsk) and network access +--- + +# dataseek + +dataseek sends one query to every dataset source it knows, merges the records that are one dataset (a shared DOI, landing URL, or title and publisher) and ranks them by how many sources agree and how much of the query each covers. It runs as an MCP server (`dsk mcp`, three tools) and as a CLI (`dsk`, also installed as `dataseek`). They are one program: a tool returns, byte for byte, the object `dsk --json` prints, so every reference here holds for both. + +**Pick the surface once per task.** If the tool list holds the dataseek server's `search`, `sources` and `inspect` tools, call them. Otherwise, with a shell, run `dsk --json`. With neither, go to the Setup lane. Clients name the tools differently (`search`, `dataseek.search`, `mcp__dataseek__search`); the server is `dataseek`. + +## Output contract + +Each lane ends in something the user can check without rerunning it. + +Search lane: +Leaves behind: the final message, in three parts in this order +Sections: Datasets, Coverage, Queries + +- **Datasets**: numbered, best first. Each carries the title, the URL and the sources that hold it, then license, last update, DOI and size when the result has them. Every value comes from the result object; a field the result lacks is left out, never guessed. +- **Coverage**: one line from the result: how many sources answered, whether `complete` was true, and each relevant source that failed, was skipped or was not waited for, with its `status` as dataseek wrote it. +- **Queries**: every query run, as the `dsk search ...` command that reproduces it. + +Inspect lane: +Leaves behind: the final message, in three parts in this order +Sections: Metadata, Files, Not stated + +Setup lane: +Leaves behind: the client's MCP entry for dataseek, and the count of sources one `sources` call returned +Sections: Config, Verified + +Troubleshoot lane: +Leaves behind: the final message, quoting the error or status verbatim +Sections: Diagnosis, Fix, Result + +Forbidden: [A-Z_]*(TOKEN|API_KEY)=[^\s$"'{] +Forbidden: (-s |--source[ =]|"source"\s*:\s*\[)[^\]\n]*\b(google|mendeley)\b +Forbidden: \bdsk (s|search|sources|inspect)\b(?:(?!--json)[^|\n])*\| + +The exemptions are under Iron rules. + +## Lanes + +| Task smells like | Lane | Open | +|---|---|---| +| "find a dataset on", "is there data about", "on Hugging Face or Kaggle", a topic with no dataset named yet (default) | Search | `references/search.md` | +| a dataset URL handed over, "what files does it have", "what license", "how big", "what format" | Inspect | `references/inspect.md` | +| install dataseek, add it to an MCP client, "the tools do not show up", API keys, credentials | Setup | `references/setup.md` | +| an `Error:` with a `Try:` line, `isError: true`, a source skipped or not waited for, no results, offline, certificate errors | Troubleshoot | `references/troubleshoot.md` | +| a shell script, a pipeline, `jq`, exit codes, CI, many queries in a loop | Script | `references/cli.md` | + +Default when ambiguous: **Search**. A search the user will choose from runs Search, then Inspect on the two or three candidates they care about. A failed call in any lane moves to Troubleshoot for that call only, then back. + +## Search (default) + +1. **Write one to three short queries**, two to four content words each, before calling anything. Most sources match every word, so a sentence finds fewer datasets than its keywords: "sea surface temperature" merged 328 results where "global monthly sea surface temperature dataset since 1980" merged 136 (2026-10-20). Years, regions and formats are filters to apply to the results, not query words. The rules and the evidence: `references/search.md`, Writing queries. +2. **Narrow only on the user's words.** A named archive becomes `source`; a clear domain becomes `category`; a source flooding the list becomes `exclude`. The ids and the fourteen categories: `references/search.md`, Arguments. +3. **Call `search`** and read `results`, then `complete` and `sources[].status`. An empty `results` list from sources that answered is an answer, not a failure. +4. **Reformulate when fewer than about five results fit**: a synonym, the field's own term or acronym, one word dropped. Stop after three rounds and say what was tried. +5. **Answer in the Search shape above.** Ranks and `score` order one search only; never compare scores across searches. + +## Inspect + +Call `inspect` with the result's landing page URL. It reads the page's schema.org Dataset markup (Croissant for Hugging Face) and lists the files the page declares; it downloads nothing. When it answers `carries no schema.org Dataset markup` and the result has a DOI, try `https://doi.org/` once, then say the page publishes no metadata and give its URL. Which archives publish markup, the JSON shape, and the answer shape: `references/inspect.md`. + +## Setup + +Check `dsk -V` first, then register `{"command": "dsk", "args": ["mcp"]}` under the client's MCP servers and verify with one `sources` call. Install commands, the absolute-path and `uvx` variants, the stdin handshake probe, keys and `credentials.toml`: `references/setup.md`. + +## Troubleshoot + +Quote the `Error:`, `Cause:` and `Try:` lines (or the source's `status`) exactly, follow the `Try:` line first, and rerun once. Every refusal, exit code and status with its fix: `references/troubleshoot.md`. + +## Script + +`dsk --json` prints one object on stdout tagged with its `schema`; narration and errors go to stderr as `dataseek-events/1` lines. Run pipelines under `set -o pipefail`, since `jq` exits 0 on the empty stdout of a failed run. Recipes, exit codes, variables and `dsk help --json`: `references/cli.md`. + +## Boundaries + +- Owns: finding datasets with dataseek, reading one dataset page's metadata and file list with `inspect`, installing and registering dataseek, its keys and cache, and reading its errors. +- Does not own: papers, citations and authors (a scholarly search tool); rows, columns or statistics inside one dataset (the archive's own API, such as the Hugging Face Dataset Viewer); downloading, converting or loading files; changing dataseek's code or a source adapter (the repository's `CONTRIBUTING.md` and `docs/`). +- `dsk bench` sends queries x sources requests and skips the cache. It is a maintainer's tool: run it only when the user asks for it by name. + +## Reference map + +| File | Contents | +|---|---| +| `references/search.md` | Arguments on both surfaces, source ids and categories, writing queries, reading results and statuses, opt-in sources, more results | +| `references/inspect.md` | What `inspect` reads, its JSON shape, which archives publish markup, the DOI fallback, the answer shape | +| `references/setup.md` | Install, MCP registration, the handshake probe, keys and `credentials.toml`, cache warm-up | +| `references/troubleshoot.md` | Tool refusals, protocol errors, exit codes, whole-search failures, per-source statuses and their fixes | +| `references/cli.md` | Commands, global flags, variables, JSON schemas, stderr events, `jq` recipes, batches | + +## Learning loop + +When dataseek behaves differently from this skill, dataseek wins: read the live surface (`tools/list`, or `dsk help --json`), follow it, and add one line to the final message naming the statement here that was wrong, so the user can report it at https://github.com/lmarkmann/dataseek/issues. + +## Iron rules + +1. **One surface per task**, MCP tools when listed, `dsk ... --json` otherwise. Never parse the text output; it wraps and truncates for a terminal. +2. **Every URL, DOI, license, size and date in an answer appears in a tool result.** dataseek returns records, not judgments about them; a field it did not return is "not stated". +3. **Google Dataset Search (`google`) and Mendeley Data (`mendeley`) only when the user names them.** Neither permits automated searches. Before a Mendeley search, tell the user its terms bar automated access without written permission. +4. **Keys never travel in an argument, a command line or a project file.** No tool takes one. They live in the environment the server starts in or in `credentials.toml` with mode 600. +5. **`complete: false` is reported, not hidden.** Name the sources it did not wait for; when one matters, search again with `source` set to it, which gives it the whole timeout. +6. **An argument you are unsure of is read from the live schema** (`tools/list`, or `dsk help search --json`), never guessed from memory; a bad argument is refused by name. +7. **At most four tool calls at once.** A fifth is refused as busy. + +| Boundary | Forbidden token | Exemption | +|---|---|---| +| Rule 4, keys | a literal assignment such as `HF_TOKEN=hf_x` in a command | `export HF_TOKEN="$()"`, which carries no literal | +| Rule 3, opt-in sources | `google` or `mendeley` in `source` or `-s` | the user named Google Dataset Search or Mendeley Data in this task | +| Rule 1, text output | `dsk search ...` piped without `--json` | a human reading through a pager, `dsk search ... \| less -R` | diff --git a/skills/dataseek/references/cli.md b/skills/dataseek/references/cli.md new file mode 100644 index 0000000..bab0301 --- /dev/null +++ b/skills/dataseek/references/cli.md @@ -0,0 +1,103 @@ +# CLI and scripts + +Verified against `docs/reference/contract.md`, `dsk help --json`, `dsk help environment`, `dsk help exit-codes` and live runs on 2026-10-20. Every `jq` recipe below was run against real output that day. + +## Contents + +- **Commands**: which command does what, and which ones change state +- **Flags and variables**: the global flags, the `DATASEEK_*` variables and their precedence +- **Streams and schemas**: what reaches stdout, what reaches stderr, and the schema tags +- **Recipes**: `jq` for the questions scripts ask most +- **Batches**: many queries, one merged list, without hammering the sources +- **Discovering the surface**: reading flags from the binary instead of from memory + +## Commands + +| Command | Does | State it changes | +|---|---|---| +| `dsk search ` (alias `dsk s`) | the merged, ranked search | the query cache | +| `dsk sources` | every source: id, category, protocol, key status, docs | none | +| `dsk inspect ` | one page's metadata and file list | none | +| `dsk doctor` | config, cache and state paths, color, every key's status | none | +| `dsk cache info` | cache path, size and budget | none | +| `dsk cache warm [-s ids] [--dry-run]` | download the catalogs now, with no deadline | the catalog cache | +| `dsk cache clear [--dry-run]` | delete every cached answer and catalog | deletes the cache; show `--dry-run` and ask first | +| `dsk mcp` | the MCP server on stdio | none | +| `dsk bench [queries]` | time every source; sends queries x sources requests, uncached | none, but heavy on the sources; only when asked by name | +| `dsk help [command \| environment \| exit-codes]` | help; `--json` describes the whole surface | none | +| `dsk completion `, `dsk man` | a completion script, the man page | none | + +## Flags and variables + +Global flags, valid with every command: `--json`, `-q`/`--quiet` (errors only on stderr), `-v`/`--verbose` (repeatable), `--color auto|always|never`, `--no-color`, `--plain` (ASCII, no color), `--no-progress`, `--cache-dir DIR`, `--connect-timeout SECS`. + +`search` flags: `-s/--source`, `-x/--exclude`, `-c/--category` (comma-separated), `-n/--limit` (20), `--per-source` (10, at most 100), `--sort relevance|newest`, `--refresh`, `--offline`, `--timeout SECS` (20; 0 waits for every source). Their meaning is the MCP argument table in `references/search.md`. + +A flag beats its variable, which beats the default: + +| Variable | Sets | +|---|---| +| `DATASEEK_LIMIT`, `DATASEEK_PER_SOURCE`, `DATASEEK_TIMEOUT`, `DATASEEK_EXCLUDE` | the `search` flags of the same name | +| `DATASEEK_CACHE_DIR`, `DATASEEK_CONNECT_TIMEOUT` | the global flags of the same name | +| `DATASEEK_CACHE_MAX_MB` | the cache budget, 1 to 10000, 30 by default | +| `NO_COLOR`, `CLICOLOR_FORCE`, `COLUMNS` | color and width of text output | +| `ALL_PROXY`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | the proxy | +| `SSL_CERT_FILE`, `SSL_CERT_DIR` | Linux root certificates | + +A script that must not inherit a user's `DATASEEK_TIMEOUT=0` or `DATASEEK_EXCLUDE` passes the flag explicitly. Key variables are in `references/setup.md`, Keys. + +## Streams and schemas + +- **stdout is data.** With `--json`, one object, indented on a terminal and one line in a pipe, tagged with `schema`: `dataseek-search/1`, `dataseek-sources/1`, `dataseek-inspect/1`, `dataseek-doctor/1`, `dataseek-cache-info/1`, `dataseek-cache-warm/1`, `dataseek-surface/1` (from `help --json`). A new key may appear without notice; a changed or removed one bumps the number, so a script can assert the tag. +- **stderr is status.** With `--json`, each line is an event `{"schema": "dataseek-events/1", "event": ..., "message": ...}`: `stage` (what it is doing), `warning` (a source that failed, a stale catalog), `ok` (the summary, including the total match count), and `error` (with `causes` and `try`). `-q` leaves only the error. +- **A failed run prints nothing on stdout.** `jq` exits 0 on empty input, so run pipelines under `set -o pipefail` in bash and zsh, or check `$pipestatus[1]` in fish. +- **An empty search is success** (exit 0, `results: []`) when any source answered. Exit codes: `references/troubleshoot.md`. + +## Recipes + +```sh +set -o pipefail + +# one URL per line +dsk search census --json | jq -r '.results[].url' + +# title, URL and holding sources as TSV +dsk search census --json | jq -r '.results[] | [.title, .url, (.sources | join(","))] | @tsv' + +# only datasets more than one archive holds +dsk search sea surface temperature --json | jq '[.results[] | select(.sources | length > 1)]' + +# only Creative Commons licenses, as the sources write them (URL or name) +dsk search sea surface temperature --json \ + | jq '[.results[] | select((.license // "") | test("creativecommons|cc-?by|cc0"; "i"))]' + +# which sources did not answer, and why +dsk search sea surface temperature --json | jq -r '.sources[] | select(.answered | not) | "\(.id)\t\(.status)"' + +# fail the script when the search did not wait for every source +dsk search sea surface temperature --json | jq -e '.complete' > /dev/null + +# keep the events: warnings and the summary line with the total +dsk search ERSST --json 2> events.ndjson > results.json +jq -r 'select(.event == "warning" or .event == "ok") | .message' events.ndjson + +# every file link a dataset page declares +dsk inspect https://zenodo.org/records/13135140 --json | jq -r '.files[].url' +``` + +## Batches + +Run queries one after another; each search already fans out to every source, and the cache answers a repeat within 6 hours. Merge by URL afterwards: + +```sh +set -o pipefail +for q in "sea surface temperature" "ERSST"; do + dsk search "$q" -n 10 --json -q | jq -c --arg q "$q" '.results[] | {query: $q, title, url, sources}' +done | jq -s 'unique_by(.url)' +``` + +For a batch larger than a few dozen queries, set `HF_TOKEN` and `GITHUB_TOKEN` first: Hugging Face allows 500 requests per 5 minutes per address without a key, GitHub 10 searches a minute. + +## Discovering the surface + +`dsk help --json` (schema `dataseek-surface/1`) lists every command, flag (with `type`, `values`, `default`, `minimum`, `maximum`, `env`), variable and exit code, generated from the parser itself. `dsk help search --json` prints one command's entry. When this reference and that output disagree, the output is right. diff --git a/skills/dataseek/references/inspect.md b/skills/dataseek/references/inspect.md new file mode 100644 index 0000000..6edf258 --- /dev/null +++ b/skills/dataseek/references/inspect.md @@ -0,0 +1,67 @@ +# Inspect + +Verified against `src/inspect.rs`, `dsk help inspect --json` and live runs on 2026-10-20. + +`inspect` reads what one dataset page says about itself and the files it lists. It is enrichment for one result, not search: it reads one page and never fans out. + +## Arguments + +| MCP argument | CLI | Meaning | +|---|---|---| +| `url` (string, required) | the URL after `inspect` | the dataset's landing page, normally a search result's `url` | +| `offline` (boolean) | `--offline` | fail at once instead of reaching for the network | + +## What it reads + +- **Most pages:** every `application/ld+json` block holding a schema.org `Dataset`, at the top level, in an array or inside `@graph`. +- **Hugging Face:** the Hub's Croissant endpoint, because the page's HTML carries no metadata. Croissant adds `recordSet` (the columns) beside the schema.org fields. +- **Files:** the dataset's `distribution`, schema.org `DataDownload` and Croissant `FileObject` and `FileSet` entries. Nothing is downloaded; a size, format or checksum is whatever the page declares. + +## The result + +Schema `dataseek-inspect/1`, two keys: + +| Key | What it holds | +|---|---| +| `dataset` | the page's own JSON-LD node as the page wrote it: commonly `name`, `description`, `creator` or `author`, `publisher`, `license`, `datePublished`, `dateModified`, `identifier`, `keywords`, `distribution`, `size` or `contentSize` | +| `files` | dataseek's reading of the file list; each entry has whichever of `name`, `format`, `size_bytes`, `checksum` (`sha256:` or `md5:`), `url` and, for a Croissant file set, `includes` (the glob its files match, such as `plain_text/*/*.parquet`) the page gave | + +Keys in `dataset` vary by publisher and may carry a `schema:` prefix; read what is there rather than expecting a fixed set. An empty `files` list means the page declares no files, not that the dataset has none. + +## Which pages publish markup + +Observed 2026-10-20 on landing pages from an `air quality` search, one per source. Publishers change their pages, so treat this as the expected outcome, not a guarantee: + +| Outcome | Sources whose result URLs gave it | +|---|---| +| metadata and files | `zenodo`, `huggingface`, `kaggle`, `datagov`, `data-gov-au`, `dataverse-no`, `aws`, `cessda`, `dbnomics`, `modelscope`, `openaire` | +| `carries no schema.org Dataset markup` | `arcgis`, `b2find`, `cmr`, `dataone`, `earth-engine`, `europa`, `figshare`, `github`, `govdata`, `hdx`, `open-canada`, `opendatasoft`, `openml`, `osf` | +| `sent a challenge page instead of results` | `gbif` | + +## When it fails + +1. **`carries no schema.org Dataset markup`** with a `doi` on the result: inspect `https://doi.org/` once. The DOI resolves to the publisher's canonical page, which worked for a Zenodo DOI and failed for a Harvard Dataverse DOI on 2026-10-20. +2. **Still no markup:** say the page publishes no machine-readable metadata, give its URL, and list what the search result itself carried. Read the page with a web fetch tool only if the user wants more. +3. **`cannot fetch`** with `sent a challenge page instead of results`: the site blocks automated requests; give the URL for the user to open. +4. **A file URL or a search page** handed to `inspect` fails the same way as a page with no markup; pass the landing page. + +## After inspect + +dataseek downloads nothing. When the user wants a file, hand them its `url` with `size_bytes` and `format`, and, if they ask you to fetch it, check the size first and verify `checksum` after the download. Reading rows or columns inside the dataset is the archive's own API, not dataseek. + +## The answer + +```text +Metadata +Evaluation of the influence of rain on air surface temperature measurements +https://zenodo.org/records/13135140 +Publisher: Zenodo | License: CC BY 4.0 | Published 2024-07-30 | 8.19 MB + +Files (3) +1. text/csv https://zenodo.org/api/records/13135140/files/Dataset_reference.csv/content +2. ... + +Not stated: file names apart from the links, sizes per file, checksums +``` + +**Not stated** names the fields the user asked about that the page does not carry, so a missing license reads as missing rather than as overlooked. diff --git a/skills/dataseek/references/search.md b/skills/dataseek/references/search.md new file mode 100644 index 0000000..d60a872 --- /dev/null +++ b/skills/dataseek/references/search.md @@ -0,0 +1,146 @@ +# Search + +Verified against `tools/list`, `dsk help search --json`, `dsk sources --json` and live searches on 2026-10-20. + +## Contents + +- **Arguments**: which argument, on which surface, and when each one is worth setting +- **Source ids and categories**: what to put in `source`, `exclude` and `category` +- **Writing queries**: how long a query should be and what stays out of it +- **Reading the result**: what each field means and which ones an answer may quote +- **Source statuses**: which `status` values mean a gap in the results +- **Opt-in sources**: when Google Dataset Search and Mendeley Data may be asked +- **More, newer, fresher**: `limit`, `per-source`, `sort`, `refresh`, `offline` +- **The answer**: the Datasets, Coverage and Queries parts, filled in + +## Arguments + +The MCP tool's input schema is generated from the CLI's flags, so the names match: an MCP argument is the long flag without its dashes. Only `query` is required. + +| MCP argument | CLI | Default | Set it when | +|---|---|---|---| +| `query` (string) | the words after `search` | required | always; several words form one query | +| `source` (array of ids) | `-s a,b` | every default source | the user names an archive; also the only way to ask an opt-in source | +| `exclude` (array of ids) | `-x a,b` | none | one source floods the list with near-duplicates | +| `category` (array of names) | `-c a,b` | every category | the domain is unmistakable (economics, life-sciences) | +| `limit` (integer) | `-n N` | 20 | the user wants more or fewer merged results | +| `per-source` (1 to 100) | `--per-source N` | 10 | a source should contribute deeper results; costs paging on some sources | +| `sort` (`relevance`, `newest`) | `--sort newest` | `relevance` | the user asks for recent or recently updated data | +| `refresh` (boolean) | `--refresh` | false | the user needs answers newer than the 6-hour cache | +| `offline` (boolean) | `--offline` | false | no network, or a repeat over the cache only | +| `timeout` (1 to 300 seconds) | `--timeout N` | 20 | a slow source matters; the CLI also takes 0, wait for all, which MCP refuses | + +Over MCP, `source`, `exclude` and `category` are JSON arrays, `["zenodo", "figshare"]`, even though their descriptions say comma-separated: that wording is the CLI's. A string where an array belongs is refused with `` `source` takes a list of strings ``. + +`source` replaces the default set rather than adding to it. A search with `source: ["kaggle"]` asks Kaggle alone, and a named source gets the whole `timeout` and is asked even if it had an outage in the last ten minutes. + +## Source ids and categories + +The `sources` tool (or `dsk sources --json`) is the live list: id, name, category, protocol, key status and docs URL for each. As of 2026-10-20, by category; `*` marks a catalog source, whose whole list dataseek downloads weekly and searches locally: + +| Category | Sources | +|---|---| +| `aggregator` | `datacite`, `openaire`, `google` (opt-in), `b2find` | +| `code` | `github` | +| `ecology` | `gbif`, `dataone` | +| `economics` | `dbnomics`, `worldbank`*, `worldbank-microdata`, `imf`*, `oecd`*, `ilo`* | +| `finance` | `ecb`*, `bis`*, `fred`, `bundesbank`*, `fiscal-data`* | +| `geospatial` | `cmr`, `planetary-computer`*, `earth-search`*, `copernicus-dataspace`*, `copernicus-cds`*, `earth-engine`*, `ncei`, `pangaea` | +| `government` | `europa`, `datagov`, `data-gov-uk`, `open-canada`, `data-gov-au`, `govdata`, `hdx`, `socrata`, `socrata-eu`, `opendatasoft`, `arcgis` | +| `life-sciences` | `geo`, `arrayexpress`, `biostudies`, `omicsdi`, `cellxgene`*, `synapse` | +| `machine-learning` | `huggingface`, `kaggle`, `openml`*, `uci`*, `roboflow`, `modelscope`, `aws`*, `tfds`* | +| `neuroscience` | `openneuro`*, `dandi`, `physionet`* | +| `physics` | `cern`, `materials-project`*, `nomad`* | +| `research` | `zenodo`, `figshare`, `harvard-dataverse`, `borealis`, `recherche-data-gouv`, `dataverse-nl`, `dataverse-no`, `osf`, `mendeley` (opt-in) | +| `social-science` | `cessda` | +| `statistics` | `ihsn`, `fao-microdata`, `unhcr-microdata`, `eurostat`*, `undata`*, `datacommons`, `owid`, `census`*, `who`* | + +Map the user's words to ids before narrowing: "Hugging Face" is `huggingface`, "data.gov" is `datagov`, "the World Bank" is `worldbank` (indicators) plus `worldbank-microdata` (surveys), "NASA Earthdata" is `cmr`, "Earth Engine" is `earth-engine`. An id outside this list is refused with the list of valid ones. + +A category is a coarse filter. Aggregators such as `datacite` and `openaire` index most research repositories and sit in `aggregator`, so a `category: ["life-sciences"]` search leaves them out; add them with a second, unfiltered search when recall matters more than focus. + +## Writing queries + +Each source runs its own search engine and most of them require every word to match: the catalog sources need every word as a token prefix, PANGAEA, CESSDA and ModelScope need every word, Socrata needs all of up to three terms, and Hugging Face matches words against the repository id only. So every word added is a filter at most sources. + +Measured 2026-10-20 over the default sources: "sea surface temperature" merged 328 results; "global monthly sea surface temperature dataset since 1980" merged 136. + +- **Two to four content words.** Drop "dataset", "data", "open", "about", "find me". +- **Constraints stay out of the query.** Years, regions, file formats and licenses filter the results afterwards (`updated`, `description`, `license`), or become a second query when they are the topic ("Kenya census"). A year in the query also weighs heavily in the ranking, because rare tokens count most, so "since 2000" lifts tables that merely contain "2000". +- **Use the field's own words and acronyms** as alternative queries: "SST" or "ERSST" beside "sea surface temperature", "scRNA-seq" beside "single cell RNA", "CPI" beside "consumer prices". +- **One concept per query.** "air quality" and "asthma admissions" are two searches whose results the answer joins, not one query that few datasets match on both. +- **English first.** Most sources index English metadata; `europa` matches across EU languages, and a national portal (`govdata`, `recherche-data-gouv`) may answer better in its own language. +- **Run independent queries in parallel**, at most four calls at once over MCP. + +## Reading the result + +`search` returns one object, schema `dataseek-search/1`: + +| Key | What it holds | +|---|---| +| `query` | the query as searched | +| `complete` | false when the search stopped waiting for a source or a catalog was still downloading, so results from those are missing | +| `results` | the merged datasets, best first, at most `limit` | +| `sources` | one entry per source asked: `id`, `status`, `answered`, `results` (how many it returned), `ms` | + +Each result: + +| Field | Meaning and use | +|---|---| +| `title`, `url` | always present; `url` is the landing page, the one to give the user and to pass to `inspect` | +| `sources` | every source that holds this dataset; more than one means independent archives agree it exists | +| `description` | cut to a few hundred characters; quote it as a summary, not as the whole record | +| `publisher`, `doi`, `license`, `updated`, `size_bytes` | present only when a source supplied them; `license` is a name or a URL as the source wrote it | +| `popularity` | downloads, votes or stars as one source counts them; compare only between results from the same source | +| `aliases` | other identifiers of the same dataset (a concept DOI, a mirror URL), used for merging | +| `score` | the rank score inside this one search; meaningless across searches and not a probability | + +Several results with the same title from one source are different datasets (one per country, year or version), because only records from different sources merge on title. Tell them apart by URL and description. + +## Source statuses + +`sources[].status` says why a source did or did not contribute: + +| Status | Answered | Meaning | +|---|---|---| +| `ok` | yes | asked now | +| `cached` | yes | answered from the cache, under 6 hours old | +| `stale cache ()` | yes | the fetch failed, so an older cached answer was used | +| `expired catalog` | yes | a catalog older than 7 days was searched as it is and is downloading again in the background | +| `needs $VAR` | no | the source requires a key that is not set; it was not asked | +| `skipped, outage N s ago` | no | it failed in the last ten minutes; naming it in `source` asks it anyway | +| `not waited for after N s` | no | past the deadline, or past one more second once 90% of the sources had answered | +| `downloading its catalog` | no | its first catalog download is still running and the next search will have it | +| any other text | no | the failure itself, such as `timed out`, `rate limited by the source`, `refused the request (HTTP 403)` | + +A missing source matters only when the topic belongs to it: a missing `fred` matters for US economic series and not for protein structures. The fix for each status: `references/troubleshoot.md`. + +## Opt-in sources + +`google` (Google Dataset Search) and `mendeley` (Mendeley Data) are never asked by default, by a category or by an empty `source`; only naming them in `source` asks them. Google has no API, so dataseek reads its results page, one request per query; Mendeley's terms bar automated access without written permission. Ask either only when the user names it, and tell the user Mendeley's terms first. Because `source` replaces the default set, run the opt-in source as its own search beside the default one, then merge the two lists in the answer by URL and DOI. + +## More, newer, fresher + +- **More results:** a full `results` list (as long as `limit`) usually means more exist; raise `limit`. The CLI's last stderr line gives the total ("3 of 317 results"); the JSON does not. +- **Deeper in one archive:** `source` set to it plus a higher `per-source`. +- **Newest:** `sort: "newest"` orders by `updated`; undated results go last, so say how many lacked a date. +- **Fresh answers:** `refresh: true` skips the 6-hour query cache; the default is right for nearly every call. +- **Many `expired catalog` statuses:** the catalogs are older than a week. `dsk cache warm` downloads them all once (`references/setup.md`). + +## The answer + +```text +Datasets +1. Extended Reconstructed Sea Surface Temperature (ERSST), Version 4 + https://catalog.data.gov/dataset/extended-reconstructed-sea-surface-temperature-ersst-version-4 + datagov, ncei | NOAA National Centers for Environmental Information | updated 2015-05-26 | CC0 1.0 | doi:10.7289/v5kd1vvf +2. ... + +Coverage: 70 of 71 sources answered; complete: false, data-gov-uk not waited for after 2 s. + +Queries +dsk search sea surface temperature -n 10 +dsk search ERSST -n 10 +``` + +List only the results that fit the request, after applying the user's constraints, and say how many were dropped and why. diff --git a/skills/dataseek/references/setup.md b/skills/dataseek/references/setup.md new file mode 100644 index 0000000..30dfd07 --- /dev/null +++ b/skills/dataseek/references/setup.md @@ -0,0 +1,102 @@ +# Setup + +Verified against `README.md`, `docs/reference/contract.md`, `docs/reference/keys-and-cache.md` and a live `dsk mcp` session on 2026-10-20. + +## Contents + +- **Install**: which command, and how to tell it worked +- **Register the MCP server**: the entry every client takes, and the three variants that fix a server that will not start +- **Verify**: the one call that proves the tools work, and the probe for when they do not appear +- **Keys**: which sources a key unlocks or speeds up, and where a key may live +- **Cache**: when to warm the catalogs and where the cache sits + +## Install + +Check first: `dsk -V` prints `dataseek `. Otherwise, any one of: + +```sh +brew install lmarkmann/tap/dataseek # macOS and Linux with Homebrew +cargo binstall dataseek # prebuilt binary through cargo +cargo install --locked dataseek # build from source +uv tool install dataseek # from PyPI +uvx dataseek search sea surface temperature # run once, install nothing +``` + +Every method installs two names for one program, `dsk` and `dataseek`. Installing changes the user's machine: ask before running one, and let the user pick the package manager they already use. + +## Register the MCP server + +The entry, under whatever key the client keeps its servers (`mcpServers` in most JSON configs): + +```json +{ + "mcpServers": { + "dataseek": { "command": "dsk", "args": ["mcp"] } + } +} +``` + +Many clients also have a command that writes the entry, typically ` mcp add dataseek -- dsk mcp`; check the client's own help for its form before guessing one. + +Variants, each for one failure: + +- **The client cannot find `dsk`.** A desktop app often starts without the shell's `PATH`. Put the absolute path from `command -v dsk` in `command`. +- **No install, only `uv`.** `"command": "uvx", "args": ["dataseek", "mcp"]`. +- **A cache directory or connect timeout.** Global flags go after `mcp` and reach every call: `"args": ["mcp", "--cache-dir", "/path/to/cache", "--connect-timeout", "5"]`. `-q` and `-v` work the same way. + +The server speaks JSON-RPC on stdin and stdout and writes its own status line, `serving search, sources, inspect over MCP on stdio`, plus each call's narration on stderr, which clients usually show in their MCP logs. It serves protocol revisions 2025-06-18 and 2025-11-25 through `initialize`, and 2026-07-28 statelessly. + +After upgrading dataseek, restart the server in the client: a running server keeps the binary and the tool list it started with. + +## Verify + +Call the `sources` tool once with no arguments. It answers with 76 rows; count them and note any `key` of `missing`. That count is the Setup lane's **Verified** part. + +When the tools do not appear at all, probe the server from a shell. This sends the handshake and a tool list request, holding stdin open for three seconds because closing it ends the server and every call still running: + +```sh +( printf '%s\n' \ + '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}}' \ + '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 3 ) | dsk mcp +``` + +Two JSON lines back, the second naming `search`, `sources` and `inspect`, means the server works and the fault is in the client's entry: the command path, the JSON, or a client that needs restarting. No output, or `command not found`, is the install. + +## Keys + +73 of the 76 sources need no key. A key unlocks three, raises the limits of four, and Kaggle reads one but answers the same without: + +| Source | Variable | Without it | +|---|---|---| +| FRED | `FRED_API_KEY` | skipped (`needs $FRED_API_KEY`) | +| Roboflow Universe | `ROBOFLOW_API_KEY` | skipped | +| Data Commons | `DATACOMMONS_API_KEY` | skipped | +| Hugging Face | `HF_TOKEN` | 500 requests per 5 minutes per IP | +| GitHub | `GITHUB_TOKEN` | 10 searches per minute | +| NCBI (GEO) | `NCBI_API_KEY` | 3 requests per second | +| Data.gov | `DATAGOV_API_KEY` | the keyless catalog search | +| Kaggle | `KAGGLE_API_TOKEN`, or the Kaggle CLI's `~/.kaggle/access_token` or `~/.kaggle/kaggle.json` | anonymous requests work | + +Each source's `key` in the `sources` result reads `none` (takes no key), `optional` (takes one, none set, works without), `set` (found) or `missing` (needs one, none set, skipped). `dsk doctor` says where each key was found and never prints one. + +Where a key lives, in order of preference: + +1. **`credentials.toml`** in dataseek's config directory, which `dsk doctor` prints, with mode 600; `doctor` fails a file other users can read. One line per key, by source id: `fred = "..."`, `datagov = "..."`, `huggingface = "..."`. The user writes the value; never echo it into a command. +2. **The environment the server starts in.** A key exported in the user's shell profile reaches `dsk` in a terminal, but a desktop client may not inherit it; then use the file. +3. **The client's `env` block** for the server entry, only in a config file that lives outside any repository and that the user chose. A key in a project's committed MCP config is a leaked key. + +No tool and no flag takes a key, so a key never belongs in a tool argument or on a command line. + +## Cache + +Query answers are cached 6 hours, catalogs (the `*` sources in `references/search.md`) 7 days, and a failed source rests 10 minutes. A first search, or a search after a week, reports catalogs as `expired catalog` or `downloading its catalog`; one warm-up fixes both: + +```sh +dsk cache warm # download every catalog now, no deadline +dsk cache warm -s openneuro # only these +dsk cache info # path, size and budget +dsk cache clear --dry-run # what clearing would delete +``` + +`cache warm` and `cache clear` are CLI only; no MCP tool runs them. `cache clear` deletes every cached answer and catalog: show the `--dry-run` output and ask before running it. diff --git a/skills/dataseek/references/troubleshoot.md b/skills/dataseek/references/troubleshoot.md new file mode 100644 index 0000000..60e39df --- /dev/null +++ b/skills/dataseek/references/troubleshoot.md @@ -0,0 +1,95 @@ +# Troubleshoot + +Verified against `docs/reference/contract.md`, `src/mcp/tools.rs`, `src/search.rs`, `src/http.rs` and live calls on 2026-10-20. + +## Contents + +- **Read the failure**: where the message, cause and hint sit on each surface +- **Tool refusals**: the argument errors a call can fix by itself +- **Protocol errors**: JSON-RPC codes, which mean the client or the server, not the call +- **Exit codes**: what the CLI returns and what counts as success +- **Whole-search failures**: offline, deadline, certificates, nothing could run +- **Per-source statuses**: one source missing from an otherwise good search +- **No results**: when sources answered and nothing came back + +## Read the failure + +Every failure carries three parts, in this order: what went wrong, why, and what to do. + +- **MCP:** a result with `isError: true`. Its text is the CLI's lines, `Error: ...`, ` Cause: ...`, ` Try: ...`; its `structuredContent` is the event `{"event": "error", "message", "causes", "try"}`. +- **CLI:** the same lines on stderr; under `--json`, one `dataseek-events/1` line with `"event": "error"`, and nothing on stdout. + +Quote the lines as they are, follow `Try:` first, and rerun once. A second identical failure goes to the user with both attempts, not into a loop. + +## Tool refusals + +A bad argument is refused before anything runs, naming the argument. Fix the call and send it again: + +| Message | Fix | +|---|---| +| `` search has no argument `` `` | use a name from the tool's input schema; the names are the CLI's long flags without dashes | +| `` `` takes a list of strings `` (or an integer, true or false) | send the schema's type; `source`, `exclude` and `category` are arrays | +| `` search needs `query` `` | pass `query` | +| `invalid value '' for '--source '`, with the possible values as its cause | use an id from that list or from the `sources` tool | +| `timeout 0 waits for every source, and a search over MCP always has a deadline` | pass 1 to 300, or leave `timeout` out for 20 | +| `timeout is past the 300 second deadline a search over MCP may have` | 300 at most | +| `` `` holds a NUL character `` | strip it | +| `4 calls are already running, the most dsk mcp runs at once` | wait for one to answer, then call again | + +## Protocol errors + +A JSON-RPC error instead of a tool result is the client's or the server's fault, never the call's arguments: `-32700` a line that is not JSON, `-32600` a malformed request or a reused id, `-32601` an unknown method, `-32602` an unknown tool, `-32603` a server fault whose message says what the command left, `-32022` an unsupported protocol revision with the supported list. Report it to the user with the code and message; for a tool that never appears, run the probe in `references/setup.md`. + +## Exit codes + +| Code | Meaning | +|---|---| +| 0 | success; for `search`, at least one source answered, even with no results | +| 1 | failure: every attempted source failed, none could run, an `inspect` failed, or a `cache warm` catalog failed | +| 2 | usage error: an unknown command, flag or value | +| 130 | interrupted | + +A source that fails while others answer is a warning on stderr and a `status` in the JSON, never a failure. + +## Whole-search failures + +When `search` itself fails, the message says which case it is: + +| Case | What to do | +|---|---| +| the machine looks offline (every source unreachable: no DNS, refused connection, failed TLS handshake) | check the network; `offline: true` searches the cache and downloaded catalogs | +| `--offline` with nothing cached | go online once; `dsk cache warm` stores the catalogs for later offline use | +| no source answered before the deadline | raise `timeout` (CLI: `--timeout 0` waits for all) | +| a certificate dataseek cannot verify, on every source | on Linux, install the distribution's `ca-certificates` package, or point `SSL_CERT_FILE` at the proxy's root certificate; the `Try:` line names the variable or path at fault | +| none could run: each lacks its key, each is resting after an outage, or `source`, `category` and `exclude` left none | read the `sources` statuses; add the key, name the resting source, or widen the selection | + +## Per-source statuses + +The search succeeded but one source is missing. Act only when that source matters for the topic: + +| `status` | Cause | Fix | +|---|---|---| +| `needs $VAR` | its required key is not set | the user sets the key (`references/setup.md`, Keys); then search again | +| `skipped, outage N s ago` | it failed within the last ten minutes | `source` set to it asks it anyway, or wait out the ten minutes | +| `not waited for after N s` | slower than the deadline, or than one second past the 90% quorum | `source` set to it gets the whole `timeout`; raise `timeout` for a slow one | +| `downloading its catalog` | a first download is running in the background | search again in a minute, or `dsk cache warm -s ` | +| `expired catalog` | answered from a copy over 7 days old | nothing urgent; `dsk cache warm` refreshes it | +| `stale cache ()` | the fetch failed and an older answer was used | say the answer may be dated; `refresh: true` once the source is back | +| `rate limited by the source` | too many requests from this address | wait; for `huggingface` or `github`, a key raises the limit | +| `refused the request (HTTP 401)` or `(HTTP 403)` without a key | the source wants authentication or blocks the request | for a source that takes a key, the key may lift it | +| `rejected the credentials (HTTP )` | the key that was sent is wrong or expired | the user replaces the key | +| `sent a challenge page instead of results` | a bot wall; counted as an outage | retry after ten minutes | +| `returned an unexpected shape: ...` | the source changed its API | report it at https://github.com/lmarkmann/dataseek/issues with the status text | +| `unreachable (...)`, `timed out`, `answered HTTP ` | the source is down or slow | retry later; the other sources stand | +| `could not verify the certificate (...)` | TLS trust, as in the whole-search case | as above | +| `did not connect within --connect-timeout (N s)` | the user's own connect limit | raise or drop `--connect-timeout` in the server's args | +| `not asked (--offline)` | an offline search had nothing cached for it | search online | + +## No results + +An empty `results` list with sources answering means none of them holds a match for those words. In order: + +1. Check `sources`: if the sources that would hold this topic did not answer, it is the table above, not the query. +2. Shorten the query to its two most specific words, then try the field's own term or acronym (`references/search.md`, Writing queries). +3. Drop `category` or `source` if they were set. +4. After three rounds, report the queries tried and the coverage, and say no dataset matched. From 05bc508670960b59419e37a34e2945c2b7456c95 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:06:01 +0100 Subject: [PATCH 03/31] feat: search --json reports total, every merged match beyond -n --- src/find.rs | 6 +++++- tests/cli.rs | 18 ++++++++++++++++++ tests/snapshots/cli__json_shapes_snapshot.snap | 3 ++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/find.rs b/src/find.rs index 7996253..bc6ca55 100644 --- a/src/find.rs +++ b/src/find.rs @@ -154,7 +154,7 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { let mut hits = ranked(&mut outcomes, &query, sort); let found = hits.len(); hits.truncate(limit); - print(out, &query, &hits, sources, complete)?; + print(out, &query, &hits, found, sources, complete)?; summarize(&query, hits.len(), found, &outcomes, renewing, &services.cache); Ok(()) } @@ -377,6 +377,8 @@ struct Report<'a> { /// False when the search stopped waiting for a source or a catalog was /// still downloading, so the results may lack what those would add. complete: bool, + /// How many merged datasets matched; `results` holds the first `limit`. + total: usize, results: &'a [Hit], sources: Vec, } @@ -408,6 +410,7 @@ fn print( out: &Out, query: &str, hits: &[Hit], + total: usize, sources: Vec, complete: bool, ) -> Result<()> { @@ -416,6 +419,7 @@ fn print( schema: SCHEMA, query, complete, + total, results: hits, sources, }); diff --git a/tests/cli.rs b/tests/cli.rs index 8624120..27c3702 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1626,6 +1626,24 @@ fn seeded_search_json() -> Value { report } +// `results` stops at `-n`; `total` still counts every merged match. +#[test] +fn search_json_counts_matches_past_the_limit() { + let mut cmd = bin(); + seed_rainfall(&cmd.cache()); + let out = cmd + .args(["search", "rainfall", "-s", "openml", "--offline", "--json"]) + .args(["-n", "1"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let every = seeded_search_json()["results"].as_array().unwrap().len(); + assert!(every > 1, "{every}"); + assert_eq!(report["results"].as_array().unwrap().len(), 1); + assert_eq!(report["total"], every); +} + #[test] fn json_shapes_snapshot() { let sources = json_of(&["sources", "--json"]); diff --git a/tests/snapshots/cli__json_shapes_snapshot.snap b/tests/snapshots/cli__json_shapes_snapshot.snap index dd84e8f..51d4fd7 100644 --- a/tests/snapshots/cli__json_shapes_snapshot.snap +++ b/tests/snapshots/cli__json_shapes_snapshot.snap @@ -189,7 +189,8 @@ expression: "serde_json::to_string_pretty(&shapes).unwrap()" "results": 2, "status": "ok" } - ] + ], + "total": 2 }, "sources": { "schema": "dataseek-sources/1", From 48273cd2df6cd14a132a0e101b3f53bbe886a4b0 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:06:01 +0100 Subject: [PATCH 04/31] fix: MCP tool arguments describe JSON arrays and the timeout bounds instead of the command line's wording --- docs/reference/contract.md | 4 +-- src/mcp/tools.rs | 50 ++++++++++++++++++++++++++++++++------ 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/docs/reference/contract.md b/docs/reference/contract.md index 6adfe8e..710f962 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -58,7 +58,7 @@ This is why `Cargo.toml` denies `print_stdout` and `print_stderr`: a stray `prin ## JSON -Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `search --json` carries `complete`, false when the search stopped waiting for a source or a catalog was still downloading, so its results may lack what those would add. `completion` and `man` print their script and page whatever the flag when stdout is not a terminal. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. +Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `search --json` carries `complete`, false when the search stopped waiting for a source or a catalog was still downloading, so its results may lack what those would add. It also carries `total`, how many merged datasets matched; `results` holds the first `-n` of them, so a full list with a larger `total` says more exist. `completion` and `man` print their script and page whatever the flag when stdout is not a terminal. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. `inspect --json` (`dataseek-inspect/1`) prints `dataset`, the page's own JSON-LD node as the page wrote it, and beside it `files`, dataseek's reading of the file list, so a `files` key on the page is never overwritten. Every string of the page's metadata, keys included, has its control characters (C0 other than newline and tab, DEL, and C1) replaced by a space before it is printed, as text or as JSON, so a page cannot drive the terminal that shows it. @@ -69,7 +69,7 @@ Every `--json` output is one object with a `schema` tag naming its shape and ver - **Protocol.** Requests naming revision `2026-07-28` in `_meta` are served statelessly, with `server/discover`; clients that open with `initialize` get revision `2025-11-25` or `2025-06-18`. A request naming any other revision gets `-32022` with the supported list. - **stdout** carries one JSON-RPC message per line and nothing else. stderr carries the server's own status line, as plain text, and its calls' narration, as `dataseek-events/1` lines. `-q`, `-v`, `--cache-dir` and `--connect-timeout` given to `dataseek mcp` reach every call. - **Include.** `--include IDS` given to `dataseek mcp` asks those sources, opt-in ones included, in every search that names no sources of its own; a call that names `source` or `include` is left alone. -- **Tools.** Each tool's input schema is its command's `help --json` entry: one property per flag, named by its long form, typed, with its possible values and default; `search`'s words are one `query` string. A call runs `dataseek --json` with those flags, and the result carries the object that prints as `structuredContent` and again as text. +- **Tools.** Each tool's input schema is its command's `help --json` entry: one property per flag, named by its long form, typed, with its possible values and default; `search`'s words are one `query` string. Each description is the flag's help worded for a call: a list argument is a JSON array rather than comma-separated, source ids come from the `sources` tool, and `timeout` states its 1 to 300 second bounds. A call runs `dataseek --json` with those flags, and the result carries the object that prints as `structuredContent` and again as text. - **Failures.** A failed call is a result with `isError: true`: the text is the `Error:`, `Cause:` and `Try:` lines the command line prints, and `structuredContent` the error event. A bad or missing argument is such a failure too, since the model can fix it, and so is a call made while four are already running. A JSON-RPC error answers the rest: a line that is not JSON in UTF-8 gets `-32700`, and the session goes on; a request without a string method, or reusing the id of a call still running, `-32600`; an unknown method `-32601`; an unknown tool or `arguments` that is not an object `-32602`; a server fault `-32603`, whose message says what the command left. A notification is never answered. - **Deadline.** Every search runs with `--timeout`, the argument or its default of 20 seconds, and with the command line's rule for stragglers: past 90% of the sources asked, the rest get one more second unless `source` names them ([ADR 0019](../adr/0019-stop-waiting-past-a-quorum.md)). A `timeout` outside 1 to 300 seconds is refused, so every call ends in a time a client waits for; the schema says so with `minimum` and `maximum`, as it does for every ranged integer. - **Keys** come from the environment and `credentials.toml`, as everywhere ([ADR 0009](../adr/0009-keys-and-contact-address.md)); no tool takes one as an argument. diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index e9fa713..fda4643 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -140,22 +140,32 @@ impl Arg { } } -/// The command behind `tool`, with `search`'s timeout held to the bounds -/// [`deadline`] enforces. +/// The command behind `tool`, its help worded for a model, with `search`'s +/// timeout held to the bounds [`deadline`] enforces. fn described(tool: &str) -> anyhow::Result { let command = help::subcommand_json(tool) .ok_or_else(|| anyhow::anyhow!("no `{tool}` command to describe"))?; let mut command: Described = serde_json::from_value(command)?; - if tool == "search" { - for arg in &mut command.args { - if arg.key() == "timeout" { - (arg.minimum, arg.maximum) = (Some(1), Some(MAX_TIMEOUT)); - } + for arg in &mut command.args { + arg.help = arg.help.as_deref().map(for_a_model); + if tool == "search" && arg.key() == "timeout" { + (arg.minimum, arg.maximum) = (Some(1), Some(MAX_TIMEOUT)); + arg.help = Some(format!( + "Seconds to wait for slow sources before answering, 1 to {MAX_TIMEOUT}" + )); } } Ok(command) } +/// A flag's help as a tool argument's description: a list is a JSON array +/// rather than a comma-separated value, and the ids come from the `sources` +/// tool rather than from a command. +fn for_a_model(help: &str) -> String { + help.replace(", comma-separated", "") + .replace("`dataseek sources`", "the sources tool") +} + /// The tool whose name is `name`, as the static string the rest uses. pub fn find(name: &str) -> Option<&'static str> { TOOLS.into_iter().find(|tool| *tool == name) @@ -582,6 +592,32 @@ mod tests { assert_eq!(search["additionalProperties"], false); } + // The descriptions come from the command line's help, which describes + // comma-separated values, `dataseek sources` and a timeout of 0; none of + // those is true of a tool call. + #[test] + fn descriptions_describe_the_call_not_the_command_line() { + for tool in TOOLS { + let schema = schema(tool); + for (key, property) in schema["properties"].as_object().unwrap() { + let text = property["description"].as_str().unwrap_or(""); + for wrong in ["comma-separated", "dataseek sources", "0 waits"] + { + assert!(!text.contains(wrong), "{tool} {key}: {text}"); + } + } + } + let search = schema("search"); + assert_eq!( + search["properties"]["source"]["description"], + "Only these sources (see the sources tool)" + ); + assert_eq!( + search["properties"]["timeout"]["description"], + "Seconds to wait for slow sources before answering, 1 to 300" + ); + } + // Through clap, the generated command line means what the call said. #[test] fn a_call_becomes_the_command_line_it_describes() { From e8abf32220a1ce27ba48dfd772227569cc4d800e Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:07:18 +0100 Subject: [PATCH 05/31] doc: the dataseek skill works through MCP first and teaches include and the total match count --- skills/dataseek/SKILL.md | 18 +++++++++++------- skills/dataseek/references/cli.md | 9 ++++++--- skills/dataseek/references/search.md | 16 ++++++++++------ skills/dataseek/references/setup.md | 1 + 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/skills/dataseek/SKILL.md b/skills/dataseek/SKILL.md index 8c5c0fc..ae03248 100644 --- a/skills/dataseek/SKILL.md +++ b/skills/dataseek/SKILL.md @@ -19,7 +19,11 @@ compatibility: needs the dataseek binary (dsk) and network access dataseek sends one query to every dataset source it knows, merges the records that are one dataset (a shared DOI, landing URL, or title and publisher) and ranks them by how many sources agree and how much of the query each covers. It runs as an MCP server (`dsk mcp`, three tools) and as a CLI (`dsk`, also installed as `dataseek`). They are one program: a tool returns, byte for byte, the object `dsk --json` prints, so every reference here holds for both. -**Pick the surface once per task.** If the tool list holds the dataseek server's `search`, `sources` and `inspect` tools, call them. Otherwise, with a shell, run `dsk --json`. With neither, go to the Setup lane. Clients name the tools differently (`search`, `dataseek.search`, `mcp__dataseek__search`); the server is `dataseek`. +**MCP first; the CLI is the fallback.** dataseek is built to be called as an MCP server, so every procedure here is written in tool arguments. + +1. The tool list holds the dataseek server's `search`, `sources` and `inspect` tools: call them. Clients name them differently (`search`, `dataseek.search`, `mcp__dataseek__search`); the server is `dataseek`. +2. No dataseek tools, but a shell with `dsk`: finish this task with `dsk --json`, using the CLI column of `references/search.md`, and tell the user once that registering the server (Setup lane) turns this into tool calls. +3. Neither: go to the Setup lane first. ## Output contract @@ -30,7 +34,7 @@ Leaves behind: the final message, in three parts in this order Sections: Datasets, Coverage, Queries - **Datasets**: numbered, best first. Each carries the title, the URL and the sources that hold it, then license, last update, DOI and size when the result has them. Every value comes from the result object; a field the result lacks is left out, never guessed. -- **Coverage**: one line from the result: how many sources answered, whether `complete` was true, and each relevant source that failed, was skipped or was not waited for, with its `status` as dataseek wrote it. +- **Coverage**: one line from the result: how many of `total` matches are shown, how many sources answered, whether `complete` was true, and each relevant source that failed, was skipped or was not waited for, with its `status` as dataseek wrote it. - **Queries**: every query run, as the `dsk search ...` command that reproduces it. Inspect lane: @@ -46,7 +50,7 @@ Leaves behind: the final message, quoting the error or status verbatim Sections: Diagnosis, Fix, Result Forbidden: [A-Z_]*(TOKEN|API_KEY)=[^\s$"'{] -Forbidden: (-s |--source[ =]|"source"\s*:\s*\[)[^\]\n]*\b(google|mendeley)\b +Forbidden: (-s |--source[ =]|--include[ =]|"(source|include)"\s*:\s*\[)[^\]\n]*\b(google|mendeley)\b Forbidden: \bdsk (s|search|sources|inspect)\b(?:(?!--json)[^|\n])*\| The exemptions are under Iron rules. @@ -66,8 +70,8 @@ Default when ambiguous: **Search**. A search the user will choose from runs Sear ## Search (default) 1. **Write one to three short queries**, two to four content words each, before calling anything. Most sources match every word, so a sentence finds fewer datasets than its keywords: "sea surface temperature" merged 328 results where "global monthly sea surface temperature dataset since 1980" merged 136 (2026-10-20). Years, regions and formats are filters to apply to the results, not query words. The rules and the evidence: `references/search.md`, Writing queries. -2. **Narrow only on the user's words.** A named archive becomes `source`; a clear domain becomes `category`; a source flooding the list becomes `exclude`. The ids and the fourteen categories: `references/search.md`, Arguments. -3. **Call `search`** and read `results`, then `complete` and `sources[].status`. An empty `results` list from sources that answered is an answer, not a failure. +2. **Narrow only on the user's words.** "Only on Kaggle" becomes `source` (those alone); "also check Kaggle" becomes `include` (beside every default source); a clear domain becomes `category`; a source flooding the list becomes `exclude`. The ids and the fourteen categories: `references/search.md`, Arguments. +3. **Call `search`** and read `results`, then `total`, `complete` and `sources[].status`. A `results` list as long as `limit` with a larger `total` means more exist. An empty `results` list from sources that answered is an answer, not a failure. 4. **Reformulate when fewer than about five results fit**: a synonym, the field's own term or acronym, one word dropped. Stop after three rounds and say what was tried. 5. **Answer in the Search shape above.** Ranks and `score` order one search only; never compare scores across searches. @@ -109,7 +113,7 @@ When dataseek behaves differently from this skill, dataseek wins: read the live ## Iron rules -1. **One surface per task**, MCP tools when listed, `dsk ... --json` otherwise. Never parse the text output; it wraps and truncates for a terminal. +1. **MCP tools when listed, `dsk ... --json` only when they are not**, and one surface for the whole task. Never parse the CLI's text output; it wraps and truncates for a terminal. 2. **Every URL, DOI, license, size and date in an answer appears in a tool result.** dataseek returns records, not judgments about them; a field it did not return is "not stated". 3. **Google Dataset Search (`google`) and Mendeley Data (`mendeley`) only when the user names them.** Neither permits automated searches. Before a Mendeley search, tell the user its terms bar automated access without written permission. 4. **Keys never travel in an argument, a command line or a project file.** No tool takes one. They live in the environment the server starts in or in `credentials.toml` with mode 600. @@ -120,5 +124,5 @@ When dataseek behaves differently from this skill, dataseek wins: read the live | Boundary | Forbidden token | Exemption | |---|---|---| | Rule 4, keys | a literal assignment such as `HF_TOKEN=hf_x` in a command | `export HF_TOKEN="$()"`, which carries no literal | -| Rule 3, opt-in sources | `google` or `mendeley` in `source` or `-s` | the user named Google Dataset Search or Mendeley Data in this task | +| Rule 3, opt-in sources | `google` or `mendeley` in `source`, `include`, `-s` or `--include` | the user named Google Dataset Search or Mendeley Data in this task | | Rule 1, text output | `dsk search ...` piped without `--json` | a human reading through a pager, `dsk search ... \| less -R` | diff --git a/skills/dataseek/references/cli.md b/skills/dataseek/references/cli.md index bab0301..5784c34 100644 --- a/skills/dataseek/references/cli.md +++ b/skills/dataseek/references/cli.md @@ -22,7 +22,7 @@ Verified against `docs/reference/contract.md`, `dsk help --json`, `dsk help envi | `dsk cache info` | cache path, size and budget | none | | `dsk cache warm [-s ids] [--dry-run]` | download the catalogs now, with no deadline | the catalog cache | | `dsk cache clear [--dry-run]` | delete every cached answer and catalog | deletes the cache; show `--dry-run` and ask first | -| `dsk mcp` | the MCP server on stdio | none | +| `dsk mcp [--include ids]` | the MCP server on stdio; `--include` adds those sources to every search that names none | none | | `dsk bench [queries]` | time every source; sends queries x sources requests, uncached | none, but heavy on the sources; only when asked by name | | `dsk help [command \| environment \| exit-codes]` | help; `--json` describes the whole surface | none | | `dsk completion `, `dsk man` | a completion script, the man page | none | @@ -31,7 +31,7 @@ Verified against `docs/reference/contract.md`, `dsk help --json`, `dsk help envi Global flags, valid with every command: `--json`, `-q`/`--quiet` (errors only on stderr), `-v`/`--verbose` (repeatable), `--color auto|always|never`, `--no-color`, `--plain` (ASCII, no color), `--no-progress`, `--cache-dir DIR`, `--connect-timeout SECS`. -`search` flags: `-s/--source`, `-x/--exclude`, `-c/--category` (comma-separated), `-n/--limit` (20), `--per-source` (10, at most 100), `--sort relevance|newest`, `--refresh`, `--offline`, `--timeout SECS` (20; 0 waits for every source). Their meaning is the MCP argument table in `references/search.md`. +`search` flags: `-s/--source`, `--include`, `-x/--exclude`, `-c/--category` (comma-separated), `-n/--limit` (20), `--per-source` (10, at most 100), `--sort relevance|newest`, `--refresh`, `--offline`, `--timeout SECS` (20; 0 waits for every source). Their meaning is the MCP argument table in `references/search.md`. A flag beats its variable, which beats the default: @@ -49,7 +49,7 @@ A script that must not inherit a user's `DATASEEK_TIMEOUT=0` or `DATASEEK_EXCLUD ## Streams and schemas - **stdout is data.** With `--json`, one object, indented on a terminal and one line in a pipe, tagged with `schema`: `dataseek-search/1`, `dataseek-sources/1`, `dataseek-inspect/1`, `dataseek-doctor/1`, `dataseek-cache-info/1`, `dataseek-cache-warm/1`, `dataseek-surface/1` (from `help --json`). A new key may appear without notice; a changed or removed one bumps the number, so a script can assert the tag. -- **stderr is status.** With `--json`, each line is an event `{"schema": "dataseek-events/1", "event": ..., "message": ...}`: `stage` (what it is doing), `warning` (a source that failed, a stale catalog), `ok` (the summary, including the total match count), and `error` (with `causes` and `try`). `-q` leaves only the error. +- **stderr is status.** With `--json`, each line is an event `{"schema": "dataseek-events/1", "event": ..., "message": ...}`: `stage` (what it is doing), `warning` (a source that failed, a stale catalog), `ok` (the summary line), and `error` (with `causes` and `try`). `-q` leaves only the error. - **A failed run prints nothing on stdout.** `jq` exits 0 on empty input, so run pipelines under `set -o pipefail` in bash and zsh, or check `$pipestatus[1]` in fish. - **An empty search is success** (exit 0, `results: []`) when any source answered. Exit codes: `references/troubleshoot.md`. @@ -61,6 +61,9 @@ set -o pipefail # one URL per line dsk search census --json | jq -r '.results[].url' +# how many matched, against how many are shown +dsk search census --json | jq -r '"\(.results | length) of \(.total)"' + # title, URL and holding sources as TSV dsk search census --json | jq -r '.results[] | [.title, .url, (.sources | join(","))] | @tsv' diff --git a/skills/dataseek/references/search.md b/skills/dataseek/references/search.md index d60a872..4e54de0 100644 --- a/skills/dataseek/references/search.md +++ b/skills/dataseek/references/search.md @@ -20,7 +20,8 @@ The MCP tool's input schema is generated from the CLI's flags, so the names matc | MCP argument | CLI | Default | Set it when | |---|---|---|---| | `query` (string) | the words after `search` | required | always; several words form one query | -| `source` (array of ids) | `-s a,b` | every default source | the user names an archive; also the only way to ask an opt-in source | +| `source` (array of ids) | `-s a,b` | every default source | the user wants those archives alone | +| `include` (array of ids) | `--include a,b` | none | the user wants an archive asked beside the default set; also the way to add an opt-in source | | `exclude` (array of ids) | `-x a,b` | none | one source floods the list with near-duplicates | | `category` (array of names) | `-c a,b` | every category | the domain is unmistakable (economics, life-sciences) | | `limit` (integer) | `-n N` | 20 | the user wants more or fewer merged results | @@ -30,9 +31,9 @@ The MCP tool's input schema is generated from the CLI's flags, so the names matc | `offline` (boolean) | `--offline` | false | no network, or a repeat over the cache only | | `timeout` (1 to 300 seconds) | `--timeout N` | 20 | a slow source matters; the CLI also takes 0, wait for all, which MCP refuses | -Over MCP, `source`, `exclude` and `category` are JSON arrays, `["zenodo", "figshare"]`, even though their descriptions say comma-separated: that wording is the CLI's. A string where an array belongs is refused with `` `source` takes a list of strings ``. +Over MCP, `source`, `include`, `exclude` and `category` are JSON arrays, `["zenodo", "figshare"]`; the CLI takes the same ids comma-separated. A string where an array belongs is refused with `` `source` takes a list of strings ``. -`source` replaces the default set rather than adding to it. A search with `source: ["kaggle"]` asks Kaggle alone, and a named source gets the whole `timeout` and is asked even if it had an outage in the last ten minutes. +`source` replaces the default set; `include` adds to it. A search with `source: ["kaggle"]` asks Kaggle alone, one with `include: ["kaggle"]` asks Kaggle and every default source. `category` and `exclude` still narrow an included source: `include: ["google"]` with `category: ["research"]` leaves Google out, because Google is an `aggregator`. A source named in `source` gets the whole `timeout` and is asked even if it had an outage in the last ten minutes. ## Source ids and categories @@ -80,6 +81,7 @@ Measured 2026-10-20 over the default sources: "sea surface temperature" merged 3 |---|---| | `query` | the query as searched | | `complete` | false when the search stopped waiting for a source or a catalog was still downloading, so results from those are missing | +| `total` | how many merged datasets matched; `results` holds the first `limit` of them | | `results` | the merged datasets, best first, at most `limit` | | `sources` | one entry per source asked: `id`, `status`, `answered`, `results` (how many it returned), `ms` | @@ -117,11 +119,13 @@ A missing source matters only when the topic belongs to it: a missing `fred` mat ## Opt-in sources -`google` (Google Dataset Search) and `mendeley` (Mendeley Data) are never asked by default, by a category or by an empty `source`; only naming them in `source` asks them. Google has no API, so dataseek reads its results page, one request per query; Mendeley's terms bar automated access without written permission. Ask either only when the user names it, and tell the user Mendeley's terms first. Because `source` replaces the default set, run the opt-in source as its own search beside the default one, then merge the two lists in the answer by URL and DOI. +`google` (Google Dataset Search) and `mendeley` (Mendeley Data) are never asked by default, by a category or by an empty `source`; only naming them in `source` or `include` asks them. Google has no API, so dataseek reads its results page, one request per query; Mendeley's terms bar automated access without written permission. Ask either only when the user names it, and tell the user Mendeley's terms first. `include: ["google"]` asks Google beside every default source in one search, merged and ranked with the rest; `source: ["google"]` asks Google alone. + +A server started with `dsk mcp --include google` adds Google to every search that sets neither `source` nor `include` (`references/setup.md`). Results then carry `google` in `sources` without the call naming it; that is the user's configuration, not a breach of rule 3. ## More, newer, fresher -- **More results:** a full `results` list (as long as `limit`) usually means more exist; raise `limit`. The CLI's last stderr line gives the total ("3 of 317 results"); the JSON does not. +- **More results:** `total` above the length of `results` means more exist; raise `limit` up to `total`. - **Deeper in one archive:** `source` set to it plus a higher `per-source`. - **Newest:** `sort: "newest"` orders by `updated`; undated results go last, so say how many lacked a date. - **Fresh answers:** `refresh: true` skips the 6-hour query cache; the default is right for nearly every call. @@ -136,7 +140,7 @@ Datasets datagov, ncei | NOAA National Centers for Environmental Information | updated 2015-05-26 | CC0 1.0 | doi:10.7289/v5kd1vvf 2. ... -Coverage: 70 of 71 sources answered; complete: false, data-gov-uk not waited for after 2 s. +Coverage: 10 of 328 matches shown; 70 of 71 sources answered; complete: false, data-gov-uk not waited for after 2 s. Queries dsk search sea surface temperature -n 10 diff --git a/skills/dataseek/references/setup.md b/skills/dataseek/references/setup.md index 30dfd07..89dc1a5 100644 --- a/skills/dataseek/references/setup.md +++ b/skills/dataseek/references/setup.md @@ -43,6 +43,7 @@ Variants, each for one failure: - **The client cannot find `dsk`.** A desktop app often starts without the shell's `PATH`. Put the absolute path from `command -v dsk` in `command`. - **No install, only `uv`.** `"command": "uvx", "args": ["dataseek", "mcp"]`. - **A cache directory or connect timeout.** Global flags go after `mcp` and reach every call: `"args": ["mcp", "--cache-dir", "/path/to/cache", "--connect-timeout", "5"]`. `-q` and `-v` work the same way. +- **An extra source on every search.** `"args": ["mcp", "--include", "google"]` adds Google Dataset Search to every search that sets neither `source` nor `include`. Only on the user's request: Google and Mendeley are opt-in because neither permits automated searches. The server speaks JSON-RPC on stdin and stdout and writes its own status line, `serving search, sources, inspect over MCP on stdio`, plus each call's narration on stderr, which clients usually show in their MCP logs. It serves protocol revisions 2025-06-18 and 2025-11-25 through `initialize`, and 2026-07-28 statelessly. From 7a7399e3eebf824e99ce86274e59ca0cd5d9bc87 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:12:19 +0100 Subject: [PATCH 06/31] fix: OSF licenses are SPDX ids, and "No license" no longer shows as one --- src/sources/osf.rs | 74 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/src/sources/osf.rs b/src/sources/osf.rs index 5fb8aef..e8469a2 100644 --- a/src/sources/osf.rs +++ b/src/sources/osf.rs @@ -2,11 +2,19 @@ //! this searches projects and registrations, which is where OSF data lives. //! An owner can mark a record's `resourceNature` as Dataset, but 4,135 of //! more than 10,000 records do, and 2 of the 45 hits for "sea ice", too few -//! to filter on. A page of 100 comes back whole, so one request serves any -//! limit; hits come by relevance and no query syntax draws an error (trove, -//! October 2026). trove throttles per client without saying how: 17 requests -//! in about three minutes drew HTTP 429 with no `Retry-After`, and every -//! `/trove/` path then answered 429 for an hour (October 2026). +//! to filter on. `page[size]` is capped at 101, so one request serves any +//! limit; hits come by relevance, words are ANDed, and no query syntax draws +//! an error (trove source and probe, October 2026). trove throttles per +//! client without saying how: 17 requests in about three minutes drew HTTP +//! 429 with no `Retry-After`, and every `/trove/` path then answered 429 for +//! an hour (October 2026). Replies carry `Cache-Control: no-store`, and no +//! term of OSF's says whether results may be stored (October 2026). +//! +//! `rights` names one of OSF's 19 licenses, or one it has since retired, and +//! its URL is no help: OSF links BSD 2-Clause to the 3-Clause text. The name +//! becomes an SPDX id; "No license" and "Other" say nothing usable and are +//! dropped (api.osf.io/v2/licenses, October 2026). `usage` counts views in +//! one month that differs per record, so it is no popularity (October 2026). //! //! `acceptMediatype=application/json` is not in trove's OpenAPI, which lists //! only `application/vnd.api+json` as stable; there the same cards sit under @@ -60,12 +68,44 @@ fn record(card: &Value) -> Option { .find(|id| id.contains("doi.org/")), ); dataset.publisher = text(card, "/publisher/0/name/0/@value"); - dataset.license = text(card, "/rights/0/name/0/@value"); + dataset.license = + text(card, "/rights/0/name/0/@value").and_then(|name| spdx(&name)); dataset.updated = day(text(card, "/dateModified/0/@value")); dataset.size_bytes = number(card, "/storageByteCount/0/@value"); dataset.valid() } +fn spdx(name: &str) -> Option { + let id = match name.to_ascii_lowercase().as_str() { + "cc0 1.0 universal" => "CC0-1.0", + "cc-by attribution 4.0 international" => "CC-BY-4.0", + "cc-by attribution-no derivatives 4.0 international" => "CC-BY-ND-4.0", + "cc-by attribution-noncommercial 4.0 international" => "CC-BY-NC-4.0", + "cc-by attribution-noncommercial-noderivatives 4.0 international" => { + "CC-BY-NC-ND-4.0" + } + "cc-by attribution-noncommercial-sharealike 4.0 international" => { + "CC-BY-NC-SA-4.0" + } + "cc-by attribution-sharealike 4.0 international" => "CC-BY-SA-4.0", + "academic free license (afl) 3.0" => "AFL-3.0", + "apache license 2.0" => "Apache-2.0", + "artistic license 2.0" => "Artistic-2.0", + "bsd 2-clause \"simplified\" license" => "BSD-2-Clause", + "bsd 3-clause \"new\"/\"revised\" license" => "BSD-3-Clause", + "eclipse public license 1.0" => "EPL-1.0", + "gnu general public license (gpl) 2.0" => "GPL-2.0-only", + "gnu general public license (gpl) 3.0" => "GPL-3.0-only", + "gnu lesser general public license (lgpl) 2.1" => "LGPL-2.1-only", + "gnu lesser general public license (lgpl) 3.0" => "LGPL-3.0-only", + "mit license" => "MIT", + "mozilla public license 2.0" => "MPL-2.0", + "no license" | "other" => return None, + _ => name, + }; + Some(id.to_owned()) +} + #[cfg(test)] mod tests { use super::*; @@ -86,7 +126,7 @@ mod tests { description: None, publisher: Some("OSF".into()), doi: None, - license: Some("CC-By Attribution 4.0 International".into()), + license: Some("CC-BY-4.0".into()), updated: Some("2026-06-23".into()), size_bytes: Some(142_773), popularity: None, @@ -118,4 +158,24 @@ mod tests { let urls: Vec<_> = hits.iter().map(|h| h.url.as_str()).collect(); assert_eq!(urls, ["https://osf.io/kzt9d", "https://osf.io/zh3w9"]); } + + #[test] + fn license_names_become_spdx_ids_and_placeholders_vanish() { + assert_eq!( + spdx("CC-By Attribution-NonCommercial-NoDerivatives 4.0 International") + .as_deref(), + Some("CC-BY-NC-ND-4.0") + ); + assert_eq!( + spdx("BSD 2-Clause \"Simplified\" License").as_deref(), + Some("BSD-2-Clause") + ); + assert_eq!( + spdx("GNU General Public License (GPL) 3.0").as_deref(), + Some("GPL-3.0-only") + ); + assert_eq!(spdx("No license"), None); + assert_eq!(spdx("Other"), None); + assert_eq!(spdx("A new one").as_deref(), Some("A new one")); + } } From 3cf91ab4d610fc3aca15ad6c4dc8c3ea983b2879 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:36:16 +0100 Subject: [PATCH 07/31] test: Dataverse answers an empty search and an error body as they arrive --- src/sources/dataverse.rs | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/sources/dataverse.rs b/src/sources/dataverse.rs index 4779c48..463a4eb 100644 --- a/src/sources/dataverse.rs +++ b/src/sources/dataverse.rs @@ -1,5 +1,15 @@ //! The Dataverse Search API, identical on every installation; a registry row -//! per installation picks the base URL. +//! per installation picks the base URL. Results come in relevance order +//! (`sort=score` is the default) and a page holds at most 1000 (a larger +//! `per_page` answers HTTP 400). The query matches any of its words in any +//! indexed field, the parent collection's name included, and tolerates +//! unbalanced quotes, brackets and operators. A dataset item carries no +//! license, size or download count, only `fileCount`; those live in the +//! per-dataset native API, one request each. The API states no rate limit +//! (Dataverse guides 6.12.1 and Harvard Dataverse 6.10.1, October 2026). +//! Harvard Dataverse includes harvested records from other archives (14348 +//! of 18270 hits for "air quality"), whose link is their own DOI or handle +//! (Harvard Dataverse, October 2026). use serde_json::Value; @@ -81,4 +91,29 @@ mod tests { } ); } + + #[test] + fn a_query_matching_nothing_is_an_empty_answer() { + let body = serde_json::json!({ + "status": "OK", + "data": { + "q": "zzqxjvkw qqxzjv", + "total_count": 0, + "start": 0, + "spelling_alternatives": {}, + "items": [], + "count_in_response": 0 + } + }); + assert_eq!(parse(&body, 10).unwrap(), vec![]); + } + + #[test] + fn an_error_body_is_a_changed_shape() { + let body = serde_json::json!({ + "status": "ERROR", + "message": "1001 results per page requested but max limit is 1000." + }); + assert!(matches!(parse(&body, 10), Err(SourceError::Shape(_)))); + } } From 76c944bb58aa4623b59273d4282b4810220f775b Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:36:30 +0100 Subject: [PATCH 08/31] feat: Figshare hits carry their unversioned DOI, so versions of one dataset merge --- src/sources/figshare.rs | 50 +++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/src/sources/figshare.rs b/src/sources/figshare.rs index a1012a7..2eeef95 100644 --- a/src/sources/figshare.rs +++ b/src/sources/figshare.rs @@ -1,16 +1,26 @@ //! Figshare's public article search, item type 3 (dataset). Covers //! figshare.com and the institutional portals on the same platform; each hit -//! links to the portal that holds it. The hits carry no description, license -//! or size; the full record has them, but one request per hit would break the -//! guideline of at most one request per second (Figshare, October 2026). -//! Results come newest first, because `order` defaults to `created_date` -//! descending and has no relevance value, and an article matches only when -//! every term appears somewhere in it (Figshare, October 2026). `updated` is -//! `modified_date`: `published_date` moves with each new version (Figshare, -//! October 2026). A page holds up to 1,000 hits, so one request covers -//! `--per-source` (Figshare, October 2026). A `search_for` shorter than 3 -//! characters is refused with HTTP 422 (Figshare, October 2026), so such a -//! query gets no results instead of a failure. +//! links to the portal that holds it. Results come newest first, because +//! `order` defaults to `created_date` descending and has no relevance value, +//! and an article matches only when every term appears somewhere in it +//! (Figshare, October 2026). `updated` is `modified_date`: `published_date` +//! moves with each new version (Figshare, October 2026). A page holds up to +//! 1,000 hits, so one request covers `--per-source` (Figshare, October 2026). +//! A `search_for` shorter than 3 characters is refused with HTTP 422 +//! (Figshare, October 2026), so such a query gets no results instead of a +//! failure. +//! +//! The hits carry no description, license, size or counts. The full record +//! (`/v2/articles/{id}`) has the first three and the stats service +//! (`stats.figshare.com/total/article/{id}`) the counts, each one more +//! request per hit, while Figshare asks clients to send at most one request +//! per second (Figshare, October 2026): ten hits would take ten seconds and +//! miss the search's grace period, so the hits stay as the search sends them. +//! The DOI Figshare mints names a version (`.33059219.v2`); the same DOI +//! without `.v2` is registered as well and resolves to the latest version +//! (doi.org, October 2026), so it travels as an alias that folds versions of +//! one article together. Metadata is CC0, which allows caching it (Figshare, +//! October 2026). use serde_json::{Value, json}; @@ -56,9 +66,23 @@ fn record(row: &Value) -> Option { .doi_from(text(row, "/doi")); dataset.updated = day(first_text(row, &["/modified_date", "/published_date"])); + dataset.aliases = dataset + .doi + .as_deref() + .zip(text(row, "/id")) + .and_then(|(doi, id)| unversioned(doi, &id)) + .into_iter() + .collect(); dataset.valid() } +fn unversioned(doi: &str, id: &str) -> Option { + let (base, version) = doi.rsplit_once(".v")?; + let numbered = + !version.is_empty() && version.chars().all(|c| c.is_ascii_digit()); + (numbered && base.ends_with(&format!(".{id}"))).then(|| base.to_owned()) +} + #[cfg(test)] mod tests { use super::*; @@ -87,7 +111,7 @@ mod tests { updated: Some("2026-10-06".into()), size_bytes: None, popularity: None, - aliases: vec![], + aliases: vec!["10.6084/m9.figshare.33059219".into()], } ); assert_eq!( @@ -101,6 +125,8 @@ mod tests { hits[1].doi.as_deref(), Some("10.3389/fmars.2026.1835248.s001") ); + assert_eq!(hits[1].aliases, Vec::::new()); + assert_eq!(hits[3].aliases, ["10.34474/data.jmsj.29191208"]); } #[test] From 11b4e9383674ff8d84f08b81a943b3a02fc819d3 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:36:57 +0100 Subject: [PATCH 09/31] feat: NASA CMR results link the dataset's landing page and carry its license link and collection size --- src/sources/cmr.rs | 162 ++- tests/fixtures/sources/cmr.tempo.json | 1717 +++++++++++++++++++++++++ 2 files changed, 1868 insertions(+), 11 deletions(-) create mode 100644 tests/fixtures/sources/cmr.tempo.json diff --git a/src/sources/cmr.rs b/src/sources/cmr.rs index a6fb7cb..819f055 100644 --- a/src/sources/cmr.rs +++ b/src/sources/cmr.rs @@ -11,13 +11,25 @@ //! come back by relevance, so one request covers any limit and keeps the //! source's order. CMR answers HTTP 400 to a keyword that mixes a quoted //! phrase with words or leaves a quote open, which `keyword` prevents. -//! Clients are asked to name themselves in `Client-Id`. +//! Clients are asked to name themselves in `Client-Id`. Throttling has no +//! published numbers: a client over a rule gets 429 with `retry-after` +//! (CMR search API, October 2026). +//! +//! The link is the provider's "DATA SET LANDING PAGE" from `RelatedUrls` +//! (a doi.org link or the archive's page), else the DOI, else CMR's own +//! HTML view of the record. The license is the `UseConstraints.LicenseURL` +//! link, the only machine form UMM-C has; most records give free text +//! instead, which is not a license id. The size is the collection total +//! from `ArchiveAndDistributionInformation`, in decimal units; the schema +//! names KB to PB without saying which (UMM-C 1.18.6, October 2026). The +//! usage score CMR ranks by is not in any search response, only in a +//! separate whole-catalog table. use serde_json::Value; use super::Ctx; use crate::http::SourceError; -use crate::record::{Dataset, day, items, text}; +use crate::record::{Dataset, day, doi, items, text}; pub fn search( ctx: &Ctx<'_>, @@ -57,12 +69,17 @@ pub(super) fn parse( fn record(item: &Value) -> Option { let id = text(item, "/meta/concept-id")?; - let mut dataset = Dataset::new( - &text(item, "/umm/EntryTitle")?, - &format!("https://cmr.earthdata.nasa.gov/search/concepts/{id}.html"), - ) - .describe(text(item, "/umm/Abstract")) - .doi_from(text(item, "/umm/DOI/DOI")); + let doi = text(item, "/umm/DOI/DOI").and_then(|raw| doi(&raw)); + let url = landing_page(item) + .or_else(|| doi.as_ref().map(|doi| format!("https://doi.org/{doi}"))) + .unwrap_or_else(|| { + format!("https://cmr.earthdata.nasa.gov/search/concepts/{id}.html") + }); + let mut dataset = Dataset::new(&text(item, "/umm/EntryTitle")?, &url) + .describe(text(item, "/umm/Abstract")); + dataset.doi = doi; + dataset.license = text(item, "/umm/UseConstraints/LicenseURL/Linkage"); + dataset.size_bytes = total_size(item); let centers = items(item, "/umm/DataCenters"); let archive = centers.iter().find(|center| { items(center, "/Roles").iter().any(|role| role == "ARCHIVER") @@ -79,6 +96,51 @@ fn record(item: &Value) -> Option { dataset.valid() } +/// The first landing page that is a plain web link; some records put a +/// bare DOI there. +fn landing_page(item: &Value) -> Option { + items(item, "/umm/RelatedUrls") + .iter() + .filter(|link| { + link.get("Type") + .is_some_and(|kind| kind == "DATA SET LANDING PAGE") + }) + .filter_map(|link| text(link, "/URL")) + .find(|url| { + url.starts_with("http") && !url.contains(char::is_whitespace) + }) +} + +/// The collection's total size, archive figures before distribution ones. +fn total_size(item: &Value) -> Option { + let info = item.pointer("/umm/ArchiveAndDistributionInformation")?; + items(info, "/FileArchiveInformation") + .iter() + .chain(items(info, "/FileDistributionInformation")) + .find_map(|file| { + let size = file.get("TotalCollectionFileSize")?.as_f64()?; + let unit = + match file.get("TotalCollectionFileSizeUnit")?.as_str()? { + "KB" => 1e3, + "MB" => 1e6, + "GB" => 1e9, + "TB" => 1e12, + "PB" => 1e15, + _ => return None, + }; + (size > 0.0).then(|| bytes((size * unit).round())) + }) +} + +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "a positive approximate size; whole bytes are the intent" +)] +fn bytes(size: f64) -> u64 { + size as u64 +} + #[cfg(test)] mod tests { use super::*; @@ -92,9 +154,7 @@ mod tests { hits[0], Dataset { title: "ATLAS/ICESat-2 L3A Sea Ice Freeboard V007".into(), - url: "https://cmr.earthdata.nasa.gov/search/concepts/\ - C3565574246-NSIDC_CPRD.html" - .into(), + url: "https://doi.org/10.5067/atlas/atl10.007".into(), description: Some( "ATL10 contains along-track sea ice freeboard calculated \ for 10 km swath segments. The data were acquired by the \ @@ -113,6 +173,86 @@ mod tests { ); } + #[test] + fn license_size_and_landing_page_map_from_a_recorded_search() { + let hits = parse(&fixture::json("cmr.tempo.json"), 10).unwrap(); + assert_eq!(hits.len(), 4); + assert_eq!( + hits[0], + Dataset { + title: "TEMPO NO2 tropospheric and stratospheric columns V04 \ + (PROVISIONAL)" + .into(), + url: "https://doi.org/10.5067/IS-40e/TEMPO/NO2_L2.004".into(), + description: Some( + "Nitrogen dioxide Level 2 (PROVISIONAL) files provide \ + trace gas information at TEMPO\u{2019}s native spatial \ + resolution, ~10 km^2 at the center of the Field of \ + Regard (FOR), for individual granules. Each granule \ + covers the entire North-South TEMPO FOR but only a \ + portion of the East-West FOR." + .into() + ), + publisher: Some("NASA/LARC/SD/ASDC".into()), + doi: Some("10.5067/is-40e/tempo/no2_l2.004".into()), + license: Some( + "https://www.earthdata.nasa.gov/engage/\ + open-data-services-software-policies/data-use-guidance" + .into() + ), + updated: Some("2026-10-16".into()), + size_bytes: Some(15_000_000_000_000), + popularity: None, + aliases: vec![], + } + ); + } + + #[test] + fn the_size_is_the_collection_total_in_decimal_units() { + let hits = parse(&fixture::json("cmr.tempo.json"), 10).unwrap(); + let sizes: Vec<_> = hits.iter().map(|h| h.size_bytes).collect(); + assert_eq!( + sizes, + [ + Some(15_000_000_000_000), + Some(12_000_000_000_000), + Some(247_000_000_000), + Some(175_000_000_000), + ] + ); + let hits = parse(&fixture::json("cmr.json"), 10).unwrap(); + assert!(hits.iter().all(|h| h.size_bytes.is_none())); + } + + #[test] + fn the_link_is_the_landing_page_else_the_doi_else_the_cmr_page() { + let tempo = parse(&fixture::json("cmr.tempo.json"), 10).unwrap(); + let older = parse(&fixture::json("cmr.json"), 10).unwrap(); + let urls: Vec<_> = + tempo.iter().chain(&older).map(|h| h.url.as_str()).collect(); + assert_eq!( + urls, + [ + "https://doi.org/10.5067/IS-40e/TEMPO/NO2_L2.004", + "https://doi.org/10.5067/IS-40e/TEMPO/NO2_L3.004", + "https://doi.org/10.5067/IS-40e/TEMPO/NO2_NRT_L2.002", + "https://doi.org/10.5067/is-40e/tempo/no2_nrt_l3.002", + "https://doi.org/10.5067/atlas/atl10.007", + "https://doi.org/10.5067/amsru/au_si12_nrt_r04", + "https://doi.org/10.26179/5d37f84cbf569", + "https://cmr.earthdata.nasa.gov/search/concepts/\ + C2545372296-AMD_USAPDC.html", + ] + ); + } + + #[test] + fn only_a_license_link_counts_as_a_license() { + let hits = parse(&fixture::json("cmr.json"), 10).unwrap(); + assert!(hits.iter().all(|h| h.license.is_none())); + } + #[test] fn the_doi_comes_from_the_records_own_field() { let hits = parse(&fixture::json("cmr.json"), 10).unwrap(); diff --git a/tests/fixtures/sources/cmr.tempo.json b/tests/fixtures/sources/cmr.tempo.json new file mode 100644 index 0000000..f450dd0 --- /dev/null +++ b/tests/fixtures/sources/cmr.tempo.json @@ -0,0 +1,1717 @@ +{ + "hits": 183, + "took": 40, + "items": [ + { + "meta": { + "revision-id": 26, + "deleted": false, + "format": "application/vnd.nasa.cmr.umm+json", + "provider-id": "LARC_CLOUD", + "has-combine": true, + "user-id": "crdowney", + "has-formats": false, + "associations": { + "variables": [ + "V3730342406-LARC_CLOUD", + "V3730342049-LARC_CLOUD", + "V3730342366-LARC_CLOUD", + "V3730342893-LARC_CLOUD" + ], + "services": [ + "S3616918926-LARC_CLOUD", + "S2874702816-XYZ_PROV", + "S2940253910-LARC_CLOUD" + ], + "visualizations": [ + "VIS4086807728-ESDIS", + "VIS4086807726-ESDIS" + ], + "data-quality-summaries": [ + "DQS3707684858-LARC_CLOUD" + ] + }, + "s3-links": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L2_V04" + ], + "has-spatial-subsetting": true, + "native-id": "TEMPO_NO2_L2_V04", + "has-transforms": true, + "association-details": { + "variables": [ + { + "concept-id": "V3730342406-LARC_CLOUD" + }, + { + "concept-id": "V3730342049-LARC_CLOUD" + }, + { + "concept-id": "V3730342366-LARC_CLOUD" + }, + { + "concept-id": "V3730342893-LARC_CLOUD" + } + ], + "services": [ + { + "concept-id": "S3616918926-LARC_CLOUD" + }, + { + "concept-id": "S2874702816-XYZ_PROV" + }, + { + "concept-id": "S2940253910-LARC_CLOUD" + } + ], + "visualizations": [ + { + "concept-id": "VIS4086807728-ESDIS" + }, + { + "concept-id": "VIS4086807726-ESDIS" + } + ], + "data-quality-summaries": [ + { + "concept-id": "DQS3707684858-LARC_CLOUD" + } + ] + }, + "has-variables": true, + "concept-id": "C3685896872-LARC_CLOUD", + "revision-date": "2026-10-16T16:42:45.971Z", + "has-temporal-subsetting": true, + "concept-type": "collection" + }, + "umm": { + "DataLanguage": "English", + "AncillaryKeywords": [ + "vertical column troposphere", + "vertical column stratosphere" + ], + "CollectionCitations": [ + { + "Creator": "Caroline R Nowlan, Gonzalo González Abad, Huiqun Wang, John C Houck, & Xiong Liu", + "Title": "TEMPO NO2 tropospheric and stratospheric columns V04 (PROVISIONAL)", + "Version": "V04", + "ReleaseDate": "2025-09-17T00:00:00.000Z" + } + ], + "AdditionalAttributes": [ + { + "Name": "CUMULUS", + "Description": "Cumulus flag", + "DataType": "BOOLEAN" + } + ], + "SpatialExtent": { + "HorizontalSpatialDomain": { + "Geometry": { + "GPolygons": [ + { + "Boundary": { + "Points": [ + { + "Longitude": -170, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 80 + }, + { + "Longitude": -170, + "Latitude": 80 + } + ] + } + } + ], + "CoordinateSystem": "CARTESIAN" + }, + "ResolutionAndCoordinateSystem": { + "HorizontalDataResolution": { + "NonGriddedResolutions": [ + { + "XDimension": 4.75, + "YDimension": 2, + "Unit": "Kilometers", + "ViewingAngleType": "At Nadir" + } + ] + } + } + }, + "SpatialCoverageType": "HORIZONTAL", + "GranuleSpatialRepresentation": "CARTESIAN" + }, + "CollectionProgress": "ACTIVE", + "StandardProduct": false, + "ScienceKeywords": [ + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "ATMOSPHERIC CHEMISTRY", + "VariableLevel1": "NITROGEN COMPOUNDS", + "VariableLevel2": "NITROGEN DIOXIDE" + }, + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "AIR QUALITY", + "VariableLevel1": "NITROGEN OXIDES" + } + ], + "TemporalExtents": [ + { + "RangeDateTimes": [ + { + "BeginningDateTime": "2023-08-02T00:00:00.000Z" + } + ], + "EndsAtPresentFlag": true, + "TemporalResolution": { + "Value": 6, + "Unit": "Minute" + } + } + ], + "ProcessingLevel": { + "Id": "2" + }, + "DOI": { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L2.004", + "Authority": "https://doi.org/" + }, + "ShortName": "TEMPO_NO2_L2", + "EntryTitle": "TEMPO NO2 tropospheric and stratospheric columns V04 (PROVISIONAL)", + "DirectDistributionInformation": { + "S3BucketAndObjectPrefixNames": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L2_V04" + ], + "Region": "us-west-2", + "S3CredentialsAPIEndpoint": "https://data.asdc.earthdata.nasa.gov/s3credentials", + "S3CredentialsAPIDocumentationURL": "https://data.asdc.earthdata.nasa.gov/s3credentialsREADME" + }, + "AccessConstraints": { + "Value": 4, + "Description": "WORLD" + }, + "MetadataLanguage": "English", + "RelatedUrls": [ + { + "Description": "TEMPO project page", + "URLContentType": "CollectionURL", + "Type": "PROJECT HOME PAGE", + "URL": "https://tempo.si.edu" + }, + { + "Description": "DOI data set landing page for TEMPO_NO2_L2_V04", + "URLContentType": "CollectionURL", + "Type": "DATA SET LANDING PAGE", + "URL": "https://doi.org/10.5067/IS-40e/TEMPO/NO2_L2.004" + }, + { + "Description": "Mission Logo", + "URLContentType": "VisualizationURL", + "Type": "GET RELATED VISUALIZATION", + "Subtype": "WORLDVIEW", + "URL": "https://asdc.larc.nasa.gov/static/images/project_logos/tempo.png" + }, + { + "Description": "How to cite ASDC data", + "URLContentType": "PublicationURL", + "Type": "VIEW RELATED INFORMATION", + "Subtype": "DATA CITATION GUIDELINES", + "URL": "https://asdc.larc.nasa.gov/citing-data" + } + ], + "DataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-08T00:00:00.000Z" + } + ], + "Abstract": "Nitrogen dioxide Level 2 (PROVISIONAL) files provide trace gas information at TEMPO’s native spatial resolution, ~10 km^2 at the center of the Field of Regard (FOR), for individual granules. Each granule covers the entire North-South TEMPO FOR but only a portion of the East-West FOR.", + "Purpose": "The Tropospheric Emissions: Monitoring of Pollution (TEMPO) V04 data products are processed using the TEMPO Science Data Processing Center (SDPC) software that is operational as of September 2025.", + "LocationKeywords": [ + { + "Category": "CONTINENT", + "Type": "NORTH AMERICA" + } + ], + "MetadataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-08T00:00:00.000Z" + } + ], + "MetadataAssociations": [ + { + "Type": "PARENT", + "EntryId": "TEMPO_NO2_L2", + "Description": "Preceding version", + "Version": "V03" + } + ], + "VersionDescription": "Review the User Guide for more information", + "Version": "V04", + "Projects": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ], + "UseConstraints": { + "LicenseURL": { + "Name": "Data Use Guidance", + "Linkage": "https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "Description": "The Earth Observing System Data and Information System (EOSDIS) data use guidance for NASA data." + }, + "Description": "For more information, see the ESDIS Data Use Guidance: https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "FreeAndOpenData": true + }, + "ContactPersons": [ + { + "Roles": [ + "Technical Contact" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory,", + "60 Garden Street,", + "MS-50" + ], + "Country": "United States", + "City": "Cambridge", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Caroline", + "LastName": "Nowlan" + }, + { + "Roles": [ + "Investigator" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory", + "60 Garden Street" + ], + "Country": "United States", + "City": "Cambridge", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Xiong", + "LastName": "Liu" + } + ], + "AssociatedDOIs": [ + { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L2.001", + "Type": "IsNewVersionOf" + }, + { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L2.003", + "Type": "IsNewVersionOf" + } + ], + "DataCenters": [ + { + "Roles": [ + "ARCHIVER" + ], + "ContactPersons": [ + { + "Roles": [ + "Data Center Contact" + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataContactURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "support-asdc@earthdata.nasa.gov" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "NASA Langley Atmospheric Science Data Center", + "User and Data Services", + "NASA Langley Research Center" + ], + "Country": "United States", + "City": "Hampton", + "PostalCode": "23681-2199" + } + ] + }, + "FirstName": "ASDC", + "LastName": "USER SERVICES" + } + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataCenterURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ] + }, + "ShortName": "NASA/LARC/SD/ASDC", + "LongName": "Atmospheric Science Data Center, Science Directorate, Langley Research Center, NASA" + } + ], + "Platforms": [ + { + "Type": "Earth Observation Satellites", + "ShortName": "IS-40e", + "LongName": "Intelsat 40e", + "Instruments": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ] + } + ], + "MetadataSpecification": { + "URL": "https://cdn.earthdata.nasa.gov/umm/collection/v1.18.6", + "Name": "UMM-C", + "Version": "1.18.6" + }, + "ArchiveAndDistributionInformation": { + "FileArchiveInformation": [ + { + "Format": "netCDF-4" + } + ], + "FileDistributionInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 15, + "TotalCollectionFileSizeUnit": "TB" + } + ] + } + } + }, + { + "meta": { + "revision-id": 24, + "deleted": false, + "format": "application/vnd.nasa.cmr.umm+json", + "provider-id": "LARC_CLOUD", + "has-combine": false, + "user-id": "crdowney", + "has-formats": true, + "associations": { + "variables": [ + "V3730339117-LARC_CLOUD", + "V3730339228-LARC_CLOUD", + "V3730338747-LARC_CLOUD", + "V3730338673-LARC_CLOUD" + ], + "services": [ + "S3616918458-LARC_CLOUD", + "S2164732315-XYZ_PROV", + "S2874702816-XYZ_PROV" + ], + "visualizations": [ + "VIS4086808246-ESDIS", + "VIS4086808301-ESDIS" + ], + "data-quality-summaries": [ + "DQS3707684858-LARC_CLOUD" + ] + }, + "s3-links": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L3_V04" + ], + "has-spatial-subsetting": true, + "native-id": "TEMPO_NO2_L3_V04", + "has-transforms": true, + "association-details": { + "variables": [ + { + "concept-id": "V3730339117-LARC_CLOUD" + }, + { + "concept-id": "V3730339228-LARC_CLOUD" + }, + { + "concept-id": "V3730338747-LARC_CLOUD" + }, + { + "concept-id": "V3730338673-LARC_CLOUD" + } + ], + "services": [ + { + "concept-id": "S3616918458-LARC_CLOUD" + }, + { + "concept-id": "S2164732315-XYZ_PROV" + }, + { + "concept-id": "S2874702816-XYZ_PROV" + } + ], + "visualizations": [ + { + "concept-id": "VIS4086808246-ESDIS" + }, + { + "concept-id": "VIS4086808301-ESDIS" + } + ], + "data-quality-summaries": [ + { + "concept-id": "DQS3707684858-LARC_CLOUD" + } + ] + }, + "has-variables": true, + "concept-id": "C3685896708-LARC_CLOUD", + "revision-date": "2026-10-16T17:32:20.280Z", + "has-temporal-subsetting": true, + "concept-type": "collection" + }, + "umm": { + "DataLanguage": "English", + "AncillaryKeywords": [ + "vertical column troposphere", + "vertical column stratosphere" + ], + "CollectionCitations": [ + { + "Version": "V04", + "Title": "TEMPO gridded NO2 tropospheric and stratospheric columns V04 (PROVISIONAL)", + "Creator": "Caroline R Nowlan, Gonzalo González Abad, Huiqun Wang, John C Houck, & Xiong Liu", + "ReleaseDate": "2025-09-17T00:00:00.000Z" + } + ], + "AdditionalAttributes": [ + { + "Name": "CUMULUS", + "Description": "Cumulus flag", + "DataType": "BOOLEAN" + } + ], + "SpatialExtent": { + "HorizontalSpatialDomain": { + "Geometry": { + "GPolygons": [ + { + "Boundary": { + "Points": [ + { + "Longitude": -170, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 80 + }, + { + "Longitude": -170, + "Latitude": 80 + } + ] + } + } + ], + "CoordinateSystem": "CARTESIAN" + }, + "ResolutionAndCoordinateSystem": { + "HorizontalDataResolution": { + "GriddedResolutions": [ + { + "XDimension": 0.02, + "YDimension": 0.02, + "Unit": "Decimal Degrees" + } + ] + } + } + }, + "SpatialCoverageType": "HORIZONTAL", + "GranuleSpatialRepresentation": "CARTESIAN" + }, + "CollectionProgress": "ACTIVE", + "StandardProduct": false, + "ScienceKeywords": [ + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "ATMOSPHERIC CHEMISTRY", + "VariableLevel1": "NITROGEN COMPOUNDS", + "VariableLevel2": "NITROGEN DIOXIDE" + }, + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "AIR QUALITY", + "VariableLevel1": "NITROGEN OXIDES" + } + ], + "TemporalExtents": [ + { + "RangeDateTimes": [ + { + "BeginningDateTime": "2023-08-02T00:00:00.000Z" + } + ], + "EndsAtPresentFlag": true, + "TemporalResolution": { + "Unit": "Hour", + "Value": 1 + } + } + ], + "ProcessingLevel": { + "Id": "3" + }, + "DOI": { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L3.004", + "Authority": "https://doi.org/" + }, + "ShortName": "TEMPO_NO2_L3", + "EntryTitle": "TEMPO gridded NO2 tropospheric and stratospheric columns V04 (PROVISIONAL)", + "DirectDistributionInformation": { + "S3BucketAndObjectPrefixNames": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L3_V04" + ], + "Region": "us-west-2", + "S3CredentialsAPIEndpoint": "https://data.asdc.earthdata.nasa.gov/s3credentials", + "S3CredentialsAPIDocumentationURL": "https://data.asdc.earthdata.nasa.gov/s3credentialsREADME" + }, + "AccessConstraints": { + "Value": 4, + "Description": "WORLD" + }, + "MetadataLanguage": "English", + "RelatedUrls": [ + { + "Description": "TEMPO project page", + "URLContentType": "CollectionURL", + "Type": "PROJECT HOME PAGE", + "URL": "https://tempo.si.edu" + }, + { + "Description": "DOI data set landing page for TEMPO_NO2_L3_V04 (PROVISIONAL)", + "URLContentType": "CollectionURL", + "Type": "DATA SET LANDING PAGE", + "URL": "https://doi.org/10.5067/IS-40e/TEMPO/NO2_L3.004" + }, + { + "Description": "Mission Logo", + "URLContentType": "VisualizationURL", + "Type": "GET RELATED VISUALIZATION", + "Subtype": "WORLDVIEW", + "URL": "https://asdc.larc.nasa.gov/static/images/project_logos/tempo.png" + }, + { + "Description": "How to cite ASDC data", + "URLContentType": "PublicationURL", + "Type": "VIEW RELATED INFORMATION", + "Subtype": "DATA CITATION GUIDELINES", + "URL": "https://asdc.larc.nasa.gov/citing-data" + } + ], + "DataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-08T00:00:00.000Z" + } + ], + "Abstract": "Nitrogen dioxide Level 3 (PROVISIONAL) files provide trace gas information on a regular grid covering the TEMPO field of regard for nominal TEMPO observations. Level 3 files are derived by combining information from all Level 2 files constituting a TEMPO East-West scan cycle.", + "Purpose": "The Tropospheric Emissions: Monitoring of Pollution (TEMPO) V04 (PROVISIONAL) data products are processed using the TEMPO Science Data Processing Center (SDPC) software that is operational as of September 2025.", + "LocationKeywords": [ + { + "Category": "CONTINENT", + "Type": "NORTH AMERICA" + } + ], + "MetadataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-15T00:00:00.000Z" + } + ], + "MetadataAssociations": [ + { + "Type": "PARENT", + "EntryId": "TEMPO_NO2_L3", + "Description": "Preceding version", + "Version": "V03" + } + ], + "VersionDescription": "Review the User Guide for more information", + "Version": "V04", + "Projects": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ], + "UseConstraints": { + "LicenseURL": { + "Name": "Data Use Guidance", + "Linkage": "https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "Description": "The Earth Observing System Data and Information System (EOSDIS) data use guidance for NASA data." + }, + "Description": "For more information, see the ESDIS Data Use Guidance: https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "FreeAndOpenData": true + }, + "ContactPersons": [ + { + "Roles": [ + "Technical Contact" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory,", + "60 Garden Street,", + "MS-50" + ], + "Country": "United States", + "City": "Cambridge", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Caroline", + "LastName": "Nowlan" + }, + { + "Roles": [ + "Investigator" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory,", + "60 Garden Street" + ], + "City": "Cambridge", + "Country": "United States", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Xiong", + "LastName": "Liu" + } + ], + "AssociatedDOIs": [ + { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L3.001", + "Type": "IsNewVersionOf" + }, + { + "DOI": "10.5067/IS-40e/TEMPO/NO2_L3.003", + "Type": "IsNewVersionOf" + } + ], + "DataCenters": [ + { + "Roles": [ + "ARCHIVER" + ], + "ContactPersons": [ + { + "Roles": [ + "Data Center Contact" + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataContactURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "ContactMechanisms": [ + { + "Type": "Telephone", + "Value": "757-864-8656" + }, + { + "Type": "Email", + "Value": "support-asdc@earthdata.nasa.gov" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "NASA Langley Atmospheric Science Data Center", + "User and Data Services", + "NASA Langley Research Center" + ], + "Country": "United States", + "City": "Hampton", + "PostalCode": "23681-2199" + } + ] + }, + "FirstName": "ASDC", + "LastName": "USER SERVICES" + } + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataCenterURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "Addresses": [ + { + "Country": "United States" + } + ] + }, + "ShortName": "NASA/LARC/SD/ASDC", + "LongName": "Atmospheric Science Data Center, Science Directorate, Langley Research Center, NASA" + } + ], + "Platforms": [ + { + "Instruments": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ], + "Type": "Earth Observation Satellites", + "ShortName": "IS-40e", + "LongName": "Intelsat 40e" + } + ], + "MetadataSpecification": { + "URL": "https://cdn.earthdata.nasa.gov/umm/collection/v1.18.6", + "Name": "UMM-C", + "Version": "1.18.6" + }, + "ArchiveAndDistributionInformation": { + "FileArchiveInformation": [ + { + "Format": "netCDF-4" + } + ], + "FileDistributionInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 12, + "TotalCollectionFileSizeUnit": "TB" + } + ] + } + } + }, + { + "meta": { + "revision-id": 23, + "deleted": false, + "format": "application/vnd.nasa.cmr.umm+json", + "provider-id": "LARC_CLOUD", + "has-combine": true, + "user-id": "crdowney", + "has-formats": false, + "associations": { + "variables": [ + "V3730377986-LARC_CLOUD", + "V3730378422-LARC_CLOUD", + "V3730363485-LARC_CLOUD", + "V3730377878-LARC_CLOUD" + ], + "services": [ + "S3616918926-LARC_CLOUD", + "S2874702816-XYZ_PROV", + "S2940253910-LARC_CLOUD" + ], + "visualizations": [ + "VIS4086808671-ESDIS", + "VIS4086808663-ESDIS" + ], + "data-quality-summaries": [ + "DQS3707678175-LARC_CLOUD" + ] + }, + "s3-links": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L2_NRT_V02" + ], + "has-spatial-subsetting": true, + "native-id": "TEMPO_NO2_L2_NRT_V02", + "has-transforms": true, + "association-details": { + "variables": [ + { + "concept-id": "V3730377986-LARC_CLOUD" + }, + { + "concept-id": "V3730378422-LARC_CLOUD" + }, + { + "concept-id": "V3730363485-LARC_CLOUD" + }, + { + "concept-id": "V3730377878-LARC_CLOUD" + } + ], + "services": [ + { + "concept-id": "S3616918926-LARC_CLOUD" + }, + { + "concept-id": "S2874702816-XYZ_PROV" + }, + { + "concept-id": "S2940253910-LARC_CLOUD" + } + ], + "visualizations": [ + { + "concept-id": "VIS4086808671-ESDIS" + }, + { + "concept-id": "VIS4086808663-ESDIS" + } + ], + "data-quality-summaries": [ + { + "concept-id": "DQS3707678175-LARC_CLOUD" + } + ] + }, + "has-variables": true, + "concept-id": "C3685668972-LARC_CLOUD", + "revision-date": "2026-10-16T16:37:51.571Z", + "has-temporal-subsetting": true, + "concept-type": "collection" + }, + "umm": { + "DataLanguage": "English", + "CollectionCitations": [ + { + "Creator": "Caroline R Nowlan, Gonzalo González Abad, Huiqun Wang, John Houck, & Xiong Liu", + "Version": "V02", + "Title": "TEMPO NO2 tropospheric and stratospheric columns V02 (NRT) (PROVISIONAL)", + "ReleaseDate": "2025-09-17T00:00:00.000Z" + } + ], + "AdditionalAttributes": [ + { + "Name": "CUMULUS", + "Description": "Cumulus flag", + "DataType": "BOOLEAN" + } + ], + "SpatialExtent": { + "HorizontalSpatialDomain": { + "Geometry": { + "GPolygons": [ + { + "Boundary": { + "Points": [ + { + "Longitude": -170, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 80 + }, + { + "Longitude": -170, + "Latitude": 80 + } + ] + } + } + ], + "CoordinateSystem": "CARTESIAN" + }, + "ResolutionAndCoordinateSystem": { + "HorizontalDataResolution": { + "NonGriddedResolutions": [ + { + "XDimension": 4.75, + "YDimension": 2, + "Unit": "Kilometers", + "ViewingAngleType": "At Nadir" + } + ] + } + } + }, + "SpatialCoverageType": "HORIZONTAL", + "GranuleSpatialRepresentation": "CARTESIAN" + }, + "CollectionProgress": "ACTIVE", + "StandardProduct": false, + "ScienceKeywords": [ + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "ATMOSPHERIC CHEMISTRY", + "VariableLevel1": "NITROGEN COMPOUNDS", + "VariableLevel2": "NITROGEN DIOXIDE" + }, + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "AIR QUALITY", + "VariableLevel1": "NITROGEN OXIDES" + }, + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "AIR QUALITY", + "VariableLevel1": "TROPOSPHERIC OZONE" + } + ], + "TemporalExtents": [ + { + "RangeDateTimes": [ + { + "BeginningDateTime": "2025-09-17T00:00:00.000Z" + } + ], + "EndsAtPresentFlag": true, + "TemporalResolution": { + "Value": 6, + "Unit": "Minute" + } + } + ], + "ProcessingLevel": { + "Id": "2" + }, + "DOI": { + "DOI": "10.5067/IS-40e/TEMPO/NO2_NRT_L2.002", + "Authority": "https://doi.org/" + }, + "ShortName": "TEMPO_NO2_L2_NRT", + "EntryTitle": "TEMPO NO2 tropospheric and stratospheric columns V02 (NRT) PROVISIONAL", + "DirectDistributionInformation": { + "S3BucketAndObjectPrefixNames": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L2_NRT_V02" + ], + "Region": "us-west-2", + "S3CredentialsAPIEndpoint": "https://data.asdc.earthdata.nasa.gov/s3credentials", + "S3CredentialsAPIDocumentationURL": "https://data.asdc.earthdata.nasa.gov/s3credentialsREADME" + }, + "AccessConstraints": { + "Value": 4, + "Description": "WORLD" + }, + "MetadataLanguage": "English", + "RelatedUrls": [ + { + "Description": "TEMPO project page", + "URLContentType": "CollectionURL", + "Type": "PROJECT HOME PAGE", + "URL": "https://tempo.si.edu" + }, + { + "Description": "DOI data set landing page for TEMPO_NO2_L2_NRT_V02", + "URLContentType": "CollectionURL", + "Type": "DATA SET LANDING PAGE", + "URL": "https://doi.org/10.5067/IS-40e/TEMPO/NO2_NRT_L2.002" + }, + { + "Description": "Mission Logo", + "URLContentType": "VisualizationURL", + "Type": "GET RELATED VISUALIZATION", + "Subtype": "WORLDVIEW", + "URL": "https://asdc.larc.nasa.gov/static/images/project_logos/tempo.png" + }, + { + "Description": "How to cite ASDC data", + "URLContentType": "PublicationURL", + "Type": "VIEW RELATED INFORMATION", + "Subtype": "DATA CITATION GUIDELINES", + "URL": "https://asdc.larc.nasa.gov/citing-data" + } + ], + "SpatialInformation": { + "VerticalCoordinateSystem": { + "DepthSystemDefinition": { + "Resolutions": [ + 2000, + 2000 + ], + "DatumName": "Horizontal", + "DistanceUnits": "Meters" + } + }, + "SpatialCoverageType": "Horizontal" + }, + "Abstract": "Nitrogen dioxide Level 2 (PROVISIONAL) files provide trace gas information at TEMPO’s native spatial resolution, ~10 km^2 at the center of the Field of Regard(FOR), for individual granules. Each granule covers the entire North-South TEMPO FOR but only a portion of the East-West FOR.", + "Purpose": "The Tropospheric Emissions: Monitoring of Pollution (TEMPO) Near Real-Time (NRT) V02 data products are processed using the TEMPO Science Data Processing Center (SDPC) software that is operational as of September 2025.", + "LocationKeywords": [ + { + "Category": "CONTINENT", + "Type": "NORTH AMERICA" + } + ], + "MetadataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-28T00:00:00.000Z" + } + ], + "MetadataAssociations": [ + { + "Type": "RELATED", + "EntryId": "TEMPO_NO2_L2", + "Version": "V04" + }, + { + "Type": "PARENT", + "EntryId": "TEMPO_NO2_L2_NRT", + "Version": "V01", + "Description": "Preceding version" + } + ], + "VersionDescription": "Review the User Guide for more information", + "Version": "V02", + "Projects": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + }, + { + "ShortName": "LANCE", + "LongName": "Land, Atmosphere Near real-time Capability for Earth observation" + }, + { + "ShortName": "SNWG", + "LongName": "Satellite Needs Working Group" + } + ], + "UseConstraints": { + "LicenseURL": { + "Name": "Data Use Guidance", + "Linkage": "https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "Description": "The Earth Observing System Data and Information System (EOSDIS) data use guidance for NASA data." + }, + "Description": "For more information, see the ESDIS Data Use Guidance: https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "FreeAndOpenData": true + }, + "ContactPersons": [ + { + "Roles": [ + "Technical Contact" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory,", + "60 Garden Street,", + "MS-50" + ], + "Country": "United States", + "City": "Cambridge", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Caroline", + "LastName": "Nowlan" + } + ], + "CollectionDataType": "NEAR_REAL_TIME", + "DataCenters": [ + { + "Roles": [ + "ARCHIVER" + ], + "ContactPersons": [ + { + "Roles": [ + "Data Center Contact" + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataContactURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "support-asdc@earthdata.nasa.gov" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "NASA Langley Atmospheric Science Data Center", + "User and Data Services", + "NASA Langley Research Center" + ], + "Country": "United States", + "City": "Hampton", + "PostalCode": "23681-2199" + } + ] + }, + "FirstName": "ASDC", + "LastName": "USER SERVICES" + } + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataCenterURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ] + }, + "ShortName": "NASA/LARC/SD/ASDC", + "LongName": "Atmospheric Science Data Center, Science Directorate, Langley Research Center, NASA" + } + ], + "TemporalKeywords": [ + "1 minute - < 1 hour" + ], + "Platforms": [ + { + "Instruments": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ], + "Type": "Earth Observation Satellites", + "ShortName": "IS-40e", + "LongName": "Intelsat 40e" + } + ], + "MetadataSpecification": { + "URL": "https://cdn.earthdata.nasa.gov/umm/collection/v1.18.6", + "Name": "UMM-C", + "Version": "1.18.6" + }, + "ArchiveAndDistributionInformation": { + "FileArchiveInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 247, + "TotalCollectionFileSizeUnit": "GB" + } + ], + "FileDistributionInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 247, + "TotalCollectionFileSizeUnit": "GB" + } + ] + } + } + }, + { + "meta": { + "revision-id": 23, + "deleted": false, + "format": "application/vnd.nasa.cmr.umm+json", + "provider-id": "LARC_CLOUD", + "has-combine": false, + "user-id": "crdowney", + "has-formats": true, + "associations": { + "variables": [ + "V3730348432-LARC_CLOUD", + "V3730348373-LARC_CLOUD", + "V3730348638-LARC_CLOUD", + "V3730348225-LARC_CLOUD" + ], + "services": [ + "S2164732315-XYZ_PROV", + "S3616918458-LARC_CLOUD", + "S2874702816-XYZ_PROV" + ], + "visualizations": [ + "VIS4086808702-ESDIS", + "VIS4086808696-ESDIS" + ], + "data-quality-summaries": [ + "DQS3707678175-LARC_CLOUD" + ] + }, + "s3-links": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L3_NRT_V02" + ], + "has-spatial-subsetting": true, + "native-id": "TEMPO_NO2_L3_NRT_V02", + "has-transforms": true, + "association-details": { + "variables": [ + { + "concept-id": "V3730348432-LARC_CLOUD" + }, + { + "concept-id": "V3730348373-LARC_CLOUD" + }, + { + "concept-id": "V3730348638-LARC_CLOUD" + }, + { + "concept-id": "V3730348225-LARC_CLOUD" + } + ], + "services": [ + { + "concept-id": "S2164732315-XYZ_PROV" + }, + { + "concept-id": "S3616918458-LARC_CLOUD" + }, + { + "concept-id": "S2874702816-XYZ_PROV" + } + ], + "visualizations": [ + { + "concept-id": "VIS4086808702-ESDIS" + }, + { + "concept-id": "VIS4086808696-ESDIS" + } + ], + "data-quality-summaries": [ + { + "concept-id": "DQS3707678175-LARC_CLOUD" + } + ] + }, + "has-variables": true, + "concept-id": "C3685668637-LARC_CLOUD", + "revision-date": "2026-10-16T17:30:46.983Z", + "has-temporal-subsetting": true, + "concept-type": "collection" + }, + "umm": { + "DataLanguage": "English", + "CollectionCitations": [ + { + "Title": "TEMPO gridded NO2 tropospheric and stratospheric columns V02 (NRT) (PROVISIONAL)", + "Version": "V02", + "Creator": "Caroline R Nowlan, Gonzalo González Abad, Huiqun Wang, John C Houck, & Xiong Liu", + "ReleaseDate": "2025-09-17T00:00:00.000Z" + } + ], + "AdditionalAttributes": [ + { + "Name": "CUMULUS", + "Description": "Cumulus flag", + "DataType": "BOOLEAN" + } + ], + "SpatialExtent": { + "HorizontalSpatialDomain": { + "Geometry": { + "GPolygons": [ + { + "Boundary": { + "Points": [ + { + "Longitude": -170, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 10 + }, + { + "Longitude": -10, + "Latitude": 80 + }, + { + "Longitude": -170, + "Latitude": 80 + } + ] + } + } + ], + "CoordinateSystem": "CARTESIAN" + }, + "ResolutionAndCoordinateSystem": { + "HorizontalDataResolution": { + "GriddedResolutions": [ + { + "XDimension": 0.02, + "YDimension": 0.02, + "Unit": "Decimal Degrees" + } + ] + } + } + }, + "SpatialCoverageType": "HORIZONTAL", + "GranuleSpatialRepresentation": "CARTESIAN" + }, + "CollectionProgress": "ACTIVE", + "StandardProduct": false, + "ScienceKeywords": [ + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "ATMOSPHERIC CHEMISTRY", + "VariableLevel1": "NITROGEN COMPOUNDS", + "VariableLevel2": "NITROGEN DIOXIDE" + }, + { + "Category": "EARTH SCIENCE", + "Topic": "ATMOSPHERE", + "Term": "AIR QUALITY", + "VariableLevel1": "NITROGEN OXIDES" + } + ], + "TemporalExtents": [ + { + "RangeDateTimes": [ + { + "BeginningDateTime": "2025-09-17T00:00:00.000Z" + } + ], + "EndsAtPresentFlag": true, + "TemporalResolution": { + "Value": 1, + "Unit": "Hour" + } + } + ], + "ProcessingLevel": { + "Id": "3" + }, + "DOI": { + "DOI": "10.5067/IS-40e/TEMPO/NO2_NRT_L3.002", + "Authority": "https://doi.org/" + }, + "ShortName": "TEMPO_NO2_L3_NRT", + "EntryTitle": "TEMPO gridded NO2 tropospheric and stratospheric columns V02 (NRT) (PROVISIONAL)", + "DirectDistributionInformation": { + "S3BucketAndObjectPrefixNames": [ + "s3://asdc-prod-protected/TEMPO/TEMPO_NO2_L3_NRT_V02" + ], + "Region": "us-west-2", + "S3CredentialsAPIEndpoint": "https://data.asdc.earthdata.nasa.gov/s3credentials", + "S3CredentialsAPIDocumentationURL": "https://data.asdc.earthdata.nasa.gov/s3credentialsREADME" + }, + "AccessConstraints": { + "Value": 4, + "Description": "WORLD" + }, + "MetadataLanguage": "English", + "RelatedUrls": [ + { + "Description": "TEMPO project page", + "URLContentType": "CollectionURL", + "Type": "PROJECT HOME PAGE", + "URL": "https://tempo.si.edu" + }, + { + "Description": "DOI data set landing page for TEMPO_NO2_L3_NRT_V02", + "URLContentType": "CollectionURL", + "Type": "DATA SET LANDING PAGE", + "URL": "10.5067/IS-40e/TEMPO/NO2_NRT_L3.002" + }, + { + "Description": "Mission Logo", + "URLContentType": "VisualizationURL", + "Type": "GET RELATED VISUALIZATION", + "Subtype": "WORLDVIEW", + "URL": "https://asdc.larc.nasa.gov/static/images/project_logos/tempo.png" + }, + { + "Description": "How to cite ASDC data", + "URLContentType": "PublicationURL", + "Type": "VIEW RELATED INFORMATION", + "Subtype": "DATA CITATION GUIDELINES", + "URL": "https://asdc.larc.nasa.gov/citing-data" + } + ], + "SpatialInformation": { + "VerticalCoordinateSystem": { + "AltitudeSystemDefinition": { + "Resolutions": [ + 2, + 2 + ], + "DistanceUnits": "Kilometers" + } + }, + "SpatialCoverageType": "Horizontal" + }, + "DataDates": [ + { + "Type": "CREATE", + "Date": "2025-09-08T13:54:47.768512Z" + } + ], + "Abstract": "Nitrogen dioxide Level 3 (PROVISIONAL) files provide trace gas information on a regular grid covering the TEMPO field of regard for nominal TEMPO observations. Level 3 files are derived by combining information from all Level 2 files constituting a TEMPO East-West scan cycle.", + "Purpose": "The Tropospheric Emissions: Monitoring of Pollution (TEMPO) Near Real-Time (NRT) V02 data products are processed using the TEMPO Science Data Processing Center (SDPC) software that is operational as of September 2025.", + "LocationKeywords": [ + { + "Category": "CONTINENT", + "Type": "NORTH AMERICA" + } + ], + "MetadataDates": [ + { + "Type": "CREATE", + "Date": "2025-07-24T00:00:00.000Z" + } + ], + "MetadataAssociations": [ + { + "Type": "RELATED", + "EntryId": "TEMPO_NO2_L3", + "Version": "V04" + }, + { + "Type": "PARENT", + "EntryId": "TEMPO_NO2_L3_NRT", + "Version": "V01", + "Description": "Preceding version" + } + ], + "VersionDescription": "Review the User Guide for more information", + "Version": "V02", + "Projects": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + }, + { + "ShortName": "LANCE", + "LongName": "Land, Atmosphere Near real-time Capability for Earth observation" + }, + { + "ShortName": "SNWG", + "LongName": "Satellite Needs Working Group" + } + ], + "UseConstraints": { + "LicenseURL": { + "Name": "Data Use Guidance", + "Linkage": "https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "Description": "The Earth Observing System Data and Information System (EOSDIS) data use guidance for NASA data." + }, + "Description": "For more information, see the ESDIS Data Use Guidance: https://www.earthdata.nasa.gov/engage/open-data-services-software-policies/data-use-guidance", + "FreeAndOpenData": true + }, + "ContactPersons": [ + { + "Roles": [ + "Technical Contact" + ], + "ContactInformation": { + "ContactMechanisms": [ + { + "Type": "Email", + "Value": "contact@example.org" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "Smithsonian Astrophysical Observatory,", + "60 Garden Street,", + "MS-50" + ], + "Country": "United States", + "City": "Cambridge", + "PostalCode": "02138" + } + ] + }, + "FirstName": "Caroline", + "LastName": "Nowlan" + } + ], + "CollectionDataType": "NEAR_REAL_TIME", + "DataCenters": [ + { + "Roles": [ + "ARCHIVER" + ], + "ContactPersons": [ + { + "Roles": [ + "Data Center Contact" + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataContactURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "ContactMechanisms": [ + { + "Type": "Telephone", + "Value": "757-864-8656" + }, + { + "Type": "Email", + "Value": "support-asdc@earthdata.nasa.gov" + } + ], + "Addresses": [ + { + "StreetAddresses": [ + "NASA Langley Atmospheric Science Data Center", + "User and Data Services", + "NASA Langley Research Center" + ], + "Country": "United States", + "City": "Hampton", + "PostalCode": "23681-2199" + } + ] + }, + "FirstName": "ASDC", + "LastName": "USER SERVICES" + } + ], + "ContactInformation": { + "RelatedUrls": [ + { + "Description": "Data Center URL", + "URLContentType": "DataCenterURL", + "Type": "HOME PAGE", + "URL": "https://asdc.larc.nasa.gov/" + } + ], + "Addresses": [ + { + "Country": "United States" + } + ] + }, + "ShortName": "NASA/LARC/SD/ASDC", + "LongName": "Atmospheric Science Data Center, Science Directorate, Langley Research Center, NASA" + } + ], + "TemporalKeywords": [ + "Hourly - < Daily" + ], + "Platforms": [ + { + "Instruments": [ + { + "ShortName": "TEMPO", + "LongName": "Tropospheric Emissions: Monitoring of Pollution" + } + ], + "Type": "Earth Observation Satellites", + "ShortName": "IS-40e", + "LongName": "Intelsat 40e" + } + ], + "MetadataSpecification": { + "URL": "https://cdn.earthdata.nasa.gov/umm/collection/v1.18.6", + "Name": "UMM-C", + "Version": "1.18.6" + }, + "ArchiveAndDistributionInformation": { + "FileArchiveInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 175, + "TotalCollectionFileSizeUnit": "GB" + } + ], + "FileDistributionInformation": [ + { + "Format": "netCDF-4", + "TotalCollectionFileSize": 175, + "TotalCollectionFileSizeUnit": "GB" + } + ] + } + } + } + ] +} From cfc06c87f33ba74db2edde9e3bd21d91fd998e4f Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:37:09 +0100 Subject: [PATCH 10/31] fix: show ArcGIS Hub's custom license text, and drop the item size of registered services and the literal null description --- src/sources/arcgis.rs | 152 ++++- tests/fixtures/sources/arcgis.json | 793 +++++++++++++++++++----- tests/fixtures/sources/arcgis.null.json | 215 +++++++ 3 files changed, 979 insertions(+), 181 deletions(-) create mode 100644 tests/fixtures/sources/arcgis.null.json diff --git a/src/sources/arcgis.rs b/src/sources/arcgis.rs index 0692a10..02f2f5d 100644 --- a/src/sources/arcgis.rs +++ b/src/sources/arcgis.rs @@ -3,19 +3,28 @@ //! other collections are `appAndMap`, `document`, `site` and `all`; Hub Search //! API, October 2026). `limit` is at most 100 per request, the same as //! `--per-source`, so one request is enough (Hub Search API definition, -//! October 2026). Results come in relevance order, and a request that reaches -//! past the 10,000th match answers HTTP 500 (probed October 2026). `license` -//! is an SPDX id, with `none` and `custom` for items that set nothing usable -//! (Hub aggregations, October 2026). Responses carry an -//! `X-RateLimit-Limit-PORTAL_SEARCH_THROTTLER` header of 10 with a reset of 1; -//! the docs state no limit (October 2026). `size` is bytes and `modified` is -//! epoch milliseconds (ArcGIS REST item reference, October 2026). +//! October 2026). `q` requires every word, so "air OR quality" matches fewer +//! items than "air quality", and a colon in it matches nothing (probed October +//! 2026). Results come in relevance order, `numberMatched` stops counting at +//! 10,000, and a request that reaches past the 10,000th match answers HTTP +//! 500 (probed October 2026). `license` is an SPDX id that Hub derives from +//! the free-text `licenseInfo`, with `none` for an empty one and `custom` for +//! text it could not map (Hub queryables and aggregations, October 2026). +//! Responses carry an `X-RateLimit-Limit-PORTAL_SEARCH_THROTTLER` header of 10 +//! with a reset of 1; the docs state no limit (October 2026). `size` is bytes +//! and `modified` is epoch milliseconds (ArcGIS REST item reference, October +//! 2026). The terms say nothing on caching search results (Esri Master +//! Agreement, August 2025). use serde_json::Value; use super::Ctx; use crate::http::SourceError; -use crate::record::{Dataset, date_from_epoch, items, number, text}; +use crate::record::{Dataset, clean, date_from_epoch, items, number, text}; + +/// A `custom` license is shown as its publisher wrote it only when it reads +/// like a licence name; longer text is terms of use. +const LONGEST_LICENSE: usize = 100; pub fn search( ctx: &Ctx<'_>, @@ -52,17 +61,50 @@ fn record(feature: &Value) -> Option { &text(props, "/title")?, &format!("https://hub.arcgis.com/datasets/{id}"), ) - .describe(text(props, "/description").or_else(|| text(props, "/snippet"))); + .describe( + written(props, "/description").or_else(|| written(props, "/snippet")), + ); dataset.publisher = text(props, "/source").or_else(|| text(props, "/owner")); - dataset.license = text(props, "/license") - .filter(|l| !matches!(l.as_str(), "custom" | "none")); + dataset.license = license(props); dataset.updated = number(props, "/modified").and_then(date_from_epoch); - dataset.size_bytes = number(props, "/size"); + dataset.size_bytes = + number(props, "/size").filter(|_| stores_its_data(props)); dataset.popularity = number(props, "/numViews"); dataset.valid() } +/// Item text its owner set. Hub sends the string `null` for some items whose +/// owner never wrote one (probed October 2026). +fn written(props: &Value, pointer: &str) -> Option { + text(props, pointer).filter(|t| t != "null") +} + +fn license(props: &Value) -> Option { + match text(props, "/license")?.as_str() { + "none" => None, + "custom" => written(props, "/licenseInfo") + .map(|info| clean(&info)) + .filter(|info| { + info.chars().count() <= LONGEST_LICENSE + && info.chars().any(char::is_alphabetic) + }), + spdx => Some(spdx.to_owned()), + } +} + +/// A registered service's item only points at a server elsewhere, so its +/// `size` is the item's own hundred-odd bytes; hosted services (typeKeyword +/// `Hosted Service`) and file items measure the data (probed October 2026). +fn stores_its_data(props: &Value) -> bool { + let has = |keyword: &str| { + items(props, "/typeKeywords") + .iter() + .any(|k| k.as_str() == Some(keyword)) + }; + !has("Service") || has("Hosted Service") +} + #[cfg(test)] mod tests { use super::*; @@ -71,28 +113,92 @@ mod tests { #[test] fn records_map_from_a_recorded_search() { let hits = parse(&fixture::json("arcgis.json"), 10).unwrap(); - assert_eq!(hits.len(), 5); + assert_eq!(hits.len(), 7); assert_eq!( hits[0], Dataset { - title: "Water".into(), + title: "Air Quality Monitoring".into(), url: "https://hub.arcgis.com/datasets/\ - 27f4373c24fc421c8194d9c813802940" + 1d11bbdb8bca44a2ad62efa6148f99b9" + .into(), + description: None, + publisher: Some("Broward County GIS".into()), + doi: None, + license: None, + updated: Some("2026-08-04".into()), + size_bytes: Some(1658), + popularity: Some(30), + aliases: vec![], + } + ); + assert_eq!( + hits[6], + Dataset { + title: "Air_Monitoring_Sites".into(), + url: "https://hub.arcgis.com/datasets/\ + 4dc97eb2f7f544e9a8340ed840f02873" .into(), description: Some( - "Zipfile with FGDB for City of Richland Public Works \ - Water Utilities." + "Air Monitoring Sites. Obtained from Oklahoma \ + Department of Environmental Quality Fall 2015. The \ + Oklahoma Department of Transportation is not liable \ + for any inaccuracies in this data." .into() ), - publisher: Some("City of Richland, Washington".into()), + publisher: Some( + "Oklahoma Department of Transportation".into() + ), doi: None, - license: None, - updated: Some("2026-09-21".into()), - size_bytes: Some(3_740_026), - popularity: Some(46), + license: Some("Authorized use only.".into()), + updated: Some("2016-03-24".into()), + size_bytes: Some(49_152), + popularity: Some(192), aliases: vec![], } ); - assert_eq!(hits[1].license, None, "\"none\" is Hub's empty license"); + } + + #[test] + fn html_descriptions_and_custom_licenses_become_plain_text() { + let hits = parse(&fixture::json("arcgis.json"), 10).unwrap(); + assert_eq!( + hits[2].description.as_deref(), + Some( + "US EPA feature layer updated to reflect the latest hour of \ + air quality data (Ozone, etc) received from monitoring \ + sites that report to AirNow." + ) + ); + assert_eq!( + hits[3].description.as_deref(), + Some( + "For further information about air quality monitoring - see \ + the City of York Council website" + ) + ); + assert_eq!(hits[2].license.as_deref(), Some("ESRI")); + assert_eq!(hits[3].license, None, "terms of use, not a licence name"); + assert_eq!( + hits[4].license.as_deref(), + Some("Licensed under Open Government Licence") + ); + } + + #[test] + fn only_hosted_services_and_files_report_a_size() { + let hits = parse(&fixture::json("arcgis.json"), 10).unwrap(); + let sizes: Vec<_> = hits.iter().map(|h| h.size_bytes).collect(); + assert_eq!( + sizes, + [Some(1658), Some(32_768), None, None, None, None, Some(49_152)] + ); + } + + #[test] + fn the_string_null_is_no_description() { + let hits = parse(&fixture::json("arcgis.null.json"), 10).unwrap(); + assert_eq!(hits.len(), 2); + assert_eq!(hits[0].title, "air quality"); + assert_eq!(hits[0].description, None); } } diff --git a/tests/fixtures/sources/arcgis.json b/tests/fixtures/sources/arcgis.json index 35f25fd..a16401b 100644 --- a/tests/fixtures/sources/arcgis.json +++ b/tests/fixtures/sources/arcgis.json @@ -2,63 +2,66 @@ "type": "FeatureCollection", "features": [ { - "id": "27f4373c24fc421c8194d9c813802940", + "id": "1d11bbdb8bca44a2ad62efa6148f99b9", "type": "Feature", "geometry": null, "properties": { - "snippet": "FGDB of Public Works Water Utilities.", + "snippet": null, "extent": null, "commentsEnabled": true, "groupDesignations": null, "access": "public", "apiToken2ExpirationDate": -1, "typeKeywords": [ - "File Geodatabase" + "CSV" ], - "description": "

Zipfile with FGDB for  City of Richland Public Works Water Utilities.

", - "licenseInfo": "

US EPA feature layer updated to reflect the latest hour of air quality data (Ozone, etc) received from monitoring sites that report to AirNow.

", + "licenseInfo": "

ESRI

", + "ownerId": "190f12cab121437fb3f20e3b8be79f30", + "title": "Air Quality Monitoring", + "type": "Feature Service", + "orgId": "rQNf5tVFXFoS6EhP", "screenshots": [], - "token2ExpirationDate": -1, "subInfo": 0, "advancedSettings": null, "appCategories": [], - "modified": 1702443834000, + "modified": 1783012124000, "avgRating": 0, - "id": "1b6abea55255434ab95f28499222d477", - "categories": [], - "robots": [ - "noindex", - "nofollow" + "id": "69603610e087445a827fee600710417e", + "categories": [ + "/Categories/Comprehensive/External" ], "spatialReference": null, "numRatings": 0, - "owner": "propsure", - "accessInformation": null, + "owner": "contact@example.org_Lenexa", + "accessInformation": "ESRI", "largeThumbnail": null, - "lastViewed": 1702443600000, - "thumbnail": null, + "lastViewed": 1786827600000, + "thumbnail": "thumbnail/thumbnail1766441543588.png", "languages": [], - "tokenExpirationDate": -1, - "created": 1702443834000, + "created": 1754498463000, "documentation": null, "banner": null, "classification": null, - "url": null, - "tags": [], - "numViews": 1, + "url": "https://services.arcgis.com/cJ9YHowT8TU7DUyn/arcgis/rest/services/Air%20Now%20Current%20Monitor%20Data%20Public/FeatureServer", + "tags": [ + "AirNow", + "AQI", + "Ozone", + "PM" + ], + "numViews": 32, "numComments": 0, - "size": 423696, + "size": 115, "listed": false, - "scoreCompleteness": 0, - "culture": "en-gb", + "scoreCompleteness": 96, + "culture": "en-us", "industries": [], - "name": "water.geojson", + "apiToken1ExpirationDate": -1, + "name": null, "guid": null, "proxyFilter": null, "properties": null, - "source": "propsure", - "license": "none" + "source": "Lenexa, Kansas", + "license": "custom" }, "time": null, "links": [ @@ -223,7 +327,7 @@ "rel": "self", "type": "application/geo+json", "title": "This document as GeoJSON", - "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/1b6abea55255434ab95f28499222d477" + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/69603610e087445a827fee600710417e" }, { "rel": "collection", @@ -234,64 +338,142 @@ ] }, { - "id": "b3064ac66d7e4a679aba2931f777298b", + "id": "d30396f5dba34f48a7205bb4db765c07", "type": "Feature", - "geometry": null, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.1491, + 54.006 + ], + [ + -1.0287, + 54.006 + ], + [ + -1.0287, + 53.9277 + ], + [ + -1.1491, + 53.9277 + ] + ] + ] + }, "properties": { - "snippet": null, - "extent": null, - "commentsEnabled": true, + "snippet": " Air quality monitoring in York", + "extent": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.1491, + 54.006 + ], + [ + -1.0287, + 54.006 + ], + [ + -1.0287, + 53.9277 + ], + [ + -1.1491, + 53.9277 + ] + ] + ] + }, + "commentsEnabled": false, "groupDesignations": null, "access": "public", "apiToken2ExpirationDate": -1, "typeKeywords": [ - "Coordinates Type", - "CRS", - "Feature", - "FeatureCollection", - "GeoJSON" + "ArcGIS Server", + "Data", + "Feature Access", + "Feature Service", + "Service" ], - "description": null, - "licenseInfo": null, - "title": "Water", - "type": "GeoJson", - "orgId": "CQDK7abdVpczSUjn", + "description": "For further information about air quality monitoring - see the City of York Council website", + "licenseInfo": "

© Crown copyright and database rights 2017 Ordnance Survey 100020818

The licensing for this dataset is listed as Derived data exemption - streamlined process

For details of the Open Government Licence (OGL v3.0) - see the National Archives website

", + "ownerId": "44d2b135a845c3e6915c0f80ee37c352", + "title": "AQ Monitoring", + "type": "Feature Service", + "orgId": "PucdQw82gWAXkLji", "screenshots": [], "subInfo": 0, "advancedSettings": null, "appCategories": [], - "modified": 1775860642000, + "modified": 1784815340000, "avgRating": 0, - "id": "b3064ac66d7e4a679aba2931f777298b", + "id": "d30396f5dba34f48a7205bb4db765c07", "categories": [], "spatialReference": null, "numRatings": 0, - "owner": "kokkinen_UofA", - "accessInformation": null, + "owner": "gis_CYC", + "accessInformation": "© Crown copyright and database rights 2017 Ordnance Survey 100020818", "largeThumbnail": null, - "lastViewed": 1776042000000, - "thumbnail": null, + "lastViewed": 1784818800000, + "thumbnail": "thumbnail/thumbnail.png", "languages": [], - "created": 1775860642000, + "created": 1498643987000, "documentation": null, "banner": null, "classification": null, - "url": null, - "tags": [], - "numViews": 42, + "url": "https://maps.york.gov.uk/arcgis/rest/services/Public/EnvPlan/MapServer/20", + "tags": [ + "AQMA", + "monitor", + "AQ" + ], + "numViews": 3358, "numComments": 0, - "size": 3006509, + "size": 73, "listed": false, - "scoreCompleteness": 0, - "culture": "en-us", + "scoreCompleteness": 88, + "culture": "en-gb", "industries": [], "apiToken1ExpirationDate": -1, - "name": "Water.geojson", + "name": null, "guid": null, "proxyFilter": null, - "properties": null, - "source": "University of Alberta", - "license": "none" + "properties": { + "location": { + "extent": [ + [ + -1.1491, + 53.9277 + ], + [ + -1.0287, + 54.006 + ] + ], + "geometries": [ + { + "ymin": 53.9277, + "xmin": -1.1491, + "ymax": 54.006, + "xmax": -1.0287, + "spatialReference": { + "wkid": 4326 + }, + "type": "extent" + } + ], + "type": "custom", + "spatialReference": { + "wkid": 4326 + } + } + }, + "source": "City of York Council", + "license": "custom" }, "time": null, "links": [ @@ -299,7 +481,7 @@ "rel": "self", "type": "application/geo+json", "title": "This document as GeoJSON", - "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/b3064ac66d7e4a679aba2931f777298b" + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/d30396f5dba34f48a7205bb4db765c07" }, { "rel": "collection", @@ -310,66 +492,361 @@ ] }, { - "id": "cb61d161171d43d89ce5a31838a7a33e", + "id": "464af7a6e8614b1bb85663fe7fd2be0c", "type": "Feature", - "geometry": null, + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.1581, + 53.0977 + ], + [ + -1.0572, + 53.0977 + ], + [ + -1.0572, + 52.9545 + ], + [ + -1.1581, + 52.9545 + ] + ] + ] + }, "properties": { - "snippet": null, - "extent": null, + "snippet": "Air Quality Monitoring Points", + "extent": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.1581, + 53.0977 + ], + [ + -1.0572, + 53.0977 + ], + [ + -1.0572, + 52.9545 + ], + [ + -1.1581, + 52.9545 + ] + ] + ] + }, "commentsEnabled": true, "groupDesignations": null, "access": "public", "apiToken2ExpirationDate": -1, "typeKeywords": [ - "Coordinates Type", - "CRS", - "Feature", - "FeatureCollection", - "GeoJSON" + "Feature Access", + "Feature Service", + "ArcGIS Server", + "Service", + "Singlelayer", + "Data" ], - "description": null, - "licenseInfo": null, - "title": "water", - "type": "GeoJson", + "description": "Air Quality Monitoring Points", + "licenseInfo": "OGL Licensed under Open Government Licence", + "title": "Air Quality Monitoring Points", + "type": "Feature Service", + "orgId": "ScBHKZTWsl0UTvga", "screenshots": [], "subInfo": 0, "advancedSettings": null, "appCategories": [], - "modified": 1764779244000, + "modified": 1760011639000, "avgRating": 0, - "id": "cb61d161171d43d89ce5a31838a7a33e", + "id": "464af7a6e8614b1bb85663fe7fd2be0c", "categories": [], - "robots": [ - "noindex", - "nofollow" + "spatialReference": "", + "numRatings": 0, + "owner": "gis_admin2@gbc", + "accessInformation": "", + "largeThumbnail": "", + "lastViewed": 1760518800000, + "thumbnail": "thumbnail/ago_downloaded.png", + "languages": [], + "created": 1759927543000, + "documentation": null, + "banner": "", + "classification": null, + "url": "https://gedlingmaps.gedling.gov.uk/arcgis/rest/services/opendata/Air_Quality_Monitoring/MapServer/0", + "tags": [ + "environment" ], - "spatialReference": null, + "numViews": 29, + "numComments": 0, + "size": 99, + "listed": false, + "scoreCompleteness": 66, + "culture": "en-gb", + "industries": [], + "apiToken1ExpirationDate": -1, + "name": "", + "guid": null, + "proxyFilter": null, + "properties": null, + "source": "Gedling Borough Council", + "license": "custom" + }, + "time": null, + "links": [ + { + "rel": "self", + "type": "application/geo+json", + "title": "This document as GeoJSON", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/464af7a6e8614b1bb85663fe7fd2be0c" + }, + { + "rel": "collection", + "type": "application/json", + "title": "Dataset", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset" + } + ] + }, + { + "id": "b946b3f030b24d0095f7456463ee38ba", + "type": "Feature", + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -111.5558, + 60.0945 + ], + [ + -100.2261, + 60.0945 + ], + [ + -100.2261, + 48.8909 + ], + [ + -111.5558, + 48.8909 + ] + ] + ] + }, + "properties": { + "snippet": "This spatial dataset is an authoritative and dynamic record of current and historical air monitoring stations within the Saskatchewan air zones.", + "extent": { + "type": "Polygon", + "coordinates": [ + [ + [ + -111.5558, + 60.0945 + ], + [ + -100.2261, + 60.0945 + ], + [ + -100.2261, + 48.8909 + ], + [ + -111.5558, + 48.8909 + ] + ] + ] + }, + "commentsEnabled": true, + "groupDesignations": null, + "access": "public", + "apiToken2ExpirationDate": -1, + "typeKeywords": [ + "ArcGIS Server", + "Data", + "Feature Access", + "Feature Service", + "Metadata", + "Multilayer", + "Service" + ], + "description": "


The Ministry of Environment operates continuous ambient air monitoring stations as well as wet depostion monitors. These stations are part of the National Air Pollution Surveillance (NAPS) and Precipitation Monitoring Network (CAPMoN) respectively. Continuous ambient air monitors measure the concentration of air pollutants across Saskatchewan. While, the wet deposition program is to help understand the effects of sulfuric and nitric acids to precipitation across the province.", + "licenseInfo": "Monitoring station location coordinates are extracted from web maps. Coordinates are not GPS verified. The Ministry of Environment distributes this data freely as a service to the people of Saskatchewan and makes no representation that this data is sufficient for all uses. Not for resale.", + "title": "Air Quality", + "type": "Feature Service", + "orgId": "zcv98lgAl8xQ04cW", + "screenshots": [], + "subInfo": 0, + "advancedSettings": null, + "appCategories": [], + "modified": 1690416371000, + "avgRating": 0, + "id": "b946b3f030b24d0095f7456463ee38ba", + "categories": [ + "/Categories/Environment" + ], + "spatialReference": "2151", "numRatings": 0, - "owner": "pasiichnuk", - "accessInformation": null, + "owner": "Saskatchewan.Government", + "accessInformation": "Air Quality, Ministry of Environment. Business Support Services, Ministry of Environment", "largeThumbnail": null, - "lastViewed": 1764777600000, - "thumbnail": null, + "lastViewed": 1724803200000, + "thumbnail": "thumbnail/thumbnail1645743862654.png", "languages": [], - "created": 1764779244000, + "created": 1574813327000, "documentation": null, "banner": null, "classification": null, - "url": null, - "tags": [], - "numViews": 1, + "url": "https://gis.saskatchewan.ca/arcgis/rest/services/EnvironmentalProtection/AirQuality_Public/FeatureServer", + "tags": [ + "air quality", + "saskatchewan", + "air monitor", + "wet deposition monitor" + ], + "numViews": 4501, "numComments": 0, - "size": 25787, + "size": 104, "listed": false, - "scoreCompleteness": 0, - "culture": "uk", + "scoreCompleteness": 100, + "culture": "en-us", "industries": [], "apiToken1ExpirationDate": -1, - "name": "water.geojson", + "name": null, "guid": null, "proxyFilter": null, "properties": null, - "license": "none" + "source": "Saskatchewan Ministry of Environment", + "license": "custom" + }, + "time": null, + "links": [ + { + "rel": "self", + "type": "application/geo+json", + "title": "This document as GeoJSON", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/b946b3f030b24d0095f7456463ee38ba" + }, + { + "rel": "collection", + "type": "application/json", + "title": "Dataset", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset" + } + ] + }, + { + "id": "4dc97eb2f7f544e9a8340ed840f02873", + "type": "Feature", + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -99.93537599990242, + 36.90811500020715 + ], + [ + -95.2938889997775, + 36.90811500020715 + ], + [ + -95.2938889997775, + 33.88081199987397 + ], + [ + -99.93537599990242, + 33.88081199987397 + ] + ] + ] + }, + "properties": { + "extent": { + "type": "Polygon", + "coordinates": [ + [ + [ + -99.93537599990242, + 36.90811500020715 + ], + [ + -95.2938889997775, + 36.90811500020715 + ], + [ + -95.2938889997775, + 33.88081199987397 + ], + [ + -99.93537599990242, + 33.88081199987397 + ] + ] + ] + }, + "snippet": "Air Monitoring Sites - Fall 2015", + "groupDesignations": null, + "commentsEnabled": true, + "access": "public", + "typeKeywords": [ + "ArcGIS Server", + "Data", + "Feature Access", + "Feature Service", + "Metadata", + "Service", + "Singlelayer", + "Hosted Service" + ], + "description": "Air Monitoring Sites. Obtained from Oklahoma Department of Environmental Quality Fall 2015. The Oklahoma Department of Transportation is not liable for any inaccuracies in this data.", + "licenseInfo": "Authorized use only.", + "type": "Feature Service", + "title": "Air_Monitoring_Sites", + "screenshots": [], + "orgId": "RBtoEUQ2lmN0K3GY", + "appCategories": [], + "modified": 1458825159000, + "avgRating": 0, + "id": "4dc97eb2f7f544e9a8340ed840f02873", + "categories": [], + "spatialReference": "GCS_WGS_1984", + "numRatings": 0, + "owner": "OKDOT_GIS", + "largeThumbnail": null, + "accessInformation": "Oklahoma Department of Environmental Quality", + "thumbnail": "thumbnail/thumbnail.png", + "languages": [], + "created": 1444763851000, + "documentation": null, + "banner": null, + "url": "https://services6.arcgis.com/RBtoEUQ2lmN0K3GY/arcgis/rest/services/Air_Monitoring_Sites/FeatureServer", + "tags": [ + "odot", + "environmental", + "okdot" + ], + "numViews": 192, + "numComments": 0, + "size": 49152, + "listed": false, + "scoreCompleteness": 88, + "culture": "en-us", + "industries": [], + "name": "Air_Monitoring_Sites", + "guid": null, + "proxyFilter": null, + "properties": null, + "source": "Oklahoma Department of Transportation", + "license": "custom" }, "time": null, "links": [ @@ -377,7 +854,7 @@ "rel": "self", "type": "application/geo+json", "title": "This document as GeoJSON", - "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/cb61d161171d43d89ce5a31838a7a33e" + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/4dc97eb2f7f544e9a8340ed840f02873" }, { "rel": "collection", @@ -388,9 +865,9 @@ ] } ], - "timestamp": "2026-10-06T15:30:41.305Z", - "numberMatched": 10000, - "numberReturned": 5, + "timestamp": "2026-10-20T12:10:29.159Z", + "numberMatched": 1018, + "numberReturned": 7, "links": [ { "rel": "self", @@ -402,7 +879,7 @@ "rel": "next", "type": "application/geo+json", "title": "items (next)", - "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items?q=water&limit=5&startindex=6" + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items?q=air quality monitoring&limit=10&startindex=11" }, { "rel": "collection", diff --git a/tests/fixtures/sources/arcgis.null.json b/tests/fixtures/sources/arcgis.null.json new file mode 100644 index 0000000..59dafea --- /dev/null +++ b/tests/fixtures/sources/arcgis.null.json @@ -0,0 +1,215 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "id": "e35400cc0e5743eeb7cfe079c506d2af", + "type": "Feature", + "geometry": null, + "properties": { + "snippet": null, + "extent": null, + "commentsEnabled": true, + "groupDesignations": null, + "access": "public", + "apiToken2ExpirationDate": -1, + "typeKeywords": [ + "CSV" + ], + "description": "null", + "licenseInfo": null, + "title": "air quality", + "type": "CSV", + "screenshots": [], + "subInfo": 0, + "advancedSettings": null, + "appCategories": [], + "modified": 1732404320000, + "avgRating": 0, + "id": "e35400cc0e5743eeb7cfe079c506d2af", + "categories": [], + "robots": [ + "noindex", + "nofollow" + ], + "spatialReference": null, + "numRatings": 0, + "owner": "Nikita_sthaa", + "accessInformation": null, + "largeThumbnail": null, + "lastViewed": 1732402800000, + "thumbnail": "thumbnail/ago_downloaded.png", + "languages": [], + "created": 1732372581000, + "documentation": null, + "banner": null, + "url": null, + "tags": [], + "numViews": 28, + "numComments": 0, + "size": 706, + "listed": false, + "scoreCompleteness": 33, + "culture": "en-gb", + "industries": [], + "apiToken1ExpirationDate": -1, + "name": "air_quality.csv", + "guid": null, + "proxyFilter": null, + "properties": null, + "source": "Nikita_sthaa", + "license": "none" + }, + "time": null, + "links": [ + { + "rel": "self", + "type": "application/geo+json", + "title": "This document as GeoJSON", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/e35400cc0e5743eeb7cfe079c506d2af" + }, + { + "rel": "collection", + "type": "application/json", + "title": "Dataset", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset" + } + ] + }, + { + "id": "3afd8a0b7f524a78ae0ef969d28c1fb3", + "type": "Feature", + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.815, + 55.0539 + ], + [ + -1.2109, + 55.0539 + ], + [ + -1.2109, + 54.5802 + ], + [ + -1.815, + 54.5802 + ] + ] + ] + }, + "properties": { + "snippet": null, + "extent": { + "type": "Polygon", + "coordinates": [ + [ + [ + -1.815, + 55.0539 + ], + [ + -1.2109, + 55.0539 + ], + [ + -1.2109, + 54.5802 + ], + [ + -1.815, + 54.5802 + ] + ] + ] + }, + "commentsEnabled": true, + "groupDesignations": null, + "access": "public", + "typeKeywords": [ + "Data", + "Feature Collection", + "Singlelayer" + ], + "description": null, + "licenseInfo": null, + "title": "Air Quality", + "type": "Feature Collection", + "screenshots": [], + "subInfo": 0, + "advancedSettings": null, + "appCategories": [], + "modified": 1660470890000, + "avgRating": 0, + "id": "3afd8a0b7f524a78ae0ef969d28c1fb3", + "categories": [], + "spatialReference": null, + "numRatings": 0, + "owner": "l.s.z.al-hinai2_ncluni", + "accessInformation": null, + "largeThumbnail": null, + "thumbnail": "thumbnail/ago_downloaded.png", + "languages": [], + "created": 1660470889000, + "documentation": null, + "banner": null, + "url": null, + "tags": [], + "numViews": 0, + "numComments": 0, + "size": 100656, + "listed": false, + "scoreCompleteness": 33, + "culture": "en-gb", + "industries": [], + "name": null, + "guid": null, + "proxyFilter": null, + "properties": null, + "source": "l.s.z.al-hinai2_ncluni", + "license": "none" + }, + "time": null, + "links": [ + { + "rel": "self", + "type": "application/geo+json", + "title": "This document as GeoJSON", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items/3afd8a0b7f524a78ae0ef969d28c1fb3" + }, + { + "rel": "collection", + "type": "application/json", + "title": "Dataset", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset" + } + ] + } + ], + "timestamp": "2026-10-20T12:03:27.827Z", + "numberMatched": 8806, + "numberReturned": 2, + "links": [ + { + "rel": "self", + "type": "application/geo+json", + "title": "This document as GeoJSON", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items" + }, + { + "rel": "next", + "type": "application/geo+json", + "title": "items (next)", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset/items?q=air quality&limit=10&startindex=11" + }, + { + "rel": "collection", + "type": "application/json", + "title": "Dataset", + "href": "https://hub.arcgis.com/api/search/v1/collections/dataset" + } + ] +} From 6fe07e420373b0b8008d6f724de2cc85101e2899 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:37:12 +0100 Subject: [PATCH 11/31] feat: HDX and the other CKAN portals report dataset sizes, B2FIND its licenses and publishers A record's size is the sum of its resources' sizes when every resource states one; B2FIND's sizes come from its Size extra. A colon in the query no longer turns CKAN's search into a fielded query that matches nothing. --- src/sources/ckan.rs | 328 ++++++++- tests/fixtures/sources/ckan.b2find.json | 655 ++++++++++++++++++ .../sources/ckan.hdx-air-quality.json | 555 +++++++++++++++ 3 files changed, 1518 insertions(+), 20 deletions(-) create mode 100644 tests/fixtures/sources/ckan.b2find.json create mode 100644 tests/fixtures/sources/ckan.hdx-air-quality.json diff --git a/src/sources/ckan.rs b/src/sources/ckan.rs index e3b87fc..34f4471 100644 --- a/src/sources/ckan.rs +++ b/src/sources/ckan.rs @@ -5,18 +5,24 @@ //! //! `rows` takes up to 1000 unless a site lowers `ckan.search.rows_max`, and //! all six portals answered `rows=100` in full, so one page serves the -//! largest per-source count (CKAN API guide, probes, October 2026). Canada -//! also indexes publications and web pages as `info` records (315 of 2,858 -//! matches for "climate"); `dataset_type:dataset` drops them and changes no -//! count on the other five (probes, October 2026). Descriptions are Markdown -//! with HTML mixed in: CKAN renders `notes` with `render_markdown`, and 95 of -//! 100 HDX notes carry links (CKAN templates, probes, October 2026). A -//! record's `metadata_modified` is often the day a portal harvested it, so -//! the dataset's own date wins where a portal sends one: `last_modified` on -//! HDX, `modified` on GovData, `dcat_modified` on data.gov.uk and +//! largest per-source count; HDX clamps `rows=1001` to 1000 without an error +//! (CKAN API guide, HDX `package_search` docs, probes, October 2026). A colon +//! anywhere in `q` switches CKAN from its dismax parser to a fielded Lucene +//! query, so "covid: deaths" matched nothing on four portals, escaped or not, +//! and "air:" is a 409 Search Error; the query goes out with colons as spaces +//! (CKAN `lib/search/query.py`, probes, October 2026). Canada also indexes +//! publications and web pages as `info` records (315 of 2,858 matches for +//! "climate"); `dataset_type:dataset` drops them and changes no count on the +//! other five (probes, October 2026). Descriptions are Markdown with HTML +//! mixed in: CKAN renders `notes` with `render_markdown`, and 95 of 100 HDX +//! notes carry links (CKAN templates, probes, October 2026). A record's +//! `metadata_modified` is often the day a portal harvested it, so the +//! dataset's own date wins where a portal sends one: `last_modified` on HDX, +//! `modified` on GovData, `dcat_modified` on data.gov.uk and //! `remote_last_updated` on data.gov.au (probes, October 2026). HDX allows -//! 60 requests a minute (HDX API docs, October 2026); data.gov.uk states no -//! limit (data.gov.uk API guide, October 2026). +//! 60 requests a minute anonymously and answers more with 429 (HDX metadata +//! endpoint troubleshooting page, October 2026); data.gov.uk states "there +//! are no rate limits" (data.gov.uk API guide, October 2026). //! //! On GovData `organization` names the portal that harvested a record //! (GDI-DE, Mobilithek), while the `publisher_name` extra names who published @@ -24,15 +30,45 @@ //! pasted statement, as in 6 of 100 data.gov.au titles; CKAN's own //! `notspecified` id, 32 of those 100, is no license at all (probes, CKAN //! `license.py`, October 2026). +//! +//! A resource's `size` is bytes: HDX's 494,307,199 for a WorldPop GeoTIFF is +//! that file's Content-Length. HDX states a size for every resource of 326 of +//! 329 records across four queries, links to other hosts included; the other +//! portals do so for 3 to 12 of 100 (probes, October 2026). A record's size +//! is the sum only when every resource states one, since a partial sum would +//! understate it. HDX has no DOI field; the DOIs in its notes and +//! `methodology_other` cite papers and upstream products, and WorldPop's +//! per-country records all cite the same global ones (probes, October 2026). +//! +//! B2FIND sends no resources and no `license_title`. Its extras carry the +//! harvested DataCite record: `Publisher` names the publisher where the +//! organization is the harvesting community ("da|ra", "CESSDA"), `Rights` +//! mixes licenses with access rights, and `Size` lists byte counts from +//! Dataverse installations ("6828; 6803"), rounded sizes from B2SHARE +//! ("215.9 kB; 1 file") or counts that are not bytes ("28254 data points") +//! (probes, October 2026). use serde_json::Value; use super::Ctx; use crate::http::SourceError; -use crate::record::{Dataset, day, from_markdown, items, number, text}; +use crate::record::{Dataset, clean, day, from_markdown, items, number, text}; const LONGEST_LICENSE: usize = 100; +/// Words by which a part of B2FIND's `Rights` names a license rather than +/// an access right or the archive that holds the data. +const LICENSE_WORDS: [&str; 8] = [ + "licen", + "creative commons", + "cc0", + "cc-by", + "cc by", + "odbl", + "etalab", + "public domain", +]; + pub struct Portal { pub api: &'static str, pub page: &'static str, @@ -80,7 +116,7 @@ pub fn search( let body = ctx .http .get(&format!("{}/package_search", portal.api)) - .query("q", query) + .query("q", query.replace(':', " ")) .query("fq", "dataset_type:dataset") .query("rows", limit) .json()?; @@ -122,6 +158,7 @@ fn record(portal: &Portal, row: &Value) -> Option { .describe(text(row, "/notes").map(|notes| from_markdown(¬es))) .doi_from(doi); dataset.publisher = extra("publisher_name") + .or_else(|| extra("Publisher")) .or_else(|| { text(row, "/organization/title").map(|title| { match title.split_once(" | ") { @@ -132,12 +169,12 @@ fn record(portal: &Portal, row: &Value) -> Option { } }) }) - .or_else(|| extra("Publisher")) .or_else(|| text(row, "/author")); dataset.license = text(row, "/license_title") .or_else(|| { items(row, "/resources").iter().find_map(|r| text(r, "/license")) }) + .or_else(|| extra("Rights").and_then(|rights| named_license(&rights))) .filter(|license| license.chars().count() <= LONGEST_LICENSE) .filter(|_| { text(row, "/license_id").as_deref() != Some("notspecified") @@ -151,6 +188,8 @@ fn record(portal: &Portal, row: &Value) -> Option { ] .into_iter() .find_map(day); + dataset.size_bytes = resource_bytes(row) + .or_else(|| extra("Size").and_then(|sizes| listed_bytes(&sizes))); dataset.popularity = number(row, "/total_res_downloads"); if let Some(source_page) = text(row, "/url") && source_page.starts_with("http") @@ -160,6 +199,55 @@ fn record(portal: &Portal, row: &Value) -> Option { dataset.valid() } +fn resource_bytes(row: &Value) -> Option { + let resources = items(row, "/resources"); + if resources.is_empty() { + return None; + } + resources.iter().try_fold(0, |total: u64, resource| { + total.checked_add(number(resource, "/size").filter(|&size| size > 0)?) + }) +} + +fn named_license(rights: &str) -> Option { + rights + .split(';') + .find(|part| { + let lower = part.to_lowercase(); + LICENSE_WORDS.iter().any(|word| lower.contains(word)) + }) + .map(clean) +} + +/// The parts of B2FIND's `Size` that are byte sizes, summed; `None` when no +/// part is. +fn listed_bytes(sizes: &str) -> Option { + let bytes: Vec = sizes.split(';').filter_map(bytes_in).collect(); + if bytes.is_empty() { + return None; + } + bytes.into_iter().try_fold(0, u64::checked_add) +} + +/// "6828", "23063374 Bytes", "215.9 kB" or "40.9 MBytes" as bytes, the units +/// read as powers of 1000. +fn bytes_in(size: &str) -> Option { + let size = size.trim(); + let (amount, unit) = size.split_once(' ').unwrap_or((size, "bytes")); + let scale: u64 = match unit.to_ascii_lowercase().as_str() { + "b" | "bytes" => 1, + "kb" | "kbytes" => 1_000, + "mb" | "mbytes" => 1_000_000, + "gb" | "gbytes" => 1_000_000_000, + "tb" | "tbytes" => 1_000_000_000_000, + _ => return None, + }; + let (whole, fraction) = amount.split_once('.').unwrap_or((amount, "")); + let digits: u64 = format!("{whole}{fraction}").parse().ok()?; + let places = u32::try_from(fraction.len()).ok()?; + digits.checked_mul(scale)?.checked_div(10_u64.checked_pow(places)?) +} + #[cfg(test)] mod tests { use super::*; @@ -190,14 +278,15 @@ mod tests { doi: None, license: None, updated: Some("2018-10-17".into()), - size_bytes: None, + size_bytes: Some(18_759 + 22_892 + 24_498 + 24_412), popularity: None, aliases: vec![ "https://datamillnorth.org/dataset/\ climate-resilience-documents-vdwno" .into() ], - } + }, + "the fixture keeps 4 of the record's 6 resources" ); assert_eq!( hits[3].license.as_deref(), @@ -211,6 +300,8 @@ mod tests { neighbourhood scale." ) ); + assert_eq!(hits[1].size_bytes, None, "its one resource has no size"); + assert_eq!(hits[3].size_bytes, None); } #[test] @@ -237,10 +328,11 @@ mod tests { doi: None, license: Some("Public Domain / No restrictions (CC0)".into()), updated: Some("2025-03-04".into()), - size_bytes: None, + size_bytes: Some(787_522), popularity: Some(29178), aliases: vec![], - } + }, + "the fixture keeps 1 of the record's 6 resources" ); assert_eq!( hits[1].description.as_deref(), @@ -252,6 +344,55 @@ mod tests { ); assert_eq!(hits[1].updated.as_deref(), Some("2026-07-16")); assert_eq!(hits[1].popularity, Some(720)); + assert_eq!(hits[1].size_bytes, Some(149_602)); + } + + #[test] + fn hdx_sums_the_sizes_of_every_resource() { + let hits = + parse(&HDX, &fixture::json("ckan.hdx-air-quality.json"), 10) + .unwrap(); + assert_eq!(hits.len(), 3); + assert_eq!( + hits[0], + Dataset { + title: "Ecuador: Monthly Air Quality in Quito".into(), + url: "https://data.humdata.org/dataset/\ + air-quality-quito-monthly-2018-2020" + .into(), + description: Some( + "Monthly air quality data based on the parameters of CO, \ + wind direction, humidity, NO2, O3, particulate matter, \ + SO2." + .into() + ), + publisher: Some("Hub Latin America".into()), + doi: None, + license: Some( + "Creative Commons Attribution Share-Alike (CC BY-SA)" + .into() + ), + updated: Some("2021-08-16".into()), + size_bytes: Some(27_652), + popularity: Some(78), + aliases: vec![], + } + ); + assert_eq!( + hits[2].size_bytes, + Some( + 5_432_680 + + 5_936_743 + + 35_407_393 + + 36_746_010 + + 1_201_928 + + 1_259_896 + + 1_230_837 + ), + "all seven CSV files" + ); + assert_eq!(hits[2].updated.as_deref(), Some("2026-10-05")); + assert_eq!(hits[2].popularity, Some(644)); } #[test] @@ -279,7 +420,7 @@ mod tests { doi: None, license: Some("Open Government Licence - Canada".into()), updated: Some("2022-03-14".into()), - size_bytes: None, + size_bytes: Some(1_134_541), popularity: None, aliases: vec![], }, @@ -289,10 +430,12 @@ mod tests { hits[1].doi.as_deref(), Some("10.23687/c1891184-b6dc-4dc7-95b3-ecf108b02a8d") ); + assert_eq!(hits[1].size_bytes, Some(273_122)); assert_eq!( hits[2].doi.as_deref(), Some("10.23687/72e3304f-4103-4060-9bf0-fdd1325b6851") ); + assert_eq!(hits[2].size_bytes, None); } #[test] @@ -368,7 +511,7 @@ mod tests { doi: None, license: None, updated: Some("2025-11-30".into()), - size_bytes: None, + size_bytes: Some(178_264), popularity: None, aliases: vec![], }, @@ -391,6 +534,151 @@ mod tests { ); assert_eq!(hits[2].license, None, "a 275-character credit line"); assert_eq!(hits[2].updated.as_deref(), Some("2022-04-13")); + assert_eq!(hits[2].size_bytes, Some(253_214)); assert_eq!(hits[3].updated.as_deref(), Some("2025-07-29")); } + + #[test] + fn b2find_reads_the_harvested_datacite_extras() { + let hits = + parse(&B2FIND, &fixture::json("ckan.b2find.json"), 10).unwrap(); + assert_eq!(hits.len(), 4); + assert_eq!( + hits[0], + Dataset { + title: "Historical Air Quality Data Austria Umweltbundesamt" + .into(), + url: "https://b2find.eudat.eu/dataset/\ + 9721faf6-3c40-55ea-beeb-9dda97b4b6dc" + .into(), + description: Some( + "This digital record contains historical air pollution \ + and air quality data from approximately 20 air \ + monitoring stations in Vienna, spanning the years from \ + 1980 to 2021. The data was provided by the \ + Umweltbundesamt and is stored in its original form in \ + this record." + .into() + ), + publisher: Some("TU Wien".into()), + doi: Some("10.48436/mtha8-w2406".into()), + license: Some( + "Creative Commons Attribution 4.0 International".into() + ), + updated: Some("2025-06-20".into()), + size_bytes: None, + popularity: None, + aliases: vec![], + }, + "no `Size` extra and no resources" + ); + assert_eq!( + hits[1].publisher.as_deref(), + Some("DANS Data Station Phys-Tech Sciences") + ); + assert_eq!(hits[1].license.as_deref(), Some("CC0 1.0")); + assert_eq!( + hits[1].description.as_deref(), + Some( + "Despite increased awareness of climate change and urban \ + air pollution, little research has been performed to \ + examine the influence of meteorology and air quality on \ + athletic performance of the general public and \ + recreational exercisers." + ) + ); + assert_eq!( + hits[1].size_bytes, + Some( + 6828 + 6803 + + 6813 + + 6799 + + 6824 + + 6817 + + 6833 + + 6823 + + 6821 + + 6829 + + 6830 + + 6827 + + 6810 + + 5062 + + 36_694 + + 1_148_641 + + 4391 + + 3774 + + 29_598 + + 31_009 + + 40_959_504 + + 140_276_743 + + 8782 + + 186_574 + + 170_780 + + 2155 + ), + "Dataverse's file sizes, one per file" + ); + assert_eq!(hits[2].size_bytes, None, "28254 data points"); + assert_eq!( + hits[2].license.as_deref(), + Some("Creative Commons Attribution 3.0 Unported") + ); + assert_eq!(hits[2].doi.as_deref(), Some("10.1594/pangaea.872005")); + assert_eq!(hits[3].size_bytes, Some(215_900), "215.9 kB; 1 file"); + assert_eq!( + hits[3].license.as_deref(), + Some("Creative Commons Attribution (CC-BY)") + ); + assert_eq!(hits[3].publisher.as_deref(), Some("EUDAT B2SHARE")); + assert_eq!(hits[3].doi, None, "the DOI in its notes cites a paper"); + assert_eq!( + hits[3].aliases, + vec![ + "https://b2share.fz-juelich.de/records/\ + be5cde68c6ba4ab08b6687b17adbb3b6" + ] + ); + } + + #[test] + fn rights_yield_the_part_that_names_a_license() { + assert_eq!( + named_license( + "etalab 2.0; info:eu-repo/semantics/openAccess; \ + https://spdx.org/licenses/etalab-2.0.html" + ) + .as_deref(), + Some("etalab 2.0") + ); + assert_eq!(named_license("info:eu-repo/semantics/openAccess"), None); + assert_eq!( + named_license( + "Access to data through SND. Data are freely accessible." + ), + None + ); + } + + #[test] + fn sizes_in_units_become_bytes() { + assert_eq!(bytes_in("23063374 Bytes"), Some(23_063_374)); + assert_eq!(bytes_in(" 40.9 MBytes"), Some(40_900_000)); + assert_eq!(bytes_in("22.2 GB"), Some(22_200_000_000)); + assert_eq!(bytes_in("6 files"), None); + assert_eq!(bytes_in("unknown"), None); + assert_eq!(listed_bytes("437.6 MB; 144 files"), Some(437_600_000)); + assert_eq!(listed_bytes("15 datasets"), None); + } + + #[test] + fn a_resource_without_a_size_leaves_the_record_unsized() { + let row = serde_json::json!({ + "resources": [{"size": 2_436_991_241_u64}, {"size": 0}] + }); + assert_eq!(resource_bytes(&row), None); + assert_eq!( + resource_bytes(&serde_json::json!({"resources": []})), + None + ); + } } diff --git a/tests/fixtures/sources/ckan.b2find.json b/tests/fixtures/sources/ckan.b2find.json new file mode 100644 index 0000000..84ee054 --- /dev/null +++ b/tests/fixtures/sources/ckan.b2find.json @@ -0,0 +1,655 @@ +{ + "help": "http://131.175.206.246/api/3/action/help_show?name=package_search", + "success": true, + "result": { + "count": 26391, + "facets": {}, + "results": [ + { + "author": "Taha, Josef", + "author_email": null, + "creator_user_id": "1dc1b4c8-ff82-46f0-a122-5d4f29ff0883", + "id": "8fee46dc-9a42-4a00-92f9-cf6533536251", + "isopen": false, + "license_id": null, + "license_title": null, + "maintainer": null, + "maintainer_email": null, + "metadata_created": "2025-06-20T04:30:08.800725", + "metadata_modified": "2025-06-20T04:30:08.800730", + "name": "9721faf6-3c40-55ea-beeb-9dda97b4b6dc", + "notes": "This digital record contains historical air pollution and air quality data from approximately 20 air monitoring stations in Vienna, spanning the years from 1980 to 2021. The data was provided by the Umweltbundesamt and is stored in its original form in this record.", + "num_resources": 0, + "num_tags": 0, + "organization": { + "id": "4b13efcb-7a1b-46e3-ad53-6c1c6522cba9", + "name": "tuw", + "title": "TU Wien", + "type": "organization", + "description": "[TU Wien](https://researchdata.tuwien.ac.at/ \"TU Wien\") Research Data is an institutional repository of TU Wien to enable storing, sharing and publishing of digital objects, in particular research data.", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/TU_Wien-Logo.svg/2000px-TU_Wien-Logo.svg.png", + "created": "2025-06-19T08:49:26.697634", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "4b13efcb-7a1b-46e3-ad53-6c1c6522cba9", + "private": false, + "state": "active", + "title": "Historical Air Quality Data Austria Umweltbundesamt", + "type": "dataset", + "url": null, + "version": "56b7da3dd2a2aad003bd31558799664a4256ba8d7d3599a0f88e42070bc00f31", + "extras": [ + { + "key": "Contact", + "value": "tudata(at)tuwien.ac.at" + }, + { + "key": "DOI", + "value": "https://doi.org/10.48436/mtha8-w2406" + }, + { + "key": "Discipline", + "value": "Other" + }, + { + "key": "Language", + "value": "German" + }, + { + "key": "MetaDataAccess", + "value": "https://researchdata.tuwien.ac.at/oai2d?verb=GetRecord&metadataPrefix=oai_datacite&identifier=oai:researchdata.tuwien.ac.at:mtha8-w2406" + }, + { + "key": "OpenAccess", + "value": "true" + }, + { + "key": "PublicationYear", + "value": "2023" + }, + { + "key": "Publisher", + "value": "TU Wien" + }, + { + "key": "RelatedIdentifier", + "value": "https://doi.org/10.48436/gc1n8-14v35|DOI|IsVersionOf" + }, + { + "key": "ResourceType", + "value": "Dataset" + }, + { + "key": "Rights", + "value": "Creative Commons Attribution 4.0 International; https://creativecommons.org/licenses/by/4.0/legalcode" + }, + { + "key": "TempCoverage", + "value": "[2023-05-15 TO *]" + }, + { + "key": "TemporalCoverage:BeginDate", + "value": "2023-05-15T00:00:00Z" + }, + { + "key": "Version", + "value": "1.0.0" + }, + { + "key": "fulltext", + "value": "oairesearchdatatuwienacatmtha8w240620240625T131259Zopenairedata43TUWTUDATA1048436mtha8w2406oairesearchdatatuwienacatmtha8w2406Taha JosefJosefTahaTU WienHistorical Air Quality Data Austria UmweltbundesamtTU Wien20232023051520240625deu1048436gc1n814v35100Creative Commons Attribution 40 InternationalTh" + }, + { + "key": "repositoryID", + "value": "re3data:r3d100013557" + }, + { + "key": "repositoryName", + "value": "TU Wien Research Data" + } + ], + "resources": [], + "tags": [], + "groups": [], + "relationships_as_subject": [], + "relationships_as_object": [] + }, + { + "author": "J R Hodgson; S Elliott; C Hudson", + "author_email": null, + "creator_user_id": "1dc1b4c8-ff82-46f0-a122-5d4f29ff0883", + "id": "79d8c8f9-34cc-42a4-876a-45dba19ea83b", + "isopen": false, + "license_id": null, + "license_title": null, + "maintainer": null, + "maintainer_email": null, + "metadata_created": "2025-06-20T01:45:00.891306", + "metadata_modified": "2025-06-20T01:45:00.891310", + "name": "518aba59-a818-586e-891a-dac267266c2e", + "notes": "

Despite increased awareness of climate change and urban air pollution, little research has been performed to examine the influence of meteorology and air quality on athletic performance of the general public and recreational exercisers.", + "num_resources": 0, + "num_tags": 1, + "organization": { + "id": "35bf721e-a4b3-4c90-b503-a0aa51f46b9e", + "name": "ds_physical_technical", + "title": "DANS Data Station Physical and Technical Sciences", + "type": "organization", + "description": "The [DANS Data Station Physical and Technical Sciences](https://dans.knaw.nl/en/physical-and-technical-sciences/ \"DANS Data Station Physical and Technical Sciences\") is a domain-specific repository for data from the physical and technical sciences, primarily aimed at the Netherlands, but not exclusi", + "image_url": "https://b2find.eudat.eu/images/communities/danseasy_logo.png", + "created": "2025-06-19T08:49:22.344980", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "35bf721e-a4b3-4c90-b503-a0aa51f46b9e", + "private": false, + "state": "active", + "title": "The influence of meteorology and air quality on parkrun athletic performance Meteorology, air quality and parkrun", + "type": "dataset", + "url": null, + "version": "8286050f89a944b4a236d3f7d1a20f4d04848efd3269c2c5785e11970ea193f1", + "extras": [ + { + "key": "Contact", + "value": "J. R. Hodgson (University of Birmingham)" + }, + { + "key": "Contributor", + "value": "J. R. Hodgson; L Chapman (University of Birmingham); F. D. Pope (University of Birmingham)" + }, + { + "key": "DOI", + "value": "https://doi.org/10.17026/dans-27m-9mkm" + }, + { + "key": "Discipline", + "value": "Earth and Environmental Science; Environmental Research; Geosciences; Natural Sciences" + }, + { + "key": "Format", + "value": "text/plain; charset=US-ASCII; type/x-r-syntax; text/csv; application/zip" + }, + { + "key": "MetaDataAccess", + "value": "https://phys-techsciences.datastations.nl/oai?verb=GetRecord&metadataPrefix=oai_datacite&identifier=doi:10.17026/dans-27m-9mkm" + }, + { + "key": "OpenAccess", + "value": "true" + }, + { + "key": "PublicationYear", + "value": "2019" + }, + { + "key": "Publisher", + "value": "DANS Data Station Phys-Tech Sciences" + }, + { + "key": "ResourceType", + "value": "Dataset" + }, + { + "key": "Rights", + "value": "CC0 1.0; info:eu-repo/semantics/openAccess; http://creativecommons.org/publicdomain/zero/1.0" + }, + { + "key": "Size", + "value": "6828; 6803; 6813; 6799; 6824; 6817; 6833; 6823; 6821; 6829; 6830; 6827; 6810; 5062; 36694; 1148641; 4391; 3774; 29598; 31009; 40959504; 140276743; 8782; 186574; 170780; 2155" + }, + { + "key": "TempCoverage", + "value": "[2019-12-17 TO *]" + }, + { + "key": "TemporalCoverage:BeginDate", + "value": "2019-12-17T00:00:00Z" + }, + { + "key": "Version", + "value": "2.0" + }, + { + "key": "fulltext", + "value": "doi1017026dans27m9mkm20231113T152142Z1017026dans27m9mkmJ R HodgsonUniversity of BirminghamS ElliottUniversity of BirminghamC HudsonAdvanced Wellbeing Research Centre 2 Old Hall Road Sheffield S9 3TU United KingdomThe influence of meteorology and air quality on parkrun athletic performance Meteorolog" + } + ], + "groups": [ + { + "description": "[DANS](https://dans.knaw.nl/en/ \"DANS\") is the Dutch national centre of expertise and repository for research data. We help researchers make their data available for reuse. This allows researchers to use the data for new research and makes published research verifiable and reproducible.", + "display_name": "DANS", + "id": "ae21a39b-13a9-45f6-b816-98b6d7a327aa", + "image_display_url": "https://b2find.eudat.eu/images/communities/danseasy_logo.png", + "name": "dans", + "title": "DANS" + } + ], + "tags": [ + { + "display_name": "Earth and Environmental Sciences", + "id": "3c2e5608-0bd3-4dcd-bea0-622373133c8e", + "name": "Earth and Environmental Sciences", + "state": "active", + "vocabulary_id": null + } + ], + "resources": [], + "relationships_as_subject": [], + "relationships_as_object": [] + }, + { + "author": "Scorgie, Yvonne; Kirkwood, John", + "author_email": null, + "creator_user_id": "1dc1b4c8-ff82-46f0-a122-5d4f29ff0883", + "id": "6e633830-0978-45af-85f8-5f6bb8b8adc4", + "isopen": false, + "license_id": null, + "license_title": null, + "maintainer": null, + "maintainer_email": null, + "metadata_created": "2025-06-19T18:19:16.263348", + "metadata_modified": "2025-06-19T18:19:16.263355", + "name": "78c74cd7-3bfc-5ead-8581-71b7025bc4c4", + "notes": null, + "num_resources": 0, + "num_tags": 21, + "organization": { + "id": "12ea7746-bf2c-422f-95d9-2ba938738189", + "name": "pangaea", + "title": "PANGAEA", + "type": "organization", + "description": "The information system [PANGAEA](https://www.pangaea.de/ \"PANGAEA\") is operated as an Open Access library aimed at archiving, publishing and distributing georeferenced data from earth system research.", + "image_url": "https://b2find.eudat.eu/images/communities/pangaea_logo.png", + "created": "2025-06-19T08:49:25.622567", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "12ea7746-bf2c-422f-95d9-2ba938738189", + "private": false, + "state": "active", + "title": "Three months of air quality measurements from Wollongong OEH air quality monitoring site, 2012-12-01 to 2013-02-28", + "type": "dataset", + "url": null, + "version": "bf28649bce1eb74ad9d0d7dd8c012e209c15743ecc03e4e63d835b0bbcec48db", + "extras": [ + { + "key": "DOI", + "value": "https://doi.org/10.1594/PANGAEA.872005" + }, + { + "key": "Discipline", + "value": "Earth System Research" + }, + { + "key": "Format", + "value": "text/tab-separated-values" + }, + { + "key": "MetaDataAccess", + "value": "https://ws.pangaea.de/oai/provider?verb=GetRecord&metadataPrefix=datacite4&identifier=oai:pangaea.de:doi:10.1594/PANGAEA.872005" + }, + { + "key": "OpenAccess", + "value": "true" + }, + { + "key": "PID", + "value": "https://hdl.handle.net/10013/epic.50378.d035" + }, + { + "key": "PublicationYear", + "value": "2017" + }, + { + "key": "Publisher", + "value": "PANGAEA" + }, + { + "key": "RelatedIdentifier", + "value": "https://doi.org/10.1594/PANGAEA.871982|DOI|IsPartOf; https://doi.org/10.5194/essd-9-349-2017|DOI|References" + }, + { + "key": "ResourceType", + "value": "Dataset" + }, + { + "key": "Rights", + "value": "Creative Commons Attribution 3.0 Unported; https://creativecommons.org/licenses/by/3.0/" + }, + { + "key": "Size", + "value": "28254 data points" + }, + { + "key": "SpatialCoverage", + "value": "(150.887 LON, -34.417 LAT); Australia" + }, + { + "key": "TempCoverage", + "value": "[2012-12-01 TO 2013-02-28]" + }, + { + "key": "TemporalCoverage:BeginDate", + "value": "2012-12-01T00:00:00Z" + }, + { + "key": "TemporalCoverage:EndDate", + "value": "2013-02-28T23:00:00Z" + }, + { + "key": "bbox", + "value": "ENVELOPE(150.8873, 150.8873, -34.4171, -34.4171)" + }, + { + "key": "fulltext", + "value": "oaipangaeadedoi101594PANGAEA87200520250312T084245ZcitabletopicAtmospheretopicChemistrytopicLithosphere101594PANGAEA872005Scorgie YvonneYvonneScorgieKirkwood JohnJohnKirkwoodThree months of air quality measurements from Wollongong OEH air quality monitoring site 20121201 to 20130228PANGAEA2017DATETIM" + }, + { + "key": "geom", + "value": "POINT (150.8873000000000104 -34.4170999999999978)" + }, + { + "key": "repositoryID", + "value": "re3data:r3d100010134" + }, + { + "key": "repositoryName", + "value": "PANGAEA" + }, + { + "key": "spatial", + "value": "POINT (150.8873000000000104 -34.4170999999999978)" + } + ], + "tags": [ + { + "display_name": "10 µm", + "id": "13401fe1-2005-42ae-8c0c-dd7d60e80be9", + "name": "10 µm", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "2 5 µm", + "id": "79db8681-4169-408e-8c44-b242111c3ce9", + "name": "2 5 µm", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Aerosol scattering at 525 nm", + "id": "7af1a173-d6a0-4a9d-ad39-a13b84cf803d", + "name": "Aerosol scattering at 525 nm", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Carbon monoxide", + "id": "b2de4416-b258-4794-91d6-21bb90f0d882", + "name": "Carbon monoxide", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "DATE TIME", + "id": "ee672df1-c7b7-4273-b9a0-683c9c889885", + "name": "DATE TIME", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "HEIGHT above ground", + "id": "72a36d65-8ee3-41ca-a4f9-453bac588281", + "name": "HEIGHT above ground", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Humidity", + "id": "6c6c0e2c-9b81-4ca8-ad2b-e07b1b083e0d", + "name": "Humidity", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Monitoring station", + "id": "5b1397a2-97c4-4f3c-b70c-8df40b16023d", + "name": "Monitoring station", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Nitric oxide", + "id": "199e0c35-9bc9-4f7e-a4fb-7748ae28a85a", + "name": "Nitric oxide", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Nitrogen dioxide", + "id": "f05c1c53-02a8-4ce5-bfbe-208b121547e5", + "name": "Nitrogen dioxide", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Nitrogen oxide", + "id": "2856273f-71e0-45fb-8c39-e07af14b426e", + "name": "Nitrogen oxide", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Ozone", + "id": "b0387e56-005b-40bd-b00e-330bab0bd620", + "name": "Ozone", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Particulate matter", + "id": "b4a518b0-cb5f-401d-a293-551ebf9f6c88", + "name": "Particulate matter", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Sulfur dioxide", + "id": "f9441898-edba-44cb-ae28-e15e3c987dba", + "name": "Sulfur dioxide", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Temperature", + "id": "7169714a-42b1-4bab-ac08-b6d20e0d35b6", + "name": "Temperature", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Wind direction", + "id": "54dca72e-421d-404a-9fde-cc0c0029d4f1", + "name": "Wind direction", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "Wind speed", + "id": "8bd7c342-58b0-4466-9278-d2f56f32583c", + "name": "Wind speed", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "air", + "id": "19dc084d-1846-4452-8a74-37317a5af0a7", + "name": "air", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "relative", + "id": "8b586b1e-02ce-4e45-a5ae-941f34b391cc", + "name": "relative", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "see further details", + "id": "c0fe5785-8065-4d2b-9f10-1b89d357e546", + "name": "see further details", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "standard deviation", + "id": "19d0d844-e35c-4b93-9d4f-a6c2e50469a4", + "name": "standard deviation", + "state": "active", + "vocabulary_id": null + } + ], + "resources": [], + "groups": [], + "relationships_as_subject": [], + "relationships_as_object": [] + }, + { + "author": "Schultz, Martin G.", + "author_email": null, + "creator_user_id": "1dc1b4c8-ff82-46f0-a122-5d4f29ff0883", + "id": "2495bba7-4694-48f6-a845-524a08bba1b6", + "isopen": false, + "license_id": null, + "license_title": null, + "maintainer": null, + "maintainer_email": null, + "metadata_created": "2025-06-19T19:42:47.087622", + "metadata_modified": "2025-06-19T19:42:47.087626", + "name": "b3b0256e-4819-5c15-859a-56909c66085f", + "notes": "This file has been obtained from the Tropospheric Ozone Assessment Report database described by Schultz, M.G. et al., Elementa Sci. Anthrop., 2017, doi:http://doi.org/10.1525/elementa.244.", + "num_resources": 0, + "num_tags": 4, + "organization": { + "id": "cf5aeae0-f83a-42d4-8574-192b965575ef", + "name": "eudat", + "title": "EUDAT", + "type": "organization", + "description": "[EUDAT](https://www.eudat.eu/eudat-cdi \"EUDAT\")’s vision is Data is shared and preserved across borders and disciplines. A", + "image_url": "https://b2find.eudat.eu/images/communities/eudat_logo.png", + "created": "2025-06-19T08:49:23.520151", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "cf5aeae0-f83a-42d4-8574-192b965575ef", + "private": false, + "state": "active", + "title": "Sample data file with TOAR air quality data for machine learning excercise", + "type": "dataset", + "url": "https://b2share.fz-juelich.de/records/be5cde68c6ba4ab08b6687b17adbb3b6", + "version": "8f9ff51e372ca8cb5964c3204b3efd05d1080f315e7dd5c4df562dd15ecc369f", + "extras": [ + { + "key": "Contact", + "value": "m.schultz(at)fz-juelich.de" + }, + { + "key": "Discipline", + "value": "3.2.4 → Chemistry → Atmospheric chemistry" + }, + { + "key": "Format", + "value": "csv" + }, + { + "key": "MetaDataAccess", + "value": "https://b2share.fz-juelich.de/api/oai2d?verb=GetRecord&metadataPrefix=eudatcore&identifier=oai:b2share.fz-juelich.de:b2rec/be5cde68c6ba4ab08b6687b17adbb3b6" + }, + { + "key": "OpenAccess", + "value": "true" + }, + { + "key": "PublicationYear", + "value": "2019" + }, + { + "key": "Publisher", + "value": "EUDAT B2SHARE" + }, + { + "key": "Rights", + "value": "Creative Commons Attribution (CC-BY); info:eu-repo/semantics/openAccess" + }, + { + "key": "Size", + "value": "215.9 kB; 1 file" + }, + { + "key": "fulltext", + "value": "oaib2sharefzjuelichdeb2recbe5cde68c6ba4ab08b6687b17adbb3b620190224T200856Ze9b9792e79fb4b07b6b4b9c2bd06d095Sample data file with TOAR air quality data for machine learning excerciseEUDAThttpsb2sharefzjuelichderecordsbe5cde68c6ba4ab08b6687b17adbb3b6EUDAT B2SHARE2019Schultz Martin GThis file has been o" + }, + { + "key": "repositoryID", + "value": "re3data:r3d100013118" + }, + { + "key": "repositoryName", + "value": "B2SHARE Server Forschungszentrum Jülich" + } + ], + "groups": [ + { + "description": "[B2SHARE](https://b2share.eudat.eu/ \"B2SHARE\") is a user-friendly, reliable and trustworthy way for researchers, scientific communities and citizen scientists to store, publish and share research data in a FAIR way.", + "display_name": "B2SHARE", + "id": "fd4b8c32-94e0-4035-bc5d-6132d7902fce", + "image_display_url": "https://b2find.eudat.eu/images/communities/b2share_logo.png", + "name": "b2share", + "title": "B2SHARE" + } + ], + "tags": [ + { + "display_name": "NO2", + "id": "f63e55da-76b6-4f73-9460-4c8c39df2205", + "name": "NO2", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "TOAR", + "id": "66d31403-4167-4f83-9dc1-248330e42670", + "name": "TOAR", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "air pollution", + "id": "9e99d757-9bc2-4193-8ec0-85a70c96570b", + "name": "air pollution", + "state": "active", + "vocabulary_id": null + }, + { + "display_name": "machine learning", + "id": "e69a1bd8-052a-4faf-ad99-4087c1135fed", + "name": "machine learning", + "state": "active", + "vocabulary_id": null + } + ], + "resources": [], + "relationships_as_subject": [], + "relationships_as_object": [] + } + ], + "sort": "score desc, metadata_modified desc", + "search_facets": {} + } +} diff --git a/tests/fixtures/sources/ckan.hdx-air-quality.json b/tests/fixtures/sources/ckan.hdx-air-quality.json new file mode 100644 index 0000000..e670750 --- /dev/null +++ b/tests/fixtures/sources/ckan.hdx-air-quality.json @@ -0,0 +1,555 @@ +{ + "help": "https://data.humdata.org/api/3/action/help_show?name=package_search", + "success": true, + "result": { + "count": 259, + "facets": {}, + "expanded": {}, + "results": [ + { + "archived": false, + "batch": "6ab0b038-5534-471d-8723-b37ec0a871b9", + "caveats": "Monitoring of stations to obtain air quality parameters collected by the Secretary of the Environment in Quito.", + "creator_user_id": "f475cc13-169d-456d-b1a3-e534abc78b1b", + "data_update_frequency": "365", + "dataset_date": "[2018-01-01T00:00:00 TO 2021-02-28T23:59:59]", + "dataset_preview": "first_resource", + "dataset_source": "Instituto de Geografia – USFQ and U.S Department of State", + "due_date": "2022-02-28T23:59:59", + "has_geodata": true, + "has_showcases": false, + "id": "cf5a3740-a140-48e5-8a40-4ad26ef6ad94", + "is_requestdata_type": false, + "isopen": true, + "last_modified": "2021-08-16T15:57:06.867749", + "license_id": "cc-by-sa", + "license_title": "Creative Commons Attribution Share-Alike (CC BY-SA)", + "license_url": "http://www.opendefinition.org/licenses/cc-by-sa", + "maintainer": "f475cc13-169d-456d-b1a3-e534abc78b1b", + "metadata_created": "2021-08-16T15:57:06.136349", + "metadata_modified": "2025-04-10T15:04:33.872733", + "methodology": "Registry", + "name": "air-quality-quito-monthly-2018-2020", + "notes": "Monthly air quality data based on the parameters of CO, wind direction, humidity, NO2, O3, particulate matter, SO2.", + "num_resources": 1, + "num_tags": 2, + "organization": { + "id": "fa2fade6-e9cd-4597-995e-fec309e64d6a", + "name": "hla", + "title": "Hub Latin America", + "type": "organization", + "description": "The Latin America HUB will focus on the spatial analysis and visualization of redistribution of poverty and other emergent processes related to it. Specifically, will focus on the processes related to migration/mobility and the multiplicative effects of the collapse of tourism in different cities.", + "image_url": "", + "created": "2021-08-09T13:18:41.752973", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "fa2fade6-e9cd-4597-995e-fec309e64d6a", + "package_creator": "mabezr_98", + "pageviews_last_14_days": 6, + "private": false, + "qa_completed": false, + "solr_additions": "{\"countries\": [\"Ecuador\"]}", + "state": "active", + "subnational": "1", + "title": "Ecuador: Monthly Air Quality in Quito", + "total_res_downloads": 78, + "type": "dataset", + "url": null, + "version": null, + "groups": [ + { + "description": "", + "display_name": "Ecuador", + "id": "ecu", + "image_display_url": "", + "name": "ecu", + "title": "Ecuador" + } + ], + "resources": [ + { + "alt_url": "https://data.humdata.org/dataset/cf5a3740-a140-48e5-8a40-4ad26ef6ad94/resource/ea1adf4b-acfe-4040-a319-764dd18f50a6/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2021-08-16T15:57:07.126948", + "dataset_preview_enabled": true, + "datastore_active": false, + "description": "Monthly air quality parameters and data in Quito during the period 2018-2021.", + "download_url": "https://data.humdata.org/dataset/cf5a3740-a140-48e5-8a40-4ad26ef6ad94/resource/ea1adf4b-acfe-4040-a319-764dd18f50a6/download/air_quality_quito_monthly_2018_2021.zip", + "format": "SHP", + "hash": "", + "hdx_rel_url": "/dataset/cf5a3740-a140-48e5-8a40-4ad26ef6ad94/resource/ea1adf4b-acfe-4040-a319-764dd18f50a6/download/air_quality_quito_monthly_2018_2021.zip", + "id": "ea1adf4b-acfe-4040-a319-764dd18f50a6", + "last_modified": "2021-08-16T15:57:06.867749", + "metadata_modified": "2025-04-10T15:04:33.890529", + "microdata": false, + "mimetype": "application/x-zip-compressed", + "mimetype_inner": null, + "name": "Air_Quality_Quito_monthly_2018_2021.zip", + "originalHash": "-988266717", + "p_coded": false, + "package_id": "cf5a3740-a140-48e5-8a40-4ad26ef6ad94", + "pii": "false", + "position": 0, + "resource_type": "file.upload", + "shape_info": "[{\"error_class\": \"None\", \"layer_id\": \"None\", \"error_type\": \"None\", \"state\": \"processing\", \"timestamp\": \"2021-08-16T15:57:06.953439\", \"message\": \"The processing of the geo-preview has started\"}, {\"error_class\": \"None\", \"layer_fields\": [{\"field_name\": \"ogc_fid\", \"data_type\": \"integer\"}, {\"field_name\":", + "size": 27652, + "state": "active", + "url": "https://data.humdata.org/dataset/cf5a3740-a140-48e5-8a40-4ad26ef6ad94/resource/ea1adf4b-acfe-4040-a319-764dd18f50a6/download/air_quality_quito_monthly_2018_2021.zip", + "url_type": "upload" + } + ], + "tags": [ + { + "display_name": "environment", + "id": "71e54185-e2ea-4dd0-b67d-8316abefe82b", + "name": "environment", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + }, + { + "display_name": "indicators", + "id": "08dade96-0bf4-4248-9d9f-421f7b844e53", + "name": "indicators", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + } + ], + "relationships_as_subject": [], + "relationships_as_object": [] + }, + { + "archived": false, + "batch": "6ab0b038-5534-471d-8723-b37ec0a871b9", + "caveats": "Monitoring of stations to obtain air quality parameters collected by the Secretary of the Environment in Quito.", + "creator_user_id": "f475cc13-169d-456d-b1a3-e534abc78b1b", + "data_update_frequency": "365", + "dataset_date": "[2018-01-01T00:00:00 TO 2020-12-31T23:59:59]", + "dataset_preview": "first_resource", + "dataset_source": "Instituto de Geografia – USFQ and U.S Department of State", + "due_date": "2021-12-31T23:59:59", + "has_geodata": true, + "has_showcases": false, + "id": "a5147aa9-978c-450b-84b5-0b86f569206c", + "is_requestdata_type": false, + "isopen": true, + "last_modified": "2021-08-16T15:42:32.616221", + "license_id": "cc-by-sa", + "license_title": "Creative Commons Attribution Share-Alike (CC BY-SA)", + "license_url": "http://www.opendefinition.org/licenses/cc-by-sa", + "maintainer": "f475cc13-169d-456d-b1a3-e534abc78b1b", + "metadata_created": "2021-08-16T15:42:31.693354", + "metadata_modified": "2025-04-10T15:04:33.195652", + "methodology": "Registry", + "name": "air-quality-quito-yearly-2018-2020", + "notes": "Annual air quality data based on the parameters of CO, wind direction, humidity, NO2, O3, particulate matter, SO2", + "num_resources": 1, + "num_tags": 2, + "organization": { + "id": "fa2fade6-e9cd-4597-995e-fec309e64d6a", + "name": "hla", + "title": "Hub Latin America", + "type": "organization", + "description": "The Latin America HUB will focus on the spatial analysis and visualization of redistribution of poverty and other emergent processes related to it. Specifically, will focus on the processes related to migration/mobility and the multiplicative effects of the collapse of tourism in different cities.", + "image_url": "", + "created": "2021-08-09T13:18:41.752973", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "fa2fade6-e9cd-4597-995e-fec309e64d6a", + "package_creator": "mabezr_98", + "pageviews_last_14_days": 3, + "private": false, + "qa_completed": false, + "solr_additions": "{\"countries\": [\"Ecuador\"]}", + "state": "active", + "subnational": "1", + "title": "Ecuador: Yearly Air quality in Quito", + "total_res_downloads": 60, + "type": "dataset", + "url": null, + "version": null, + "groups": [ + { + "description": "", + "display_name": "Ecuador", + "id": "ecu", + "image_display_url": "", + "name": "ecu", + "title": "Ecuador" + } + ], + "resources": [ + { + "alt_url": "https://data.humdata.org/dataset/a5147aa9-978c-450b-84b5-0b86f569206c/resource/06593579-0eb1-4396-929a-53d849633e6e/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2021-08-16T15:42:32.886476", + "dataset_preview_enabled": true, + "datastore_active": false, + "description": "Annual air quality parameters and data in Quito during the period 2018-2020", + "download_url": "https://data.humdata.org/dataset/a5147aa9-978c-450b-84b5-0b86f569206c/resource/06593579-0eb1-4396-929a-53d849633e6e/download/air_quality_quito_yearly_2018_2020.zip", + "format": "SHP", + "hash": "", + "hdx_rel_url": "/dataset/a5147aa9-978c-450b-84b5-0b86f569206c/resource/06593579-0eb1-4396-929a-53d849633e6e/download/air_quality_quito_yearly_2018_2020.zip", + "id": "06593579-0eb1-4396-929a-53d849633e6e", + "last_modified": "2021-08-16T15:42:32.616221", + "metadata_modified": "2025-04-10T15:04:33.219708", + "microdata": false, + "mimetype": "application/x-zip-compressed", + "mimetype_inner": null, + "name": "Air_Quality_Quito_yearly_2018_2020.zip", + "originalHash": 1638209220, + "p_coded": false, + "package_id": "a5147aa9-978c-450b-84b5-0b86f569206c", + "pii": "false", + "position": 0, + "resource_type": "file.upload", + "shape_info": "[{\"error_class\": \"None\", \"layer_id\": \"None\", \"error_type\": \"None\", \"state\": \"processing\", \"timestamp\": \"2021-08-16T15:42:32.699796\", \"message\": \"The processing of the geo-preview has started\"}, {\"error_class\": \"None\", \"layer_fields\": [{\"field_name\": \"ogc_fid\", \"data_type\": \"integer\"}, {\"field_name\":", + "size": 8915, + "state": "active", + "url": "https://data.humdata.org/dataset/a5147aa9-978c-450b-84b5-0b86f569206c/resource/06593579-0eb1-4396-929a-53d849633e6e/download/air_quality_quito_yearly_2018_2020.zip", + "url_type": "upload" + } + ], + "tags": [ + { + "display_name": "environment", + "id": "71e54185-e2ea-4dd0-b67d-8316abefe82b", + "name": "environment", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + }, + { + "display_name": "indicators", + "id": "08dade96-0bf4-4248-9d9f-421f7b844e53", + "name": "indicators", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + } + ], + "relationships_as_subject": [], + "relationships_as_object": [] + }, + { + "archived": false, + "batch": "5b036842-75bd-4d65-9d64-51dbd9e26340", + "caveats": "See methodology documents for sector specific caveats", + "creator_user_id": "1a008a13-52b1-4326-a9ea-aa541372577c", + "data_update_frequency": "30", + "dataset_date": "[2024-01-01T00:00:00 TO 2026-10-19T23:59:59]", + "dataset_preview": "first_resource", + "dataset_source": "Climate TRACE", + "due_date": "2026-11-18T23:59:59", + "has_geodata": false, + "has_showcases": false, + "id": "344cf819-92ff-4239-b36c-1d8138f37757", + "is_requestdata_type": false, + "isopen": true, + "last_modified": "2026-10-05T11:06:30.047508", + "license_id": "cc-by", + "license_title": "Creative Commons Attribution International (CC BY)", + "license_url": "http://www.opendefinition.org/licenses/cc-by", + "maintainer": "8c24c8ce-f313-4020-bda6-00ae42b2aef1", + "metadata_created": "2026-03-11T21:14:09.252261", + "metadata_modified": "2026-10-19T19:37:13.949869", + "methodology": "Other", + "methodology_other": "Climate TRACE identifies the most significant gaps in emissions reporting within current greenhouse gas inventories and develops models to estimate those emissions gaps.", + "name": "egy-climate-trace", + "notes": "Climate TRACE is a non-profit coalition of organizations building a timely, open, and accessible inventory of exactly where greenhouse gas emissions are coming from.", + "num_resources": 7, + "num_tags": 3, + "organization": { + "id": "23c9b1c9-5fcf-4118-923f-d383c68e253e", + "name": "climate-trace", + "title": "Climate TRACE", + "type": "organization", + "description": "Climate TRACE is a non-profit coalition of organizations building a timely, open, and accessible inventory of exactly where greenhouse gas emissions are coming from and how they can be reduced.", + "image_url": "", + "created": "2025-12-11T12:58:49.944160", + "is_organization": true, + "approval_status": "approved", + "state": "active" + }, + "owner_org": "23c9b1c9-5fcf-4118-923f-d383c68e253e", + "package_creator": "HDX Data Systems Team", + "pageviews_last_14_days": 51, + "private": false, + "qa_completed": false, + "solr_additions": "{\"countries\": [\"Egypt\"]}", + "state": "active", + "subnational": "1", + "title": "Egypt: Greenhouse Gas and Air Pollutant Emissions", + "total_res_downloads": 644, + "type": "dataset", + "updated_by_script": "HDX Scraper: Climate TRACE (2026-10-19T19:37:11.867970)", + "url": null, + "version": null, + "groups": [ + { + "description": "", + "display_name": "Egypt", + "id": "egy", + "image_display_url": "", + "name": "egy", + "title": "Egypt" + } + ], + "resources": [ + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/f3a96add-e4a4-4b22-808f-40a1a2046544/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256069", + "datastore_active": true, + "description": "Egypt methane emissions over the past 2 years at the admin 0 and 1 level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/f3a96add-e4a4-4b22-808f-40a1a2046544/download/egy_ch4_admin_0_1.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003779\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:21.447014\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "069239f2f13d3073675f2e5d0026f959", + "hdx_data_dictionary": "[{\"field\": \"full_name\", \"label\": \"Full name\", \"data_type\": \"text\", \"description\": \"Full name of administrative area including parent levels\"}, {\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"text\", \"description\": \"GADM identifier of administrative area at given level\"}, {\"field\": \"level\", \"label\": \"Lev", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/f3a96add-e4a4-4b22-808f-40a1a2046544/download/egy_ch4_admin_0_1.csv", + "id": "f3a96add-e4a4-4b22-808f-40a1a2046544", + "last_modified": "2026-10-05T11:06:30.045860", + "metadata_modified": "2026-10-19T02:12:16.725871", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_ch4_admin_0_1.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 0, + "preview": true, + "preview_rows": 48048, + "resource_type": "file.upload", + "size": 5432680, + "state": "active", + "total_record_count": 48048, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/f3a96add-e4a4-4b22-808f-40a1a2046544/download/egy_ch4_admin_0_1.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/71ef7a16-2374-4db0-a197-70a5e9147f26/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256073", + "datastore_active": true, + "description": "Egypt carbon dioxide equivalent (CO2e) on a 20-year time horizon emissions over the past 2 years at the admin 0 and 1 level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/71ef7a16-2374-4db0-a197-70a5e9147f26/download/egy_co2e_20yr_admin_0_1.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003790\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:21.575092\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "5761413505d738f1099ff2b60fd272d1", + "hdx_data_dictionary": "[{\"field\": \"full_name\", \"label\": \"Full name\", \"data_type\": \"text\", \"description\": \"Full name of administrative area including parent levels\"}, {\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"text\", \"description\": \"GADM identifier of administrative area at given level\"}, {\"field\": \"level\", \"label\": \"Lev", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/71ef7a16-2374-4db0-a197-70a5e9147f26/download/egy_co2e_20yr_admin_0_1.csv", + "id": "71ef7a16-2374-4db0-a197-70a5e9147f26", + "last_modified": "2026-10-05T11:06:30.046563", + "metadata_modified": "2026-10-19T02:12:18.361600", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_co2e_20yr_admin_0_1.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 1, + "preview": true, + "preview_rows": 48048, + "resource_type": "file.upload", + "size": 5936743, + "state": "active", + "total_record_count": 48048, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/71ef7a16-2374-4db0-a197-70a5e9147f26/download/egy_co2e_20yr_admin_0_1.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/9a166be9-5d6c-42e9-b153-1dc0bf42cd0c/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256074", + "datastore_active": true, + "description": "Egypt methane emissions over the past 2 years at the city level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/9a166be9-5d6c-42e9-b153-1dc0bf42cd0c/download/egy_ch4_city.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003799\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:22.555603\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "b130614d8d9da359babcd7a233686ab8", + "hdx_data_dictionary": "[{\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"text\", \"description\": \"Identifier of city, Functional Urban Area of GHSL\"}, {\"field\": \"name\", \"label\": \"Name\", \"data_type\": \"text\", \"description\": \"Name of city (GHSL Functional Urban Area)\"}, {\"field\": \"country\", \"label\": \"Country\", \"data_type\": \"text\",", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/9a166be9-5d6c-42e9-b153-1dc0bf42cd0c/download/egy_ch4_city.csv", + "id": "9a166be9-5d6c-42e9-b153-1dc0bf42cd0c", + "last_modified": "2026-10-05T11:06:30.047078", + "metadata_modified": "2026-10-19T02:12:19.984786", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_ch4_city.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 2, + "preview": true, + "preview_rows": 132132, + "resource_type": "file.upload", + "size": 35407393, + "state": "active", + "total_record_count": 132132, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/9a166be9-5d6c-42e9-b153-1dc0bf42cd0c/download/egy_ch4_city.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/17103be0-736a-43dc-bcf6-2f67cf372bc4/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256075", + "datastore_active": true, + "description": "Egypt carbon dioxide equivalent (CO2e) on a 20-year time horizon emissions over the past 2 years at the city level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/17103be0-736a-43dc-bcf6-2f67cf372bc4/download/egy_co2e_20yr_city.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003804\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:22.514884\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "b9300e049080c73703a419e976ccb041", + "hdx_data_dictionary": "[{\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"text\", \"description\": \"Identifier of city, Functional Urban Area of GHSL\"}, {\"field\": \"name\", \"label\": \"Name\", \"data_type\": \"text\", \"description\": \"Name of city (GHSL Functional Urban Area)\"}, {\"field\": \"country\", \"label\": \"Country\", \"data_type\": \"text\",", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/17103be0-736a-43dc-bcf6-2f67cf372bc4/download/egy_co2e_20yr_city.csv", + "id": "17103be0-736a-43dc-bcf6-2f67cf372bc4", + "last_modified": "2026-10-05T11:06:30.047508", + "metadata_modified": "2026-10-19T02:12:21.580623", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_co2e_20yr_city.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 3, + "preview": true, + "preview_rows": 132132, + "resource_type": "file.upload", + "size": 36746010, + "state": "active", + "total_record_count": 132132, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/17103be0-736a-43dc-bcf6-2f67cf372bc4/download/egy_co2e_20yr_city.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/32167f8c-e466-4fbf-a895-c44d97649531/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256076", + "datastore_active": true, + "description": "Egypt methane emissions over the past 2 years at the source level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/32167f8c-e466-4fbf-a895-c44d97649531/download/egy_ch4_source.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003809\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:21.194720\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "0dc6d1b178730d1eb1dcea1bf3fb91b4", + "hdx_data_dictionary": "[{\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"numeric\", \"description\": \"Internal Climate TRACE identifier for emissions source\"}, {\"field\": \"name\", \"label\": \"Name\", \"data_type\": \"text\", \"description\": \"Name of entity or source producing emissions\"}, {\"field\": \"sector\", \"label\": \"Sector\", \"data_type\"", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/32167f8c-e466-4fbf-a895-c44d97649531/download/egy_ch4_source.csv", + "id": "32167f8c-e466-4fbf-a895-c44d97649531", + "last_modified": "2026-09-28T11:09:32.626240", + "metadata_modified": "2026-10-19T02:12:23.237444", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_ch4_source.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 4, + "preview": true, + "preview_rows": 4050, + "resource_type": "file.upload", + "size": 1201928, + "state": "active", + "total_record_count": 4050, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/32167f8c-e466-4fbf-a895-c44d97649531/download/egy_ch4_source.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/e57393a4-5e31-4c05-8797-c367efd9d539/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256077", + "datastore_active": true, + "description": "Egypt carbon dioxide equivalent (CO2e) on a 20-year time horizon emissions over the past 2 years at the source level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/e57393a4-5e31-4c05-8797-c367efd9d539/download/egy_co2e_20yr_source.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003813\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:21.222342\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "b51ada5d99981b70c4a8123ffe1fe836", + "hdx_data_dictionary": "[{\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"numeric\", \"description\": \"Internal Climate TRACE identifier for emissions source\"}, {\"field\": \"name\", \"label\": \"Name\", \"data_type\": \"text\", \"description\": \"Name of entity or source producing emissions\"}, {\"field\": \"sector\", \"label\": \"Sector\", \"data_type\"", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/e57393a4-5e31-4c05-8797-c367efd9d539/download/egy_co2e_20yr_source.csv", + "id": "e57393a4-5e31-4c05-8797-c367efd9d539", + "last_modified": "2026-09-28T11:09:32.626766", + "metadata_modified": "2026-10-19T02:12:25.021230", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_co2e_20yr_source.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 5, + "preview": true, + "preview_rows": 4050, + "resource_type": "file.upload", + "size": 1259896, + "state": "active", + "total_record_count": 4050, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/e57393a4-5e31-4c05-8797-c367efd9d539/download/egy_co2e_20yr_source.csv", + "url_type": "upload" + }, + { + "alt_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/5ab1d050-b831-44d4-a154-2d1d12c198b8/download/", + "cache_last_updated": null, + "cache_url": null, + "created": "2026-03-11T21:14:09.256078", + "datastore_active": true, + "description": "Egypt PM2.5 emissions over the past 2 years at the source level.", + "download_url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/5ab1d050-b831-44d4-a154-2d1d12c198b8/download/egy_pm2_5_source.csv", + "format": "CSV", + "fs_check_info": "[{\"state\": \"processing\", \"message\": \"The processing of the file structure check has started\", \"timestamp\": \"2026-03-11T21:14:14.003818\"}, {\"state\": \"success\", \"message\": \"File structure check completed\", \"timestamp\": \"2026-03-11T21:14:23.661566\", \"sheet_changes\": [], \"hxl_proxy_response\": {\"url_or_f", + "hash": "7066b24da20b99c6cc860458587781da", + "hdx_data_dictionary": "[{\"field\": \"id\", \"label\": \"ID\", \"data_type\": \"numeric\", \"description\": \"Internal Climate TRACE identifier for emissions source\"}, {\"field\": \"name\", \"label\": \"Name\", \"data_type\": \"text\", \"description\": \"Name of entity or source producing emissions\"}, {\"field\": \"sector\", \"label\": \"Sector\", \"data_type\"", + "hdx_rel_url": "/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/5ab1d050-b831-44d4-a154-2d1d12c198b8/download/egy_pm2_5_source.csv", + "id": "5ab1d050-b831-44d4-a154-2d1d12c198b8", + "last_modified": "2026-09-28T11:09:32.627337", + "metadata_modified": "2026-10-19T02:12:26.667892", + "microdata": false, + "mimetype": null, + "mimetype_inner": null, + "name": "egy_pm2_5_source.csv", + "package_id": "344cf819-92ff-4239-b36c-1d8138f37757", + "position": 6, + "preview": true, + "preview_rows": 3891, + "resource_type": "file.upload", + "size": 1230837, + "state": "active", + "total_record_count": 3891, + "url": "https://data.humdata.org/dataset/344cf819-92ff-4239-b36c-1d8138f37757/resource/5ab1d050-b831-44d4-a154-2d1d12c198b8/download/egy_pm2_5_source.csv", + "url_type": "upload" + } + ], + "tags": [ + { + "display_name": "climate-weather", + "id": "6f0a101d-5c57-408b-aa2a-61c078d32713", + "name": "climate-weather", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + }, + { + "display_name": "environment", + "id": "71e54185-e2ea-4dd0-b67d-8316abefe82b", + "name": "environment", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + }, + { + "display_name": "points of interest-poi", + "id": "55dd76c8-6de4-4d7f-bbd4-c7c9240a2c60", + "name": "points of interest-poi", + "state": "active", + "vocabulary_id": "b891512e-9516-4bf5-962a-7a289772a2a1" + } + ], + "relationships_as_subject": [], + "relationships_as_object": [] + } + ], + "sort": "score desc, last_modified desc", + "search_facets": { + "pivot": {}, + "queries": [] + }, + "facet_pivot": {}, + "facet_queries": {} + } +} From 3319e4892b1742959034964cca845059ce16df15 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:37:22 +0100 Subject: [PATCH 12/31] feat: OpenML results carry their description, licence, update date and run count --- src/sources/openml.rs | 190 ++++++++++++---- tests/fixtures/sources/openml.json | 346 +++++++++++------------------ 2 files changed, 280 insertions(+), 256 deletions(-) diff --git a/src/sources/openml.rs b/src/sources/openml.rs index fce6527..e672ad4 100644 --- a/src/sources/openml.rs +++ b/src/sources/openml.rs @@ -1,70 +1,93 @@ -//! OpenML's active datasets, downloaded whole and searched locally: the REST -//! API filters by name and tag but has no full-text search (live API, October -//! 2026). Only the latest version of each name is kept, in the place its name -//! first appears. +//! OpenML's active datasets, downloaded whole and searched locally. Only the +//! latest version of each name is kept, in the place its name first appears. //! -//! One request returns every active dataset: 6,434 against the 20,000 limit -//! in the URL (October 2026). Past that limit the list would be cut silently; -//! `limit/10000/offset/N` pages it, and a page past the end answers HTTP 412 -//! with error 372 (OpenML, October 2026). The list holds a name, a version and -//! a few size qualities per dataset, no text, so the description is the size. -//! The real description is one request per dataset, 6,434 of them against -//! unpublished rate limits ("rate limits apply", docs.openml.org/intro). +//! The list comes from the Elasticsearch index behind openml.org, the one the +//! website's own search queries from the browser (`ELASTICSEARCH_SERVER` in +//! github.com/openml/openml.org, October 2026). It is not part of the +//! documented REST API, answers only POST (GET is HTTP 403), and speaks +//! Elasticsearch 6 (live, October 2026). The REST `data/list` it replaces +//! carries a name, a version and size qualities but no description, licence +//! or date (`data.tpl.php` in github.com/openml/OpenML, October 2026), and +//! failed with database error 107 "due to high server load" on the day the +//! index answered (October 2026). +//! +//! One request returns every active dataset: 6,668 documents, 10.7 MB in +//! 4.5 s (October 2026), against the index's `max_result_window` of 10,000. +//! Past that window the list would be cut silently; asking for more is HTTP +//! 500 (live, October 2026). Reads are limited to "~1000 requests/hour" +//! (openml.org/apis, October 2026), one request per catalog refresh. +//! +//! `licence` is free text ("Public" on 4,024 of 6,668, "CC0", "CC BY 4.0"); +//! the values that name no licence are dropped. `last_update` is the +//! modification date. `runs`, the experiments run on the dataset, is the +//! popularity: filled for 2,327 datasets, against 1,408 with any download +//! count (October 2026). The index holds no DOI, citation or file size. use std::collections::HashMap; -use serde_json::Value; +use serde_json::{Value, json}; use super::Ctx; use crate::http::SourceError; -use crate::record::{Dataset, items, number, text}; +use crate::record::{Dataset, day, from_markdown, items, number, text}; + +/// Lowercase `licence` values that say nothing about the licence. +const NO_LICENCE: [&str; 5] = [ + "na", + "see source", + "type license() to see the full license text", + "undefined", + "unknown", +]; pub fn list(ctx: &Ctx<'_>) -> Result, SourceError> { let body = ctx .http - .get("https://www.openml.org/api/v1/json/data/list/limit/20000/status/active") + .post("https://www.openml.org/es/data/data/_search") + .json_body(json!({ + "size": 10_000, + "sort": [{"data_id": "asc"}], + "_source": [ + "data_id", + "name", + "version", + "description", + "licence", + "last_update", + "runs", + "qualities.NumberOfInstances", + "qualities.NumberOfFeatures", + ], + "query": {"term": {"status": "active"}}, + })) .slow() .json()?; parse(&body) } pub(super) fn parse(body: &Value) -> Result, SourceError> { - let rows = items(body, "/data/dataset"); + let rows = items(body, "/hits/hits"); if rows.is_empty() { - return Err(SourceError::shape("no data.dataset list")); + return Err(SourceError::shape("no hits.hits list")); } let mut latest: Vec<(u64, Dataset)> = Vec::new(); let mut slot: HashMap = HashMap::new(); for row in rows { - let (Some(id), Some(name)) = (number(row, "/did"), text(row, "/name")) + let Some(doc) = row.get("_source") else { + continue; + }; + let (Some(id), Some(name)) = + (number(doc, "/data_id"), text(doc, "/name")) else { continue; }; - let version = number(row, "/version").unwrap_or(0); + let version = number(doc, "/version").unwrap_or(0); let seen = slot.get(&name).copied(); if seen.and_then(|i| latest.get(i)).is_some_and(|(v, _)| *v >= version) { continue; } - let quality = |key: &str| { - items(row, "/quality").iter().find_map(|q| { - (text(q, "/name").as_deref() == Some(key)) - .then(|| number(q, "/value")) - .flatten() - }) - }; - let shape = match ( - quality("NumberOfInstances"), - quality("NumberOfFeatures"), - ) { - (Some(rows), Some(cols)) => { - Some(format!("{rows} rows, {cols} features")) - } - _ => None, - }; - let dataset = - Dataset::new(&name, &format!("https://www.openml.org/d/{id}")) - .describe(shape); + let dataset = record(doc, id, &name); if let Some(older) = seen.and_then(|i| latest.get_mut(i)) { *older = (version, dataset); } else { @@ -75,6 +98,35 @@ pub(super) fn parse(body: &Value) -> Result, SourceError> { Ok(latest.into_iter().map(|(_, d)| d).filter_map(Dataset::valid).collect()) } +/// The description leads with the table's shape, which no other field +/// carries. A description that only repeats the name is no description. +fn record(doc: &Value, id: u64, name: &str) -> Dataset { + let shape = match ( + number(doc, "/qualities/NumberOfInstances"), + number(doc, "/qualities/NumberOfFeatures"), + ) { + (Some(rows), Some(cols)) => { + Some(format!("{rows} rows, {cols} features")) + } + _ => None, + }; + let prose = text(doc, "/description") + .filter(|d| d != name) + .map(|d| from_markdown(&d)); + let description = match (shape, prose) { + (Some(shape), Some(prose)) => Some(format!("{shape}. {prose}")), + (shape, prose) => shape.or(prose), + }; + let mut dataset = + Dataset::new(name, &format!("https://www.openml.org/d/{id}")) + .describe(description); + dataset.license = text(doc, "/licence") + .filter(|l| !NO_LICENCE.contains(&l.to_lowercase().as_str())); + dataset.updated = day(text(doc, "/last_update")); + dataset.popularity = number(doc, "/runs"); + dataset +} + #[cfg(test)] mod tests { use super::*; @@ -87,22 +139,76 @@ mod tests { hits.iter().map(|h| h.title.as_str()).collect(); assert_eq!( titles, - ["anneal", "kr-vs-kp", "labor", "18ProductivityPrediction"] + [ + "anneal", + "kr-vs-kp", + "BNG(anneal,nominal,1000000)", + "dating_profile", + "18ProductivityPrediction", + ] + ); + assert_eq!( + hits[0], + Dataset { + title: "anneal".into(), + url: "https://www.openml.org/d/2".into(), + description: Some( + "898 rows, 39 features. Author: Unknown. Donated by \ + David Sterling and Wray Buntine Source: UCI - 1990 \ + Please cite: UCI The original Annealing dataset from \ + UCI. The exact meaning of the features and classes is \ + largely unknown." + .into() + ), + publisher: None, + doi: None, + license: Some("Public".into()), + updated: Some("2015-09-02".into()), + size_bytes: None, + popularity: Some(13_779), + aliases: vec![], + } ); + } + + #[test] + fn the_latest_version_keeps_the_first_place_of_its_name() { + let hits = parse(&fixture::json("openml.json")).unwrap(); assert_eq!( - hits[3], + hits[4], Dataset { title: "18ProductivityPrediction".into(), url: "https://www.openml.org/d/43250".into(), description: Some("1197 rows, 15 features".into()), publisher: None, doi: None, - license: None, - updated: None, + license: Some("Public".into()), + updated: Some("2022-02-22".into()), size_bytes: None, - popularity: None, + popularity: Some(0), aliases: vec![], } ); } + + #[test] + fn a_licence_that_names_none_is_dropped() { + let hits = parse(&fixture::json("openml.json")).unwrap(); + assert_eq!(hits[3].title, "dating_profile"); + assert_eq!(hits[3].license, None, "the index says \"NA\""); + assert_eq!( + hits[3].description.as_deref(), + Some( + "59946 rows, 31 features. Anonymized data of dating \ + profiles from OkCupid" + ) + ); + } + + #[test] + fn the_rest_list_shape_is_a_shape_error() { + let rest = + json!({"data": {"dataset": [{"did": 2, "name": "anneal"}]}}); + assert!(matches!(parse(&rest), Err(SourceError::Shape(_)))); + } } diff --git a/tests/fixtures/sources/openml.json b/tests/fixtures/sources/openml.json index d6a7cae..9dc0be6 100644 --- a/tests/fixtures/sources/openml.json +++ b/tests/fixtures/sources/openml.json @@ -1,231 +1,149 @@ { - "data": { - "dataset": [ + "took": 4030, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": 6668, + "max_score": null, + "hits": [ { - "did": 2, - "name": "anneal", - "version": 1, - "status": "active", - "format": "ARFF", - "md5_checksum": "", - "file_id": 1666876, - "quality": [ - { - "name": "MajorityClassSize", - "value": "684.0" - }, - { - "name": "MaxNominalAttDistinctValues", - "value": "7.0" - }, - { - "name": "MinorityClassSize", - "value": "8.0" - }, - { - "name": "NumberOfClasses", - "value": "5.0" - }, - { - "name": "NumberOfFeatures", - "value": "39.0" - }, - { - "name": "NumberOfInstances", - "value": "898.0" - }, - { - "name": "NumberOfInstancesWithMissingValues", - "value": "898.0" - }, - { - "name": "NumberOfMissingValues", - "value": "22175.0" - }, - { - "name": "NumberOfNumericFeatures", - "value": "6.0" - }, - { - "name": "NumberOfSymbolicFeatures", - "value": "33.0" - } + "_index": "data", + "_type": "data", + "_id": "2", + "_score": null, + "_source": { + "licence": "Public", + "data_id": "2", + "last_update": "2015-09-02 00:49:04", + "name": "anneal", + "description": "**Author**: Unknown. Donated by David Sterling and Wray Buntine \n\n**Source**: [UCI](https://archive.ics.uci.edu/ml/datasets/Annealing) - 1990 \n\n**Please cite**: [UCI](https://archive.ics.uci.edu/ml/citation_policy.html) \n\n\n\nThe original Annealing dataset from UCI. The exact meaning of the features and classes is largely unknown.", + "qualities": { + "NumberOfFeatures": 39.0, + "NumberOfInstances": 898.0 + }, + "version": 1.0, + "runs": 13779.0 + }, + "sort": [ + 2 ] }, { - "did": 3, - "name": "kr-vs-kp", - "version": 1, - "status": "active", - "format": "ARFF", - "md5_checksum": "", - "file_id": 3, - "quality": [ - { - "name": "MajorityClassSize", - "value": "1669.0" - }, - { - "name": "MaxNominalAttDistinctValues", - "value": "3.0" - }, - { - "name": "MinorityClassSize", - "value": "1527.0" - }, - { - "name": "NumberOfClasses", - "value": "2.0" - }, - { - "name": "NumberOfFeatures", - "value": "37.0" - }, - { - "name": "NumberOfInstances", - "value": "3196.0" - }, - { - "name": "NumberOfInstancesWithMissingValues", - "value": "0.0" - }, - { - "name": "NumberOfMissingValues", - "value": "0.0" - }, - { - "name": "NumberOfNumericFeatures", - "value": "0.0" - }, - { - "name": "NumberOfSymbolicFeatures", - "value": "37.0" - } + "_index": "data", + "_type": "data", + "_id": "3", + "_score": null, + "_source": { + "licence": "Public", + "data_id": "3", + "last_update": "2014-04-06 23:19:28", + "name": "kr-vs-kp", + "description": "Author: Alen Shapiro\nSource: [UCI](https://archive.ics.uci.edu/ml/datasets/Chess+(King-Rook+vs.+King-Pawn))\nPlease cite: [UCI citation policy](https://archive.ics.uci.edu/ml/citation_policy.html)\n\n1. Title: Chess End-Game -- King+Rook versus King+Pawn on a7\n(usually abbreviated KRKPA7). The pawn on a7 means it is one square\naway from queening. It is the King+Rook's side (white) to move.", + "qualities": { + "NumberOfFeatures": 37.0, + "NumberOfInstances": 3196.0 + }, + "version": 1.0, + "runs": 274253.0 + }, + "sort": [ + 3 ] }, { - "did": 4, - "name": "labor", - "version": 1, - "status": "active", - "format": "ARFF", - "md5_checksum": "", - "file_id": 4, - "quality": [ - { - "name": "MajorityClassSize", - "value": "37.0" - }, - { - "name": "MaxNominalAttDistinctValues", - "value": "3.0" - }, - { - "name": "MinorityClassSize", - "value": "20.0" - }, - { - "name": "NumberOfClasses", - "value": "2.0" - }, - { - "name": "NumberOfFeatures", - "value": "17.0" - }, - { - "name": "NumberOfInstances", - "value": "57.0" - }, - { - "name": "NumberOfInstancesWithMissingValues", - "value": "56.0" - }, - { - "name": "NumberOfMissingValues", - "value": "326.0" - }, - { - "name": "NumberOfNumericFeatures", - "value": "8.0" - }, - { - "name": "NumberOfSymbolicFeatures", - "value": "9.0" - } + "_index": "data", + "_type": "data", + "_id": "70", + "_score": null, + "_ignored": [ + "suggest" + ], + "_source": { + "licence": "Public", + "data_id": "70", + "last_update": "2014-04-08 05:57:14", + "name": "BNG(anneal,nominal,1000000)", + "description": "", + "qualities": { + "NumberOfFeatures": 39.0, + "NumberOfInstances": 1000000.0 + }, + "version": 1.0, + "runs": 143.0 + }, + "sort": [ + 70 ] }, { - "did": 43219, - "name": "18ProductivityPrediction", - "version": 1, - "status": "active", - "format": "ARFF", - "md5_checksum": "", - "file_id": 22101905, - "quality": [ - { - "name": "NumberOfFeatures", - "value": "15.0" - }, - { - "name": "NumberOfInstances", - "value": "1197.0" - }, - { - "name": "NumberOfInstancesWithMissingValues", - "value": "506.0" - }, - { - "name": "NumberOfMissingValues", - "value": "506.0" - }, - { - "name": "NumberOfNumericFeatures", - "value": "11.0" - }, - { - "name": "NumberOfSymbolicFeatures", - "value": "4.0" - } + "_index": "data", + "_type": "data", + "_id": "42164", + "_score": null, + "_source": { + "licence": "NA", + "data_id": "42164", + "last_update": "2019-10-04 12:46:11", + "name": "dating_profile", + "description": "Anonymized data of dating profiles from OkCupid", + "qualities": { + "NumberOfFeatures": 31.0, + "NumberOfInstances": 59946.0 + }, + "version": 1.0, + "runs": 0.0 + }, + "sort": [ + 42164 ] }, { - "did": 43250, - "name": "18ProductivityPrediction", - "version": 2, - "status": "active", - "format": "ARFF", - "md5_checksum": "", - "file_id": 22101938, - "quality": [ - { - "name": "NumberOfClasses", - "value": "0.0" - }, - { - "name": "NumberOfFeatures", - "value": "15.0" - }, - { - "name": "NumberOfInstances", - "value": "1197.0" - }, - { - "name": "NumberOfInstancesWithMissingValues", - "value": "506.0" - }, - { - "name": "NumberOfMissingValues", - "value": "506.0" - }, - { - "name": "NumberOfNumericFeatures", - "value": "11.0" - }, - { - "name": "NumberOfSymbolicFeatures", - "value": "4.0" - } + "_index": "data", + "_type": "data", + "_id": "43219", + "_score": null, + "_source": { + "licence": "CC0", + "data_id": "43219", + "last_update": "2022-02-21 10:04:15", + "name": "18ProductivityPrediction", + "description": "18ProductivityPrediction", + "qualities": { + "NumberOfFeatures": 15.0, + "NumberOfInstances": 1197.0 + }, + "version": 1.0, + "runs": 0.0 + }, + "sort": [ + 43219 + ] + }, + { + "_index": "data", + "_type": "data", + "_id": "43250", + "_score": null, + "_source": { + "licence": "Public", + "data_id": "43250", + "last_update": "2022-02-22 09:17:57", + "name": "18ProductivityPrediction", + "description": "18ProductivityPrediction", + "qualities": { + "NumberOfFeatures": 15.0, + "NumberOfInstances": 1197.0 + }, + "version": 2.0, + "runs": 0.0 + }, + "sort": [ + 43250 ] } ] From db4396929e0404856d5496ac1afe835d5e8d2aef Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:47:42 +0100 Subject: [PATCH 13/31] feat: data.europa.eu results carry SPDX license ids, file sizes and Zenodo concept DOIs --- src/sources/europa.rs | 217 +++++++++++-- tests/fixtures/sources/europa.italy.json | 390 +++++++++++++++++++++++ tests/fixtures/sources/europa.json | 238 +++++++++----- 3 files changed, 737 insertions(+), 108 deletions(-) create mode 100644 tests/fixtures/sources/europa.italy.json diff --git a/src/sources/europa.rs b/src/sources/europa.rs index d52f736..22ae08c 100644 --- a/src/sources/europa.rs +++ b/src/sources/europa.rs @@ -13,19 +13,43 @@ //! the search engine fail with HTTP 400, while a balanced pair searches a //! phrase and no other character matters (data.europa.eu, October 2026). //! The DOI, where the record has one, is the link to doi.org that Zenodo -//! records carry as identifier or page and others as landing page. The -//! metadata is CC0 and the API is read only; no rate limit or caching term -//! is published (data.europa.eu legal notice, October 2026). +//! records carry as identifier or page and others as landing page, and a +//! Zenodo record's concept DOI arrives in `is_version_of` (probes, October +//! 2026). The metadata is CC0 and the API is read only; no rate limit, +//! caching term or API key is published (data.europa.eu legal notice, data +//! provider manual, October 2026). +//! +//! A license sits on each distribution. Where the portal maps it to the EU +//! licence vocabulary, `resource` is the spdx.org URI; otherwise `id`, +//! `label` and `resource` all repeat the publisher's own URI, most often a +//! Creative Commons deed (probes of 600 records, October 2026). `byte_size` +//! is per distribution, and data.gov.it writes 1024 or 0 for files of any +//! size: 1,098 of its 1,257 sized distributions in four queries (probes, +//! October 2026). The dataset's `modified`, else `issued`, is its date: +//! `catalog_record.modified` and a distribution's `modified` are the days +//! the portal re-harvested it, within the last few months even for records +//! published years before (probes, October 2026). use serde_json::Value; use super::Ctx; use crate::http::SourceError; -use crate::record::{Dataset, day, doi, items, localized, text}; +use crate::record::{Dataset, day, doi, items, localized, number, text}; const INCLUDES: &str = "id,title,description,publisher,catalog.id,\ - catalog.title,distributions.license,modified,issued,\ - landing_page,page,identifier"; + catalog.title,distributions.license,\ + distributions.byte_size,modified,issued,\ + landing_page,page,identifier,is_version_of"; + +/// The sizes data.gov.it writes for a file it has not measured. +const UNMEASURED_BYTES: [u64; 2] = [0, 1024]; + +/// License ids and URIs that say no license was given. +const NO_LICENSE: [&str; 2] = [ + "notspecified", + "http://inspire.ec.europa.eu/metadata-codelist/\ + ConditionsApplyingToAccessAndUse/conditionsUnknown", +]; pub fn search( ctx: &Ctx<'_>, @@ -79,15 +103,74 @@ fn record(row: &Value) -> Option { .pointer("/publisher/name") .and_then(|v| localized(Some(v))) .or_else(|| localized(row.pointer("/catalog/title"))); - dataset.license = items(row, "/distributions").iter().find_map(|d| { - localized(d.pointer("/license/label")) - .or_else(|| text(d, "/license/id")) - }); + let distributions = items(row, "/distributions"); + dataset.license = distributions.iter().find_map(license); dataset.updated = day(text(row, "/modified").or_else(|| text(row, "/issued"))); + dataset.size_bytes = distributions + .iter() + .filter_map(|d| number(d, "/byte_size")) + .filter(|bytes| !UNMEASURED_BYTES.contains(bytes)) + .reduce(u64::saturating_add); + dataset.aliases = items(row, "/is_version_of") + .iter() + .filter_map(|link| text(link, "")) + .filter(|raw| raw.contains("doi.org/")) + .filter_map(|raw| doi(&raw)) + .filter(|concept| dataset.doi.as_ref() != Some(concept)) + .collect(); dataset.valid() } +fn license(distribution: &Value) -> Option { + let license = distribution.get("license")?; + let id = text(license, "/id"); + let resource = text(license, "/resource"); + if [&id, &resource] + .into_iter() + .flatten() + .any(|named| NO_LICENSE.contains(&named.as_str())) + { + return None; + } + resource + .as_deref() + .and_then(spdx) + .or_else(|| localized(license.get("label"))) + .or(id) +} + +/// The SPDX id a license URI names: the id of an spdx.org URI, or the +/// license and version of an unported Creative Commons deed or legal code. +/// A national port such as `by/3.0/at` has no SPDX id of this form. +fn spdx(uri: &str) -> Option { + let path = uri.split_once("://")?.1; + let path = path.strip_prefix("www.").unwrap_or(path); + if let Some(id) = path.strip_prefix("spdx.org/licenses/") { + let id = id.trim_end_matches('/').trim_end_matches(".html"); + return (!id.is_empty()).then(|| id.to_owned()); + } + let mut parts = path.strip_prefix("creativecommons.org/")?.split('/'); + let (kind, code, version) = (parts.next()?, parts.next()?, parts.next()?); + let rest = parts.next().unwrap_or_default(); + let unported = rest.is_empty() + || rest.starts_with("legalcode") + || rest.starts_with("deed"); + let numbered = version.starts_with(|c: char| c.is_ascii_digit()) + && version.chars().all(|c| c.is_ascii_digit() || c == '.'); + if !unported || !numbered { + return None; + } + match (kind, code) { + ("publicdomain", "zero") => Some(format!("CC0-{version}")), + ( + "licenses", + "by" | "by-sa" | "by-nd" | "by-nc" | "by-nc-sa" | "by-nc-nd", + ) => Some(format!("CC-{}-{version}", code.to_ascii_uppercase())), + _ => None, + } +} + fn doi_of(row: &Value) -> Option { let links = ["/landing_page", "/page"] .into_iter() @@ -109,7 +192,7 @@ mod tests { #[test] fn records_map_from_a_recorded_search() { let hits = parse(&fixture::json("europa.json"), 10).unwrap(); - assert_eq!(hits.len(), 5); + assert_eq!(hits.len(), 6); assert_eq!( hits[0], Dataset { @@ -126,34 +209,122 @@ mod tests { ), publisher: Some("Zenodo".into()), doi: Some("10.5281/zenodo.1631856".into()), - license: Some( - "https://creativecommons.org/licenses/by/4.0/legalcode" - .into() - ), + license: None, updated: Some("2024-08-01".into()), - size_bytes: None, + size_bytes: Some(43_125_616), popularity: None, - aliases: vec![], + aliases: vec!["10.5281/zenodo.1631855".into()], } ); } #[test] - fn a_doi_comes_from_a_doi_link_and_a_catalog_stands_in_as_publisher() { + fn a_doi_comes_from_a_doi_link_and_a_concept_doi_is_an_alias() { let hits = parse(&fixture::json("europa.json"), 10).unwrap(); let dois: Vec<_> = hits.iter().map(|h| h.doi.as_deref()).collect(); assert_eq!( dois, [ Some("10.5281/zenodo.1631856"), - None, - Some("10.1594/wdcc/uni_hh_mi_acsys2003"), - Some("10.5281/zenodo.14975004"), Some("10.5281/zenodo.3540757"), + None, + None, + None, + Some("10.16904/envidat.381"), ] ); - assert_eq!(hits[2].publisher.as_deref(), Some("GDI-DE")); - assert_eq!(hits[1].updated.as_deref(), Some("2023-03-22")); + assert_eq!(hits[1].aliases, ["10.5281/zenodo.3540756"]); + assert_eq!(hits[5].aliases, Vec::::new()); + } + + #[test] + fn licenses_become_spdx_ids_where_the_uri_names_one() { + let licenses = |name| { + parse(&fixture::json(name), 10) + .unwrap() + .into_iter() + .map(|h| h.license) + .collect::>() + }; + let ogl = "http://reference.data.gov.uk/id/open-government-licence"; + let swiss = "http://dcat-ap.ch/vocabulary/licenses/terms_open"; + assert_eq!( + licenses("europa.json"), + [None, Some("CC-BY-4.0"), Some(ogl), Some("CC-BY-4.0"), Some(ogl)] + .into_iter() + .chain([Some(swiss)]) + .map(|l| l.map(String::from)) + .collect::>() + ); + let by = Some("CC-BY-4.0".to_owned()); + assert_eq!( + licenses("europa.italy.json"), + [ + by.clone(), + None, + None, + None, + by.clone(), + by.clone(), + by, + Some("CC0-1.0".into()), + ], + "INSPIRE's conditionsUnknown is no license" + ); + } + + #[test] + fn a_national_creative_commons_port_keeps_its_uri() { + assert_eq!( + spdx("http://creativecommons.org/licenses/by/4.0/deed.nl") + .as_deref(), + Some("CC-BY-4.0") + ); + assert_eq!( + spdx("https://creativecommons.org/licenses/by/3.0/at/deed.de"), + None + ); + assert_eq!(spdx("http://dcat-ap.de/def/licenses/dl-by-de/2.0"), None); + } + + #[test] + fn sizes_add_up_and_data_gov_it_placeholders_are_dropped() { + let sizes = |name| { + parse(&fixture::json(name), 10) + .unwrap() + .into_iter() + .map(|h| h.size_bytes) + .collect::>() + }; + assert_eq!( + sizes("europa.json"), + [Some(43_125_616), None, None, None, None, Some(2_386_070)] + ); + assert_eq!(sizes("europa.italy.json"), [None; 8]); + } + + #[test] + fn the_date_is_the_last_modification_and_a_catalog_stands_in_as_publisher() + { + let hits = parse(&fixture::json("europa.italy.json"), 10).unwrap(); + let days: Vec<_> = hits.iter().map(|h| h.updated.as_deref()).collect(); + assert_eq!( + days, + [ + Some("2023-01-12"), + None, + None, + Some("2025-06-13"), + Some("2026-06-22"), + Some("2020-01-16"), + Some("2018-08-05"), + Some("2019-09-30"), + ] + ); + assert_eq!( + hits[1].publisher.as_deref(), + Some("Italian Catalogue of metadata for Spatial Data") + ); } #[test] diff --git a/tests/fixtures/sources/europa.italy.json b/tests/fixtures/sources/europa.italy.json new file mode 100644 index 0000000..99f91a7 --- /dev/null +++ b/tests/fixtures/sources/europa.italy.json @@ -0,0 +1,390 @@ +{ + "result": { + "index": "dataset", + "count": 32340, + "results": [ + { + "identifier": [ + "r_marche_1_1703248088" + ], + "catalog": { + "id": "dati-gov-it", + "title": { + "en": "data.gov.it" + } + }, + "description": { + "en": "Air quality website." + }, + "modified": "2023-01-12T00:00:00", + "landing_page": [ + { + "resource": "https://dati.regione.marche.it/dataset/qualita-dell-aria#" + } + ], + "publisher": { + "type": "Agent", + "name": "ARPAM" + }, + "index": "dataset", + "id": "r_marche_1_1703248088", + "title": { + "en": "Air quality" + }, + "issued": "2023-01-12T00:00:00", + "distributions": [ + { + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + }, + "byte_size": 1024 + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + } + ] + }, + { + "identifier": [ + "https://geodati.gov.it/resource/id/r_lazio:696ae46c-5cc7-11ec-9eaf-0242" + ], + "description": { + "en": "Zoning of the regional territory for the purposes of assessing ambient air quality in Lazio (Articles 3 and 4 of Legislative Decree No 155/2010, as amended) and updating the classification of areas an" + }, + "index": "dataset", + "id": "r_lazio-696ae46c-5cc7-11ec-9eaf-0242", + "title": { + "en": "Air quality" + }, + "catalog": { + "id": "rndt", + "title": { + "en": "Italian Catalogue of metadata for Spatial Data" + } + } + }, + { + "identifier": [ + "r_piemon:9ce253c5-1dd5-4254-8c80-8b55cdc78e74" + ], + "catalog": { + "id": "rndt", + "title": { + "en": "Italian Catalogue of metadata for Spatial Data" + } + }, + "description": { + "en": "The Air Quality Database contains:- all data collected for the individual polluted by stations of public and private networks (managed by ARPA or by private individuals themselves) present in the terr" + }, + "index": "dataset", + "id": "r_piemon-9ce253c5-1dd5-4254-8c80-8b55cdc78e74", + "title": { + "en": "Air Quality — Regional Air Quality Assessment System" + }, + "distributions": [ + { + "license": { + "resource": "http://inspire.ec.europa.eu/metadata-codelist/ConditionsApplyingToAccessAndUse/conditionsUnknown", + "id": "http://inspire.ec.europa.eu/metadata-codelist/ConditionsApplyingToAccessAndUse/conditionsUnknown", + "label": "http://inspire.ec.europa.eu/metadata-codelist/ConditionsApplyingToAccessAndUse/conditionsUnknown" + } + } + ] + }, + { + "identifier": [ + "arpa_09:03649-DATA" + ], + "catalog": { + "id": "rndt", + "title": { + "en": "Italian Catalogue of metadata for Spatial Data" + } + }, + "description": { + "en": "The regional air quality monitoring network, which has been operating since the 1990s, is a cognitive tool designed to provide information on the general state of air quality throughout the region and not exclusively aimed at verifying compliance with regulatory limits." + }, + "modified": "2025-06-13", + "index": "dataset", + "id": "arpa_09-03649-meta-20180206-090000", + "title": { + "en": "ARPA monitoring: Air quality" + }, + "issued": "2018-02-06" + }, + { + "identifier": [ + "p_TN:ispat_939" + ], + "catalog": { + "id": "dati-gov-it", + "title": { + "en": "data.gov.it" + } + }, + "description": { + "en": "**Sector:** State of the environment\n\n**Algorithm:** Percentage of valid measurements above the WHO health reference value of average annual PM2.5 concentrations\n\n**Fenomenon:** Stock\n\n**Territorial comparisons:** Trentino." + }, + "modified": "2026-06-22T00:00:00", + "landing_page": [ + { + "resource": "https://dati.trentino.it/dataset/qualita-dellaria-pm-2-51#" + } + ], + "publisher": { + "type": "Agent", + "name": "ISPAT Istituto di statistica della provincia di Trento" + }, + "index": "dataset", + "id": "p_tn-ispat_939", + "title": { + "en": "Air quality - PM 2.5" + }, + "issued": "2026-06-25T00:00:00", + "distributions": [ + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + }, + { + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + }, + "byte_size": 1024 + } + ] + }, + { + "identifier": [ + "Monitoraggiomensilequalitàdell'aria" + ], + "catalog": { + "id": "dati-gov-it", + "title": { + "en": "data.gov.it" + } + }, + "description": { + "en": "Dataset with monthly air quality surveys." + }, + "publisher": { + "type": "Agent", + "name": "DO" + }, + "modified": "2020-01-16T00:00:00", + "landing_page": [ + { + "resource": "http://dati.comune.lecce.it/dataset/monitoraggio-mensile-qualita-dell-aria#" + } + ], + "index": "dataset", + "id": "monitoraggiomensilequalita-dell-aria", + "title": { + "en": "Monthly air quality monitoring" + }, + "issued": "2020-01-16T00:00:00", + "distributions": [ + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + }, + { + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + }, + "byte_size": 1024 + }, + { + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + }, + "byte_size": 1024 + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + } + ] + }, + { + "identifier": [ + "monitaraggio-mensile-qualita-dell-aria" + ], + "catalog": { + "id": "dati-gov-it", + "title": { + "en": "data.gov.it" + } + }, + "description": { + "en": "Dataset with monthly air quality surveys." + }, + "publisher": { + "type": "Agent", + "name": "Redazione OD" + }, + "modified": "2018-08-05T00:00:00", + "landing_page": [ + { + "resource": "http://dati.comune.lecce.it/dataset/monitaraggio-mensile-qualita-dell-aria#" + } + ], + "index": "dataset", + "id": "monitaraggio-mensile-qualita-dell-aria", + "title": { + "en": "Monthly air quality monitoring" + }, + "issued": "2014-08-01T19:43:44.667293", + "distributions": [ + { + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + }, + "byte_size": 1024 + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + }, + { + "byte_size": 1024, + "license": { + "id": "CC_BY_4_0", + "label": "Creative Commons Attribution 4.0 International", + "description": "Creative Commons Attribution 4.0 International", + "resource": "http://spdx.org/licenses/CC-BY-4.0" + } + } + ] + }, + { + "identifier": [ + "Datiqualitdellaria2019Salerno" + ], + "catalog": { + "id": "dati-gov-it", + "title": { + "en": "data.gov.it" + } + }, + "description": { + "en": "The values of the air quality parameters are reported." + }, + "landing_page": [ + { + "resource": "https://dati.regione.campania.it/catalogo/datasetdetail/dati-qualita-dell-aria-2019-salerno#" + } + ], + "publisher": { + "type": "Agent", + "name": "Regione Campania" + }, + "modified": "2019-09-30T00:00:00", + "index": "dataset", + "id": "datiqualitdellaria2019salerno", + "title": { + "en": "Air quality data 2019 Salerno" + }, + "issued": "2019-09-30T00:00:00", + "distributions": [ + { + "byte_size": 1024, + "license": { + "id": "CC0", + "label": "Creative Commons CC0 1.0 Universal", + "description": "Creative Commons CC0 1.0 Universal", + "resource": "https://creativecommons.org/publicdomain/zero/1.0/" + } + }, + { + "byte_size": 1024, + "license": { + "id": "CC0", + "label": "Creative Commons CC0 1.0 Universal", + "description": "Creative Commons CC0 1.0 Universal", + "resource": "https://creativecommons.org/publicdomain/zero/1.0/" + } + }, + { + "byte_size": 1024, + "license": { + "id": "CC0", + "label": "Creative Commons CC0 1.0 Universal", + "description": "Creative Commons CC0 1.0 Universal", + "resource": "https://creativecommons.org/publicdomain/zero/1.0/" + } + }, + { + "license": { + "id": "CC0", + "label": "Creative Commons CC0 1.0 Universal", + "description": "Creative Commons CC0 1.0 Universal", + "resource": "https://creativecommons.org/publicdomain/zero/1.0/" + }, + "byte_size": 1024 + } + ] + } + ], + "facets": [] + } +} diff --git a/tests/fixtures/sources/europa.json b/tests/fixtures/sources/europa.json index e36c658..be6e43b 100644 --- a/tests/fixtures/sources/europa.json +++ b/tests/fixtures/sources/europa.json @@ -1,18 +1,19 @@ { "result": { "index": "dataset", - "count": 77680, + "count": 78365, "results": [ { "identifier": [ "https://doi.org/10.5281/zenodo.1631856" ], + "is_version_of": [ + "https://doi.org/10.5281/zenodo.1631855" + ], "catalog": { "id": "zenodo", "title": { - "en": "EU Open Research Repository", - "fr": "Répertoire ouvert de l’UE pour la recherche", - "de": "Open Research Repository der EU" + "en": "EU Open Research Repository" } }, "description": { @@ -37,153 +38,220 @@ "issued": "2018-11-28", "distributions": [ { - "license": { - "resource": "https://creativecommons.org/licenses/by/4.0/legalcode", - "id": "https://creativecommons.org/licenses/by/4.0/legalcode", - "label": "https://creativecommons.org/licenses/by/4.0/legalcode" - } + "byte_size": 10781404 + }, + { + "byte_size": 10781404 + }, + { + "byte_size": 10781404 + }, + { + "byte_size": 10781404 } ] }, { + "identifier": [ + "https://doi.org/10.5281/zenodo.3540757" + ], + "is_version_of": [ + "https://doi.org/10.5281/zenodo.3540756" + ], "catalog": { - "id": "oppnadata", + "id": "zenodo", "title": { - "en": "Sweden's data portal", - "fr": "Portail de données de la Suède", - "de": "Schwedens Datenportal" + "en": "EU Open Research Repository" } }, "description": { - "de": "Daten, die während der schwedisch-kanadischen Expedition Arctic Ocean 2016 mit der Forschungskreuzfahrt Oden erhoben wurden.\n\nWeitere Informationen finden Sie auf der englischen Katalogseite: https://snd.gu.se/en/catalogue/study/ecds0237", - "fr": "Données recueillies lors de l'expédition canado-suédoise Arctic Ocean 2016, avec la croisière de recherche Oden.\n\nPour plus d'informations, voir la page du catalogue en anglais: https://snd.gu.se/en/catalogue/study/ecds0237", - "en": "This dataset contains data collected during the Canadian-Swedish expedition Arctic Ocean 2016. The research cruise took place August through September 2016, using the icebreaker Oden.\n\nFor ship data from the cruise, as well as graphics and files describing the route, see https://snd.gu." + "en": "For additional information or any request, please email contact@example.org" }, "publisher": { - "resource": "https://ror.org/05xg72x27", - "name": "The Norwegian University of Science and Technology (NTNU)", - "type": "Agent", - "homepage": "http://www.ntnu.edu" + "name": "Zenodo", + "type": "Agent" }, - "modified": "2023-03-22T10:50:26.974532Z", + "modified": "2020-01-24", "index": "dataset", - "id": "https-admin-dataportal-se-store-818-resource-945854a112344f4755c13af47d669761", + "id": "oai-zenodo-org-3540757", + "page": [ + { + "resource": "https://doi.org/10.5281/zenodo.3540757" + } + ], "title": { - "de": "Arctic Ocean 2016 - Eisdicke und Kamerabilder", - "fr": "Océan Arctique 2016 - Épaisseur de glace et images de la caméra", - "en": "Arctic Ocean 2016 - Ice Thickness Camera Images" + "en": "Impact of the ice thickness distribution discretization on the sea ice concentration variability in the NEMO3.6-LIM3 global ocean–sea ice model" }, - "issued": "2023-03-22T10:50:26.974532Z" + "issued": "2019", + "distributions": [ + { + "license": { + "resource": "https://creativecommons.org/licenses/by/4.0/legalcode", + "id": "https://creativecommons.org/licenses/by/4.0/legalcode", + "label": "https://creativecommons.org/licenses/by/4.0/legalcode" + } + } + ] }, { - "identifier": [ - "None", - "doi:10.1594/WDCC/UNI_HH_MI_ACSYS2003/ACSYS%202003%20-%20Arctic%20Atmospheric%20Boundary%20Layer%20and%20Sea%20Ice%20Interaction%20Study%20north%20of%20Spitsbergen:%20meteorological%20measurements%20of%20the%20research%20aircraft%20Falcon,%2011%20autonomous%20ice%20buoys%20and%20radiosoundings%20at%20the%20research%20vessels%20Aranda%20and%20Polarstern" - ], "catalog": { - "id": "gdi-de", + "id": "data-gov-uk", "title": { - "de": "GDI-DE", - "fr": "GDI-DE", - "en": "GDI-DE" + "en": "data.gov.uk" } }, + "publisher": { + "type": "Agent", + "name": "Centre for Environmental Data Analysis" + }, "description": { - "de": "From 26 March to 22 April 2003, Germany and Finland carried out a joint expedition (ABSIS - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study) to test and improve the description of the ocean-ice-atmosphere interaction processes.", - "fr": "From 26 March to 22 April 2003, Germany and Finland carried out a joint expedition (ABSIS - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study) to test and improve the description of the ocean-ice-atmosphere interaction processes.", - "en": "From 26 March to 22 April 2003, Germany and Finland carried out a joint expedition (ABSIS - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study) to test and improve the description of the ocean-ice-atmosphere interaction processes." + "en": "Theme 5 - Cryosphere and Polar Oceans - of the National Centre for Earth Observation (NCEO) is aimed at resolving uncertainties in future climate and sea-level arising from behaviour of the cryosphere." }, - "landing_page": [ - { - "resource": "http://doi.org/doi:10.1594/WDCC/UNI_HH_MI_ACSYS2003" - } - ], "index": "dataset", - "id": "de-dkrz-wdcc-iso2250972", + "id": "national-centre-for-earth-observation-nceo-sea-ice-elevation-and-thickness-and-ice-sheet-elevat1", "title": { - "de": "ACSYS 2003 - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study", - "fr": "ACSYS 2003 - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study", - "en": "ACSYS 2003 - Arctic Atmospheric Boundary Layer and Sea Ice Interaction Study" - } + "en": "National Centre for Earth Observation (NCEO): Sea Ice Elevation and Thickness and Ice Sheet Elevation Change Data" + }, + "distributions": [ + { + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + }, + { + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + } + ] }, { "identifier": [ - "https://doi.org/10.5281/zenodo.14975004" + "527b0f30-7d22-11ed-a51b-432755aaeed3" ], "catalog": { - "id": "zenodo", + "id": "oppnadata", "title": { - "en": "EU Open Research Repository", - "fr": "Répertoire ouvert de l’UE pour la recherche", - "de": "Open Research Repository der EU" + "en": "Sweden's data portal" } }, "description": { - "en": "The ASILaC datasets presents monthly files of correlation statistics calculated between Sea Ice Area (SIA) in eight Arctic basins and terrestrial parameters in the Arctic region North of 60°N. Data format: raster GeoTIFF The terrestrial parameters are: 1." + "en": "Purpose: Describes the current and historical hydrological state in Sweden.\n\nUnit: cm\n\nCharacteristics: Weekly information on ice thickness in lakes in Sweden.\n\nNetwork information:\n- SMHI's station network: Data is collected and stored in SMHI's databases." }, - "modified": "2025-10-27", + "modified": "2023-08-21", "publisher": { - "name": "Zenodo", - "type": "Agent" + "type": "Agent", + "email": "mailto:opendata-support@smhi.se", + "name": "Sveriges meteorologiska och hydrologiska institut", + "resource": "http://dataportal.se/organisation/SE2021000696" }, "index": "dataset", - "id": "oai-zenodo-org-14975004", - "page": [ + "id": "https-opendata-catalog-smhi-se-md-527b0f30-7d22-11ed-a51b-432755aaeed3", + "title": { + "en": "SE.ACMF Hydrological observations - Thickness of ice" + }, + "issued": "2022-12-16", + "distributions": [ { - "resource": "https://doi.org/10.5281/zenodo.14975004" + "license": { + "resource": "https://creativecommons.org/licenses/by/4.0/", + "id": "https://creativecommons.org/licenses/by/4.0/", + "label": "https://creativecommons.org/licenses/by/4.0/" + } + }, + { + "license": { + "resource": "https://creativecommons.org/licenses/by/4.0/", + "id": "https://creativecommons.org/licenses/by/4.0/", + "label": "https://creativecommons.org/licenses/by/4.0/" + } } - ], + ] + }, + { + "catalog": { + "id": "data-gov-uk", + "title": { + "en": "data.gov.uk" + } + }, + "publisher": { + "type": "Agent", + "name": "Centre for Environmental Data Analysis" + }, + "description": { + "en": "Theme 5 - Cryosphere and Polar Oceans - of the National Centre for Earth Observation (NCEO) is aimed at resolving uncertainties in future climate and sea-level arising from behaviour of the cryosphere." + }, + "index": "dataset", + "id": "national-centre-for-earth-observation-nceo-sea-ice-elevation-and-thickness-and-ice-sheet-elevat", "title": { - "en": "Arctic Sea Ice and Land Parameter Correlations (ASILaC)" + "en": "National Centre for Earth Observation (NCEO): Sea Ice Elevation and Thickness and Ice Sheet Elevation Change Data" }, - "issued": "2025", "distributions": [ { "license": { - "resource": "https://creativecommons.org/licenses/by-nc/4.0/legalcode", - "id": "https://creativecommons.org/licenses/by-nc/4.0/legalcode", - "label": "https://creativecommons.org/licenses/by-nc/4.0/legalcode" + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + }, + { + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" } } ] }, { "identifier": [ - "https://doi.org/10.5281/zenodo.3540757" + "10.16904_ENVIDAT.381@envidat" ], "catalog": { - "id": "zenodo", + "id": "opendata-swiss", "title": { - "en": "EU Open Research Repository", - "fr": "Répertoire ouvert de l’UE pour la recherche", - "de": "Open Research Repository der EU" + "en": "opendata.swiss" } }, + "modified": "2026-06-09T23:07:06Z", "description": { - "en": "For additional information or any request, please email contact@example.org" - }, - "publisher": { - "name": "Zenodo", - "type": "Agent" + "en": "Data accompanying David Wagners' Dissertation." }, - "modified": "2020-01-24", - "index": "dataset", - "id": "oai-zenodo-org-3540757", - "page": [ + "landing_page": [ { - "resource": "https://doi.org/10.5281/zenodo.3540757" + "resource": "https://doi.org/10.16904/ENVIDAT.381" } ], + "publisher": { + "type": "Agent", + "name": "EnviDat", + "resource": "https://opendata.swiss/organization/envidat" + }, + "index": "dataset", + "id": "10-16904_envidat-381-envidat", "title": { - "en": "Impact of the ice thickness distribution discretization on the sea ice concentration variability in the NEMO3.6-LIM3 global ocean–sea ice model" + "en": "MOSAIC Snow on Sea Ice Data" }, - "issued": "2019", + "issued": "2023-01-01T00:00:00", "distributions": [ { "license": { - "resource": "https://creativecommons.org/licenses/by/4.0/legalcode", - "id": "https://creativecommons.org/licenses/by/4.0/legalcode", - "label": "https://creativecommons.org/licenses/by/4.0/legalcode" + "resource": "http://dcat-ap.ch/vocabulary/licenses/terms_open", + "id": "http://dcat-ap.ch/vocabulary/licenses/terms_open", + "label": "http://dcat-ap.ch/vocabulary/licenses/terms_open" + } + }, + { + "byte_size": 2386070, + "license": { + "resource": "http://dcat-ap.ch/vocabulary/licenses/terms_open", + "id": "http://dcat-ap.ch/vocabulary/licenses/terms_open", + "label": "http://dcat-ap.ch/vocabulary/licenses/terms_open" } } ] From 5ff5effc9c40516bedba33f688e3d65d1a84cff6 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:03:44 +0100 Subject: [PATCH 14/31] fix: a page behind an AWS bot wall reads as blocked, not as a page without dataset markup --- src/http.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/http.rs b/src/http.rs index 64e2caa..ddcf923 100644 --- a/src/http.rs +++ b/src/http.rs @@ -316,6 +316,9 @@ impl<'a> Call<'a> { _ => Retry::Fail(SourceError::RateLimited), }); } + if waf_challenge(response.headers()) { + return Err(Retry::Fail(SourceError::Blocked)); + } let body = response .body_mut() .with_config() @@ -428,6 +431,15 @@ fn quota_spent(headers: &ureq::http::HeaderMap) -> bool { || headers.contains_key("retry-after") } +/// AWS WAF Bot Control answers with this header and a script for a browser +/// to run, under any status: Harvard Dataverse, HDX and Figshare pages send +/// it with 202 and an empty body (October 2026). +fn waf_challenge(headers: &ureq::http::HeaderMap) -> bool { + headers + .get("x-amzn-waf-action") + .is_some_and(|v| v.as_bytes() == b"challenge") +} + /// Cloudflare and similar bot walls answer 403 with an HTML interstitial. fn looks_like_challenge(body: &str) -> bool { body.contains("Just a moment...") || body.contains("cf-chl") @@ -667,6 +679,26 @@ mod tests { } } + #[test] + fn a_waf_challenge_is_blocked_whatever_its_status() { + for (status, action, blocked) in [ + ("202 Accepted", "challenge", true), + ("200 OK", "challenge", true), + ("200 OK", "allow", false), + ] { + let header = format!("x-amzn-waf-action: {action}"); + let (url, server) = + serve(vec![response(status, &[header.as_str()], b"{}")]); + let outcome = Http::new().get(&url).text(); + assert_eq!( + matches!(outcome, Err(SourceError::Blocked)), + blocked, + "{status} {action}: {outcome:?}" + ); + server.join().unwrap(); + } + } + #[test] fn an_invalid_byte_costs_one_character_not_the_body() { let (url, server) = From 2e1246b76fda0859300dacc66702d3bde2384aa5 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:03:44 +0100 Subject: [PATCH 15/31] doc: OpenML is read from its Elasticsearch index, and re-recorded fixtures keep the arrays a record sums over --- docs/adr/0004-every-source-is-searched.md | 2 +- docs/reference/development.md | 2 +- docs/synthesis/search-methods.md | 2 +- src/sources.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/adr/0004-every-source-is-searched.md b/docs/adr/0004-every-source-is-searched.md index 88b5569..ddb46a4 100644 --- a/docs/adr/0004-every-source-is-searched.md +++ b/docs/adr/0004-every-source-is-searched.md @@ -43,7 +43,7 @@ Every source below is implemented to the same contract (`src/sources.rs`) and se |---|---|---|---|---|---| | `huggingface` | Hugging Face Hub | Hub API | live | `$HF_TOKEN` (optional) | [docs](https://huggingface.co/docs/huggingface_hub/package_reference/hf_api) | | `kaggle` | Kaggle | Kaggle API | live | `$KAGGLE_API_TOKEN` (optional) | [docs](https://www.kaggle.com/docs/api) | -| `openml` | OpenML | OpenML REST, listed | local | | [docs](https://docs.openml.org/ecosystem/Rest/) | +| `openml` | OpenML | OpenML Elasticsearch, listed | local | | [docs](https://docs.openml.org/ecosystem/Rest/) | | `uci` | UCI Machine Learning Repository | list endpoint | local | | [docs](https://github.com/uci-ml-repo/ucimlrepo) | | `roboflow` | Roboflow Universe | Universe API | live | `$ROBOFLOW_API_KEY` (required) | [docs](https://docs.roboflow.com/datasets/universe/universe/universe-search) | | `modelscope` | ModelScope | site API | live | | [docs](https://www.modelscope.cn/docs) | diff --git a/docs/reference/development.md b/docs/reference/development.md index 1a1053c..53f6112 100644 --- a/docs/reference/development.md +++ b/docs/reference/development.md @@ -40,7 +40,7 @@ Every adapter splits its request (`search` or `list`) from a pure `parse`, and e `inspect` reads whole pages, and `tests/fixtures/inspect/` keeps real responses: `zenodo.html` is a record page with its `` and a `` cut down to its `application/ld+json` script, and the other fixtures are the JSON documents Dataverse and Hugging Face serve. The MCP session test in `tests/cli.rs` serves `zenodo.html` through a helper on `127.0.0.1` that acts as the proxy and answers every request with the page, tunnelled through `CONNECT` or not, so `inspect` runs end to end on an `http://` URL without the network. -To re-record a fixture after a source changes, repeat the adapter's request with `xh` and the dataseek User-Agent (`dataseek/ (+https://github.com/lmarkmann/dataseek; mailto:user@dataseek.dev)`), never with a key, trim arrays to a few rows with `jq 'walk(if type=="array" then .[:4] else . end)'`, shorten long descriptions to a real prefix, replace any individual's e-mail address with `contact@example.org`, and then re-derive the expected record by reading the new file. Sources that need a key (FRED, Roboflow) use the example response from their API docs, linked above the test. +To re-record a fixture after a source changes, repeat the adapter's request with `xh` and the dataseek User-Agent (`dataseek/ (+https://github.com/lmarkmann/dataseek; mailto:user@dataseek.dev)`), never with a key, trim arrays to a few rows with `jq 'walk(if type=="array" then .[:4] else . end)'` (except arrays a record's own fields sum over, such as CKAN `resources` and `extras`, which stay whole while the list of results is trimmed), shorten long descriptions to a real prefix, replace any individual's e-mail address with `contact@example.org`, and then re-derive the expected record by reading the new file. Sources that need a key (FRED, Roboflow) use the example response from their API docs, linked above the test. `inspect` reads its file lists from recorded pages in `tests/fixtures/inspect/`, recorded under the same rules. Its `--json` shape is part of `json_shapes_snapshot` in `tests/cli.rs`, read from a page served on a random local port that a snapshot filter replaces with `[LOCAL_ADDR]`. diff --git a/docs/synthesis/search-methods.md b/docs/synthesis/search-methods.md index 952e75b..09a7924 100644 --- a/docs/synthesis/search-methods.md +++ b/docs/synthesis/search-methods.md @@ -51,7 +51,7 @@ These publish a complete list but no search endpoint, so dataseek downloads the | source | list endpoint | entries (2026-10-06) | |---|---|---| -| OpenML | `/api/v1/json/data/list/limit/20000/status/active` (latest version per name) | 5,025 | +| OpenML | `POST /es/data/data/_search`, `status: active`, sorted by `data_id` (latest version per name); the index the openml.org site queries, since the REST list carries no description, licence or date | 6,668 (2026-10-20) | | UCI | `/api/datasets/list` | 689 | | World Bank indicators | `/v2/indicator?per_page=40000` | 29,533 | | SDMX agencies | `/dataflow` as SDMX-ML 2.1 | IMF 222 (101 with a portal page), OECD 1,548, ECB 215, BIS 32, ILO 1,216, UNdata 15, Bundesbank 94 | diff --git a/src/sources.rs b/src/sources.rs index 156c2d6..ee7c029 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -522,7 +522,7 @@ pub static SOURCES: &[Source] = &[ "openml", "OpenML", MachineLearning, - "OpenML REST, listed", + "OpenML Elasticsearch, listed", "https://docs.openml.org/ecosystem/Rest/", openml::list, ), From b28dd75b2d4a7d71e72901f79e45bf1d7a6412e9 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:03:44 +0100 Subject: [PATCH 16/31] doc: the dataseek skill names the bot walls and CMR's landing pages in inspect --- skills/dataseek/references/inspect.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/skills/dataseek/references/inspect.md b/skills/dataseek/references/inspect.md index 6edf258..f841883 100644 --- a/skills/dataseek/references/inspect.md +++ b/skills/dataseek/references/inspect.md @@ -35,12 +35,14 @@ Observed 2026-10-20 on landing pages from an `air quality` search, one per sourc | Outcome | Sources whose result URLs gave it | |---|---| | metadata and files | `zenodo`, `huggingface`, `kaggle`, `datagov`, `data-gov-au`, `dataverse-no`, `aws`, `cessda`, `dbnomics`, `modelscope`, `openaire` | -| `carries no schema.org Dataset markup` | `arcgis`, `b2find`, `cmr`, `dataone`, `earth-engine`, `europa`, `figshare`, `github`, `govdata`, `hdx`, `open-canada`, `opendatasoft`, `openml`, `osf` | -| `sent a challenge page instead of results` | `gbif` | +| `carries no schema.org Dataset markup` | `arcgis`, `b2find`, `dataone`, `earth-engine`, `europa`, `github`, `govdata`, `open-canada`, `opendatasoft`, `openml`, `osf` | +| `sent a challenge page instead of results` | `gbif`, and the AWS bot wall in front of `hdx`, `figshare` and `harvard-dataverse` pages | + +`cmr` results now link the provider's landing page or the DOI rather than NASA's record page, so whether they publish markup depends on that provider. ## When it fails -1. **`carries no schema.org Dataset markup`** with a `doi` on the result: inspect `https://doi.org/` once. The DOI resolves to the publisher's canonical page, which worked for a Zenodo DOI and failed for a Harvard Dataverse DOI on 2026-10-20. +1. **`carries no schema.org Dataset markup`** with a `doi` on the result: inspect `https://doi.org/` once. The DOI resolves to the publisher's canonical page, which worked for a Zenodo DOI on 2026-10-20; a DOI that lands behind a bot wall fails as in step 3. 2. **Still no markup:** say the page publishes no machine-readable metadata, give its URL, and list what the search result itself carried. Read the page with a web fetch tool only if the user wants more. 3. **`cannot fetch`** with `sent a challenge page instead of results`: the site blocks automated requests; give the URL for the user to open. 4. **A file URL or a search page** handed to `inspect` fails the same way as a page with no markup; pass the landing page. From d75a216cb790cb55ed7289a92877e8ac69e5bf55 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:37:53 +0100 Subject: [PATCH 17/31] fix: punctuation after markup stays on its word, "rain, snow" rather than "rain , snow" --- src/record.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/record.rs b/src/record.rs index 4422bd1..d0b5295 100644 --- a/src/record.rs +++ b/src/record.rs @@ -104,9 +104,12 @@ fn already_clean(text: &str) -> bool { && !text.contains(" ") } -/// Tags removed, control characters as spaces, invisible ones dropped. +/// Tags removed, control characters as spaces, invisible ones dropped. A +/// tag becomes a space, except before punctuation that closes up to the +/// word before it, so "rain, snow" reads "rain, snow". fn strip_tags(text: &str, mut push: impl FnMut(char)) { let mut in_tag = false; + let mut after_tag = false; let mut chars = without_controls(text).peekable(); while let Some(c) = chars.next() { match c { @@ -115,19 +118,32 @@ fn strip_tags(text: &str, mut push: impl FnMut(char)) { } '>' if in_tag => { in_tag = false; - push(' '); + after_tag = true; + } + _ if !in_tag && !invisible(c) => { + if after_tag && !closes_up(c) { + push(' '); + } + after_tag = false; + push(c); } - _ if !in_tag && !invisible(c) => push(c), _ => {} } } if in_tag { + if after_tag { + push(' '); + } without_controls(unclosed_tag(text)) .filter(|&c| !invisible(c)) .for_each(push); } } +fn closes_up(c: char) -> bool { + matches!(c, ',' | '.' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '%') +} + fn opens_tag(next: char) -> bool { next.is_alphabetic() || matches!(next, '/' | '!') } @@ -644,6 +660,15 @@ mod tests { assert_eq!(clean("1 > 0, A 0, A Monthly rain, snow. Sites (map)"), + "Monthly rain, snow. Sites ( map)" + ); + assert_eq!(clean("103% of a
b"), "10 3% of a b"); + } + #[test] fn day_keeps_only_the_date_of_iso_stamps() { assert_eq!( @@ -690,7 +715,7 @@ mod tests { assert_eq!( clean(&from_markdown(md)), "Title: Aged brain Dataset contact: J. Whalley one two \ - a b 1 2 sentinel_2_l2a, bold , aged <5" + a b 1 2 sentinel_2_l2a, bold, aged <5" ); } From 8c5e691c0f11d0248353fa8f865503c4f2b75a02 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:22:39 +0100 Subject: [PATCH 18/31] feat: inspect reads a Dataverse dataset through its schema.org export, so Harvard's bot wall no longer stops it --- src/inspect.rs | 105 +++++++++++++++++++++++++++++++++++++++++++++---- tests/cli.rs | 20 ++++++++++ 2 files changed, 117 insertions(+), 8 deletions(-) diff --git a/src/inspect.rs b/src/inspect.rs index 972b02a..7c69d54 100644 --- a/src/inspect.rs +++ b/src/inspect.rs @@ -1,6 +1,11 @@ //! `inspect`: the machine-readable metadata a dataset page publishes about //! itself, and the files it lists. Hugging Face pages carry none in their -//! HTML, so for them the Hub's Croissant endpoint is read instead; every other +//! HTML, so for them the Hub's Croissant endpoint is read instead. A +//! Dataverse dataset page is read through its installation's schema.org +//! export, which answers where the page sits behind a bot wall (Harvard's +//! does, October 2026), and a DOI link is first looked up in the DOI's +//! handle record, so a DOI that lands on such a page is known as one before +//! anything is requested from it. Every other //! page is searched for `application/ld+json` blocks holding a schema.org //! `Dataset` (top level, in an array, or inside `@graph`, whose other nodes //! answer `{"@id": ...}` references; keys may carry a `schema:` prefix, as @@ -19,7 +24,7 @@ use serde_json::Value; use crate::find::human_bytes; use crate::http::{Http, SourceError}; use crate::output::{self, Out}; -use crate::record::{clean, number, scrub_controls, summary, text}; +use crate::record::{clean, doi, number, scrub_controls, summary, text}; use crate::ui; #[derive(Debug, thiserror::Error)] @@ -72,20 +77,26 @@ pub fn run(url: &str, out: &Out) -> Result<()> { }, _ => Error::Fetch { url: url.to_owned(), source: e }, }; + let no_markup = || Error::NoMarkup { url: url.to_owned() }; let progress = ui::spinner(format!("reading {url}")); - let found = if let Some(id) = huggingface_id(url) { + let address = doi_link(url) + .and_then(|doi| landing(&http, &doi)) + .unwrap_or_else(|| url.to_owned()); + let found = if let Some(id) = huggingface_id(&address) { http.get(&format!( "https://huggingface.co/api/datasets/{id}/croissant" )) .json() .map(|dataset| Page { dataset, graph: Vec::new() }) .map_err(fetch_error) + } else if let Some(export) = dataverse_export(&address) { + http.get(&export) + .json() + .map_err(fetch_error) + .and_then(|metadata| Page::find(&metadata).ok_or_else(no_markup)) } else { - http.get(url).text().map_err(fetch_error).and_then(|html| { - json_ld(&html) - .iter() - .find_map(Page::find) - .ok_or_else(|| Error::NoMarkup { url: url.to_owned() }) + http.get(&address).text().map_err(fetch_error).and_then(|html| { + json_ld(&html).iter().find_map(Page::find).ok_or_else(no_markup) }) }; progress.finish_and_clear(); @@ -312,6 +323,43 @@ fn checksum(file: &Value) -> Option { ) } +/// The DOI a `doi.org` link names, when it is one the handle API can be +/// asked about in its path. +fn doi_link(url: &str) -> Option { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://"))?; + let path = rest + .strip_prefix("doi.org/") + .or_else(|| rest.strip_prefix("dx.doi.org/"))?; + doi(path).filter(|d| !d.contains(['?', '#', '%'])) +} + +/// Where a DOI points, from its handle record; `None` when the lookup +/// fails, and the link is then followed as given. +fn landing(http: &Http, doi: &str) -> Option { + let handle = http + .get(&format!("https://doi.org/api/handles/{doi}")) + .query("type", "URL") + .json() + .ok()?; + text(&handle, "/values/0/data/value").filter(|t| t.starts_with("http")) +} + +/// The schema.org export of a Dataverse dataset page, `.../dataset.xhtml` +/// or `.../citation` with a `persistentId`, which the installation's API +/// serves beside the page. +fn dataverse_export(url: &str) -> Option { + let (page, query) = url.split_once('?')?; + let (root, last) = page.rsplit_once('/')?; + if !matches!(last, "dataset.xhtml" | "citation") || !root.contains("://") { + return None; + } + let id = + query.split(['&', '#']).find(|p| p.starts_with("persistentId="))?; + Some(format!("{root}/api/datasets/export?exporter=schema.org&{id}")) +} + fn huggingface_id(url: &str) -> Option { let path = url.split_once("huggingface.co/datasets/")?.1; let id: Vec<&str> = path.split(['/', '?', '#']).take(2).collect(); @@ -603,6 +651,47 @@ mod tests { assert_eq!(huggingface_id("https://huggingface.co/models/x"), None); } + #[test] + fn dataverse_pages_are_read_through_their_export() { + assert_eq!( + dataverse_export( + "https://dataverse.harvard.edu/citation?persistentId=doi:10.7910/DVN/DUWBBU" + ) + .as_deref(), + Some( + "https://dataverse.harvard.edu/api/datasets/export?exporter=schema.org&persistentId=doi:10.7910/DVN/DUWBBU" + ) + ); + assert_eq!( + dataverse_export( + "https://data.example.org/dv/dataset.xhtml?version=2.0&persistentId=hdl:1902/X#files" + ) + .as_deref(), + Some( + "https://data.example.org/dv/api/datasets/export?exporter=schema.org&persistentId=hdl:1902/X" + ) + ); + assert_eq!(dataverse_export("https://x.org/dataset.xhtml?id=4"), None); + assert_eq!( + dataverse_export("https://x.org/records/citation?q=1"), + None + ); + } + + #[test] + fn only_doi_links_are_looked_up_as_handles() { + assert_eq!( + doi_link("https://doi.org/10.7910/DVN/DUWBBU").as_deref(), + Some("10.7910/dvn/duwbbu") + ); + assert_eq!( + doi_link("http://dx.doi.org/10.5281/zenodo.1").as_deref(), + Some("10.5281/zenodo.1") + ); + assert_eq!(doi_link("https://zenodo.org/doi/10.5281/zenodo.1"), None); + assert_eq!(doi_link("https://doi.org/10.1000/a?b"), None); + } + #[test] fn names_flatten_people_and_lists() { let v = json!([{"@type":"Person","name":"Ada"}, "Grace"]); diff --git a/tests/cli.rs b/tests/cli.rs index 27c3702..3961ba2 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1015,6 +1015,26 @@ fn inspect_lists_the_files_a_page_describes() { assert!(text.lines().any(|l| l == line), "{text}"); } +#[test] +fn inspect_reads_a_dataverse_page_through_its_export() { + // The server answers every path with the export's JSON, which carries no + // ld+json script: only a request to the export endpoint can read it. + let export = include_str!("fixtures/inspect/dataverse-schema-org.json"); + let page = format!( + "{}citation?persistentId=doi:10.7910/DVN/X", + serve_page(export) + ); + let out = bin() + .env_remove("HTTPS_PROXY") + .env_remove("HTTP_PROXY") + .args(["inspect", &page, "--json"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(report["files"].as_array().map(Vec::len), Some(2)); +} + #[test] fn inspect_says_when_a_page_lists_no_files() { let out = inspect_page(BARE_PAGE, &["--json"]); From 75c8c814d3d401220a9e8959a0e9adacefba1f3f Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:22:52 +0100 Subject: [PATCH 19/31] feat: every source's licenses read as SPDX ids, CC-BY-4.0 however the source spelled it --- src/lib.rs | 1 + src/license.rs | 531 ++++++++++++++++++++++++++++++++++++++++++ src/sources.rs | 17 ++ src/sources/europa.rs | 48 +--- src/sources/gbif.rs | 38 +-- src/sources/osf.rs | 56 +---- 6 files changed, 565 insertions(+), 126 deletions(-) create mode 100644 src/license.rs diff --git a/src/lib.rs b/src/lib.rs index f88a25e..106e9e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,7 @@ mod fs; mod help; mod http; mod inspect; +mod license; mod listing; mod mcp; mod output; diff --git a/src/license.rs b/src/license.rs new file mode 100644 index 0000000..911ee89 --- /dev/null +++ b/src/license.rs @@ -0,0 +1,531 @@ +//! Licenses as SPDX ids, so one license reads the same from every source +//! and `--license` can match it. Sources spell a license many ways: a +//! Creative Commons deed URL, a CKAN slug (`cc-by`, `odc-odbl`, `uk-ogl`), a +//! dcat-ap.de or EU vocabulary URI, or a name ("Attribution 4.0 +//! International (CC BY 4.0)"); six queries over every source in October +//! 2026 returned 180 spellings, about 30 of them for CC BY 4.0. What is +//! recognized becomes its SPDX id. A Creative Commons license named without +//! a version keeps its family alone (`CC-BY`), and an Open Government +//! Licence named without one is the UK's current version 3.0. Anything else +//! is shown as the source wrote it, and placeholders such as "other" or +//! "notspecified", which say nothing about the terms, are dropped. + +use crate::record::clean; + +/// Slugs that name no license. +const PLACEHOLDERS: &[&str] = &[ + "other", + "unknown", + "none", + "notspecified", + "not-specified", + "unspecified", + "unsupported", + "no-license", + "other-specified-in-description", +]; + +/// Names and slugs of licenses whose SPDX id no rule below derives. +const NAMES: &[(&str, &str)] = &[ + ("mit", "MIT"), + ("mit-license", "MIT"), + ("apache-2.0", "Apache-2.0"), + ("apache-2", "Apache-2.0"), + ("apache2", "Apache-2.0"), + ("apache-license-2.0", "Apache-2.0"), + ("apache-license-version-2.0", "Apache-2.0"), + ("bsd-2-clause", "BSD-2-Clause"), + ("bsd-2-clause-simplified-license", "BSD-2-Clause"), + ("bsd-3-clause", "BSD-3-Clause"), + ("bsd-3-clause-new-revised-license", "BSD-3-Clause"), + ("mpl-2.0", "MPL-2.0"), + ("mozilla-public-license-2.0", "MPL-2.0"), + ("epl-1.0", "EPL-1.0"), + ("eclipse-public-license-1.0", "EPL-1.0"), + ("epl-2.0", "EPL-2.0"), + ("eclipse-public-license-2.0", "EPL-2.0"), + ("afl-3.0", "AFL-3.0"), + ("academic-free-license-afl-3.0", "AFL-3.0"), + ("artistic-2.0", "Artistic-2.0"), + ("artistic-license-2.0", "Artistic-2.0"), + ("unlicense", "Unlicense"), + ("the-unlicense", "Unlicense"), + ("isc", "ISC"), + ("cdla-permissive-1.0", "CDLA-Permissive-1.0"), + ( + "community-data-license-agreement-permissive-version-1.0", + "CDLA-Permissive-1.0", + ), + ("cdla-permissive-2.0", "CDLA-Permissive-2.0"), + ( + "community-data-license-agreement-permissive-version-2.0", + "CDLA-Permissive-2.0", + ), + ("cdla-sharing-1.0", "CDLA-Sharing-1.0"), + ( + "community-data-license-agreement-sharing-version-1.0", + "CDLA-Sharing-1.0", + ), + ("odbl", "ODbL-1.0"), + ("odbl-1.0", "ODbL-1.0"), + ("odc-odbl", "ODbL-1.0"), + ("open-database-license", "ODbL-1.0"), + ("open-database-license-odbl", "ODbL-1.0"), + ("open-database-license-odc-odbl", "ODbL-1.0"), + ("odc-by", "ODC-By-1.0"), + ("odc-by-1.0", "ODC-By-1.0"), + ("odby", "ODC-By-1.0"), + ("open-data-commons-attribution-license", "ODC-By-1.0"), + ("pddl", "PDDL-1.0"), + ("pddl-1.0", "PDDL-1.0"), + ("odc-pddl", "PDDL-1.0"), + ("odcpddl", "PDDL-1.0"), + ("open-data-commons-public-domain-dedication-and-license", "PDDL-1.0"), + ("odc-public-domain-dedication-and-licence-pddl", "PDDL-1.0"), + ("dl-de-by-2.0", "DL-DE-BY-2.0"), + ("dl-by-de-2.0", "DL-DE-BY-2.0"), + ("dl-de-zero-2.0", "DL-DE-ZERO-2.0"), + ("dl-zero-de-2.0", "DL-DE-ZERO-2.0"), + ("etalab-2.0", "etalab-2.0"), + ("licence-ouverte-2.0", "etalab-2.0"), +]; + +/// The license as shown and matched: its SPDX id when recognized, the +/// source's own text otherwise, `None` for a placeholder. +pub fn normalized(raw: &str) -> Option { + let shown = clean(raw); + let shown = shown.trim_matches(['[', ']', ' ']); + if shown.is_empty() || PLACEHOLDERS.contains(&slug(shown).as_str()) { + return None; + } + Some(spdx(shown).unwrap_or_else(|| shown.to_owned())) +} + +/// The SPDX id a license name, slug or URI stands for. +pub fn spdx(raw: &str) -> Option { + match raw.trim().split_once("://") { + Some((_, address)) => from_uri(address), + None => from_name(&slug(raw)), + } +} + +/// An id without its version: `CC-BY-4.0` is `CC-BY`, `CC0-1.0` is `CC0`, +/// `GPL-3.0-only` is `GPL`. An id with no version is its own family. +pub fn family(id: &str) -> &str { + id.match_indices('-') + .find(|(i, _)| { + id.get(i.saturating_add(1)..).is_some_and(|rest| { + rest.starts_with(|c: char| c.is_ascii_digit()) + }) + }) + .and_then(|(i, _)| id.get(..i)) + .unwrap_or(id) +} + +/// Whether a license is what `--license` asked for: the same id, or the +/// family it belongs to, ignoring case. +pub fn matches(license: &str, wanted: &str) -> bool { + license.eq_ignore_ascii_case(wanted) + || family(license).eq_ignore_ascii_case(wanted) +} + +/// Lowercase words joined by `-`, every other character a separator, and +/// an `_` between digits a dot, as the EU vocabulary writes `CC_BY_4_0`. +fn slug(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut slug = String::with_capacity(text.len()); + for (i, &c) in chars.iter().enumerate() { + let digit_at = |j: Option| { + j.and_then(|j| chars.get(j)).is_some_and(char::is_ascii_digit) + }; + let between_digits = c == '_' + && digit_at(i.checked_sub(1)) + && digit_at(i.checked_add(1)); + if c.is_alphanumeric() || between_digits || c == '.' { + slug.push(if between_digits { '.' } else { c }); + } else if !slug.ends_with('-') { + slug.push('-'); + } + } + slug.to_lowercase().trim_matches(['-', '.']).to_owned() +} + +fn from_uri(address: &str) -> Option { + let address = address.strip_prefix("www.").unwrap_or(address); + let (host, path) = address.split_once('/')?; + let path = path.trim_end_matches('/'); + match host { + "spdx.org" => { + let id = path.strip_prefix("licenses/")?; + let id = id.trim_end_matches(".html").trim_end_matches(".json"); + (!id.is_empty()) + .then(|| from_name(&slug(id)).unwrap_or_else(|| id.to_owned())) + } + "creativecommons.org" => creative_commons_deed(path), + "opendatacommons.org" | "opendefinition.org" => { + let name = path.strip_prefix("licenses/")?.split('/').next()?; + from_name(if name == "by" { "odc-by" } else { name }) + } + "nationalarchives.gov.uk" => { + let version = + path.strip_prefix("doc/open-government-licence/version/")?; + matches!(version, "1" | "2" | "3") + .then(|| format!("OGL-UK-{version}.0")) + } + "reference.data.gov.uk" => (path == "id/open-government-licence") + .then(|| "OGL-UK-3.0".to_owned()), + "dcat-ap.de" => from_name(&slug(path.strip_prefix("def/licenses/")?)), + "publications.europa.eu" => { + from_name(&slug(path.strip_prefix("resource/authority/licence/")?)) + } + "etalab.gouv.fr" => path + .starts_with("licence-ouverte") + .then(|| "etalab-2.0".to_owned()), + _ => None, + } +} + +/// A Creative Commons deed or legal code: `licenses/by-sa/4.0/`, +/// `licenses/by/3.0/at/deed.de` (a national port, `CC-BY-3.0-AT`) or +/// `publicdomain/zero/1.0/legalcode`. +fn creative_commons_deed(path: &str) -> Option { + let mut parts = path.split('/'); + let (kind, code, version) = (parts.next()?, parts.next()?, parts.next()?); + let version = cc_version(version)?; + let port = parts.next().and_then(cc_port); + match (kind, code) { + ("publicdomain", "zero") => Some(format!("CC0-{version}")), + ( + "licenses", + "by" | "by-sa" | "by-nd" | "by-nc" | "by-nc-sa" | "by-nc-nd", + ) => { + let id = format!("CC-{}-{version}", code.to_ascii_uppercase()); + Some(match port { + Some(port) => format!("{id}-{port}"), + None => id, + }) + } + _ => None, + } +} + +fn from_name(slug: &str) -> Option { + if let Some((_, id)) = NAMES.iter().find(|(name, _)| *name == slug) { + return Some((*id).to_owned()); + } + let words: Vec<&str> = slug.split('-').collect(); + creative_commons(&words).or_else(|| gnu(&words)).or_else(|| ogl(&words)) +} + +/// A Creative Commons license from the words of its name or slug, in SPDX +/// order (`CC-BY-NC-SA`), with its version when one is named and a +/// national port after it. +fn creative_commons(words: &[&str]) -> Option { + let has = |word: &str| words.contains(&word); + let named = has("cc") + || has("cc0") + || (has("creative") && has("commons")) + || words.first() == Some(&"attribution"); + if !named { + return None; + } + if has("cc0") + || has("zero") + || words == ["cc", "0"] + || (has("public") && has("domain") && has("dedication")) + { + return Some("CC0-1.0".to_owned()); + } + let nc = + has("nc") || has("noncommercial") || (has("non") && has("commercial")); + let nd = has("nd") + || has("noderivatives") + || has("noderivs") + || (has("no") && has("derivatives")); + let sa = has("sa") || has("sharealike") || (has("share") && has("alike")); + if !(has("by") || has("attribution") || nc || nd || sa) { + return None; + } + let mut id = String::from("CC-BY"); + if nc { + id.push_str("-NC"); + } + if nd { + id.push_str("-ND"); + } else if sa { + id.push_str("-SA"); + } + if let Some(version) = words.iter().find_map(|w| cc_version(w)) { + id = format!("{id}-{version}"); + if let Some(port) = words.iter().find_map(|w| cc_port(w)) { + id = format!("{id}-{port}"); + } + } + Some(id) +} + +fn cc_version(word: &str) -> Option<&'static str> { + match word { + "1" | "1.0" => Some("1.0"), + "2" | "2.0" => Some("2.0"), + "2.5" => Some("2.5"), + "3" | "3.0" => Some("3.0"), + "4" | "4.0" => Some("4.0"), + _ => None, + } +} + +fn cc_port(word: &str) -> Option<&'static str> { + match word { + "at" | "austria" => Some("AT"), + "au" | "australia" => Some("AU"), + "de" | "germany" => Some("DE"), + "nl" | "netherlands" => Some("NL"), + "igo" => Some("IGO"), + _ => None, + } +} + +/// The GNU licenses, `-only` unless the name says "or later". +fn gnu(words: &[&str]) -> Option { + let has = |word: &str| words.contains(&word); + let kind = if has("agpl") || has("affero") { + "AGPL" + } else if has("lgpl") || has("lesser") { + "LGPL" + } else if has("gpl") || (has("gnu") && has("general") && has("public")) { + "GPL" + } else { + return None; + }; + let version = words.iter().find_map(|w| match *w { + "2" | "2.0" => Some("2.0"), + "2.1" => Some("2.1"), + "3" | "3.0" => Some("3.0"), + _ => None, + })?; + let scope = if has("later") { "or-later" } else { "only" }; + Some(format!("{kind}-{version}-{scope}")) +} + +/// The UK's and Canada's Open Government Licences. A provincial or +/// territorial one ("Nova Scotia Open Government Licence") has no SPDX id, +/// so a word outside the licence's own name rules the match out. +fn ogl(words: &[&str]) -> Option { + let has = |word: &str| words.contains(&word); + let licence = has("licence") || has("license"); + if !(has("ogl") || (has("open") && has("government") && licence)) { + return None; + } + let version = |w: &str| match w.strip_prefix('v').unwrap_or(w) { + "1" | "1.0" => Some('1'), + "2" | "2.0" => Some('2'), + "3" | "3.0" => Some('3'), + _ => None, + }; + let own = [ + "open", + "government", + "licence", + "license", + "ogl", + "uk", + "united", + "kingdom", + "the", + "v", + "version", + "canada", + ]; + if words.iter().any(|w| !own.contains(w) && version(w).is_none()) { + return None; + } + let named = words.iter().find_map(|w| version(w)); + if has("canada") { + return Some("OGL-Canada-2.0".to_owned()); + } + Some(format!("OGL-UK-{}.0", named.unwrap_or('3'))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Spellings from six searches over every source, October 2026. + #[test] + fn spellings_sources_send_become_one_id() { + for (raw, id) in [ + ("cc-by-4.0", "CC-BY-4.0"), + ("cc-by-4", "CC-BY-4.0"), + ("CC BY 3", "CC-BY-3.0"), + ("Creative Commons Attribution 4.0 International", "CC-BY-4.0"), + ("Attribution 4.0 International (CC BY 4.0)", "CC-BY-4.0"), + ( + "Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)", + "CC-BY-NC-4.0", + ), + ( + "CC-By Attribution-NonCommercial-NoDerivatives 4.0 International", + "CC-BY-NC-ND-4.0", + ), + ( + "Creative Commons Attribution Share-Alike (CC BY-SA)", + "CC-BY-SA", + ), + ("Creative Commons Attribution International (CC BY)", "CC-BY"), + ("CC BY NC ND", "CC-BY-NC-ND"), + ("Creative Commons Attribution 2.5 Australia", "CC-BY-2.5-AU"), + ("CC BY 3.0 IGO", "CC-BY-3.0-IGO"), + ( + "Creative Commons Attribution 4.0 International (Embargo: 2020-07-31)", + "CC-BY-4.0", + ), + ("CC0: Public Domain", "CC0-1.0"), + ("cc-zero", "CC0-1.0"), + ("CC 0", "CC0-1.0"), + ("[CC0 1.0]", "CC0-1.0"), + ("Public Domain / No restrictions (CC0)", "CC0-1.0"), + ( + "Creative Commons 1.0 Universal (Public Domain Dedication)", + "CC0-1.0", + ), + ("Open Database License (ODC-ODbL)", "ODbL-1.0"), + ("odc-odbl", "ODbL-1.0"), + ("Open Data Commons Attribution License", "ODC-By-1.0"), + ("ODC Public Domain Dedication and Licence (PDDL)", "PDDL-1.0"), + ("UK Open Government Licence (OGL)", "OGL-UK-3.0"), + ("uk-ogl", "OGL-UK-3.0"), + ("Open Government Licence V 3.0", "OGL-UK-3.0"), + ("Open Government Licence v2", "OGL-UK-2.0"), + ("Open Government Licence - Canada", "OGL-Canada-2.0"), + ("ogl-canada-2.0", "OGL-Canada-2.0"), + ("etalab 2.0", "etalab-2.0"), + ("Apache License 2.0", "Apache-2.0"), + ("Apache 2.0", "Apache-2.0"), + ("BSD 2-Clause \"Simplified\" License", "BSD-2-Clause"), + ("GNU General Public License (GPL) 3.0", "GPL-3.0-only"), + ("GPL 2", "GPL-2.0-only"), + ("agpl-3.0", "AGPL-3.0-only"), + ("GNU Lesser General Public License (LGPL) 2.1", "LGPL-2.1-only"), + ( + "Community Data License Agreement - Sharing - Version 1.0", + "CDLA-Sharing-1.0", + ), + ("mit", "MIT"), + ] { + assert_eq!(normalized(raw).as_deref(), Some(id), "{raw}"); + } + } + + #[test] + fn license_uris_become_ids() { + for (uri, id) in [ + ("https://creativecommons.org/publicdomain/zero/1.0/", "CC0-1.0"), + ( + "http://creativecommons.org/licenses/by-nc/4.0/legalcode", + "CC-BY-NC-4.0", + ), + ( + "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en", + "CC-BY-NC-SA-4.0", + ), + ( + "https://creativecommons.org/licenses/by/3.0/at/deed.de", + "CC-BY-3.0-AT", + ), + ("https://spdx.org/licenses/etalab-2.0.html", "etalab-2.0"), + ("http://spdx.org/licenses/CC-BY-4.0", "CC-BY-4.0"), + ("https://opendatacommons.org/licenses/odbl/summary", "ODbL-1.0"), + ("https://opendatacommons.org/licenses/pddl/summary", "PDDL-1.0"), + ("http://opendefinition.org/licenses/odc-odbl/", "ODbL-1.0"), + ("http://www.opendefinition.org/licenses/cc-by", "CC-BY"), + ( + "http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/", + "OGL-UK-3.0", + ), + ( + "http://reference.data.gov.uk/id/open-government-licence", + "OGL-UK-3.0", + ), + ("http://dcat-ap.de/def/licenses/cc-by/4.0", "CC-BY-4.0"), + ("http://dcat-ap.de/def/licenses/cc-by-de/3.0", "CC-BY-3.0-DE"), + ("http://dcat-ap.de/def/licenses/dl-by-de/2.0", "DL-DE-BY-2.0"), + ( + "http://dcat-ap.de/def/licenses/dl-zero-de/2.0", + "DL-DE-ZERO-2.0", + ), + ("http://dcat-ap.de/def/licenses/odcpddl", "PDDL-1.0"), + ( + "http://publications.europa.eu/resource/authority/licence/CC_BY_2_5", + "CC-BY-2.5", + ), + ( + "https://www.etalab.gouv.fr/licence-ouverte-open-licence", + "etalab-2.0", + ), + ] { + assert_eq!(spdx(uri).as_deref(), Some(id), "{uri}"); + } + } + + #[test] + fn what_is_not_recognized_is_kept_and_placeholders_are_dropped() { + for kept in [ + "Public Domain", + "Nova Scotia Open Government Licence", + "Open Government Licence - British Columbia", + "Database: Open Database, Contents: Database Contents", + "http://creativecommons.org/publicdomain/mark/1.0/deed.nl", + "http://dcat-ap.de/def/licenses/other-closed", + "https://www.nist.gov/open/license", + "Creative Commons", + "other-open", + ] { + assert_eq!(normalized(kept).as_deref(), Some(kept), "{kept}"); + } + for placeholder in [ + "other", + "Other", + "unknown", + "notspecified", + "unspecified", + "No license", + "Other (specified in description)", + " ", + ] { + assert_eq!(normalized(placeholder), None, "{placeholder}"); + } + } + + #[test] + fn an_id_normalizes_to_itself() { + let ids = NAMES.iter().map(|(_, id)| *id).chain([ + "CC-BY-4.0", + "CC-BY-NC-SA-3.0", + "CC-BY-3.0-AU", + "CC-BY", + "CC0-1.0", + "GPL-3.0-only", + "LGPL-2.1-or-later", + "OGL-UK-3.0", + "OGL-Canada-2.0", + ]); + for id in ids { + assert_eq!(normalized(id).as_deref(), Some(id), "{id}"); + } + } + + #[test] + fn a_family_matches_every_version_of_it_and_nothing_else() { + assert_eq!(family("CC-BY-4.0"), "CC-BY"); + assert_eq!(family("CC-BY-3.0-AU"), "CC-BY"); + assert_eq!(family("CC0-1.0"), "CC0"); + assert_eq!(family("GPL-3.0-only"), "GPL"); + assert_eq!(family("MIT"), "MIT"); + assert!(matches("CC-BY-4.0", "cc-by")); + assert!(matches("CC-BY-4.0", "CC-BY-4.0")); + assert!(!matches("CC-BY-SA-4.0", "CC-BY")); + assert!(!matches("CC-BY-3.0", "CC-BY-4.0")); + assert!(matches("Public Domain", "public domain")); + } +} diff --git a/src/sources.rs b/src/sources.rs index ee7c029..6aaa639 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -76,6 +76,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use crate::cache::{CATALOG_TTL, Cache, Freshness, Kind}; use crate::credentials::{Credentials, Key}; use crate::http::{Http, SourceError}; +use crate::license; use crate::record::Dataset; pub type Live = fn(&Ctx<'_>, &str, usize) -> Result, SourceError>; @@ -206,11 +207,27 @@ impl Source { } } + /// The source's answer, each record's license as [`license::normalized`] + /// gives it, so every source spells one license alike. pub fn search( &self, ctx: &Ctx<'_>, query: &str, limit: usize, + ) -> Result { + let mut answer = self.ask(ctx, query, limit)?; + for dataset in &mut answer.datasets { + dataset.license = + dataset.license.as_deref().and_then(license::normalized); + } + Ok(answer) + } + + fn ask( + &self, + ctx: &Ctx<'_>, + query: &str, + limit: usize, ) -> Result { let fresh = match &self.adapter { Adapter::Live(run) => run(ctx, query, limit), diff --git a/src/sources/europa.rs b/src/sources/europa.rs index 22ae08c..bbfece1 100644 --- a/src/sources/europa.rs +++ b/src/sources/europa.rs @@ -34,6 +34,7 @@ use serde_json::Value; use super::Ctx; use crate::http::SourceError; +use crate::license::spdx; use crate::record::{Dataset, day, doi, items, localized, number, text}; const INCLUDES: &str = "id,title,description,publisher,catalog.id,\ @@ -140,37 +141,6 @@ fn license(distribution: &Value) -> Option { .or(id) } -/// The SPDX id a license URI names: the id of an spdx.org URI, or the -/// license and version of an unported Creative Commons deed or legal code. -/// A national port such as `by/3.0/at` has no SPDX id of this form. -fn spdx(uri: &str) -> Option { - let path = uri.split_once("://")?.1; - let path = path.strip_prefix("www.").unwrap_or(path); - if let Some(id) = path.strip_prefix("spdx.org/licenses/") { - let id = id.trim_end_matches('/').trim_end_matches(".html"); - return (!id.is_empty()).then(|| id.to_owned()); - } - let mut parts = path.strip_prefix("creativecommons.org/")?.split('/'); - let (kind, code, version) = (parts.next()?, parts.next()?, parts.next()?); - let rest = parts.next().unwrap_or_default(); - let unported = rest.is_empty() - || rest.starts_with("legalcode") - || rest.starts_with("deed"); - let numbered = version.starts_with(|c: char| c.is_ascii_digit()) - && version.chars().all(|c| c.is_ascii_digit() || c == '.'); - if !unported || !numbered { - return None; - } - match (kind, code) { - ("publicdomain", "zero") => Some(format!("CC0-{version}")), - ( - "licenses", - "by" | "by-sa" | "by-nd" | "by-nc" | "by-nc-sa" | "by-nc-nd", - ) => Some(format!("CC-{}-{version}", code.to_ascii_uppercase())), - _ => None, - } -} - fn doi_of(row: &Value) -> Option { let links = ["/landing_page", "/page"] .into_iter() @@ -246,7 +216,7 @@ mod tests { .map(|h| h.license) .collect::>() }; - let ogl = "http://reference.data.gov.uk/id/open-government-licence"; + let ogl = "OGL-UK-3.0"; let swiss = "http://dcat-ap.ch/vocabulary/licenses/terms_open"; assert_eq!( licenses("europa.json"), @@ -273,20 +243,6 @@ mod tests { ); } - #[test] - fn a_national_creative_commons_port_keeps_its_uri() { - assert_eq!( - spdx("http://creativecommons.org/licenses/by/4.0/deed.nl") - .as_deref(), - Some("CC-BY-4.0") - ); - assert_eq!( - spdx("https://creativecommons.org/licenses/by/3.0/at/deed.de"), - None - ); - assert_eq!(spdx("http://dcat-ap.de/def/licenses/dl-by-de/2.0"), None); - } - #[test] fn sizes_add_up_and_data_gov_it_placeholders_are_dropped() { let sizes = |name| { diff --git a/src/sources/gbif.rs b/src/sources/gbif.rs index 8c92bcc..bbb5d64 100644 --- a/src/sources/gbif.rs +++ b/src/sources/gbif.rs @@ -48,26 +48,11 @@ fn record(row: &Value) -> Option { .describe(text(row, "/description")) .doi_from(text(row, "/doi")); dataset.publisher = text(row, "/publishingOrganizationTitle"); - dataset.license = text(row, "/license").and_then(|raw| spdx(&raw)); + dataset.license = text(row, "/license"); dataset.updated = day(text(row, "/modified")); dataset.valid() } -fn spdx(license: &str) -> Option { - let id = match license.to_ascii_lowercase().as_str() { - "http://creativecommons.org/publicdomain/zero/1.0/legalcode" => { - "CC0-1.0" - } - "http://creativecommons.org/licenses/by/4.0/legalcode" => "CC-BY-4.0", - "http://creativecommons.org/licenses/by-nc/4.0/legalcode" => { - "CC-BY-NC-4.0" - } - "unspecified" | "unsupported" => return None, - _ => license, - }; - Some(id.to_owned()) -} - #[cfg(test)] mod tests { use super::*; @@ -97,7 +82,7 @@ mod tests { "The International Plant Names Index Collaborators".into() ), doi: Some("10.15468/uhllmw".into()), - license: None, + license: Some("unspecified".into()), updated: Some("2019-11-11".into()), size_bytes: None, popularity: None, @@ -107,20 +92,21 @@ mod tests { } #[test] - fn licenses_become_spdx_ids_and_placeholders_vanish() { + fn licenses_arrive_as_urls_or_placeholder_words() { let hits = parse(&fixture::json("gbif.json"), 10).unwrap(); let licenses: Vec<_> = hits.iter().map(|h| h.license.as_deref()).collect(); + let by = "http://creativecommons.org/licenses/by/4.0/legalcode"; assert_eq!( licenses, - [None, Some("CC-BY-4.0"), Some("CC-BY-4.0"), Some("CC0-1.0")] - ); - assert_eq!( - spdx("http://creativecommons.org/licenses/by-nc/4.0/legalcode") - .as_deref(), - Some("CC-BY-NC-4.0") + [ + Some("unspecified"), + Some(by), + Some(by), + Some( + "http://creativecommons.org/publicdomain/zero/1.0/legalcode" + ), + ] ); - assert_eq!(spdx("unsupported"), None); - assert_eq!(spdx("custom terms").as_deref(), Some("custom terms")); } } diff --git a/src/sources/osf.rs b/src/sources/osf.rs index e8469a2..930b598 100644 --- a/src/sources/osf.rs +++ b/src/sources/osf.rs @@ -68,44 +68,12 @@ fn record(card: &Value) -> Option { .find(|id| id.contains("doi.org/")), ); dataset.publisher = text(card, "/publisher/0/name/0/@value"); - dataset.license = - text(card, "/rights/0/name/0/@value").and_then(|name| spdx(&name)); + dataset.license = text(card, "/rights/0/name/0/@value"); dataset.updated = day(text(card, "/dateModified/0/@value")); dataset.size_bytes = number(card, "/storageByteCount/0/@value"); dataset.valid() } -fn spdx(name: &str) -> Option { - let id = match name.to_ascii_lowercase().as_str() { - "cc0 1.0 universal" => "CC0-1.0", - "cc-by attribution 4.0 international" => "CC-BY-4.0", - "cc-by attribution-no derivatives 4.0 international" => "CC-BY-ND-4.0", - "cc-by attribution-noncommercial 4.0 international" => "CC-BY-NC-4.0", - "cc-by attribution-noncommercial-noderivatives 4.0 international" => { - "CC-BY-NC-ND-4.0" - } - "cc-by attribution-noncommercial-sharealike 4.0 international" => { - "CC-BY-NC-SA-4.0" - } - "cc-by attribution-sharealike 4.0 international" => "CC-BY-SA-4.0", - "academic free license (afl) 3.0" => "AFL-3.0", - "apache license 2.0" => "Apache-2.0", - "artistic license 2.0" => "Artistic-2.0", - "bsd 2-clause \"simplified\" license" => "BSD-2-Clause", - "bsd 3-clause \"new\"/\"revised\" license" => "BSD-3-Clause", - "eclipse public license 1.0" => "EPL-1.0", - "gnu general public license (gpl) 2.0" => "GPL-2.0-only", - "gnu general public license (gpl) 3.0" => "GPL-3.0-only", - "gnu lesser general public license (lgpl) 2.1" => "LGPL-2.1-only", - "gnu lesser general public license (lgpl) 3.0" => "LGPL-3.0-only", - "mit license" => "MIT", - "mozilla public license 2.0" => "MPL-2.0", - "no license" | "other" => return None, - _ => name, - }; - Some(id.to_owned()) -} - #[cfg(test)] mod tests { use super::*; @@ -126,7 +94,7 @@ mod tests { description: None, publisher: Some("OSF".into()), doi: None, - license: Some("CC-BY-4.0".into()), + license: Some("CC-By Attribution 4.0 International".into()), updated: Some("2026-06-23".into()), size_bytes: Some(142_773), popularity: None, @@ -158,24 +126,4 @@ mod tests { let urls: Vec<_> = hits.iter().map(|h| h.url.as_str()).collect(); assert_eq!(urls, ["https://osf.io/kzt9d", "https://osf.io/zh3w9"]); } - - #[test] - fn license_names_become_spdx_ids_and_placeholders_vanish() { - assert_eq!( - spdx("CC-By Attribution-NonCommercial-NoDerivatives 4.0 International") - .as_deref(), - Some("CC-BY-NC-ND-4.0") - ); - assert_eq!( - spdx("BSD 2-Clause \"Simplified\" License").as_deref(), - Some("BSD-2-Clause") - ); - assert_eq!( - spdx("GNU General Public License (GPL) 3.0").as_deref(), - Some("GPL-3.0-only") - ); - assert_eq!(spdx("No license"), None); - assert_eq!(spdx("Other"), None); - assert_eq!(spdx("A new one").as_deref(), Some("A new one")); - } } From 7bd8adaf9380ca8ce9af7f91c2adf2be7217e832 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:22:52 +0100 Subject: [PATCH 20/31] feat: search --license, --updated-since and --min-sources filter the merged list, and ask each source for 30 when they do --- src/bench.rs | 6 +- src/cli.rs | 39 +++- src/filter.rs | 179 ++++++++++++++++++ src/find.rs | 80 ++++++-- src/help.rs | 1 + src/lib.rs | 3 + src/mcp/tools.rs | 22 +++ tests/cli.rs | 43 +++++ .../snapshots/cli__json_shapes_snapshot.snap | 1 + 9 files changed, 354 insertions(+), 20 deletions(-) create mode 100644 src/filter.rs diff --git a/src/bench.rs b/src/bench.rs index 8db872f..9a7a4e7 100644 --- a/src/bench.rs +++ b/src/bench.rs @@ -15,7 +15,7 @@ use std::time::Duration; use anyhow::Result; use serde::Serialize; -use crate::cli::Selection; +use crate::cli::{PER_SOURCE_DEFAULT, Selection}; use crate::dedup::merge; use crate::output::Out; use crate::search::{Plan, run as search}; @@ -86,7 +86,9 @@ pub fn run( let plan = Arc::new(Plan { query: query.clone(), sources: sources.clone(), - per_source: usize::from(selection.per_source), + per_source: usize::from( + selection.per_source.unwrap_or(PER_SOURCE_DEFAULT), + ), forced: true, }); let outcomes = search(&services, true, &plan, &progress, None); diff --git a/src/cli.rs b/src/cli.rs index e2c49cc..3c42a88 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -172,15 +172,45 @@ pub struct Selection { )] pub categories: Vec, - /// How many results to ask each source for (1-100). + /// How many results to ask each source for (1-100; 10, or 30 when + /// search filters). #[arg( long, value_name = "N", - default_value_t = 10, value_parser = clap::value_parser!(u16).range(PER_SOURCE), env = "DATASEEK_PER_SOURCE" )] - pub per_source: u16, + pub per_source: Option, +} + +/// How many results each source is asked for when nothing says otherwise. +pub const PER_SOURCE_DEFAULT: u16 = 10; +/// The same when `search` filters, so the filters have more to keep. +pub const PER_SOURCE_FILTERED: u16 = 30; +/// The values `--min-sources` accepts. +pub const MIN_SOURCES: RangeFrom = 1..; + +/// What `search` keeps of the merged list. A dataset that does not state a +/// field never passes a filter on that field. +#[derive(Args, Clone, Debug, Default)] +pub struct Filters { + /// Only datasets under these licenses, comma-separated: SPDX ids such + /// as CC-BY-4.0, or a family such as cc-by for every version of it. + #[arg(long, value_name = "IDS", value_delimiter = ',')] + pub license: Vec, + + /// Only datasets updated on or after this day (YYYY, YYYY-MM or + /// YYYY-MM-DD). + #[arg(long, value_name = "DATE", value_parser = crate::filter::day)] + pub updated_since: Option, + + /// Only datasets that at least this many sources found. + #[arg( + long, + value_name = "N", + value_parser = clap::value_parser!(u16).range(MIN_SOURCES) + )] + pub min_sources: Option, } fn source_ids() -> PossibleValuesParser { @@ -259,6 +289,9 @@ pub enum Command { #[command(flatten)] selection: Selection, + #[command(flatten)] + filters: Filters, + /// How many merged results to print. #[arg( short = 'n', diff --git a/src/filter.rs b/src/filter.rs new file mode 100644 index 0000000..eac9a4d --- /dev/null +++ b/src/filter.rs @@ -0,0 +1,179 @@ +//! The filters `search` applies to the merged list (ADR 0020). They run on +//! merged hits, so a field any one of a dataset's sources stated counts, +//! and they hold alike for every source whatever its own API can filter. +//! A dataset that does not state a field never passes a filter on it: a +//! license filter keeps only datasets that name a matching license. + +use crate::cli::Filters; +use crate::dedup::Hit; +use crate::license; + +/// The filters with their values normalized as the records' are, so a +/// license asked for as `cc by 4.0` matches one recorded as `CC-BY-4.0`. +#[derive(Debug, Default)] +pub struct Wanted { + pub licenses: Vec, + /// A full ISO day. + pub since: Option, + pub min_sources: usize, +} + +impl Wanted { + pub fn new(filters: &Filters) -> Self { + Self { + licenses: filters + .license + .iter() + .filter_map(|l| license::normalized(l)) + .collect(), + since: filters.updated_since.clone(), + min_sources: filters.min_sources.map_or(0, usize::from), + } + } + + /// Whether any filter is set. + pub fn any(&self) -> bool { + !self.licenses.is_empty() + || self.since.is_some() + || self.min_sources > 1 + } + + pub fn admits(&self, hit: &Hit) -> bool { + let d = &hit.dataset; + let licensed = self.licenses.is_empty() + || d.license.as_deref().is_some_and(|l| { + self.licenses.iter().any(|w| license::matches(l, w)) + }); + let recent = self.since.as_deref().is_none_or(|since| { + d.updated.as_deref().is_some_and(|day| on_or_after(day, since)) + }); + licensed && recent && hit.sources.len() >= self.min_sources + } +} + +/// What [`day`] accepts, as a JSON Schema `pattern`. +pub const DAY_PATTERN: &str = r"^[0-9]{4}(-[0-9]{2}(-[0-9]{2})?)?$"; + +/// `--updated-since` as a full day: `2024` is `2024-01-01`, `2024-07` is +/// `2024-07-01`. +pub fn day(raw: &str) -> Result { + let day = iso_prefix(raw.trim()) + .filter(|prefix| prefix.len() == raw.trim().len()) + .ok_or_else(|| { + format!("`{raw}` is not a day; write YYYY, YYYY-MM or YYYY-MM-DD") + })?; + Ok(match day.len() { + 4 => format!("{day}-01-01"), + 7 => format!("{day}-01"), + _ => day.to_owned(), + }) +} + +/// Whether a recorded date is on or after `since`, a full day, compared to +/// the precision the record gives: a dataset dated only `2024` counts as +/// updated after `2024-06-01`, since it may well have been. +fn on_or_after(recorded: &str, since: &str) -> bool { + iso_prefix(recorded).is_some_and(|date| { + since.get(..date.len()).is_some_and(|wanted| date >= wanted) + }) +} + +/// The leading `YYYY`, `YYYY-MM` or `YYYY-MM-DD` of a date, month and day +/// in range. +fn iso_prefix(text: &str) -> Option<&str> { + let digits = |range: std::ops::Range| { + text.get(range).filter(|s| s.bytes().all(|b| b.is_ascii_digit())) + }; + let in_range = |range, low, high| { + digits(range) + .and_then(|s| s.parse::().ok()) + .is_some_and(|n| (low..=high).contains(&n)) + }; + digits(0..4)?; + let dash = |at: usize| text.get(at..at.saturating_add(1)) == Some("-"); + let length = if dash(4) && in_range(5..7, 1, 12) { + if dash(7) && in_range(8..10, 1, 31) { 10 } else { 7 } + } else { + 4 + }; + text.get(..length) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::record::Dataset; + + fn hit( + license: Option<&str>, + updated: Option<&str>, + sources: usize, + ) -> Hit { + let mut dataset = Dataset::new("Rain", "https://x.org/rain"); + dataset.license = license.map(String::from); + dataset.updated = updated.map(String::from); + Hit { + dataset, + sources: ["zenodo", "datacite", "openaire"] + .into_iter() + .take(sources) + .collect(), + #[cfg(feature = "internals")] + ranks: vec![0; sources], + score: 1.0, + } + } + + fn wanted(license: &[&str], since: Option<&str>, min: u16) -> Wanted { + Wanted::new(&Filters { + license: license.iter().map(|l| (*l).to_owned()).collect(), + updated_since: since.map(|s| day(s).unwrap()), + min_sources: Some(min), + }) + } + + #[test] + fn days_are_full_iso_days_or_refused() { + assert_eq!(day("2024").as_deref(), Ok("2024-01-01")); + assert_eq!(day("2024-07").as_deref(), Ok("2024-07-01")); + assert_eq!(day("2024-07-30").as_deref(), Ok("2024-07-30")); + for bad in ["24", "2024-13", "2024-7-1", "July 2024", "2024-07-30T00"] + { + assert!(day(bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_date_counts_at_the_precision_it_is_recorded_with() { + assert!(on_or_after("2024-07-30", "2024-07-30")); + assert!(!on_or_after("2024-07-29", "2024-07-30")); + assert!(on_or_after("2024", "2024-06-01")); + assert!(on_or_after("2024-06", "2024-06-15")); + assert!(!on_or_after("2023-12-31T23:59:59Z", "2024-01-01")); + assert!(!on_or_after("Feb 17, 2026", "2020-01-01")); + } + + #[test] + fn a_license_filter_matches_ids_and_families_and_drops_the_unstated() { + let by = wanted(&["cc by"], None, 1); + assert!(by.admits(&hit(Some("CC-BY-4.0"), None, 1))); + assert!(by.admits(&hit(Some("CC-BY-3.0-AU"), None, 1))); + assert!(!by.admits(&hit(Some("CC-BY-SA-4.0"), None, 1))); + assert!(!by.admits(&hit(None, None, 1))); + let exact = wanted(&["CC-BY-4.0", "cc0"], None, 1); + assert!(exact.admits(&hit(Some("CC0-1.0"), None, 1))); + assert!(!exact.admits(&hit(Some("CC-BY-3.0"), None, 1))); + } + + #[test] + fn every_filter_must_hold() { + let all = wanted(&["cc-by"], Some("2024"), 2); + assert!(all.any()); + assert!(all.admits(&hit(Some("CC-BY-4.0"), Some("2025-01-02"), 2))); + assert!(!all.admits(&hit(Some("CC-BY-4.0"), Some("2023-01-02"), 2))); + assert!(!all.admits(&hit(Some("CC-BY-4.0"), Some("2025-01-02"), 1))); + assert!(!all.admits(&hit(Some("CC-BY-4.0"), None, 3))); + assert!(!wanted(&[], None, 1).any()); + assert!(wanted(&[], None, 1).admits(&hit(None, None, 1))); + } +} diff --git a/src/find.rs b/src/find.rs index bc6ca55..ed28075 100644 --- a/src/find.rs +++ b/src/find.rs @@ -18,8 +18,11 @@ use clap::builder::styling::Style; use serde::Serialize; use crate::cache::Cache; -use crate::cli::{Selection, Sort}; +use crate::cli::{ + Filters, PER_SOURCE_DEFAULT, PER_SOURCE_FILTERED, Selection, Sort, +}; use crate::dedup::{Hit, merge, weigh}; +use crate::filter::Wanted; use crate::http::SourceError; use crate::output::{self, Out, fit}; use crate::search::{Outcome, Plan, Status, run}; @@ -66,6 +69,7 @@ pub enum Error { pub struct Request<'a> { pub words: &'a [String], pub selection: &'a Selection, + pub filters: &'a Filters, pub limit: usize, pub sort: Sort, pub refresh: bool, @@ -75,8 +79,17 @@ pub struct Request<'a> { } pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { - let Request { words, selection, limit, sort, refresh, offline, timeout } = - *request; + let Request { + words, + selection, + filters, + limit, + sort, + refresh, + offline, + timeout, + } = *request; + let wanted = Wanted::new(filters); let services = Arc::new(Services::load()?); let query = words.join(" "); let plan = Arc::new(Plan { @@ -87,7 +100,13 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { &selection.exclude, &selection.categories, ), - per_source: usize::from(selection.per_source), + per_source: usize::from(selection.per_source.unwrap_or( + if wanted.any() { + PER_SOURCE_FILTERED + } else { + PER_SOURCE_DEFAULT + }, + )), forced: offline || !selection.only.is_empty(), }); if plan.sources.is_empty() { @@ -152,10 +171,22 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { .iter() .any(|o| matches!(o.status, Status::Running(_) | Status::Downloading)); let mut hits = ranked(&mut outcomes, &query, sort); - let found = hits.len(); + let matched = hits.len(); + hits.retain(|hit| wanted.admits(hit)); + let found = Found { + total: hits.len(), + filtered_out: matched.saturating_sub(hits.len()), + }; hits.truncate(limit); - print(out, &query, &hits, found, sources, complete)?; - summarize(&query, hits.len(), found, &outcomes, renewing, &services.cache); + print(out, &query, &hits, &found, sources, complete)?; + summarize( + &query, + hits.len(), + &found, + &outcomes, + renewing, + &services.cache, + ); Ok(()) } @@ -332,12 +363,18 @@ fn named(ids: &[&str]) -> String { const NAMED: usize = 3; +/// How many merged datasets passed the filters, and how many did not. +struct Found { + total: usize, + filtered_out: usize, +} + /// The closing lines on stderr, after the results: what failed, then one /// line on how it went and how to see more. fn summarize( query: &str, shown: usize, - found: usize, + found: &Found, outcomes: &[Outcome], renewing: bool, cache: &Cache, @@ -355,15 +392,25 @@ fn summarize( "{answered} of {} answered{still}", ui::count(attempted, "source") ); - if found == 0 { + let Found { total, filtered_out } = *found; + let filtered = if filtered_out > 0 { + format!(", {filtered_out} more without the filters") + } else { + String::new() + }; + if total == 0 && filtered_out > 0 { + ui::warn(format!( + "no datasets matched \"{query}\" and the filters; {filtered_out} matched without them; {sources}" + )); + } else if total == 0 { ui::warn(format!("no datasets matched \"{query}\"; {sources}")); - } else if shown < found { + } else if shown < total { ui::ok(format!( - "{shown} of {}; {sources}; -n {found} shows all", - ui::count(found, "result") + "{shown} of {}{filtered}; {sources}; -n {total} shows all", + ui::count(total, "result") )); } else { - ui::ok(format!("{}; {sources}", ui::count(found, "result"))); + ui::ok(format!("{}{filtered}; {sources}", ui::count(total, "result"))); } } @@ -379,6 +426,8 @@ struct Report<'a> { complete: bool, /// How many merged datasets matched; `results` holds the first `limit`. total: usize, + /// How many more matched but failed a filter. + filtered_out: usize, results: &'a [Hit], sources: Vec, } @@ -410,7 +459,7 @@ fn print( out: &Out, query: &str, hits: &[Hit], - total: usize, + found: &Found, sources: Vec, complete: bool, ) -> Result<()> { @@ -419,7 +468,8 @@ fn print( schema: SCHEMA, query, complete, - total, + total: found.total, + filtered_out: found.filtered_out, results: hits, sources, }); diff --git a/src/help.rs b/src/help.rs index 69883c1..16e4ca4 100644 --- a/src/help.rs +++ b/src/help.rs @@ -427,6 +427,7 @@ fn bounds(arg: &Arg) -> (Value, Value) { "per_source" => { (json!(cli::PER_SOURCE.start()), json!(cli::PER_SOURCE.end())) } + "min_sources" => (json!(cli::MIN_SOURCES.start), Value::Null), _ => (Value::Null, Value::Null), } } diff --git a/src/lib.rs b/src/lib.rs index 106e9e3..097e11e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,7 @@ mod cli; mod credentials; mod dedup; mod doctor; +mod filter; mod find; mod fs; mod help; @@ -237,6 +238,7 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { Command::Search { query, selection, + filters, limit, sort, refresh, @@ -249,6 +251,7 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { let request = find::Request { words: &query, selection: &selection, + filters: &filters, limit, sort, refresh, diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index fda4643..d0a9f76 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -114,6 +114,10 @@ struct Arg { required: bool, repeatable: bool, help: Option, + /// The JSON Schema `pattern` and an example of a string value whose + /// shape `help --json` cannot state. + #[serde(skip)] + shape: Option<(&'static str, &'static str)>, } impl Arg { @@ -148,6 +152,9 @@ fn described(tool: &str) -> anyhow::Result { let mut command: Described = serde_json::from_value(command)?; for arg in &mut command.args { arg.help = arg.help.as_deref().map(for_a_model); + if tool == "search" && arg.key() == "updated-since" { + arg.shape = Some((crate::filter::DAY_PATTERN, "2024-07-01")); + } if tool == "search" && arg.key() == "timeout" { (arg.minimum, arg.maximum) = (Some(1), Some(MAX_TIMEOUT)); arg.help = Some(format!( @@ -221,6 +228,10 @@ fn property(arg: &Arg) -> Value { if let Some(maximum) = arg.maximum { value.insert("maximum".into(), json!(maximum)); } + if let Some((pattern, example)) = arg.shape { + value.insert("pattern".into(), json!(pattern)); + value.insert("examples".into(), json!([example])); + } let mut property = if arg.takes_list() { let mut list = Map::new(); list.insert("type".into(), json!("array")); @@ -626,6 +637,9 @@ mod tests { &arguments(json!({ "query": "sea surface temperature", "source": ["zenodo", "datacite"], + "license": ["cc-by", "CC0-1.0"], + "updated-since": "2024-07", + "min-sources": 2, "limit": 5, "sort": "newest", "offline": true, @@ -640,6 +654,7 @@ mod tests { let Some(Cmd::Search { query, selection, + filters, limit, sort, offline, @@ -651,6 +666,9 @@ mod tests { }; assert_eq!(query, ["sea surface temperature"]); assert_eq!(selection.only, ["zenodo", "datacite"]); + assert_eq!(filters.license, ["cc-by", "CC0-1.0"]); + assert_eq!(filters.updated_since.as_deref(), Some("2024-07-01")); + assert_eq!(filters.min_sources, Some(2)); assert_eq!( (limit, sort, offline, refresh), (5, Sort::Newest, true, false) @@ -675,6 +693,10 @@ mod tests { } "boolean" => values.push(json!(true)), "integer" => values.push(json!(1)), + _ if property.get("examples").is_some() => { + values + .extend(property["examples"].as_array().unwrap().clone()); + } _ => values.push(json!("x")), } values diff --git a/tests/cli.rs b/tests/cli.rs index 3961ba2..1928411 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1664,6 +1664,49 @@ fn search_json_counts_matches_past_the_limit() { assert_eq!(report["total"], every); } +// A license matches in whatever spelling its source wrote, and what fails a +// filter is counted, not shown. +#[test] +fn search_filters_keep_what_passes_and_count_the_rest() { + let mut cmd = bin(); + let catalog = json!([ + { + "title": "Rainfall in Lisbon", + "url": "https://www.openml.org/d/1", + "updated": "2001-01-01", + "license": "Creative Commons Attribution 4.0 International", + }, + { + "title": "Monthly rainfall in Porto", + "url": "https://www.openml.org/d/2", + "updated": "2025-06-01", + "license": "https://creativecommons.org/licenses/by/4.0/", + }, + { + "title": "Rainfall in Faro", + "url": "https://www.openml.org/d/3", + "updated": "2025-06-01", + "license": "odc-odbl", + }, + ]); + seed(&cmd.cache(), "catalogs/openml.json", 0, &catalog); + let out = cmd + .args(["search", "rainfall", "-s", "openml", "--offline", "--json"]) + .args(["--license", "cc-by", "--updated-since", "2024"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let results = report["results"].as_array().unwrap(); + assert_eq!(results.len(), 1, "{report}"); + assert_eq!(results[0]["url"], "https://www.openml.org/d/2"); + assert_eq!(results[0]["license"], "CC-BY-4.0"); + assert_eq!( + (&report["total"], &report["filtered_out"]), + (&json!(1), &json!(2)) + ); +} + #[test] fn json_shapes_snapshot() { let sources = json_of(&["sources", "--json"]); diff --git a/tests/snapshots/cli__json_shapes_snapshot.snap b/tests/snapshots/cli__json_shapes_snapshot.snap index 51d4fd7..48a63f0 100644 --- a/tests/snapshots/cli__json_shapes_snapshot.snap +++ b/tests/snapshots/cli__json_shapes_snapshot.snap @@ -159,6 +159,7 @@ expression: "serde_json::to_string_pretty(&shapes).unwrap()" }, "search": { "complete": true, + "filtered_out": 0, "query": "rainfall", "results": [ { From 312a49567287417a16237af698380d8dac38f5fa Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:51:04 +0100 Subject: [PATCH 21/31] feat: results carry their file formats from CKAN portals, data.europa.eu, ArcGIS Hub, NASA CMR and data.gov, and search --format filters by them --- src/cache.rs | 1 + src/cli.rs | 5 + src/dedup.rs | 8 +- src/filter.rs | 22 +- src/find.rs | 43 +- src/mcp/tools.rs | 2 + src/record.rs | 138 ++++++ src/sources.rs | 6 +- src/sources/arcgis.rs | 5 + src/sources/aws.rs | 1 + src/sources/cellxgene.rs | 1 + src/sources/census.rs | 1 + src/sources/cern.rs | 1 + src/sources/cessda.rs | 1 + src/sources/ckan.rs | 21 + src/sources/cmr.rs | 12 + src/sources/dandi.rs | 1 + src/sources/datacite.rs | 1 + src/sources/datacommons.rs | 1 + src/sources/datagov.rs | 16 +- src/sources/dataone.rs | 1 + src/sources/dataverse.rs | 1 + src/sources/dbnomics.rs | 1 + src/sources/ebi.rs | 2 + src/sources/europa.rs | 22 +- src/sources/eurostat.rs | 1 + src/sources/figshare.rs | 1 + src/sources/fiscal.rs | 1 + src/sources/fred.rs | 1 + src/sources/gbif.rs | 1 + src/sources/gee.rs | 1 + src/sources/github.rs | 1 + src/sources/google.rs | 2 + src/sources/huggingface.rs | 1 + src/sources/kaggle.rs | 1 + src/sources/materials.rs | 1 + src/sources/mendeley.rs | 1 + src/sources/modelscope.rs | 1 + src/sources/nada.rs | 3 + src/sources/ncbi.rs | 1 + src/sources/ncei.rs | 1 + src/sources/nomad.rs | 2 + src/sources/omicsdi.rs | 1 + src/sources/openaire.rs | 1 + src/sources/opendatasoft.rs | 1 + src/sources/openml.rs | 2 + src/sources/openneuro.rs | 1 + src/sources/osf.rs | 1 + src/sources/owid.rs | 1 + src/sources/pangaea.rs | 1 + src/sources/physionet.rs | 2 + src/sources/roboflow.rs | 1 + src/sources/socrata.rs | 1 + src/sources/stac.rs | 2 + src/sources/synapse.rs | 1 + src/sources/tfds.rs | 1 + src/sources/uci.rs | 1 + src/sources/who.rs | 1 + src/sources/worldbank.rs | 2 + src/sources/zenodo.rs | 1 + tests/fixtures/sources/europa.formats.json | 507 +++++++++++++++++++++ 61 files changed, 848 insertions(+), 16 deletions(-) create mode 100644 tests/fixtures/sources/europa.formats.json diff --git a/src/cache.rs b/src/cache.rs index 3d4cd44..fbf5a7f 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -478,6 +478,7 @@ mod tests { updated: Some("2026-01-02".into()), size_bytes: Some(7), popularity: Some(3), + formats: vec![], aliases: vec!["10.5067/concept".into()], }; let bare = Dataset::new("Bare", "https://x.org/bare"); diff --git a/src/cli.rs b/src/cli.rs index 3c42a88..91f3338 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -204,6 +204,11 @@ pub struct Filters { #[arg(long, value_name = "DATE", value_parser = crate::filter::day)] pub updated_since: Option, + /// Only datasets offered in one of these file formats, comma-separated: + /// csv, json, parquet, netcdf, geotiff, ... + #[arg(long, value_name = "NAMES", value_delimiter = ',')] + pub format: Vec, + /// Only datasets that at least this many sources found. #[arg( long, diff --git a/src/dedup.rs b/src/dedup.rs index cd8458d..914e16f 100644 --- a/src/dedup.rs +++ b/src/dedup.rs @@ -188,7 +188,8 @@ fn fusion(rank: usize) -> f64 { 1.0 / (K + rank as f64 + 1.0) } -/// Keep the first source's fields; take only what it lacked from later ones. +/// Keep the first source's fields; take only what it lacked from later ones, +/// and every format any of them offers. fn fill(target: &mut Dataset, other: Dataset) { if target.description.is_none() { target.description = other.description; @@ -208,6 +209,11 @@ fn fill(target: &mut Dataset, other: Dataset) { if target.size_bytes.is_none() { target.size_bytes = other.size_bytes; } + for format in other.formats { + if !target.formats.contains(&format) { + target.formats.push(format); + } + } } /// Re-score fused hits by how much of the query they mention, because many diff --git a/src/filter.rs b/src/filter.rs index eac9a4d..9a917f0 100644 --- a/src/filter.rs +++ b/src/filter.rs @@ -7,12 +7,15 @@ use crate::cli::Filters; use crate::dedup::Hit; use crate::license; +use crate::record::file_format; /// The filters with their values normalized as the records' are, so a /// license asked for as `cc by 4.0` matches one recorded as `CC-BY-4.0`. #[derive(Debug, Default)] pub struct Wanted { pub licenses: Vec, + /// [`file_format`] names. + pub formats: Vec, /// A full ISO day. pub since: Option, pub min_sources: usize, @@ -26,6 +29,11 @@ impl Wanted { .iter() .filter_map(|l| license::normalized(l)) .collect(), + formats: filters + .format + .iter() + .filter_map(|f| file_format(f)) + .collect(), since: filters.updated_since.clone(), min_sources: filters.min_sources.map_or(0, usize::from), } @@ -34,6 +42,7 @@ impl Wanted { /// Whether any filter is set. pub fn any(&self) -> bool { !self.licenses.is_empty() + || !self.formats.is_empty() || self.since.is_some() || self.min_sources > 1 } @@ -44,10 +53,12 @@ impl Wanted { || d.license.as_deref().is_some_and(|l| { self.licenses.iter().any(|w| license::matches(l, w)) }); + let offered = self.formats.is_empty() + || d.formats.iter().any(|f| self.formats.contains(f)); let recent = self.since.as_deref().is_none_or(|since| { d.updated.as_deref().is_some_and(|day| on_or_after(day, since)) }); - licensed && recent && hit.sources.len() >= self.min_sources + licensed && offered && recent && hit.sources.len() >= self.min_sources } } @@ -127,6 +138,7 @@ mod tests { fn wanted(license: &[&str], since: Option<&str>, min: u16) -> Wanted { Wanted::new(&Filters { license: license.iter().map(|l| (*l).to_owned()).collect(), + format: Vec::new(), updated_since: since.map(|s| day(s).unwrap()), min_sources: Some(min), }) @@ -174,6 +186,14 @@ mod tests { assert!(!all.admits(&hit(Some("CC-BY-4.0"), Some("2025-01-02"), 1))); assert!(!all.admits(&hit(Some("CC-BY-4.0"), None, 3))); assert!(!wanted(&[], None, 1).any()); + let csv = Wanted::new(&Filters { + format: vec!["text/csv".into()], + ..Filters::default() + }); + let mut offered = hit(None, None, 1); + offered.dataset.formats = vec!["PDF".into(), "CSV".into()]; + assert!(csv.admits(&offered)); + assert!(!csv.admits(&hit(None, None, 1))); assert!(wanted(&[], None, 1).admits(&hit(None, None, 1))); } } diff --git a/src/find.rs b/src/find.rs index ed28075..c9c279c 100644 --- a/src/find.rs +++ b/src/find.rs @@ -170,14 +170,8 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { let complete = !outcomes .iter() .any(|o| matches!(o.status, Status::Running(_) | Status::Downloading)); - let mut hits = ranked(&mut outcomes, &query, sort); - let matched = hits.len(); - hits.retain(|hit| wanted.admits(hit)); - let found = Found { - total: hits.len(), - filtered_out: matched.saturating_sub(hits.len()), - }; - hits.truncate(limit); + let (hits, found) = + filtered(ranked(&mut outcomes, &query, sort), &wanted, limit); print(out, &query, &hits, &found, sources, complete)?; summarize( &query, @@ -190,6 +184,23 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { Ok(()) } +/// The hits that pass the filters, cut to `limit`, and how many passed and +/// failed them. +fn filtered( + mut hits: Vec, + wanted: &Wanted, + limit: usize, +) -> (Vec, Found) { + let matched = hits.len(); + hits.retain(|hit| wanted.admits(hit)); + let found = Found { + total: hits.len(), + filtered_out: matched.saturating_sub(hits.len()), + }; + hits.truncate(limit); + (hits, found) +} + /// Download again, in the background, the catalogs this search searched /// expired or stopped waiting for. Whether that download is under way. fn renew(cache: &Cache, outcomes: &[Outcome]) -> bool { @@ -515,18 +526,30 @@ fn print( } /// The one-line provenance under a title: sources, publisher, date, size, -/// license, whichever are known. +/// formats, license, whichever are known. Past [`FORMATS_SHOWN`] formats, +/// the rest are counted. fn facts(hit: &Hit) -> String { let d = &hit.dataset; let mut parts = vec![hit.sources.join(", ")]; parts.extend(d.publisher.clone()); parts.extend(d.updated.clone()); parts.extend(d.size_bytes.map(human_bytes)); + if !d.formats.is_empty() { + let shown = d.formats.iter().take(FORMATS_SHOWN); + let mut formats = shown.cloned().collect::>().join(", "); + let more = d.formats.len().saturating_sub(FORMATS_SHOWN); + if more > 0 { + formats = format!("{formats} +{more}"); + } + parts.push(formats); + } parts.extend(d.license.clone()); parts.extend(d.doi.as_ref().map(|doi| format!("doi:{doi}"))); parts.join(" | ") } +const FORMATS_SHOWN: usize = 3; + #[expect( clippy::cast_precision_loss, reason = "display rounding; exactness past 2^53 bytes is irrelevant" @@ -634,7 +657,7 @@ mod tests { /// What ranking [`answered`] allocates: keys, the owner map, hits, the /// text weighing reads and the term sets rarity weighting builds. One /// publisher copied on top of it reaches the bound. - const RANKING_BYTES: usize = 430_068; + const RANKING_BYTES: usize = 460_404; fn rain(url: &str, publisher: bool) -> Dataset { let mut d = Dataset::new("Rain", url); diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index d0a9f76..e917845 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -639,6 +639,7 @@ mod tests { "source": ["zenodo", "datacite"], "license": ["cc-by", "CC0-1.0"], "updated-since": "2024-07", + "format": ["csv"], "min-sources": 2, "limit": 5, "sort": "newest", @@ -668,6 +669,7 @@ mod tests { assert_eq!(selection.only, ["zenodo", "datacite"]); assert_eq!(filters.license, ["cc-by", "CC0-1.0"]); assert_eq!(filters.updated_since.as_deref(), Some("2024-07-01")); + assert_eq!(filters.format, ["csv"]); assert_eq!(filters.min_sources, Some(2)); assert_eq!( (limit, sort, offline, refresh), diff --git a/src/record.rs b/src/record.rs index d0b5295..74aaa9b 100644 --- a/src/record.rs +++ b/src/record.rs @@ -31,6 +31,10 @@ pub struct Dataset { /// within one source. #[serde(default, skip_serializing_if = "Option::is_none")] pub popularity: Option, + /// The file formats the dataset is offered in, each once, as + /// [`file_format`] names them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub formats: Vec, /// Other identifiers for the same dataset (a concept DOI, a mirror URL), /// used only to merge duplicates. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -514,6 +518,104 @@ pub fn day(timestamp: Option) -> Option { } } +/// Spellings of one format, lowercase, and the name every one becomes. +const FORMATS: &[(&[&str], &str)] = &[ + (&["csv", "text/csv", "comma separated values"], "CSV"), + (&["tsv", "tab", "text/tab-separated-values"], "TSV"), + (&["json", "application/json"], "JSON"), + ( + &["geojson", "application/geo+json", "application/vnd.geo+json"], + "GEOJSON", + ), + (&["json-ld", "jsonld", "application/ld+json"], "JSON-LD"), + (&["xml", "application/xml", "text/xml"], "XML"), + (&["rdf", "rdf/xml", "application/rdf+xml"], "RDF"), + (&["xls", "excel xls", "application/vnd.ms-excel"], "XLS"), + ( + &[ + "xlsx", + "excel", + "excel xlsx", + "microsoft excel", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ], + "XLSX", + ), + ( + &[ + "parquet", + "application/vnd.apache.parquet", + "application/x-parquet", + ], + "PARQUET", + ), + (&["nc", "nc4", "application/x-netcdf", "application/netcdf"], "NETCDF"), + (&["hdf5", "h5", "he5", "hdf-eos5", "application/x-hdf5"], "HDF5"), + (&["hdf", "hdf4", "hdf-eos", "hdf-eos2", "hdf-eos4"], "HDF4"), + (&["geotiff", "cog", "cloud optimized geotiff"], "GEOTIFF"), + (&["tif", "tiff", "image/tiff"], "TIFF"), + ( + &["shp", "shapefile", "esri shapefile", "application/x-shapefile"], + "SHAPEFILE", + ), + (&["kml", "application/vnd.google-earth.kml+xml"], "KML"), + (&["grib", "grib1", "grib2"], "GRIB"), + (&["zip", "application/zip"], "ZIP"), + (&["pdf", "application/pdf"], "PDF"), + (&["html", "htm", "text/html"], "HTML"), + (&["txt", "text/plain"], "TXT"), + ( + &[ + "esri rest", + "feature service", + "map service", + "image service", + "arcgis geoservices rest api", + ], + "ESRI REST", + ), +]; + +/// A file format as one short upper-case name, so `--format csv` matches +/// `text/csv`, `.csv` and an EU file-type URI ending in `CSV` alike: a media +/// type or a known spelling becomes its name (`netCDF-4` is `NETCDF`), and +/// anything else is upper-cased. `None` for what names no format ("Not +/// provided") or is too long to be a format's name. +pub fn file_format(raw: &str) -> Option { + let text = clean(raw); + let text = if text.contains("://") { + text.rsplit('/').find(|part| !part.is_empty()).unwrap_or_default() + } else { + text.as_str() + }; + let lower = text.trim_start_matches('.').to_lowercase(); + let lower = lower.strip_suffix("_srvc").unwrap_or(&lower); + if let Some((_, name)) = + FORMATS.iter().find(|(spellings, _)| spellings.contains(&lower)) + { + return Some((*name).to_owned()); + } + if lower.starts_with("netcdf") { + return Some("NETCDF".to_owned()); + } + let named = !lower.is_empty() + && lower.chars().count() <= 20 + && lower.chars().all(|c| c.is_alphanumeric() || " -_.+/".contains(c)) + && !matches!(lower, "not provided" | "not applicable" | "unknown"); + named.then(|| lower.to_uppercase()) +} + +/// [`file_format`] of each, every name once, in the order first given. +pub fn file_formats(raws: &[String]) -> Vec { + let mut names: Vec = Vec::new(); + for name in raws.iter().filter_map(|raw| file_format(raw)) { + if !names.contains(&name) { + names.push(name); + } + } + names +} + #[cfg(test)] mod tests { use proptest::prelude::*; @@ -758,4 +860,40 @@ mod tests { assert!(Dataset::new("", "https://x").valid().is_none()); assert!(Dataset::new("t", "ftp://x").valid().is_none()); } + + /// Spellings from the CKAN, data.europa.eu, ArcGIS, CMR and data.gov + /// fixtures and live answers, October 2026. + #[test] + fn format_spellings_become_one_name() { + for (raw, name) in [ + ("CSV", "CSV"), + ("text/csv", "CSV"), + (".csv", "CSV"), + ( + "http://publications.europa.eu/resource/authority/file-type/ZIP", + "ZIP", + ), + ("WMS_SRVC", "WMS"), + ("Excel XLSX", "XLSX"), + ( + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "XLSX", + ), + ("netCDF-4", "NETCDF"), + ("NetCDF4-CF", "NETCDF"), + ("HDF-EOS5", "HDF5"), + ("Feature Service", "ESRI REST"), + ("GeoTIFF", "GEOTIFF"), + ("ASPX", "ASPX"), + ] { + assert_eq!(file_format(raw).as_deref(), Some(name), "{raw}"); + } + for nothing in ["", "Not provided", "unknown", &"word ".repeat(9)] { + assert_eq!(file_format(nothing), None, "{nothing}"); + } + assert_eq!( + file_formats(&["CSV".into(), "csv".into(), "PDF".into()]), + ["CSV", "PDF"] + ); + } } diff --git a/src/sources.rs b/src/sources.rs index 6aaa639..46b3465 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -77,7 +77,7 @@ use crate::cache::{CATALOG_TTL, Cache, Freshness, Kind}; use crate::credentials::{Credentials, Key}; use crate::http::{Http, SourceError}; use crate::license; -use crate::record::Dataset; +use crate::record::{Dataset, file_formats}; pub type Live = fn(&Ctx<'_>, &str, usize) -> Result, SourceError>; pub type Listing = fn(&Ctx<'_>) -> Result, SourceError>; @@ -208,7 +208,8 @@ impl Source { } /// The source's answer, each record's license as [`license::normalized`] - /// gives it, so every source spells one license alike. + /// gives it and its formats as [`file_formats`] does, so every source + /// spells them alike. pub fn search( &self, ctx: &Ctx<'_>, @@ -219,6 +220,7 @@ impl Source { for dataset in &mut answer.datasets { dataset.license = dataset.license.as_deref().and_then(license::normalized); + dataset.formats = file_formats(&dataset.formats); } Ok(answer) } diff --git a/src/sources/arcgis.rs b/src/sources/arcgis.rs index 02f2f5d..00d80ff 100644 --- a/src/sources/arcgis.rs +++ b/src/sources/arcgis.rs @@ -15,6 +15,8 @@ //! and `modified` is epoch milliseconds (ArcGIS REST item reference, October //! 2026). The terms say nothing on caching search results (Esri Master //! Agreement, August 2025). +//! An item's `type` is its one format, a file type ("CSV") or a service +//! ("Feature Service"; ArcGIS REST item types, October 2026). use serde_json::Value; @@ -71,6 +73,7 @@ fn record(feature: &Value) -> Option { dataset.size_bytes = number(props, "/size").filter(|_| stores_its_data(props)); dataset.popularity = number(props, "/numViews"); + dataset.formats.extend(text(props, "/type")); dataset.valid() } @@ -128,6 +131,7 @@ mod tests { updated: Some("2026-08-04".into()), size_bytes: Some(1658), popularity: Some(30), + formats: vec!["CSV".into()], aliases: vec![], } ); @@ -153,6 +157,7 @@ mod tests { updated: Some("2016-03-24".into()), size_bytes: Some(49_152), popularity: Some(192), + formats: vec!["Feature Service".into()], aliases: vec![], } ); diff --git a/src/sources/aws.rs b/src/sources/aws.rs index 7afb7f0..94f6f37 100644 --- a/src/sources/aws.rs +++ b/src/sources/aws.rs @@ -106,6 +106,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/cellxgene.rs b/src/sources/cellxgene.rs index 9443170..38357df 100644 --- a/src/sources/cellxgene.rs +++ b/src/sources/cellxgene.rs @@ -78,6 +78,7 @@ mod tests { updated: Some("2026-06-11".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/census.rs b/src/sources/census.rs index f9ccd50..dbe17f6 100644 --- a/src/sources/census.rs +++ b/src/sources/census.rs @@ -84,6 +84,7 @@ mod tests { updated: Some("2019-10-09".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/cern.rs b/src/sources/cern.rs index 030aef8..5dca5ae 100644 --- a/src/sources/cern.rs +++ b/src/sources/cern.rs @@ -160,6 +160,7 @@ mod tests { updated: Some("2018".into()), size_bytes: Some(8371), popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/cessda.rs b/src/sources/cessda.rs index 7f006fa..50887fd 100644 --- a/src/sources/cessda.rs +++ b/src/sources/cessda.rs @@ -108,6 +108,7 @@ mod tests { updated: Some("2026-08-11".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec!["https://urn.fi/urn:nbn:fi:fsd:T-FSD3325".into()], } ); diff --git a/src/sources/ckan.rs b/src/sources/ckan.rs index 34f4471..0620004 100644 --- a/src/sources/ckan.rs +++ b/src/sources/ckan.rs @@ -47,6 +47,11 @@ //! Dataverse installations ("6828; 6803"), rounded sizes from B2SHARE //! ("215.9 kB; 1 file") or counts that are not bytes ("28254 data points") //! (probes, October 2026). +//! +//! Each resource's `format` is the publisher's free text: "CSV", "XLSX", +//! "SHP", "JPG", "BIN", or empty on GovData; B2FIND sends no resources and +//! so no formats (probes, October 2026). `file_format` turns the spellings +//! into one name per format. use serde_json::Value; @@ -191,6 +196,10 @@ fn record(portal: &Portal, row: &Value) -> Option { dataset.size_bytes = resource_bytes(row) .or_else(|| extra("Size").and_then(|sizes| listed_bytes(&sizes))); dataset.popularity = number(row, "/total_res_downloads"); + dataset.formats = items(row, "/resources") + .iter() + .filter_map(|resource| text(resource, "/format")) + .collect(); if let Some(source_page) = text(row, "/url") && source_page.starts_with("http") { @@ -280,6 +289,12 @@ mod tests { updated: Some("2018-10-17".into()), size_bytes: Some(18_759 + 22_892 + 24_498 + 24_412), popularity: None, + formats: vec![ + "CSV".into(), + "XLSX".into(), + "XLSX".into(), + "CSV".into() + ], aliases: vec![ "https://datamillnorth.org/dataset/\ climate-resilience-documents-vdwno" @@ -330,6 +345,7 @@ mod tests { updated: Some("2025-03-04".into()), size_bytes: Some(787_522), popularity: Some(29178), + formats: vec!["CSV".into()], aliases: vec![], }, "the fixture keeps 1 of the record's 6 resources" @@ -375,6 +391,7 @@ mod tests { updated: Some("2021-08-16".into()), size_bytes: Some(27_652), popularity: Some(78), + formats: vec!["SHP".into()], aliases: vec![], } ); @@ -422,6 +439,7 @@ mod tests { updated: Some("2022-03-14".into()), size_bytes: Some(1_134_541), popularity: None, + formats: vec!["JPG".into()], aliases: vec![], }, "`url` there is a Python dict of two API links, not a page" @@ -470,6 +488,7 @@ mod tests { updated: Some("2026-09-09".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], }, "no `modified` extra, so the portal's own record date stands" @@ -513,6 +532,7 @@ mod tests { updated: Some("2025-11-30".into()), size_bytes: Some(178_264), popularity: None, + formats: vec!["BIN".into()], aliases: vec![], }, "CKAN's `notspecified` license id is no license" @@ -568,6 +588,7 @@ mod tests { updated: Some("2025-06-20".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], }, "no `Size` extra and no resources" diff --git a/src/sources/cmr.rs b/src/sources/cmr.rs index 819f055..1c7a765 100644 --- a/src/sources/cmr.rs +++ b/src/sources/cmr.rs @@ -24,6 +24,9 @@ //! names KB to PB without saying which (UMM-C 1.18.6, October 2026). The //! usage score CMR ranks by is not in any search response, only in a //! separate whole-catalog table. +//! The formats are each `FileDistributionInformation` entry's `Format`, free +//! text such as "HDF5", "netCDF-4" or "HDF-EOS5" (UMM-C 1.18.6, probes, +//! October 2026). use serde_json::Value; @@ -93,6 +96,13 @@ fn record(item: &Value) -> Option { .and_then(|date| text(date, "/Date")); dataset.updated = day(data_update.or_else(|| text(item, "/meta/revision-date"))); + dataset.formats = items( + item, + "/umm/ArchiveAndDistributionInformation/FileDistributionInformation", + ) + .iter() + .filter_map(|file| text(file, "/Format")) + .collect(); dataset.valid() } @@ -168,6 +178,7 @@ mod tests { updated: Some("2026-10-02".into()), size_bytes: None, popularity: None, + formats: vec!["HDF5".into()], aliases: vec![], } ); @@ -203,6 +214,7 @@ mod tests { updated: Some("2026-10-16".into()), size_bytes: Some(15_000_000_000_000), popularity: None, + formats: vec!["netCDF-4".into()], aliases: vec![], } ); diff --git a/src/sources/dandi.rs b/src/sources/dandi.rs index b5d58f3..cd60309 100644 --- a/src/sources/dandi.rs +++ b/src/sources/dandi.rs @@ -115,6 +115,7 @@ mod tests { updated: Some("2026-03-25".into()), size_bytes: Some(38_464_536_222_290), popularity: Some(6), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/datacite.rs b/src/sources/datacite.rs index 0b46c6c..074b9cd 100644 --- a/src/sources/datacite.rs +++ b/src/sources/datacite.rs @@ -215,6 +215,7 @@ mod tests { updated: Some("2026-04-21".into()), size_bytes: None, popularity: Some(14), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/datacommons.rs b/src/sources/datacommons.rs index 12102f6..d3f1f0e 100644 --- a/src/sources/datacommons.rs +++ b/src/sources/datacommons.rs @@ -88,6 +88,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/datagov.rs b/src/sources/datagov.rs index c3a88be..94fc18a 100644 --- a/src/sources/datagov.rs +++ b/src/sources/datagov.rs @@ -9,13 +9,17 @@ //! keyless host states no limit (api.data.gov, October 2026). `popularity` is //! the dataset page's views in the last month, the figure the catalog prints //! as "Views last month" (Data.gov user guide, October 2026). +//! A distribution names its format in DCAT `format`, else `mediaType` +//! (probes, October 2026). use serde_json::Value; use super::Ctx; use crate::credentials::Key; use crate::http::SourceError; -use crate::record::{Dataset, day, doi, from_markdown, number, text}; +use crate::record::{ + Dataset, day, doi, first_text, from_markdown, items, number, text, +}; /// What harvested records say when the publisher gave nothing. const NO_DESCRIPTION: &str = "No description found"; @@ -67,6 +71,10 @@ fn record(row: &Value) -> Option { text(row, "/dcat/license").filter(|l| !l.ends_with(UNKNOWN_LICENSE)); dataset.updated = day(text(row, "/dcat/modified")); dataset.popularity = number(row, "/popularity"); + dataset.formats = items(row, "/dcat/distribution") + .iter() + .filter_map(|d| first_text(d, &["/format", "/mediaType"])) + .collect(); dataset.aliases.extend(landing); dataset.valid() } @@ -130,6 +138,12 @@ mod tests { updated: Some("2024-11-27".into()), size_bytes: None, popularity: Some(13), + formats: vec![ + "CSV".into(), + "CSV".into(), + "CSV".into(), + "CSV".into() + ], aliases: vec![], } ); diff --git a/src/sources/dataone.rs b/src/sources/dataone.rs index d5c25e0..b03e6ff 100644 --- a/src/sources/dataone.rs +++ b/src/sources/dataone.rs @@ -142,6 +142,7 @@ mod tests { updated: Some("2024-11-14".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/dataverse.rs b/src/sources/dataverse.rs index 463a4eb..6b42498 100644 --- a/src/sources/dataverse.rs +++ b/src/sources/dataverse.rs @@ -87,6 +87,7 @@ mod tests { updated: Some("2025-06-16".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/dbnomics.rs b/src/sources/dbnomics.rs index f14a7b4..6cad749 100644 --- a/src/sources/dbnomics.rs +++ b/src/sources/dbnomics.rs @@ -111,6 +111,7 @@ mod tests { updated: Some("2026-06-12".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/ebi.rs b/src/sources/ebi.rs index bc76a90..f781b06 100644 --- a/src/sources/ebi.rs +++ b/src/sources/ebi.rs @@ -152,6 +152,7 @@ mod tests { updated: Some("2010-07-08".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); @@ -187,6 +188,7 @@ mod tests { updated: Some("2020-09-02".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/europa.rs b/src/sources/europa.rs index bbfece1..d330406 100644 --- a/src/sources/europa.rs +++ b/src/sources/europa.rs @@ -29,6 +29,10 @@ //! `catalog_record.modified` and a distribution's `modified` are the days //! the portal re-harvested it, within the last few months even for records //! published years before (probes, October 2026). +//! +//! A distribution's `format.id` is an id from the EU file-type vocabulary +//! ("CSV", "GEOJSON", "WMS_SRVC" for a map service) and `format.resource` +//! its URI (probes, October 2026). use serde_json::Value; @@ -39,7 +43,8 @@ use crate::record::{Dataset, day, doi, items, localized, number, text}; const INCLUDES: &str = "id,title,description,publisher,catalog.id,\ catalog.title,distributions.license,\ - distributions.byte_size,modified,issued,\ + distributions.byte_size,distributions.format,\ + modified,issued,\ landing_page,page,identifier,is_version_of"; /// The sizes data.gov.it writes for a file it has not measured. @@ -108,6 +113,8 @@ fn record(row: &Value) -> Option { dataset.license = distributions.iter().find_map(license); dataset.updated = day(text(row, "/modified").or_else(|| text(row, "/issued"))); + dataset.formats = + distributions.iter().filter_map(|d| text(d, "/format/id")).collect(); dataset.size_bytes = distributions .iter() .filter_map(|d| number(d, "/byte_size")) @@ -157,6 +164,7 @@ fn doi_of(row: &Value) -> Option { #[cfg(test)] mod tests { use super::*; + use crate::record::file_formats; use crate::sources::fixture; #[test] @@ -183,6 +191,7 @@ mod tests { updated: Some("2024-08-01".into()), size_bytes: Some(43_125_616), popularity: None, + formats: vec![], aliases: vec!["10.5281/zenodo.1631855".into()], } ); @@ -283,6 +292,17 @@ mod tests { ); } + #[test] + fn each_distribution_names_its_file_type() { + let hits = parse(&fixture::json("europa.formats.json"), 10).unwrap(); + let formats: Vec<_> = hits.iter().map(|h| h.formats.clone()).collect(); + assert_eq!( + formats, + [vec!["CSV"; 4], vec!["CSV", "JSON"], vec!["WMS_SRVC", "GEOJSON"],] + ); + assert_eq!(file_formats(&hits[2].formats), ["WMS", "GEOJSON"]); + } + #[test] fn an_unbalanced_quote_is_dropped_and_a_phrase_is_kept() { assert_eq!( diff --git a/src/sources/eurostat.rs b/src/sources/eurostat.rs index e068c9b..b2e77eb 100644 --- a/src/sources/eurostat.rs +++ b/src/sources/eurostat.rs @@ -188,6 +188,7 @@ mod tests { updated: Some("2026-10-02".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/figshare.rs b/src/sources/figshare.rs index 2eeef95..ba8d8b0 100644 --- a/src/sources/figshare.rs +++ b/src/sources/figshare.rs @@ -111,6 +111,7 @@ mod tests { updated: Some("2026-10-06".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec!["10.6084/m9.figshare.33059219".into()], } ); diff --git a/src/sources/fiscal.rs b/src/sources/fiscal.rs index ff4c358..86488cb 100644 --- a/src/sources/fiscal.rs +++ b/src/sources/fiscal.rs @@ -83,6 +83,7 @@ mod tests { updated: Some("2026-09-04".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/fred.rs b/src/sources/fred.rs index 633a791..4292d03 100644 --- a/src/sources/fred.rs +++ b/src/sources/fred.rs @@ -96,6 +96,7 @@ mod tests { updated: Some("2014-01-17".into()), size_bytes: None, popularity: Some(34), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/gbif.rs b/src/sources/gbif.rs index bbb5d64..cced1f2 100644 --- a/src/sources/gbif.rs +++ b/src/sources/gbif.rs @@ -86,6 +86,7 @@ mod tests { updated: Some("2019-11-11".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/gee.rs b/src/sources/gee.rs index cb7d8ae..3aa620f 100644 --- a/src/sources/gee.rs +++ b/src/sources/gee.rs @@ -133,6 +133,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/github.rs b/src/sources/github.rs index a26448b..91995e1 100644 --- a/src/sources/github.rs +++ b/src/sources/github.rs @@ -87,6 +87,7 @@ mod tests { updated: Some("2026-04-09".into()), size_bytes: Some(73_274_368), popularity: Some(202), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/google.rs b/src/sources/google.rs index e88a537..1fc00da 100644 --- a/src/sources/google.rs +++ b/src/sources/google.rs @@ -232,6 +232,7 @@ mod tests { updated: Some("2019-08-13".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![ "https://nsidc.org/data/g02135/versions/3".into() ], @@ -296,6 +297,7 @@ mod tests { updated: Some("2022-10-06".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![ "https://datasetcatalog.nlm.nih.gov/dataset?q=0002202795" .into() diff --git a/src/sources/huggingface.rs b/src/sources/huggingface.rs index 2f6b69f..1d3fd8f 100644 --- a/src/sources/huggingface.rs +++ b/src/sources/huggingface.rs @@ -249,6 +249,7 @@ mod tests { updated: Some("2023-04-18".into()), size_bytes: Some(498_654), popularity: Some(254), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/kaggle.rs b/src/sources/kaggle.rs index c1e8e38..a397fb4 100644 --- a/src/sources/kaggle.rs +++ b/src/sources/kaggle.rs @@ -135,6 +135,7 @@ mod tests { updated: Some("2024-02-22".into()), size_bytes: Some(34_794), popularity: Some(20_272), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/materials.rs b/src/sources/materials.rs index ce23d52..931fd80 100644 --- a/src/sources/materials.rs +++ b/src/sources/materials.rs @@ -84,6 +84,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/mendeley.rs b/src/sources/mendeley.rs index eb347a2..6d7e758 100644 --- a/src/sources/mendeley.rs +++ b/src/sources/mendeley.rs @@ -96,6 +96,7 @@ mod tests { updated: Some("2026-10-06".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/modelscope.rs b/src/sources/modelscope.rs index 81478c9..9beafd1 100644 --- a/src/sources/modelscope.rs +++ b/src/sources/modelscope.rs @@ -88,6 +88,7 @@ mod tests { updated: Some("2023-03-01".into()), size_bytes: Some(68_276), popularity: Some(2275), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/nada.rs b/src/sources/nada.rs index 2cc3589..eb7d9ea 100644 --- a/src/sources/nada.rs +++ b/src/sources/nada.rs @@ -95,6 +95,7 @@ mod tests { updated: Some("2023-02-21".into()), size_bytes: None, popularity: Some(675), + formats: vec![], aliases: vec![], } ); @@ -136,6 +137,7 @@ mod tests { updated: Some("2019-03-29".into()), size_bytes: None, popularity: Some(72), + formats: vec![], aliases: vec![], } ); @@ -170,6 +172,7 @@ mod tests { updated: Some("2025-12-12".into()), size_bytes: None, popularity: Some(2), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/ncbi.rs b/src/sources/ncbi.rs index 2090e28..4eda7f7 100644 --- a/src/sources/ncbi.rs +++ b/src/sources/ncbi.rs @@ -174,6 +174,7 @@ mod tests { ), publisher: Some("NCBI GEO".into()), updated: Some("2015-05-16".into()), + formats: vec![], aliases: vec![ "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE68918" .into() diff --git a/src/sources/ncei.rs b/src/sources/ncei.rs index d72d2ac..1cd6e09 100644 --- a/src/sources/ncei.rs +++ b/src/sources/ncei.rs @@ -120,6 +120,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/nomad.rs b/src/sources/nomad.rs index 6a1c961..35441c7 100644 --- a/src/sources/nomad.rs +++ b/src/sources/nomad.rs @@ -85,6 +85,7 @@ mod tests { updated: Some("2020-05-20".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); @@ -112,6 +113,7 @@ mod tests { updated: Some("2026-06-04".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/omicsdi.rs b/src/sources/omicsdi.rs index 95efeba..d556aca 100644 --- a/src/sources/omicsdi.rs +++ b/src/sources/omicsdi.rs @@ -150,6 +150,7 @@ mod tests { updated: Some("2024-12-16".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/openaire.rs b/src/sources/openaire.rs index e451f05..660ee33 100644 --- a/src/sources/openaire.rs +++ b/src/sources/openaire.rs @@ -150,6 +150,7 @@ mod tests { updated: Some("2020-09-28".into()), size_bytes: None, popularity: Some(1), + formats: vec![], aliases: vec![ "10.5281/zenodo.8260345".into(), "https://zenodo.org/records/8260345".into(), diff --git a/src/sources/opendatasoft.rs b/src/sources/opendatasoft.rs index 6313fe5..dddb463 100644 --- a/src/sources/opendatasoft.rs +++ b/src/sources/opendatasoft.rs @@ -119,6 +119,7 @@ mod tests { updated: Some("2018-03-26".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/openml.rs b/src/sources/openml.rs index e672ad4..46bef21 100644 --- a/src/sources/openml.rs +++ b/src/sources/openml.rs @@ -166,6 +166,7 @@ mod tests { updated: Some("2015-09-02".into()), size_bytes: None, popularity: Some(13_779), + formats: vec![], aliases: vec![], } ); @@ -186,6 +187,7 @@ mod tests { updated: Some("2022-02-22".into()), size_bytes: None, popularity: Some(0), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/openneuro.rs b/src/sources/openneuro.rs index f272726..ff2ba66 100644 --- a/src/sources/openneuro.rs +++ b/src/sources/openneuro.rs @@ -112,6 +112,7 @@ mod tests { updated: Some("2020-05-14".into()), size_bytes: Some(2_416_199_965), popularity: Some(2523), + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/osf.rs b/src/sources/osf.rs index 930b598..98e8f63 100644 --- a/src/sources/osf.rs +++ b/src/sources/osf.rs @@ -98,6 +98,7 @@ mod tests { updated: Some("2026-06-23".into()), size_bytes: Some(142_773), popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/owid.rs b/src/sources/owid.rs index 08fa83c..b028c1a 100644 --- a/src/sources/owid.rs +++ b/src/sources/owid.rs @@ -100,6 +100,7 @@ mod tests { updated: Some("2025-10-22".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/pangaea.rs b/src/sources/pangaea.rs index 31e4441..6639ef3 100644 --- a/src/sources/pangaea.rs +++ b/src/sources/pangaea.rs @@ -135,6 +135,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/physionet.rs b/src/sources/physionet.rs index fd505bb..ad50090 100644 --- a/src/sources/physionet.rs +++ b/src/sources/physionet.rs @@ -100,6 +100,7 @@ mod tests { updated: Some("1999-08-03".into()), size_bytes: Some(663_056_564), popularity: None, + formats: vec![], aliases: vec![], } ); @@ -121,6 +122,7 @@ mod tests { updated: Some("2018-06-07".into()), size_bytes: Some(115_343_616), popularity: None, + formats: vec![], aliases: vec!["10.13026/twfd-kb89".into()], } ); diff --git a/src/sources/roboflow.rs b/src/sources/roboflow.rs index efa207c..dfb4078 100644 --- a/src/sources/roboflow.rs +++ b/src/sources/roboflow.rs @@ -126,6 +126,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/socrata.rs b/src/sources/socrata.rs index afd0a4a..a546822 100644 --- a/src/sources/socrata.rs +++ b/src/sources/socrata.rs @@ -91,6 +91,7 @@ mod tests { updated: Some("2026-03-16".into()), size_bytes: None, popularity: Some(3841), + formats: vec![], aliases: vec![ "https://datahub.austintexas.gov/d/sxk7-7k6z".into() ], diff --git a/src/sources/stac.rs b/src/sources/stac.rs index dc419fe..afdf65e 100644 --- a/src/sources/stac.rs +++ b/src/sources/stac.rs @@ -162,6 +162,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); @@ -217,6 +218,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/synapse.rs b/src/sources/synapse.rs index 2ee4994..0406189 100644 --- a/src/sources/synapse.rs +++ b/src/sources/synapse.rs @@ -95,6 +95,7 @@ mod tests { updated: Some("2026-06-08".into()), size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/tfds.rs b/src/sources/tfds.rs index b733249..bebb148 100644 --- a/src/sources/tfds.rs +++ b/src/sources/tfds.rs @@ -142,6 +142,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/uci.rs b/src/sources/uci.rs index 9484d7b..eb4f01f 100644 --- a/src/sources/uci.rs +++ b/src/sources/uci.rs @@ -58,6 +58,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/who.rs b/src/sources/who.rs index f3a80da..cf97839 100644 --- a/src/sources/who.rs +++ b/src/sources/who.rs @@ -67,6 +67,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/worldbank.rs b/src/sources/worldbank.rs index 823cf2e..b59aaee 100644 --- a/src/sources/worldbank.rs +++ b/src/sources/worldbank.rs @@ -87,6 +87,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); @@ -115,6 +116,7 @@ mod tests { updated: None, size_bytes: None, popularity: None, + formats: vec![], aliases: vec![], } ); diff --git a/src/sources/zenodo.rs b/src/sources/zenodo.rs index ef00d42..82e1f1a 100644 --- a/src/sources/zenodo.rs +++ b/src/sources/zenodo.rs @@ -157,6 +157,7 @@ mod tests { updated: Some("2026-10-01".into()), size_bytes: Some(585 + 939_174 + 242_821), popularity: Some(3), + formats: vec![], aliases: vec!["10.5281/zenodo.23077367".into()], } ); diff --git a/tests/fixtures/sources/europa.formats.json b/tests/fixtures/sources/europa.formats.json new file mode 100644 index 0000000..d6e54e5 --- /dev/null +++ b/tests/fixtures/sources/europa.formats.json @@ -0,0 +1,507 @@ +{ + "result": { + "index": "dataset", + "count": 98233, + "results": [ + { + "catalog": { + "id": "data-gov-uk", + "title": { + "nl": "data.gov.uk", + "mt": "data.gov.uk", + "da": "data.gov.uk", + "lv": "data.gov.uk", + "es": "data.gov.uk", + "pl": "data.gov.uk", + "et": "data.gov.uk", + "hu": "data.gov.uk", + "cs": "data.gov.uk", + "it": "data.gov.uk", + "ga": "data.gov.uk", + "ro": "data.gov.uk", + "el": "data.gov.uk", + "hr": "data.gov.uk", + "fi": "data.gov.uk", + "pt": "data.gov.uk", + "sk": "data.gov.uk", + "bg": "данни.gov.uk", + "sl": "data.gov.uk", + "sv": "data.gov.uk", + "fr": "data.gov.uk", + "en": "data.gov.uk", + "de": "data.gov.uk", + "uk": "data.gov.uk", + "lt": "data.gov.uk" + } + }, + "description": { + "pl": "Jakość powietrza jest stale monitorowana w kilku miejscach w mieście i wokół niego za pomocą ciągłych analizatorów. Dane w czasie rzeczywistym z naszej sieci monitorowania jakości powietrza oraz z zak", + "sl": "Kakovost zraka se stalno spremlja na več lokacijah v mestu in okoli njega s stalnimi analizatorji. Podatki v realnem času iz naše mreže za spremljanje kakovosti zraka in iz lokacij v Bristolu, ki so d", + "hu": "A levegő minőségét folyamatosan ellenőrzik a város több pontján és környékén, folyamatos analizátorokkal. Valós idejű adatok a levegőminőség-figyelő hálózatunkból és a bristoli telephelyekről, amelyek", + "lt": "Oro kokybė nuolat stebima keliose miesto ir aplink jį esančiose vietose, naudojant nuolatinius analizatorius. Realaus laiko duomenys iš mūsų oro kokybės stebėjimo tinklo ir iš Bristolio vietų, kurios ", + "uk": "Якість повітря постійно контролюється на кількох об'єктах у місті та навколо нього за допомогою безперервних аналізаторів. Дані в режимі реального часу з нашої мережі моніторингу якості повітря та з с", + "fi": "Ilmanlaatua seurataan jatkuvasti useissa kohteissa kaupungissa ja sen ympäristössä jatkuvatoimisilla analysaattoreilla. Reaaliaikaiset tiedot ilmanlaadun seurantaverkostostamme ja Bristolissa sijaitse", + "pt": "A qualidade do ar é monitorizada continuamente em vários locais dentro e à volta da cidade com analisadores contínuos. Dados em tempo real da nossa rede de monitorização da qualidade do ar e de locais", + "el": "Η ποιότητα του αέρα παρακολουθείται συνεχώς σε διάφορες τοποθεσίες μέσα και γύρω από την πόλη με συνεχείς αναλυτές. Δεδομένα σε πραγματικό χρόνο από το δίκτυο παρακολούθησης της ποιότητας του αέρα και", + "bg": "Качеството на въздуха се следи непрекъснато на няколко места в и около града с непрекъснати анализатори. Данни в реално време от нашата мрежа за мониторинг на качеството на въздуха и от обекти в Брист", + "de": "An mehreren Standorten in und um die Stadt wird die Luftqualität kontinuierlich mit kontinuierlichen Analysatoren überwacht. Echtzeitdaten aus unserem Netzwerk zur Überwachung der Luftqualität und von", + "da": "Luftkvaliteten overvåges løbende flere steder i og omkring byen med kontinuerlige analysatorer. Data i realtid fra vores luftkvalitetsovervågningsnetværk og fra steder i Bristol, der er en del af det ", + "lv": "Gaisa kvalitāte tiek pastāvīgi uzraudzīta vairākās vietās pilsētā un tās apkārtnē, izmantojot nepārtrauktus analizatorus. Reālā laika dati no mūsu gaisa kvalitātes monitoringa tīkla un no objektiem Br", + "hr": "Kvaliteta zraka kontinuirano se prati na nekoliko lokacija u gradu i oko njega s pomoću kontinuiranih analizatora. Podaci u stvarnom vremenu iz naše mreže za praćenje kvalitete zraka i s lokacija u Br", + "mt": "Il-kwalità tal-arja tiġi mmonitorjata kontinwament f’diversi siti fil-belt u madwarha b’analizzaturi kontinwi. Data f’ħin reali min-network tagħna ta’ monitoraġġ tal-kwalità tal-arja, u minn siti fi B", + "ga": "Déantar monatóireacht leanúnach ar cháilíocht an aeir ag roinnt suíomhanna sa chathair agus timpeall uirthi le hanailíseoirí leanúnacha. Sonraí fíor-ama ónár líonra monatóireachta ar cháilíocht an aei", + "fr": "La qualité de l'air est surveillée en permanence sur plusieurs sites dans et autour de la ville à l'aide d'analyseurs en continu. Données en temps réel de notre réseau de surveillance de la qualité de", + "en": "Air quality is monitored continuously at several sites in and around the city with continuous analysers. Real time data from our air quality monitoring network, and from sites in Bristol that are part", + "et": "Õhukvaliteeti jälgitakse pidevalt mitmes kohas linnas ja selle ümbruses pidevate analüsaatoritega. Reaalajas andmed meie õhukvaliteedi seire võrgustikust ja Bristolis asuvatest kohtadest, mis on osa r", + "ro": "Calitatea aerului este monitorizată continuu în mai multe locații din oraș și din împrejurimi cu analizoare continue. Date în timp real de la rețeaua noastră de monitorizare a calității aerului și de ", + "sk": "Kvalita ovzdušia sa nepretržite monitoruje na viacerých miestach v meste a v jeho okolí pomocou kontinuálnych analyzátorov. Údaje v reálnom čase z našej siete na monitorovanie kvality ovzdušia a z lok", + "nl": "De luchtkwaliteit wordt continu bewaakt op verschillende locaties in en rond de stad met continue analysers. Realtime gegevens van ons monitoringnetwerk voor luchtkwaliteit en van locaties in Bristol ", + "it": "La qualità dell'aria viene monitorata continuamente in diversi siti all'interno e nei dintorni della città con analizzatori continui. Dati in tempo reale dalla nostra rete di monitoraggio della qualit", + "es": "La calidad del aire es monitoreada continuamente en varios sitios dentro y alrededor de la ciudad con analizadores continuos. Datos en tiempo real de nuestra red de monitoreo de calidad del aire y de ", + "cs": "Kvalita ovzduší je kontinuálně sledována na několika místech ve městě a jeho okolí pomocí kontinuálních analyzátorů. Údaje v reálném čase z naší sítě pro monitorování kvality ovzduší a z lokalit v Bri", + "sv": "Luftkvaliteten övervakas kontinuerligt på flera platser i och runt staden med kontinuerliga analysatorer. Realtidsdata från vårt nätverk för övervakning av luftkvaliteten och från anläggningar i Brist" + }, + "publisher": { + "type": "Agent", + "name": "Bristol City Council" + }, + "index": "dataset", + "id": "bristol-air-quality", + "title": { + "cs": "Bristol Kvalita ovzduší", + "en": "Bristol Air quality", + "bg": "Бристол Качество на въздуха", + "sk": "Bristol Kvalita ovzdušia", + "fr": "Bristol Qualité de l'air", + "hr": "Bristol Kvaliteta zraka", + "pl": "Bristol Jakość powietrza", + "uk": "Брістоль Якість повітря", + "it": "Bristol Qualità dell'aria", + "pt": "Bristol Qualidade do ar", + "lt": "Bristolis Oro kokybė", + "lv": "Bristole Gaisa kvalitāte", + "de": "Bristol Luftqualität", + "ro": "Bristol Calitatea aerului", + "da": "Bristol Luftkvalitet", + "es": "Bristol Calidad del aire", + "hu": "Bristol Levegőminőség", + "fi": "Bristol Ilmanlaatu", + "mt": "Bristol Kwalità tal-arja", + "ga": "Bristol Air quality", + "et": "Bristol Õhukvaliteet", + "el": "Bristol Ποιότητα του αέρα", + "nl": "Bristol Luchtkwaliteit", + "sv": "Bristol Luftkvalitet", + "sl": "Bristol Kakovost zraka" + }, + "distributions": [ + { + "format": { + "id": "CSV", + "label": "CSV", + "resource": "http://publications.europa.eu/resource/authority/file-type/CSV", + "format_types": [ + { + "id": "tabular", + "label": { + "en": "Tabular" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + }, + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + }, + { + "format": { + "id": "CSV", + "label": "CSV", + "resource": "http://publications.europa.eu/resource/authority/file-type/CSV", + "format_types": [ + { + "id": "tabular", + "label": { + "en": "Tabular" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + }, + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + }, + { + "format": { + "id": "CSV", + "label": "CSV", + "resource": "http://publications.europa.eu/resource/authority/file-type/CSV", + "format_types": [ + { + "id": "tabular", + "label": { + "en": "Tabular" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + }, + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + }, + { + "format": { + "id": "CSV", + "label": "CSV", + "resource": "http://publications.europa.eu/resource/authority/file-type/CSV", + "format_types": [ + { + "id": "tabular", + "label": { + "en": "Tabular" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + }, + "license": { + "resource": "http://reference.data.gov.uk/id/open-government-licence", + "id": "http://reference.data.gov.uk/id/open-government-licence", + "label": "http://reference.data.gov.uk/id/open-government-licence" + } + } + ] + }, + { + "identifier": [ + "https://data.laregion.fr/explore/dataset/pln-air-donnees-2021/" + ], + "catalog": { + "id": "plateforme-ouverte-des-donnees-publiques-francaises", + "title": { + "da": "Åben platform af franske offentlige data", + "sv": "Öppen plattform för franska offentliga data", + "mt": "Pjattaforma miftuħa tad-data pubblika Franċiża", + "sk": "Otvorená platforma francúzskych verejných údajov", + "it": "Piattaforma aperta di dati pubblici francesi", + "fi": "Ranskan julkisen datan avoin alusta", + "bg": "Отворена платформа за френски публични данни", + "fr": "Plateforme ouverte des données publiques françaises", + "nl": "Open platform van Franse publieke data", + "hr": "Otvorena platforma francuskih javnih podataka", + "pl": "Otwarta platforma francuskich danych publicznych", + "cs": "Otevřená platforma francouzských veřejných dat", + "ro": "Platforma deschisă de date publice franceze", + "ga": "Ardán oscailte sonraí poiblí na Fraince", + "es": "Plataforma abierta de datos públicos franceses", + "lv": "Francijas publisko datu atvērtā platforma", + "uk": "Відкрита платформа французьких публічних даних", + "en": "Open platform of French public data", + "hu": "A francia nyilvános adatok nyílt platformja", + "lt": "Atvira Prancūzijos viešųjų duomenų platforma", + "sl": "Odprta platforma francoskih javnih podatkov", + "de": "Offene Plattform für öffentliche Daten in Frankreich", + "el": "Ανοικτή πλατφόρμα γαλλικών δημόσιων δεδομένων", + "pt": "Plataforma aberta de dados públicos franceses", + "et": "Prantsusmaa avalike andmete avatud platvorm" + } + }, + "description": { + "de": "Sonde Station Schwimmbecken und Sonde Station Kapitänschaft Kontinuierliche Überwachung durch Ministationen \n\nAnalysen Stickstoffdioxid NO 2\n\nAnalysen Schwefeldioxid SO 2\n\nAnlayses Partikel PM 10", + "fi": "Uima-allasasemaluotain ja kapteenin asemaluotain Ministeriöiden jatkuva seuranta \n\nAnalyysit Typpidioksidi NO 2\n\nAnalyysit Rikkidioksidi SO 2\n\nAnlayses Hiukkaset PM 10", + "pt": "Sonda da estação da piscina e sonda da estação do capitão Monitoramento contínuo por miniestações \n\nAnálises de dióxido de azoto NO 2\n\nAnálises Dióxido de enxofre SO 2\n\nPartículas de Anlayses PM 10", + "bg": "Сонда за плувен басейн и сонда за капитанска станция Непрекъснато наблюдение от страна на министерствата \n\nАнализи Азотен диоксид NO 2\n\nАнализи Серен диоксид SO 2\n\nАнлази Частици PM 10", + "lt": "Baseinų stoties zondas ir kapitono stoties zondas Nuolatinis stebėjimas kasant \n\nAnalizuoja azoto dioksidą NO 2\n\nAnalizės Sieros dioksidas SO 2\n\nAnlayses dalelių PM 10", + "hr": "Sonda za bazensku stanicu i sonda za kapetansku stanicu Kontinuirano praćenje pomoću ministanica \n\nAnalize dušikovog dioksida NO 2\n\nAnalize sumpornog dioksida SO 2\n\nAnlayses Čestice PM 10", + "lv": "Peldbaseina stacijas zonde un kapteiņa stacijas zonde Nepārtraukta uzraudzība ar ministacijām \n\nAnalizē slāpekļa dioksīdu NO 2\n\nAnalizē sēra dioksīdu SO 2\n\nAnlayses Daļiņas PM 10", + "fr": "Sonde Station Piscine et sonde station capitainerie Surveillance continue par ministations \n\nAnalyses Dioxyde d'azote NO 2\n\nAnalyses Dioxyde de soufre SO 2\n\nAnlayses Particules PM 10", + "hu": "Úszómedence-állomás szonda és kapitány-állomás szonda Folyamatos megfigyelés miniállomásokkal \n\nElemzi a nitrogén-dioxidot NO 2\n\nElemzések Kén-dioxid SO 2\n\nAnlayses Részecskék PM 10", + "uk": "Зонд станції басейну та зонд станції капітана Безперервний моніторинг міністанціями \n\nАналізи Діоксид азоту NO 2\n\nАналізи діоксиду сірки SO 2\n\nАнлейси Частинки PM 10", + "sk": "Sonda bazénovej stanice a sonda kapitánskej stanice Nepretržité monitorovanie ministáciami \n\nAnalýza oxidu dusičitého NO 2\n\nAnalýza oxidu siričitého SO 2\n\nAnlayses Častice PM 10", + "sl": "Sonda za bazensko postajo in sonda za kapitanovo postajo Neprekinjeno spremljanje z mini postajami \n\nAnalize dušikovega dioksida NO 2\n\nAnaliza žveplovega dioksida SO 2\n\nAnlayses Delci PM 10", + "ga": "Snámha probe stáisiún linn snámha agus probe stáisiún captaen Monatóireacht leanúnach ag ministations \n\nAnailísí Dé-ocsaíd nítrigine NÍL 2\n\nAnailísí Dé-ocsaíd sulfair SO 2\n\nAnlayses Cáithníní PM 10", + "sv": "Simbassängsstationssond och kaptensstationssond Kontinuerlig övervakning av ministationer \n\nAnalyserar kvävedioxid NO 2\n\nAnalyser av svaveldioxid SO 2\n\nAnlag Partiklar PM 10", + "el": "Έλεγχος σταθμού πισίνας και έλεγχος σταθμού καπετάνιου Συνεχής παρακολούθηση από υπουργεία \n\nΑναλύσεις Διοξείδιο του αζώτου NO 2\n\nΑναλύσεις Διοξείδιο του θείου SO 2\n\nΑναλώσεις Σωματίδια PM 10", + "mt": "Sonda tal-istazzjon tal-pixxina u sonda tal-istazzjon tal-kaptan Monitoraġġ kontinwu permezz ta' ministations \n\nAnaliżi tad-diossidu tan-nitroġenu NO 2\n\nAnaliżi tad-diossidu tal-kubrit SO 2\n\nAnlayses ", + "en": "Swimming pool station probe and captain's station probe Continuous monitoring by ministations \n\nAnalyses Nitrogen dioxide NO 2\n\nAnalyses Sulphur dioxide SO 2\n\nAnlayses Particles PM 10", + "it": "Sonda della stazione della piscina e sonda della stazione del capitano Monitoraggio continuo dalle ministazioni \n\nAnalizza il biossido di azoto NO 2\n\nAnalizza il biossido di zolfo SO 2\n\nParticelle di ", + "es": "Sonda de la estación de la piscina y sonda de la estación del capitán Monitoreo continuo por miniestaciones \n\nAnálisis de dióxido de nitrógeno NO 2\n\nAnálisis del dióxido de azufre SO 2\n\nAnlayses Partí", + "et": "Ujumisbasseini jaama sond ja kapteni jaama sond Pidev seire ministations \n\nAnalüüsid Lämmastikdioksiid NO 2\n\nAnalüüsib vääveldioksiidi SO 2\n\nAnlayses Osakesed PM 10", + "cs": "Sonda pro bazénovou stanici a kapitánská sonda Kontinuální monitorování ministanicemi \n\nAnalýzy oxidu dusičitého NO 2\n\nAnalýzy oxidu siřičitého SO 2\n\nAnlayses Částice PM 10", + "pl": "Sonda do stacji basenowej i sonda do stacji kapitana Ciągłe monitorowanie przez ministacje \n\nAnalizy dwutlenku azotu NO 2\n\nAnalizy dwutlenku siarki SO 2\n\nAnlayses Cząstki PM 10", + "ro": "Sonda stației de înot și sonda stației căpitanului Monitorizare continuă prin ministații \n\nAnalizează dioxidul de azot NO 2\n\nAnalizează dioxidul de sulf SO 2\n\nAnlayses Particule PM 10", + "da": "Swimmingpool station sonde og kaptajnens station sonde Kontinuerlig overvågning af ministationer \n\nAnalyser Nitrogendioxid NO 2\n\nAnalyser svovldioxid SO 2\n\nAnlæg Partikler PM 10", + "nl": "De sonde van het zwembadpost en de sonde van het kapiteinspost Ononderbroken controle door ministations \n\nAnalyses Stikstofdioxide NO 2\n\nAnalyses Zwaveldioxide SO 2\n\nAnlayses Deeltjes PM 10" + }, + "landing_page": [ + { + "resource": "https://data.laregion.fr/explore/dataset/pln-air-donnees-2021/" + } + ], + "publisher": { + "resource": "https://www.data.gouv.fr/organizations/5a153f5688ee3829e2fbf39f", + "name": "Région Occitanie / Pyrénées Méditerranée", + "type": "Organization", + "homepage": "https://www.laregion.fr/" + }, + "modified": "2024-05-07T13:14:38", + "index": "dataset", + "id": "https-data-laregion-fr-explore-dataset-pln-air-donnees-2021-", + "title": { + "de": "PLN 2021 AIR-Qualität", + "fi": "PLN 2021 Laatu Vuotuinen täytäntöönpanokertomus", + "pt": "RAE de qualidade de 2021 em PLN", + "bg": "PLN 2021 Качествен ГДИ", + "lt": "2021 m. PLN kokybės MĮA", + "lv": "PLN 2021. gada kvalitātes GĪZ", + "hr": "Godišnje izvješće o kvaliteti za 2021. za PLN", + "fr": "PLN 2021 Qualité AIR", + "hu": "PLN 2021 Minőségi ÉVJ", + "uk": "PLN 2021 Quality AIR", + "sk": "ZVZ kvality za rok 2021 v PLN", + "sl": "Kvalitetno letno poročilo o izvajanju za leto 2021 v PLN", + "ga": "PLN 2021 Cáilíocht AIR", + "sv": "PLN 2021 Luftfart av hög kvalitet", + "el": "PLN 2021 Ποιοτικός αέρας", + "mt": "PLN 2021 AIR tal-Kwalità", + "en": "PLN 2021 Quality AIR", + "it": "PLN 2021 ARIA di qualità", + "es": "PLN 2021 AIR de calidad", + "et": "2021. aasta kvaliteediaruanne Poola zlottides", + "cs": "PLN 2021 Quality AIR", + "pl": "PLN 2021 Jakość AIR", + "ro": "PLN 2021 AIR Calitate", + "da": "PLN 2021 kvalitet AIR", + "nl": "PLN 2021 Kwaliteit AIR" + }, + "issued": "2024-05-07T13:14:38", + "distributions": [ + { + "license": { + "resource": "https://www.etalab.gouv.fr/licence-ouverte-open-licence", + "id": "https://www.etalab.gouv.fr/licence-ouverte-open-licence", + "label": "https://www.etalab.gouv.fr/licence-ouverte-open-licence" + }, + "format": { + "format_types": [ + { + "id": "tabular", + "label": { + "en": "Tabular" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ], + "resource": "http://publications.europa.eu/resource/authority/file-type/CSV", + "id": "CSV", + "label": "CSV" + } + }, + { + "license": { + "resource": "https://www.etalab.gouv.fr/licence-ouverte-open-licence", + "id": "https://www.etalab.gouv.fr/licence-ouverte-open-licence", + "label": "https://www.etalab.gouv.fr/licence-ouverte-open-licence" + }, + "format": { + "format_types": [ + { + "id": "structured", + "label": { + "en": "Structured" + } + } + ], + "resource": "http://publications.europa.eu/resource/authority/file-type/JSON", + "id": "JSON", + "label": "JSON" + } + } + ] + }, + { + "catalog": { + "id": "data-gov-uk", + "title": { + "nl": "data.gov.uk", + "mt": "data.gov.uk", + "da": "data.gov.uk", + "lv": "data.gov.uk", + "es": "data.gov.uk", + "pl": "data.gov.uk", + "et": "data.gov.uk", + "hu": "data.gov.uk", + "cs": "data.gov.uk", + "it": "data.gov.uk", + "ga": "data.gov.uk", + "ro": "data.gov.uk", + "el": "data.gov.uk", + "hr": "data.gov.uk", + "fi": "data.gov.uk", + "pt": "data.gov.uk", + "sk": "data.gov.uk", + "bg": "данни.gov.uk", + "sl": "data.gov.uk", + "sv": "data.gov.uk", + "fr": "data.gov.uk", + "en": "data.gov.uk", + "de": "data.gov.uk", + "uk": "data.gov.uk", + "lt": "data.gov.uk" + } + }, + "description": { + "hu": "Az 1995-ös környezetvédelmi törvény (Environment Act 1995) értelmében törvényes kötelességünk Sheffield helyi levegőminőségének kezelése. Van egy levegőminőségi cselekvési tervünk arra vonatkozóan, ho", + "fi": "Meillä on lakisääteinen velvollisuus hallita paikallista ilmanlaatua Sheffieldissä vuoden 1995 ympäristölain nojalla. Meillä on ilmanlaatua koskeva toimintasuunnitelma siitä, miten puutumme ilmanlaatu", + "ro": "Avem o datorie statutară de a gestiona calitatea aerului local în Sheffield în conformitate cu Legea mediului 1995. Avem un plan de acțiune privind calitatea aerului pentru modul în care vom aborda pr", + "lt": "Mes turime įstatyminę pareigą valdyti vietinę oro kokybę Šefilde pagal 1995 m. Turime oro kokybės veiksmų planą, kaip spręsime Šefildo oro kokybės problemas. Veiksmų planas susijęs su mūsų oro kokybės", + "sl": "Imamo zakonsko dolžnost, da upravljamo lokalno kakovost zraka v Sheffieldu v skladu z zakonom o okolju iz leta 1995. Imamo akcijski načrt za kakovost zraka za reševanje težav s kakovostjo zraka v Shef", + "de": "Wir sind gesetzlich verpflichtet, die lokale Luftqualität in Sheffield gemäß dem Environment Act 1995 zu verwalten. Wir haben einen Aktionsplan für Luftqualität, wie wir Probleme mit der Luftqualität ", + "nl": "We hebben een wettelijke plicht om de lokale luchtkwaliteit in Sheffield te beheren op grond van de Environment Act 1995. We hebben een luchtkwaliteitsactieplan voor hoe we problemen met de luchtkwali", + "hr": "Imamo zakonsku dužnost upravljati lokalnom kvalitetom zraka u Sheffieldu prema Zakonu o okolišu iz 1995. godine. Imamo akcijski plan za kvalitetu zraka kako ćemo riješiti probleme s kvalitetom zraka u", + "sk": "Máme zákonnú povinnosť riadiť kvalitu miestneho ovzdušia v Sheffielde podľa zákona o životnom prostredí z roku 1995. Máme akčný plán kvality ovzdušia, ako budeme riešiť problémy s kvalitou ovzdušia v ", + "cs": "Máme zákonnou povinnost řídit místní kvalitu ovzduší v Sheffieldu podle zákona o životním prostředí z roku 1995. Máme akční plán kvality ovzduší, jak budeme řešit problémy s kvalitou ovzduší v Sheffie", + "mt": "Għandna d-dmir statutorju li nimmaniġġjaw il-kwalità tal-arja lokali f’Sheffield skont l-Att dwar l-Ambjent tal-1995. Għandna Pjan ta’ Azzjoni dwar il-Kwalità tal-Arja għal kif se nindirizzaw il-probl", + "fr": "Nous avons l'obligation légale de gérer la qualité de l'air à Sheffield en vertu de l'Environment Act 1995. Nous avons un plan d'action sur la qualité de l'air pour résoudre les problèmes de qualité d", + "sv": "Vi har en lagstadgad skyldighet att hantera den lokala luftkvaliteten i Sheffield enligt miljölagen 1995. Vi har en handlingsplan för luftkvalitet för hur vi ska ta itu med problemen med luftkvalitete", + "pl": "Mamy ustawowy obowiązek zarządzania lokalną jakością powietrza w Sheffield na mocy ustawy o środowisku z 1995 r. Mamy plan działania na rzecz jakości powietrza określający, w jaki sposób będziemy rozw", + "da": "Vi har en lovbestemt pligt til at styre den lokale luftkvalitet i Sheffield i henhold til miljøloven 1995. Vi har en luftkvalitetshandlingsplan for, hvordan vi vil tackle problemer med luftkvaliteten ", + "ga": "Tá dualgas reachtúil orainn cáilíocht an aeir áitiúil a bhainistiú i Sheffield faoin Acht Comhshaoil 1995. Tá Plean Gníomhaíochta um Cháilíocht an Aeir againn maidir leis an gcaoi a rachaimid i ngleic", + "es": "Tenemos el deber legal de gestionar la calidad del aire local en Sheffield bajo la Ley de Medio Ambiente de 1995. Tenemos un Plan de Acción de Calidad del Aire sobre cómo abordaremos los problemas con", + "et": "Meil on seadusjärgne kohustus juhtida kohalikku õhukvaliteeti Sheffieldis vastavalt 1995. aasta keskkonnaseadusele. Meil on õhukvaliteedi tegevuskava selle kohta, kuidas me Sheffieldis õhukvaliteediga", + "en": "We have a statutory duty to manage local air quality in Sheffield under the Environment Act 1995. We have an Air Quality Action Plan for how we will tackle problems with air quality in Sheffield. The ", + "pt": "Temos o dever estatutário de gerir a qualidade do ar local em Sheffield sob o Environment Act 1995. Temos um Plano de Ação para a Qualidade do Ar para resolver os problemas com a qualidade do ar em Sh", + "bg": "Ние имаме законово задължение да управляваме качеството на местния въздух в Шефилд съгласно Закона за околната среда от 1995 г. Имаме план за действие за качеството на въздуха за това как ще се справи", + "el": "Έχουμε εκ του νόμου καθήκον να διαχειριστούμε την τοπική ποιότητα του αέρα στο Σέφιλντ βάσει του νόμου για το περιβάλλον του 1995. Έχουμε ένα σχέδιο δράσης για την ποιότητα του αέρα για το πώς θα αντι", + "lv": "Mums ir likumā noteikts pienākums pārvaldīt vietējo gaisa kvalitāti Šefīldā saskaņā ar 1995. gada Vides likumu. Mums ir gaisa kvalitātes rīcības plāns par to, kā mēs risināsim gaisa kvalitātes problēm", + "uk": "Ми маємо статутний обов'язок керувати місцевою якістю повітря в Шеффілді відповідно до Закону про навколишнє середовище 1995 року. У нас є План дій щодо якості повітря, як ми будемо вирішувати проблем", + "it": "Abbiamo il dovere statutario di gestire la qualità dell'aria locale a Sheffield ai sensi dell'Environment Act 1995. Abbiamo un piano d'azione per la qualità dell'aria per come affronteremo i problemi " + }, + "publisher": { + "type": "Agent", + "name": "Sheffield City Council" + }, + "index": "dataset", + "id": "sheffield-air-quality-management-area", + "title": { + "hr": "Područje upravljanja kvalitetom zraka Sheffield", + "sl": "Sheffield Air Quality Management Area", + "sk": "Sheffieldská oblasť riadenia kvality ovzdušia", + "bg": "Област за управление на качеството на въздуха в Шефилд", + "sv": "Sheffields luftvårdsområde", + "fi": "Sheffieldin ilmanlaadun hallinta-alue", + "ro": "Zona de management al calității aerului Sheffield", + "pt": "Zona de Gestão da Qualidade do Ar de Sheffield", + "lt": "Šefildo oro kokybės valdymo zona", + "en": "Sheffield Air Quality Management Area", + "da": "Sheffield Air Quality Management Area", + "ga": "Limistéar Bainistíochta Cáilíochta Aeir Sheffield", + "fr": "Zone de gestion de la qualité de l'air de Sheffield", + "cs": "Oblast řízení kvality ovzduší v Sheffieldu", + "it": "Area di gestione della qualità dell'aria di Sheffield", + "pl": "Sheffield Obszar Zarządzania Jakością Powietrza", + "el": "Περιοχή διαχείρισης της ποιότητας του αέρα του Σέφιλντ", + "uk": "Шеффілдський район управління якістю повітря", + "lv": "Šefīldas gaisa kvalitātes pārvaldības zona", + "de": "Sheffield Air Quality Management Area", + "nl": "Sheffield Air Quality Management Area", + "es": "Área de Gestión de la Calidad del Aire de Sheffield", + "mt": "Żona ta’ Ġestjoni tal-Kwalità tal-Arja ta’ Sheffield", + "et": "Sheffieldi õhukvaliteedi juhtimise piirkond", + "hu": "Sheffield levegőminőség-kezelési terület" + }, + "distributions": [ + { + "format": { + "id": "WMS_SRVC", + "label": "WMS", + "resource": "http://publications.europa.eu/resource/authority/file-type/WMS_SRVC", + "format_types": [ + { + "id": "structured", + "label": { + "en": "Structured" + } + }, + { + "id": "geographical", + "label": { + "en": "Geographical" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + } + }, + { + "format": { + "id": "GEOJSON", + "label": "GeoJSON", + "resource": "http://publications.europa.eu/resource/authority/file-type/GEOJSON", + "format_types": [ + { + "id": "structured", + "label": { + "en": "Structured" + } + }, + { + "id": "geographical", + "label": { + "en": "Geographical" + } + }, + { + "id": "textual", + "label": { + "en": "Textual" + } + } + ] + } + } + ] + } + ], + "facets": [] + } +} From 099257a9863f986c2a89ff6ad7f66a1f04035d1c Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:02:03 +0100 Subject: [PATCH 22/31] feat: search --updated-since asks CKAN portals, NASA CMR and ArcGIS Hub for recent records only, so more of what they return passes the filter --- examples/relevance/record.rs | 1 + src/bench.rs | 1 + src/cache.rs | 31 ++++++++++++++++++++++--------- src/find.rs | 1 + src/search.rs | 17 ++++++++++++++--- src/sources.rs | 6 ++++++ src/sources/arcgis.rs | 14 +++++++++++--- src/sources/ckan.rs | 29 ++++++++++++++++++++++++++++- src/sources/cmr.rs | 15 ++++++++++++--- 9 files changed, 96 insertions(+), 19 deletions(-) diff --git a/examples/relevance/record.rs b/examples/relevance/record.rs index 815ed75..842f46b 100644 --- a/examples/relevance/record.rs +++ b/examples/relevance/record.rs @@ -52,6 +52,7 @@ pub fn run(queries: &[Query], args: &[String]) -> Result<()> { sources, per_source: PER_SOURCE, forced: true, + since: None, }); search(&services, false, &plan, &ProgressBar::hidden(), None) }; diff --git a/src/bench.rs b/src/bench.rs index 9a7a4e7..eec1dc8 100644 --- a/src/bench.rs +++ b/src/bench.rs @@ -90,6 +90,7 @@ pub fn run( selection.per_source.unwrap_or(PER_SOURCE_DEFAULT), ), forced: true, + since: None, }); let outcomes = search(&services, true, &plan, &progress, None); for o in &outcomes { diff --git a/src/cache.rs b/src/cache.rs index fbf5a7f..44ef008 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -405,10 +405,19 @@ fn trim_files( /// A short, stable file name for a query. FNV-1a, not for security: it only /// has to be the same on every run and spread keys over the alphabet. -pub fn query_key(source: &str, query: &str, limit: usize) -> String { +/// `since` is part of the key because some sources filter by it. +pub fn query_key( + source: &str, + query: &str, + limit: usize, + since: Option<&str>, +) -> String { let normalized = query.split_whitespace().collect::>().join(" "); - let material = + let mut material = format!("{source}\u{1f}{}\u{1f}{limit}", normalized.to_lowercase()); + if let Some(since) = since { + material = format!("{material}\u{1f}{since}"); + } let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for byte in material.bytes() { hash ^= u64::from(byte); @@ -603,18 +612,22 @@ mod tests { } #[test] - fn query_keys_ignore_case_and_spacing_but_not_limit() { + fn query_keys_ignore_case_and_spacing_but_not_limit_or_date() { assert_eq!( - query_key("hf", "Climate Data", 10), - query_key("hf", "climate data", 10) + query_key("hf", "Climate Data", 10, None), + query_key("hf", "climate data", 10, None) + ); + assert_ne!( + query_key("hf", "climate", 10, None), + query_key("hf", "climate", 20, None) ); assert_ne!( - query_key("hf", "climate", 10), - query_key("hf", "climate", 20) + query_key("hf", "climate", 10, None), + query_key("kg", "climate", 10, None) ); assert_ne!( - query_key("hf", "climate", 10), - query_key("kg", "climate", 10) + query_key("hf", "climate", 10, None), + query_key("hf", "climate", 10, Some("2024-01-01")) ); } } diff --git a/src/find.rs b/src/find.rs index c9c279c..4d60f86 100644 --- a/src/find.rs +++ b/src/find.rs @@ -108,6 +108,7 @@ pub fn run_search(request: &Request<'_>, out: &Out) -> Result<()> { }, )), forced: offline || !selection.only.is_empty(), + since: wanted.since.clone(), }); if plan.sources.is_empty() { return Err(Error::NoneSelected.into()); diff --git a/src/search.rs b/src/search.rs index 58cb793..00fe2e5 100644 --- a/src/search.rs +++ b/src/search.rs @@ -53,6 +53,9 @@ pub struct Plan { /// The user named these sources, or `--offline` costs no request, so /// recent outages do not skip them. pub forced: bool, + /// `--updated-since`, a full day, for the sources that can ask for it + /// themselves through [`Ctx::since`]. + pub since: Option, } #[derive(Debug)] @@ -237,7 +240,9 @@ fn spawn( sender.clone(), ); std::thread::spawn(move || { - let outcome = one(&services.ctx(refresh), &plan, source); + let mut ctx = services.ctx(refresh); + ctx.since = plan.since.as_deref(); + let outcome = one(&ctx, &plan, source); if !matches!(outcome.status, Status::NeedsKey(_)) { progress.inc(1); } @@ -310,7 +315,12 @@ fn one(ctx: &Ctx<'_>, plan: &Plan, source: &'static Source) -> Outcome { } let cacheable = source.persist && !source.is_catalog(); - let key = query_key(source.id, &plan.query, plan.per_source); + let key = query_key( + source.id, + &plan.query, + plan.per_source, + plan.since.as_deref(), + ); let cached = if cacheable { ctx.cache.load::>(Kind::Query, &key, QUERY_TTL) } else { @@ -474,11 +484,12 @@ mod tests { sources: vec![source], per_source: 10, forced, + since: None, } } fn query_entry(source: &Source) -> String { - query_key(source.id, "rain", 10) + query_key(source.id, "rain", 10, None) } #[test] diff --git a/src/sources.rs b/src/sources.rs index 46b3465..e066b01 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -96,6 +96,11 @@ pub struct Ctx<'a> { pub creds: &'a Credentials, pub cache: &'a Cache, pub refresh: bool, + /// The day `--updated-since` asks for. An adapter passes it on only where + /// the source filters on a date never earlier than the one dataseek + /// reads, so the source drops nothing the filter on the merged list + /// would keep (ADR 0020). + pub since: Option<&'a str>, stop: &'a AtomicBool, } @@ -371,6 +376,7 @@ impl Services { creds: &self.creds, cache: &self.cache, refresh, + since: None, stop: &self.stop, } } diff --git a/src/sources/arcgis.rs b/src/sources/arcgis.rs index 00d80ff..dbaa018 100644 --- a/src/sources/arcgis.rs +++ b/src/sources/arcgis.rs @@ -17,6 +17,11 @@ //! Agreement, August 2025). //! An item's `type` is its one format, a file type ("CSV") or a service //! ("Feature Service"; ArcGIS REST item types, October 2026). +//! `--updated-since` goes out as the CQL filter `modified >= 'YYYY-MM-DD'`, +//! which matches as many items as the same day in epoch milliseconds. The +//! queryables list gives `modified` the path `properties.created`, but the +//! filter compares `modified`: 13 of 100 filtered items were created +//! earlier, none modified earlier (probes, October 2026). use serde_json::Value; @@ -33,12 +38,15 @@ pub fn search( query: &str, limit: usize, ) -> Result, SourceError> { - let body = ctx + let mut call = ctx .http .get("https://hub.arcgis.com/api/search/v1/collections/dataset/items") .query("q", query) - .query("limit", limit) - .json()?; + .query("limit", limit); + if let Some(day) = ctx.since { + call = call.query("filter", format!("modified >= '{day}'")); + } + let body = call.json()?; parse(&body, limit) } diff --git a/src/sources/ckan.rs b/src/sources/ckan.rs index 0620004..01dfa97 100644 --- a/src/sources/ckan.rs +++ b/src/sources/ckan.rs @@ -52,6 +52,13 @@ //! "SHP", "JPG", "BIN", or empty on GovData; B2FIND sends no resources and //! so no formats (probes, October 2026). `file_format` turns the spellings //! into one name per format. +//! +//! `--updated-since` goes out as a `metadata_modified` range in `fq`, which +//! all six portals honor. The date a record shows is never later than its +//! `metadata_modified` (600 records on data.gov.uk, Canada and data.gov.au), +//! so the range drops nothing the filter on the merged list keeps; on +//! GovData, HDX and B2FIND it drops nothing at all, since every record there +//! was re-harvested after 2024 (probes, October 2026). use serde_json::Value; @@ -122,12 +129,22 @@ pub fn search( .http .get(&format!("{}/package_search", portal.api)) .query("q", query.replace(':', " ")) - .query("fq", "dataset_type:dataset") + .query("fq", filter_query(ctx.since)) .query("rows", limit) .json()?; parse(portal, &body, limit) } +fn filter_query(since: Option<&str>) -> String { + let datasets = "dataset_type:dataset"; + since.map_or_else( + || datasets.to_owned(), + |day| { + format!("{datasets} AND metadata_modified:[{day}T00:00:00Z TO *]") + }, + ) +} + pub(super) fn parse( portal: &Portal, body: &Value, @@ -680,6 +697,16 @@ mod tests { ); } + #[test] + fn a_date_asks_for_records_modified_since() { + assert_eq!(filter_query(None), "dataset_type:dataset"); + assert_eq!( + filter_query(Some("2024-07-01")), + "dataset_type:dataset AND \ + metadata_modified:[2024-07-01T00:00:00Z TO *]" + ); + } + #[test] fn sizes_in_units_become_bytes() { assert_eq!(bytes_in("23063374 Bytes"), Some(23_063_374)); diff --git a/src/sources/cmr.rs b/src/sources/cmr.rs index 1c7a765..5c05472 100644 --- a/src/sources/cmr.rs +++ b/src/sources/cmr.rs @@ -27,6 +27,12 @@ //! The formats are each `FileDistributionInformation` entry's `Format`, free //! text such as "HDF5", "netCDF-4" or "HDF-EOS5" (UMM-C 1.18.6, probes, //! October 2026). +//! +//! `--updated-since` goes out as `updated_since`, which compares the +//! revision date (CMR search API, October 2026). In 200 "sea ice" records +//! no `DataDates` update was later than the revision, so it drops nothing +//! the filter on the merged list keeps; it cut that query from 3,387 +//! matches to 957 (probes, October 2026). use serde_json::Value; @@ -39,13 +45,16 @@ pub fn search( query: &str, limit: usize, ) -> Result, SourceError> { - let body = ctx + let mut call = ctx .http .get("https://cmr.earthdata.nasa.gov/search/collections.umm_json") .header("Client-Id", "dataseek") .query("keyword", keyword(query)) - .query("page_size", limit.clamp(1, 2000)) - .json()?; + .query("page_size", limit.clamp(1, 2000)); + if let Some(day) = ctx.since { + call = call.query("updated_since", format!("{day}T00:00:00Z")); + } + let body = call.json()?; parse(&body, limit) } From a7200cd93909cd1184979f83c0a617edf432d32d Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:08:41 +0100 Subject: [PATCH 23/31] doc: ADR 0020 on search filters, the contract and agent skill for --license, --updated-since, --format and --min-sources, and inspect on Dataverse and DOI links --- README.md | 1 + .../0020-filters-run-on-the-merged-list.md | 36 +++++++++++++++++++ docs/adr/README.md | 1 + docs/reference/contract.md | 6 ++-- docs/synthesis/capabilities.md | 2 +- skills/dataseek/SKILL.md | 2 +- skills/dataseek/references/cli.md | 8 ++--- skills/dataseek/references/inspect.md | 8 +++-- skills/dataseek/references/search.md | 28 ++++++++++++--- src/cli.rs | 4 ++- 10 files changed, 78 insertions(+), 18 deletions(-) create mode 100644 docs/adr/0020-filters-run-on-the-merged-list.md diff --git a/README.md b/README.md index f8776f1..d88d4be 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ uvx dataseek search sea surface temperature dsk search sea surface temperature # every default source, merged and ranked dsk search mnist -s huggingface,kaggle # only these sources dsk search inflation -c economics,finance # only these categories +dsk search rainfall --license cc-by --format csv # only CC BY datasets offered as CSV dsk search census --json | jq -r '.results[].url' # one URL per line, for scripts dsk sources # every source, its protocol, key and docs dsk inspect https://zenodo.org/records/13135140 # a page's metadata and the files it lists diff --git a/docs/adr/0020-filters-run-on-the-merged-list.md b/docs/adr/0020-filters-run-on-the-merged-list.md new file mode 100644 index 0000000..fd76067 --- /dev/null +++ b/docs/adr/0020-filters-run-on-the-merged-list.md @@ -0,0 +1,36 @@ +# ADR 0020: Filters run on the merged list; a source filters only where it is never stricter + +- Status: accepted +- Date: 2026-10-20 + +## Context + +An agent or a user often knows more than the words of a query: the data must be openly licensed, recent, offered as CSV, or confirmed by more than one source. Putting those constraints in the query does not work, because every source treats them as more words to match. Each source has its own filter syntax or none at all: CKAN takes Solr `fq` clauses, NASA CMR an `updated_since` parameter, ArcGIS Hub a CQL `filter`, Dataverse `fq` over its own Solr fields, and most of the 76 sources nothing. The fields disagree too: licenses arrive as SPDX ids, Creative Commons deed URLs, EU vocabulary URIs or free text ("CC-By Attribution 4.0 International"), and a record's date is a different field on every source. + +## Decision + +- `search` takes `--license`, `--updated-since`, `--format` and `--min-sources`, and applies them to the merged, ranked list before `--limit` cuts it. A merged dataset passes on a field any of its sources stated. A dataset that does not state a field never passes a filter on it. +- Every source's license is read as an SPDX id at the source boundary (`src/license.rs`): `CC-BY-4.0` however the source spelled it, placeholders such as `notspecified` dropped, anything unrecognized kept as written. `--license cc-by` matches the family, every version and port of CC BY but not CC BY-SA. +- `--updated-since` takes a year, a month or a day and compares at the precision a record states, so a dataset dated only `2024` counts as updated after `2024-06-01`. +- File formats are read as one name per format (`CSV`, `NETCDF`, `GEOTIFF`) from the sources that list them: CKAN portals, data.europa.eu, ArcGIS Hub, NASA CMR and data.gov. +- With any filter set, each source is asked for 30 results instead of 10, since most of what comes back is dropped. `--per-source` still overrides it. +- A source is handed a filter only where its own filter is never stricter than dataseek's, so it drops nothing the merged-list filter would keep. Today that is `--updated-since` on CKAN (`metadata_modified`), CMR (`updated_since`) and ArcGIS Hub (`modified`). The query cache key includes the day. +- `--json` reports `filtered_out`, the merged datasets the filters dropped, and `total` counts the ones that passed. + +## Consequences + +- One filter means the same thing for every source, whatever its API offers, and a source with no filter at all is filtered just as well. +- A filter cannot find what a source did not return: a search for recent CSV files sees only the 30 best matches of each source, filtered. A source-side filter widens that window only where it is safe. +- Licenses are sparse: 315 of 978 merged results over three queries name one, so a license filter drops most of a search. The summary line says how many matched without the filters, so an empty result is not mistaken for no data. +- Pushing a filter down to another source needs evidence that its field is never stricter than the one dataseek reads, recorded in that adapter's header. + +## Evidence + +Probes of the live sources, October 2026, recorded in the adapter headers: + +- CKAN: across 600 records on data.gov.uk, Open Canada and data.gov.au, no record's displayed date was later than its `metadata_modified`. All six portals accept the range in `fq`. `res_format` matches the publisher's free text exactly ("CSV", "csv", ".csv"), so the format stays on the merged list. +- CMR: in 200 "sea ice" collections no `DataDates` update was later than the revision date `updated_since` compares; the parameter cut that query from 3,387 matches to 957. +- ArcGIS Hub: the CQL filter on `modified` compares the modification date, although the queryables list gives it the path `properties.created`. Of 100 filtered items, 13 were created before the cut-off and none modified before it. +- Dataverse is left out: `dateSort`, the only date field `fq` reaches, is the publication date, and 2 of the 54 Harvard records updated since 2024 were published earlier, so it would drop them. +- data.europa.eu is left out: `minDate` filters on `modified` by default, while dataseek falls back to `issued`, and 109 of 200 "air quality" records have no `modified`. +- Licenses: no source filters on SPDX ids, so no license filter is pushed down. Of 978 merged results for "sea surface temperature", "air quality" and "unemployment rate", 315 name a license. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2920ee2..5ab90e5 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -41,3 +41,4 @@ A decision that constrains future work lives here, once, and is cited from where | [0017](0017-release-builds-on-a-platform-matrix.md) | Release builds run on a per-platform matrix | accepted | | [0018](0018-a-search-never-waits-for-a-catalog-download.md) | A search never waits for a catalog download it can do without | accepted | | [0019](0019-stop-waiting-past-a-quorum.md) | Past 90% of the sources, the rest get one second | accepted | +| [0020](0020-filters-run-on-the-merged-list.md) | Filters run on the merged list; a source filters only where it is never stricter | accepted | diff --git a/docs/reference/contract.md b/docs/reference/contract.md index 710f962..07f991a 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -13,7 +13,7 @@ The version lives only in `Cargo.toml`. Clap reads it via `#[command(version)]`, - `--json`, `--color=auto|always|never`, `--no-color`, `--plain`, `--no-progress` - `--cache-dir DIR` and `--connect-timeout SECS`, each with a `DATASEEK_*` variable; the cache size budget has only its variable, `DATASEEK_CACHE_MAX_MB` -`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` or `--include` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). +`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` or `--include` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). `--license`, `--updated-since`, `--format` and `--min-sources` filter the merged list before `-n` cuts it, and a dataset that does not state a field never passes a filter on it; with any of them set, `--per-source` defaults to 30 instead of 10 ([ADR 0020](../adr/0020-filters-run-on-the-merged-list.md)). A license is an SPDX id or a family (`cc-by`), a date is `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, and a format is one of the names results carry in `formats` (`CSV`, `NETCDF`, ...), matched without regard to case or spelling (`text/csv` is `CSV`). `-v` is verbose, never version. `--color` follows the ecosystem standard used by git, ripgrep, and fd: @@ -58,7 +58,7 @@ This is why `Cargo.toml` denies `print_stdout` and `print_stderr`: a stray `prin ## JSON -Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `search --json` carries `complete`, false when the search stopped waiting for a source or a catalog was still downloading, so its results may lack what those would add. It also carries `total`, how many merged datasets matched; `results` holds the first `-n` of them, so a full list with a larger `total` says more exist. `completion` and `man` print their script and page whatever the flag when stdout is not a terminal. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. +Every `--json` output is one object with a `schema` tag naming its shape and version (`dataseek-search/1`, `dataseek-sources/1`, `dataseek-doctor/1`, ...). A key that changes meaning or disappears bumps the tag; a new key does not. On a terminal the JSON is indented, in a pipe it is one line. To pick fields, pipe it into `jq`. A failed run prints its error event on stderr and nothing on stdout, and `jq` exits 0 on empty input, so a script runs the pipeline under `set -o pipefail` (bash, zsh) or checks `$pipestatus[1]` (fish) to see the failure. `search --json` carries `complete`, false when the search stopped waiting for a source or a catalog was still downloading, so its results may lack what those would add. It also carries `total`, how many merged datasets matched and passed the filters, and `filtered_out`, how many the filters dropped; `results` holds the first `-n` of them, so a full list with a larger `total` says more exist. A result's `license` is an SPDX id where the source's spelling maps to one, and `formats`, absent when empty, lists its file formats. `completion` and `man` print their script and page whatever the flag when stdout is not a terminal. `tests/snapshots/` freezes the search, sources, doctor, cache info, inspect, exit-codes and error-event shapes. `inspect --json` (`dataseek-inspect/1`) prints `dataset`, the page's own JSON-LD node as the page wrote it, and beside it `files`, dataseek's reading of the file list, so a `files` key on the page is never overwritten. Every string of the page's metadata, keys included, has its control characters (C0 other than newline and tab, DEL, and C1) replaced by a space before it is printed, as text or as JSON, so a page cannot drive the terminal that shows it. @@ -69,7 +69,7 @@ Every `--json` output is one object with a `schema` tag naming its shape and ver - **Protocol.** Requests naming revision `2026-07-28` in `_meta` are served statelessly, with `server/discover`; clients that open with `initialize` get revision `2025-11-25` or `2025-06-18`. A request naming any other revision gets `-32022` with the supported list. - **stdout** carries one JSON-RPC message per line and nothing else. stderr carries the server's own status line, as plain text, and its calls' narration, as `dataseek-events/1` lines. `-q`, `-v`, `--cache-dir` and `--connect-timeout` given to `dataseek mcp` reach every call. - **Include.** `--include IDS` given to `dataseek mcp` asks those sources, opt-in ones included, in every search that names no sources of its own; a call that names `source` or `include` is left alone. -- **Tools.** Each tool's input schema is its command's `help --json` entry: one property per flag, named by its long form, typed, with its possible values and default; `search`'s words are one `query` string. Each description is the flag's help worded for a call: a list argument is a JSON array rather than comma-separated, source ids come from the `sources` tool, and `timeout` states its 1 to 300 second bounds. A call runs `dataseek --json` with those flags, and the result carries the object that prints as `structuredContent` and again as text. +- **Tools.** Each tool's input schema is its command's `help --json` entry: one property per flag, named by its long form, typed, with its possible values and default; `search`'s words are one `query` string. Each description is the flag's help worded for a call: a list argument is a JSON array rather than comma-separated, source ids come from the `sources` tool, and `timeout` states its 1 to 300 second bounds. `updated-since` carries the `pattern` the command line accepts and an example day. A call runs `dataseek --json` with those flags, and the result carries the object that prints as `structuredContent` and again as text. - **Failures.** A failed call is a result with `isError: true`: the text is the `Error:`, `Cause:` and `Try:` lines the command line prints, and `structuredContent` the error event. A bad or missing argument is such a failure too, since the model can fix it, and so is a call made while four are already running. A JSON-RPC error answers the rest: a line that is not JSON in UTF-8 gets `-32700`, and the session goes on; a request without a string method, or reusing the id of a call still running, `-32600`; an unknown method `-32601`; an unknown tool or `arguments` that is not an object `-32602`; a server fault `-32603`, whose message says what the command left. A notification is never answered. - **Deadline.** Every search runs with `--timeout`, the argument or its default of 20 seconds, and with the command line's rule for stragglers: past 90% of the sources asked, the rest get one more second unless `source` names them ([ADR 0019](../adr/0019-stop-waiting-past-a-quorum.md)). A `timeout` outside 1 to 300 seconds is refused, so every call ends in a time a client waits for; the schema says so with `minimum` and `maximum`, as it does for every ranged integer. - **Keys** come from the environment and `credentials.toml`, as everywhere ([ADR 0009](../adr/0009-keys-and-contact-address.md)); no tool takes one as an argument. diff --git a/docs/synthesis/capabilities.md b/docs/synthesis/capabilities.md index e58ffe4..bef830e 100644 --- a/docs/synthesis/capabilities.md +++ b/docs/synthesis/capabilities.md @@ -1,6 +1,6 @@ # What each source offers for the next features -The filter and file-list features planned for dataseek (server-side filters by license, update date, format and resource type; a resolve step that lists a dataset's files without downloading them; paging past the first page; total hit counts; links from a dataset to the papers and datasets related to it; machine-readable metadata for `inspect`) depend on what each provider exposes. One row per registry id, as probed or read from the provider's documentation on 2026-10-06. A cell is the exact parameter, field or endpoint, or `none`. This file records only; none of these is implemented, because each needs new `Dataset` fields and CLI flags. +The filter and file-list features planned for dataseek (server-side filters by license, update date, format and resource type; a resolve step that lists a dataset's files without downloading them; paging past the first page; total hit counts; links from a dataset to the papers and datasets related to it; machine-readable metadata for `inspect`) depend on what each provider exposes. One row per registry id, as probed or read from the provider's documentation on 2026-10-06. A cell is the exact parameter, field or endpoint, or `none`. License, date and format filters now run on the merged list ([ADR 0020](../adr/0020-filters-run-on-the-merged-list.md)), and of the server-side filters below only the date filters of CKAN, CMR and ArcGIS Hub are used: the others match different license ids or file-type spellings, or a different date, so they would drop datasets the merged-list filter keeps. The rest of this file records only. Columns: **license**, **date** and **format** filters; **type** is a resource-type filter; **manifest** is a file list with names, sizes, checksums or download URLs; **paging** is the parameter and the deepest reachable result; **total** is a hit count; **related** is papers or datasets linked to a record; **machine** is Croissant, schema.org JSON-LD, DCAT or another structured record. Rows of one protocol module (CKAN, Dataverse, NADA, SDMX, STAC, Socrata, EBI) repeat the protocol's cells; a difference between portals is named in the cell. diff --git a/skills/dataseek/SKILL.md b/skills/dataseek/SKILL.md index ae03248..25baa11 100644 --- a/skills/dataseek/SKILL.md +++ b/skills/dataseek/SKILL.md @@ -69,7 +69,7 @@ Default when ambiguous: **Search**. A search the user will choose from runs Sear ## Search (default) -1. **Write one to three short queries**, two to four content words each, before calling anything. Most sources match every word, so a sentence finds fewer datasets than its keywords: "sea surface temperature" merged 328 results where "global monthly sea surface temperature dataset since 1980" merged 136 (2026-10-20). Years, regions and formats are filters to apply to the results, not query words. The rules and the evidence: `references/search.md`, Writing queries. +1. **Write one to three short queries**, two to four content words each, before calling anything. Most sources match every word, so a sentence finds fewer datasets than its keywords: "sea surface temperature" merged 328 results where "global monthly sea surface temperature dataset since 1980" merged 136 (2026-10-20). Licenses, dates and formats go in the `license`, `updated-since` and `format` arguments, not the query. The rules and the evidence: `references/search.md`, Writing queries. 2. **Narrow only on the user's words.** "Only on Kaggle" becomes `source` (those alone); "also check Kaggle" becomes `include` (beside every default source); a clear domain becomes `category`; a source flooding the list becomes `exclude`. The ids and the fourteen categories: `references/search.md`, Arguments. 3. **Call `search`** and read `results`, then `total`, `complete` and `sources[].status`. A `results` list as long as `limit` with a larger `total` means more exist. An empty `results` list from sources that answered is an answer, not a failure. 4. **Reformulate when fewer than about five results fit**: a synonym, the field's own term or acronym, one word dropped. Stop after three rounds and say what was tried. diff --git a/skills/dataseek/references/cli.md b/skills/dataseek/references/cli.md index 5784c34..c16108a 100644 --- a/skills/dataseek/references/cli.md +++ b/skills/dataseek/references/cli.md @@ -31,7 +31,7 @@ Verified against `docs/reference/contract.md`, `dsk help --json`, `dsk help envi Global flags, valid with every command: `--json`, `-q`/`--quiet` (errors only on stderr), `-v`/`--verbose` (repeatable), `--color auto|always|never`, `--no-color`, `--plain` (ASCII, no color), `--no-progress`, `--cache-dir DIR`, `--connect-timeout SECS`. -`search` flags: `-s/--source`, `--include`, `-x/--exclude`, `-c/--category` (comma-separated), `-n/--limit` (20), `--per-source` (10, at most 100), `--sort relevance|newest`, `--refresh`, `--offline`, `--timeout SECS` (20; 0 waits for every source). Their meaning is the MCP argument table in `references/search.md`. +`search` flags: `-s/--source`, `--include`, `-x/--exclude`, `-c/--category` (comma-separated), `-n/--limit` (20), `--per-source` (10, or 30 with a filter; at most 100), `--license`, `--updated-since`, `--format`, `--min-sources N`, `--sort relevance|newest`, `--refresh`, `--offline`, `--timeout SECS` (20; 0 waits for every source). Their meaning is the MCP argument table in `references/search.md`. A flag beats its variable, which beats the default: @@ -70,9 +70,9 @@ dsk search census --json | jq -r '.results[] | [.title, .url, (.sources | join(" # only datasets more than one archive holds dsk search sea surface temperature --json | jq '[.results[] | select(.sources | length > 1)]' -# only Creative Commons licenses, as the sources write them (URL or name) -dsk search sea surface temperature --json \ - | jq '[.results[] | select((.license // "") | test("creativecommons|cc-?by|cc0"; "i"))]' +# only CC BY (any version) or CC0, updated since 2024, offered as CSV +dsk search air quality --license cc-by,cc0 --updated-since 2024 --format csv --json \ + | jq '{total, filtered_out}' # which sources did not answer, and why dsk search sea surface temperature --json | jq -r '.sources[] | select(.answered | not) | "\(.id)\t\(.status)"' diff --git a/skills/dataseek/references/inspect.md b/skills/dataseek/references/inspect.md index f841883..143c8aa 100644 --- a/skills/dataseek/references/inspect.md +++ b/skills/dataseek/references/inspect.md @@ -15,6 +15,8 @@ Verified against `src/inspect.rs`, `dsk help inspect --json` and live runs on 20 - **Most pages:** every `application/ld+json` block holding a schema.org `Dataset`, at the top level, in an array or inside `@graph`. - **Hugging Face:** the Hub's Croissant endpoint, because the page's HTML carries no metadata. Croissant adds `recordSet` (the columns) beside the schema.org fields. +- **Dataverse:** a `dataset.xhtml?persistentId=...` page is read through the installation's schema.org export, which answers where the page itself sits behind a bot wall (Harvard). +- **doi.org links:** `inspect` looks up where the DOI points and reads that page, so a result whose `url` is a DOI needs no extra step. - **Files:** the dataset's `distribution`, schema.org `DataDownload` and Croissant `FileObject` and `FileSet` entries. Nothing is downloaded; a size, format or checksum is whatever the page declares. ## The result @@ -34,15 +36,15 @@ Observed 2026-10-20 on landing pages from an `air quality` search, one per sourc | Outcome | Sources whose result URLs gave it | |---|---| -| metadata and files | `zenodo`, `huggingface`, `kaggle`, `datagov`, `data-gov-au`, `dataverse-no`, `aws`, `cessda`, `dbnomics`, `modelscope`, `openaire` | +| metadata and files | `zenodo`, `huggingface`, `kaggle`, `datagov`, `data-gov-au`, `harvard-dataverse` and the other Dataverse installations, `aws`, `cessda`, `dbnomics`, `modelscope`, `openaire` | | `carries no schema.org Dataset markup` | `arcgis`, `b2find`, `dataone`, `earth-engine`, `europa`, `github`, `govdata`, `open-canada`, `opendatasoft`, `openml`, `osf` | -| `sent a challenge page instead of results` | `gbif`, and the AWS bot wall in front of `hdx`, `figshare` and `harvard-dataverse` pages | +| `sent a challenge page instead of results` | `gbif`, and the AWS bot wall in front of `hdx` and `figshare` pages | `cmr` results now link the provider's landing page or the DOI rather than NASA's record page, so whether they publish markup depends on that provider. ## When it fails -1. **`carries no schema.org Dataset markup`** with a `doi` on the result: inspect `https://doi.org/` once. The DOI resolves to the publisher's canonical page, which worked for a Zenodo DOI on 2026-10-20; a DOI that lands behind a bot wall fails as in step 3. +1. **`carries no schema.org Dataset markup`** with a `doi` on the result and a `url` that is not a doi.org link: inspect `https://doi.org/` once. `inspect` reads the publisher's canonical page the DOI names; a DOI that lands behind a bot wall fails as in step 3. 2. **Still no markup:** say the page publishes no machine-readable metadata, give its URL, and list what the search result itself carried. Read the page with a web fetch tool only if the user wants more. 3. **`cannot fetch`** with `sent a challenge page instead of results`: the site blocks automated requests; give the URL for the user to open. 4. **A file URL or a search page** handed to `inspect` fails the same way as a page with no markup; pass the landing page. diff --git a/skills/dataseek/references/search.md b/skills/dataseek/references/search.md index 4e54de0..3f50408 100644 --- a/skills/dataseek/references/search.md +++ b/skills/dataseek/references/search.md @@ -5,6 +5,7 @@ Verified against `tools/list`, `dsk help search --json`, `dsk sources --json` an ## Contents - **Arguments**: which argument, on which surface, and when each one is worth setting +- **Filters**: license, date, format and agreement constraints, and what an empty filtered result means - **Source ids and categories**: what to put in `source`, `exclude` and `category` - **Writing queries**: how long a query should be and what stays out of it - **Reading the result**: what each field means and which ones an answer may quote @@ -25,7 +26,11 @@ The MCP tool's input schema is generated from the CLI's flags, so the names matc | `exclude` (array of ids) | `-x a,b` | none | one source floods the list with near-duplicates | | `category` (array of names) | `-c a,b` | every category | the domain is unmistakable (economics, life-sciences) | | `limit` (integer) | `-n N` | 20 | the user wants more or fewer merged results | -| `per-source` (1 to 100) | `--per-source N` | 10 | a source should contribute deeper results; costs paging on some sources | +| `license` (array of ids) | `--license a,b` | none | the user needs a license: SPDX ids (`CC-BY-4.0`, `CC0-1.0`) or a family (`cc-by`, every version and port) | +| `updated-since` (`YYYY`, `YYYY-MM` or `YYYY-MM-DD`) | `--updated-since 2024` | none | the user needs data updated on or after a date | +| `format` (array of names) | `--format csv,parquet` | none | the user needs a file format: `csv`, `json`, `parquet`, `netcdf`, `geotiff`, ... | +| `min-sources` (integer, at least 1) | `--min-sources 2` | none | only datasets several archives hold are wanted | +| `per-source` (1 to 100) | `--per-source N` | 10, or 30 when a filter is set | a source should contribute deeper results; costs paging on some sources | | `sort` (`relevance`, `newest`) | `--sort newest` | `relevance` | the user asks for recent or recently updated data | | `refresh` (boolean) | `--refresh` | false | the user needs answers newer than the 6-hour cache | | `offline` (boolean) | `--offline` | false | no network, or a repeat over the cache only | @@ -35,6 +40,17 @@ Over MCP, `source`, `include`, `exclude` and `category` are JSON arrays, `["zeno `source` replaces the default set; `include` adds to it. A search with `source: ["kaggle"]` asks Kaggle alone, one with `include: ["kaggle"]` asks Kaggle and every default source. `category` and `exclude` still narrow an included source: `include: ["google"]` with `category: ["research"]` leaves Google out, because Google is an `aggregator`. A source named in `source` gets the whole `timeout` and is asked even if it had an outage in the last ten minutes. +## Filters + +`license`, `updated-since`, `format` and `min-sources` filter the merged list before `limit` cuts it, the same way for every source. A merged dataset passes on what any of its sources stated, and a dataset that does not state a field never passes a filter on it. With a filter set each source is asked for 30 results instead of 10, so a filtered search can return more matches than the unfiltered one. + +Measured 2026-10-20 on "sea surface temperature", 328 matches unfiltered: `license: ["cc-by"]` kept 160, `updated-since: "2024"` 488, `format: ["netcdf"]` 37, `min-sources: 2` 10. + +- **Licenses are sparse.** About three results in ten name one (315 of 978 over three queries, 2026-10-20), so a license filter drops most of a search. A dropped dataset may still be openly licensed on its page; say so when the filtered list is short, and offer `inspect` on a promising unfiltered result. +- **Formats come from five kinds of source only:** CKAN portals (`data-gov-uk`, `open-canada`, `data-gov-au`, `govdata`, `hdx`), `europa`, `arcgis`, `cmr` and `datagov`. A `format` filter leaves out every research repository; for those, `inspect` the result to read its files. +- **An empty filtered result** says how many matched without the filters (`filtered_out` in the result). Report that number and which filter was strictest rather than "nothing found". +- **`min-sources: 2`** keeps datasets independent archives agree on; it suits a "which datasets are well established" question, not a search for something specific. + ## Source ids and categories The `sources` tool (or `dsk sources --json`) is the live list: id, name, category, protocol, key status and docs URL for each. As of 2026-10-20, by category; `*` marks a catalog source, whose whole list dataseek downloads weekly and searches locally: @@ -67,7 +83,7 @@ Each source runs its own search engine and most of them require every word to ma Measured 2026-10-20 over the default sources: "sea surface temperature" merged 328 results; "global monthly sea surface temperature dataset since 1980" merged 136. - **Two to four content words.** Drop "dataset", "data", "open", "about", "find me". -- **Constraints stay out of the query.** Years, regions, file formats and licenses filter the results afterwards (`updated`, `description`, `license`), or become a second query when they are the topic ("Kenya census"). A year in the query also weighs heavily in the ranking, because rare tokens count most, so "since 2000" lifts tables that merely contain "2000". +- **Constraints stay out of the query.** Licenses, dates and file formats go in the filter arguments (Filters above). A region becomes a second query when it is the topic ("Kenya census"), or is read off `description` afterwards. A year in the query also weighs heavily in the ranking, because rare tokens count most, so "since 2000" lifts tables that merely contain "2000". - **Use the field's own words and acronyms** as alternative queries: "SST" or "ERSST" beside "sea surface temperature", "scRNA-seq" beside "single cell RNA", "CPI" beside "consumer prices". - **One concept per query.** "air quality" and "asthma admissions" are two searches whose results the answer joins, not one query that few datasets match on both. - **English first.** Most sources index English metadata; `europa` matches across EU languages, and a national portal (`govdata`, `recherche-data-gouv`) may answer better in its own language. @@ -81,7 +97,8 @@ Measured 2026-10-20 over the default sources: "sea surface temperature" merged 3 |---|---| | `query` | the query as searched | | `complete` | false when the search stopped waiting for a source or a catalog was still downloading, so results from those are missing | -| `total` | how many merged datasets matched; `results` holds the first `limit` of them | +| `total` | how many merged datasets matched and passed the filters; `results` holds the first `limit` of them | +| `filtered_out` | how many merged datasets the filters dropped; 0 without filters | | `results` | the merged datasets, best first, at most `limit` | | `sources` | one entry per source asked: `id`, `status`, `answered`, `results` (how many it returned), `ms` | @@ -92,7 +109,8 @@ Each result: | `title`, `url` | always present; `url` is the landing page, the one to give the user and to pass to `inspect` | | `sources` | every source that holds this dataset; more than one means independent archives agree it exists | | `description` | cut to a few hundred characters; quote it as a summary, not as the whole record | -| `publisher`, `doi`, `license`, `updated`, `size_bytes` | present only when a source supplied them; `license` is a name or a URL as the source wrote it | +| `publisher`, `doi`, `license`, `updated`, `size_bytes` | present only when a source supplied them; `license` is an SPDX id (`CC-BY-4.0`) where the source's spelling maps to one, else the source's own text | +| `formats` | the file formats the sources list, one name each (`CSV`, `NETCDF`); absent when none did | | `popularity` | downloads, votes or stars as one source counts them; compare only between results from the same source | | `aliases` | other identifiers of the same dataset (a concept DOI, a mirror URL), used for merging | | `score` | the rank score inside this one search; meaningless across searches and not a probability | @@ -147,4 +165,4 @@ dsk search sea surface temperature -n 10 dsk search ERSST -n 10 ``` -List only the results that fit the request, after applying the user's constraints, and say how many were dropped and why. +List only the results that fit the request. Constraints the filter arguments cover go in the call; any other constraint is applied to the results, and the answer says how many were dropped and why. diff --git a/src/cli.rs b/src/cli.rs index 91f3338..119e514 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -342,7 +342,9 @@ pub enum Command { Croissant for Hugging Face. The file list comes from the same \ metadata: each file's name, format, size, checksum and link, \ whichever the page gives, and for a Croissant file set the \ - pattern its files match; nothing is downloaded. Under --json \ + pattern its files match; nothing is downloaded. A doi.org \ + link is read as the page its DOI names, and a Dataverse page \ + through its installation's schema.org export. Under --json \ the list is .files, beside the page's own .dataset.", after_help = "Examples: dsk inspect https://zenodo.org/records/13135140 From 973fb09cdd4e904c2a925144d3f6057e5ecb86a8 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:16:07 +0100 Subject: [PATCH 24/31] fix: rustls 0.23.46, so a resumed TLS connection keeps its post-quantum key exchange (RUSTSEC-2026-0346 to 0349) --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9d10009..1fc9cab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1497,9 +1497,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", From 25abc9d039ca5b4443a3e472401f20f2e996535c Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:17:44 +0100 Subject: [PATCH 25/31] ci: spell-check passes on Creative Commons ND ids --- _typos.toml | 5 +++++ src/license.rs | 20 +++++++++++++------- src/sources/osf.rs | 2 +- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/_typos.toml b/_typos.toml index fe7f823..191bea1 100644 --- a/_typos.toml +++ b/_typos.toml @@ -7,6 +7,11 @@ extend-exclude = ["tests/fixtures/"] extend-ignore-re = [ "Dateset contains past", "CC-BY-NC-ND-4\\.0", + # The Creative Commons NoDerivatives element, in license ids and names. + "(?i)\\bby(-nc)?-nd\\b", + "(?i)\\bcc by nc nd\\b", + "\"-ND\"", + "has\\(\"nd\"\\)", "Burnt Area \\(BA\\)", "census for BA 44/45", ] diff --git a/src/license.rs b/src/license.rs index 911ee89..977705d 100644 --- a/src/license.rs +++ b/src/license.rs @@ -236,23 +236,29 @@ fn creative_commons(words: &[&str]) -> Option { { return Some("CC0-1.0".to_owned()); } - let nc = + let noncommercial = has("nc") || has("noncommercial") || (has("non") && has("commercial")); - let nd = has("nd") + let no_derivatives = has("nd") || has("noderivatives") || has("noderivs") || (has("no") && has("derivatives")); - let sa = has("sa") || has("sharealike") || (has("share") && has("alike")); - if !(has("by") || has("attribution") || nc || nd || sa) { + let share_alike = + has("sa") || has("sharealike") || (has("share") && has("alike")); + if !(has("by") + || has("attribution") + || noncommercial + || no_derivatives + || share_alike) + { return None; } let mut id = String::from("CC-BY"); - if nc { + if noncommercial { id.push_str("-NC"); } - if nd { + if no_derivatives { id.push_str("-ND"); - } else if sa { + } else if share_alike { id.push_str("-SA"); } if let Some(version) = words.iter().find_map(|w| cc_version(w)) { diff --git a/src/sources/osf.rs b/src/sources/osf.rs index 98e8f63..2c6a2fe 100644 --- a/src/sources/osf.rs +++ b/src/sources/osf.rs @@ -3,7 +3,7 @@ //! An owner can mark a record's `resourceNature` as Dataset, but 4,135 of //! more than 10,000 records do, and 2 of the 45 hits for "sea ice", too few //! to filter on. `page[size]` is capped at 101, so one request serves any -//! limit; hits come by relevance, words are ANDed, and no query syntax draws +//! limit; hits come by relevance, every word must match, and no query syntax draws //! an error (trove source and probe, October 2026). trove throttles per //! client without saying how: 17 requests in about three minutes drew HTTP //! 429 with no `Retry-After`, and every `/trove/` path then answered 429 for From 01601e08b38f7586e2b95de0c4614ba2bcb216d6 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:19:24 +0100 Subject: [PATCH 26/31] fix: search refuses a --license or --format value that names nothing, such as unknown, instead of running unfiltered --- docs/reference/contract.md | 2 +- src/cli.rs | 14 +++++++++-- src/filter.rs | 49 +++++++++++++++++++++++++++----------- src/mcp/tools.rs | 4 ++-- 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/docs/reference/contract.md b/docs/reference/contract.md index 07f991a..ac8355a 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -13,7 +13,7 @@ The version lives only in `Cargo.toml`. Clap reads it via `#[command(version)]`, - `--json`, `--color=auto|always|never`, `--no-color`, `--plain`, `--no-progress` - `--cache-dir DIR` and `--connect-timeout SECS`, each with a `DATASEEK_*` variable; the cache size budget has only its variable, `DATASEEK_CACHE_MAX_MB` -`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` or `--include` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). `--license`, `--updated-since`, `--format` and `--min-sources` filter the merged list before `-n` cuts it, and a dataset that does not state a field never passes a filter on it; with any of them set, `--per-source` defaults to 30 instead of 10 ([ADR 0020](../adr/0020-filters-run-on-the-merged-list.md)). A license is an SPDX id or a family (`cc-by`), a date is `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, and a format is one of the names results carry in `formats` (`CSV`, `NETCDF`, ...), matched without regard to case or spelling (`text/csv` is `CSV`). +`search` reads `-x`, `--per-source`, `-n` and `--timeout` from `DATASEEK_EXCLUDE`, `DATASEEK_PER_SOURCE`, `DATASEEK_LIMIT` and `DATASEEK_TIMEOUT` too. A flag beats its variable, which beats the default; `dataseek help environment` lists them all. A source marked `opt-in` in `dataseek sources` runs only when `-s` or `--include` names it ([ADR 0013](../adr/0013-opt-in-sources.md)). `--license`, `--updated-since`, `--format` and `--min-sources` filter the merged list before `-n` cuts it, and a dataset that does not state a field never passes a filter on it; with any of them set, `--per-source` defaults to 30 instead of 10 ([ADR 0020](../adr/0020-filters-run-on-the-merged-list.md)). A license is an SPDX id or a family (`cc-by`), a date is `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, and a format is one of the names results carry in `formats` (`CSV`, `NETCDF`, ...), matched without regard to case or spelling (`text/csv` is `CSV`). A value that names no license or format, such as `unknown`, is a usage error rather than a filter that quietly does nothing. `-v` is verbose, never version. `--color` follows the ecosystem standard used by git, ripgrep, and fd: diff --git a/src/cli.rs b/src/cli.rs index 119e514..4ce484e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -196,7 +196,12 @@ pub const MIN_SOURCES: RangeFrom = 1..; pub struct Filters { /// Only datasets under these licenses, comma-separated: SPDX ids such /// as CC-BY-4.0, or a family such as cc-by for every version of it. - #[arg(long, value_name = "IDS", value_delimiter = ',')] + #[arg( + long, + value_name = "IDS", + value_delimiter = ',', + value_parser = crate::filter::license + )] pub license: Vec, /// Only datasets updated on or after this day (YYYY, YYYY-MM or @@ -206,7 +211,12 @@ pub struct Filters { /// Only datasets offered in one of these file formats, comma-separated: /// csv, json, parquet, netcdf, geotiff, ... - #[arg(long, value_name = "NAMES", value_delimiter = ',')] + #[arg( + long, + value_name = "NAMES", + value_delimiter = ',', + value_parser = crate::filter::format + )] pub format: Vec, /// Only datasets that at least this many sources found. diff --git a/src/filter.rs b/src/filter.rs index 9a917f0..3d8947e 100644 --- a/src/filter.rs +++ b/src/filter.rs @@ -9,8 +9,9 @@ use crate::dedup::Hit; use crate::license; use crate::record::file_format; -/// The filters with their values normalized as the records' are, so a -/// license asked for as `cc by 4.0` matches one recorded as `CC-BY-4.0`. +/// The filters, whose values the parsers below normalized as the records' +/// are, so a license asked for as `cc by 4.0` matches one recorded as +/// `CC-BY-4.0`. #[derive(Debug, Default)] pub struct Wanted { pub licenses: Vec, @@ -24,16 +25,8 @@ pub struct Wanted { impl Wanted { pub fn new(filters: &Filters) -> Self { Self { - licenses: filters - .license - .iter() - .filter_map(|l| license::normalized(l)) - .collect(), - formats: filters - .format - .iter() - .filter_map(|f| file_format(f)) - .collect(), + licenses: filters.license.clone(), + formats: filters.format.clone(), since: filters.updated_since.clone(), min_sources: filters.min_sources.map_or(0, usize::from), } @@ -62,6 +55,22 @@ impl Wanted { } } +/// `--license` as the records spell it. A word that names no license, such +/// as `unknown`, is refused rather than dropped, so the search never runs +/// unfiltered without saying so. +pub fn license(raw: &str) -> Result { + license::normalized(raw).ok_or_else(|| { + format!("`{raw}` names no license; write an SPDX id such as CC-BY-4.0") + }) +} + +/// `--format` as the records spell it, refused when it names no format. +pub fn format(raw: &str) -> Result { + file_format(raw).ok_or_else(|| { + format!("`{raw}` names no file format; write one such as csv") + }) +} + /// What [`day`] accepts, as a JSON Schema `pattern`. pub const DAY_PATTERN: &str = r"^[0-9]{4}(-[0-9]{2}(-[0-9]{2})?)?$"; @@ -137,7 +146,10 @@ mod tests { fn wanted(license: &[&str], since: Option<&str>, min: u16) -> Wanted { Wanted::new(&Filters { - license: license.iter().map(|l| (*l).to_owned()).collect(), + license: license + .iter() + .map(|l| super::license(l).unwrap()) + .collect(), format: Vec::new(), updated_since: since.map(|s| day(s).unwrap()), min_sources: Some(min), @@ -155,6 +167,15 @@ mod tests { } } + #[test] + fn a_value_that_names_nothing_is_refused() { + assert_eq!(license("cc by 4.0").as_deref(), Ok("CC-BY-4.0")); + assert!(license("unknown").is_err()); + assert!(license(" ").is_err()); + assert_eq!(format(".CSV").as_deref(), Ok("CSV")); + assert!(format("not provided").is_err()); + } + #[test] fn a_date_counts_at_the_precision_it_is_recorded_with() { assert!(on_or_after("2024-07-30", "2024-07-30")); @@ -187,7 +208,7 @@ mod tests { assert!(!all.admits(&hit(Some("CC-BY-4.0"), None, 3))); assert!(!wanted(&[], None, 1).any()); let csv = Wanted::new(&Filters { - format: vec!["text/csv".into()], + format: vec![format("text/csv").unwrap()], ..Filters::default() }); let mut offered = hit(None, None, 1); diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index e917845..723664f 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -667,9 +667,9 @@ mod tests { }; assert_eq!(query, ["sea surface temperature"]); assert_eq!(selection.only, ["zenodo", "datacite"]); - assert_eq!(filters.license, ["cc-by", "CC0-1.0"]); + assert_eq!(filters.license, ["CC-BY", "CC0-1.0"]); assert_eq!(filters.updated_since.as_deref(), Some("2024-07-01")); - assert_eq!(filters.format, ["csv"]); + assert_eq!(filters.format, ["CSV"]); assert_eq!(filters.min_sources, Some(2)); assert_eq!( (limit, sort, offline, refresh), From 2b5a03a334f6afb398149cef0cfa81fc037a84cf Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:10:36 +0100 Subject: [PATCH 27/31] fix: inspect keeps a Dataverse page's version, and reads the page itself when the export cannot serve it --- src/inspect.rs | 39 +++++++++++++++++++++++++++------------ tests/cli.rs | 19 +++++++++++++++++++ 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/src/inspect.rs b/src/inspect.rs index 7c69d54..9fafaee 100644 --- a/src/inspect.rs +++ b/src/inspect.rs @@ -78,6 +78,11 @@ pub fn run(url: &str, out: &Out) -> Result<()> { _ => Error::Fetch { url: url.to_owned(), source: e }, }; let no_markup = || Error::NoMarkup { url: url.to_owned() }; + let read_page = |address: &str| { + http.get(address).text().map_err(fetch_error).and_then(|html| { + json_ld(&html).iter().find_map(Page::find).ok_or_else(no_markup) + }) + }; let progress = ui::spinner(format!("reading {url}")); let address = doi_link(url) .and_then(|doi| landing(&http, &doi)) @@ -90,14 +95,12 @@ pub fn run(url: &str, out: &Out) -> Result<()> { .map(|dataset| Page { dataset, graph: Vec::new() }) .map_err(fetch_error) } else if let Some(export) = dataverse_export(&address) { - http.get(&export) - .json() - .map_err(fetch_error) - .and_then(|metadata| Page::find(&metadata).ok_or_else(no_markup)) + match http.get(&export).json().ok().as_ref().and_then(Page::find) { + Some(page) => Ok(page), + None => read_page(&address), + } } else { - http.get(&address).text().map_err(fetch_error).and_then(|html| { - json_ld(&html).iter().find_map(Page::find).ok_or_else(no_markup) - }) + read_page(&address) }; progress.finish_and_clear(); let mut page = found?; @@ -348,16 +351,28 @@ fn landing(http: &Http, doi: &str) -> Option { /// The schema.org export of a Dataverse dataset page, `.../dataset.xhtml` /// or `.../citation` with a `persistentId`, which the installation's API -/// serves beside the page. +/// serves beside the page. The page's `version` goes with it: the export +/// serves only the latest published version and refuses an older one, which +/// is then read from its page (Dataverse native API guide, October 2026). fn dataverse_export(url: &str) -> Option { let (page, query) = url.split_once('?')?; let (root, last) = page.rsplit_once('/')?; if !matches!(last, "dataset.xhtml" | "citation") || !root.contains("://") { return None; } - let id = - query.split(['&', '#']).find(|p| p.starts_with("persistentId="))?; - Some(format!("{root}/api/datasets/export?exporter=schema.org&{id}")) + let query = query.split('#').next().unwrap_or_default(); + let pair = |key: &str| { + query.split('&').find(|p| { + p.strip_prefix(key).is_some_and(|value| value.starts_with('=')) + }) + }; + let id = pair("persistentId")?; + let export = + format!("{root}/api/datasets/export?exporter=schema.org&{id}"); + Some(match pair("version") { + Some(version) => format!("{export}&{version}"), + None => export, + }) } fn huggingface_id(url: &str) -> Option { @@ -668,7 +683,7 @@ mod tests { ) .as_deref(), Some( - "https://data.example.org/dv/api/datasets/export?exporter=schema.org&persistentId=hdl:1902/X" + "https://data.example.org/dv/api/datasets/export?exporter=schema.org&persistentId=hdl:1902/X&version=2.0" ) ); assert_eq!(dataverse_export("https://x.org/dataset.xhtml?id=4"), None); diff --git a/tests/cli.rs b/tests/cli.rs index 1928411..9c8d404 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1035,6 +1035,25 @@ fn inspect_reads_a_dataverse_page_through_its_export() { assert_eq!(report["files"].as_array().map(Vec::len), Some(2)); } +#[test] +fn inspect_reads_the_page_when_the_dataverse_export_refuses() { + // Every path answers with an HTML page, so the export request gets no + // JSON, as when it refuses a version older than the latest. + let page = format!( + "{}dataset.xhtml?persistentId=doi:10.7910/DVN/X&version=1.0", + serve_page(include_str!("fixtures/inspect/zenodo.html")) + ); + let out = bin() + .env_remove("HTTPS_PROXY") + .env_remove("HTTP_PROXY") + .args(["inspect", &page, "--json"]) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert!(report["dataset"]["name"].is_string(), "{report}"); +} + #[test] fn inspect_says_when_a_page_lists_no_files() { let out = inspect_page(BARE_PAGE, &["--json"]); From de4751c7b8d238a5b9b07b5bb180bca4d5a7ba95 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:10:39 +0100 Subject: [PATCH 28/31] fix: search --updated-since refuses a day the calendar lacks, such as 2024-02-30 --- src/filter.rs | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/filter.rs b/src/filter.rs index 3d8947e..f7783c1 100644 --- a/src/filter.rs +++ b/src/filter.rs @@ -1,6 +1,7 @@ -//! The filters `search` applies to the merged list (ADR 0020). They run on -//! merged hits, so a field any one of a dataset's sources stated counts, -//! and they hold alike for every source whatever its own API can filter. +//! The filters `search` applies to the merged list (ADR 0020). They read a +//! merged hit as it is shown: its license and date are the first ones a +//! source stated, its formats every source's. They hold alike for every +//! source whatever its own API can filter. //! A dataset that does not state a field never passes a filter on it: a //! license filter keeps only datasets that name a matching license. @@ -79,6 +80,7 @@ pub const DAY_PATTERN: &str = r"^[0-9]{4}(-[0-9]{2}(-[0-9]{2})?)?$"; pub fn day(raw: &str) -> Result { let day = iso_prefix(raw.trim()) .filter(|prefix| prefix.len() == raw.trim().len()) + .filter(|prefix| on_the_calendar(prefix)) .ok_or_else(|| { format!("`{raw}` is not a day; write YYYY, YYYY-MM or YYYY-MM-DD") })?; @@ -89,6 +91,28 @@ pub fn day(raw: &str) -> Result { }) } +/// Whether a `YYYY-MM-DD` date names a day the month has: no 30 February. +/// A year or a month alone always does. +fn on_the_calendar(date: &str) -> bool { + let part = |range: std::ops::Range| { + date.get(range).and_then(|s| s.parse::().ok()) + }; + let (Some(year), Some(month), Some(day)) = + (part(0..4), part(5..7), part(8..10)) + else { + return true; + }; + let leap = year.is_multiple_of(4) + && (!year.is_multiple_of(100) || year.is_multiple_of(400)); + let last = match month { + 2 if leap => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + }; + day <= last +} + /// Whether a recorded date is on or after `since`, a full day, compared to /// the precision the record gives: a dataset dated only `2024` counts as /// updated after `2024-06-01`, since it may well have been. @@ -161,8 +185,18 @@ mod tests { assert_eq!(day("2024").as_deref(), Ok("2024-01-01")); assert_eq!(day("2024-07").as_deref(), Ok("2024-07-01")); assert_eq!(day("2024-07-30").as_deref(), Ok("2024-07-30")); - for bad in ["24", "2024-13", "2024-7-1", "July 2024", "2024-07-30T00"] - { + assert_eq!(day("2024-02-29").as_deref(), Ok("2024-02-29")); + for bad in [ + "24", + "2024-13", + "2024-7-1", + "July 2024", + "2024-07-30T00", + "2024-02-30", + "2023-02-29", + "2023-04-31", + "1900-02-29", + ] { assert!(day(bad).is_err(), "{bad}"); } } From f5826676a239b4dd2204157c71583157bdb458c0 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:10:40 +0100 Subject: [PATCH 29/31] fix: a media type with parameters, such as text/csv; charset=utf-8, reads as its file format --- src/record.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/record.rs b/src/record.rs index 74aaa9b..d28a846 100644 --- a/src/record.rs +++ b/src/record.rs @@ -588,6 +588,7 @@ pub fn file_format(raw: &str) -> Option { } else { text.as_str() }; + let text = text.split(';').next().unwrap_or_default().trim(); let lower = text.trim_start_matches('.').to_lowercase(); let lower = lower.strip_suffix("_srvc").unwrap_or(&lower); if let Some((_, name)) = @@ -874,6 +875,7 @@ mod tests { "ZIP", ), ("WMS_SRVC", "WMS"), + ("text/csv; charset=utf-8", "CSV"), ("Excel XLSX", "XLSX"), ( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", From 8066455083dd060992af955ba095e29e883f224f Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:10:42 +0100 Subject: [PATCH 30/31] test: the B2FIND fixture carries no researcher's address --- tests/fixtures/sources/ckan.b2find.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fixtures/sources/ckan.b2find.json b/tests/fixtures/sources/ckan.b2find.json index 84ee054..9da3b95 100644 --- a/tests/fixtures/sources/ckan.b2find.json +++ b/tests/fixtures/sources/ckan.b2find.json @@ -557,7 +557,7 @@ "extras": [ { "key": "Contact", - "value": "m.schultz(at)fz-juelich.de" + "value": "contact@example.org" }, { "key": "Discipline", From 4c62c8c786c8c707bf87b63ca0df9bd3f80f1f79 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:10:42 +0100 Subject: [PATCH 31/31] doc: filters read a result as shown, and the skill covers filtered-empty searches, uvx, opt-in sources and inspect's four keys --- docs/adr/0020-filters-run-on-the-merged-list.md | 2 +- skills/dataseek/SKILL.md | 2 +- skills/dataseek/references/inspect.md | 4 +++- skills/dataseek/references/search.md | 2 +- skills/dataseek/references/setup.md | 2 +- skills/dataseek/references/troubleshoot.md | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/adr/0020-filters-run-on-the-merged-list.md b/docs/adr/0020-filters-run-on-the-merged-list.md index fd76067..a13c0dc 100644 --- a/docs/adr/0020-filters-run-on-the-merged-list.md +++ b/docs/adr/0020-filters-run-on-the-merged-list.md @@ -9,7 +9,7 @@ An agent or a user often knows more than the words of a query: the data must be ## Decision -- `search` takes `--license`, `--updated-since`, `--format` and `--min-sources`, and applies them to the merged, ranked list before `--limit` cuts it. A merged dataset passes on a field any of its sources stated. A dataset that does not state a field never passes a filter on it. +- `search` takes `--license`, `--updated-since`, `--format` and `--min-sources`, and applies them to the merged, ranked list before `--limit` cuts it. A filter reads a merged dataset as it is shown: its license and date are the first ones a source stated, and its formats are every source's, so a result never passes on a value it does not display. A dataset that does not state a field never passes a filter on it. - Every source's license is read as an SPDX id at the source boundary (`src/license.rs`): `CC-BY-4.0` however the source spelled it, placeholders such as `notspecified` dropped, anything unrecognized kept as written. `--license cc-by` matches the family, every version and port of CC BY but not CC BY-SA. - `--updated-since` takes a year, a month or a day and compares at the precision a record states, so a dataset dated only `2024` counts as updated after `2024-06-01`. - File formats are read as one name per format (`CSV`, `NETCDF`, `GEOTIFF`) from the sources that list them: CKAN portals, data.europa.eu, ArcGIS Hub, NASA CMR and data.gov. diff --git a/skills/dataseek/SKILL.md b/skills/dataseek/SKILL.md index 25baa11..18c96aa 100644 --- a/skills/dataseek/SKILL.md +++ b/skills/dataseek/SKILL.md @@ -17,7 +17,7 @@ compatibility: needs the dataseek binary (dsk) and network access # dataseek -dataseek sends one query to every dataset source it knows, merges the records that are one dataset (a shared DOI, landing URL, or title and publisher) and ranks them by how many sources agree and how much of the query each covers. It runs as an MCP server (`dsk mcp`, three tools) and as a CLI (`dsk`, also installed as `dataseek`). They are one program: a tool returns, byte for byte, the object `dsk --json` prints, so every reference here holds for both. +dataseek sends one query to every default dataset source (the opt-in ones only when named), merges the records that are one dataset (a shared DOI, landing URL, or title and publisher) and ranks them by how many sources agree and how much of the query each covers. It runs as an MCP server (`dsk mcp`, three tools) and as a CLI (`dsk`, also installed as `dataseek`). They are one program: a tool returns, byte for byte, the object `dsk --json` prints, so every reference here holds for both. **MCP first; the CLI is the fallback.** dataseek is built to be called as an MCP server, so every procedure here is written in tool arguments. diff --git a/skills/dataseek/references/inspect.md b/skills/dataseek/references/inspect.md index 143c8aa..2cd61c7 100644 --- a/skills/dataseek/references/inspect.md +++ b/skills/dataseek/references/inspect.md @@ -21,10 +21,12 @@ Verified against `src/inspect.rs`, `dsk help inspect --json` and live runs on 20 ## The result -Schema `dataseek-inspect/1`, two keys: +Schema `dataseek-inspect/1`, four keys: | Key | What it holds | |---|---| +| `schema` | `dataseek-inspect/1` | +| `url` | the URL as it was passed | | `dataset` | the page's own JSON-LD node as the page wrote it: commonly `name`, `description`, `creator` or `author`, `publisher`, `license`, `datePublished`, `dateModified`, `identifier`, `keywords`, `distribution`, `size` or `contentSize` | | `files` | dataseek's reading of the file list; each entry has whichever of `name`, `format`, `size_bytes`, `checksum` (`sha256:` or `md5:`), `url` and, for a Croissant file set, `includes` (the glob its files match, such as `plain_text/*/*.parquet`) the page gave | diff --git a/skills/dataseek/references/search.md b/skills/dataseek/references/search.md index 3f50408..79d5491 100644 --- a/skills/dataseek/references/search.md +++ b/skills/dataseek/references/search.md @@ -42,7 +42,7 @@ Over MCP, `source`, `include`, `exclude` and `category` are JSON arrays, `["zeno ## Filters -`license`, `updated-since`, `format` and `min-sources` filter the merged list before `limit` cuts it, the same way for every source. A merged dataset passes on what any of its sources stated, and a dataset that does not state a field never passes a filter on it. With a filter set each source is asked for 30 results instead of 10, so a filtered search can return more matches than the unfiltered one. +`license`, `updated-since`, `format` and `min-sources` filter the merged list before `limit` cuts it, the same way for every source. A filter reads each result as it is shown: the license and date it displays (the first ones a source stated) and the formats of every source. A result that does not state a field never passes a filter on it. With a filter set each source is asked for 30 results instead of 10, so a filtered search can return more matches than the unfiltered one. Measured 2026-10-20 on "sea surface temperature", 328 matches unfiltered: `license: ["cc-by"]` kept 160, `updated-since: "2024"` 488, `format: ["netcdf"]` 37, `min-sources: 2` 10. diff --git a/skills/dataseek/references/setup.md b/skills/dataseek/references/setup.md index 89dc1a5..7cb8611 100644 --- a/skills/dataseek/references/setup.md +++ b/skills/dataseek/references/setup.md @@ -22,7 +22,7 @@ uv tool install dataseek # from PyPI uvx dataseek search sea surface temperature # run once, install nothing ``` -Every method installs two names for one program, `dsk` and `dataseek`. Installing changes the user's machine: ask before running one, and let the user pick the package manager they already use. +Every method but `uvx` installs two names for one program, `dsk` and `dataseek`; `uvx` runs it once and installs neither. Installing changes the user's machine: ask before running one, and let the user pick the package manager they already use. ## Register the MCP server diff --git a/skills/dataseek/references/troubleshoot.md b/skills/dataseek/references/troubleshoot.md index 60e39df..085576c 100644 --- a/skills/dataseek/references/troubleshoot.md +++ b/skills/dataseek/references/troubleshoot.md @@ -87,7 +87,7 @@ The search succeeded but one source is missing. Act only when that source matter ## No results -An empty `results` list with sources answering means none of them holds a match for those words. In order: +An empty `results` list with a positive `filtered_out` is not a missing match: the filters dropped that many datasets. Report the count and the filter that was set, and offer the search without it; only with `filtered_out` at 0 does an empty list with sources answering mean none of them holds a match for those words. Then, in order: 1. Check `sources`: if the sources that would hold this topic did not answer, it is the table above, not the query. 2. Shorten the query to its two most specific words, then try the field's own term or acronym (`references/search.md`, Writing queries).