Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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
31 changes: 21 additions & 10 deletions crates/engine/src/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,10 @@ async fn delete_catalog_backup<S: BackupCatalog + ?Sized>(
return Err(refusal);
}
if let StoreProblem::Catalog(e) = &problem {
tracing::error!("DeleteBackup {arn_text}: the catalog id could not be read: {e}");
log_storage_fault!(
e,
"DeleteBackup {arn_text}: the catalog id could not be read"
);
return Err(DynamoDbError::InternalServerError(
"Internal server error".to_owned(),
));
Expand Down Expand Up @@ -1173,7 +1176,7 @@ pub(crate) async fn handle_restore_table_from_backup(
/// drops only the wait, so the restore is not cancelled part-way. Without
/// this, a disconnect while the backup was being read (step 4 below) dropped
/// the request before the backend registered the restore, and no restore ran.
async fn restore_table_from_backup_detached<S, F, Fut>(
pub(crate) async fn restore_table_from_backup_detached<S, F, Fut>(
storage: Arc<S>,
runtime: Arc<BackupRuntime>,
account_id: Arc<str>,
Expand All @@ -1195,13 +1198,21 @@ where
F: FnOnce(Arc<str>, String) -> Fut + Send + 'static,
Fut: std::future::Future<Output = ()> + Send,
{
tokio::spawn(async move {
let (target_table_name, response) =
restore_table_from_backup(&storage, &runtime, &account_id, &region, &limits, &body)
.await?;
after(account_id, target_table_name).await;
Ok(response)
})
// The restore runs in a task of its own so a client disconnect does not
// cancel it part-way. A spawned task does not inherit the request scope,
// so it is carried across by hand: the task's fault lines then name the
// request id the client received.
let scope = extenddb_storage::request_scope::current();
tokio::spawn(extenddb_storage::request_scope::with_scope_opt(
scope,
async move {
let (target_table_name, response) =
restore_table_from_backup(&storage, &runtime, &account_id, &region, &limits, &body)
.await?;
after(account_id, target_table_name).await;
Ok(response)
},
))
.await
.map_err(|e| {
tracing::error!("RestoreTableFromBackup task failed: {e}");
Expand Down Expand Up @@ -1639,4 +1650,4 @@ pub mod store_identity;
pub mod store_maintenance;
pub mod sync;
#[cfg(test)]
mod tests;
pub(crate) mod tests;
2 changes: 1 addition & 1 deletion crates/engine/src/backup/restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ where
if let Some(metrics) = runtime.metrics() {
metrics.record_backup_store_error("get");
}
tracing::error!("backup {arn_text}: reading {name} from the store failed: {e}");
log_storage_fault!(e, "backup {arn_text}: reading {name} from the store failed");
Err(DynamoDbError::InternalServerError(
"Internal server error".to_owned(),
))
Expand Down
35 changes: 32 additions & 3 deletions crates/engine/src/backup/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn source_arn() -> String {
// --- double -----------------------------------------------------------------

#[derive(Default)]
struct Fake {
pub(crate) struct Fake {
/// Cancelled by `list_dead_restore_jobs`: a token that fires in the
/// middle of a cycle, after its store check.
cancel_on_list_dead: Mutex<Option<extenddb_storage::CancellationToken>>,
Expand All @@ -67,7 +67,7 @@ struct Fake {
summaries: Mutex<Vec<BackupSummary>>,
restore_error: Mutex<Option<StorageError>>,
/// Returned (once) by `restore_source` instead of the stored source.
source_error: Mutex<Option<StorageError>>,
pub(crate) source_error: Mutex<Option<StorageError>>,
restores: Mutex<Vec<RestoreRequest>>,
/// The permits the legacy restore and create were handed, held as the
/// backend would hold them for the job's life.
Expand Down Expand Up @@ -1013,7 +1013,7 @@ fn unused<T: Send + 'static>() -> BoxedFuture<'static, Result<T, StorageError>>
}

/// The runtime the tests run with: four slots, no configured store.
fn runtime() -> BackupRuntime {
pub(crate) fn runtime() -> BackupRuntime {
BackupRuntime::new(4)
}

Expand Down Expand Up @@ -1826,6 +1826,35 @@ fn runtime_on(mem: &Arc<MemStore>, identity: StoreIdentity) -> BackupRuntime {
))
}

/// A `RestoreTableFromBackup` whose backup row is AVAILABLE on the configured
/// store, and whose store refuses every read under the backup's prefix: the
/// request's read of the manifest's sidecar fails. The catalog, the runtime
/// and the request body.
pub(crate) fn restore_from_an_unreadable_store() -> (Arc<Fake>, BackupRuntime, Value) {
let mem = Arc::new(MemStore::default());
let fake = Arc::new(Fake::default());
let runtime = runtime_on(&mem, store());
let arn = arn(ACCOUNT);
seed_rows(&fake, &[row(&arn, BackupStatus::Available)]);
*mem.fail_gets_under.lock().unwrap() = Some(prefix_of(&arn));
(fake, runtime, restore_body(json!({})))
}

/// A `DeleteBackup` of a backup whose row is AVAILABLE on the configured
/// store, run against a catalog whose id cannot be read, so the deletion
/// fence fails before the DELETING write: the client's error.
pub(crate) async fn delete_backup_with_an_unreadable_catalog() -> DynamoDbError {
let mem = Arc::new(MemStore::default());
let fake = Arc::new(Fake::default());
let runtime = runtime_on(&mem, store());
let arn = arn(ACCOUNT);
seed_rows(&fake, &[row(&arn, BackupStatus::Available)]);
*fake.catalog_id_error.lock().unwrap() = true;
delete_backup(&*fake, &runtime, ACCOUNT, REGION, &own(&arn))
.await
.unwrap_err()
}

/// A runtime whose configured store (`store()`'s kind and root) failed its
/// startup check with `problem`: the id is unknown.
fn runtime_unhealthy(mem: &Arc<MemStore>, problem: StoreProblem) -> BackupRuntime {
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/backup_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ pub(crate) fn storage_err_to_dynamo(e: StorageError) -> DynamoDbError {
StorageError::BackupInUse(msg) => DynamoDbError::BackupInUseException(msg),
StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e),
other => {
tracing::error!(internal_error = %other, "backup storage error");
log_storage_fault!(other, "backup storage error");
DynamoDbError::InternalServerError("Internal server error".to_owned())
}
}
Expand Down
7 changes: 4 additions & 3 deletions crates/engine/src/batch_write_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,10 +352,11 @@ async fn write_batch(
} else {
"they are returned in UnprocessedItems"
};
tracing::warn!(
log_storage_fault!(
warn,
last_error = last_error,
applied,
not_applied,
last_error = %last_error,
"BatchWriteItem: {not_applied} request(s) of the batch not applied; {outcome}"
);
if applied == 0 {
Expand Down Expand Up @@ -625,7 +626,7 @@ fn collect_icm_if_needed(
}

#[cfg(test)]
mod scripted;
pub(crate) mod scripted;
#[cfg(test)]
mod write_batch_deferral_tests;
#[cfg(test)]
Expand Down
12 changes: 12 additions & 0 deletions crates/engine/src/batch_write_item/scripted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,18 @@ pub(super) fn rejected(result: Result<DispatchResult, DynamoDbError>) -> DynamoD
}
}

/// A batch of two puts whose first write fails with a connection error, so
/// nothing is applied and the batch is rejected: the client's error and the
/// `table/pk` of the writes the double received.
pub(crate) async fn batch_that_applies_nothing_after_a_connection_error()
-> (DynamoDbError, Vec<String>) {
let down = StorageError::Connection("refused".to_owned());
let data = Scripted::new(vec![Err(down)]);
let items = json!({"t": [put("a"), put("b")]});
let err = rejected(run(&data, items, &["t"], found(&["t"])).await);
(err, data.writes())
}

/// The body of a batch that must have been answered with a 200.
pub(super) fn answered(result: Result<DispatchResult, DynamoDbError>) -> DispatchResult {
result.unwrap_or_else(|e| panic!("the batch must answer 200: {e:?}"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,11 @@ async fn a_connection_error_leaves_the_rest_of_the_batch_unattempted() {
/// A connection error with nothing applied answers 503 after one attempt.
#[tokio::test]
async fn a_connection_error_with_nothing_applied_answers_503_after_one_attempt() {
let down = StorageError::Connection("refused".to_owned());
let data = Scripted::new(vec![Err(down)]);
let items = json!({"t": [put("a"), put("b")]});

let err = rejected(run(&data, items, &["t"], found(&["t"])).await);
let (err, writes) =
super::scripted::batch_that_applies_nothing_after_a_connection_error().await;

assert_eq!(err.status_code(), 503, "{err:?}");
assert_eq!(data.writes(), ["t/a"]);
assert_eq!(writes, ["t/a"]);
}

/// An error a replay would not clear fails the batch with 500, also after an
Expand Down
14 changes: 7 additions & 7 deletions crates/engine/src/create_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo
// Raised by the backup catalog's claim alone, whose caller handles
// it; here it is a programming error, reported without the row.
StorageError::AlreadyExists(msg) => {
tracing::error!(internal_error = %msg, "unexpected already-exists storage error");
log_storage_fault!(msg, "unexpected already-exists storage error");
DynamoDbError::InternalServerError("Internal server error".to_owned())
}
// The resource exists and the request is well formed; its current state
Expand All @@ -166,21 +166,21 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo
StorageError::LimitExceeded(msg) => DynamoDbError::LimitExceededException(msg), // Retryable by definition, so it maps like Connection: a 503 the SDKs
// retry, rather than a 500 they surface.
StorageError::Transient(msg) => {
tracing::warn!(transient_error = %msg, "transient storage error");
log_storage_fault!(warn, transient_error = msg, "transient storage error");
DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned())
}
// Only backup and export jobs hold snapshots; a request that reaches
// this arm lost one mid-operation. The job owner restarts it; the
// client sees the same retryable 503 as a transient fault.
StorageError::SnapshotExpired(msg) => {
tracing::warn!(snapshot_error = %msg, "storage snapshot expired");
log_storage_fault!(warn, snapshot_error = msg, "storage snapshot expired");
DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned())
}
StorageError::DeletionProtected(arn) => DynamoDbError::ValidationException(format!(
"Resource '{arn}' cannot be deleted as it is currently protected against deletion. Disable deletion protection first then try again."
)),
StorageError::Connection(msg) => {
tracing::error!(internal_error = %msg, "storage connection error");
log_storage_fault!(msg, "storage connection error");
DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned())
}
// Not a fault, so deliberately not logged at error level: the backend
Expand All @@ -206,10 +206,10 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo
}
StorageError::Validation(msg) => DynamoDbError::ValidationException(msg),
StorageError::NoOpUpdate(msg) => DynamoDbError::ValidationException(msg),
StorageError::IdempotentReplay | StorageError::IdempotentMismatch => {
e @ (StorageError::IdempotentReplay | StorageError::IdempotentMismatch) => {
// These are handled directly by the transact_write_items caller.
// If they reach here, it's a programming error.
tracing::error!("Unexpected idempotency error in generic error handler");
log_storage_fault!(e, "Unexpected idempotency error in generic error handler");
DynamoDbError::InternalServerError("Internal server error".to_owned())
}
StorageError::TransactionConflict(msg) => {
Expand All @@ -226,7 +226,7 @@ pub fn storage_err_to_dynamo(e: extenddb_storage::error::StorageError) -> Dynamo
// Log the raw message for debugging but do not expose storage
// backend details (e.g. PostgreSQL error text) to the client.
// REQ-ERR: tenet 4 — only DynamoDB-shaped errors cross the wire.
tracing::error!(internal_error = %msg, "storage internal error");
log_storage_fault!(msg, "storage internal error");
DynamoDbError::InternalServerError("Internal server error".to_owned())
}
StorageError::Service(e) => service_err_to_dynamo(e),
Expand Down
47 changes: 47 additions & 0 deletions crates/engine/src/fault_log.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2026 ExtendDB contributors
// SPDX-License-Identifier: Apache-2.0

//! The log line for a storage fault the client sees as a redacted 500 or as
//! a retryable 503.
//!
//! `log_storage_fault!` expands at its call site, so the event keeps the
//! site's own `target`, `module_path`, `file` and `line`; an operator who
//! filters on `extenddb_engine::backup_requests` still matches the backup
//! mapper's line. The macro adds `request_id` and `operation` from the
//! request scope the server sets around the request (see
//! `extenddb_storage::request_scope`), so the line can be matched to the
//! `x-amzn-RequestId` the client received. Outside a request both are
//! `None`, and `tracing` records nothing for a `None`, so the line carries
//! neither field.

/// Write an event for a storage fault.
///
/// `log_storage_fault!(error, "message")` writes an error-level event that
/// records `internal_error` from `error` (by `Display`) with the message
/// literal. The message may carry format arguments:
/// `log_storage_fault!(error, "backup {arn_text}: reading {name} from the
/// store failed")`.
///
/// `log_storage_fault!(warn, field = error, "message")` writes the same
/// event at warn level, with the error recorded under `field`: the form for
/// the lines that have always been warn level, the transient error, the
/// expired snapshot and the BatchWriteItem line for the requests a batch did
/// not apply. More fields may follow the error, before the message.
macro_rules! log_storage_fault {
(@event $level:expr, $field:ident, $error:expr, $($message:tt)+) => {{
let (request_id, operation) = extenddb_storage::request_scope::log_fields();
tracing::event!(
$level,
$field = %$error,
request_id = request_id.as_deref(),
operation = operation.as_deref(),
$($message)+
);
}};
(warn, $field:ident = $error:expr, $($message:tt)+) => {
log_storage_fault!(@event tracing::Level::WARN, $field, $error, $($message)+)
};
($error:expr, $($message:tt)+) => {
log_storage_fault!(@event tracing::Level::ERROR, internal_error, $error, $($message)+)
};
}
13 changes: 12 additions & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
//! inputs, dispatches operations by name, and translates storage errors into
//! `DynamoDB`-format error responses.

#[macro_use]
mod fault_log;
// The store-backed backup subsystem depends on an S3/filesystem store,
// networking and background threads that have no wasm32 target, so it is
// compiled only off wasm; on wasm32 `dispatch` refuses its four operations
Expand Down Expand Up @@ -60,6 +62,8 @@ mod put_item;
mod query;
mod read_helpers;
mod request_limits;
#[cfg(test)]
mod request_scope_log_tests;
mod scan;
mod search_vectors;
#[cfg(test)]
Expand Down Expand Up @@ -211,7 +215,7 @@ pub(crate) fn sanitize_storage_error(e: extenddb_storage::error::StorageError) -
if let extenddb_storage::error::StorageError::Service(e) = e {
return create_table::service_err_to_dynamo(e);
}
tracing::error!(internal_error = %e, "storage internal error");
log_storage_fault!(e, "storage internal error");
DynamoDbError::InternalServerError("Internal server error".to_owned())
}

Expand Down Expand Up @@ -524,12 +528,19 @@ impl OperationContext {
/// Dispatch an operation by name.
///
/// Returns the JSON response body and sideband metrics for the metrics collector.
///
/// The server calls this inside the request scope
/// (`extenddb_storage::request_scope`), so everything reached from here on the
/// same task, including the storage backend and the error mappers, can read
/// the request id and operation. The trace event at entry, under the target
/// `extenddb_engine::dispatch`, is written inside that scope too.
pub async fn dispatch(
operation: &str,
body: serde_json::Value,
ctx: &OperationContext,
server_addr: &str,
) -> Result<DispatchResult, DynamoDbError> {
tracing::trace!(target: "extenddb_engine::dispatch", operation, "dispatch");
match operation {
"CreateTable" => handle_create_table(body, ctx)
.await
Expand Down
Loading
Loading