Skip to content

Commit

Permalink
Improve error reporting, Add some helper functions to implement api m…
Browse files Browse the repository at this point in the history
…ethods manually
  • Loading branch information
YannikSc committed Nov 27, 2024
1 parent 72c3d80 commit cd767f2
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 8 deletions.
36 changes: 34 additions & 2 deletions rust/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ pub struct NewObjectResponse {
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CommitResponse {
pub status: String,
#[serde(default)]
pub message: Option<String>,
}

pub async fn query_objects<T: serde::de::DeserializeOwned>(
Expand Down Expand Up @@ -55,9 +57,22 @@ pub async fn new_object(servertype: impl Display) -> anyhow::Result<NewObjectRes
pub async fn commit_changes(commit: &Commit) -> anyhow::Result<CommitResponse> {
let config = Config::build_from_environment()?;
let response = request_api(COMMIT_ENDPOINT, serde_json::to_value(commit)?, config).await?;
let response = response.error_for_status()?;
let status = response.status();
let body = response.json::<CommitResponse>().await?;

Ok(response.json().await?)
if status.is_client_error() || status.is_server_error() {
return Err(anyhow::anyhow!("Unable to process request").context(format!("{:?}", body)));
}

if body.status == "error" {
return Err(anyhow::anyhow!(
"Error while committing {}",
body.message
.unwrap_or_else(|| String::from("Unknown commit error"))
));
}

Ok(body)
}

pub async fn request_api(
Expand Down Expand Up @@ -149,6 +164,12 @@ fn calculate_app_id(token: &String) -> String {
}

impl Server {
pub fn clear(&mut self, attribute: impl ToString) -> anyhow::Result<&mut Self> {
self.attributes.clear(attribute.to_string());

Ok(self)
}

pub fn set(
&mut self,
attribute: impl ToString,
Expand Down Expand Up @@ -264,6 +285,17 @@ impl Server {

set
}

/// Rolls back the changes.
///
/// Returns the reverted changes
pub fn rollback(&mut self) -> Changeset {
let old_changes = self.changeset();

self.changes = Changeset::default();

old_changes
}
}

impl<T: serde::de::DeserializeOwned> QueryResponse<T> {
Expand Down
6 changes: 6 additions & 0 deletions rust/src/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ impl Dataset {
Self(Default::default())
}

pub fn clear(&mut self, name: impl ToString) -> &mut Self {
self.0.remove(&name.to_string());

self
}

pub fn set(
&mut self,
name: impl ToString,
Expand Down
10 changes: 6 additions & 4 deletions rust/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::fmt::{Debug, Formatter};
use std::path::Path;
use std::rc::Rc;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};

use signature::Signer;

Expand All @@ -24,7 +23,7 @@ pub struct Config {
pub enum SshSigner {
Agent(
Box<ssh_key::PublicKey>,
Box<Rc<Mutex<ssh_agent_client_rs::Client>>>,
Box<Arc<Mutex<ssh_agent_client_rs::Client>>>,
),
Key(Box<ssh_key::PrivateKey>),
}
Expand Down Expand Up @@ -72,7 +71,7 @@ impl Config {

return Ok(Some(SshSigner::Agent(
Box::new(key),
Box::new(Rc::new(Mutex::new(client))),
Box::new(Arc::new(Mutex::new(client))),
)));
}
}
Expand Down Expand Up @@ -120,3 +119,6 @@ impl Signer<ssh_key::Signature> for SshSigner {
}
}
}

unsafe impl Send for SshSigner {}
unsafe impl Sync for SshSigner {}
26 changes: 24 additions & 2 deletions rust/src/new_object.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::ops::{Deref, DerefMut};

use crate::api::{commit_changes, new_object, NewObjectResponse, Server};
use crate::commit::{AttributeValue, Changeset, Commit};
use crate::commit::{AttributeValue, Changeset, Commit, Dataset};
use crate::query::Query;

#[derive(Clone, Debug)]
Expand All @@ -12,6 +12,18 @@ pub struct NewObject {
}

impl NewObject {
pub fn from_dataset(dataset: Dataset) -> Self {
Self {
object_id: None,
server: Server {
object_id: 0,
attributes: dataset,
changes: Default::default(),
},
deferred_changes: Default::default(),
}
}

pub async fn request_new(servertype: impl ToString) -> anyhow::Result<Self> {
let servertype = servertype.to_string();
let NewObjectResponse { result } = new_object(&servertype).await?;
Expand All @@ -31,7 +43,7 @@ impl NewObject {
servertype: impl ToString,
hostname: impl ToString,
) -> anyhow::Result<Self> {
let mut new_object = Self::request_new(servertype).await?;
let mut new_object = Self::request_new(servertype.to_string()).await?;

if let Ok(server) = Query::builder()
.filter("hostname", hostname.to_string())
Expand Down Expand Up @@ -89,6 +101,16 @@ impl NewObject {
Ok(server)
}

///
/// Gets the initial commit data and the follow-up commit of deferred changes
///
pub fn get_commit(self) -> (Commit, Commit) {
(
Commit::new().create(self.server.attributes),
Commit::new().update(self.deferred_changes),
)
}

///
/// The deferred method allows you to pre-update the newly created object
///
Expand Down

0 comments on commit cd767f2

Please sign in to comment.