Skip to content

Commit e914a0f

Browse files
authored
Operation Builder Future (#510)
* Convert create_database to a builder pattern * Inline the future * Fix changes with pipeline * Fix clippy error * Fix test
1 parent 0c724e3 commit e914a0f

16 files changed

+74
-115
lines changed

sdk/core/src/macros.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/// Creates setter methods
22
///
3-
/// The methods created are of the form `with_$name` that takes an argument of type `$typ`
3+
/// The methods created are of the form `$name` that takes an argument of type `$typ`
44
/// and sets the field $name to result of calling `$transform` with the value of the argument.
55
///
66
/// In other words. The following macro call:

sdk/core/src/options.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,14 @@ use std::time::Duration;
1717
/// ```
1818
#[derive(Clone, Debug, Default)]
1919
pub struct ClientOptions {
20-
// TODO: Expose transport override.
2120
/// Policies called per call.
2221
pub(crate) per_call_policies: Vec<Arc<dyn Policy>>,
23-
2422
/// Policies called per retry.
2523
pub(crate) per_retry_policies: Vec<Arc<dyn Policy>>,
26-
2724
/// Retry options.
2825
pub(crate) retry: RetryOptions,
29-
3026
/// Telemetry options.
3127
pub(crate) telemetry: TelemetryOptions,
32-
3328
/// Transport options.
3429
pub(crate) transport: TransportOptions,
3530
}

sdk/cosmos/examples/cancellation.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use azure_core::prelude::*;
21
use azure_cosmos::prelude::*;
32
use stop_token::prelude::*;
43
use stop_token::StopSource;
@@ -19,8 +18,7 @@ async fn main() -> azure_cosmos::Result<()> {
1918
let client = CosmosClient::new(account.clone(), authorization_token.clone(), options);
2019

2120
// Create a new database, and time out if it takes more than 1 second.
22-
let options = CreateDatabaseOptions::new();
23-
let future = client.create_database(Context::new(), "my_database", options);
21+
let future = client.create_database("my_database").into_future();
2422
let deadline = Instant::now() + Duration::from_secs(1);
2523
match future.until(deadline).await {
2624
Ok(Ok(r)) => println!("successful response: {:?}", r),
@@ -36,8 +34,7 @@ async fn main() -> azure_cosmos::Result<()> {
3634
// Clone the stop token for each request.
3735
let stop = source.token();
3836
tokio::spawn(async move {
39-
let options = CreateDatabaseOptions::new();
40-
let future = client.create_database(Context::new(), "my_database", options);
37+
let future = client.create_database("my_database").into_future();
4138
match future.until(stop).await {
4239
Ok(Ok(r)) => println!("successful response: {:?}", r),
4340
Ok(Err(e)) => println!("request was made but failed: {:?}", e),

sdk/cosmos/src/clients/cosmos_client.rs

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -169,21 +169,8 @@ impl CosmosClient {
169169
}
170170

171171
/// Create a database
172-
pub async fn create_database<S: AsRef<str>>(
173-
&self,
174-
ctx: Context,
175-
database_name: S,
176-
options: CreateDatabaseOptions,
177-
) -> crate::Result<CreateDatabaseResponse> {
178-
let mut request = self.prepare_request_pipeline("dbs", http::Method::POST);
179-
180-
options.decorate_request(&mut request, database_name.as_ref())?;
181-
let response = self
182-
.pipeline()
183-
.send(ctx.clone().insert(ResourceType::Databases), &mut request)
184-
.await?;
185-
186-
Ok(CreateDatabaseResponse::try_from(response).await?)
172+
pub fn create_database<S: AsRef<str>>(&self, database_name: S) -> CreateDatabaseBuilder {
173+
CreateDatabaseBuilder::new(self.clone(), database_name.as_ref().to_owned())
187174
}
188175

189176
/// List all databases

sdk/cosmos/src/operations/create_database.rs

Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,68 @@ use crate::prelude::*;
33
use crate::resources::Database;
44
use crate::ResourceQuota;
55
use azure_core::headers::{etag_from_headers, session_token_from_headers};
6-
use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse};
6+
use azure_core::{collect_pinned_stream, Context, Response as HttpResponse};
77
use chrono::{DateTime, Utc};
88

99
#[derive(Debug, Clone)]
10-
pub struct CreateDatabaseOptions {
10+
pub struct CreateDatabaseBuilder {
11+
client: CosmosClient,
12+
database_name: String,
1113
consistency_level: Option<ConsistencyLevel>,
14+
context: Context,
1215
}
1316

14-
impl CreateDatabaseOptions {
15-
pub fn new() -> Self {
17+
impl CreateDatabaseBuilder {
18+
pub(crate) fn new(client: CosmosClient, database_name: String) -> Self {
1619
Self {
20+
client,
21+
database_name,
1722
consistency_level: None,
23+
context: Context::new(),
1824
}
1925
}
2026

2127
setters! {
2228
consistency_level: ConsistencyLevel => Some(consistency_level),
29+
context: Context => context,
2330
}
24-
}
2531

26-
impl CreateDatabaseOptions {
27-
pub(crate) fn decorate_request(
28-
&self,
29-
request: &mut HttpRequest,
30-
database_name: &str,
31-
) -> crate::Result<()> {
32-
#[derive(Serialize)]
33-
struct CreateDatabaseRequest<'a> {
34-
pub id: &'a str,
35-
}
36-
let req = CreateDatabaseRequest { id: database_name };
32+
pub fn insert<E: Send + Sync + 'static>(&mut self, entity: E) -> &mut Self {
33+
self.context.insert(entity);
34+
self
35+
}
36+
37+
pub fn into_future(mut self) -> CreateDatabase {
38+
Box::pin(async move {
39+
let mut request = self
40+
.client
41+
.prepare_request_pipeline("dbs", http::Method::POST);
42+
43+
let body = CreateDatabaseBody {
44+
id: self.database_name.as_str(),
45+
};
3746

38-
azure_core::headers::add_optional_header2(&self.consistency_level, request)?;
39-
request.set_body(bytes::Bytes::from(serde_json::to_string(&req)?).into());
40-
Ok(())
47+
azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?;
48+
request.set_body(bytes::Bytes::from(serde_json::to_string(&body)?).into());
49+
let response = self
50+
.client
51+
.pipeline()
52+
.send(self.context.insert(ResourceType::Databases), &mut request)
53+
.await?;
54+
55+
CreateDatabaseResponse::try_from(response).await
56+
})
4157
}
4258
}
4359

60+
/// A future of a create database response
61+
type CreateDatabase = futures::future::BoxFuture<'static, crate::Result<CreateDatabaseResponse>>;
62+
63+
#[derive(Serialize)]
64+
struct CreateDatabaseBody<'a> {
65+
pub id: &'a str,
66+
}
67+
4468
#[derive(Debug, Clone, PartialEq, PartialOrd)]
4569
pub struct CreateDatabaseResponse {
4670
pub database: Database,

sdk/cosmos/tests/attachment_00.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,8 @@ async fn attachment() -> Result<(), azure_cosmos::Error> {
3737

3838
// create a temp database
3939
let _create_database_response = client
40-
.create_database(
41-
azure_core::Context::new(),
42-
DATABASE_NAME,
43-
CreateDatabaseOptions::new(),
44-
)
40+
.create_database(DATABASE_NAME)
41+
.into_future()
4542
.await
4643
.unwrap();
4744

sdk/cosmos/tests/collection_operations.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ async fn collection_operations() -> Result<(), BoxedError> {
1717
let database_name = "test-collection-operations";
1818
let context = Context::new();
1919

20-
client
21-
.create_database(context.clone(), database_name, CreateDatabaseOptions::new())
22-
.await?;
20+
client.create_database(database_name).into_future().await?;
2321

2422
// create collection!
2523
let db_client = client.clone().into_database_client(database_name.clone());

sdk/cosmos/tests/cosmos_collection.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,8 @@ async fn create_and_delete_collection() {
1414
let client = setup::initialize().unwrap();
1515

1616
client
17-
.create_database(
18-
azure_core::Context::new(),
19-
DATABASE_NAME,
20-
CreateDatabaseOptions::new(),
21-
)
17+
.create_database(DATABASE_NAME)
18+
.into_future()
2219
.await
2320
.unwrap();
2421

@@ -85,11 +82,8 @@ async fn replace_collection() {
8582
const COLLECTION_NAME: &str = "test-collection";
8683

8784
client
88-
.create_database(
89-
azure_core::Context::new(),
90-
DATABASE_NAME,
91-
CreateDatabaseOptions::new(),
92-
)
85+
.create_database(DATABASE_NAME)
86+
.into_future()
9387
.await
9488
.unwrap();
9589

sdk/cosmos/tests/cosmos_database.rs.disabled

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,8 @@ async fn create_and_delete_database() {
2222

2323
// create a new database and check if the number of DBs increased
2424
let database = client
25-
.create_database(
26-
azure_core::Context::new(),
27-
DATABASE_NAME,
28-
CreateDatabaseOptions::new(),
29-
)
25+
.create_database(DATABASE_NAME)
26+
.into_future()
3027
.await
3128
.unwrap();
3229

sdk/cosmos/tests/cosmos_document.rs

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,8 @@ async fn create_and_delete_document() {
3232
let client = setup::initialize().unwrap();
3333

3434
client
35-
.create_database(
36-
azure_core::Context::new(),
37-
DATABASE_NAME,
38-
CreateDatabaseOptions::new(),
39-
)
35+
.create_database(DATABASE_NAME)
36+
.into_future()
4037
.await
4138
.unwrap();
4239

@@ -126,11 +123,8 @@ async fn query_documents() {
126123
let client = setup::initialize().unwrap();
127124

128125
client
129-
.create_database(
130-
azure_core::Context::new(),
131-
DATABASE_NAME,
132-
CreateDatabaseOptions::new(),
133-
)
126+
.create_database(DATABASE_NAME)
127+
.into_future()
134128
.await
135129
.unwrap();
136130
let database_client = client.into_database_client(DATABASE_NAME);
@@ -203,11 +197,8 @@ async fn replace_document() {
203197
let client = setup::initialize().unwrap();
204198

205199
client
206-
.create_database(
207-
azure_core::Context::new(),
208-
DATABASE_NAME,
209-
CreateDatabaseOptions::new(),
210-
)
200+
.create_database(DATABASE_NAME)
201+
.into_future()
211202
.await
212203
.unwrap();
213204
let database_client = client.into_database_client(DATABASE_NAME);

sdk/cosmos/tests/create_database_and_collection.rs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,7 @@ async fn create_database_and_collection() -> Result<(), BoxedError> {
1919

2020
// create database!
2121
log::info!("Creating a database with name '{}'...", database_name);
22-
let db = client
23-
.create_database(
24-
context.clone(),
25-
&database_name,
26-
CreateDatabaseOptions::new(),
27-
)
28-
.await?;
22+
let db = client.create_database(&database_name).into_future().await?;
2923
log::info!("Successfully created a database");
3024
log::debug!("The create_database response: {:#?}", db);
3125

sdk/cosmos/tests/permission.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,8 @@ async fn permissions() {
1717

1818
// create a temp database
1919
let _create_database_response = client
20-
.create_database(
21-
azure_core::Context::new(),
22-
DATABASE_NAME,
23-
CreateDatabaseOptions::new(),
24-
)
20+
.create_database(DATABASE_NAME)
21+
.into_future()
2522
.await
2623
.unwrap();
2724

sdk/cosmos/tests/permission_token_usage.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,8 @@ async fn permission_token_usage() {
3333

3434
// create a temp database
3535
let _create_database_response = client
36-
.create_database(
37-
azure_core::Context::new(),
38-
DATABASE_NAME,
39-
CreateDatabaseOptions::new(),
40-
)
36+
.create_database(DATABASE_NAME)
37+
.into_future()
4138
.await
4239
.unwrap();
4340

sdk/cosmos/tests/trigger.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,8 @@ async fn trigger() -> Result<(), azure_cosmos::Error> {
4545

4646
// create a temp database
4747
let _create_database_response = client
48-
.create_database(
49-
azure_core::Context::new(),
50-
DATABASE_NAME,
51-
CreateDatabaseOptions::new(),
52-
)
48+
.create_database(DATABASE_NAME)
49+
.into_future()
5350
.await
5451
.unwrap();
5552

sdk/cosmos/tests/user.rs.disabled

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,8 @@ async fn users() {
1818

1919
// create a temp database
2020
let _create_database_response = client
21-
.create_database(
22-
azure_core::Context::new(),
23-
DATABASE_NAME,
24-
CreateDatabaseOptions::new(),
25-
)
21+
.create_database(DATABASE_NAME)
22+
.into_future()
2623
.await
2724
.unwrap();
2825

sdk/cosmos/tests/user_defined_function00.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,8 @@ async fn user_defined_function00() -> Result<(), azure_cosmos::Error> {
2828

2929
// create a temp database
3030
let _create_database_response = client
31-
.create_database(
32-
azure_core::Context::new(),
33-
DATABASE_NAME,
34-
CreateDatabaseOptions::new(),
35-
)
31+
.create_database(DATABASE_NAME)
32+
.into_future()
3633
.await
3734
.unwrap();
3835

0 commit comments

Comments
 (0)