use std::sync::Arc;
use std::time::{Duration, Instant};
use log::debug;
use crate::error::{RenamedError, Result};
use crate::models::{JobStatus, JobStatusResponse, PdfSplitResult};
const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(2);
const MAX_POLL_ATTEMPTS: u32 = 150;
pub type ProgressCallback = Box<dyn Fn(&JobStatusResponse) + Send + Sync>;
pub struct AsyncJob {
client: Arc<reqwest::Client>,
api_key: String,
status_url: String,
poll_interval: Duration,
max_attempts: u32,
debug: bool,
}
impl AsyncJob {
pub(crate) fn new(
client: Arc<reqwest::Client>,
api_key: String,
status_url: String,
debug: bool,
) -> Self {
Self {
client,
api_key,
status_url,
poll_interval: DEFAULT_POLL_INTERVAL,
max_attempts: MAX_POLL_ATTEMPTS,
debug,
}
}
fn extract_job_id(&self) -> &str {
self.status_url.rsplit('/').next().unwrap_or("unknown")
}
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts;
self
}
pub fn status_url(&self) -> &str {
&self.status_url
}
pub async fn status(&self) -> Result<JobStatusResponse> {
let start = Instant::now();
let response = self
.client
.get(&self.status_url)
.header("Authorization", format!("Bearer {}", self.api_key))
.send()
.await
.map_err(RenamedError::from_reqwest)?;
let status_code = response.status().as_u16();
let elapsed_ms = start.elapsed().as_millis();
let body = response.text().await.map_err(RenamedError::from_reqwest)?;
if status_code >= 400 {
return Err(RenamedError::from_http_status(status_code, Some(&body)));
}
let status_response: JobStatusResponse =
serde_json::from_str(&body).map_err(RenamedError::from_serde)?;
if self.debug {
let progress_str = status_response
.progress
.map(|p| format!(" ({}%)", p))
.unwrap_or_default();
debug!(
"[Renamed] Job {}: {}{} ({}ms)",
self.extract_job_id(),
status_response.status,
progress_str,
elapsed_ms
);
}
Ok(status_response)
}
pub async fn wait(&self, on_progress: Option<ProgressCallback>) -> Result<PdfSplitResult> {
for _attempt in 0..self.max_attempts {
let status = self.status().await?;
if let Some(ref callback) = on_progress {
callback(&status);
}
if status.status == JobStatus::Completed {
return status.result.ok_or_else(|| {
RenamedError::job_error(
"Job completed but no result returned",
Some(status.job_id),
)
});
}
if status.status == JobStatus::Failed {
return Err(RenamedError::job_error(
status.error.unwrap_or_else(|| "Job failed".to_string()),
Some(status.job_id),
));
}
tokio::time::sleep(self.poll_interval).await;
}
Err(RenamedError::job_error(
"Job polling timeout exceeded",
None,
))
}
pub async fn wait_without_progress(&self) -> Result<PdfSplitResult> {
self.wait(None).await
}
}
impl std::fmt::Debug for AsyncJob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AsyncJob")
.field("status_url", &self.status_url)
.field("poll_interval", &self.poll_interval)
.field("max_attempts", &self.max_attempts)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_async_job_builder() {
let client = Arc::new(reqwest::Client::new());
let job = AsyncJob::new(
client,
"test_key".to_string(),
"https://example.com/status".to_string(),
false,
)
.with_poll_interval(Duration::from_secs(5))
.with_max_attempts(10);
assert_eq!(job.poll_interval, Duration::from_secs(5));
assert_eq!(job.max_attempts, 10);
assert_eq!(job.status_url(), "https://example.com/status");
}
#[test]
fn test_extract_job_id() {
let client = Arc::new(reqwest::Client::new());
let job = AsyncJob::new(
client,
"test_key".to_string(),
"https://example.com/status/abc123".to_string(),
false,
);
assert_eq!(job.extract_job_id(), "abc123");
}
}