azure-lite-rs 0.1.1

Lightweight HTTP client for Azure APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Azure CosmosDB API client.
//!
//! Wraps the ARM management plane operations for Azure CosmosDB: database
//! accounts, SQL databases, and SQL containers. All URL construction is in
//! `ops::cosmosdb::CosmosdbOps`. `subscription_id` is auto-injected from the
//! parent `AzureHttpClient`.

use crate::{
    AzureHttpClient, Result,
    ops::cosmosdb::CosmosdbOps,
    types::cosmosdb::{
        DatabaseAccount, DatabaseAccountCreateRequest, DatabaseAccountListResult,
        SqlContainerGetResults, SqlContainerListResult, SqlDatabaseCreateRequest,
        SqlDatabaseGetResults, SqlDatabaseListResult,
    },
};

/// Client for the Azure CosmosDB ARM management plane.
///
/// Wraps [`CosmosdbOps`] with ergonomic signatures that auto-inject
/// `subscription_id` from the parent [`AzureHttpClient`].
pub struct CosmosDbClient<'a> {
    ops: CosmosdbOps<'a>,
    client: &'a AzureHttpClient,
}

impl<'a> CosmosDbClient<'a> {
    /// Create a new Azure CosmosDB API client.
    pub(crate) fn new(client: &'a AzureHttpClient) -> Self {
        Self {
            ops: CosmosdbOps::new(client),
            client,
        }
    }

    // --- Account operations ---

    /// Lists all the Azure Cosmos DB database accounts available under the subscription.
    pub async fn list_accounts(&self) -> Result<DatabaseAccountListResult> {
        self.ops.list_accounts(self.client.subscription_id()).await
    }

    /// Retrieves the properties of an existing Azure Cosmos DB database account.
    pub async fn get_account(
        &self,
        resource_group_name: &str,
        account_name: &str,
    ) -> Result<DatabaseAccount> {
        self.ops
            .get_account(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
            )
            .await
    }

    /// Creates or updates an Azure Cosmos DB database account.
    pub async fn create_account(
        &self,
        resource_group_name: &str,
        account_name: &str,
        body: &DatabaseAccountCreateRequest,
    ) -> Result<DatabaseAccount> {
        self.ops
            .create_account(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
                body,
            )
            .await
    }

    /// Deletes an existing Azure Cosmos DB database account.
    pub async fn delete_account(
        &self,
        resource_group_name: &str,
        account_name: &str,
    ) -> Result<()> {
        self.ops
            .delete_account(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
            )
            .await
    }

    // --- SQL Database operations ---

    /// Lists the SQL databases under an existing Azure Cosmos DB database account.
    pub async fn list_sql_databases(
        &self,
        resource_group_name: &str,
        account_name: &str,
    ) -> Result<SqlDatabaseListResult> {
        self.ops
            .list_sql_databases(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
            )
            .await
    }

    /// Gets the SQL database under an existing Azure Cosmos DB database account.
    pub async fn get_sql_database(
        &self,
        resource_group_name: &str,
        account_name: &str,
        database_name: &str,
    ) -> Result<SqlDatabaseGetResults> {
        self.ops
            .get_sql_database(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
                database_name,
            )
            .await
    }

    /// Creates or updates an Azure Cosmos DB SQL database.
    pub async fn create_sql_database(
        &self,
        resource_group_name: &str,
        account_name: &str,
        database_name: &str,
        body: &SqlDatabaseCreateRequest,
    ) -> Result<SqlDatabaseGetResults> {
        self.ops
            .create_sql_database(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
                database_name,
                body,
            )
            .await
    }

    // --- SQL Container operations ---

    /// Lists the SQL containers under an existing Azure Cosmos DB SQL database.
    pub async fn list_sql_containers(
        &self,
        resource_group_name: &str,
        account_name: &str,
        database_name: &str,
    ) -> Result<SqlContainerListResult> {
        self.ops
            .list_sql_containers(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
                database_name,
            )
            .await
    }

    /// Gets the SQL container under an existing Azure Cosmos DB SQL database.
    pub async fn get_sql_container(
        &self,
        resource_group_name: &str,
        account_name: &str,
        database_name: &str,
        container_name: &str,
    ) -> Result<SqlContainerGetResults> {
        self.ops
            .get_sql_container(
                self.client.subscription_id(),
                resource_group_name,
                account_name,
                database_name,
                container_name,
            )
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        MockClient,
        types::cosmosdb::{
            ConsistencyPolicy, DatabaseAccountCreateUpdateProperties,
            SqlDatabaseCreateUpdateProperties, SqlDatabaseResource,
        },
    };

    const SUB_ID: &str = "test-subscription-id";
    const RG: &str = "test-rg";
    const ACCOUNT: &str = "cloud-lite-test-cosmos";
    const DATABASE: &str = "cloud-lite-test-db";
    const CONTAINER: &str = "cloud-lite-test-container";

    fn make_client(mock: MockClient) -> AzureHttpClient {
        AzureHttpClient::from_mock(mock)
    }

    fn account_json() -> serde_json::Value {
        serde_json::json!({
            "id": format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}"),
            "name": ACCOUNT,
            "type": "Microsoft.DocumentDB/databaseAccounts",
            "location": "eastus",
            "kind": "GlobalDocumentDB",
            "properties": {
                "documentEndpoint": format!("https://{ACCOUNT}.documents.azure.com:443/"),
                "provisioningState": "Succeeded",
                "databaseAccountOfferType": "Standard",
                "consistencyPolicy": {
                    "defaultConsistencyLevel": "Session",
                    "maxStalenessPrefix": 100,
                    "maxIntervalInSeconds": 5
                },
                "enableAutomaticFailover": false,
                "enableMultipleWriteLocations": false
            }
        })
    }

    fn sql_database_json() -> serde_json::Value {
        serde_json::json!({
            "id": format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}"),
            "name": DATABASE,
            "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
            "location": "eastus",
            "properties": {
                "resource": {
                    "id": DATABASE,
                    "colls": "colls/",
                    "users": "users/"
                }
            }
        })
    }

    fn sql_container_json() -> serde_json::Value {
        serde_json::json!({
            "id": format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}/containers/{CONTAINER}"),
            "name": CONTAINER,
            "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
            "location": "eastus",
            "properties": {
                "resource": {
                    "id": CONTAINER,
                    "partitionKey": {
                        "kind": "Hash",
                        "version": 2
                    }
                }
            }
        })
    }

    #[tokio::test]
    async fn list_accounts_returns_list() {
        let mut mock = MockClient::new();
        mock.expect_get(&format!(
            "/subscriptions/{SUB_ID}/providers/Microsoft.DocumentDB/databaseAccounts"
        ))
        .returning_json(serde_json::json!({ "value": [account_json()] }));
        let client = make_client(mock);
        let result = client
            .cosmosdb()
            .list_accounts()
            .await
            .expect("list_accounts failed");
        assert_eq!(result.value.len(), 1);
        let a = &result.value[0];
        assert_eq!(a.name.as_deref(), Some(ACCOUNT));
        assert_eq!(a.kind.as_deref(), Some("GlobalDocumentDB"));
    }

    #[tokio::test]
    async fn get_account_deserializes_properties() {
        let mut mock = MockClient::new();
        mock.expect_get(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}"),
        )
        .returning_json(account_json());
        let client = make_client(mock);
        let a = client
            .cosmosdb()
            .get_account(RG, ACCOUNT)
            .await
            .expect("get_account failed");
        assert_eq!(a.name.as_deref(), Some(ACCOUNT));
        let props = a.properties.as_ref().unwrap();
        assert_eq!(props.provisioning_state.as_deref(), Some("Succeeded"));
        assert_eq!(
            props.database_account_offer_type.as_deref(),
            Some("Standard")
        );
        assert!(props.document_endpoint.is_some());
        let cp = props.consistency_policy.as_ref().unwrap();
        assert_eq!(cp.default_consistency_level, "Session");
    }

    #[tokio::test]
    async fn create_account_sends_body() {
        let mut mock = MockClient::new();
        mock.expect_put(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}"),
        )
        .returning_json(account_json());
        let client = make_client(mock);
        let body = DatabaseAccountCreateRequest {
            location: "eastus".into(),
            kind: Some("GlobalDocumentDB".into()),
            properties: DatabaseAccountCreateUpdateProperties {
                database_account_offer_type: "Standard".into(),
                consistency_policy: Some(ConsistencyPolicy {
                    default_consistency_level: "Session".into(),
                    ..Default::default()
                }),
                ..Default::default()
            },
            ..Default::default()
        };
        let a = client
            .cosmosdb()
            .create_account(RG, ACCOUNT, &body)
            .await
            .expect("create_account failed");
        assert_eq!(a.name.as_deref(), Some(ACCOUNT));
    }

    #[tokio::test]
    async fn delete_account_succeeds() {
        let mut mock = MockClient::new();
        mock.expect_delete(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}"),
        )
        .returning_json(serde_json::json!({}));
        let client = make_client(mock);
        client
            .cosmosdb()
            .delete_account(RG, ACCOUNT)
            .await
            .expect("delete_account failed");
    }

    #[tokio::test]
    async fn list_sql_databases_returns_list() {
        let mut mock = MockClient::new();
        mock.expect_get(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases"),
        )
        .returning_json(serde_json::json!({ "value": [sql_database_json()] }));
        let client = make_client(mock);
        let result = client
            .cosmosdb()
            .list_sql_databases(RG, ACCOUNT)
            .await
            .expect("list_sql_databases failed");
        assert_eq!(result.value.len(), 1);
        assert_eq!(result.value[0].name.as_deref(), Some(DATABASE));
    }

    #[tokio::test]
    async fn get_sql_database_deserializes_resource() {
        let mut mock = MockClient::new();
        mock.expect_get(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}"),
        )
        .returning_json(sql_database_json());
        let client = make_client(mock);
        let db = client
            .cosmosdb()
            .get_sql_database(RG, ACCOUNT, DATABASE)
            .await
            .expect("get_sql_database failed");
        assert_eq!(db.name.as_deref(), Some(DATABASE));
        let props = db.properties.as_ref().unwrap();
        let resource = props.resource.as_ref().unwrap();
        assert_eq!(resource.id.as_deref(), Some(DATABASE));
        assert_eq!(resource.colls.as_deref(), Some("colls/"));
    }

    #[tokio::test]
    async fn create_sql_database_sends_body() {
        let mut mock = MockClient::new();
        mock.expect_put(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}"),
        )
        .returning_json(sql_database_json());
        let client = make_client(mock);
        let body = SqlDatabaseCreateRequest {
            location: "eastus".into(),
            properties: SqlDatabaseCreateUpdateProperties {
                resource: SqlDatabaseResource {
                    id: DATABASE.into(),
                },
            },
            ..Default::default()
        };
        let db = client
            .cosmosdb()
            .create_sql_database(RG, ACCOUNT, DATABASE, &body)
            .await
            .expect("create_sql_database failed");
        assert_eq!(db.name.as_deref(), Some(DATABASE));
    }

    #[tokio::test]
    async fn list_sql_containers_returns_list() {
        let mut mock = MockClient::new();
        mock.expect_get(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}/containers"),
        )
        .returning_json(serde_json::json!({ "value": [sql_container_json()] }));
        let client = make_client(mock);
        let result = client
            .cosmosdb()
            .list_sql_containers(RG, ACCOUNT, DATABASE)
            .await
            .expect("list_sql_containers failed");
        assert_eq!(result.value.len(), 1);
        assert_eq!(result.value[0].name.as_deref(), Some(CONTAINER));
    }

    #[tokio::test]
    async fn get_sql_container_deserializes_partition_key() {
        let mut mock = MockClient::new();
        mock.expect_get(
            &format!("/subscriptions/{SUB_ID}/resourceGroups/{RG}/providers/Microsoft.DocumentDB/databaseAccounts/{ACCOUNT}/sqlDatabases/{DATABASE}/containers/{CONTAINER}"),
        )
        .returning_json(sql_container_json());
        let client = make_client(mock);
        let c = client
            .cosmosdb()
            .get_sql_container(RG, ACCOUNT, DATABASE, CONTAINER)
            .await
            .expect("get_sql_container failed");
        assert_eq!(c.name.as_deref(), Some(CONTAINER));
        let props = c.properties.as_ref().unwrap();
        let resource = props.resource.as_ref().unwrap();
        assert_eq!(resource.id.as_deref(), Some(CONTAINER));
        let pk = resource.partition_key.as_ref().unwrap();
        assert_eq!(pk.kind.as_deref(), Some("Hash"));
        assert_eq!(pk.version, Some(2));
    }
}