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 },
227 )
228 }
229
230 fn host_of(uri: &str) -> String {
231 uri.parse::<Url>()
232 .expect("valid uri")
233 .host_str()
234 .expect("has host")
235 .to_string()
236 }
237
238 fn base_of(server_uri: &str) -> Url {
239 format!("{}/v2", server_uri).parse().expect("valid base")
243 }
244
245 fn ok_response_body() -> serde_json::Value {
246 serde_json::json!({
247 "doi": TEST_DOI,
248 "is_oa": true,
249 "title": "Example",
250 "best_oa_location": {
251 "url": "https://example.org/free.pdf",
252 "license": "cc-by"
253 }
254 })
255 }
256
257 #[test]
258 fn unpaywall_can_serve_returns_true_for_doi() {
259 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
260 let profile = CapabilityProfile::from_env().expect("profile");
261 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
262 assert!(s.can_serve(&profile, &r));
263 }
264
265 #[test]
266 fn unpaywall_can_serve_returns_false_for_arxiv() {
267 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
268 let profile = CapabilityProfile::from_env().expect("profile");
269 let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
270 assert!(!s.can_serve(&profile, &r));
271 }
272
273 #[tokio::test]
274 async fn unpaywall_fetch_returns_oa_metadata() {
275 let server = MockServer::start().await;
276 Mock::given(method("GET"))
277 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
278 .and(query_param("email", TEST_EMAIL))
279 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
280 .mount(&server)
281 .await;
282
283 let host = host_of(&server.uri());
284 let (_td, ctx) = build_test_context(&host);
285 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
286 let profile = CapabilityProfile::from_env().expect("profile");
287 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
288
289 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
290 assert_eq!(res.source, "unpaywall");
291 assert!(res.final_url.is_some());
292 let meta = res.metadata_json.expect("metadata present");
293 let parsed: UnpaywallWork = serde_json::from_value(meta).expect("metadata round-trips");
294 assert!(parsed.is_oa);
295 assert_eq!(parsed.doi, TEST_DOI);
296 }
297
298 #[tokio::test]
299 async fn unpaywall_extracts_license_from_best_oa_location() {
300 let server = MockServer::start().await;
301 Mock::given(method("GET"))
302 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
303 .and(query_param("email", TEST_EMAIL))
304 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
305 .mount(&server)
306 .await;
307
308 let host = host_of(&server.uri());
309 let (_td, ctx) = build_test_context(&host);
310 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
311 let profile = CapabilityProfile::from_env().expect("profile");
312 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
313
314 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
315 assert_eq!(res.license, "cc-by");
316 }
317
318 #[tokio::test]
319 async fn unpaywall_falls_back_to_unknown_license() {
320 let body = serde_json::json!({
321 "doi": TEST_DOI,
322 "is_oa": true,
323 "best_oa_location": {
324 "url": "https://example.org/free.pdf",
325 "license": serde_json::Value::Null
326 }
327 });
328 let server = MockServer::start().await;
329 Mock::given(method("GET"))
330 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
331 .and(query_param("email", TEST_EMAIL))
332 .respond_with(ResponseTemplate::new(200).set_body_json(body))
333 .mount(&server)
334 .await;
335
336 let host = host_of(&server.uri());
337 let (_td, ctx) = build_test_context(&host);
338 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
339 let profile = CapabilityProfile::from_env().expect("profile");
340 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
341
342 let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
343 assert_eq!(res.license, "unknown");
344 }
345
346 #[tokio::test]
347 async fn unpaywall_with_arxiv_ref_errors_not_eligible() {
348 let (_td, ctx) = build_test_context("127.0.0.1");
351 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
352 let profile = CapabilityProfile::from_env().expect("profile");
353 let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
354
355 let err = s
356 .fetch(&r, &profile, &ctx)
357 .await
358 .expect_err("arxiv must be ineligible");
359 match err {
360 FetchError::NotEligible { source_key } => {
361 assert_eq!(source_key, "unpaywall");
362 }
363 other => panic!("expected NotEligible, got {:?}", other),
364 }
365 }
366
367 #[tokio::test]
368 async fn unpaywall_writes_log_row_with_license() {
369 let server = MockServer::start().await;
370 Mock::given(method("GET"))
371 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
372 .and(query_param("email", TEST_EMAIL))
373 .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
374 .mount(&server)
375 .await;
376
377 let host = host_of(&server.uri());
378 let (td, ctx) = build_test_context(&host);
379 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
380 let profile = CapabilityProfile::from_env().expect("profile");
381 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
382
383 let _res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
384
385 let log_path = Utf8PathBuf::try_from(td.path().to_path_buf())
388 .expect("temp path utf-8")
389 .join("test.jsonl");
390 let raw = std::fs::read_to_string(&log_path).expect("read log");
391 let rows: Vec<LogRow> = raw
392 .lines()
393 .filter(|l| !l.is_empty())
394 .map(|l| serde_json::from_str::<LogRow>(l).expect("valid LogRow"))
395 .collect();
396
397 let fetch_rows: Vec<&LogRow> = rows.iter().filter(|r| r.event == LogEvent::Fetch).collect();
398 assert_eq!(
399 fetch_rows.len(),
400 1,
401 "expected one Fetch row, got {:?}",
402 rows
403 );
404 let row = fetch_rows[0];
405 assert_eq!(row.result, LogResult::Ok);
406 assert_eq!(row.license.as_deref(), Some("cc-by"));
407 assert_eq!(row.source.as_deref(), Some("unpaywall"));
408 assert_eq!(row.ref_.as_deref(), Some(TEST_DOI));
409 }
410
411 #[test]
412 fn unpaywall_email_is_in_query_string() {
413 let s = UnpaywallSource::new(TEST_EMAIL.to_string());
420 let doi = Doi(TEST_DOI.to_string());
421 let url = s.request_url(&doi).expect("url builds");
422 let pair = url
423 .query_pairs()
424 .find(|(k, _)| k == "email")
425 .expect("email pair present");
426 assert_eq!(pair.1, TEST_EMAIL, "decoded email must match: {:?}", pair);
427 }
428
429 #[tokio::test]
430 async fn unpaywall_404_maps_to_http_error() {
431 let server = MockServer::start().await;
432 Mock::given(method("GET"))
433 .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
434 .respond_with(ResponseTemplate::new(404))
435 .mount(&server)
436 .await;
437
438 let host = host_of(&server.uri());
439 let (_td, ctx) = build_test_context(&host);
440 let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
441 let profile = CapabilityProfile::from_env().expect("profile");
442 let r = Ref::Doi(Doi(TEST_DOI.to_string()));
443
444 let err = s
445 .fetch(&r, &profile, &ctx)
446 .await
447 .expect_err("404 must error");
448 match err {
449 FetchError::Http(_) => {}
450 other => panic!("expected FetchError::Http, got {:?}", other),
451 }
452 }
453}