Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 81 additions & 58 deletions crates/core/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub use messages::{
validation_errors_detected,
};

use serde::ser::{SerializeMap as _, Serializer as _};

use crate::types::{CancellationReason, Item};

/// The `ExpiredIteratorException` message for a shard iterator older than its
Expand Down Expand Up @@ -411,32 +413,48 @@ impl DynamoDbError {
pub const SERIALIZATION_FAILURE_BODY: &[u8] =
br#"{"__type":"com.amazonaws.dynamodb.v20120810#InternalServerError","message":"Internal error"}"#;

/// Build the DynamoDB-shaped error document for `error`.
/// Build the DynamoDB-shaped error document for `error`, as JSON bytes.
///
/// Returns the JSON body a client receives for a failed request: `__type` with
/// its namespace prefix (REQ-ERR-001), an optional message under the key
/// `message_key` picks (REQ-ERR-002), omitted when empty
/// (REQ-ERR-003 — real DynamoDB omits it for `UnknownOperationException` and
/// other messageless errors), and the `CancellationReasons` /`Item` members
/// that `TransactionCanceledException` and `ConditionalCheckFailedException`
/// carry. This is only the body; the HTTP status line and headers belong to a
/// transport and stay with the caller that has one. Error responses are part of
/// the observable contract, so every entry point builds this body the same way.
/// Returns the JSON body a client receives for a failed request, with its
/// members in the order DynamoDB writes them (us-east-1, raw bodies,
/// 2026-11-20): `__type` with its namespace prefix (REQ-ERR-001), then the
/// `CancellationReasons` of a `TransactionCanceledException` or the `Item` of
/// a `ConditionalCheckFailedException`, then the message under the key
/// `message_key` picks (REQ-ERR-002), omitted when empty (REQ-ERR-003:
/// DynamoDB omits it for `UnknownOperationException` and other messageless
/// errors). The top-level members are written one by one, so their order does
/// not depend on serde_json's `preserve_order` feature, which bson turns on in
/// any build that includes the MongoDB backend. If the body cannot be
/// serialized, the bytes are [`SERIALIZATION_FAILURE_BODY`]. This is only the
/// body; the HTTP status line and headers belong to a transport and stay with
/// the caller that has one. Error responses are part of the observable
/// contract, so every entry point builds this body the same way.
#[doc(hidden)]
#[must_use]
pub fn error_document(error: &DynamoDbError) -> serde_json::Value {
let mut body = serde_json::json!({ "__type": error.full_error_type() });
let message = error.message();
if !message.is_empty() {
body[message_key(error)] = serde_json::Value::String(message.to_owned());
}
pub fn error_document(error: &DynamoDbError) -> Vec<u8> {
error_body(error).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec())
}

/// The members of [`error_document`], in its order.
fn error_body(error: &DynamoDbError) -> serde_json::Result<Vec<u8>> {
let mut bytes = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut bytes);
let mut body = serializer.serialize_map(None)?;
body.serialize_entry("__type", &error.full_error_type())?;
// Each reason writes `Code`, `Item`, `Message`, the field order of
// `CancellationReason` and the order `DynamoDB` writes.
if let Some(reasons) = error.cancellation_reasons() {
body["CancellationReasons"] = serde_json::to_value(reasons).unwrap_or_default();
body.serialize_entry("CancellationReasons", reasons)?;
}
if let Some(item) = error.condition_check_item() {
body["Item"] = serde_json::to_value(item).unwrap_or_default();
body.serialize_entry("Item", item)?;
}
body
let msg = error.message();
if !msg.is_empty() {
body.serialize_entry(message_key(error), msg)?;
}
body.end()?;
Ok(bytes)
}

/// The key that carries the error message: `Message` on the errors matched
Expand Down Expand Up @@ -485,6 +503,7 @@ pub fn webassembly_unsupported_message(subject: &str, reason: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::types::AttributeValue;

/// SP-ERR-002: verify every variant returns the correct HTTP status code.
#[test]
Expand Down Expand Up @@ -634,46 +653,50 @@ mod tests {
);
}

/// The bytes of each body: `__type`, then `CancellationReasons` or `Item`,
/// then the message, which is omitted when empty (REQ-ERR-003), and a
/// cancellation reason as `Code`, `Item`, `Message`. DynamoDB wrote these
/// orders in us-east-1 on 2026-11-20 (raw bodies, each request twice). An
/// `Item` here holds one attribute, because DynamoDB changed the order of
/// the attributes inside an `Item` between two sends of one request.
#[test]
fn error_document_carries_type_and_message() {
let doc = error_document(&DynamoDbError::ValidationException("bad input".to_owned()));
assert_eq!(
doc["__type"],
serde_json::json!("com.amazon.coral.validate#ValidationException")
);
assert_eq!(doc["message"], serde_json::json!("bad input"));
}

#[test]
fn error_document_omits_empty_message() {
// REQ-ERR-003: real DynamoDB omits `message` when it is empty.
let doc = error_document(&DynamoDbError::UnknownOperationException(String::new()));
assert_eq!(
doc["__type"],
serde_json::json!("com.amazon.coral.service#UnknownOperationException")
);
assert!(doc.get("message").is_none(), "{doc}");
}

#[test]
fn error_document_includes_cancellation_reasons() {
let doc = error_document(&DynamoDbError::TransactionCanceledException {
message: "Transaction cancelled".to_owned(),
cancellation_reasons: vec![CancellationReason {
code: "ConditionalCheckFailed".to_owned(),
message: Some("The conditional request failed".to_owned()),
item: None,
}],
});
assert_eq!(doc["Message"], serde_json::json!("Transaction cancelled"));
let reasons = doc["CancellationReasons"]
.as_array()
.expect("CancellationReasons is an array");
assert_eq!(reasons.len(), 1);
assert_eq!(
reasons[0]["Code"],
serde_json::json!("ConditionalCheckFailed")
);
fn error_document_writes_the_members_in_the_service_order() {
let item = Item::from([("pk".to_owned(), AttributeValue::S("e1222".to_owned()))]);
let failed = "The conditional request failed";
let rows = [
(
DynamoDbError::ValidationException("bad input".to_owned()),
r#"{"__type":"com.amazon.coral.validate#ValidationException","message":"bad input"}"#,
),
(
DynamoDbError::UnknownOperationException(String::new()),
r#"{"__type":"com.amazon.coral.service#UnknownOperationException"}"#,
),
(
DynamoDbError::TransactionCanceledException {
message:
"Transaction cancelled, please refer cancellation reasons for specific \
reasons [ConditionalCheckFailed]"
.to_owned(),
cancellation_reasons: vec![CancellationReason {
code: "ConditionalCheckFailed".to_owned(),
item: Some(item.clone()),
message: Some(failed.to_owned()),
}],
},
r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Item":{"pk":{"S":"e1222"}},"Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#,
),
(
DynamoDbError::ConditionalCheckFailedException(failed.to_owned(), Some(item)),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","Item":{"pk":{"S":"e1222"}},"message":"The conditional request failed"}"#,
),
];
let got: Vec<String> = rows
.iter()
.map(|(error, _)| String::from_utf8(error_document(error)).expect("UTF-8 body"))
.collect();
let want: Vec<&str> = rows.iter().map(|(_, body)| *body).collect();
assert_eq!(got, want);
}

#[test]
Expand Down
9 changes: 6 additions & 3 deletions crates/core/src/types/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,17 +259,20 @@ pub struct TransactWriteItemsOutput {
}

/// Per-item cancellation reason in a `TransactionCanceledException`.
///
/// The fields are declared in the order `DynamoDB` writes the members of a
/// reason (`Code`, `Item`, `Message`), and serialize in that order.
#[derive(Debug, Clone, Serialize)]
pub struct CancellationReason {
/// Status code: `"None"`, `"ConditionalCheckFailed"`, `"ValidationError"`, etc.
#[serde(rename = "Code")]
pub code: String,
/// Human-readable message, omitted for items with no error.
#[serde(rename = "Message", skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// The existing item when `ReturnValuesOnConditionCheckFailure` is `ALL_OLD`.
#[serde(rename = "Item", skip_serializing_if = "Option::is_none")]
pub item: Option<Item>,
/// Human-readable message, omitted for items with no error.
#[serde(rename = "Message", skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}

impl CancellationReason {
Expand Down
11 changes: 5 additions & 6 deletions crates/server/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@ pub(crate) fn success_response(body: &Value, request_id: &str) -> Response {
/// key `error_document` picks. REQ-ERR-003: Omit the message field when empty
/// (real `DynamoDB` behavior, verified 2026-05-04).
pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Response {
// The body shape (`__type`, optional message, `CancellationReasons`, `Item`)
// is built by the shared `error_document` helper so the wire body and the
// in-process body come from the same code; this transport adds the HTTP status and headers.
let body = error_document(error);
let body_bytes =
serde_json::to_vec(&body).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec());
// The body (`__type`, then `CancellationReasons` or `Item`, then the
// message) is written by the shared `error_document` helper so the wire
// body and the in-process body come from the same code; this transport adds
// the HTTP status and headers.
let body_bytes = error_document(error);
let crc = crc32fast::hash(&body_bytes);
let status =
StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
Expand Down
103 changes: 66 additions & 37 deletions crates/server/src/response_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,60 +4,89 @@
//! Tests of the error bodies [`super::error_response`] sends.

use extenddb_core::error::DynamoDbError;
use extenddb_core::types::CancellationReason;
use extenddb_core::types::{AttributeValue, CancellationReason, Item};

use super::error_response;

/// The top-level keys of the body `error_response` sends for `error`.
async fn body_keys(error: &DynamoDbError) -> Vec<String> {
/// The body `error_response` sends for `error`.
async fn body(error: &DynamoDbError) -> String {
let response = error_response(error, "request-1");
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let body: serde_json::Value = serde_json::from_slice(&bytes).expect("json body");
let mut keys: Vec<String> = body.as_object().expect("object").keys().cloned().collect();
keys.sort_unstable();
keys
String::from_utf8(bytes.to_vec()).expect("UTF-8 body")
}

/// The errors measured with `Message` carry it under that key, as the
/// service sends them; the errors measured with `message` keep it.
/// Each expected body is the one the service sent for that error (us-east-1,
/// raw bodies, 2026-11-20, each request twice): `__type` first, the other
/// members in the service's order, and the message under the key the service
/// uses for that error. An `Item` here holds one attribute, because the service
/// changed the order of the attributes inside an `Item` between two sends of
/// one request. The `SerializationException` with an empty text has no measured
/// body: ExtendDB omits an empty message (REQ-ERR-003).
#[tokio::test]
async fn the_message_key_follows_the_service_per_error() {
let cancelled = DynamoDbError::TransactionCanceledException {
async fn the_members_follow_the_service_per_error() {
let cancelled = |item: Option<Item>| DynamoDbError::TransactionCanceledException {
message: "Transaction cancelled, please refer cancellation reasons for specific \
reasons [ConditionalCheckFailed]"
.to_owned(),
cancellation_reasons: vec![CancellationReason {
code: "ConditionalCheckFailed".to_owned(),
message: Some("The conditional request failed".to_owned()),
item: None,
item,
}],
};
assert_eq!(
body_keys(&cancelled).await,
["CancellationReasons", "Message", "__type"]
);
let mismatch = DynamoDbError::IdempotentParameterMismatchException(
"Specified idempotent token was used with different request parameters within \
the idempotency window"
.to_owned(),
);
assert_eq!(body_keys(&mismatch).await, ["Message", "__type"]);
let serialization = DynamoDbError::SerializationException(
"STRING_VALUE cannot be converted to Integer".to_owned(),
);
assert_eq!(body_keys(&serialization).await, ["Message", "__type"]);
let empty = DynamoDbError::SerializationException(String::new());
assert_eq!(body_keys(&empty).await, ["__type"]);
for other in [
DynamoDbError::ValidationException("One or more parameter values were invalid".into()),
DynamoDbError::ConditionalCheckFailedException(
"The conditional request failed".into(),
None,
),
DynamoDbError::TransactionConflictException("Transaction is ongoing".into()),
] {
assert_eq!(body_keys(&other).await, ["__type", "message"], "{other:?}");
let old_item = Item::from([("pk".to_owned(), AttributeValue::S("e1222".to_owned()))]);
let failed = "The conditional request failed";
let rows: [(DynamoDbError, &str); 8] = [
(
cancelled(None),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#,
),
(
cancelled(Some(old_item.clone())),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#TransactionCanceledException","CancellationReasons":[{"Code":"ConditionalCheckFailed","Item":{"pk":{"S":"e1222"}},"Message":"The conditional request failed"}],"Message":"Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed]"}"#,
),
(
DynamoDbError::ConditionalCheckFailedException(failed.into(), Some(old_item)),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","Item":{"pk":{"S":"e1222"}},"message":"The conditional request failed"}"#,
),
(
DynamoDbError::ConditionalCheckFailedException(failed.into(), None),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException","message":"The conditional request failed"}"#,
),
(
DynamoDbError::IdempotentParameterMismatchException(
"Specified idempotent token was used with different request parameters \
within the idempotency window"
.to_owned(),
),
r#"{"__type":"com.amazonaws.dynamodb.v20120810#IdempotentParameterMismatchException","Message":"Specified idempotent token was used with different request parameters within the idempotency window"}"#,
),
(
DynamoDbError::SerializationException(
"STRING_VALUE cannot be converted to Integer".to_owned(),
),
r#"{"__type":"com.amazon.coral.service#SerializationException","Message":"STRING_VALUE cannot be converted to Integer"}"#,
),
(
DynamoDbError::SerializationException(String::new()),
r#"{"__type":"com.amazon.coral.service#SerializationException"}"#,
),
(
DynamoDbError::ValidationException(
"1 validation error detected: Value null at 'key' failed to satisfy \
constraint: Member must not be null"
.to_owned(),
),
r#"{"__type":"com.amazon.coral.validate#ValidationException","message":"1 validation error detected: Value null at 'key' failed to satisfy constraint: Member must not be null"}"#,
),
];
let mut got = Vec::new();
let mut want = Vec::new();
for (error, expected) in &rows {
got.push(body(error).await);
want.push(*expected);
}
assert_eq!(got, want);
}
Loading
Loading