use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::Traced;
use crate::error::SdkError;
use super::ingest::expect_json;
use super::merge::{MergeConflict, MergeReport, MergeStats, Signature, expect_json_or_conflict};
use super::{ArtifactStorageClient, decode_empty};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkspaceInfo {
pub id: String,
pub ref_name: String,
pub principal: String,
pub base: String,
pub base_ref: Option<String>,
pub head: String,
pub created_at_secs: u64,
pub lease_secs: u64,
pub lease_due_ms: Option<u64>,
pub pinned: bool,
#[serde(default)]
pub shared_target: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct CreateWorkspaceRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shared_target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reconcile_policy: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct WorkspaceHeartbeat {
pub lease_due_ms: Option<u64>,
pub pinned: bool,
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct PromoteWorkspaceRequest {
pub branch: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub expect_oid: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub full_history: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub author: Option<Signature>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PromoteWorkspaceResponse {
pub commit: String,
pub ref_name: String,
pub created: bool,
pub squashed: bool,
#[serde(default)]
pub merged: bool,
#[serde(default)]
pub fast_forwarded: bool,
}
#[derive(Clone, Debug)]
pub enum PromoteOutcome {
Promoted(PromoteWorkspaceResponse),
Conflicted(MergeReport),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PromotePreflight {
pub target_ref: String,
pub target_head: Option<String>,
pub workspace_base: String,
pub workspace_head: String,
pub moved: bool,
pub fast_forward: bool,
}
#[derive(Clone, Debug, Default, Serialize)]
pub struct SyncWorkspaceRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub policy: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub author: Option<Signature>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncWorkspaceResponse {
pub workspace_head: String,
pub target_head: String,
pub base: String,
pub clean: bool,
pub up_to_date: bool,
pub fast_forwarded: bool,
pub changed_paths: u64,
pub conflicts: Vec<MergeConflict>,
pub stats: MergeStats,
}
#[derive(Clone, Debug, Deserialize)]
pub struct RefStatus {
pub ref_name: String,
pub oid: Option<String>,
pub generation: u64,
}
#[derive(Clone, Debug, Deserialize)]
pub struct TreePage {
pub entries: Vec<TreeEntry>,
pub truncated: bool,
pub next_after: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct TreeEntry {
pub name: String,
pub oid: String,
pub mode: u32,
pub size: Option<u64>,
}
impl ArtifactStorageClient {
pub async fn create_workspace(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
request: &CreateWorkspaceRequest,
) -> Result<Traced<WorkspaceInfo>, SdkError> {
let (req, trace_id) = self.git_request(
Method::POST,
project_id,
repo,
Some("workspaces"),
git_username,
git_token,
)?;
let info = expect_json(req.json(request).send().await?).await?;
Ok(Traced::new(trace_id, info))
}
pub async fn get_workspace(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
) -> Result<Traced<WorkspaceInfo>, SdkError> {
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some(&format!("workspaces/{workspace_id}")),
git_username,
git_token,
)?;
let info = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, info))
}
pub async fn list_workspaces(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
) -> Result<Traced<Vec<WorkspaceInfo>>, SdkError> {
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some("workspaces"),
git_username,
git_token,
)?;
let list = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, list))
}
pub async fn workspace_heartbeat(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
) -> Result<Traced<WorkspaceHeartbeat>, SdkError> {
let (req, trace_id) = self.git_request(
Method::POST,
project_id,
repo,
Some(&format!("workspaces/{workspace_id}/heartbeat")),
git_username,
git_token,
)?;
let hb = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, hb))
}
pub async fn workspace_promote(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
request: &PromoteWorkspaceRequest,
) -> Result<Traced<PromoteOutcome>, SdkError> {
let (req, trace_id) = self.git_request(
Method::POST,
project_id,
repo,
Some(&format!("workspaces/{workspace_id}/promote")),
git_username,
git_token,
)?;
let outcome = expect_json_or_conflict::<PromoteWorkspaceResponse, MergeReport>(
req.json(request).send().await?,
)
.await?
.map(PromoteOutcome::Promoted)
.unwrap_or_else(PromoteOutcome::Conflicted);
Ok(Traced::new(trace_id, outcome))
}
pub async fn workspace_promote_preflight(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
target: &str,
) -> Result<Traced<PromotePreflight>, SdkError> {
let suffix = format!(
"workspaces/{workspace_id}/promote/preflight?target={}",
url::form_urlencoded::byte_serialize(target.as_bytes()).collect::<String>()
);
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some(&suffix),
git_username,
git_token,
)?;
let preflight = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, preflight))
}
pub async fn workspace_sync(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
request: &SyncWorkspaceRequest,
) -> Result<Traced<SyncWorkspaceResponse>, SdkError> {
let (req, trace_id) = self.git_request(
Method::POST,
project_id,
repo,
Some(&format!("workspaces/{workspace_id}/sync")),
git_username,
git_token,
)?;
let resp = expect_json_or_conflict::<SyncWorkspaceResponse, SyncWorkspaceResponse>(
req.json(request).send().await?,
)
.await?
.unwrap_or_else(|conflicted| conflicted);
Ok(Traced::new(trace_id, resp))
}
pub async fn delete_workspace(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
workspace_id: &str,
) -> Result<Traced<()>, SdkError> {
let (req, trace_id) = self.git_request(
Method::DELETE,
project_id,
repo,
Some(&format!("workspaces/{workspace_id}")),
git_username,
git_token,
)?;
decode_empty(req.send().await?, trace_id).await
}
pub async fn ref_status(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
refspec: &str,
) -> Result<Traced<RefStatus>, SdkError> {
let suffix = format!(
"ref-status?ref={}",
url::form_urlencoded::byte_serialize(refspec.as_bytes()).collect::<String>()
);
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some(&suffix),
git_username,
git_token,
)?;
let status = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, status))
}
pub async fn list_tree_page(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
version: &str,
dir_path: &str,
after: Option<&str>,
limit: usize,
) -> Result<Traced<TreePage>, SdkError> {
let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
let mut suffix = if dir_path.is_empty() {
format!("tree?version={}&limit={limit}", enc(version))
} else {
format!("tree/{}?version={}&limit={limit}", dir_path, enc(version))
};
if let Some(after) = after {
suffix.push_str(&format!("&after={}", enc(after)));
}
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some(&suffix),
git_username,
git_token,
)?;
let page = expect_json(req.send().await?).await?;
Ok(Traced::new(trace_id, page))
}
pub async fn get_file_bytes(
&self,
project_id: &str,
repo: &str,
git_username: &str,
git_token: &str,
version: &str,
file_path: &str,
) -> Result<Traced<Vec<u8>>, SdkError> {
let suffix = format!(
"files/{file_path}?version={}",
url::form_urlencoded::byte_serialize(version.as_bytes()).collect::<String>()
);
let (req, trace_id) = self.git_request(
Method::GET,
project_id,
repo,
Some(&suffix),
git_username,
git_token,
)?;
let resp = req.send().await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(SdkError::ServerError {
status,
message: body,
});
}
let bytes = resp.bytes().await?.to_vec();
Ok(Traced::new(trace_id, bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn promote_response_tolerates_old_servers() {
let body = r#"{"commit": "aa", "ref_name": "refs/heads/main", "created": false, "squashed": true}"#;
let resp: PromoteWorkspaceResponse = serde_json::from_str(body).unwrap();
assert!(resp.squashed);
assert!(!resp.merged);
assert!(!resp.fast_forwarded);
}
#[test]
fn sync_response_decodes_server_shape() {
let body = r#"{
"workspace_head": "ws1", "target_head": "t1", "base": "t1",
"clean": false, "up_to_date": false, "fast_forwarded": false,
"changed_paths": 2,
"conflicts": [{"path": "f", "kind": "content", "potential": false,
"ours": {"mode": 33188, "oid": "o"}, "base": {"mode": 33188, "oid": "b"},
"theirs": {"mode": 33188, "oid": "t"}}],
"stats": {"trees_read": 4, "entries_compared": 9, "blobs_merged": 1, "wall_ms": 0.7}
}"#;
let resp: SyncWorkspaceResponse = serde_json::from_str(body).unwrap();
assert!(!resp.clean);
assert_eq!(resp.base, "t1");
assert_eq!(resp.conflicts.len(), 1);
assert_eq!(resp.conflicts[0].kind, "content");
}
}