use std::time::Duration;
use reqwest::Client;
use reqwest::header::{HeaderMap, HeaderValue};
use tracing::{debug, warn};
use crate::error::Error;
use crate::models::*;
use crate::pagination::PagedResponse;
const DEFAULT_TIMEOUT_SECS: u64 = 30;
const MAX_RETRIES: u32 = 3;
#[derive(Clone)]
pub struct FuncspecClient {
http: Client,
base_url: String,
max_retries: u32,
}
impl FuncspecClient {
pub fn new(base_url: &str, api_key: &str) -> Result<Self, Error> {
Self::with_timeout(base_url, api_key, Duration::from_secs(DEFAULT_TIMEOUT_SECS))
}
pub fn with_timeout(base_url: &str, api_key: &str, timeout: Duration) -> Result<Self, Error> {
let mut headers = HeaderMap::new();
headers.insert(
"X-Api-Key",
HeaderValue::from_str(api_key).map_err(|e| Error::Other(e.to_string()))?,
);
let http = Client::builder()
.default_headers(headers)
.user_agent(format!("funcspec-cli/{}", env!("CARGO_PKG_VERSION")))
.timeout(timeout)
.build()?;
let base_url = base_url.trim_end_matches('/').to_string();
Ok(Self {
http,
base_url,
max_retries: MAX_RETRIES,
})
}
fn api_url(&self, path: &str) -> String {
format!("{}/api/v1{}", self.base_url, path)
}
async fn request_with_retry<F, Fut>(&self, make_request: F) -> Result<reqwest::Response, Error>
where
F: Fn() -> Fut,
Fut: std::future::Future<Output = Result<reqwest::Response, reqwest::Error>>,
{
let mut attempt = 0u32;
loop {
match make_request().await {
Ok(resp) => {
if resp.status().as_u16() == 429 && attempt < self.max_retries {
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or_else(|| {
1u64 << attempt.min(6)
});
let delay = Duration::from_secs(retry_after.min(60));
warn!(
attempt,
retry_after_secs = retry_after,
"Rate limited, backing off"
);
tokio::time::sleep(delay).await;
attempt += 1;
continue;
}
return Ok(resp);
}
Err(e) if attempt < self.max_retries => {
if e.is_connect() {
let delay = Duration::from_secs(1u64 << attempt.min(6));
warn!(attempt, error = %e, "Connection error, retrying");
tokio::time::sleep(delay).await;
attempt += 1;
continue;
}
return Err(Error::from(e));
}
Err(e) => return Err(Error::from(e)),
}
}
}
pub async fn validate_auth(&self) -> Result<UserInfo, Error> {
let projects = self.list_projects().await?;
let project_count = projects.len();
Ok(UserInfo {
id: String::new(),
email: String::new(),
name: format!("{project_count} project(s) accessible"),
org_id: String::new(),
org_name: String::new(),
})
}
pub async fn list_projects(&self) -> Result<Vec<Project>, Error> {
let url = self.api_url("/projects");
debug!(%url, "list_projects");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<Project> = resp.json().await?;
Ok(body.data)
}
pub async fn list_projects_paged(
&self,
page: u32,
per_page: u32,
) -> Result<PagedResponse<Project>, Error> {
let url = self.api_url("/projects");
let resp = self
.request_with_retry(|| {
self.http
.get(&url)
.query(&[("page", page), ("per", per_page)])
.send()
})
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<Project> = resp.json().await?;
Ok((body.data, body.meta).into())
}
pub async fn get_project(&self, slug_or_id: &str) -> Result<Project, Error> {
let url = self.api_url(&format!("/projects/{slug_or_id}"));
debug!(%url, "get_project");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Project> = resp.json().await?;
Ok(body.data)
}
pub async fn create_project(&self, params: &CreateProjectParams) -> Result<Project, Error> {
let url = self.api_url("/projects");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Project> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_project(&self, slug_or_id: &str) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{slug_or_id}"));
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn list_items(
&self,
project_id: u64,
filter: &ItemFilter,
) -> Result<(Vec<SpecItem>, Option<PaginationMeta>), Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
debug!(%url, "list_items");
let resp = self
.request_with_retry(|| self.http.get(&url).query(&filter.to_query_pairs()).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<SpecItem> = resp.json().await?;
Ok((body.data, body.meta))
}
pub async fn list_items_paged(
&self,
project_id: u64,
filter: &ItemFilter,
page: u32,
per_page: u32,
) -> Result<PagedResponse<SpecItem>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
let mut pairs = filter.to_query_pairs();
pairs.push(("page".into(), page.to_string()));
pairs.push(("per".into(), per_page.to_string()));
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<SpecItem> = resp.json().await?;
Ok((body.data, body.meta).into())
}
pub async fn list_all_items(
&self,
project_id: u64,
filter: &ItemFilter,
) -> Result<Vec<SpecItem>, Error> {
const PER: u32 = 100;
let mut all: Vec<SpecItem> = Vec::new();
let mut page: u32 = 1;
loop {
let resp = self.list_items_paged(project_id, filter, page, PER).await?;
let total_pages = resp.total_pages;
let items = resp.data;
let got = items.len() as u32;
all.extend(items);
let more = if total_pages > 0 {
page < total_pages
} else {
got == PER
};
if !more {
break;
}
page += 1;
}
Ok(all)
}
pub async fn search_items(
&self,
project_id: u64,
query: &str,
filter: &ItemFilter,
) -> Result<PagedResponse<SpecItem>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
debug!(%url, %query, "search_items");
let mut pairs = filter.to_query_pairs();
pairs.retain(|(k, _)| k != "q");
pairs.push(("q".into(), query.to_string()));
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<SpecItem> = resp.json().await?;
Ok((body.data, body.meta).into())
}
pub async fn resolve_item_id(
&self,
project_id: u64,
id_or_permalink: &str,
) -> Result<u64, Error> {
if let Ok(numeric) = id_or_permalink.parse::<u64>() {
return Ok(numeric);
}
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{id_or_permalink}"
));
debug!(%url, "resolve_item_id via permalink");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::NotFound(format!(
"Item with permalink \"{id_or_permalink}\" not found"
)));
}
let body: ApiResponse<SpecItem> = resp.json().await?;
Ok(body.data.id)
}
pub async fn get_item(
&self,
project_id: u64,
id_or_permalink: &str,
) -> Result<SpecItem, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{id_or_permalink}"
));
debug!(%url, "get_item");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<SpecItem> = resp.json().await?;
Ok(body.data)
}
pub async fn create_item(
&self,
project_id: u64,
params: &CreateItemParams,
) -> Result<SpecItem, Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items"));
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<SpecItem> = resp.json().await?;
Ok(body.data)
}
pub async fn update_item(
&self,
project_id: u64,
item_id: u64,
params: &UpdateItemParams,
) -> Result<SpecItem, Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items/{item_id}"));
let resp = self
.request_with_retry(|| self.http.patch(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<SpecItem> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_item(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/items/{item_id}"));
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn deprecate_item(
&self,
project_id: u64,
permalink: &str,
reason: Option<&str>,
confirm: bool,
) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{permalink}/deprecate"
));
debug!(%url, "deprecate_item");
let mut body = serde_json::Map::new();
if let Some(r) = reason {
body.insert("reason".into(), serde_json::Value::String(r.to_string()));
}
if confirm {
body.insert("confirm".into(), serde_json::Value::Bool(true));
}
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn undeprecate_item(&self, project_id: u64, permalink: &str) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{permalink}/undeprecate"
));
debug!(%url, "undeprecate_item");
let resp = self
.request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn transition_item_state(
&self,
project_id: u64,
permalink: &str,
state: &str,
) -> Result<SpecItem, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{permalink}/transition"
));
debug!(%url, %state, "transition_item_state");
let body = serde_json::json!({ "state": state });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<SpecItem> = resp.json().await?;
Ok(body.data)
}
pub async fn list_reviews(&self, spec_item_id: u64) -> Result<Vec<Review>, Error> {
let url = self.api_url(&format!("/spec/items/{spec_item_id}/reviews"));
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<Review> = resp.json().await?;
Ok(body.data)
}
pub async fn create_review(
&self,
spec_item_id: u64,
params: &CreateReviewParams,
) -> Result<Review, Error> {
let url = self.api_url(&format!("/spec/items/{spec_item_id}/reviews"));
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Review> = resp.json().await?;
Ok(body.data)
}
pub async fn list_jobs(&self) -> Result<Vec<Job>, Error> {
let url = self.api_url("/jobs");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<Job> = resp.json().await?;
Ok(body.data)
}
pub async fn get_job(&self, project_id: u64, job_id: u64) -> Result<Job, Error> {
let url = self.api_url(&format!("/projects/{project_id}/jobs/{job_id}"));
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Job> = resp.json().await?;
Ok(body.data)
}
pub async fn review_item(&self, project_id: u64, item_id: u64) -> Result<Review, Error> {
self.review_item_async(project_id, item_id, "review").await
}
async fn review_item_async(
&self,
project_id: u64,
item_id: u64,
kind: &str,
) -> Result<Review, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/{kind}"
));
debug!(%url, "review_item_async");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AsyncJobRef> = resp.json().await?;
let job_id = body
.data
.job_id
.ok_or_else(|| Error::Other("review response did not include a job_id".into()))?;
let job = self
.poll_job_until_done(project_id, job_id, Duration::from_secs(300))
.await?;
if job.attributes.status == JobStatus::Failed {
return Err(Error::Other(format!("AI review job {job_id} failed")));
}
let _ = kind;
let item = self.get_item(project_id, &item_id.to_string()).await?;
let summary = item.attributes.review.ok_or_else(|| {
Error::Other("review job completed but no review is present on the item".into())
})?;
let coverage_map = summary
.coverage_map
.and_then(|v| serde_json::from_value(v).ok())
.unwrap_or_default();
Ok(Review {
id: None,
resource_type: "review".to_string(),
attributes: ReviewAttributes {
coverage_score: summary.coverage_score,
collective_coverage_score: None,
verdict: summary.verdict,
tech_item_id: None,
tech_item_title: None,
func_item_ids: Vec::new(),
functional_requirements_parsed: Vec::new(),
coverage_map,
gaps: summary.gaps.unwrap_or_default(),
suggestions: summary.suggestions.unwrap_or_default(),
risks: summary.risks.unwrap_or_default(),
reviewed_at: summary.reviewed_at,
},
})
}
pub async fn review_all(&self, project_id: u64) -> Result<u64, Error> {
let url = self.api_url(&format!("/projects/{project_id}/work_package/review_all"));
debug!(%url, "review_all");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AsyncJobRef> = resp.json().await?;
body.data
.job_id
.ok_or_else(|| Error::Other("review_all response had no job_id".into()))
}
pub async fn propose_improvement(
&self,
project_id: u64,
item_id: u64,
) -> Result<Proposal, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/propose"
));
debug!(%url, "propose_improvement");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Proposal> = resp.json().await?;
Ok(body.data)
}
pub async fn accept_proposal(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/accept"
));
debug!(%url, "accept_proposal");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn reject_proposal(&self, project_id: u64, item_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/reject"
));
debug!(%url, "reject_proposal");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn generate_tech(
&self,
project_id: u64,
item_id: u64,
) -> Result<TechProposals, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/generate_tech"
));
debug!(%url, "generate_tech");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<TechProposals> = resp.json().await?;
Ok(body.data)
}
pub async fn audit_item(&self, project_id: u64, item_id: u64) -> Result<AuditResult, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/audit"
));
debug!(%url, "audit_item");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditResult> = resp.json().await?;
Ok(body.data)
}
pub async fn get_project_job(&self, project_id: u64, job_id: u64) -> Result<Job, Error> {
let url = self.api_url(&format!("/projects/{project_id}/jobs/{job_id}"));
debug!(%url, "get_project_job");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Job> = resp.json().await?;
Ok(body.data)
}
pub async fn poll_job_until_done(
&self,
project_id: u64,
job_id: u64,
timeout: Duration,
) -> Result<Job, Error> {
let start = std::time::Instant::now();
let poll_interval = Duration::from_millis(500);
loop {
let job = self.get_job(project_id, job_id).await?;
match job.attributes.status {
JobStatus::Completed | JobStatus::Failed => return Ok(job),
_ => {}
}
if start.elapsed() >= timeout {
return Err(Error::Timeout {
secs: timeout.as_secs(),
});
}
tokio::time::sleep(poll_interval).await;
}
}
pub async fn transition_item_implementation(
&self,
project_id: u64,
item_id: u64,
status: &str,
) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/spec/items/{item_id}/transition_implementation"
));
debug!(%url, %status, "transition_item_implementation");
let body = serde_json::json!({ "implementation_status": status });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn link_commit(
&self,
project_id: u64,
item_id: u64,
params: &LinkCommitParams,
) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/link_commit"
));
debug!(%url, sha = %params.sha, "link_commit");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn record_run(
&self,
project_id: u64,
item_id: u64,
params: &RecordRunParams,
) -> Result<Option<u64>, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/work_package/{item_id}/record_run"
));
debug!(%url, "record_run");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
let run_id = body
.get("data")
.and_then(|d| d.get("id"))
.and_then(|v| v.as_u64());
Ok(run_id)
}
pub async fn review_item_functional(
&self,
project_id: u64,
item_id: u64,
) -> Result<Review, Error> {
self.review_item_async(project_id, item_id, "func_review")
.await
}
pub async fn list_usage(&self) -> Result<Vec<UsageLogEntry>, Error> {
let url = self.api_url("/usage");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<UsageLogEntry> = resp.json().await?;
Ok(body.data)
}
pub async fn get_project_stats(
&self,
project_id: u64,
release_version: Option<&str>,
) -> Result<ProjectStats, Error> {
let url = self.api_url(&format!("/projects/{project_id}/stats"));
debug!(%url, ?release_version, "get_project_stats");
let mut pairs: Vec<(String, String)> = Vec::new();
if let Some(rv) = release_version {
pairs.push(("release_version".into(), rv.to_string()));
}
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let text = resp
.text()
.await
.map_err(|e| Error::Network(e.to_string()))?;
let body: ApiResponse<ProjectStats> = serde_json::from_str(&text).map_err(|e| {
Error::Other(format!("Failed to parse stats response: {e}\nBody: {text}"))
})?;
Ok(body.data)
}
pub async fn get_usage_logs(
&self,
project_id: u64,
filter: &UsageFilter,
) -> Result<PagedResponse<UsageLogEntry>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/usage/logs"));
debug!(%url, "get_usage_logs");
let pairs = filter.to_query_pairs();
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<UsageLogEntry> = resp.json().await?;
Ok((body.data, body.meta).into())
}
pub async fn get_usage_stats(
&self,
project_id: u64,
year: Option<i32>,
month: Option<u32>,
) -> Result<UsageStats, Error> {
let url = self.api_url(&format!("/projects/{project_id}/usage"));
debug!(%url, "get_usage_stats");
let mut pairs: Vec<(String, String)> = Vec::new();
if let Some(y) = year {
pairs.push(("year".into(), y.to_string()));
}
if let Some(m) = month {
pairs.push(("month".into(), m.to_string()));
}
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let text = resp
.text()
.await
.map_err(|e| Error::Network(e.to_string()))?;
let body: UsageStats = serde_json::from_str(&text).map_err(|e| {
Error::Other(format!(
"Failed to parse usage stats: {e}
Body: {text}"
))
})?;
Ok(body)
}
pub async fn export_project(
&self,
project_id: u64,
format: &str,
item_type: Option<&str>,
tag: Option<&str>,
release_version: Option<&str>,
) -> Result<ExportData, Error> {
let format_path = match format {
"md" => "markdown",
"json" => "json",
"csv" => "csv",
"html" => "html",
"pdf" => "pdf",
"docx" => "docx",
other => other,
};
let url = self.api_url(&format!("/projects/{project_id}/export/{format_path}"));
debug!(%url, %format, "export_project");
let mut pairs: Vec<(String, String)> = vec![];
if let Some(t) = item_type {
pairs.push(("type_of".into(), t.to_string()));
}
if let Some(t) = tag {
pairs.push(("tag".into(), t.to_string()));
}
if let Some(rv) = release_version {
pairs.push(("release_version".into(), rv.to_string()));
}
let resp = self
.request_with_retry(|| self.http.get(&url).query(&pairs).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let is_binary = matches!(format, "pdf" | "docx");
if is_binary {
let bytes = resp.bytes().await.map_err(Error::from)?;
Ok(ExportData::Binary(bytes.to_vec()))
} else {
let text = resp.text().await.map_err(Error::from)?;
Ok(ExportData::Text(text))
}
}
pub async fn get_viewable_html(&self, project_id: u64) -> Result<String, Error> {
let url = self.api_url(&format!("/projects/{project_id}/spec/view"));
debug!(%url, "get_viewable_html");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
resp.text().await.map_err(Error::from)
}
pub async fn list_snapshots(&self, project_id: u64) -> Result<Vec<Snapshot>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/snapshots"));
debug!(%url, "list_snapshots");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<Snapshot> = resp.json().await?;
Ok(body.data)
}
pub async fn create_snapshot(
&self,
project_id: u64,
params: &CreateSnapshotParams,
) -> Result<Snapshot, Error> {
let url = self.api_url(&format!("/projects/{project_id}/snapshots"));
debug!(%url, "create_snapshot");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Snapshot> = resp.json().await?;
Ok(body.data)
}
pub async fn get_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<Snapshot, Error> {
let url = self.api_url(&format!("/projects/{project_id}/snapshots/{snapshot_id}"));
debug!(%url, "get_snapshot");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<Snapshot> = resp.json().await?;
Ok(body.data)
}
pub async fn restore_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/snapshots/{snapshot_id}/restore"
));
debug!(%url, "restore_snapshot");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn delete_snapshot(&self, project_id: u64, snapshot_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{project_id}/snapshots/{snapshot_id}"));
debug!(%url, "delete_snapshot");
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn diff_snapshot(
&self,
project_id: u64,
snapshot_id: u64,
) -> Result<SnapshotDiff, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/snapshots/{snapshot_id}/diff"
));
debug!(%url, "diff_snapshot");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<SnapshotDiff> = resp.json().await?;
Ok(body.data)
}
pub async fn list_edges(
&self,
project_id: u64,
source_id: Option<u64>,
target_id: Option<u64>,
edge_type: Option<&str>,
) -> Result<Vec<DependencyEdge>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/graph/edges"));
debug!(%url, "list_edges");
let mut params: Vec<(&str, String)> = vec![];
if let Some(sid) = source_id {
params.push(("source_id", sid.to_string()));
}
if let Some(tid) = target_id {
params.push(("target_id", tid.to_string()));
}
if let Some(et) = edge_type {
params.push(("edge_type", et.to_string()));
}
let resp = self
.request_with_retry(|| self.http.get(&url).query(¶ms).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
#[derive(serde::Deserialize)]
struct Resp {
data: Vec<DependencyEdge>,
}
let body: Resp = resp.json().await?;
Ok(body.data)
}
pub async fn create_edge(
&self,
project_id: u64,
params: &CreateEdgeParams,
) -> Result<DependencyEdge, Error> {
let url = self.api_url(&format!("/projects/{project_id}/graph/edges"));
debug!(%url, "create_edge");
let body = serde_json::json!({ "dependency_edge": params });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let resp_body: ApiResponse<DependencyEdge> = resp.json().await?;
Ok(resp_body.data)
}
pub async fn get_edge(&self, project_id: u64, edge_id: u64) -> Result<DependencyEdge, Error> {
let url = self.api_url(&format!("/projects/{project_id}/graph/edges/{edge_id}"));
debug!(%url, "get_edge");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<DependencyEdge> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_edge(&self, project_id: u64, edge_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{project_id}/graph/edges/{edge_id}"));
debug!(%url, "delete_edge");
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn get_org_slug(&self) -> Result<String, Error> {
let url = self.api_url("/settings");
debug!(%url, "get_org_slug");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: serde_json::Value = resp.json().await?;
let slug = body
.get("data")
.and_then(|d| d.get("attributes"))
.and_then(|a| a.get("slug"))
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string();
Ok(slug)
}
pub async fn get_agent_instructions(
&self,
project_slug: &str,
) -> Result<serde_json::Value, Error> {
let url = self.api_url(&format!("/projects/{project_slug}/agent_instructions"));
debug!(%url, "get_agent_instructions");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: serde_json::Value = resp.json().await?;
Ok(body)
}
pub async fn list_runs(
&self,
project_id: u64,
page: u32,
per: u32,
) -> Result<(Vec<AuditRun>, Option<PaginationMeta>), Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs"));
debug!(%url, "list_runs");
let resp = self
.request_with_retry(|| {
self.http
.get(&url)
.query(&[("page", page), ("per", per)])
.send()
})
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<AuditRun> = resp.json().await?;
Ok((body.data, body.meta))
}
pub async fn preview_run(
&self,
project_id: u64,
params: &CreateRunParams,
) -> Result<RunPreview, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/preview"));
debug!(%url, "preview_run");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<RunPreview> = resp.json().await?;
Ok(body.data)
}
pub async fn create_run(
&self,
project_id: u64,
params: &CreateRunParams,
) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs"));
debug!(%url, "create_run");
let resp = self
.request_with_retry(|| self.http.post(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn get_run(
&self,
project_id: u64,
run_id: u64,
page: u32,
per: u32,
) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
debug!(%url, "get_run");
let resp = self
.request_with_retry(|| {
self.http
.get(&url)
.query(&[("page", page), ("per", per)])
.send()
})
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn update_run(
&self,
project_id: u64,
run_id: u64,
params: &UpdateRunParams,
) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
debug!(%url, "update_run");
let resp = self
.request_with_retry(|| self.http.patch(&url).json(params).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn start_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/start"));
debug!(%url, "start_run");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn pause_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/pause"));
debug!(%url, "pause_run");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn resume_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/resume"));
debug!(%url, "resume_run");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn cancel_run(&self, project_id: u64, run_id: u64) -> Result<AuditRun, Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}/cancel"));
debug!(%url, "cancel_run");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<AuditRun> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_run(&self, project_id: u64, run_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{project_id}/runs/{run_id}"));
debug!(%url, "delete_run");
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn add_items_to_version(
&self,
project_id: u64,
version: &str,
spec_item_keys: &[String],
) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/items"
));
debug!(%url, "add_items_to_version");
let body = serde_json::json!({ "spec_item_ids": spec_item_keys });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn remove_item_from_version(
&self,
project_id: u64,
version: &str,
spec_item_key: &str,
) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/items/{spec_item_key}"
));
debug!(%url, "remove_item_from_version");
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn diff_versions(
&self,
project_id: u64,
version: &str,
other: &str,
) -> Result<VersionDiff, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/diff/{other}"
));
debug!(%url, "diff_versions");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<VersionDiff> = resp.json().await?;
Ok(body.data)
}
pub async fn clone_version(
&self,
project_id: u64,
version: &str,
semver: &str,
name: Option<&str>,
description: Option<&str>,
branch: Option<&str>,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/clone"
));
debug!(%url, "clone_version");
let mut rv = serde_json::Map::new();
rv.insert(
"semver".into(),
serde_json::Value::String(semver.to_string()),
);
if let Some(n) = name {
rv.insert("name".into(), serde_json::Value::String(n.to_string()));
}
if let Some(d) = description {
rv.insert(
"description".into(),
serde_json::Value::String(d.to_string()),
);
}
if let Some(b) = branch {
rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
}
let body = serde_json::json!({ "release_version": rv });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_version(&self, project_id: u64, version: &str) -> Result<(), Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}"
));
debug!(%url, "delete_version");
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn create_version(
&self,
project_id: u64,
semver: &str,
name: Option<&str>,
description: Option<&str>,
branch: Option<&str>,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!("/projects/{project_id}/release_versions"));
debug!(%url, "create_version");
let mut rv = serde_json::Map::new();
rv.insert(
"semver".into(),
serde_json::Value::String(semver.to_string()),
);
if let Some(n) = name {
rv.insert("name".into(), serde_json::Value::String(n.to_string()));
}
if let Some(d) = description {
rv.insert(
"description".into(),
serde_json::Value::String(d.to_string()),
);
}
if let Some(b) = branch {
rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
}
let body = serde_json::json!({ "release_version": rv });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn update_version(
&self,
project_id: u64,
version: &str,
semver: Option<&str>,
name: Option<&str>,
description: Option<&str>,
branch: Option<&str>,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}"
));
debug!(%url, "update_version");
let mut rv = serde_json::Map::new();
if let Some(s) = semver {
rv.insert("semver".into(), serde_json::Value::String(s.to_string()));
}
if let Some(n) = name {
rv.insert("name".into(), serde_json::Value::String(n.to_string()));
}
if let Some(d) = description {
rv.insert(
"description".into(),
serde_json::Value::String(d.to_string()),
);
}
if let Some(b) = branch {
rv.insert("branch".into(), serde_json::Value::String(b.to_string()));
}
let body = serde_json::json!({ "release_version": rv });
let resp = self
.request_with_retry(|| self.http.patch(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn transition_version(
&self,
project_id: u64,
version: &str,
lifecycle_state: &str,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/transition"
));
debug!(%url, "transition_version");
let body = serde_json::json!({ "lifecycle_state": lifecycle_state });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn move_item_in_version(
&self,
project_id: u64,
version: &str,
spec_item_key: &str,
position: i64,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}/items/{spec_item_key}"
));
debug!(%url, "move_item_in_version");
let body = serde_json::json!({ "position": position });
let resp = self
.request_with_retry(|| self.http.patch(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn list_versions(&self, project_id: u64) -> Result<Vec<ReleaseVersion>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/release_versions"));
debug!(%url, "list_versions");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn get_version(
&self,
project_id: u64,
version: &str,
include_deprecated: bool,
) -> Result<ReleaseVersion, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/release_versions/{version}"
));
debug!(%url, "get_version");
let mut req = self.http.get(&url);
if include_deprecated {
req = req.query(&[("include_deprecated", "true")]);
}
let resp = self
.request_with_retry(|| req.try_clone().unwrap().send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ReleaseVersion> = resp.json().await?;
Ok(body.data)
}
pub async fn report_implementation(
&self,
project_id: u64,
report: &ImplementationReport,
) -> Result<ImplementationReportResult, Error> {
let url = self.api_url(&format!("/projects/{project_id}/implementation_reports"));
debug!(%url, "report_implementation");
let resp = self
.request_with_retry(|| self.http.post(&url).json(report).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ImplementationReportResult> = resp.json().await?;
Ok(body.data)
}
pub async fn preview_import(
&self,
project_id: u64,
raw_body: &str,
) -> Result<ImportPreview, Error> {
let url = self.api_url(&format!("/projects/{project_id}/import/preview"));
debug!(%url, "preview_import");
let body_bytes = raw_body.as_bytes().to_vec();
let resp = self
.request_with_retry(|| {
self.http
.post(&url)
.header("Content-Type", "text/plain")
.body(body_bytes.clone())
.send()
})
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ImportPreview> = resp.json().await?;
Ok(body.data)
}
pub async fn commit_import(
&self,
project_id: u64,
items: &[ImportItem],
) -> Result<ImportResult, Error> {
let url = self.api_url(&format!("/projects/{project_id}/import/commit"));
debug!(%url, items_count = items.len(), "commit_import");
let body = serde_json::json!({ "items": items });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ImportResult> = resp.json().await?;
Ok(body.data)
}
pub async fn upload_document(
&self,
project_id: u64,
filename: &str,
mime_type: &str,
bytes: Vec<u8>,
) -> Result<DocumentUpload, Error> {
let url = self.api_url(&format!("/projects/{project_id}/import/upload"));
debug!(%url, filename, size = bytes.len(), "upload_document");
reqwest::multipart::Part::bytes(Vec::new()).mime_str(mime_type)?;
let resp = self
.request_with_retry(|| {
let part = reqwest::multipart::Part::bytes(bytes.clone())
.file_name(filename.to_string())
.mime_str(mime_type)
.expect("mime type validated above");
let form = reqwest::multipart::Form::new().part("file", part);
self.http.post(&url).multipart(form).send()
})
.await?;
if !resp.status().is_success() {
return Err(Error::from_coded_response(resp).await);
}
Ok(resp.json().await?)
}
pub async fn start_extract(
&self,
project_id: u64,
session_id: u64,
) -> Result<ImportStageStarted, Error> {
self.start_import_stage(project_id, session_id, "extract")
.await
}
pub async fn start_enrich(
&self,
project_id: u64,
session_id: u64,
) -> Result<ImportStageStarted, Error> {
self.start_import_stage(project_id, session_id, "enrich")
.await
}
async fn start_import_stage(
&self,
project_id: u64,
session_id: u64,
stage: &str,
) -> Result<ImportStageStarted, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/import/sessions/{session_id}/{stage}"
));
debug!(%url, "start_import_stage");
let resp = self
.request_with_retry(|| self.http.post(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_coded_response(resp).await);
}
Ok(resp.json().await?)
}
pub async fn poll_import_session(
&self,
project_id: u64,
session_id: u64,
) -> Result<ImportSession, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/import/sessions/{session_id}"
));
debug!(%url, "poll_import_session");
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_coded_response(resp).await);
}
Ok(resp.json().await?)
}
pub async fn commit_import_session(
&self,
project_id: u64,
session_id: u64,
items: Option<&[DocumentImportItem]>,
) -> Result<DocumentImportCommit, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/import/sessions/{session_id}/commit"
));
debug!(%url, "commit_import_session");
let body = match items {
Some(items) => serde_json::json!({ "items": items }),
None => serde_json::json!({}),
};
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_coded_response(resp).await);
}
Ok(resp.json().await?)
}
pub async fn list_repositories(
&self,
project_id: u64,
) -> Result<Vec<ProjectRepository>, Error> {
let url = self.api_url(&format!("/projects/{project_id}/repositories"));
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiListResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
pub async fn get_repository(
&self,
project_id: u64,
repo_id: u64,
) -> Result<ProjectRepository, Error> {
let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
let resp = self
.request_with_retry(|| self.http.get(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
pub async fn create_repository(
&self,
project_id: u64,
params: &CreateRepositoryParams,
) -> Result<ProjectRepository, Error> {
let url = self.api_url(&format!("/projects/{project_id}/repositories"));
let body = serde_json::json!({ "project_repository": params });
let resp = self
.request_with_retry(|| self.http.post(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
pub async fn update_repository(
&self,
project_id: u64,
repo_id: u64,
params: &UpdateRepositoryParams,
) -> Result<ProjectRepository, Error> {
let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
let body = serde_json::json!({ "project_repository": params });
let resp = self
.request_with_retry(|| self.http.patch(&url).json(&body).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
pub async fn delete_repository(&self, project_id: u64, repo_id: u64) -> Result<(), Error> {
let url = self.api_url(&format!("/projects/{project_id}/repositories/{repo_id}"));
let resp = self
.request_with_retry(|| self.http.delete(&url).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
Ok(())
}
pub async fn sync_repository(
&self,
project_id: u64,
repo_id: u64,
) -> Result<ProjectRepository, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/repositories/{repo_id}/sync"
));
let resp = self
.request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
pub async fn set_primary_repository(
&self,
project_id: u64,
repo_id: u64,
) -> Result<ProjectRepository, Error> {
let url = self.api_url(&format!(
"/projects/{project_id}/repositories/{repo_id}/set_primary"
));
let resp = self
.request_with_retry(|| self.http.post(&url).json(&serde_json::json!({})).send())
.await?;
if !resp.status().is_success() {
return Err(Error::from_response(resp).await);
}
let body: ApiResponse<ProjectRepository> = resp.json().await?;
Ok(body.data)
}
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
async fn make_client(base_url: &str) -> FuncspecClient {
FuncspecClient::new(base_url, "test-key").unwrap()
}
#[tokio::test]
async fn get_agent_instructions_returns_full_json() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/my-proj/agent_instructions"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 1,
"type": "agent_instruction",
"attributes": {
"content": "# Instructions\n\nDo the thing.",
"scope": "project",
"version": 1
}
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client.get_agent_instructions("my-proj").await.unwrap();
let content = result["data"]["attributes"]["content"].as_str().unwrap();
assert!(content.contains("# Instructions"));
}
#[tokio::test]
async fn get_agent_instructions_propagates_auth_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/secret/agent_instructions"))
.respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
"error": "Unauthorized"
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let err = client.get_agent_instructions("secret").await.unwrap_err();
assert!(matches!(err, crate::error::Error::Auth(_)));
}
#[tokio::test]
async fn get_agent_instructions_propagates_not_found() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/no-such/agent_instructions"))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"error": "Not found"
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let err = client.get_agent_instructions("no-such").await.unwrap_err();
assert!(matches!(err, crate::error::Error::NotFound(_)));
}
#[tokio::test]
async fn export_project_text_format() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/42/export/markdown"))
.respond_with(ResponseTemplate::new(200).set_body_string("# My Spec\n\nContent here."))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client
.export_project(42, "markdown", None, None, None)
.await
.unwrap();
match result {
ExportData::Text(text) => assert!(text.contains("# My Spec")),
ExportData::Binary(_) => panic!("expected text"),
}
}
#[tokio::test]
async fn export_project_with_filters() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/42/export/csv"))
.and(query_param("type_of", "functional"))
.and(query_param("tag", "v1"))
.respond_with(ResponseTemplate::new(200).set_body_string("id,title\n1,Login"))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client
.export_project(42, "csv", Some("functional"), Some("v1"), None)
.await
.unwrap();
match result {
ExportData::Text(text) => assert!(text.contains("id,title")),
ExportData::Binary(_) => panic!("expected text"),
}
}
#[tokio::test]
async fn export_project_binary_format() {
let server = MockServer::start().await;
let pdf_bytes = b"%PDF-1.4 fake pdf content".to_vec();
Mock::given(method("GET"))
.and(path("/api/v1/projects/7/export/pdf"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(pdf_bytes.clone()))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client
.export_project(7, "pdf", None, None, None)
.await
.unwrap();
match result {
ExportData::Binary(bytes) => assert_eq!(bytes, pdf_bytes),
ExportData::Text(_) => panic!("expected binary"),
}
}
#[tokio::test]
async fn export_project_docx_binary() {
let server = MockServer::start().await;
let docx_bytes = b"PK\x03\x04fake docx".to_vec();
Mock::given(method("GET"))
.and(path("/api/v1/projects/5/export/docx"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(docx_bytes.clone()))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client
.export_project(5, "docx", None, None, None)
.await
.unwrap();
match result {
ExportData::Binary(bytes) => assert_eq!(bytes, docx_bytes),
ExportData::Text(_) => panic!("expected binary"),
}
}
#[tokio::test]
async fn export_project_error_response() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/99/export/markdown"))
.respond_with(
ResponseTemplate::new(404)
.set_body_json(serde_json::json!({"error": "Project not found"})),
)
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client
.export_project(99, "markdown", None, None, None)
.await;
assert!(matches!(result, Err(Error::NotFound(_))));
}
#[tokio::test]
async fn get_viewable_html_returns_string() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/3/spec/view"))
.respond_with(
ResponseTemplate::new(200).set_body_string("<html><body>Spec</body></html>"),
)
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let html = client.get_viewable_html(3).await.unwrap();
assert!(html.contains("<html>"));
}
#[tokio::test]
async fn get_viewable_html_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/0/spec/view"))
.respond_with(
ResponseTemplate::new(403).set_body_json(serde_json::json!({"error": "Forbidden"})),
)
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client.get_viewable_html(0).await;
assert!(matches!(result, Err(Error::Forbidden(_))));
}
#[tokio::test]
async fn review_item_returns_review() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/5/review"))
.respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
"data": { "job_id": 77, "status": "queued" }
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/jobs/77"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": { "id": 77, "job_type": "review", "status": "completed",
"progress": null, "result": null,
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z" }
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/spec/items/5"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": { "id": 5, "type": "spec_item", "attributes": {
"title": "Auth service", "description": "x", "type_of": "technical",
"state": "accepted", "implementation_status": "implemented",
"permalink": "T-5", "url": "/o/p/T-5", "version": 1, "priority": null,
"position": null, "tags": [], "parent_id": null, "project_id": 1,
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z",
"review": {
"coverage_score": 90.0, "verdict": "pass", "review_type": "tech_review",
"reviewed_at": "2026-01-01T00:00:00Z", "fresh": true,
"coverage_map": {
"Auth flow": {"status": "covered"}, "Error cases": {"status": "covered"}
},
"gaps": [], "suggestions": ["Consider adding retry logic"], "risks": []
}
} }
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let review = client.review_item(1, 5).await.unwrap();
assert_eq!(review.attributes.coverage_score, Some(90.0));
assert_eq!(review.attributes.verdict.as_deref(), Some("pass"));
assert_eq!(review.attributes.coverage_map.len(), 2);
assert!(review.attributes.gaps.is_empty());
assert_eq!(review.attributes.suggestions.len(), 1);
}
#[tokio::test]
async fn review_item_not_found() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/999/review"))
.respond_with(
ResponseTemplate::new(404).set_body_json(serde_json::json!({"error": "Not found"})),
)
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let result = client.review_item(1, 999).await;
assert!(matches!(result, Err(Error::NotFound(_))));
}
#[tokio::test]
async fn review_all_returns_job() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/2/work_package/review_all"))
.respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
"data": { "job_id": 77, "status": "queued" }
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let job_id = client.review_all(2).await.unwrap();
assert_eq!(job_id, 77);
}
#[tokio::test]
async fn propose_improvement_returns_proposal() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/3/work_package/10/propose"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 1,
"type": "proposal",
"attributes": {
"spec_item_id": 10,
"original_description": "User logs in.",
"proposed_description": "User logs in with email and password.",
"rationale": "More specific",
"status": "pending",
"created_at": "2026-01-01T00:00:00Z"
}
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let proposal = client.propose_improvement(3, 10).await.unwrap();
assert_eq!(proposal.attributes.spec_item_id, 10);
assert_eq!(proposal.attributes.status, "pending");
assert!(
proposal
.attributes
.proposed_description
.unwrap()
.contains("email")
);
}
#[tokio::test]
async fn accept_proposal_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/4/work_package/20/accept"))
.respond_with(ResponseTemplate::new(200).set_body_string(""))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
assert!(client.accept_proposal(4, 20).await.is_ok());
}
#[tokio::test]
async fn reject_proposal_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/4/work_package/20/reject"))
.respond_with(ResponseTemplate::new(200).set_body_string(""))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
assert!(client.reject_proposal(4, 20).await.is_ok());
}
#[tokio::test]
async fn generate_tech_returns_proposals() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/5/work_package/30/generate_tech"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"functional_item_id": 30,
"functional_item_permalink": "F-30",
"proposals": [
{
"title": "Users table schema",
"description": "Create users table",
"type_of": "technical",
"rationale": "Required for auth"
},
{
"title": "JWT service",
"description": null,
"type_of": "technical",
"rationale": null
}
]
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let tp = client.generate_tech(5, 30).await.unwrap();
assert_eq!(tp.functional_item_id, 30);
assert_eq!(tp.functional_item_permalink, "F-30");
assert_eq!(tp.proposals.len(), 2);
assert_eq!(tp.proposals[0].title, "Users table schema");
}
#[tokio::test]
async fn audit_item_returns_result() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/6/work_package/40/audit"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 55,
"status_recommendation": "implemented",
"confidence": "high",
"files_discovered": 28,
"coverage_percentage": 73.3,
"criteria_coverage": [
{
"criterion": "All requirements covered",
"status": "implemented",
"evidence": [
{"file": "app/models/foo.rb", "lines": "1-10", "note": "present"}
]
}
],
"notes": "All requirements covered",
"created_at": "2026-01-01T00:00:00Z"
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let audit = client.audit_item(6, 40).await.unwrap();
assert_eq!(audit.status_recommendation, "implemented");
assert_eq!(audit.confidence, "high");
assert_eq!(audit.files_discovered, 28);
assert_eq!(audit.criteria_coverage.len(), 1);
assert_eq!(audit.criteria_coverage[0].status, "implemented");
}
#[tokio::test]
async fn get_project_job_returns_job() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/7/jobs/88"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 88, "job_type": "review", "status": "completed",
"progress": 100.0, "result": "All items reviewed",
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:01:00Z"
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let job = client.get_project_job(7, 88).await.unwrap();
assert_eq!(job.id, 88);
assert_eq!(job.attributes.status, JobStatus::Completed);
}
#[tokio::test]
async fn poll_job_until_done_completes_immediately() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/jobs/99"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 99, "job_type": "review", "status": "completed",
"progress": 100.0, "result": "Done",
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:30Z"
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let job = client
.poll_job_until_done(1, 99, Duration::from_secs(30))
.await
.unwrap();
assert_eq!(job.attributes.status, JobStatus::Completed);
}
#[tokio::test]
async fn transition_item_implementation_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(
"/api/v1/projects/1/spec/items/5/transition_implementation",
))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
client
.transition_item_implementation(1, 5, "in_progress")
.await
.unwrap();
}
#[tokio::test]
async fn transition_item_implementation_422_returns_validation_error() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(
"/api/v1/projects/1/spec/items/5/transition_implementation",
))
.respond_with(ResponseTemplate::new(422).set_body_json(
serde_json::json!({"error": "Cannot transition from released to not_started"}),
))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let err = client
.transition_item_implementation(1, 5, "not_started")
.await
.unwrap_err();
assert!(matches!(err, Error::Validation(_)));
}
#[tokio::test]
async fn link_commit_sends_sha_and_optional_fields() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/5/link_commit"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let params = LinkCommitParams {
sha: "abc1234".into(),
message: Some("Fix auth".into()),
source: Some("cli".into()),
agent_run_id: Some(9),
..Default::default()
};
client.link_commit(1, 5, ¶ms).await.unwrap();
}
#[tokio::test]
async fn link_commit_bare_sha_only() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/2/work_package/7/link_commit"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let params = LinkCommitParams {
sha: "deadbeef".into(),
..Default::default()
};
client.link_commit(2, 7, ¶ms).await.unwrap();
}
#[tokio::test]
async fn record_run_returns_run_id() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/5/record_run"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {"id": 42, "spec_item_id": 5, "status": "pending"}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let params = RecordRunParams {
model: Some("claude-sonnet-4-6".into()),
provider: Some("anthropic".into()),
..Default::default()
};
let run_id = client.record_run(1, 5, ¶ms).await.unwrap();
assert_eq!(run_id, Some(42));
}
#[tokio::test]
async fn record_run_returns_none_when_no_id_in_response() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/5/record_run"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let run_id = client
.record_run(1, 5, &RecordRunParams::default())
.await
.unwrap();
assert_eq!(run_id, None);
}
#[tokio::test]
async fn review_item_functional_returns_review() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/work_package/5/func_review"))
.respond_with(ResponseTemplate::new(202).set_body_json(serde_json::json!({
"data": { "job_id": 88, "status": "queued" }
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/jobs/88"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": { "id": 88, "job_type": "func_review", "status": "completed",
"progress": null, "result": null,
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z" }
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/spec/items/5"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": { "id": 5, "type": "spec_item", "attributes": {
"title": "Rate limiter", "description": "x", "type_of": "functional",
"state": "accepted", "implementation_status": "implemented",
"permalink": "F-5", "url": "/o/p/F-5", "version": 1, "priority": null,
"position": null, "tags": [], "parent_id": null, "project_id": 1,
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z",
"review": {
"coverage_score": 75.0, "verdict": "needs_refinement",
"review_type": "func_review", "reviewed_at": "2026-01-01T00:00:00Z",
"fresh": true, "coverage_map": {},
"gaps": ["Missing burst allowance detail"], "suggestions": [], "risks": []
}
} }
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let review = client.review_item_functional(1, 5).await.unwrap();
assert_eq!(review.attributes.coverage_score, Some(75.0));
assert_eq!(
review.attributes.verdict.as_deref(),
Some("needs_refinement")
);
assert_eq!(review.attributes.gaps.len(), 1);
}
#[tokio::test]
async fn poll_job_until_done_returns_failed_job() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/projects/1/jobs/100"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"id": 100, "job_type": "audit", "status": "failed",
"progress": null, "result": "Internal error",
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:05Z"
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let job = client
.poll_job_until_done(1, 100, Duration::from_secs(30))
.await
.unwrap();
assert_eq!(job.attributes.status, JobStatus::Failed);
}
#[tokio::test]
async fn preview_run_returns_count_and_items() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/runs/preview"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": {
"count": 2,
"truncated": false,
"filter_criteria": { "type_of": "functional" },
"items": [
{ "id": 10, "permalink": "F-10", "title": "Login", "type_of": "functional" },
{ "id": 11, "permalink": "F-11", "title": "Logout", "type_of": "functional" }
]
}
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let params = CreateRunParams {
type_of: Some("functional".into()),
..Default::default()
};
let preview = client.preview_run(1, ¶ms).await.unwrap();
assert_eq!(preview.count, 2);
assert!(!preview.truncated);
assert_eq!(preview.items.len(), 2);
assert_eq!(preview.items[0].permalink.as_deref(), Some("F-10"));
}
#[tokio::test]
async fn preview_run_empty_result() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v1/projects/1/runs/preview"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": { "count": 0, "truncated": false, "filter_criteria": {}, "items": [] }
})))
.mount(&server)
.await;
let client = make_client(&server.uri()).await;
let preview = client
.preview_run(1, &CreateRunParams::default())
.await
.unwrap();
assert_eq!(preview.count, 0);
assert!(preview.items.is_empty());
}
}