diff --git a/sdk/core/src/headers/mod.rs b/sdk/core/src/headers/mod.rs index dd1e07045f..b2bc2036bb 100644 --- a/sdk/core/src/headers/mod.rs +++ b/sdk/core/src/headers/mod.rs @@ -83,6 +83,13 @@ pub fn add_mandatory_header(item: &T, builder: Builder) -> Build item.add_as_header(builder) } +pub fn add_mandatory_header2( + item: &T, + request: &mut crate::Request, +) -> Result<(), crate::errors::HTTPHeaderError> { + item.add_as_header2(request) +} + pub const SERVER: &str = "server"; pub const SOURCE_IF_MODIFIED_SINCE: &str = "x-ms-source-if-modified-since"; pub const SOURCE_IF_UNMODIFIED_SINCE: &str = "x-ms-source-if-unmodified-since"; diff --git a/sdk/cosmos/examples/attachments_00.rs b/sdk/cosmos/examples/attachments_00.rs index f5ee5a76ee..4c95152613 100644 --- a/sdk/cosmos/examples/attachments_00.rs +++ b/sdk/cosmos/examples/attachments_00.rs @@ -1,3 +1,4 @@ +use azure_core::Context; use azure_cosmos::prelude::*; use serde::{Deserialize, Serialize}; use std::borrow::Cow; @@ -56,7 +57,10 @@ async fn main() -> Result<(), Box> { }; // let's add an entity. - match client.create_document().execute(&doc).await { + match client + .create_document(Context::new(), &doc, CreateDocumentOptions::new()) + .await + { Ok(_) => { println!("document created"); } diff --git a/sdk/cosmos/examples/database_00.rs b/sdk/cosmos/examples/database_00.rs index 0f5fa2ed93..7b092866db 100644 --- a/sdk/cosmos/examples/database_00.rs +++ b/sdk/cosmos/examples/database_00.rs @@ -1,3 +1,4 @@ +use azure_core::Context; use azure_cosmos::prelude::*; use serde_json::Value; use std::error::Error; @@ -40,10 +41,12 @@ async fn main() -> Result<(), Box> { }"#; let document: Value = serde_json::from_str(data)?; - let resp = collection_client - .create_document() + let options = CreateDocumentOptions::new() .is_upsert(true) - .execute_with_partition_key(&document, &43u32) + .partition_key(&43u32) + .unwrap(); + let resp = collection_client + .create_document(Context::new(), &document, options) .await?; println!("resp == {:?}", resp); diff --git a/sdk/cosmos/examples/document_00.rs b/sdk/cosmos/examples/document_00.rs index 602554f415..482045751c 100644 --- a/sdk/cosmos/examples/document_00.rs +++ b/sdk/cosmos/examples/document_00.rs @@ -130,7 +130,9 @@ async fn main() -> Result<(), Box> { // The method create_document will return, upon success, // the document attributes. - let create_document_response = collection_client.create_document().execute(&doc).await?; + let create_document_response = collection_client + .create_document(Context::new(), &doc, CreateDocumentOptions::new()) + .await?; println!( "create_document_response == {:#?}", create_document_response diff --git a/sdk/cosmos/examples/document_entries_00.rs b/sdk/cosmos/examples/document_entries_00.rs index 52e2deaca8..755666c656 100644 --- a/sdk/cosmos/examples/document_entries_00.rs +++ b/sdk/cosmos/examples/document_entries_00.rs @@ -59,7 +59,11 @@ async fn main() -> Result<(), Box> { }; // let's add an entity. - response = Some(client.create_document().execute(&doc).await?); + response = Some( + client + .create_document(Context::new(), &doc, CreateDocumentOptions::new()) + .await?, + ); } println!("Created 5 documents."); diff --git a/sdk/cosmos/examples/document_entries_01.rs b/sdk/cosmos/examples/document_entries_01.rs index db14081726..74c01795fb 100644 --- a/sdk/cosmos/examples/document_entries_01.rs +++ b/sdk/cosmos/examples/document_entries_01.rs @@ -1,3 +1,4 @@ +use azure_core::Context; use azure_cosmos::prelude::*; use serde::{Deserialize, Serialize}; use std::borrow::Cow; @@ -49,9 +50,11 @@ async fn main() -> Result<(), Box> { // let's add an entity. let create_document_response = client - .create_document() - .is_upsert(true) - .execute(&doc) + .create_document( + Context::new(), + &doc, + CreateDocumentOptions::new().is_upsert(true), + ) .await?; println!( diff --git a/sdk/cosmos/examples/readme.rs b/sdk/cosmos/examples/readme.rs index 6959e6ffb8..c42a78058e 100644 --- a/sdk/cosmos/examples/readme.rs +++ b/sdk/cosmos/examples/readme.rs @@ -1,3 +1,4 @@ +use azure_core::Context; use serde::{Deserialize, Serialize}; // Using the prelude module of the Cosmos crate makes easier to use the Rust Azure SDK for Cosmos. use azure_cosmos::prelude::*; @@ -79,9 +80,11 @@ async fn main() -> Result<(), Box> { // insert it and store the returned session token for later use! session_token = Some( collection_client - .create_document() - .is_upsert(true) // this option will overwrite a preexisting document (if any) - .execute(&document_to_insert) + .create_document( + Context::new(), + &document_to_insert, + CreateDocumentOptions::new().is_upsert(true), + ) .await? .session_token, // get only the session token, if everything else was ok! ); diff --git a/sdk/cosmos/examples/user_permission_token.rs b/sdk/cosmos/examples/user_permission_token.rs index d987c2c786..d845efe7aa 100644 --- a/sdk/cosmos/examples/user_permission_token.rs +++ b/sdk/cosmos/examples/user_permission_token.rs @@ -115,9 +115,14 @@ async fn main() -> Result<(), Box> { .clone() .into_database_client(database_name.clone()) .into_collection_client(collection_name.clone()) - .create_document() - .is_upsert(true) - .execute_with_partition_key(&document, &"Gianluigi Bombatomica") + .create_document( + Context::new(), + &document, + CreateDocumentOptions::new() + .is_upsert(true) + .partition_key(&"Gianluigi Bombatomica") + .unwrap(), + ) .await { Ok(_) => panic!("this should not happen!"), @@ -154,9 +159,14 @@ async fn main() -> Result<(), Box> { let create_document_response = client .into_database_client(database_name) .into_collection_client(collection_name) - .create_document() - .is_upsert(true) - .execute_with_partition_key(&document, &"Gianluigi Bombatomica") + .create_document( + Context::new(), + &document, + CreateDocumentOptions::new() + .is_upsert(true) + .partition_key(&"Gianluigi Bombatomica") + .unwrap(), + ) .await?; println!( "create_document_response == {:#?}", diff --git a/sdk/cosmos/src/clients/collection_client.rs b/sdk/cosmos/src/clients/collection_client.rs index 75268e8e02..9291b186b6 100644 --- a/sdk/cosmos/src/clients/collection_client.rs +++ b/sdk/cosmos/src/clients/collection_client.rs @@ -1,9 +1,13 @@ use super::{DatabaseClient, UserDefinedFunctionClient}; +use crate::authorization_policy::CosmosContext; use crate::clients::*; +use crate::operations::*; use crate::requests; use crate::resources::ResourceType; +use crate::CosmosEntity; use crate::ReadonlyString; -use azure_core::HttpClient; +use azure_core::PipelineContext; +use azure_core::{pipeline::Pipeline, Context, HttpClient, Request}; use serde::Serialize; /// A client for Cosmos collection resources. @@ -60,8 +64,24 @@ impl CollectionClient { } /// create a document in a collection - pub fn create_document(&self) -> requests::CreateDocumentBuilder<'_, '_> { - requests::CreateDocumentBuilder::new(self) + pub async fn create_document<'a, D: Serialize + CosmosEntity<'a>>( + &self, + ctx: Context, + document: &'a D, + options: CreateDocumentOptions<'_>, + ) -> Result { + let mut request = self.prepare_doc_request_pipeline(http::Method::POST); + let mut pipeline_context = PipelineContext::new(ctx, ResourceType::Documents.into()); + + options.decorate_request(&mut request, document)?; + let response = self + .pipeline() + .send(&mut pipeline_context, &mut request) + .await? + .validate(http::StatusCode::CREATED) + .await?; + + Ok(CreateDocumentResponse::try_from(response).await?) } /// query documents in a collection @@ -137,4 +157,18 @@ impl CollectionClient { pub(crate) fn http_client(&self) -> &dyn HttpClient { self.cosmos_client().http_client() } + + pub(crate) fn pipeline(&self) -> &Pipeline { + self.cosmos_client().pipeline() + } + + fn prepare_doc_request_pipeline(&self, http_method: http::Method) -> Request { + let path = &format!( + "dbs/{}/colls/{}/docs", + self.database_client().database_name(), + self.collection_name() + ); + self.cosmos_client() + .prepare_request_pipeline(&path, http_method) + } } diff --git a/sdk/cosmos/src/consistency_level.rs b/sdk/cosmos/src/consistency_level.rs index be15965001..a5aa759810 100644 --- a/sdk/cosmos/src/consistency_level.rs +++ b/sdk/cosmos/src/consistency_level.rs @@ -1,5 +1,5 @@ use crate::headers; -use crate::operations::CreateUserResponse; +use crate::operations::*; use crate::responses::*; use azure_core::AddAsHeader; use http::request; diff --git a/sdk/cosmos/src/cosmos_entity.rs b/sdk/cosmos/src/cosmos_entity.rs index 0f8fe604d3..71f85ff329 100644 --- a/sdk/cosmos/src/cosmos_entity.rs +++ b/sdk/cosmos/src/cosmos_entity.rs @@ -1,4 +1,5 @@ use crate::headers; +use azure_core::Request as HttpRequest; use http::request::Builder; use serde::Serialize; @@ -11,6 +12,13 @@ pub trait CosmosEntity<'a> { fn partition_key(&'a self) -> Self::Entity; } +impl<'a> CosmosEntity<'a> for serde_json::Value { + type Entity = &'a Self; + fn partition_key(&'a self) -> Self::Entity { + self + } +} + /// Serialize the partition key in the format CosmosDB expects. pub(crate) fn serialize_partition_key(pk: &PK) -> Result { // this must be serialized as an array even tough CosmosDB supports only a sigle @@ -18,20 +26,6 @@ pub(crate) fn serialize_partition_key(pk: &PK) -> Result>( - pk: &'a P, - builder: Builder, -) -> Result { - Ok(builder.header( - headers::HEADER_DOCUMENTDB_PARTITIONKEY, - &serialize_partition_key(&pk.partition_key())?, - )) -} - pub(crate) fn add_as_partition_key_header_serialized( partition_key_serialized: &str, builder: Builder, @@ -41,3 +35,13 @@ pub(crate) fn add_as_partition_key_header_serialized( partition_key_serialized, ) } + +pub(crate) fn add_as_partition_key_header_serialized2( + partition_key_serialized: &str, + request: &mut HttpRequest, +) { + request.headers_mut().insert( + headers::HEADER_DOCUMENTDB_PARTITIONKEY, + http::header::HeaderValue::from_str(partition_key_serialized).unwrap(), + ); +} diff --git a/sdk/cosmos/src/lib.rs b/sdk/cosmos/src/lib.rs index 7c8f73d7e2..17f6144e7a 100644 --- a/sdk/cosmos/src/lib.rs +++ b/sdk/cosmos/src/lib.rs @@ -10,6 +10,7 @@ should also be possible with this crate. ```no_run // Using the prelude module of the Cosmos crate makes easier to use the Rust Azure SDK for Cosmos DB. use azure_cosmos::prelude::*; +use azure_core::Context; use serde::{Deserialize, Serialize}; use std::error::Error; @@ -75,9 +76,11 @@ async fn main() -> Result<(), Box> { // insert it collection_client - .create_document() - .is_upsert(true) // this option will overwrite a preexisting document (if any) - .execute(&document_to_insert) + .create_document( + Context::new(), + &document_to_insert, + CreateDocumentOptions::new().is_upsert(true), + ) .await?; } // wow that was easy and fast, wasn't it? :) diff --git a/sdk/cosmos/src/operations/create_document.rs b/sdk/cosmos/src/operations/create_document.rs new file mode 100644 index 0000000000..00ea4c3d7a --- /dev/null +++ b/sdk/cosmos/src/operations/create_document.rs @@ -0,0 +1,147 @@ +use crate::cosmos_entity::{add_as_partition_key_header_serialized2, serialize_partition_key}; +use crate::headers::from_headers::*; +use crate::prelude::*; +use crate::resources::document::DocumentAttributes; +use crate::ResourceQuota; +use azure_core::headers::{etag_from_headers, session_token_from_headers}; +use azure_core::prelude::*; +use chrono::{DateTime, Utc}; +use http::StatusCode; +use serde::Serialize; +use std::convert::TryFrom; + +use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse}; + +#[derive(Debug, Clone)] +pub struct CreateDocumentOptions<'a> { + is_upsert: IsUpsert, + indexing_directive: IndexingDirective, + if_match_condition: Option>, + if_modified_since: Option>, + consistency_level: Option, + allow_tentative_writes: TenativeWritesAllowance, + partition_key: Option, +} + +impl<'a> CreateDocumentOptions<'a> { + pub fn new() -> Self { + Self { + is_upsert: IsUpsert::No, + indexing_directive: IndexingDirective::Default, + if_match_condition: None, + if_modified_since: None, + consistency_level: None, + allow_tentative_writes: TenativeWritesAllowance::Deny, + partition_key: None, + } + } + + setters! { + consistency_level: ConsistencyLevel => Some(consistency_level), + if_match_condition: IfMatchCondition<'a> => Some(if_match_condition), + if_modified_since: &'a DateTime => Some(IfModifiedSince::new(if_modified_since)), + allow_tentative_writes: TenativeWritesAllowance, + is_upsert: bool => if is_upsert { IsUpsert::Yes } else { IsUpsert::No }, + indexing_directive: IndexingDirective, + } + + pub fn partition_key( + mut self, + partition_key: &PK, + ) -> Result { + self.partition_key = Some(serialize_partition_key(partition_key)?); + Ok(self) + } + + pub(crate) fn decorate_request<'b, DOC>( + &self, + req: &mut HttpRequest, + document: &'b DOC, + ) -> Result<(), crate::Error> + where + DOC: Serialize + CosmosEntity<'b>, + { + let serialized = serde_json::to_string(document)?; + let partition_key = self + .partition_key + .clone() + .unwrap_or_else(|| serialize_partition_key(&document.partition_key()).unwrap()); + + add_as_partition_key_header_serialized2(&partition_key, req); + azure_core::headers::add_optional_header2(&self.if_match_condition, req)?; + azure_core::headers::add_optional_header2(&self.if_modified_since, req)?; + azure_core::headers::add_optional_header2(&self.consistency_level, req)?; + azure_core::headers::add_mandatory_header2(&self.is_upsert, req)?; + azure_core::headers::add_mandatory_header2(&self.indexing_directive, req)?; + azure_core::headers::add_mandatory_header2(&self.allow_tentative_writes, req)?; + + req.set_body(bytes::Bytes::from(serialized).into()); + Ok(()) + } +} + +#[derive(Debug, Clone)] +pub struct CreateDocumentResponse { + pub document_attributes: DocumentAttributes, + pub is_update: bool, + pub last_state_change: DateTime, + pub etag: String, + pub resource_quota: Vec, + pub resource_usage: Vec, + pub lsn: u64, + 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: u64, + pub session_token: String, + pub charge: f64, + pub service_version: String, + pub activity_id: uuid::Uuid, + pub gateway_version: String, + pub date: DateTime, +} + +impl CreateDocumentResponse { + pub async fn try_from(response: HttpResponse) -> Result { + let (status_code, headers, pinned_stream) = response.deconstruct(); + let body = collect_pinned_stream(pinned_stream).await?; + + Ok(CreateDocumentResponse { + is_update: status_code == StatusCode::OK, + + last_state_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)?, + 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(&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)?, + + document_attributes: DocumentAttributes::try_from(body)?, + }) + } +} diff --git a/sdk/cosmos/src/operations/mod.rs b/sdk/cosmos/src/operations/mod.rs index 75cee1d409..93704b4500 100644 --- a/sdk/cosmos/src/operations/mod.rs +++ b/sdk/cosmos/src/operations/mod.rs @@ -4,6 +4,7 @@ mod create_collection; mod create_database; +mod create_document; mod create_user; mod get_database; mod get_user; @@ -11,6 +12,7 @@ mod replace_user; pub use create_collection::*; pub use create_database::*; +pub use create_document::*; pub use create_user::*; pub use get_database::*; pub use get_user::*; diff --git a/sdk/cosmos/src/requests/create_document_builder.rs b/sdk/cosmos/src/requests/create_document_builder.rs deleted file mode 100644 index 8874f204da..0000000000 --- a/sdk/cosmos/src/requests/create_document_builder.rs +++ /dev/null @@ -1,139 +0,0 @@ -use crate::cosmos_entity::{ - add_as_partition_key_header, add_as_partition_key_header_serialized, serialize_partition_key, -}; -use crate::prelude::*; -use crate::resources::ResourceType; -use crate::responses::CreateDocumentResponse; -use azure_core::prelude::*; -use azure_core::HttpError; -use chrono::{DateTime, Utc}; -use http::StatusCode; -use serde::Serialize; -use std::convert::TryFrom; - -#[derive(Debug, Clone)] -pub struct CreateDocumentBuilder<'a, 'b> { - collection_client: &'a CollectionClient, - is_upsert: IsUpsert, - indexing_directive: IndexingDirective, - if_match_condition: Option>, - if_modified_since: Option>, - user_agent: Option>, - activity_id: Option>, - consistency_level: Option, - allow_tentative_writes: TenativeWritesAllowance, -} - -impl<'a, 'b> CreateDocumentBuilder<'a, 'b> { - pub(crate) fn new(collection_client: &'a CollectionClient) -> Self { - Self { - collection_client, - is_upsert: IsUpsert::No, - indexing_directive: IndexingDirective::Default, - if_match_condition: None, - if_modified_since: None, - user_agent: None, - activity_id: None, - consistency_level: None, - allow_tentative_writes: TenativeWritesAllowance::Deny, - } - } -} - -impl<'a, 'b> CreateDocumentBuilder<'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<'b> => Some(if_match_condition), - if_modified_since: &'b DateTime => Some(IfModifiedSince::new(if_modified_since)), - allow_tentative_writes: TenativeWritesAllowance, - is_upsert: bool => if is_upsert { IsUpsert::Yes } else { IsUpsert::No }, - indexing_directive: IndexingDirective, - } -} - -impl<'a, 'b, 'c> CreateDocumentBuilder<'a, 'b> { - async fn perform_execute( - &self, - document: &'c DOC, - fn_add_primary_key: FNPK, - ) -> Result - where - DOC: Serialize, - FNPK: FnOnce(http::request::Builder) -> Result, - { - let mut req = self.collection_client.cosmos_client().prepare_request( - &format!( - "dbs/{}/colls/{}/docs", - self.collection_client.database_client().database_name(), - self.collection_client.collection_name() - ), - http::Method::POST, - ResourceType::Documents, - ); - - req = fn_add_primary_key(req)?; - - req = azure_core::headers::add_optional_header(&self.if_match_condition, req); - req = azure_core::headers::add_optional_header(&self.if_modified_since, 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 = azure_core::headers::add_mandatory_header(&self.is_upsert, req); - req = azure_core::headers::add_mandatory_header(&self.indexing_directive, req); - req = azure_core::headers::add_mandatory_header(&self.allow_tentative_writes, req); - - let serialized = azure_core::to_json(document)?; - let req = req.body(serialized)?; - - let response = self - .collection_client - .http_client() - .execute_request(req) - .await?; - - const NON_UTF8_BODY: &'static str = ""; - if self.is_upsert == IsUpsert::No && response.status() != StatusCode::CREATED { - return Err(HttpError::new_unexpected_status_code( - StatusCode::CREATED, - response.status(), - std::str::from_utf8(response.body()).unwrap_or_else(|_| NON_UTF8_BODY), - ) - .into()); - } else if response.status() != StatusCode::CREATED && response.status() != StatusCode::OK { - return Err(HttpError::new_multiple_unexpected_status_code( - vec![StatusCode::CREATED, StatusCode::OK], - response.status(), - std::str::from_utf8(response.body()).unwrap_or_else(|_| NON_UTF8_BODY), - ) - .into()); - } - - CreateDocumentResponse::try_from(response) - } - - pub async fn execute_with_partition_key( - &self, - document: &'c DOC, - partition_key: &PK, - ) -> Result { - self.perform_execute(document, |req| { - Ok(add_as_partition_key_header_serialized( - &serialize_partition_key(partition_key)?, - req, - )) - }) - .await - } - - pub async fn execute>( - &self, - document: &'c T, - ) -> Result { - self.perform_execute(document, |req| { - Ok(add_as_partition_key_header(document, req)?) - }) - .await - } -} diff --git a/sdk/cosmos/src/requests/mod.rs b/sdk/cosmos/src/requests/mod.rs index f69ab4b164..671bf43199 100644 --- a/sdk/cosmos/src/requests/mod.rs +++ b/sdk/cosmos/src/requests/mod.rs @@ -6,7 +6,6 @@ #![allow(missing_docs)] -mod create_document_builder; mod create_or_replace_trigger_builder; mod create_or_replace_user_defined_function_builder; mod create_permission_builder; @@ -45,7 +44,6 @@ mod replace_reference_attachment_builder; mod replace_slug_attachment_builder; mod replace_stored_procedure_builder; -pub use create_document_builder::CreateDocumentBuilder; pub use create_or_replace_trigger_builder::CreateOrReplaceTriggerBuilder; pub use create_or_replace_user_defined_function_builder::CreateOrReplaceUserDefinedFunctionBuilder; pub use create_permission_builder::CreatePermissionBuilder; diff --git a/sdk/cosmos/src/resources/document/document_attributes.rs b/sdk/cosmos/src/resources/document/document_attributes.rs index b97d44b267..714910a398 100644 --- a/sdk/cosmos/src/resources/document/document_attributes.rs +++ b/sdk/cosmos/src/resources/document/document_attributes.rs @@ -51,6 +51,14 @@ impl std::convert::TryFrom> for DocumentAttributes { } } +impl std::convert::TryFrom for DocumentAttributes { + type Error = crate::Error; + + fn try_from(body: bytes::Bytes) -> Result { + Ok(serde_json::from_slice(&body)?) + } +} + impl<'a> std::convert::From<&'a DocumentAttributes> for IfMatchCondition<'a> { fn from(document_attributes: &'a DocumentAttributes) -> Self { IfMatchCondition::Match(&document_attributes.etag) diff --git a/sdk/cosmos/src/responses/create_document_response.rs b/sdk/cosmos/src/responses/create_document_response.rs deleted file mode 100644 index c95b723ea2..0000000000 --- a/sdk/cosmos/src/responses/create_document_response.rs +++ /dev/null @@ -1,80 +0,0 @@ -use crate::headers::from_headers::*; -use crate::resources::document::DocumentAttributes; -use crate::ResourceQuota; -use azure_core::headers::{etag_from_headers, session_token_from_headers}; -use chrono::{DateTime, Utc}; -use http::response::Response; -use http::StatusCode; - -#[derive(Debug, Clone)] -pub struct CreateDocumentResponse { - pub document_attributes: DocumentAttributes, - pub is_update: bool, - pub last_state_change: DateTime, - pub etag: String, - pub resource_quota: Vec, - pub resource_usage: Vec, - pub lsn: u64, - 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: u64, - pub session_token: String, - pub charge: f64, - pub service_version: String, - pub activity_id: uuid::Uuid, - pub gateway_version: String, - pub date: DateTime, -} - -impl std::convert::TryFrom> for CreateDocumentResponse { - type Error = crate::Error; - - fn try_from(response: Response) -> Result { - let status_code = response.status(); - let headers = response.headers(); - let body = response.body(); - - debug!("status_code == {:#?}", status_code); - debug!("headers == {:#?}", headers); - debug!("body == {:#?}", std::str::from_utf8(body)); - - Ok(CreateDocumentResponse { - is_update: status_code == StatusCode::OK, - - last_state_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)?, - 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(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)?, - - document_attributes: DocumentAttributes::try_from(response)?, - }) - } -} diff --git a/sdk/cosmos/src/responses/mod.rs b/sdk/cosmos/src/responses/mod.rs index b93f547df9..c590df3e61 100644 --- a/sdk/cosmos/src/responses/mod.rs +++ b/sdk/cosmos/src/responses/mod.rs @@ -3,7 +3,6 @@ #![allow(missing_docs)] mod create_collection_response; -mod create_document_response; mod create_permission_response; mod create_reference_attachment_response; mod create_slug_attachment_response; @@ -41,7 +40,6 @@ mod replace_reference_attachment_response; mod replace_stored_procedure_response; pub use create_collection_response::CreateCollectionResponse; -pub use create_document_response::CreateDocumentResponse; pub use create_permission_response::CreatePermissionResponse; pub use create_reference_attachment_response::CreateReferenceAttachmentResponse; pub use create_slug_attachment_response::CreateSlugAttachmentResponse; diff --git a/sdk/cosmos/tests/attachment_00.rs b/sdk/cosmos/tests/attachment_00.rs index a78c4315bb..79677f97ec 100644 --- a/sdk/cosmos/tests/attachment_00.rs +++ b/sdk/cosmos/tests/attachment_00.rs @@ -1,5 +1,5 @@ #![cfg(all(test, feature = "test_e2e"))] -use azure_core::prelude::*; +use azure_core::Context; use azure_cosmos::prelude::*; use serde::{Deserialize, Serialize}; use std::borrow::Cow; @@ -91,8 +91,7 @@ async fn attachment() -> Result<(), azure_cosmos::Error> { // let's add an entity. let session_token: ConsistencyLevel = collection_client - .create_document() - .execute(&doc) + .create_document(Context::new(), &doc, CreateDocumentOptions::new()) .await? .into(); diff --git a/sdk/cosmos/tests/cosmos_document.rs b/sdk/cosmos/tests/cosmos_document.rs index 7694643da2..f4f5b7c095 100644 --- a/sdk/cosmos/tests/cosmos_document.rs +++ b/sdk/cosmos/tests/cosmos_document.rs @@ -1,4 +1,6 @@ #![cfg(all(test, feature = "test_e2e"))] +use azure_core::Context; +use azure_cosmos::prelude::CreateDocumentOptions; use serde::{Deserialize, Serialize}; mod setup; @@ -67,8 +69,7 @@ async fn create_and_delete_document() { hello: 42, }; collection_client - .create_document() - .execute(&document_data) + .create_document(Context::new(), &document_data, CreateDocumentOptions::new()) .await .unwrap(); @@ -156,8 +157,7 @@ async fn query_documents() { hello: 42, }; collection_client - .create_document() - .execute(&document_data) + .create_document(Context::new(), &document_data, CreateDocumentOptions::new()) .await .unwrap(); @@ -231,8 +231,7 @@ async fn replace_document() { hello: 42, }; collection_client - .create_document() - .execute(&document_data) + .create_document(Context::new(), &document_data, CreateDocumentOptions::new()) .await .unwrap(); diff --git a/sdk/cosmos/tests/permission_token_usage.rs b/sdk/cosmos/tests/permission_token_usage.rs index c0c239fe9d..c36ad85542 100644 --- a/sdk/cosmos/tests/permission_token_usage.rs +++ b/sdk/cosmos/tests/permission_token_usage.rs @@ -106,9 +106,11 @@ async fn permission_token_usage() { }; new_collection_client - .create_document() - .is_upsert(true) - .execute(&document) + .create_document( + Context::new(), + &document, + CreateDocumentOptions::new().is_upsert(true), + ) .await .unwrap_err(); @@ -138,9 +140,11 @@ async fn permission_token_usage() { // now we have an "All" authorization_token // so the create_document should succeed! let create_document_response = new_collection_client - .create_document() - .is_upsert(true) - .execute(&document) + .create_document( + Context::new(), + &document, + CreateDocumentOptions::new().is_upsert(true), + ) .await .unwrap(); println!(