dynoxide-rs 0.11.1

A lightweight, embeddable DynamoDB emulator backed by SQLite
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;

/// Per-item cancellation reason in a `TransactionCanceledException` response.
///
/// Real DynamoDB returns one reason per `TransactItem`, with `Code: "None"` for
/// items that would have succeeded.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CancellationReason {
    #[serde(rename = "Code")]
    pub code: String,
    #[serde(rename = "Message", skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(rename = "Item", skip_serializing_if = "Option::is_none")]
    pub item: Option<HashMap<String, crate::types::AttributeValue>>,
}

/// DynamoDB error types.
///
/// Each variant corresponds to a DynamoDB API error, carrying a human-readable
/// message that matches DynamoDB's actual error messages.
///
/// Marked `#[non_exhaustive]` as of 0.10.0 (itself a breaking release), so
/// later variant additions stay non-breaking. Downstream `match` arms over
/// this enum must include a wildcard.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DynoxideError {
    /// Table or resource not found.
    #[error("{0}")]
    ResourceNotFoundException(String),

    /// Table or resource already exists / is in use.
    #[error("{0}")]
    ResourceInUseException(String),

    /// Input validation failed.
    #[error("{0}")]
    ValidationException(String),

    /// An empty-string or empty-binary key value on a write. Serialises identically
    /// to `ValidationException`, but is a distinct variant so the transaction loops can
    /// surface it as a top-level error instead of a `ValidationError` cancellation
    /// reason (#95).
    #[error("{0}")]
    KeyEmptyValueValidation(String),

    /// Conditional check (ConditionExpression) failed on write.
    /// Optionally carries the existing item when `ReturnValuesOnConditionCheckFailure` is `ALL_OLD`.
    #[error("{0}")]
    ConditionalCheckFailedException(
        String,
        Option<HashMap<String, crate::types::AttributeValue>>,
    ),

    /// One or more transaction conditions failed.
    /// Carries the message and per-item cancellation reasons.
    #[error("{0}")]
    TransactionCanceledException(String, Vec<CancellationReason>),

    /// Item collection exceeded size limit (10 GB per partition key value).
    #[error("{0}")]
    ItemCollectionSizeLimitExceededException(String),

    /// Duplicate primary key on PartiQL INSERT (distinct from ConditionalCheckFailedException).
    #[error("{0}")]
    DuplicateItemException(String),

    /// Throughput exceeded (stored but not enforced — included for API fidelity).
    #[error("{0}")]
    ProvisionedThroughputExceededException(String),

    /// Request body deserialisation failed (malformed JSON, wrong types).
    #[error("{0}")]
    SerializationException(String),

    /// Too many concurrent operations or index updates.
    #[error("{0}")]
    LimitExceededException(String),

    /// Access denied (e.g. non-existent resource ARN in tag operations).
    #[error("{0}")]
    AccessDeniedException(String),

    /// Idempotent request token reused with different request content.
    #[error("{0}")]
    IdempotentParameterMismatchException(String),

    /// Catch-all for internal / unexpected errors (SQLite failures, etc.).
    #[error("{0}")]
    InternalServerError(String),

    /// Type conversion error (e.g. wrong AttributeValue variant).
    #[error("Conversion error: {0}")]
    ConversionError(#[from] crate::types::ConversionError),

    /// SQLite error (converted from rusqlite).
    #[cfg(any(feature = "native-sqlite", feature = "_has-encryption"))]
    #[error("Internal error: {0}")]
    SqliteError(#[from] rusqlite::Error),

    /// OPFS is present in the browser but its pool could not be acquired
    /// (typically another tab holds the database). wasm backend only; carries a
    /// dynoxide-specific `__type` so a client can detect a busy database.
    #[cfg(feature = "wasm-sqlite")]
    #[error("{0}")]
    OpfsUnavailable(String),
}

/// Most backend failures (`BackendError`) are storage-level faults: a locked
/// database, an I/O error, a constraint the application layer did not
/// anticipate. None of those is part of DynamoDB's client-facing error
/// contract, so they surface as `InternalServerError` (HTTP 500), matching how
/// a raw `rusqlite::Error` surfaces via `SqliteError`.
///
/// The one exception is `BackendError::Validation`: a backend method such as
/// `set_tags` enforces a client-facing limit (the 50-tag cap) and raises a
/// `ValidationException`. That crosses the trait boundary as
/// `BackendError::Validation` and is restored here to its `ValidationException`
/// (HTTP 400) so the envelope is unchanged from calling `Storage` directly.
///
/// A one-way `From` is deliberate rather than merging the two types:
/// `BackendError` is the narrow storage vocabulary, `DynoxideError` the wider
/// API vocabulary. A merge is deferred.
impl From<crate::storage_backend::BackendError> for DynoxideError {
    fn from(err: crate::storage_backend::BackendError) -> Self {
        use crate::storage_backend::BackendError;
        match err {
            BackendError::Validation(msg) => DynoxideError::ValidationException(msg),
            #[cfg(feature = "wasm-sqlite")]
            BackendError::OpfsUnavailable(msg) => DynoxideError::OpfsUnavailable(msg),
            other => DynoxideError::InternalServerError(other.to_string()),
        }
    }
}

impl DynoxideError {
    /// Returns the DynamoDB `__type` string for this error.
    pub fn error_type(&self) -> &'static str {
        match self {
            DynoxideError::ResourceNotFoundException(_) => {
                "com.amazonaws.dynamodb.v20120810#ResourceNotFoundException"
            }
            DynoxideError::ResourceInUseException(_) => {
                "com.amazonaws.dynamodb.v20120810#ResourceInUseException"
            }
            DynoxideError::ValidationException(_) | DynoxideError::KeyEmptyValueValidation(_) => {
                "com.amazon.coral.validate#ValidationException"
            }
            DynoxideError::ConditionalCheckFailedException(..) => {
                "com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException"
            }
            DynoxideError::TransactionCanceledException(..) => {
                "com.amazonaws.dynamodb.v20120810#TransactionCanceledException"
            }
            DynoxideError::DuplicateItemException(_) => {
                "com.amazonaws.dynamodb.v20120810#DuplicateItemException"
            }
            DynoxideError::ItemCollectionSizeLimitExceededException(_) => {
                "com.amazonaws.dynamodb.v20120810#ItemCollectionSizeLimitExceededException"
            }
            DynoxideError::ProvisionedThroughputExceededException(_) => {
                "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException"
            }
            DynoxideError::SerializationException(_) => {
                "com.amazon.coral.service#SerializationException"
            }
            DynoxideError::LimitExceededException(_) => {
                "com.amazonaws.dynamodb.v20120810#LimitExceededException"
            }
            DynoxideError::AccessDeniedException(_) => {
                "com.amazonaws.dynamodb.v20120810#AccessDeniedException"
            }
            DynoxideError::IdempotentParameterMismatchException(_) => {
                "com.amazonaws.dynamodb.v20120810#IdempotentParameterMismatchException"
            }
            DynoxideError::ConversionError(_) => "com.amazon.coral.validate#ValidationException",
            DynoxideError::InternalServerError(_) => {
                "com.amazonaws.dynamodb.v20120810#InternalServerError"
            }
            #[cfg(any(feature = "native-sqlite", feature = "_has-encryption"))]
            DynoxideError::SqliteError(_) => "com.amazonaws.dynamodb.v20120810#InternalServerError",
            #[cfg(feature = "wasm-sqlite")]
            DynoxideError::OpfsUnavailable(_) => "com.dynoxide.wasm#OpfsUnavailable",
        }
    }

    /// Returns the short error code used in `BatchExecuteStatement` per-statement errors.
    ///
    /// These are the short-form codes that DynamoDB uses in `BatchStatementError.Code`,
    /// as opposed to the fully qualified `__type` strings from `error_type()`.
    pub fn short_error_code(&self) -> &'static str {
        match self {
            DynoxideError::ResourceNotFoundException(_) => "ResourceNotFound",
            DynoxideError::ResourceInUseException(_) => "ResourceInUse",
            DynoxideError::ValidationException(_)
            | DynoxideError::KeyEmptyValueValidation(_)
            | DynoxideError::ConversionError(_) => "ValidationError",
            DynoxideError::ConditionalCheckFailedException(..) => "ConditionalCheckFailed",
            DynoxideError::TransactionCanceledException(..) => "TransactionConflict",
            DynoxideError::DuplicateItemException(_) => "DuplicateItem",
            DynoxideError::ItemCollectionSizeLimitExceededException(_) => {
                "ItemCollectionSizeLimitExceeded"
            }
            DynoxideError::ProvisionedThroughputExceededException(_) => {
                "ProvisionedThroughputExceeded"
            }
            DynoxideError::AccessDeniedException(_) => "AccessDenied",
            DynoxideError::IdempotentParameterMismatchException(_) => "IdempotentParameterMismatch",
            DynoxideError::SerializationException(_) => "SerializationError",
            DynoxideError::LimitExceededException(_) => "RequestLimitExceeded",
            DynoxideError::InternalServerError(_) => "InternalServerError",
            #[cfg(any(feature = "native-sqlite", feature = "_has-encryption"))]
            DynoxideError::SqliteError(_) => "InternalServerError",
            #[cfg(feature = "wasm-sqlite")]
            DynoxideError::OpfsUnavailable(_) => "OpfsUnavailable",
        }
    }

    /// Returns the HTTP status code for this error.
    pub fn status_code(&self) -> u16 {
        match self {
            DynoxideError::InternalServerError(_) => 500,
            #[cfg(any(feature = "native-sqlite", feature = "_has-encryption"))]
            DynoxideError::SqliteError(_) => 500,
            _ => 400,
        }
    }

    /// Convert to a DynamoDB-compatible JSON error response body.
    pub fn to_response(&self) -> ErrorResponse {
        let item = if let DynoxideError::ConditionalCheckFailedException(_, item) = self {
            item.clone()
        } else {
            None
        };
        ErrorResponse {
            error_type: self.error_type().to_string(),
            message: self.to_string(),
            item,
        }
    }

    /// Serialise to DynamoDB-compatible JSON string.
    ///
    /// `SerializationException` and `TransactionCanceledException` use
    /// `Message` (capital M) while all other errors use `message` (lowercase),
    /// matching real DynamoDB behaviour.
    pub fn to_json(&self) -> String {
        let error_type = self.error_type();
        let message = self.to_string();

        match self {
            DynoxideError::TransactionCanceledException(_, reasons) => {
                let mut m = serde_json::Map::new();
                m.insert(
                    "__type".to_string(),
                    serde_json::Value::String(error_type.to_string()),
                );
                m.insert("Message".to_string(), serde_json::Value::String(message));
                if let Ok(reasons_val) = serde_json::to_value(reasons) {
                    m.insert("CancellationReasons".to_string(), reasons_val);
                }
                serde_json::to_string(&m).unwrap_or_default()
            }
            DynoxideError::SerializationException(_) => {
                let mut m = serde_json::Map::new();
                m.insert(
                    "__type".to_string(),
                    serde_json::Value::String(error_type.to_string()),
                );
                m.insert("Message".to_string(), serde_json::Value::String(message));
                serde_json::to_string(&m).unwrap_or_default()
            }
            _ => {
                let resp = self.to_response();
                serde_json::to_string(&resp).unwrap_or_default()
            }
        }
    }
}

/// DynamoDB JSON error response body.
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
    #[serde(rename = "__type")]
    pub error_type: String,
    #[serde(rename = "message")]
    pub message: String,
    #[serde(rename = "Item", skip_serializing_if = "Option::is_none")]
    pub item: Option<HashMap<String, crate::types::AttributeValue>>,
}

impl fmt::Display for ErrorResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(self).unwrap_or_default())
    }
}

/// Convenience alias.
pub type Result<T> = std::result::Result<T, DynoxideError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_response_format() {
        let err = DynoxideError::ResourceNotFoundException(
            "Requested resource not found: Table: NonExistent not found".to_string(),
        );
        let resp = err.to_response();
        let json = serde_json::to_string(&resp).unwrap();

        assert!(json.contains("\"__type\""));
        assert!(json.contains("ResourceNotFoundException"));
        assert!(json.contains("NonExistent not found"));
    }

    #[test]
    fn test_status_codes() {
        assert_eq!(
            DynoxideError::ResourceNotFoundException("".into()).status_code(),
            400
        );
        assert_eq!(
            DynoxideError::ResourceInUseException("".into()).status_code(),
            400
        );
        assert_eq!(
            DynoxideError::ValidationException("".into()).status_code(),
            400
        );
        assert_eq!(
            DynoxideError::ConditionalCheckFailedException("".into(), None).status_code(),
            400
        );
        assert_eq!(
            DynoxideError::TransactionCanceledException("".into(), vec![]).status_code(),
            400
        );
        assert_eq!(
            DynoxideError::InternalServerError("".into()).status_code(),
            500
        );
    }

    #[test]
    fn test_key_empty_value_validation_is_wire_identical_to_validation_exception() {
        // The variant must be indistinguishable from ValidationException on every wire
        // surface, for both the empty-string and empty-binary messages it now carries.
        let messages = [
            "One or more parameter values are not valid. The AttributeValue for a key \
             attribute cannot contain an empty string value. Key: pk",
            "One or more parameter values are not valid. The AttributeValue for a key \
             attribute cannot contain an empty binary value. Key: pk",
        ];
        for msg in messages {
            let empty = DynoxideError::KeyEmptyValueValidation(msg.to_string());
            let plain = DynoxideError::ValidationException(msg.to_string());
            assert_eq!(empty.status_code(), plain.status_code());
            assert_eq!(empty.error_type(), plain.error_type());
            assert_eq!(empty.short_error_code(), plain.short_error_code());
            assert_eq!(empty.to_json(), plain.to_json());
            assert_eq!(empty.to_string(), plain.to_string());
        }
    }

    #[test]
    fn test_error_type_strings() {
        let err = DynoxideError::ValidationException("bad input".into());
        assert_eq!(
            err.error_type(),
            "com.amazon.coral.validate#ValidationException"
        );
    }

    #[cfg(any(feature = "native-sqlite", feature = "_has-encryption"))]
    #[test]
    fn test_sqlite_error_maps_to_internal() {
        let sqlite_err = rusqlite::Error::QueryReturnedNoRows;
        let err = DynoxideError::from(sqlite_err);
        assert_eq!(err.status_code(), 500);
        assert!(err.error_type().contains("InternalServerError"));
    }

    // Error-envelope fidelity for the wasm backend.
    //
    // Client-facing envelopes (ResourceNotFound, ConditionalCheckFailed,
    // Validation, ...) are raised by the shared, generic action handlers, so
    // they are backend-independent by construction. The only backend-specific
    // boundary is `From<BackendError> for DynoxideError`, exercised here: the
    // wasm backend's storage faults must land on the same envelopes the native
    // rusqlite path produces.
    #[test]
    fn test_backend_error_envelopes_match_native() {
        use crate::storage_backend::BackendError;

        // A client-facing validation limit crosses the boundary as a 400.
        let v: DynoxideError = BackendError::Validation("too many tags".into()).into();
        assert_eq!(v.status_code(), 400);
        assert_eq!(
            v.error_type(),
            "com.amazon.coral.validate#ValidationException"
        );

        // Unsupported (e.g. TTL on wasm) surfaces as a 500 carrying the
        // capability tag, the documented AWS-style code for the preview.
        let u: DynoxideError = BackendError::Unsupported { capability: "ttl" }.into();
        assert_eq!(u.status_code(), 500);
        assert!(u.error_type().contains("InternalServerError"));
        assert!(u.to_string().contains("ttl"));

        // Every other storage fault maps to a 500, matching the native
        // `rusqlite::Error -> SqliteError -> InternalServerError` path.
        for e in [
            BackendError::NotADatabase,
            BackendError::Locked,
            BackendError::Constraint("constraint".into()),
            BackendError::Io("io".into()),
            BackendError::Other("sqlite-wasm: boom".into()),
        ] {
            let d: DynoxideError = e.into();
            assert_eq!(d.status_code(), 500);
            assert!(d.error_type().contains("InternalServerError"));
        }
    }

    #[test]
    fn test_error_response_json_structure() {
        let err = DynoxideError::ValidationException("1 validation error detected".to_string());
        let resp = err.to_response();
        let json: serde_json::Value = serde_json::to_value(&resp).unwrap();

        assert!(json.get("__type").is_some());
        assert!(json.get("message").is_some());
        assert_eq!(
            json["__type"],
            "com.amazon.coral.validate#ValidationException"
        );
        assert_eq!(json["message"], "1 validation error detected");
    }

    #[test]
    fn test_short_error_codes() {
        assert_eq!(
            DynoxideError::ResourceNotFoundException("".into()).short_error_code(),
            "ResourceNotFound"
        );
        assert_eq!(
            DynoxideError::ValidationException("".into()).short_error_code(),
            "ValidationError"
        );
        assert_eq!(
            DynoxideError::ConditionalCheckFailedException("".into(), None).short_error_code(),
            "ConditionalCheckFailed"
        );
        assert_eq!(
            DynoxideError::DuplicateItemException("".into()).short_error_code(),
            "DuplicateItem"
        );
        assert_eq!(
            DynoxideError::InternalServerError("".into()).short_error_code(),
            "InternalServerError"
        );
    }

    #[test]
    fn test_transaction_cancelled_json_has_cancellation_reasons() {
        let reasons = vec![
            CancellationReason {
                code: "ConditionalCheckFailed".to_string(),
                message: Some("The conditional request failed".to_string()),
                item: None,
            },
            CancellationReason {
                code: "None".to_string(),
                message: None,
                item: None,
            },
        ];
        let err = DynoxideError::TransactionCanceledException(
            "Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed, None]".to_string(),
            reasons,
        );
        let json_str = err.to_json();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        // CancellationReasons must be a top-level field
        assert!(json.get("CancellationReasons").is_some());
        let reasons = json["CancellationReasons"].as_array().unwrap();
        assert_eq!(reasons.len(), 2);
        assert_eq!(reasons[0]["Code"], "ConditionalCheckFailed");
        assert_eq!(reasons[1]["Code"], "None");

        // Uses capital Message (not lowercase)
        assert!(json.get("Message").is_some());
        assert!(json.get("message").is_none());
    }

    #[test]
    fn test_backend_error_maps_to_internal() {
        use crate::storage_backend::BackendError;
        let err: DynoxideError = BackendError::Locked.into();
        assert_eq!(err.status_code(), 500);
        assert!(err.error_type().contains("InternalServerError"));
        assert!(err.to_string().contains("locked"));
    }
}