1use async_trait::async_trait;
9use serde::Deserialize;
10use url::Url;
11
12use crate::provenance::{Capability, LogEvent, LogResult, RowInput};
13use crate::source::{FetchContext, FetchError, FetchResult, Source};
14use crate::{CapabilityProfile, Ref};
15
16const DEFAULT_BASE: &str = "https://api.unpaywall.org/v2";
17
18#[derive(Clone, Debug)]
20pub struct UnpaywallSource {
21 base: Url,
22 contact_email: String,
23}
24
25impl UnpaywallSource {
26 pub fn new(contact_email: String) -> Self {
29 #[allow(clippy::expect_used)]
34 let base = Url::parse(DEFAULT_BASE).expect("hard-coded base URL is valid");
35 Self {
36 base,
37 contact_email,
38 }
39 }
40
41 pub fn with_base(base: Url, contact_email: String) -> Self {
48 Self {
49 base,
50 contact_email,
51 }
52 }
53
54 fn request_url(&self, doi: &crate::Doi) -> Result<Url, FetchError> {
55 let mut url = self.base.clone();
58 url.path_segments_mut()
61 .map_err(|()| FetchError::SourceSchema {
62 hint: "unpaywall base URL is cannot-be-a-base".into(),
63 })?
64 .push(doi.as_str()); url.query_pairs_mut()
66 .append_pair("email", &self.contact_email);
67 Ok(url)
68 }
69}
70
71#[async_trait]
72impl Source for UnpaywallSource {
73 fn name(&self) -> &str {
74 "unpaywall"
75 }
76
77 fn can_serve(&self, _profile: &CapabilityProfile, ref_: &Ref) -> bool {
78 matches!(ref_, Ref::Doi(_))
79 }
80
81 async fn fetch(
82 &self,
83 ref_: &Ref,
84 _profile: &CapabilityProfile,
85 ctx: &FetchContext,
86 ) -> Result<FetchResult, FetchError> {
87 let doi = match ref_ {
88 Ref::Doi(d) => d,
89 Ref::Arxiv(_) => {
90 return Err(FetchError::NotEligible {
91 source_key: "unpaywall".into(),
92 });
93 }
94 };
95
96 let _permit = ctx.rate_limiter.acquire(self.name()).await;
97
98 let url = self.request_url(doi)?;
99 let (body, final_url) = ctx.http.fetch_bytes(self.name(), url).await?;
100
101 let work: UnpaywallWork =
102 serde_json::from_slice(&body).map_err(|e| FetchError::SourceSchema {
103 hint: format!("unpaywall returned non-JSON: {e}"),
104 })?;
105
106 let license = work
110 .best_oa_location
111 .as_ref()
112 .and_then(|loc| loc.license.clone())
113 .unwrap_or_else(|| "unknown".to_string());
114
115 let canonical = ref_.promote(self.name(), None).digest_hex();
118 ctx.log.append(RowInput {
119 event: LogEvent::Fetch,
120 result: LogResult::Ok,
121 capability: Capability::Oa,
122 ref_: Some(doi.as_str()),
123 source: Some(self.name()),
124 error_code: None,
125 size_bytes: Some(body.len() as u64),
126 license: Some(&license),
127 store_path: None,
128 canonical_digest: Some(&canonical),
129 })?;
130
131 Ok(FetchResult {
141 source: self.name().to_string(),
142 license,
143 pdf_bytes: None,
144 final_url: Some(final_url),
145 metadata_json: Some(serde_json::to_value(&work).unwrap_or(serde_json::Value::Null)),
146 })
147 }
148}
149
150#[derive(Debug, Deserialize, serde::Serialize)]
153struct UnpaywallWork {
154 doi: String,
155 is_oa: bool,
156 #[serde(default)]
157 title: Option<String>,
158 #[serde(default)]
159 best_oa_location: Option<UnpaywallOaLocation>,
160 #[serde(default)]
161 oa_locations: Vec<UnpaywallOaLocation>,
162}
163
164#[derive(Debug, Deserialize, serde::Serialize, Clone)]
165struct UnpaywallOaLocation {
166 #[serde(default)]
167 url: Option<String>,
168 #[serde(default)]
169 url_for_pdf: Option<String>,
170 #[serde(default)]
171 license: Option<String>,
172}
173
174#[cfg(test)]
179#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
180mod tests {
181 use super::*;
182
183 use std::sync::Arc;
184
185 use camino::Utf8PathBuf;
186 use tempfile::TempDir;
187 use wiremock::matchers::{method, path, query_param};
188 use wiremock::{Mock, MockServer, ResponseTemplate};
189
190 use crate::http::HttpClient;
191 use crate::provenance::{LogRow, ProvenanceLog};
192 use crate::rate_limiter::RateLimiter;
193 use crate::source::FetchContext;
194 use crate::{ArxivId, CapabilityProfile, Doi, RateLimits};
195
196 const TEST_EMAIL: &str = "alice@example.org";
197 const TEST_DOI: &str = "10.1234/example";
198 const TEST_DOI_ENCODED: &str = "10.1234%2Fexample";
202
203 fn build_test_context(host: &str) -> (TempDir, FetchContext) {
207 let td = TempDir::new().expect("tempdir");
208 let log_dir =
209 Utf8PathBuf::try_from(td.path().to_path_buf()).expect("temp dir path must be UTF-8");
210 let log_path = log_dir.join("test.jsonl");
211
212 let http = Arc::new(HttpClient::new_for_tests_allow_http("unpaywall", host));
213 let rate_limiter = Arc::new(RateLimiter::new(RateLimits::HARD_CODED));
214 let session_id = "01J0000000000000000000TEST".to_string();
215 let log = Arc::new(
216 ProvenanceLog::open(log_path, session_id.clone()).expect("provenance log opens"),
217 );
218
219 (
220 td,
221 FetchContext {
222 http,
223 rate_limiter,
224 log,
225 session_id,
226 cache_root: None,
227 },
228 )
229 }
230
231 fn host_of(uri: &str) -> String {
232 uri.parse::<Url>()
233 .expect("valid uri")
234 .host_str()
235 .expect("has host")
236 .to_string()
237 }
238
239 fn base_of(server_uri: &str) -> Url {
240 format!("{}/v2", server_uri).parse().expect("valid base")
244 }
245
246 fn ok_response_body() -> serde_json::Value {
247 serde_json::json!({
248 "doi": TEST_DOI,
249 "is_oa": true,
250 "title": "Example",
251 "best_oa_location": {
252 "url": "https://example.org/free.pdf",
253 "license": "cc-by"
254 }
255 })
256 }
257
258 #[test]
259 fn unpaywall_can_serve_returns_true_for_doi() {
260 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
261 let profile = CapabilityProfile::from_env().expect("profile");
262 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
263 assert!(s.can_serve(&profile, &r));
264 }
265
266 #[test]
267 fn unpaywall_can_serve_returns_false_for_arxiv() {
268 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
269 let profile = CapabilityProfile::from_env().expect("profile");
270 let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
271 assert!(!s.can_serve(&profile, &r));
272 }
273
274 #[tokio::test]
275 async fn unpaywall_fetch_returns_oa_metadata() {
276 let server = MockServer::start().await;
277 Mock::given(method("GET"))
278 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
279 .and(query_param("email", TEST_EMAIL))
280 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
281 .mount(&server)
282 .await;
283
284 let host = host_of(&server.uri());
285 let (_td, ctx) = build_test_context(&host);
286 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
287 let profile = CapabilityProfile::from_env().expect("profile");
288 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
289
290 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
291 assert_eq!(res.source, "unpaywall");
292 assert!(res.final_url.is_some());
293 let meta = res.metadata_json.expect("metadata present");
294 let parsed: UnpaywallWork = serde_json::from_value(meta).expect("metadata round-trips");
295 assert!(parsed.is_oa);
296 assert_eq!(parsed.doi, TEST_DOI);
297 }
298
299 #[tokio::test]
300 async fn unpaywall_extracts_license_from_best_oa_location() {
301 let server = MockServer::start().await;
302 Mock::given(method("GET"))
303 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
304 .and(query_param("email", TEST_EMAIL))
305 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
306 .mount(&server)
307 .await;
308
309 let host = host_of(&server.uri());
310 let (_td, ctx) = build_test_context(&host);
311 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
312 let profile = CapabilityProfile::from_env().expect("profile");
313 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
314
315 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
316 assert_eq!(res.license, "cc-by");
317 }
318
319 #[tokio::test]
320 async fn unpaywall_falls_back_to_unknown_license() {
321 let body = serde_json::json!({
322 "doi": TEST_DOI,
323 "is_oa": true,
324 "best_oa_location": {
325 "url": "https://example.org/free.pdf",
326 "license": serde_json::Value::Null
327 }
328 });
329 let server = MockServer::start().await;
330 Mock::given(method("GET"))
331 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
332 .and(query_param("email", TEST_EMAIL))
333 .respond_with(ResponseTemplate::new(200).set_body_json(body))
334 .mount(&server)
335 .await;
336
337 let host = host_of(&server.uri());
338 let (_td, ctx) = build_test_context(&host);
339 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
340 let profile = CapabilityProfile::from_env().expect("profile");
341 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
342
343 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
344 assert_eq!(res.license, "unknown");
345 }
346
347 #[tokio::test]
348 async fn unpaywall_with_arxiv_ref_errors_not_eligible() {
349 let (_td, ctx) = build_test_context("127.0.0.1");
352 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
353 let profile = CapabilityProfile::from_env().expect("profile");
354 let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
355
356 let err = s
357 .fetch(&r, &profile, &ctx)
358 .await
359 .expect_err("arxiv must be ineligible");
360 match err {
361 FetchError::NotEligible { source_key } => {
362 assert_eq!(source_key, "unpaywall");
363 }
364 other => panic!("expected NotEligible, got {:?}", other),
365 }
366 }
367
368 #[tokio::test]
369 async fn unpaywall_writes_log_row_with_license() {
370 let server = MockServer::start().await;
371 Mock::given(method("GET"))
372 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
373 .and(query_param("email", TEST_EMAIL))
374 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
375 .mount(&server)
376 .await;
377
378 let host = host_of(&server.uri());
379 let (td, ctx) = build_test_context(&host);
380 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
381 let profile = CapabilityProfile::from_env().expect("profile");
382 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
383
384 let _res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
385
386 let log_path = Utf8PathBuf::try_from(td.path().to_path_buf())
389 .expect("temp path utf-8")
390 .join("test.jsonl");
391 let raw = std::fs::read_to_string(&log_path).expect("read log");
392 let rows: Vec<LogRow> = raw
393 .lines()
394 .filter(|l| !l.is_empty())
395 .map(|l| serde_json::from_str::<LogRow>(l).expect("valid LogRow"))
396 .collect();
397
398 let fetch_rows: Vec<&LogRow> = rows.iter().filter(|r| r.event == LogEvent::Fetch).collect();
399 assert_eq!(
400 fetch_rows.len(),
401 1,
402 "expected one Fetch row, got {:?}",
403 rows
404 );
405 let row = fetch_rows[0];
406 assert_eq!(row.result, LogResult::Ok);
407 assert_eq!(row.license.as_deref(), Some("cc-by"));
408 assert_eq!(row.source.as_deref(), Some("unpaywall"));
409 assert_eq!(row.ref_.as_deref(), Some(TEST_DOI));
410 }
411
412 #[test]
413 fn unpaywall_email_is_in_query_string() {
414 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
421 let doi = Doi(TEST_DOI.to_string());
422 let url = s.request_url(&doi).expect("url builds");
423 let pair = url
424 .query_pairs()
425 .find(|(k, _)| k == "email")
426 .expect("email pair present");
427 assert_eq!(pair.1, TEST_EMAIL, "decoded email must match: {:?}", pair);
428 }
429
430 #[tokio::test]
431 async fn unpaywall_404_maps_to_http_error() {
432 let server = MockServer::start().await;
433 Mock::given(method("GET"))
434 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
435 .respond_with(ResponseTemplate::new(404))
436 .mount(&server)
437 .await;
438
439 let host = host_of(&server.uri());
440 let (_td, ctx) = build_test_context(&host);
441 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
442 let profile = CapabilityProfile::from_env().expect("profile");
443 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
444
445 let err = s
446 .fetch(&r, &profile, &ctx)
447 .await
448 .expect_err("404 must error");
449 match err {
450 FetchError::Http(_) => {}
451 other => panic!("expected FetchError::Http, got {:?}", other),
452 }
453 }
454}