Skip to content

Commit

Permalink
more fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
JanZachmann committed Apr 8, 2024
1 parent 7e00dd0 commit 3afb8f9
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 62 deletions.
21 changes: 0 additions & 21 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ azure_storage_blobs = { git = "https://github.com/Azure/azure-sdk-for-rust.git",
base64 = "0.13"
bzip2 = "0.4"
clap = { version = "4.0", features = ["derive"] }
const_format = "0.2"
directories = "5.0"
env_logger = "0.8"
filemagic = "0.12"
Expand Down
5 changes: 3 additions & 2 deletions src/device_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,9 @@ pub async fn import_update(

debug!("import update: {import_update}");

let import_update_response = client.import_update(instance_id, import_update).await?;
info!("Result of import update: {:?}", &import_update_response);
client.import_update(instance_id, import_update).await?;

info!("Import update succeeded");

Ok(())
}
Expand Down
62 changes: 24 additions & 38 deletions src/device_update_client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
use anyhow::Result;
use azure_core::{
auth::{AccessToken, TokenCredential},
error::{Error, ErrorKind, ResultExt},
from_json, sleep, Url,
from_json, Url,
};
use const_format::formatcp;
use getset::Getters;
use log::debug;
use log::{debug, error};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;
use time::OffsetDateTime;

pub(crate) const API_VERSION: &str = "2022-10-01";
pub(crate) const API_VERSION_PARAM: &str = formatcp!("api-version={}", API_VERSION);
const API_VERSION: &str = "api-version=2022-10-01";

#[derive(Debug, Deserialize, Getters)]
#[getset(get = "pub")]
Expand Down Expand Up @@ -61,8 +60,8 @@ pub struct UpdateOperation {
#[derive(Clone)]
pub struct DeviceUpdateClient {
pub(crate) device_update_url: Url,
pub(crate) token_credential: Arc<dyn TokenCredential>,
device_update_url: Url,
token_credential: Arc<dyn TokenCredential>,
}

impl DeviceUpdateClient {
Expand All @@ -78,7 +77,7 @@ impl DeviceUpdateClient {
pub fn new(
device_update_url: &str,
token_credential: Arc<dyn TokenCredential>,
) -> azure_core::Result<Self> {
) -> Result<Self> {
let device_update_url = Url::parse(device_update_url)
.with_context(ErrorKind::DataConversion, || {
format!("failed to parse update url: {device_update_url}")
Expand All @@ -93,40 +92,30 @@ impl DeviceUpdateClient {

/// Import new update version.
/// `POST https://{endpoint}/deviceupdate/{instanceId}/updates?action=import&api-version=2021-06-01-preview`
pub async fn import_update(
&self,
instance_id: &str,
import_json: String,
) -> azure_core::Result<UpdateOperation> {
pub async fn import_update(&self, instance_id: &str, import_json: String) -> Result<()> {
let mut uri = self.device_update_url.clone();
let path = format!("deviceupdate/{instance_id}/updates:import");
uri.set_path(&path);
uri.set_query(Some(API_VERSION_PARAM));
uri.set_query(Some(API_VERSION));

debug!("Import request: {}", &uri);
let resp_body = self.post(uri.to_string(), Some(import_json)).await?;
debug!("Import response: {}", &resp_body);

loop {
sleep(Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_secs(5)).await;
let mut uri = self.device_update_url.clone();
uri.set_path(&resp_body);
debug!("Requesting operational status: {}", &uri);
let update_operation: UpdateOperation = self.get(uri.to_string()).await.expect("error while getting operation status");

match update_operation.status {
OperationStatus::Failed => {
return Err(Error::with_message(ErrorKind::Other, {
|| {
format!(
"import unsuccessful with status failed. status: {:?}",
update_operation.status
)
}
}))
}
OperationStatus::Succeeded => return Ok(update_operation),
OperationStatus::NotStarted | OperationStatus::Running => continue,

match self.get::<UpdateOperation>(uri.to_string()).await {
Ok(op) => match op.status {
OperationStatus::Succeeded => return Ok(()),
OperationStatus::Failed => anyhow::bail!("Import failed"),
OperationStatus::NotStarted => debug!("Import not started"),
OperationStatus::Running => debug!("Import running"),
},
Err(e) => error!("Error while requesting operational status: {e}"),
}
}
}
Expand All @@ -143,7 +132,7 @@ impl DeviceUpdateClient {
let mut uri = self.device_update_url.clone();
let path = format!("deviceupdate/{instance_id}/updates/providers/{provider}/names/{name}/versions/{version}");
uri.set_path(&path);
uri.set_query(Some(API_VERSION_PARAM));
uri.set_query(Some(API_VERSION));

self.delete(uri.to_string()).await
}
Expand All @@ -155,7 +144,7 @@ impl DeviceUpdateClient {
.context(ErrorKind::Credential, "get token failed")
}

pub(crate) async fn get<R>(&self, uri: String) -> azure_core::Result<R>
async fn get<R>(&self, uri: String) -> azure_core::Result<R>
where
R: DeserializeOwned,
{
Expand All @@ -171,14 +160,11 @@ impl DeviceUpdateClient {
let body = resp.bytes().await.with_context(ErrorKind::Io, || {
format!("failed to read response body text. uri: {uri}")
})?;
debug!("{:?}", body);
from_json(&body)
}

pub(crate) async fn post(
&self,
uri: String,
json_body: Option<String>,
) -> azure_core::Result<String> {
async fn post(&self, uri: String, json_body: Option<String>) -> azure_core::Result<String> {
let mut req = reqwest::Client::new()
.post(&uri)
.bearer_auth(self.get_token().await?.token.secret());
Expand Down Expand Up @@ -212,7 +198,7 @@ impl DeviceUpdateClient {
}))
}

pub(crate) async fn delete(&self, uri: String) -> azure_core::Result<String> {
async fn delete(&self, uri: String) -> azure_core::Result<String> {
let resp = reqwest::Client::new()
.delete(&uri)
.bearer_auth(self.get_token().await?.token.secret())
Expand Down

0 comments on commit 3afb8f9

Please sign in to comment.