1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
use std::time::Duration;
use crate::cache::{create_cache, PmcCache};
use crate::common::{PmcId, PubMedId};
use crate::config::ClientConfig;
use crate::error::{PubMedError, Result};
use crate::pmc::models::{ExtractedFigure, OaSubsetInfo, PmcFullText};
use crate::pmc::oa_api;
use crate::pmc::parser::parse_pmc_xml;
use crate::rate_limit::RateLimiter;
use crate::retry::with_retry;
use reqwest::{Client, Response};
use tracing::{debug, info};
#[cfg(not(target_arch = "wasm32"))]
use {crate::pmc::tar::PmcTarClient, std::path::Path};
/// Client for interacting with PMC (PubMed Central) API
#[derive(Clone)]
pub struct PmcClient {
client: Client,
base_url: String,
rate_limiter: RateLimiter,
config: ClientConfig,
#[cfg(not(target_arch = "wasm32"))]
tar_client: PmcTarClient,
cache: Option<PmcCache>,
}
impl PmcClient {
/// Create a new PMC client with default configuration
///
/// Uses default NCBI rate limiting (3 requests/second) and no API key.
/// For production use, consider using `with_config()` to set an API key.
///
/// # Example
///
/// ```
/// use pubmed_client_rs::PmcClient;
///
/// let client = PmcClient::new();
/// ```
pub fn new() -> Self {
let config = ClientConfig::new();
Self::with_config(config)
}
pub fn get_pmc_config(&self) -> &ClientConfig {
&self.config
}
#[cfg(not(target_arch = "wasm32"))]
pub fn get_tar_client_config(&self) -> &ClientConfig {
&self.tar_client.config
}
/// Create a new PMC client with custom configuration
///
/// # Arguments
///
/// * `config` - Client configuration including rate limits, API key, etc.
///
/// # Example
///
/// ```
/// use pubmed_client_rs::{PmcClient, ClientConfig};
///
/// let config = ClientConfig::new()
/// .with_api_key("your_api_key_here")
/// .with_email("researcher@university.edu");
///
/// let client = PmcClient::with_config(config);
/// ```
pub fn with_config(config: ClientConfig) -> Self {
let rate_limiter = config.create_rate_limiter();
let base_url = config.effective_base_url().to_string();
let client = {
#[cfg(not(target_arch = "wasm32"))]
{
Client::builder()
.user_agent(config.effective_user_agent())
.timeout(Duration::from_secs(config.timeout.as_secs()))
.build()
.expect("Failed to create HTTP client")
}
#[cfg(target_arch = "wasm32")]
{
Client::builder()
.user_agent(config.effective_user_agent())
.build()
.expect("Failed to create HTTP client")
}
};
let cache = config.cache_config.as_ref().map(create_cache);
Self {
client,
base_url,
rate_limiter,
#[cfg(not(target_arch = "wasm32"))]
tar_client: PmcTarClient::new(config.clone()),
cache,
config,
}
}
/// Create a new PMC client with custom HTTP client and default configuration
///
/// # Arguments
///
/// * `client` - Custom reqwest client with specific configuration
///
/// # Example
///
/// ```
/// use pubmed_client_rs::PmcClient;
/// use reqwest::Client;
/// use std::time::Duration;
///
/// let http_client = Client::builder()
/// .timeout(Duration::from_secs(30))
/// .build()
/// .unwrap();
///
/// let client = PmcClient::with_client(http_client);
/// ```
pub fn with_client(client: Client) -> Self {
let config = ClientConfig::new();
let rate_limiter = config.create_rate_limiter();
let base_url = config.effective_base_url().to_string();
Self {
client,
base_url,
rate_limiter,
#[cfg(not(target_arch = "wasm32"))]
tar_client: PmcTarClient::new(config.clone()),
cache: None,
config,
}
}
/// Set a custom base URL for the PMC API
///
/// # Arguments
///
/// * `base_url` - The base URL for the PMC API
pub fn with_base_url(mut self, base_url: String) -> Self {
self.base_url = base_url;
self
}
/// Fetch full text from PMC using PMCID
///
/// # Arguments
///
/// * `pmcid` - PMC ID (with or without "PMC" prefix)
///
/// # Returns
///
/// Returns a `Result<PmcFullText>` containing the structured full text
///
/// # Errors
///
/// * `PubMedError::PmcNotAvailable` - If PMC full text is not available
/// * `PubMedError::RequestError` - If the HTTP request fails
/// * `PubMedError::XmlError` - If XML parsing fails
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// let full_text = client.fetch_full_text("PMC7906746").await?;
/// println!("Title: {}", full_text.title);
/// println!("Sections: {}", full_text.sections.len());
/// Ok(())
/// }
/// ```
pub async fn fetch_full_text(&self, pmcid: &str) -> Result<PmcFullText> {
let normalized_pmcid = self.normalize_pmcid(pmcid);
let cache_key = format!("pmc:{}", normalized_pmcid);
// Check cache first if available
if let Some(cache) = &self.cache {
if let Some(cached) = cache.get(&cache_key).await {
info!(pmcid = %normalized_pmcid, "Cache hit for PMC full text");
return Ok(cached);
}
}
// Fetch from API if not cached
let xml_content = self.fetch_xml(pmcid).await?;
let full_text = parse_pmc_xml(&xml_content, &normalized_pmcid)?;
// Store in cache if available
if let Some(cache) = &self.cache {
cache.insert(cache_key, full_text.clone()).await;
}
Ok(full_text)
}
/// Fetch raw XML content from PMC
///
/// # Arguments
///
/// * `pmcid` - PMC ID (with or without "PMC" prefix)
///
/// # Returns
///
/// Returns a `Result<String>` containing the raw XML content
pub async fn fetch_xml(&self, pmcid: &str) -> Result<String> {
// Validate and parse PMC ID
let pmc_id = PmcId::parse(pmcid)?;
let normalized_pmcid = pmc_id.as_str();
let numeric_part = pmc_id.numeric_part();
// Build URL with API parameters
let mut url = format!(
"{}/efetch.fcgi?db=pmc&id=PMC{numeric_part}&retmode=xml",
self.base_url
);
// Add API parameters (API key, email, tool)
let api_params = self.config.build_api_params();
for (key, value) in api_params {
url.push('&');
url.push_str(&key);
url.push('=');
url.push_str(&urlencoding::encode(&value));
}
let response = self.make_request(&url).await?;
if !response.status().is_success() {
return Err(PubMedError::ApiError {
status: response.status().as_u16(),
message: response
.status()
.canonical_reason()
.unwrap_or("Unknown error")
.to_string(),
});
}
let xml_content = response.text().await?;
// Check if the response contains an error
if xml_content.contains("<ERROR>") {
return Err(PubMedError::PmcNotAvailable {
id: normalized_pmcid,
});
}
Ok(xml_content)
}
/// Check if PMC full text is available for a given PMID
///
/// # Arguments
///
/// * `pmid` - PubMed ID
///
/// # Returns
///
/// Returns `Result<Option<String>>` containing the PMCID if available
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// if let Some(pmcid) = client.check_pmc_availability("33515491").await? {
/// println!("PMC available: {}", pmcid);
/// let full_text = client.fetch_full_text(&pmcid).await?;
/// println!("Title: {}", full_text.title);
/// } else {
/// println!("PMC not available");
/// }
/// Ok(())
/// }
/// ```
pub async fn check_pmc_availability(&self, pmid: &str) -> Result<Option<String>> {
// Validate and parse PMID
let pmid_obj = PubMedId::parse(pmid)?;
let pmid_value = pmid_obj.as_u32();
// Build URL with API parameters
let mut url = format!(
"{}/elink.fcgi?dbfrom=pubmed&db=pmc&id={pmid_value}&retmode=json",
self.base_url
);
// Add API parameters (API key, email, tool)
let api_params = self.config.build_api_params();
for (key, value) in api_params {
url.push('&');
url.push_str(&key);
url.push('=');
url.push_str(&urlencoding::encode(&value));
}
let response = self.make_request(&url).await?;
if !response.status().is_success() {
return Err(PubMedError::ApiError {
status: response.status().as_u16(),
message: response
.status()
.canonical_reason()
.unwrap_or("Unknown error")
.to_string(),
});
}
let link_result: serde_json::Value = response.json().await?;
// Extract PMCID from response
if let Some(linksets) = link_result["linksets"].as_array() {
for linkset in linksets {
if let Some(linksetdbs) = linkset["linksetdbs"].as_array() {
for linksetdb in linksetdbs {
if linksetdb["dbto"] == "pmc" {
if let Some(links) = linksetdb["links"].as_array() {
if let Some(pmcid) = links.first() {
return Ok(Some(format!("PMC{pmcid}")));
}
}
}
}
}
}
}
Ok(None)
}
/// Check if a PMC article is in the OA (Open Access) subset
///
/// The OA subset contains articles with programmatic access to full-text XML.
/// Some publishers restrict programmatic access even though the article may be
/// viewable on the PMC website.
///
/// # Arguments
///
/// * `pmcid` - PMC ID (with or without "PMC" prefix)
///
/// # Returns
///
/// Returns `Result<OaSubsetInfo>` containing detailed information about OA availability
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// let oa_info = client.is_oa_subset("PMC7906746").await?;
///
/// if oa_info.is_oa_subset {
/// println!("Article is in OA subset");
/// if let Some(link) = oa_info.download_link {
/// println!("Download: {}", link);
/// }
/// } else {
/// println!("Article is NOT in OA subset");
/// if let Some(code) = oa_info.error_code {
/// println!("Reason: {}", code);
/// }
/// }
/// Ok(())
/// }
/// ```
pub async fn is_oa_subset(&self, pmcid: &str) -> Result<OaSubsetInfo> {
let url = oa_api::build_oa_api_url(pmcid)?;
let response = self.make_request(&url).await?;
if !response.status().is_success() {
return Err(PubMedError::ApiError {
status: response.status().as_u16(),
message: response
.status()
.canonical_reason()
.unwrap_or("Unknown error")
.to_string(),
});
}
let xml_content = response.text().await?;
// Parse the OA API XML response
oa_api::parse_oa_response(&xml_content, pmcid)
}
/// Download and extract tar.gz file for a PMC article using the OA API
///
/// # Arguments
///
/// * `pmcid` - PMC ID (with or without "PMC" prefix)
/// * `output_dir` - Directory to extract the tar.gz contents to
///
/// # Returns
///
/// Returns a `Result<Vec<String>>` containing the list of extracted file paths
///
/// # Errors
///
/// * `PubMedError::InvalidPmid` - If the PMCID format is invalid
/// * `PubMedError::RequestError` - If the HTTP request fails
/// * `PubMedError::IoError` - If file operations fail
/// * `PubMedError::PmcNotAvailable` - If the article is not available in OA
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
/// use std::path::Path;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// let output_dir = Path::new("./extracted_articles");
/// let files = client.download_and_extract_tar("PMC7906746", output_dir).await?;
///
/// for file in files {
/// println!("Extracted: {}", file);
/// }
/// Ok(())
/// }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn download_and_extract_tar<P: AsRef<Path>>(
&self,
pmcid: &str,
output_dir: P,
) -> Result<Vec<String>> {
self.tar_client
.download_and_extract_tar(pmcid, output_dir)
.await
}
/// Download, extract tar.gz file, and match figures with their captions from XML
///
/// # Arguments
///
/// * `pmcid` - PMC ID (with or without "PMC" prefix)
/// * `output_dir` - Directory to extract the tar.gz contents to
///
/// # Returns
///
/// Returns a `Result<Vec<ExtractedFigure>>` containing figures with both XML metadata and file paths
///
/// # Errors
///
/// * `PubMedError::InvalidPmid` - If the PMCID format is invalid
/// * `PubMedError::RequestError` - If the HTTP request fails
/// * `PubMedError::IoError` - If file operations fail
/// * `PubMedError::PmcNotAvailable` - If the article is not available in OA
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
/// use std::path::Path;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// let output_dir = Path::new("./extracted_articles");
/// let figures = client.extract_figures_with_captions("PMC7906746", output_dir).await?;
///
/// for figure in figures {
/// println!("Figure {}: {}", figure.figure.id, figure.figure.caption);
/// println!("File: {}", figure.extracted_file_path);
/// }
/// Ok(())
/// }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn extract_figures_with_captions<P: AsRef<Path>>(
&self,
pmcid: &str,
output_dir: P,
) -> Result<Vec<ExtractedFigure>> {
self.tar_client
.extract_figures_with_captions(pmcid, output_dir)
.await
}
/// Clear all cached PMC data
///
/// # Example
///
/// ```no_run
/// use pubmed_client_rs::PmcClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = PmcClient::new();
/// client.clear_cache().await;
/// Ok(())
/// }
/// ```
pub async fn clear_cache(&self) {
if let Some(cache) = &self.cache {
cache.clear().await;
info!("Cleared PMC cache");
}
}
/// Get cache statistics
///
/// Returns the number of items in cache, or 0 if caching is disabled
///
/// # Example
///
/// ```
/// use pubmed_client_rs::PmcClient;
///
/// let client = PmcClient::new();
/// let count = client.cache_entry_count();
/// println!("Cache entries: {}", count);
/// ```
pub fn cache_entry_count(&self) -> u64 {
self.cache.as_ref().map_or(0, |cache| cache.entry_count())
}
/// Synchronize cache operations to ensure all pending operations are flushed
///
/// This is useful for testing to ensure cache statistics are accurate
pub async fn sync_cache(&self) {
if let Some(cache) = &self.cache {
cache.sync().await;
}
}
/// Normalize PMCID format (ensure it starts with "PMC")
fn normalize_pmcid(&self, pmcid: &str) -> String {
// Use PmcId for validation and normalization
// If parsing fails, fall back to the old behavior for backwards compatibility
PmcId::parse(pmcid)
.map(|id| id.as_str())
.unwrap_or_else(|_| {
if pmcid.starts_with("PMC") {
pmcid.to_string()
} else {
format!("PMC{pmcid}")
}
})
}
/// Internal helper method for making HTTP requests with retry logic
async fn make_request(&self, url: &str) -> Result<Response> {
with_retry(
|| async {
self.rate_limiter.acquire().await?;
debug!("Making API request to: {url}");
let response = self
.client
.get(url)
.send()
.await
.map_err(PubMedError::from)?;
// Check if response has server error status and convert to retryable error
if response.status().is_server_error() || response.status().as_u16() == 429 {
return Err(PubMedError::ApiError {
status: response.status().as_u16(),
message: response
.status()
.canonical_reason()
.unwrap_or("Unknown error")
.to_string(),
});
}
Ok(response)
},
&self.config.retry_config,
"NCBI API request",
)
.await
}
}
impl Default for PmcClient {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_pmcid() {
let client = PmcClient::new();
assert_eq!(client.normalize_pmcid("1234567"), "PMC1234567");
assert_eq!(client.normalize_pmcid("PMC1234567"), "PMC1234567");
}
#[test]
fn test_client_creation() {
let client = PmcClient::new();
assert!(client.base_url.contains("eutils.ncbi.nlm.nih.gov"));
}
#[test]
fn test_custom_base_url() {
let client = PmcClient::new().with_base_url("https://custom.api.example.com".to_string());
assert_eq!(client.base_url, "https://custom.api.example.com");
}
}