diff --git a/sdk/core/src/mock/mock_request.rs b/sdk/core/src/mock/mock_request.rs index 6b924e6cad..4c08971179 100644 --- a/sdk/core/src/mock/mock_request.rs +++ b/sdk/core/src/mock/mock_request.rs @@ -8,17 +8,6 @@ use std::str::FromStr; const FIELDS: &[&str] = &["uri", "method", "headers", "body"]; -impl Request { - fn new(uri: Uri, method: Method, headers: HeaderMap, body: Body) -> Self { - Self { - uri, - method, - headers, - body, - } - } -} - impl<'de> Deserialize<'de> for Request { fn deserialize(deserializer: D) -> Result where @@ -98,12 +87,12 @@ impl<'de> Visitor<'de> for RequestVisitor { ); } - Ok(Self::Value::new( - Uri::from_str(uri.1).expect("expected a valid uri"), - Method::from_str(method.1).expect("expected a valid HTTP method"), - hm, - bytes::Bytes::from(body).into(), - )) + Ok(Self::Value { + uri: Uri::from_str(uri.1).expect("expected a valid uri"), + method: Method::from_str(method.1).expect("expected a valid HTTP method"), + headers: hm, + body: bytes::Bytes::from(body).into(), + }) } } diff --git a/sdk/core/src/request.rs b/sdk/core/src/request.rs index 6f03dda08c..79737f1afa 100644 --- a/sdk/core/src/request.rs +++ b/sdk/core/src/request.rs @@ -36,6 +36,16 @@ pub struct Request { } impl Request { + /// Create a new request with an empty body and no headers + pub fn new(uri: Uri, method: Method) -> Self { + Self { + uri, + method, + headers: HeaderMap::default(), + body: Body::Bytes(bytes::Bytes::new()), + } + } + pub fn uri(&self) -> &Uri { &self.uri } diff --git a/sdk/data_cosmos/examples/attachments_00.rs b/sdk/data_cosmos/examples/attachments_00.rs index 49b4dc17d7..86507d4557 100644 --- a/sdk/data_cosmos/examples/attachments_00.rs +++ b/sdk/data_cosmos/examples/attachments_00.rs @@ -75,7 +75,7 @@ async fn main() -> Result<(), Box> { println!("creating"); let attachment_client = document_client.clone().into_attachment_client("myref06"); let resp = attachment_client - .create_reference( + .create_attachment( "https://cdn.pixabay.com/photo/2020/01/11/09/30/abstract-background-4756987__340.jpg", "image/jpeg", ) @@ -100,12 +100,12 @@ async fn main() -> Result<(), Box> { println!("replacing"); let attachment_client = document_client.clone().into_attachment_client("myref06"); let resp = attachment_client - .replace_reference() - .consistency_level(session_token) - .execute( + .replace_attachment( "https://Adn.pixabay.com/photo/2020/01/11/09/30/abstract-background-4756987__340.jpg", "image/jpeg", ) + .consistency_level(session_token) + .into_future() .await?; println!("replace reference == {:#?}", resp); diff --git a/sdk/data_cosmos/examples/key_ranges_00.rs b/sdk/data_cosmos/examples/key_ranges_00.rs index f7a8470872..08402d6471 100644 --- a/sdk/data_cosmos/examples/key_ranges_00.rs +++ b/sdk/data_cosmos/examples/key_ranges_00.rs @@ -25,7 +25,7 @@ async fn main() -> Result<(), Box> { let client = client.into_database_client(database); let client = client.into_collection_client(collection); - let resp = client.get_partition_key_ranges().execute().await?; + let resp = client.get_partition_key_ranges().into_future().await?; println!("resp == {:#?}", resp); Ok(()) diff --git a/sdk/data_cosmos/examples/stored_proc_00.rs b/sdk/data_cosmos/examples/stored_proc_00.rs index 515e7148ce..a04c9f36a7 100644 --- a/sdk/data_cosmos/examples/stored_proc_00.rs +++ b/sdk/data_cosmos/examples/stored_proc_00.rs @@ -35,7 +35,7 @@ async fn main() -> Result<(), Box> { .into_stored_procedure_client("test_proc") .execute_stored_procedure() .parameters(["Robert"]) - .execute::() + .into_future::() .await?; println!("Response object:\n{:#?}", ret); diff --git a/sdk/data_cosmos/examples/stored_proc_01.rs b/sdk/data_cosmos/examples/stored_proc_01.rs index ac3a54c2db..06bce5a790 100644 --- a/sdk/data_cosmos/examples/stored_proc_01.rs +++ b/sdk/data_cosmos/examples/stored_proc_01.rs @@ -70,7 +70,7 @@ async fn main() -> Result<(), Box> { let execute_stored_procedure_response = stored_procedure_client .execute_stored_procedure() .parameters(["Robert"]) - .execute::() + .into_future::() .await?; println!( diff --git a/sdk/data_cosmos/src/clients/attachment_client.rs b/sdk/data_cosmos/src/clients/attachment_client.rs index fddc875199..2918bb6c5c 100644 --- a/sdk/data_cosmos/src/clients/attachment_client.rs +++ b/sdk/data_cosmos/src/clients/attachment_client.rs @@ -1,10 +1,6 @@ use crate::operations::*; -use crate::requests; -use crate::resources::ResourceType; use crate::ReadonlyString; -use azure_core::HttpClient; -use azure_core::Pipeline; -use azure_core::Request; +use azure_core::{Pipeline, Request}; use bytes::Bytes; use super::*; @@ -73,27 +69,35 @@ impl AttachmentClient { CreateOrReplaceSlugAttachmentBuilder::new(self.clone(), false, body) } - /// Initiate a request to create ant. - pub fn create_reference( + /// Initiate a request to create a reference attachment. + pub fn create_attachment( &self, media: M, content_type: C, - ) -> CreateReferenceAttachmentBuilder + ) -> CreateOrReplaceAttachmentBuilder where M: Into, C: Into, { - CreateReferenceAttachmentBuilder::new(self.clone(), media.into(), content_type.into()) + CreateOrReplaceAttachmentBuilder::new(self.clone(), true, media.into(), content_type.into()) } /// Initiate a request to replace an attachment. - pub fn replace_reference(&self) -> requests::ReplaceReferenceAttachmentBuilder<'_, '_> { - requests::ReplaceReferenceAttachmentBuilder::new(self) - } - - /// Get a raw [`HttpClient`]. - pub(crate) fn http_client(&self) -> &dyn HttpClient { - self.cosmos_client().http_client() + pub fn replace_attachment( + &self, + media: M, + content_type: C, + ) -> CreateOrReplaceAttachmentBuilder + where + M: Into, + C: Into, + { + CreateOrReplaceAttachmentBuilder::new( + self.clone(), + false, + media.into(), + content_type.into(), + ) } pub(crate) fn prepare_pipeline(&self, method: http::Method) -> Request { @@ -108,23 +112,6 @@ impl AttachmentClient { ) } - pub(crate) fn prepare_request_with_attachment_name( - &self, - method: http::Method, - ) -> http::request::Builder { - self.cosmos_client().prepare_request( - &format!( - "dbs/{}/colls/{}/docs/{}/attachments/{}", - self.database_client().database_name(), - self.collection_client().collection_name(), - self.document_client().document_name(), - self.attachment_name() - ), - method, - ResourceType::Attachments, - ) - } - pub(crate) fn prepare_pipeline_with_attachment_name(&self, method: http::Method) -> Request { self.cosmos_client().prepare_request_pipeline( &format!( diff --git a/sdk/data_cosmos/src/clients/collection_client.rs b/sdk/data_cosmos/src/clients/collection_client.rs index 7db94bfb05..d272384bb2 100644 --- a/sdk/data_cosmos/src/clients/collection_client.rs +++ b/sdk/data_cosmos/src/clients/collection_client.rs @@ -1,12 +1,11 @@ use super::{DatabaseClient, UserDefinedFunctionClient}; use crate::clients::*; use crate::operations::*; -use crate::requests; use crate::resources::collection::PartitionKey; use crate::resources::document::Query; use crate::CosmosEntity; use crate::ReadonlyString; -use azure_core::{HttpClient, Pipeline, Request}; +use azure_core::{Pipeline, Request}; use serde::Serialize; /// A client for Cosmos collection resources. @@ -94,8 +93,8 @@ impl CollectionClient { } /// list the partition key ranges in a collection - pub fn get_partition_key_ranges(&self) -> requests::GetPartitionKeyRangesBuilder<'_, '_> { - requests::GetPartitionKeyRangesBuilder::new(self) + pub fn get_partition_key_ranges(&self) -> GetPartitionKeyRangesBuilder { + GetPartitionKeyRangesBuilder::new(self.clone()) } /// convert into a [`DocumentClient`] @@ -141,10 +140,6 @@ impl CollectionClient { .prepare_request_pipeline(path, http_method) } - pub(crate) fn http_client(&self) -> &dyn HttpClient { - self.cosmos_client().http_client() - } - pub(crate) fn pipeline(&self) -> &Pipeline { self.cosmos_client().pipeline() } diff --git a/sdk/data_cosmos/src/clients/cosmos_client.rs b/sdk/data_cosmos/src/clients/cosmos_client.rs index db28051e61..1efd2076ea 100644 --- a/sdk/data_cosmos/src/clients/cosmos_client.rs +++ b/sdk/data_cosmos/src/clients/cosmos_client.rs @@ -1,14 +1,9 @@ use super::DatabaseClient; -use crate::authorization_policy::{generate_authorization, generate_resource_link}; -use crate::headers::*; use crate::operations::*; use crate::resources::permission::AuthorizationToken; -use crate::resources::ResourceType; -use crate::{ReadonlyString, TimeNonce}; +use crate::ReadonlyString; -use azure_core::{ClientOptions, HttpClient, Pipeline, Request}; -use http::request::Builder as RequestBuilder; -use http::{header, HeaderValue}; +use azure_core::{ClientOptions, Pipeline, Request}; use std::fmt::Debug; use std::sync::Arc; @@ -18,13 +13,10 @@ use std::sync::Arc; pub const EMULATOR_ACCOUNT_KEY: &str = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="; -const AZURE_VERSION: &str = "2018-12-31"; - /// A plain Cosmos client. #[derive(Debug, Clone)] pub struct CosmosClient { pipeline: Pipeline, - auth_token: AuthorizationToken, cloud_location: CloudLocation, } @@ -75,14 +67,9 @@ impl CosmosClient { /// Create a new `CosmosClient` which connects to the account's instance in the public Azure cloud. pub fn new(account: String, auth_token: AuthorizationToken, options: CosmosOptions) -> Self { let cloud_location = CloudLocation::Public(account); - // TODO: The AuthorizationToken will only be stored in the pipeline via its policy. - // Right now the AuthorizationToken is a field of the Client. - // This will be corrected once every Cosmos function has been be migrated to the pipeline. - // Once that happens, we will remove the clone below. - let pipeline = new_pipeline_from_options(options, auth_token.clone()); + let pipeline = new_pipeline_from_options(options, auth_token); Self { pipeline, - auth_token, cloud_location, } } @@ -108,10 +95,9 @@ impl CosmosClient { options: CosmosOptions, ) -> Self { let cloud_location = CloudLocation::China(account); - let pipeline = new_pipeline_from_options(options, auth_token.clone()); + let pipeline = new_pipeline_from_options(options, auth_token); Self { pipeline, - auth_token, cloud_location, } } @@ -124,10 +110,9 @@ impl CosmosClient { options: CosmosOptions, ) -> Self { let cloud_location = CloudLocation::Custom { account, uri }; - let pipeline = new_pipeline_from_options(options, auth_token.clone()); + let pipeline = new_pipeline_from_options(options, auth_token); Self { pipeline, - auth_token, cloud_location, } } @@ -140,19 +125,15 @@ impl CosmosClient { account: String::from("Custom"), uri, }; - let pipeline = new_pipeline_from_options(options, auth_token.clone()); + let pipeline = new_pipeline_from_options(options, auth_token); Self { pipeline, - auth_token, cloud_location, } } /// Set the auth token used pub fn auth_token(&mut self, auth_token: AuthorizationToken) { - // TODO: To remove once everything uses the AutorizationPolicy - self.auth_token = auth_token.clone(); - // we replace the AuthorizationPolicy. This is // the last-1 policy by construction. let auth_policy: Arc = @@ -177,74 +158,23 @@ impl CosmosClient { DatabaseClient::new(self, database_name) } - /// Prepares an `http::RequestBuilder`. - /// - /// TODO: Remove once all operations have been moved to pipeline architecture. This is used by - /// legacy operations that have not moved to the use of the pipeline architecture. Once - /// that is complete, this will be superceded by `prepare_request_pipeline`. - pub(crate) fn prepare_request( - &self, - uri_path: &str, - http_method: http::Method, - resource_type: ResourceType, - ) -> RequestBuilder { - let time = TimeNonce::default(); - - let auth = { - let resource_link = generate_resource_link(uri_path); - trace!( - "resource_link generated by prepare_request == {}", - resource_link - ); - generate_authorization( - &self.auth_token, - &http_method, - &resource_type, - resource_link, - time, - ) - }; - trace!("prepare_request::auth == {:?}", auth); - let uri = format!("{}/{}", self.cloud_location.url(), uri_path); - debug!("building request. uri: {}", uri); - - RequestBuilder::new() - .method(http_method) - .uri(uri) - .header(HEADER_DATE, time.to_string()) - .header(HEADER_VERSION, HeaderValue::from_static(AZURE_VERSION)) - .header(header::AUTHORIZATION, auth) - } - - /// Prepares' an `azure_core::Request`. This function will - /// add the cloud location to the URI suffix and generate - /// a Request with the specified HTTP Method. - /// It will also set the body to an empty Bytes instance. - /// *Note*: This call does not handle authorization as - /// it will be done by the `AuthorizationPolicy`. + /// Prepares' an `azure_core::Request`. /// - /// Note: Eventually this method will replace `prepare_request` fully. + /// This function will add the cloud location to the URI suffix and generate + /// a Request with the specified HTTP Method. It will also set the body + /// to an empty `Bytes` instance. pub(crate) fn prepare_request_pipeline( &self, uri_path: &str, http_method: http::Method, ) -> Request { let uri = format!("{}/{}", self.cloud_location.url(), uri_path); - RequestBuilder::new() - .method(http_method) - .uri(uri) - .body(bytes::Bytes::new()) - .unwrap() - .into() + Request::new(uri.parse().unwrap(), http_method) } pub(crate) fn pipeline(&self) -> &Pipeline { &self.pipeline } - - pub(crate) fn http_client(&self) -> &dyn HttpClient { - self.pipeline.http_client() - } } /// The cloud with which you want to interact. diff --git a/sdk/data_cosmos/src/clients/document_client.rs b/sdk/data_cosmos/src/clients/document_client.rs index 45e52878e0..932ac6f944 100644 --- a/sdk/data_cosmos/src/clients/document_client.rs +++ b/sdk/data_cosmos/src/clients/document_client.rs @@ -13,12 +13,9 @@ pub struct DocumentClient { } impl DocumentClient { - /// This function creates a new instance of a DocumentClient. A document is identified by its - /// primary key and its partition key. + /// Create a new instance of a DocumentClient. /// - /// Partition key is eagerly evaluated: the json representation is generated as soon as you - /// call the `new` function. This avoids doing the serialization over and over, saving time. - /// It also releases the borrow since the serialized string is owned by the `DocumentClient`. + /// A document is identified by its primary key and its partition key. pub(crate) fn new, PK: Serialize>( collection_client: CollectionClient, document_name: S, diff --git a/sdk/data_cosmos/src/clients/stored_procedure_client.rs b/sdk/data_cosmos/src/clients/stored_procedure_client.rs index 6d3f824768..9f28382845 100644 --- a/sdk/data_cosmos/src/clients/stored_procedure_client.rs +++ b/sdk/data_cosmos/src/clients/stored_procedure_client.rs @@ -1,8 +1,7 @@ use super::*; use crate::prelude::*; -use crate::resources::ResourceType; -use crate::{requests, ReadonlyString}; -use azure_core::{HttpClient, Pipeline, Request}; +use crate::ReadonlyString; +use azure_core::{Pipeline, Request}; /// A client for Cosmos stored procedure resources. #[derive(Debug, Clone)] @@ -59,8 +58,8 @@ impl StoredProcedureClient { } /// Execute the stored procedure - pub fn execute_stored_procedure(&self) -> requests::ExecuteStoredProcedureBuilder<'_, '_> { - requests::ExecuteStoredProcedureBuilder::new(self) + pub fn execute_stored_procedure(&self) -> ExecuteStoredProcedureBuilder { + ExecuteStoredProcedureBuilder::new(self.clone()) } /// Delete the stored procedure @@ -68,22 +67,6 @@ impl StoredProcedureClient { DeleteStoredProcedureBuilder::new(self.clone()) } - pub(crate) fn prepare_request_with_stored_procedure_name( - &self, - method: http::Method, - ) -> http::request::Builder { - self.cosmos_client().prepare_request( - &format!( - "dbs/{}/colls/{}/sprocs/{}", - self.database_client().database_name(), - self.collection_client().collection_name(), - self.stored_procedure_name() - ), - method, - ResourceType::StoredProcedures, - ) - } - pub(crate) fn prepare_pipeline_with_stored_procedure_name( &self, method: http::Method, @@ -113,8 +96,4 @@ impl StoredProcedureClient { pub(crate) fn pipeline(&self) -> &Pipeline { self.cosmos_client().pipeline() } - - pub(crate) fn http_client(&self) -> &dyn HttpClient { - self.cosmos_client().http_client() - } } diff --git a/sdk/data_cosmos/src/consistency_level.rs b/sdk/data_cosmos/src/consistency_level.rs index db02581653..f516c9bea1 100644 --- a/sdk/data_cosmos/src/consistency_level.rs +++ b/sdk/data_cosmos/src/consistency_level.rs @@ -1,7 +1,6 @@ use crate::headers; use crate::operations::*; use crate::resources::user::UserResponse; -use crate::responses::*; use azure_core::AddAsHeader; use http::request; use serde::de::DeserializeOwned; @@ -68,8 +67,7 @@ implement_from!(CreateOrReplaceSlugAttachmentResponse); implement_from!(GetCollectionResponse); implement_from!(UserResponse); implement_from!(DeleteAttachmentResponse); -implement_from!(ReplaceReferenceAttachmentResponse); -implement_from!(CreateReferenceAttachmentResponse); +implement_from!(CreateOrReplaceAttachmentResponse); implement_from!(ListAttachmentsResponse); implement_from!(GetAttachmentResponse); implement_from!(CreateDocumentResponse); diff --git a/sdk/data_cosmos/src/cosmos_entity.rs b/sdk/data_cosmos/src/cosmos_entity.rs index 6544cac9d0..4a7233438b 100644 --- a/sdk/data_cosmos/src/cosmos_entity.rs +++ b/sdk/data_cosmos/src/cosmos_entity.rs @@ -1,6 +1,5 @@ use crate::headers; use azure_core::Request as HttpRequest; -use http::request::Builder; use serde::Serialize; /// CosmosDB partition key. Every CosmosDB entity must implement it. @@ -26,16 +25,6 @@ pub(crate) fn serialize_partition_key(pk: &PK) -> Result Builder { - builder.header( - headers::HEADER_DOCUMENTDB_PARTITIONKEY, - partition_key_serialized, - ) -} - pub(crate) fn add_as_partition_key_header_serialized2( partition_key_serialized: &str, request: &mut HttpRequest, diff --git a/sdk/data_cosmos/src/lib.rs b/sdk/data_cosmos/src/lib.rs index 9849eabc27..cee4cc2cbb 100644 --- a/sdk/data_cosmos/src/lib.rs +++ b/sdk/data_cosmos/src/lib.rs @@ -107,9 +107,7 @@ extern crate azure_core; pub mod clients; pub mod operations; pub mod prelude; -pub mod requests; pub mod resources; -pub mod responses; mod authorization_policy; mod consistency_level; diff --git a/sdk/data_cosmos/src/operations/create_reference_attachment.rs b/sdk/data_cosmos/src/operations/create_or_replace_attachment.rs similarity index 82% rename from sdk/data_cosmos/src/operations/create_reference_attachment.rs rename to sdk/data_cosmos/src/operations/create_or_replace_attachment.rs index d7604a2632..86593549d6 100644 --- a/sdk/data_cosmos/src/operations/create_reference_attachment.rs +++ b/sdk/data_cosmos/src/operations/create_or_replace_attachment.rs @@ -10,18 +10,25 @@ use azure_core::{collect_pinned_stream, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] -pub struct CreateReferenceAttachmentBuilder { +pub struct CreateOrReplaceAttachmentBuilder { client: AttachmentClient, + is_create: bool, media: String, content_type: String, consistency_level: Option, context: Context, } -impl CreateReferenceAttachmentBuilder { - pub(crate) fn new(client: AttachmentClient, media: String, content_type: String) -> Self { +impl CreateOrReplaceAttachmentBuilder { + pub(crate) fn new( + client: AttachmentClient, + is_create: bool, + media: String, + content_type: String, + ) -> Self { Self { client, + is_create, media, content_type, consistency_level: None, @@ -33,9 +40,14 @@ impl CreateReferenceAttachmentBuilder { context: Context => context, } - pub fn into_future(self) -> CreateReferenceAttachment { + pub fn into_future(self) -> CreateOrReplaceAttachment { Box::pin(async move { - let mut req = self.client.prepare_pipeline(http::Method::POST); + let mut req = if self.is_create { + self.client.prepare_pipeline(http::Method::POST) + } else { + self.client + .prepare_pipeline_with_attachment_name(http::Method::PUT) + }; azure_core::headers::add_optional_header2(&self.consistency_level, &mut req)?; crate::cosmos_entity::add_as_partition_key_header_serialized2( @@ -67,26 +79,26 @@ impl CreateReferenceAttachmentBuilder { &mut req, ) .await?; - CreateReferenceAttachmentResponse::try_from(response).await + CreateOrReplaceAttachmentResponse::try_from(response).await }) } } /// The future returned by calling `into_future` on the builder. -pub type CreateReferenceAttachment = - futures::future::BoxFuture<'static, crate::Result>; +pub type CreateOrReplaceAttachment = + futures::future::BoxFuture<'static, crate::Result>; #[cfg(feature = "into_future")] -impl std::future::IntoFuture for CreateReferenceAttachmentBuilder { - type Future = CreateReferenceAttachment; - type Output = ::Output; +impl std::future::IntoFuture for CreateOrReplaceAttachmentBuilder { + type Future = CreateOrReplaceAttachment; + type Output = ::Output; fn into_future(self) -> Self::Future { Self::into_future(self) } } #[derive(Debug, Clone, PartialEq)] -pub struct CreateReferenceAttachmentResponse { +pub struct CreateOrReplaceAttachmentResponse { pub attachment: Attachment, pub max_media_storage_usage_mb: u64, pub media_storage_usage_mb: u64, @@ -113,7 +125,7 @@ pub struct CreateReferenceAttachmentResponse { pub date: DateTime, } -impl CreateReferenceAttachmentResponse { +impl CreateOrReplaceAttachmentResponse { pub async fn try_from(response: HttpResponse) -> crate::Result { let (_status_code, headers, pinned_stream) = response.deconstruct(); let body = collect_pinned_stream(pinned_stream).await?; diff --git a/sdk/data_cosmos/src/operations/execute_stored_procedure.rs b/sdk/data_cosmos/src/operations/execute_stored_procedure.rs new file mode 100644 index 0000000000..f6fd88bb70 --- /dev/null +++ b/sdk/data_cosmos/src/operations/execute_stored_procedure.rs @@ -0,0 +1,152 @@ +use crate::headers::from_headers::*; +use crate::prelude::*; +use crate::resources::stored_procedure::Parameters; +use azure_core::collect_pinned_stream; +use azure_core::headers::session_token_from_headers; +use azure_core::prelude::*; +use azure_core::{Response as HttpResponse, SessionToken}; +use bytes::Bytes; +use chrono::{DateTime, Utc}; +use serde::de::DeserializeOwned; + +#[derive(Debug, Clone)] +pub struct ExecuteStoredProcedureBuilder { + client: StoredProcedureClient, + parameters: Option, + consistency_level: Option, + allow_tentative_writes: TentativeWritesAllowance, + partition_key: Option, + context: Context, +} + +static EMPTY_LIST: &[u8; 2] = b"[]"; + +impl ExecuteStoredProcedureBuilder { + pub(crate) fn new(client: StoredProcedureClient) -> Self { + Self { + client, + parameters: None, + consistency_level: None, + allow_tentative_writes: TentativeWritesAllowance::Deny, + partition_key: None, + context: Context::new(), + } + } + + setters! { + consistency_level: ConsistencyLevel => Some(consistency_level), + allow_tentative_writes: TentativeWritesAllowance, + parameters: Parameters => Some(parameters), + context: Context, + } + + pub fn partition_key(self, pk: &PK) -> Result { + Ok(Self { + partition_key: Some(crate::cosmos_entity::serialize_partition_key(pk)?), + ..self + }) + } + + pub fn into_future(self) -> ExecuteStoredProcedure + where + T: DeserializeOwned, + { + Box::pin(async move { + let mut request = self + .client + .prepare_pipeline_with_stored_procedure_name(http::Method::POST); + + if let Some(pk) = self.partition_key.as_ref() { + crate::cosmos_entity::add_as_partition_key_header_serialized2(pk, &mut request) + } + + azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?; + azure_core::headers::add_mandatory_header2(&self.allow_tentative_writes, &mut request)?; + + let body = if let Some(parameters) = self.parameters.as_ref() { + Bytes::from(parameters.to_json()) + } else { + Bytes::from_static(EMPTY_LIST) + }; + + request.set_body(body.into()); + + let response = self + .client + .cosmos_client() + .pipeline() + .send( + self.context.clone().insert(ResourceType::StoredProcedures), + &mut request, + ) + .await?; + + ExecuteStoredProcedureResponse::try_from(response).await + }) + } +} + +/// The future returned by calling `into_future` on the builder. +pub type ExecuteStoredProcedure = + futures::future::BoxFuture<'static, crate::Result>>; + +#[derive(Debug, Clone)] +pub struct ExecuteStoredProcedureResponse +where + T: DeserializeOwned, +{ + pub payload: T, + + pub last_state_change: DateTime, + pub schema_version: String, + pub alt_content_path: String, + pub content_path: String, + pub quorum_acked_lsn: u64, + pub current_write_quorum: u64, + pub current_replica_set_size: u64, + pub role: u32, + pub global_committed_lsn: u64, + pub number_of_read_regions: u32, + pub transport_request_id: u64, + pub cosmos_llsn: u64, + pub cosmos_quorum_acked_llsn: Option, + pub session_token: SessionToken, + pub charge: f64, + pub service_version: String, + pub activity_id: uuid::Uuid, + pub gateway_version: String, + pub date: DateTime, +} + +impl ExecuteStoredProcedureResponse +where + T: DeserializeOwned, +{ + pub async fn try_from(response: HttpResponse) -> crate::Result { + let (_status_code, headers, pinned_stream) = response.deconstruct(); + let body = collect_pinned_stream(pinned_stream).await?; + + Ok(Self { + payload: serde_json::from_slice(&body)?, + last_state_change: last_state_change_from_headers(&headers)?, + schema_version: schema_version_from_headers(&headers)?.to_owned(), + alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(), + content_path: content_path_from_headers(&headers)?.to_owned(), + quorum_acked_lsn: quorum_acked_lsn_from_headers(&headers)?, + current_write_quorum: current_write_quorum_from_headers(&headers)?, + current_replica_set_size: current_replica_set_size_from_headers(&headers)?, + role: role_from_headers(&headers)?, + global_committed_lsn: global_committed_lsn_from_headers(&headers)?, + number_of_read_regions: number_of_read_regions_from_headers(&headers)?, + transport_request_id: transport_request_id_from_headers(&headers)?, + cosmos_llsn: cosmos_llsn_from_headers(&headers)?, + cosmos_quorum_acked_llsn: cosmos_quorum_acked_llsn_from_headers_optional(&headers)?, + session_token: session_token_from_headers(&headers)?, + charge: request_charge_from_headers(&headers)?, + service_version: service_version_from_headers(&headers)?.to_owned(), + activity_id: activity_id_from_headers(&headers)?, + gateway_version: gateway_version_from_headers(&headers)?.to_owned(), + date: date_from_headers(&headers)?, + }) + } +} diff --git a/sdk/data_cosmos/src/operations/get_partition_key_ranges.rs b/sdk/data_cosmos/src/operations/get_partition_key_ranges.rs new file mode 100644 index 0000000000..e70b3cbc9e --- /dev/null +++ b/sdk/data_cosmos/src/operations/get_partition_key_ranges.rs @@ -0,0 +1,163 @@ +use crate::headers::from_headers::*; +use crate::prelude::*; +use crate::resources::ResourceType; +use azure_core::headers::{item_count_from_headers, session_token_from_headers}; +use azure_core::{collect_pinned_stream, prelude::*, Response as HttpResponse}; +use chrono::{DateTime, Utc}; + +#[derive(Debug, Clone)] +pub struct GetPartitionKeyRangesBuilder { + client: CollectionClient, + if_match_condition: Option, + if_modified_since: Option, + consistency_level: Option, + context: Context, +} + +impl GetPartitionKeyRangesBuilder { + pub(crate) fn new(client: CollectionClient) -> Self { + Self { + client, + if_match_condition: None, + if_modified_since: None, + consistency_level: None, + context: Context::new(), + } + } + + setters! { + consistency_level: ConsistencyLevel => Some(consistency_level), + if_match_condition: IfMatchCondition => Some(if_match_condition), + if_modified_since: DateTime => Some(IfModifiedSince::new(if_modified_since)), + context: Context => context, + } + + pub fn into_future(self) -> GetPartitionKeyRanges { + Box::pin(async move { + let mut request = self.client.cosmos_client().prepare_request_pipeline( + &format!( + "dbs/{}/colls/{}/pkranges", + self.client.database_client().database_name(), + self.client.collection_name() + ), + http::Method::GET, + ); + + azure_core::headers::add_optional_header2(&self.if_match_condition, &mut request)?; + azure_core::headers::add_optional_header2(&self.if_modified_since, &mut request)?; + azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?; + + let response = self + .client + .pipeline() + .send( + self.context + .clone() + .insert(ResourceType::PartitionKeyRanges), + &mut request, + ) + .await?; + + GetPartitionKeyRangesResponse::try_from(response).await + }) + } +} + +/// The future returned by calling `into_future` on the builder. +pub type GetPartitionKeyRanges = + futures::future::BoxFuture<'static, crate::Result>; + +#[cfg(feature = "into_future")] +impl std::future::IntoFuture for GetPartitionKeyRangesBuilder { + type Future = GetPartitionKeyRanges; + type Output = ::Output; + fn into_future(self) -> Self::Future { + Self::into_future(self) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct GetPartitionKeyRangesResponse { + pub rid: String, + pub content_location: String, + pub server: String, + pub last_state_change: DateTime, + pub lsn: u64, + pub item_count: u32, + pub schema_version: String, + pub alt_content_path: String, + pub content_path: String, + pub role: u32, + pub global_committed_lsn: u64, + pub number_of_read_regions: u32, + pub transport_request_id: u64, + pub cosmos_llsn: u64, + pub session_token: String, + pub service_version: String, + pub activity_id: uuid::Uuid, + pub gateway_version: String, + pub date: DateTime, + pub partition_key_ranges: Vec, +} + +impl GetPartitionKeyRangesResponse { + pub async fn try_from(response: HttpResponse) -> crate::Result { + let (_status_code, headers, pinned_stream) = response.deconstruct(); + let body = collect_pinned_stream(pinned_stream).await?; + + #[derive(Debug, Deserialize)] + struct Response { + #[serde(rename = "_rid")] + pub rid: String, + #[serde(rename = "PartitionKeyRanges")] + pub partition_key_ranges: Vec, + } + + let r: Response = serde_json::from_slice(&body)?; + + Ok(Self { + rid: r.rid, + content_location: content_location_from_headers(&headers)?.to_owned(), + server: server_from_headers(&headers)?.to_owned(), + last_state_change: last_state_change_from_headers(&headers)?, + lsn: lsn_from_headers(&headers)?, + item_count: item_count_from_headers(&headers)?, + schema_version: schema_version_from_headers(&headers)?.to_owned(), + alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(), + content_path: content_path_from_headers(&headers)?.to_owned(), + role: role_from_headers(&headers)?, + global_committed_lsn: global_committed_lsn_from_headers(&headers)?, + number_of_read_regions: number_of_read_regions_from_headers(&headers)?, + transport_request_id: transport_request_id_from_headers(&headers)?, + cosmos_llsn: cosmos_llsn_from_headers(&headers)?, + service_version: service_version_from_headers(&headers)?.to_owned(), + activity_id: activity_id_from_headers(&headers)?, + session_token: session_token_from_headers(&headers)?, + gateway_version: gateway_version_from_headers(&headers)?.to_owned(), + date: date_from_headers(&headers)?, + partition_key_ranges: r.partition_key_ranges, + }) + } +} + +#[derive(Debug, PartialEq, PartialOrd, Clone, Deserialize)] +pub struct PartitionKeyRange { + #[serde(rename = "_rid")] + pub rid: String, + pub id: String, + #[serde(rename = "_etag")] + pub etag: String, + #[serde(rename = "minInclusive")] + pub min_exclusive: String, + #[serde(rename = "maxExclusive")] + pub max_exclusive: String, + #[serde(rename = "ridPrefix")] + pub rid_prefix: u64, + pub _self: String, + #[serde(rename = "throughputFraction")] + pub throughput_fraction: u64, + pub status: String, + // TODO: parents + #[serde(rename = "_ts")] + pub ts: u64, +} diff --git a/sdk/data_cosmos/src/operations/mod.rs b/sdk/data_cosmos/src/operations/mod.rs index 2b7bbcfe8f..a87adf58f3 100644 --- a/sdk/data_cosmos/src/operations/mod.rs +++ b/sdk/data_cosmos/src/operations/mod.rs @@ -5,11 +5,11 @@ mod create_collection; mod create_database; mod create_document; +mod create_or_replace_attachment; mod create_or_replace_slug_attachment; mod create_or_replace_trigger; mod create_or_replace_user_defined_function; mod create_permission; -mod create_reference_attachment; mod create_stored_procedure; mod create_user; mod delete_attachment; @@ -21,10 +21,12 @@ mod delete_stored_procedure; mod delete_trigger; mod delete_user; mod delete_user_defined_function; +mod execute_stored_procedure; mod get_attachment; mod get_collection; mod get_database; mod get_document; +mod get_partition_key_ranges; mod get_permission; mod get_user; mod list_attachments; @@ -46,11 +48,11 @@ mod replace_user; pub use create_collection::*; pub use create_database::*; pub use create_document::*; +pub use create_or_replace_attachment::*; pub use create_or_replace_slug_attachment::*; pub use create_or_replace_trigger::*; pub use create_or_replace_user_defined_function::*; pub use create_permission::*; -pub use create_reference_attachment::*; pub use create_stored_procedure::*; pub use create_user::*; pub use delete_attachment::*; @@ -62,10 +64,12 @@ pub use delete_stored_procedure::*; pub use delete_trigger::*; pub use delete_user::*; pub use delete_user_defined_function::*; +pub use execute_stored_procedure::*; pub use get_attachment::*; pub use get_collection::*; pub use get_database::*; pub use get_document::*; +pub use get_partition_key_ranges::*; pub use get_permission::*; pub use get_user::*; pub use list_attachments::*; diff --git a/sdk/data_cosmos/src/requests/execute_stored_procedure_builder.rs b/sdk/data_cosmos/src/requests/execute_stored_procedure_builder.rs deleted file mode 100644 index a023cc3f41..0000000000 --- a/sdk/data_cosmos/src/requests/execute_stored_procedure_builder.rs +++ /dev/null @@ -1,90 +0,0 @@ -use crate::prelude::*; -use crate::resources::stored_procedure::Parameters; -use crate::responses::ExecuteStoredProcedureResponse; -use azure_core::prelude::*; -use bytes::Bytes; -use http::StatusCode; -use serde::de::DeserializeOwned; -use std::convert::TryInto; - -#[derive(Debug, Clone)] -pub struct ExecuteStoredProcedureBuilder<'a, 'b> { - stored_procedure_client: &'a StoredProcedureClient, - parameters: Option, - user_agent: Option>, - activity_id: Option>, - consistency_level: Option, - allow_tentative_writes: TentativeWritesAllowance, - partition_key: Option, -} - -static EMPTY_LIST: &[u8; 2] = b"[]"; - -impl<'a, 'b> ExecuteStoredProcedureBuilder<'a, 'b> { - pub(crate) fn new(stored_procedure_client: &'a StoredProcedureClient) -> Self { - Self { - stored_procedure_client, - parameters: None, - user_agent: None, - activity_id: None, - consistency_level: None, - allow_tentative_writes: TentativeWritesAllowance::Deny, - partition_key: None, - } - } - - setters! { - user_agent: &'b str => Some(UserAgent::new(user_agent)), - activity_id: &'b str => Some(ActivityId::new(activity_id)), - consistency_level: ConsistencyLevel => Some(consistency_level), - allow_tentative_writes: TentativeWritesAllowance, - parameters: Parameters => Some(parameters), - } - - pub fn partition_key(self, pk: &PK) -> Result { - Ok(Self { - partition_key: Some(crate::cosmos_entity::serialize_partition_key(pk)?), - ..self - }) - } - - pub async fn execute(&self) -> crate::Result> - where - T: DeserializeOwned, - { - trace!("ExecuteStoredProcedureBuilder::execute called"); - - let request = self - .stored_procedure_client - .prepare_request_with_stored_procedure_name(http::Method::POST); - - let request = if let Some(pk) = self.partition_key.as_ref() { - crate::cosmos_entity::add_as_partition_key_header_serialized(pk, request) - } else { - request - }; - - let request = azure_core::headers::add_optional_header(&self.user_agent, request); - let request = azure_core::headers::add_optional_header(&self.activity_id, request); - let request = azure_core::headers::add_optional_header(&self.consistency_level, request); - let request = - azure_core::headers::add_mandatory_header(&self.allow_tentative_writes, request); - - let request = request.header(http::header::CONTENT_TYPE, "application/json"); - - let body = if let Some(parameters) = self.parameters.as_ref() { - Bytes::from(parameters.to_json()) - } else { - Bytes::from_static(EMPTY_LIST) - }; - - let request = request.body(body)?; - - Ok(self - .stored_procedure_client - .http_client() - .execute_request_check_status(request, StatusCode::OK) - .await? - .try_into()?) - } -} diff --git a/sdk/data_cosmos/src/requests/get_partition_key_ranges_builder.rs b/sdk/data_cosmos/src/requests/get_partition_key_ranges_builder.rs deleted file mode 100644 index 9f9aed2a06..0000000000 --- a/sdk/data_cosmos/src/requests/get_partition_key_ranges_builder.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::prelude::*; -use crate::resources::ResourceType; -use crate::responses::GetPartitionKeyRangesResponse; -use azure_core::prelude::*; -use chrono::{DateTime, Utc}; -use http::StatusCode; -use std::convert::TryInto; - -#[derive(Debug, Clone)] -pub struct GetPartitionKeyRangesBuilder<'a, 'b> { - collection_client: &'a CollectionClient, - if_match_condition: Option, - if_modified_since: Option, - user_agent: Option>, - activity_id: Option>, - consistency_level: Option, -} - -impl<'a, 'b> GetPartitionKeyRangesBuilder<'a, 'b> { - pub(crate) fn new(collection_client: &'a CollectionClient) -> Self { - Self { - collection_client, - if_match_condition: None, - if_modified_since: None, - user_agent: None, - activity_id: None, - consistency_level: None, - } - } - - setters! { - user_agent: &'b str => Some(UserAgent::new(user_agent)), - activity_id: &'b str => Some(ActivityId::new(activity_id)), - consistency_level: ConsistencyLevel => Some(consistency_level), - if_match_condition: IfMatchCondition => Some(if_match_condition), - if_modified_since: DateTime => Some(IfModifiedSince::new(if_modified_since)), - } - - pub async fn execute(&self) -> crate::Result { - trace!("GetPartitionKeyRangesBuilder::execute called"); - - let request = self.collection_client.cosmos_client().prepare_request( - &format!( - "dbs/{}/colls/{}/pkranges", - self.collection_client.database_client().database_name(), - self.collection_client.collection_name() - ), - http::Method::GET, - ResourceType::PartitionKeyRanges, - ); - - let request = request.header(http::header::CONTENT_LENGTH, "0"); - let request = azure_core::headers::add_optional_header(&self.if_match_condition, request); - let request = azure_core::headers::add_optional_header(&self.if_modified_since, request); - let request = azure_core::headers::add_optional_header(&self.user_agent, request); - let request = azure_core::headers::add_optional_header(&self.activity_id, request); - let request = azure_core::headers::add_optional_header(&self.consistency_level, request); - - let request = request.body(azure_core::EMPTY_BODY)?; - - Ok(self - .collection_client - .http_client() - .execute_request_check_status(request, StatusCode::OK) - .await? - .try_into()?) - } -} diff --git a/sdk/data_cosmos/src/requests/mod.rs b/sdk/data_cosmos/src/requests/mod.rs deleted file mode 100644 index 29cc0eaae6..0000000000 --- a/sdk/data_cosmos/src/requests/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Request builder objects for every kind of request. -//! -//! These objects are usually created by calling some sort of method on a client. They -//! then give you the ability to modify your request with certain options and finally -//! execute the request with the `execute` method. - -#![allow(missing_docs)] - -mod execute_stored_procedure_builder; -mod get_partition_key_ranges_builder; -mod replace_reference_attachment_builder; - -pub use execute_stored_procedure_builder::ExecuteStoredProcedureBuilder; -pub use get_partition_key_ranges_builder::GetPartitionKeyRangesBuilder; -pub use replace_reference_attachment_builder::ReplaceReferenceAttachmentBuilder; diff --git a/sdk/data_cosmos/src/requests/replace_reference_attachment_builder.rs b/sdk/data_cosmos/src/requests/replace_reference_attachment_builder.rs deleted file mode 100644 index 8a4e5ea175..0000000000 --- a/sdk/data_cosmos/src/requests/replace_reference_attachment_builder.rs +++ /dev/null @@ -1,91 +0,0 @@ -use crate::prelude::*; -use azure_core::prelude::*; -use http::StatusCode; -use std::convert::TryInto; - -#[derive(Debug, Clone)] -pub struct ReplaceReferenceAttachmentBuilder<'a, 'b> { - attachment_client: &'a AttachmentClient, - if_match_condition: Option, - user_agent: Option>, - activity_id: Option>, - consistency_level: Option, -} - -impl<'a, 'b> ReplaceReferenceAttachmentBuilder<'a, 'b> { - pub(crate) fn new(attachment_client: &'a AttachmentClient) -> Self { - Self { - attachment_client, - if_match_condition: None, - user_agent: None, - activity_id: None, - consistency_level: None, - } - } -} - -impl<'a, 'b> ReplaceReferenceAttachmentBuilder<'a, 'b> { - setters! { - user_agent: &'b str => Some(UserAgent::new(user_agent)), - activity_id: &'b str => Some(ActivityId::new(activity_id)), - consistency_level: ConsistencyLevel => Some(consistency_level), - if_match_condition: IfMatchCondition => Some(if_match_condition), - } -} - -// methods callable only when every mandatory field has been filled -impl<'a, 'b> ReplaceReferenceAttachmentBuilder<'a, 'b> { - pub async fn execute( - &self, - media: M, - content_type: C, - ) -> crate::Result - where - M: AsRef, - C: Into>, - { - let mut req = self - .attachment_client - .prepare_request_with_attachment_name(http::Method::PUT); - - // add trait headers - req = azure_core::headers::add_optional_header(&self.if_match_condition, req); - req = azure_core::headers::add_optional_header(&self.user_agent, req); - req = azure_core::headers::add_optional_header(&self.activity_id, req); - req = azure_core::headers::add_optional_header(&self.consistency_level, req); - - req = crate::cosmos_entity::add_as_partition_key_header_serialized( - self.attachment_client - .document_client() - .partition_key_serialized(), - req, - ); - - // create serialized request - #[derive(Debug, Clone, Serialize)] - struct _Request<'r> { - pub id: &'r str, - #[serde(rename = "contentType")] - pub content_type: &'r str, - pub media: &'r str, - } - - let request = azure_core::to_json(&_Request { - id: self.attachment_client.attachment_name(), - content_type: content_type.into().as_str(), - media: media.as_ref(), - })?; - - req = req.header(http::header::CONTENT_TYPE, "application/json"); - req = req.header(http::header::CONTENT_LENGTH, request.len()); - let req = req.body(request)?; - debug!("req == {:#?}", req); - - Ok(self - .attachment_client - .http_client() - .execute_request_check_status(req, StatusCode::OK) - .await? - .try_into()?) - } -} diff --git a/sdk/data_cosmos/src/responses/execute_stored_procedure_response.rs b/sdk/data_cosmos/src/responses/execute_stored_procedure_response.rs deleted file mode 100644 index b858ac80af..0000000000 --- a/sdk/data_cosmos/src/responses/execute_stored_procedure_response.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::headers::from_headers::*; -use azure_core::headers::session_token_from_headers; -use azure_core::SessionToken; -use chrono::{DateTime, Utc}; -use http::response::Response; -use serde::de::DeserializeOwned; - -#[derive(Debug, Clone)] -pub struct ExecuteStoredProcedureResponse -where - T: DeserializeOwned, -{ - pub payload: T, - - pub last_state_change: DateTime, - pub schema_version: String, - pub alt_content_path: String, - pub content_path: String, - pub quorum_acked_lsn: u64, - pub current_write_quorum: u64, - pub current_replica_set_size: u64, - pub role: u32, - pub global_committed_lsn: u64, - pub number_of_read_regions: u32, - pub transport_request_id: u64, - pub cosmos_llsn: u64, - pub cosmos_quorum_acked_llsn: Option, - pub session_token: SessionToken, - pub charge: f64, - pub service_version: String, - pub activity_id: uuid::Uuid, - pub gateway_version: String, - pub date: DateTime, -} - -impl std::convert::TryFrom> for ExecuteStoredProcedureResponse -where - T: DeserializeOwned, -{ - type Error = crate::Error; - - fn try_from(response: Response) -> Result { - let headers = response.headers(); - let body = response.body(); - - debug!("headers == {:#?}", headers); - debug!("body == {:#?}", body); - - Ok(Self { - payload: serde_json::from_slice(body)?, - - last_state_change: last_state_change_from_headers(headers)?, - schema_version: schema_version_from_headers(headers)?.to_owned(), - alt_content_path: alt_content_path_from_headers(headers)?.to_owned(), - content_path: content_path_from_headers(headers)?.to_owned(), - quorum_acked_lsn: quorum_acked_lsn_from_headers(headers)?, - current_write_quorum: current_write_quorum_from_headers(headers)?, - current_replica_set_size: current_replica_set_size_from_headers(headers)?, - role: role_from_headers(headers)?, - global_committed_lsn: global_committed_lsn_from_headers(headers)?, - number_of_read_regions: number_of_read_regions_from_headers(headers)?, - transport_request_id: transport_request_id_from_headers(headers)?, - cosmos_llsn: cosmos_llsn_from_headers(headers)?, - cosmos_quorum_acked_llsn: cosmos_quorum_acked_llsn_from_headers_optional(headers)?, - session_token: session_token_from_headers(headers)?, - charge: request_charge_from_headers(headers)?, - service_version: service_version_from_headers(headers)?.to_owned(), - activity_id: activity_id_from_headers(headers)?, - gateway_version: gateway_version_from_headers(headers)?.to_owned(), - date: date_from_headers(headers)?, - }) - } -} diff --git a/sdk/data_cosmos/src/responses/get_partition_key_ranges_response.rs b/sdk/data_cosmos/src/responses/get_partition_key_ranges_response.rs deleted file mode 100644 index b119d9c999..0000000000 --- a/sdk/data_cosmos/src/responses/get_partition_key_ranges_response.rs +++ /dev/null @@ -1,92 +0,0 @@ -use crate::headers::from_headers::*; -use azure_core::headers::{item_count_from_headers, session_token_from_headers}; -use chrono::{DateTime, Utc}; -use http::response::Response; - -#[derive(Debug, Clone, PartialEq)] -pub struct GetPartitionKeyRangesResponse { - pub rid: String, - pub content_location: String, - pub server: String, - pub last_state_change: DateTime, - pub lsn: u64, - pub item_count: u32, - pub schema_version: String, - pub alt_content_path: String, - pub content_path: String, - pub role: u32, - pub global_committed_lsn: u64, - pub number_of_read_regions: u32, - pub transport_request_id: u64, - pub cosmos_llsn: u64, - pub session_token: String, - pub service_version: String, - pub activity_id: uuid::Uuid, - pub gateway_version: String, - pub date: DateTime, - pub partition_key_ranges: Vec, -} - -impl std::convert::TryFrom> for GetPartitionKeyRangesResponse { - type Error = crate::Error; - - fn try_from(response: Response) -> Result { - let headers = response.headers(); - let body = response.body(); - - #[derive(Debug, Deserialize)] - struct Response { - #[serde(rename = "_rid")] - pub rid: String, - #[serde(rename = "PartitionKeyRanges")] - pub partition_key_ranges: Vec, - } - - let r: Response = serde_json::from_slice(body)?; - - Ok(Self { - rid: r.rid, - content_location: content_location_from_headers(headers)?.to_owned(), - server: server_from_headers(headers)?.to_owned(), - last_state_change: last_state_change_from_headers(headers)?, - lsn: lsn_from_headers(headers)?, - item_count: item_count_from_headers(headers)?, - schema_version: schema_version_from_headers(headers)?.to_owned(), - alt_content_path: alt_content_path_from_headers(headers)?.to_owned(), - content_path: content_path_from_headers(headers)?.to_owned(), - role: role_from_headers(headers)?, - global_committed_lsn: global_committed_lsn_from_headers(headers)?, - number_of_read_regions: number_of_read_regions_from_headers(headers)?, - transport_request_id: transport_request_id_from_headers(headers)?, - cosmos_llsn: cosmos_llsn_from_headers(headers)?, - service_version: service_version_from_headers(headers)?.to_owned(), - activity_id: activity_id_from_headers(headers)?, - session_token: session_token_from_headers(headers)?, - gateway_version: gateway_version_from_headers(headers)?.to_owned(), - date: date_from_headers(headers)?, - partition_key_ranges: r.partition_key_ranges, - }) - } -} - -#[derive(Debug, PartialEq, PartialOrd, Clone, Deserialize)] -pub struct PartitionKeyRange { - #[serde(rename = "_rid")] - pub rid: String, - pub id: String, - #[serde(rename = "_etag")] - pub etag: String, - #[serde(rename = "minInclusive")] - pub min_exclusive: String, - #[serde(rename = "maxExclusive")] - pub max_exclusive: String, - #[serde(rename = "ridPrefix")] - pub rid_prefix: u64, - pub _self: String, - #[serde(rename = "throughputFraction")] - pub throughput_fraction: u64, - pub status: String, - // TODO: parents - #[serde(rename = "_ts")] - pub ts: u64, -} diff --git a/sdk/data_cosmos/src/responses/mod.rs b/sdk/data_cosmos/src/responses/mod.rs deleted file mode 100644 index cef0288007..0000000000 --- a/sdk/data_cosmos/src/responses/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Responses from any call to the Cosmos API. - -#![allow(missing_docs)] - -mod execute_stored_procedure_response; -mod get_partition_key_ranges_response; -mod replace_reference_attachment_response; - -pub use execute_stored_procedure_response::ExecuteStoredProcedureResponse; -pub use get_partition_key_ranges_response::GetPartitionKeyRangesResponse; -pub use replace_reference_attachment_response::ReplaceReferenceAttachmentResponse; diff --git a/sdk/data_cosmos/src/responses/replace_reference_attachment_response.rs b/sdk/data_cosmos/src/responses/replace_reference_attachment_response.rs deleted file mode 100644 index 1b141fc53f..0000000000 --- a/sdk/data_cosmos/src/responses/replace_reference_attachment_response.rs +++ /dev/null @@ -1,72 +0,0 @@ -use crate::headers::from_headers::*; -use crate::resources::Attachment; -use crate::ResourceQuota; -use azure_core::headers::{etag_from_headers, session_token_from_headers}; -use azure_core::SessionToken; -use chrono::{DateTime, Utc}; -use http::response::Response; - -#[derive(Debug, Clone, PartialEq)] -pub struct ReplaceReferenceAttachmentResponse { - pub attachment: Attachment, - pub last_change: DateTime, - pub etag: String, - pub resource_quota: Vec, - pub resource_usage: Vec, - pub lsn: u64, - pub alt_content_path: String, - pub content_path: String, - pub quorum_acked_lsn: u64, - pub current_write_quorum: u64, - pub current_replica_set_size: u64, - pub global_committed_lsn: u64, - pub number_of_read_regions: u32, - pub transport_request_id: u64, - pub cosmos_llsn: u64, - pub cosmos_quorum_acked_llsn: u64, - pub session_token: SessionToken, - pub request_charge: f64, - pub service_version: String, - pub activity_id: uuid::Uuid, - pub gateway_version: String, - pub date: DateTime, -} - -impl std::convert::TryFrom> for ReplaceReferenceAttachmentResponse { - type Error = crate::Error; - - fn try_from(response: Response) -> Result { - let headers = response.headers(); - let body = response.body(); - - debug!("headers == {:#?}", headers); - debug!("body == {:#?}", std::str::from_utf8(body)); - - let attachment: Attachment = serde_json::from_slice(body)?; - - Ok(Self { - attachment, - last_change: last_state_change_from_headers(headers)?, - etag: etag_from_headers(headers)?, - resource_quota: resource_quota_from_headers(headers)?, - resource_usage: resource_usage_from_headers(headers)?, - lsn: lsn_from_headers(headers)?, - alt_content_path: alt_content_path_from_headers(headers)?.to_owned(), - content_path: content_path_from_headers(headers)?.to_owned(), - quorum_acked_lsn: quorum_acked_lsn_from_headers(headers)?, - current_write_quorum: current_write_quorum_from_headers(headers)?, - current_replica_set_size: current_replica_set_size_from_headers(headers)?, - global_committed_lsn: global_committed_lsn_from_headers(headers)?, - number_of_read_regions: number_of_read_regions_from_headers(headers)?, - transport_request_id: transport_request_id_from_headers(headers)?, - cosmos_llsn: cosmos_llsn_from_headers(headers)?, - cosmos_quorum_acked_llsn: cosmos_quorum_acked_llsn_from_headers(headers)?, - session_token: session_token_from_headers(headers)?, - request_charge: request_charge_from_headers(headers)?, - service_version: service_version_from_headers(headers)?.to_owned(), - activity_id: activity_id_from_headers(headers)?, - gateway_version: gateway_version_from_headers(headers)?.to_owned(), - date: date_from_headers(headers)?, - }) - } -} diff --git a/sdk/data_cosmos/tests/attachment_00.rs b/sdk/data_cosmos/tests/attachment_00.rs index 27bad910c5..95a66eda74 100644 --- a/sdk/data_cosmos/tests/attachment_00.rs +++ b/sdk/data_cosmos/tests/attachment_00.rs @@ -107,16 +107,16 @@ async fn attachment() -> Result<(), azure_data_cosmos::Error> { // create reference attachment let attachment_client = document_client.clone().into_attachment_client("reference"); let resp = attachment_client - .create_reference("https://www.bing.com", "image/jpeg") + .create_attachment("https://www.bing.com", "image/jpeg") .consistency_level(&ret) .into_future() .await?; // replace reference attachment let resp = attachment_client - .replace_reference() + .replace_attachment("https://www.microsoft.com", "image/jpeg") .consistency_level(&resp) - .execute("https://www.microsoft.com", "image/jpeg") + .into_future() .await?; // create slug attachment diff --git a/sdk/data_cosmos/tests/cosmos_collection.rs b/sdk/data_cosmos/tests/cosmos_collection.rs index fb7bb92279..f68f214e2c 100644 --- a/sdk/data_cosmos/tests/cosmos_collection.rs +++ b/sdk/data_cosmos/tests/cosmos_collection.rs @@ -48,7 +48,7 @@ async fn create_and_delete_collection() { // check GetPartitionKeyRanges: https://docs.microsoft.com/rest/api/cosmos-db/get-partition-key-ranges collection_client .get_partition_key_ranges() - .execute() + .into_future() .await .unwrap();