azure_data_cosmos 0.36.0

Rust wrappers around Microsoft Azure REST APIs - Azure Cosmos DB
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! [`TransactionalBatch`] and the result types its execution returns.

use crate::options::{
    BatchDeleteOptions, BatchReadOptions, BatchReplaceOptions, BatchUpsertOptions, Precondition,
};
use crate::PartitionKey;
use azure_core::fmt::SafeDebug;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

/// Represents a transactional batch of operations to be executed atomically.
///
/// All operations in the batch must target the same partition key.
///
/// # Examples
///
/// ```rust,no_run
/// use azure_data_cosmos::TransactionalBatch;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Deserialize, Serialize)]
/// struct Product {
///     id: String,
///     category: String,
///     name: String,
/// }
///
/// # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
/// # let container_client: azure_data_cosmos::clients::ContainerClient = panic!("this is a non-running example");
/// let product1 = Product {
///     id: "product1".to_string(),
///     category: "category1".to_string(),
///     name: "Product #1".to_string(),
/// };
///
/// let batch = TransactionalBatch::new("category1")
///     .create_item(product1)?;
///
/// let response = container_client.execute_transactional_batch(batch, None).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, SafeDebug)]
#[safe(true)]
pub struct TransactionalBatch {
    partition_key: PartitionKey,
    operations: Vec<TransactionalBatchOperation>,
}

impl TransactionalBatch {
    /// Creates a new transactional batch for the specified partition key.
    ///
    /// # Arguments
    /// * `partition_key` - The partition key for all operations in this batch.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use azure_data_cosmos::TransactionalBatch;
    ///
    /// let batch = TransactionalBatch::new("my_partition_key");
    /// ```
    pub fn new(partition_key: impl Into<PartitionKey>) -> Self {
        Self {
            partition_key: partition_key.into(),
            operations: Vec::new(),
        }
    }

    /// Returns the partition key for this batch.
    pub fn partition_key(&self) -> &PartitionKey {
        &self.partition_key
    }

    /// Returns the operations in this batch.
    pub(crate) fn operations(&self) -> &[TransactionalBatchOperation] {
        &self.operations
    }

    /// Adds a create operation to the batch.
    ///
    /// # Arguments
    /// * `item` - The item to create. Must implement [`Serialize`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use azure_data_cosmos::TransactionalBatch;
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)]
    /// struct Product {
    ///     id: String,
    ///     name: String,
    /// }
    ///
    /// # fn doc() -> Result<(), Box<dyn std::error::Error>> {
    /// let product = Product {
    ///     id: "product1".to_string(),
    ///     name: "Product #1".to_string(),
    /// };
    ///
    /// let batch = TransactionalBatch::new("partition1")
    ///     .create_item(product)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_item<T: Serialize>(mut self, item: T) -> crate::Result<Self> {
        let resource_body = serde_json::to_value(item)?;
        self.operations.push(TransactionalBatchOperation::Create {
            resource_body,
            id: None,
        });
        Ok(self)
    }

    /// Adds an upsert operation to the batch.
    ///
    /// # Arguments
    /// * `item` - The item to upsert. Must implement [`Serialize`].
    /// * `options` - Optional conditional options for the operation.
    pub fn upsert_item<T: Serialize>(
        mut self,
        item: T,
        options: Option<BatchUpsertOptions>,
    ) -> crate::Result<Self> {
        let resource_body = serde_json::to_value(item)?;
        let (if_match, if_none_match) = match options.as_ref().and_then(|o| o.precondition.as_ref())
        {
            Some(Precondition::IfMatch(etag)) => (Some(etag.to_string()), None),
            Some(Precondition::IfNoneMatch(etag)) => (None, Some(etag.to_string())),
            None | Some(_) => (None, None),
        };
        self.operations.push(TransactionalBatchOperation::Upsert {
            resource_body,
            id: None,
            if_match,
            if_none_match,
        });
        Ok(self)
    }

    /// Adds a replace operation to the batch.
    ///
    /// # Arguments
    /// * `item_id` - The id of the item to replace.
    /// * `item` - The new item data. Must implement [`Serialize`].
    /// * `options` - Optional conditional options for the operation (e.g., `if_match` for optimistic concurrency).
    pub fn replace_item<T: Serialize>(
        mut self,
        item_id: impl Into<Cow<'static, str>>,
        item: T,
        options: Option<BatchReplaceOptions>,
    ) -> crate::Result<Self> {
        let resource_body = serde_json::to_value(item)?;
        let if_match = match options.as_ref().and_then(|o| o.precondition.as_ref()) {
            Some(Precondition::IfMatch(etag)) => Some(etag.to_string()),
            _ => None,
        };
        self.operations.push(TransactionalBatchOperation::Replace {
            id: item_id.into(),
            resource_body,
            if_match,
        });
        Ok(self)
    }

    /// Adds a read operation to the batch.
    ///
    /// # Arguments
    /// * `item_id` - The id of the item to read.
    /// * `options` - Optional conditional options for the operation.
    pub fn read_item(
        mut self,
        item_id: impl Into<Cow<'static, str>>,
        options: Option<BatchReadOptions>,
    ) -> Self {
        let (if_match, if_none_match) = match options.as_ref().and_then(|o| o.precondition.as_ref())
        {
            Some(Precondition::IfMatch(etag)) => (Some(etag.to_string()), None),
            Some(Precondition::IfNoneMatch(etag)) => (None, Some(etag.to_string())),
            None | Some(_) => (None, None),
        };
        self.operations.push(TransactionalBatchOperation::Read {
            id: item_id.into(),
            if_match,
            if_none_match,
        });
        self
    }

    /// Adds a delete operation to the batch.
    ///
    /// # Arguments
    /// * `item_id` - The id of the item to delete.
    /// * `options` - Optional conditional options for the operation (e.g., `if_match` to only delete if ETag matches).
    pub fn delete_item(
        mut self,
        item_id: impl Into<Cow<'static, str>>,
        options: Option<BatchDeleteOptions>,
    ) -> Self {
        let if_match = match options.as_ref().and_then(|o| o.precondition.as_ref()) {
            Some(Precondition::IfMatch(etag)) => Some(etag.to_string()),
            _ => None,
        };
        self.operations.push(TransactionalBatchOperation::Delete {
            id: item_id.into(),
            if_match,
        });
        self
    }
}

/// Represents a single operation within a transactional batch.
///
/// Each operation is serialized with the "operationType" field indicating the type
/// of operation (e.g., "Create", "Read", "Delete"). The variant names match the
/// Cosmos DB REST API requirements for transactional batch operations.
///
/// # Serialization Format
///
/// Operations are serialized as JSON objects with the following structure:
///
/// ```json
/// {
///   "operationType": "Create",
///   "resourceBody": { /* item data */ }
/// }
/// ```
///
/// Or for operations that reference an existing item:
///
/// ```json
/// {
///   "operationType": "Read",
///   "id": "item-id"
/// }
/// ```
#[derive(Clone, SafeDebug, Serialize, Deserialize)]
#[safe(true)]
#[serde(tag = "operationType", rename_all_fields = "camelCase")]
pub(crate) enum TransactionalBatchOperation {
    /// Create a new item.
    Create {
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<Cow<'static, str>>,
        resource_body: serde_json::Value,
    },
    /// Upsert an item (create or replace).
    Upsert {
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<Cow<'static, str>>,
        resource_body: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_match: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_none_match: Option<String>,
    },
    /// Replace an existing item.
    Replace {
        id: Cow<'static, str>,
        resource_body: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_match: Option<String>,
    },
    /// Read an item.
    Read {
        id: Cow<'static, str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_match: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_none_match: Option<String>,
    },
    /// Delete an item.
    Delete {
        id: Cow<'static, str>,
        #[serde(skip_serializing_if = "Option::is_none")]
        if_match: Option<String>,
    },
}

/// Response from executing a transactional batch.
///
/// The Cosmos DB batch API returns a raw JSON array of operation results,
/// so we implement a custom deserializer to handle this format.
#[derive(Clone, SafeDebug)]
#[safe(true)]
#[non_exhaustive]
pub struct TransactionalBatchResponse {
    /// The results of each operation in the batch.
    results: Vec<TransactionalBatchOperationResult>,
}

impl TransactionalBatchResponse {
    /// Returns the results of each operation in the batch.
    pub fn results(&self) -> &[TransactionalBatchOperationResult] {
        &self.results
    }
}

impl<'de> Deserialize<'de> for TransactionalBatchResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // The Cosmos DB batch API returns a raw JSON array, not an object with a "results" field
        let results = Vec::<TransactionalBatchOperationResult>::deserialize(deserializer)?;
        Ok(TransactionalBatchResponse { results })
    }
}

/// Result of a single operation within a transactional batch.
#[derive(Clone, SafeDebug, Deserialize)]
#[safe(true)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct TransactionalBatchOperationResult {
    /// HTTP status code for this operation.
    ///
    /// This is exposed as a raw `u16` because the per-operation status comes
    /// directly from the JSON body of the batch response. We deliberately do
    /// not deserialize into [`azure_core::http::StatusCode`]: that enum is
    /// closed and would fail deserialization for any non-canonical status
    /// code returned by the service. Failing the entire batch deserialization
    /// because the service introduced a new status value would be a much
    /// worse caller experience than surfacing the integer as-is.
    status_code: u16,

    /// The resource body returned by the operation, if any. Stored as
    /// [`RawValue`](serde_json::value::RawValue) so the JSON bytes are kept
    /// exactly as the service produced them — callers decide whether (and how)
    /// to parse them via [`into_model::<T>`](Self::into_model) or
    /// inspect the raw JSON via [`resource_body`](Self::resource_body).
    #[serde(default)]
    resource_body: Option<Box<serde_json::value::RawValue>>,

    /// ETag of the resource after the operation.
    #[serde(rename = "eTag")]
    #[serde(default)]
    etag: Option<String>,

    /// Request charge for this operation.
    #[serde(default)]
    request_charge: Option<f64>,

    /// Retry after duration in milliseconds, if applicable.
    #[serde(default)]
    retry_after_milliseconds: Option<u64>,

    /// Substatus code for this operation, if applicable.
    #[serde(default)]
    substatus_code: Option<u32>,
}

impl TransactionalBatchOperationResult {
    /// Returns the HTTP status code for this operation.
    pub fn status_code(&self) -> u16 {
        self.status_code
    }

    /// Returns the resource body returned by the operation, if any.
    ///
    /// The body is returned as a still-serialized
    /// [`RawValue`](serde_json::value::RawValue) — its `get()` method yields
    /// the raw JSON text. To deserialize into a typed value, use
    /// [`into_model`](Self::into_model) instead.
    pub fn resource_body(&self) -> Option<&serde_json::value::RawValue> {
        self.resource_body.as_deref()
    }

    /// Returns the ETag of the resource after the operation, if any.
    pub fn etag(&self) -> Option<&str> {
        self.etag.as_deref()
    }

    /// Returns the request charge for this operation, if any.
    pub fn request_charge(&self) -> Option<f64> {
        self.request_charge
    }

    /// Returns the retry after duration in milliseconds, if applicable.
    pub fn retry_after_milliseconds(&self) -> Option<u64> {
        self.retry_after_milliseconds
    }

    /// Returns the substatus code for this operation, if applicable.
    pub fn substatus_code(&self) -> Option<u32> {
        self.substatus_code
    }

    /// Deserializes the resource body as the specified type.
    ///
    /// Returns `None` if there is no resource body.
    ///
    /// # Errors
    ///
    /// Returns an error if the resource body cannot be deserialized as the
    /// specified type.
    pub fn into_model<T: serde::de::DeserializeOwned>(&self) -> crate::Result<Option<T>> {
        match &self.resource_body {
            Some(value) => Ok(Some(serde_json::from_str(value.get())?)),
            None => Ok(None),
        }
    }

    /// Returns `true` if this operation was successful (2xx status code).
    pub fn is_success(&self) -> bool {
        self.status_code >= 200 && self.status_code < 300
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use azure_core::http::Etag;
    use serde::Serialize;

    #[derive(Serialize)]
    struct TestItem {
        id: String,
        value: i32,
    }

    #[test]
    fn create_batch_with_partition_key() {
        let batch = TransactionalBatch::new("test_partition");
        assert_eq!(batch.partition_key(), &PartitionKey::from("test_partition"));
        assert_eq!(batch.operations().len(), 0);
    }

    #[test]
    fn serialize_all_operations() -> Result<(), Box<dyn std::error::Error>> {
        let item = TestItem {
            id: "item1".to_string(),
            value: 42,
        };

        let replace_options = BatchReplaceOptions::default()
            .with_precondition(Precondition::IfMatch(Etag::from("some-etag")));

        let batch = TransactionalBatch::new("test_partition")
            .create_item(&item)?
            .upsert_item(&item, None)?
            .replace_item("id1", &item, Some(replace_options))?
            .read_item("id2", None)
            .delete_item("id3", None);

        assert_eq!(batch.operations().len(), 5);

        let serialized = serde_json::to_string_pretty(batch.operations())?;

        let expected = r#"[
  {
    "operationType": "Create",
    "resourceBody": {
      "id": "item1",
      "value": 42
    }
  },
  {
    "operationType": "Upsert",
    "resourceBody": {
      "id": "item1",
      "value": 42
    }
  },
  {
    "operationType": "Replace",
    "id": "id1",
    "resourceBody": {
      "id": "item1",
      "value": 42
    },
    "ifMatch": "some-etag"
  },
  {
    "operationType": "Read",
    "id": "id2"
  },
  {
    "operationType": "Delete",
    "id": "id3"
  }
]"#;

        assert_eq!(serialized, expected);

        Ok(())
    }
}