diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 65d703eaf..80157236d 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -878,7 +878,10 @@ async fn delete_catalog_backup( 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(), )); @@ -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( +pub(crate) async fn restore_table_from_backup_detached( storage: Arc, runtime: Arc, account_id: Arc, @@ -1195,13 +1198,21 @@ where F: FnOnce(Arc, String) -> Fut + Send + 'static, Fut: std::future::Future + Send, { - tokio::spawn(async move { - let (target_table_name, response) = - restore_table_from_backup(&storage, &runtime, &account_id, ®ion, &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, ®ion, &limits, &body) + .await?; + after(account_id, target_table_name).await; + Ok(response) + }, + )) .await .map_err(|e| { tracing::error!("RestoreTableFromBackup task failed: {e}"); @@ -1639,4 +1650,4 @@ pub mod store_identity; pub mod store_maintenance; pub mod sync; #[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/crates/engine/src/backup/restore.rs b/crates/engine/src/backup/restore.rs index 31cfedd58..820d1d6f3 100644 --- a/crates/engine/src/backup/restore.rs +++ b/crates/engine/src/backup/restore.rs @@ -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(), )) diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index ced9602e6..74163bb1e 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -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>, @@ -67,7 +67,7 @@ struct Fake { summaries: Mutex>, restore_error: Mutex>, /// Returned (once) by `restore_source` instead of the stored source. - source_error: Mutex>, + pub(crate) source_error: Mutex>, restores: Mutex>, /// The permits the legacy restore and create were handed, held as the /// backend would hold them for the job's life. @@ -1013,7 +1013,7 @@ fn unused() -> BoxedFuture<'static, Result> } /// The runtime the tests run with: four slots, no configured store. -fn runtime() -> BackupRuntime { +pub(crate) fn runtime() -> BackupRuntime { BackupRuntime::new(4) } @@ -1826,6 +1826,35 @@ fn runtime_on(mem: &Arc, 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, 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, problem: StoreProblem) -> BackupRuntime { diff --git a/crates/engine/src/backup_requests.rs b/crates/engine/src/backup_requests.rs index 267173ee4..fa2f201e4 100644 --- a/crates/engine/src/backup_requests.rs +++ b/crates/engine/src/backup_requests.rs @@ -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()) } } diff --git a/crates/engine/src/batch_write_item.rs b/crates/engine/src/batch_write_item.rs index fb2591e42..1211eff4e 100755 --- a/crates/engine/src/batch_write_item.rs +++ b/crates/engine/src/batch_write_item.rs @@ -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 { @@ -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)] diff --git a/crates/engine/src/batch_write_item/scripted.rs b/crates/engine/src/batch_write_item/scripted.rs index 687be8981..8eedc0720 100644 --- a/crates/engine/src/batch_write_item/scripted.rs +++ b/crates/engine/src/batch_write_item/scripted.rs @@ -256,6 +256,18 @@ pub(super) fn rejected(result: Result) -> 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) { + 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 { result.unwrap_or_else(|e| panic!("the batch must answer 200: {e:?}")) diff --git a/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs b/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs index 5a190d8e7..cbec6935f 100644 --- a/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs +++ b/crates/engine/src/batch_write_item/write_batch_deferral_tests.rs @@ -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 diff --git a/crates/engine/src/create_table.rs b/crates/engine/src/create_table.rs index 08325fdfb..7230a82f0 100755 --- a/crates/engine/src/create_table.rs +++ b/crates/engine/src/create_table.rs @@ -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 @@ -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 @@ -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) => { @@ -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), diff --git a/crates/engine/src/fault_log.rs b/crates/engine/src/fault_log.rs new file mode 100644 index 000000000..ee7e018f7 --- /dev/null +++ b/crates/engine/src/fault_log.rs @@ -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)+) + }; +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ae55ba3aa..ad3367116 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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 @@ -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)] @@ -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()) } @@ -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 { + tracing::trace!(target: "extenddb_engine::dispatch", operation, "dispatch"); match operation { "CreateTable" => handle_create_table(body, ctx) .await diff --git a/crates/engine/src/request_scope_log_tests.rs b/crates/engine/src/request_scope_log_tests.rs new file mode 100644 index 000000000..aa376bd71 --- /dev/null +++ b/crates/engine/src/request_scope_log_tests.rs @@ -0,0 +1,418 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The fault log line names the request it belongs to. Each engine mapping +//! arm that turns a `StorageError` into a redacted 500 or a retryable 503 +//! writes the line through `log_storage_fault!`, which reads the request id +//! and operation from the request scope the server sets around the request. +//! Inside a scope the two fields carry the request's values; outside one the +//! line carries neither. The macro expands at its call site, so each line +//! keeps the site's own target and level. The detached restore re-enters the +//! scope in its spawned task, so the store read its request makes there +//! names the request too. DeleteBackup's line for a catalog id that cannot +//! be read and BatchWriteItem's line for the requests a batch did not apply +//! go through the macro as well. + +use std::sync::{Arc, Mutex}; + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::error::StorageError; +use extenddb_storage::request_scope::{RequestScope, with_scope}; +use tracing::field::{Field, Visit}; +use tracing::{Event, Level, Subscriber}; +use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + +/// What the subscriber saw of one error- or warn-level event: the +/// `request_id` and `operation` fields (`None` when the field was not +/// recorded), the message, the event's static target and its level. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Seen { + request_id: Option, + operation: Option, + message: String, + target: String, + level: String, +} + +impl Visit for Seen { + fn record_str(&mut self, field: &Field, value: &str) { + match field.name() { + "request_id" => self.request_id = Some(value.to_owned()), + "operation" => self.operation = Some(value.to_owned()), + _ => {} + } + } + + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.message = format!("{value:?}"); + } + } +} + +#[derive(Default)] +struct Captured(Arc>>); + +impl Layer for Captured { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + if *event.metadata().level() <= Level::WARN { + let mut seen = Seen { + target: event.metadata().target().to_owned(), + level: event.metadata().level().to_string(), + ..Seen::default() + }; + event.record(&mut seen); + self.0.lock().unwrap().push(seen); + } + } +} + +/// Runs `f` under a fresh subscriber and returns every error and warn event +/// it logged. A second registered subscriber makes `tracing` compute a newly hit +/// callsite's interest from every registered subscriber, so a parallel test +/// with none cannot leave an error callsite disabled for this one. +fn error_events_during(f: impl FnOnce()) -> Vec { + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); + let captured = Captured::default(); + let events = Arc::clone(&captured.0); + let subscriber = tracing_subscriber::registry().with(captured); + let _guard = tracing::subscriber::set_default(subscriber); + f(); + events.lock().unwrap().clone() +} + +/// Runs `fut` under a fresh subscriber and returns every error and warn +/// event it logged, with the second subscriber of [`error_events_during`]. +async fn error_events_during_async(fut: F) -> Vec { + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); + let captured = Captured::default(); + let events = Arc::clone(&captured.0); + let subscriber = tracing_subscriber::registry().with(captured); + let _guard = tracing::subscriber::set_default(subscriber); + fut.await; + events.lock().unwrap().clone() +} + +fn scope() -> RequestScope { + RequestScope::new("req-0f2a".to_owned(), "CreateTable".to_owned()) +} + +/// A mapping arm: its name, the error that reaches it, the function, the +/// status the client gets, the message text and the level its line has +/// always carried, and the target of the module that owns the arm. +struct Site { + name: &'static str, + error: fn() -> StorageError, + map: fn(StorageError) -> DynamoDbError, + status: u16, + message: &'static str, + level: &'static str, + target: &'static str, +} + +fn internal() -> StorageError { + StorageError::Internal("driver text".to_owned()) +} + +/// Every engine arm that maps a `StorageError` to a redacted 500 or to a +/// retryable 503 and logs the fault. +fn sites() -> Vec { + vec![ + Site { + name: "create_table::storage_err_to_dynamo, Internal", + error: internal, + map: crate::create_table::storage_err_to_dynamo, + status: 500, + message: "storage internal error", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, IdempotentReplay", + error: || StorageError::IdempotentReplay, + map: crate::create_table::storage_err_to_dynamo, + status: 500, + message: "Unexpected idempotency error in generic error handler", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, AlreadyExists", + error: || StorageError::AlreadyExists("row text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 500, + message: "unexpected already-exists storage error", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, Transient", + error: || StorageError::Transient("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "transient storage error", + level: "WARN", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, SnapshotExpired", + error: || StorageError::SnapshotExpired("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "storage snapshot expired", + level: "WARN", + target: "extenddb_engine::create_table", + }, + Site { + name: "create_table::storage_err_to_dynamo, Connection", + error: || StorageError::Connection("driver text".to_owned()), + map: crate::create_table::storage_err_to_dynamo, + status: 503, + message: "storage connection error", + level: "ERROR", + target: "extenddb_engine::create_table", + }, + Site { + name: "backup_requests::storage_err_to_dynamo", + error: internal, + map: crate::backup_requests::storage_err_to_dynamo, + status: 500, + message: "backup storage error", + level: "ERROR", + target: "extenddb_engine::backup_requests", + }, + Site { + name: "update_table::update_table_err_to_dynamo", + error: internal, + map: |e| crate::update_table::update_table_err_to_dynamo(e, "t"), + status: 500, + message: "storage internal error", + level: "ERROR", + target: "extenddb_engine::update_table", + }, + Site { + name: "streams::storage_to_dynamo", + error: internal, + map: crate::streams::storage_to_dynamo, + status: 500, + message: "storage internal error", + level: "ERROR", + target: "extenddb_engine::streams", + }, + Site { + name: "ttl::storage_to_dynamo", + error: internal, + map: crate::ttl::storage_to_dynamo, + status: 500, + message: "storage internal error", + level: "ERROR", + target: "extenddb_engine::ttl", + }, + Site { + name: "sanitize_storage_error", + error: internal, + map: crate::sanitize_storage_error, + status: 500, + message: "storage internal error", + level: "ERROR", + target: "extenddb_engine", + }, + ] +} + +#[tokio::test] +async fn the_fault_line_names_the_request_inside_a_scope_at_every_site() { + for site in sites() { + let logged = with_scope(scope(), async { + error_events_during(|| { + let err = (site.map)((site.error)()); + assert_eq!(err.status_code(), site.status, "{}", site.name); + }) + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-0f2a".to_owned()), + operation: Some("CreateTable".to_owned()), + message: site.message.to_owned(), + target: site.target.to_owned(), + level: site.level.to_owned(), + }], + "{}: the fault line did not carry the scope's request id and operation", + site.name + ); + } +} + +#[tokio::test] +async fn the_fault_line_carries_no_request_fields_outside_a_scope_at_every_site() { + for site in sites() { + let logged = error_events_during(|| { + let err = (site.map)((site.error)()); + assert_eq!(err.status_code(), site.status, "{}", site.name); + }); + assert_eq!( + logged, + vec![Seen { + request_id: None, + operation: None, + message: site.message.to_owned(), + target: site.target.to_owned(), + level: site.level.to_owned(), + }], + "{}: a fault outside a request carried a request id or operation", + site.name + ); + } +} + +/// Runs `fut` inside a scope for `request_id` and `operation` under a fresh +/// subscriber and returns the error and warn lines written meanwhile. +async fn scoped_fault_lines( + request_id: &str, + operation: &str, + fut: F, +) -> Vec { + with_scope( + RequestScope::new(request_id.to_owned(), operation.to_owned()), + error_events_during_async(fut), + ) + .await +} + +/// Runs `RestoreTableFromBackup` through its detached entry point inside a +/// scope for `request_id`, checks that the client gets a redacted 500, and +/// returns the error and warn lines written meanwhile. +async fn detached_restore_fault_lines( + backups: Arc, + runtime: crate::backup::BackupRuntime, + body: serde_json::Value, + request_id: &str, +) -> Vec { + let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); + scoped_fault_lines(request_id, "RestoreTableFromBackup", async { + let result = crate::backup::restore_table_from_backup_detached( + backups, + Arc::new(runtime), + Arc::from("123456789012"), + Arc::from("us-east-1"), + limits, + body, + |_, _| async {}, + ) + .await; + assert!(matches!(result, Err(DynamoDbError::InternalServerError(_)))); + }) + .await +} + +/// `RestoreTableFromBackup` runs its restore in a task of its own. The task +/// does not inherit the request scope, so the engine carries it across; the +/// `backup storage error` line written inside the task names the request. +#[tokio::test] +async fn the_detached_restore_carries_the_scope_into_its_task() { + let body = serde_json::json!({ + "BackupArn": "arn:aws:dynamodb:us-east-1:123456789012:table/src/backup/01700000000000-abcdef12", + "TargetTableName": "restored", + }); + // A backup engine whose source lookup fails with a storage fault. It has + // no catalog row for the ARN, so the restore reads the source next. + let backups = crate::backup::tests::Fake::default(); + *backups.source_error.lock().unwrap() = Some(internal()); + let logged = detached_restore_fault_lines( + Arc::new(backups), + crate::backup::tests::runtime(), + body, + "req-restore", + ) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-restore".to_owned()), + operation: Some("RestoreTableFromBackup".to_owned()), + message: "backup storage error".to_owned(), + target: "extenddb_engine::backup_requests".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the failed source lookup, naming the request" + ); +} + +/// Inside the same task, the restore request reads the manifest's checksum +/// sidecar and the manifest from the backup store. A read that fails answers +/// the client a redacted 500, and its line names the request. +#[tokio::test] +async fn the_restore_tasks_failed_store_read_names_the_request() { + let (backups, runtime, body) = crate::backup::tests::restore_from_an_unreadable_store(); + let logged = detached_restore_fault_lines(backups, runtime, body, "req-store").await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-store".to_owned()), + operation: Some("RestoreTableFromBackup".to_owned()), + message: "backup arn:aws:dynamodb:us-east-1:123456789012:table/Music/backup/\ + 01791976431438-73d8d5bc: reading extenddb-manifest.sha256 from the store \ + failed" + .to_owned(), + target: "extenddb_engine::backup::restore".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the failed store read, naming the request" + ); +} + +/// DeleteBackup runs its deletion fence on the request task. When the +/// catalog's id cannot be read, the client gets a redacted 500 and the line +/// names the request. +#[tokio::test] +async fn the_delete_backup_line_for_an_unreadable_catalog_names_the_request() { + let logged = scoped_fault_lines("req-delete", "DeleteBackup", async { + let err = crate::backup::tests::delete_backup_with_an_unreadable_catalog().await; + assert!( + matches!(err, DynamoDbError::InternalServerError(_)), + "{err:?}" + ); + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-delete".to_owned()), + operation: Some("DeleteBackup".to_owned()), + message: "DeleteBackup arn:aws:dynamodb:us-east-1:123456789012:table/Music/backup/\ + 01791976431438-73d8d5bc: the catalog id could not be read" + .to_owned(), + target: "extenddb_engine::backup".to_owned(), + level: "ERROR".to_owned(), + }], + "one fault line for the catalog id that could not be read, naming the request" + ); +} + +/// A BatchWriteItem whose first write meets a connection error applies +/// nothing and answers 503. Its one line, at warn level, names the request. +#[tokio::test] +async fn the_batch_write_item_line_for_a_batch_that_applied_nothing_names_the_request() { + let logged = scoped_fault_lines("req-batch", "BatchWriteItem", async { + let (err, _) = + crate::batch_write_item::scripted::batch_that_applies_nothing_after_a_connection_error( + ) + .await; + assert_eq!(err.status_code(), 503, "{err:?}"); + }) + .await; + assert_eq!( + logged, + vec![Seen { + request_id: Some("req-batch".to_owned()), + operation: Some("BatchWriteItem".to_owned()), + message: "BatchWriteItem: 2 request(s) of the batch not applied; no request applied \ + and the batch answers 503" + .to_owned(), + target: "extenddb_engine::batch_write_item".to_owned(), + level: "WARN".to_owned(), + }], + "one warn line for the batch that applied nothing, naming the request" + ); +} diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 0a7759cc9..febb418bc 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -546,7 +546,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { StorageError::TableNotFound(name) => DynamoDbError::ResourceNotFoundException(name), StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index 2ee75d209..2eeab60a0 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -233,7 +233,7 @@ pub(crate) fn storage_to_dynamo(e: StorageError) -> DynamoDbError { } StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index f397a29e9..c30b1193c 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -393,7 +393,7 @@ pub(crate) fn update_table_err_to_dynamo( StorageError::IndexesInUse(msg) => DynamoDbError::ResourceInUseException(msg), StorageError::Service(e) => crate::create_table::service_err_to_dynamo(e), other => { - tracing::error!(internal_error = %other, "storage internal error"); + log_storage_fault!(other, "storage internal error"); DynamoDbError::InternalServerError("Internal server error".to_owned()) } } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 1ec5be2ab..1c26bd3f7 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -2,8 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 //! Main `DynamoDB` request handler with per-segment latency instrumentation. -//! -//! Extracted from `lib.rs` to keep both files under the 500-line limit. use std::sync::Arc; @@ -97,12 +95,217 @@ pub(crate) async fn handle_request( Err(e) => return error_response(&e, &request_id), }; - // --- Auth segment --- - let auth_start = std::time::Instant::now(); - let identity = match state.auth.authenticate(&headers, &body).await { - Ok(id) => id, + // --- Authentication through dispatch, inside the request scope --- + // The scope carries the request id and operation (and the two SDK + // correlation headers when the client sent them) to every storage read + // the request makes and to the engine's error mappers, so a fault log line + // can name the x-amzn-RequestId the client received. The early returns + // above touch no storage and the response building below runs outside it. + let Served { + account_id, + table_name, + metric_table, + partition_value, + batch_entries, + dispatch_result, + auth_us, + authz_us, + throttle_us, + dispatch_us, + } = match extenddb_storage::request_scope::with_scope( + request_scope_for(&request_id, &operation, &headers), + serve_request( + &state, + &headers, + &body, + peer_addr, + &request_id, + &operation, + request, + ), + ) + .await + { + Ok(served) => served, Err(e) => return error_response(&e, &request_id), }; + + // --- Response segment --- + let response_start = std::time::Instant::now(); + let mut succeeded = false; + let response = match dispatch_result { + Ok(result) => { + update_throttle_buckets( + &state.throttle, + &operation, + &account_id, + table_name.as_deref(), + &result.body, + ); + // A batch a backend served partially is a throttle the server's own + // bucket never saw; count it so the metrics do not read as zero. + record_partial_batch_throttle( + &state.metrics, + &account_id, + &operation, + &result.metrics.throttled_tables, + ); + + let m = &result.metrics; + if let Some(ref tn) = metric_table { + if m.read_capacity_units > 0.0 { + state.metrics.record( + extenddb_core::metrics::MetricName::ConsumedReadCapacityUnits, + m.read_capacity_units, + Some(&account_id), + Some(tn), + m.index_name.as_deref(), + Some(&operation), + ); + } + if m.write_capacity_units > 0.0 { + state.metrics.record( + extenddb_core::metrics::MetricName::ConsumedWriteCapacityUnits, + m.write_capacity_units, + Some(&account_id), + Some(tn), + m.index_name.as_deref(), + Some(&operation), + ); + } + if m.returned_item_count > 0 { + state.metrics.record_returned_items( + &account_id, + tn, + &operation, + m.returned_item_count, + ); + } + if m.returned_bytes > 0 { + state.metrics.record_returned_bytes( + &account_id, + tn, + &operation, + m.returned_bytes, + ); + } + } + // Throttle buckets stay keyed by the name the request sent, which + // is the name they were registered under above. + if let Some(ref tn) = table_name { + state.throttle.consume_with_partition( + &account_id, + tn, + m.read_capacity_units, + m.write_capacity_units, + partition_value.as_deref(), + ); + } + + succeeded = true; + success_response(&result.body, &request_id) + } + Err(e) => { + record_error_metrics( + &state.metrics, + &e, + &account_id, + metric_table.as_deref(), + &operation, + ); + // A throttle error from a batch is the engine's answer to a batch + // whose every entry a backend throttled: each entry is a throttle + // event, as on a 200. A throttle the backend reports on the catalog + // read also comes out as the batch's throttle error and counts every + // entry; the service has no such failure. + if e.is_throttle() + && let Some(entries) = &batch_entries + { + record_partial_batch_throttle(&state.metrics, &account_id, &operation, entries); + } + error_response(&e, &request_id) + } + }; + #[allow(clippy::cast_precision_loss)] + let response_us = response_start.elapsed().as_micros() as f64; + + // Record per-segment latency breakdown and total latency. + #[allow(clippy::cast_precision_loss)] + let total_us = handler_start.elapsed().as_micros() as f64; + // `SuccessfulRequestLatency` counts successful requests only, as + // CloudWatch's does. + if succeeded { + state + .metrics + .record_latency(&account_id, metric_table.as_deref(), &operation, total_us); + } + state.metrics.record_request_count(&account_id, &operation); + state.metrics.record_segments( + &account_id, + &operation, + metric_table.as_deref(), + extenddb_core::metrics::LatencySegments { + auth_us, + authz_us, + throttle_us, + dispatch_us, + response_us, + total_us, + }, + ); + + // P79: Request-level trace logging. + tracing::debug!( + request_id = %request_id, + operation = %operation, + table = table_name.as_deref().unwrap_or("-"), + auth_us = auth_us, + authz_us = authz_us, + throttle_us = throttle_us, + dispatch_us = dispatch_us, + response_us = response_us, + total_us = total_us, + "request complete" + ); + + response +} + +/// What the request produced between authentication and the end of dispatch: +/// the dispatch result and what the response segment needs to account for it. +struct Served { + account_id: Arc, + table_name: Option, + metric_table: Option, + partition_value: Option, + /// The entries of a batch by table, for the throttle events of a batch + /// whose every entry a backend throttled; `None` for any other request. + batch_entries: Option>, + dispatch_result: Result, + auth_us: f64, + authz_us: f64, + throttle_us: f64, + dispatch_us: f64, +} + +/// Authenticate, authorize, throttle and dispatch one request. Every storage +/// read the request makes happens here, so `handle_request` runs this whole +/// future inside the request scope. A refusal before dispatch returns `Err`; +/// a dispatch error is inside `Served::dispatch_result`, because the response +/// segment accounts for it differently. +#[allow(clippy::too_many_lines)] // sequential request pipeline +async fn serve_request( + state: &Arc, + headers: &HeaderMap, + body: &Bytes, + peer_addr: std::net::SocketAddr, + request_id: &str, + operation: &str, + request: extenddb_engine::ParsedRequest<'_>, +) -> Result { + // --- Auth segment --- + let auth_start = std::time::Instant::now(); + let identity = state.auth.authenticate(headers, body).await?; #[allow(clippy::cast_precision_loss)] let auth_us = auth_start.elapsed().as_micros() as f64; @@ -126,9 +329,9 @@ pub(crate) async fn handle_request( principal = crate::authz_resource::cross_account::principal_arn(&identity), "Point-in-time recovery refused" ); - record_error_metrics(&state.metrics, &e, &account_id, None, &operation); - state.metrics.record_request_count(&account_id, &operation); - return error_response(&e, &request_id); + record_error_metrics(&state.metrics, &e, &account_id, None, operation); + state.metrics.record_request_count(&account_id, operation); + return Err(e); } }; @@ -139,12 +342,9 @@ pub(crate) async fn handle_request( { if state.catalog_store.is_none() { tracing::error!("Authorization required but catalog_store is not configured"); - return error_response( - &DynamoDbError::AccessDeniedException( - "User: is not authorized to perform this operation".to_owned(), - ), - &request_id, - ); + return Err(DynamoDbError::AccessDeniedException( + "User: is not authorized to perform this operation".to_owned(), + )); } // aws:SourceIp is the connection peer address; aws:UserAgent is the // User-Agent header. Behind a proxy only the peer address is trusted, @@ -154,23 +354,19 @@ pub(crate) async fn handle_request( .get("user-agent") .and_then(|v| v.to_str().ok()) .map(ToOwned::to_owned); - match authorize_request( - &state, + authorized_key_info = authorize_request( + state, &identity, &input, - &operation, + operation, &account_id, Some(source_ip.as_str()), user_agent.as_deref(), ) - .await - { - Ok(ki) => authorized_key_info = ki, - Err(e) => return error_response(&e, &request_id), - } + .await?; // The engine authorizes each PartiQL statement through it. item_authorizer = - crate::item_authz::for_request(&state, identity, &account_id, source_ip, user_agent); + crate::item_authz::for_request(state, identity, &account_id, source_ip, user_agent); } #[allow(clippy::cast_precision_loss)] let authz_us = authz_start.elapsed().as_micros() as f64; @@ -197,12 +393,12 @@ pub(crate) async fn handle_request( // when the operation acts on the table it names and the name passes the // table name rules, with a table ARN reduced to its name. See // `metric_table_name`. - let metric_table = metric_table_name(&operation, &input, &state.limits); + let metric_table = metric_table_name(operation, &input, &state.limits); // --- Throttle segment --- let throttle_start = std::time::Instant::now(); - let (is_read_op, is_write_op) = classify_data_operation(&operation); - let partition_value = extract_partition_value(&input, &operation); + let (is_read_op, is_write_op) = classify_data_operation(operation); + let partition_value = extract_partition_value(&input, operation); // A name the table name rules refuse (length or pattern), and the ARN of // a table in another Region, are not throttled: the engine answers them // as it does with capacity left. The service refuses such a name before @@ -255,7 +451,7 @@ pub(crate) async fn handle_request( Some(&ctx.account_id), metric_table.as_deref(), None, - Some(&operation), + Some(operation), ); state.metrics.record( extenddb_core::metrics::MetricName::ThrottledRequests, @@ -263,7 +459,7 @@ pub(crate) async fn handle_request( Some(&ctx.account_id), metric_table.as_deref(), None, - Some(&operation), + Some(operation), ); // The service names the throttled resource and the limit on a // throttle: one reason with the table ARN, the same string @@ -272,10 +468,7 @@ pub(crate) async fn handle_request( // billing mode. let table_arn = extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name); - return error_response( - &throttle_error(cause, throttled_read, &table_arn), - &request_id, - ); + return Err(throttle_error(cause, throttled_read, &table_arn)); } } #[allow(clippy::cast_precision_loss)] @@ -285,14 +478,14 @@ pub(crate) async fn handle_request( // The entries of a batch, for the throttle events of a batch whose every // entry a backend throttled: the engine answers that one with the error // alone (`input` moves into the dispatch). - let batch_entries = batch_entry_counts(&operation, &input); + let batch_entries = batch_entry_counts(operation, &input); let dispatch_start = std::time::Instant::now(); let dispatch_result = - extenddb_engine::dispatch(&operation, input, &ctx, &state.server_addr).await; + extenddb_engine::dispatch(operation, input, &ctx, &state.server_addr).await; #[allow(clippy::cast_precision_loss)] let dispatch_us = dispatch_start.elapsed().as_micros() as f64; // P120c: Record storage query metrics for the request's dispatch phase. - let category = match operation.as_str() { + let category = match operation { "CreateTable" | "DeleteTable" | "DescribeTable" @@ -316,151 +509,55 @@ pub(crate) async fn handle_request( dispatch_us, ); - // --- Response segment --- - let response_start = std::time::Instant::now(); - let mut succeeded = false; - let response = match dispatch_result { - Ok(result) => { - update_throttle_buckets( - &state.throttle, - &operation, - &ctx.account_id, - table_name.as_deref(), - &result.body, - ); - // A batch a backend served partially is a throttle the server's own - // bucket never saw; count it so the metrics do not read as zero. - record_partial_batch_throttle( - &state.metrics, - &ctx.account_id, - &operation, - &result.metrics.throttled_tables, - ); - - let m = &result.metrics; - if let Some(ref tn) = metric_table { - if m.read_capacity_units > 0.0 { - state.metrics.record( - extenddb_core::metrics::MetricName::ConsumedReadCapacityUnits, - m.read_capacity_units, - Some(&ctx.account_id), - Some(tn), - m.index_name.as_deref(), - Some(&operation), - ); - } - if m.write_capacity_units > 0.0 { - state.metrics.record( - extenddb_core::metrics::MetricName::ConsumedWriteCapacityUnits, - m.write_capacity_units, - Some(&ctx.account_id), - Some(tn), - m.index_name.as_deref(), - Some(&operation), - ); - } - if m.returned_item_count > 0 { - state.metrics.record_returned_items( - &ctx.account_id, - tn, - &operation, - m.returned_item_count, - ); - } - if m.returned_bytes > 0 { - state.metrics.record_returned_bytes( - &ctx.account_id, - tn, - &operation, - m.returned_bytes, - ); - } - } - // Throttle buckets stay keyed by the name the request sent, which - // is the name they were registered under above. - if let Some(ref tn) = table_name { - state.throttle.consume_with_partition( - &ctx.account_id, - tn, - m.read_capacity_units, - m.write_capacity_units, - partition_value.as_deref(), - ); - } - - succeeded = true; - success_response(&result.body, &request_id) - } - Err(e) => { - record_error_metrics( - &state.metrics, - &e, - &ctx.account_id, - metric_table.as_deref(), - &operation, - ); - // A throttle error from a batch is the engine's answer to a batch - // whose every entry a backend throttled: each entry is a throttle - // event, as on a 200. A throttle the backend reports on the catalog - // read also comes out as the batch's throttle error and counts every - // entry; the service has no such failure. - if e.is_throttle() - && let Some(entries) = &batch_entries - { - record_partial_batch_throttle(&state.metrics, &ctx.account_id, &operation, entries); - } - error_response(&e, &request_id) - } - }; - #[allow(clippy::cast_precision_loss)] - let response_us = response_start.elapsed().as_micros() as f64; + Ok(Served { + account_id: ctx.account_id, + table_name, + metric_table, + partition_value, + batch_entries, + dispatch_result, + auth_us, + authz_us, + throttle_us, + dispatch_us, + }) +} - // Record per-segment latency breakdown and total latency. - #[allow(clippy::cast_precision_loss)] - let total_us = handler_start.elapsed().as_micros() as f64; - // `SuccessfulRequestLatency` counts successful requests only, as - // CloudWatch's does. - if succeeded { - state.metrics.record_latency( - &ctx.account_id, - metric_table.as_deref(), - &operation, - total_us, - ); - } - state - .metrics - .record_request_count(&ctx.account_id, &operation); - state.metrics.record_segments( - &ctx.account_id, - &operation, - metric_table.as_deref(), - extenddb_core::metrics::LatencySegments { - auth_us, - authz_us, - throttle_us, - dispatch_us, - response_us, - total_us, - }, - ); +/// The scope the request runs inside from authentication through dispatch: +/// the request id the response will carry in `x-amzn-RequestId`, the +/// operation from `X-Amz-Target`, and the two SDK correlation headers when the +/// client sent them. Cost: two `String` clones per request plus the header +/// copies. +fn request_scope_for( + request_id: &str, + operation: &str, + headers: &HeaderMap, +) -> extenddb_storage::RequestScope { + extenddb_storage::RequestScope::new(request_id.to_owned(), operation.to_owned()) + .with_sdk_headers( + header_string(headers, "amz-sdk-invocation-id"), + header_string(headers, "amz-sdk-request"), + ) +} - // P79: Request-level trace logging. - tracing::debug!( - request_id = %request_id, - operation = %operation, - table = table_name.as_deref().unwrap_or("-"), - auth_us = auth_us, - authz_us = authz_us, - throttle_us = throttle_us, - dispatch_us = dispatch_us, - response_us = response_us, - total_us = total_us, - "request complete" - ); +/// The longest SDK correlation header value the scope carries. The SDKs send +/// a UUID and a short attempt counter; a longer value is read as absent, so a +/// client cannot place arbitrary text of any length in a backend's log line. +const MAX_SDK_HEADER_LEN: usize = 256; - response +/// The value of header `name` as an owned string, or `None` when the header is +/// absent, holds a byte outside printable ASCII (space through tilde) and tab, +/// or is longer than [`MAX_SDK_HEADER_LEN`]. A header value cannot hold CR or +/// LF, so a value that reads as present cannot split a log line. +fn header_string(headers: &HeaderMap, name: &str) -> Option { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .filter(|s| s.len() <= MAX_SDK_HEADER_LEN) + .map(str::to_owned) } +#[cfg(test)] +mod request_scope_tests; #[cfg(test)] mod throttle_wire_tests; diff --git a/crates/server/src/handler/request_scope_tests.rs b/crates/server/src/handler/request_scope_tests.rs new file mode 100644 index 000000000..44464e438 --- /dev/null +++ b/crates/server/src/handler/request_scope_tests.rs @@ -0,0 +1,286 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The request scope the handler sets from authentication through dispatch. +//! Three tests drive a request through `handle_request` against an in-memory +//! engine: one checks the bounds (no scope on the task before the request, +//! none after the response, none at the `request complete` event the response +//! segment writes); one reads the scope current when the auth provider runs, +//! the first call inside the span; one reads it at the engine's dispatch entry +//! event, the last segment inside the span, and checks it carries the request +//! id the response returned in `x-amzn-RequestId`, the operation and both SDK +//! correlation headers. The remaining tests check `request_scope_for` and +//! `header_string` on their own. That every `.await` reached inside the span +//! sees the scope, including the engine's error mappers and the detached +//! restore, is tested in the storage crate (`request_scope`) and the engine +//! crate (`request_scope_log_tests`). + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::State; +use axum::http::HeaderMap; +use extenddb_auth::{AuthIdentity, AuthProvider}; +use extenddb_core::error::DynamoDbError; +use extenddb_storage::request_scope::{RequestScope, current}; +use tracing::{Event, Subscriber}; +use tracing_subscriber::layer::{Context, Layer, SubscriberExt}; + +use super::throttle_wire_tests::{build_state, build_state_with}; +use super::{MAX_SDK_HEADER_LEN, header_string, request_scope_for}; +use crate::AppState; + +/// Records the scope current on the task at two events: the engine's dispatch +/// entry (target `extenddb_engine::dispatch`, the last segment inside the +/// span) and the handler's `request complete` (the response segment, outside +/// the span). +#[derive(Default)] +struct ScopeAtEvents { + at_dispatch: Arc>>>, + at_complete: Arc>>>, +} + +impl Layer for ScopeAtEvents { + fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) { + if event.metadata().target() == "extenddb_engine::dispatch" { + self.at_dispatch.lock().unwrap().push(current()); + return; + } + let mut message = Message::default(); + event.record(&mut message); + if message.0 == "request complete" { + self.at_complete.lock().unwrap().push(current()); + } + } +} + +#[derive(Default)] +struct Message(String); + +impl tracing::field::Visit for Message { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.0 = format!("{value:?}"); + } + } +} + +/// An auth provider that records the scope current when it runs, then answers +/// with the default account like the fixture's stub. +struct ScopeAtAuth { + account_id: String, + seen: Arc>>>, +} + +#[async_trait::async_trait] +impl AuthProvider for ScopeAtAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + _body: &[u8], + ) -> Result { + self.seen.lock().unwrap().push(current()); + Ok(AuthIdentity::User { + account_id: self.account_id.clone(), + user_name: "dev".to_owned(), + }) + } +} + +const INVOCATION_ID: &str = "11111111-2222-3333-4444-555555555555"; +const SDK_REQUEST: &str = "attempt=2; max=4"; + +async fn fire( + state: Arc, + operation: &str, + body: &'static str, + extra: &[(&'static str, &str)], +) -> (u16, String) { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + format!("DynamoDB_20120810.{operation}") + .parse() + .expect("target header"), + ); + for (name, value) in extra { + headers.insert(*name, value.parse().expect("header value")); + } + let response = super::handle_request( + State(state), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40001))), + headers, + Ok(Bytes::from(body)), + ) + .await; + let status = response.status().as_u16(); + let request_id = response + .headers() + .get("x-amzn-requestid") + .and_then(|v| v.to_str().ok()) + .expect("response carries x-amzn-RequestId") + .to_owned(); + (status, request_id) +} + +fn expect_scope(seen: &Option, request_id: &str, operation: &str) { + let scope = seen + .as_ref() + .expect("the segment ran inside the request scope"); + assert_eq!(scope.request_id, request_id); + assert_eq!(scope.operation, operation); + assert_eq!(scope.sdk_invocation_id.as_deref(), Some(INVOCATION_ID)); + assert_eq!(scope.sdk_request.as_deref(), Some(SDK_REQUEST)); +} + +#[tokio::test] +async fn no_scope_on_the_task_before_the_request_or_after_the_response() { + assert_eq!(current(), None, "ambient scope before the request"); + let (state, _) = build_state().await; + let (status, _) = fire(state, "ListTables", "{}", &[]).await; + assert_eq!(status, 200); + assert_eq!(current(), None, "the scope leaked past the handler"); +} + +#[tokio::test] +async fn the_scope_is_current_when_the_auth_provider_runs() { + let seen = Arc::new(Mutex::new(Vec::new())); + let recorded = Arc::clone(&seen); + let (state, _) = build_state_with(None, move |account_id| { + Arc::new(ScopeAtAuth { + account_id, + seen: recorded, + }) + }) + .await; + + let (status, request_id) = fire( + state, + "ListTables", + "{}", + &[ + ("amz-sdk-invocation-id", INVOCATION_ID), + ("amz-sdk-request", SDK_REQUEST), + ], + ) + .await; + assert_eq!(status, 200); + + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 1, "one authenticate call per request"); + expect_scope(&seen[0], &request_id, "ListTables"); +} + +#[tokio::test] +async fn the_scope_is_current_at_dispatch_entry_and_gone_at_request_complete() { + let (state, _) = build_state().await; + // While only one subscriber is registered, `tracing` computes a newly hit + // callsite's interest from the hitting thread's own subscriber and caches + // it, so a parallel test with none that first hits `request complete` or + // the dispatch entry event leaves it disabled for this test. A second + // registered subscriber makes `tracing` compute the interest from every + // registered subscriber, this test's included. + let _second = tracing::Dispatch::new(tracing_subscriber::registry()); + let layer = ScopeAtEvents::default(); + let at_dispatch = Arc::clone(&layer.at_dispatch); + let at_complete = Arc::clone(&layer.at_complete); + let subscriber = tracing_subscriber::registry().with(layer); + let _guard = tracing::subscriber::set_default(subscriber); + + let (status, request_id) = fire( + state, + "ListTables", + "{}", + &[ + ("amz-sdk-invocation-id", INVOCATION_ID), + ("amz-sdk-request", SDK_REQUEST), + ], + ) + .await; + assert_eq!(status, 200); + + let at_dispatch = at_dispatch.lock().unwrap(); + assert_eq!(at_dispatch.len(), 1, "one dispatch entry event per request"); + expect_scope(&at_dispatch[0], &request_id, "ListTables"); + + // The response segment runs outside the span: the `request complete` + // event it writes sees no scope. + let at_complete = at_complete.lock().unwrap(); + assert_eq!( + at_complete.as_slice(), + &[None], + "the scope reached the response segment" + ); +} + +#[test] +fn the_scope_carries_the_request_id_operation_and_both_sdk_headers() { + let mut headers = HeaderMap::new(); + headers.insert( + "amz-sdk-invocation-id", + INVOCATION_ID.parse().expect("header value"), + ); + headers.insert( + "amz-sdk-request", + SDK_REQUEST.parse().expect("header value"), + ); + + let scope = request_scope_for("req-7c1d", "PutItem", &headers); + + assert_eq!(scope.request_id, "req-7c1d"); + assert_eq!(scope.operation, "PutItem"); + assert_eq!(scope.sdk_invocation_id.as_deref(), Some(INVOCATION_ID)); + assert_eq!(scope.sdk_request.as_deref(), Some(SDK_REQUEST)); +} + +#[test] +fn the_sdk_headers_are_absent_from_the_scope_when_the_client_sent_none() { + let scope = request_scope_for("req-9a0b", "Query", &HeaderMap::new()); + + assert_eq!(scope.request_id, "req-9a0b"); + assert_eq!(scope.operation, "Query"); + assert_eq!(scope.sdk_invocation_id, None); + assert_eq!(scope.sdk_request, None); +} + +#[test] +fn a_header_reads_as_absent_unless_it_is_printable_ascii_or_tab() { + let mut headers = HeaderMap::new(); + headers.insert( + "amz-sdk-request", + axum::http::HeaderValue::from_bytes(&[0xff, 0xfe]).expect("opaque header bytes"), + ); + // `HeaderValue::to_str` accepts printable ASCII (space through tilde) and + // tab only; a byte above 0x7e is refused, so a value with an accented + // letter also reads as absent. + headers.insert( + "amz-sdk-invocation-id", + axum::http::HeaderValue::from_bytes("caf\u{e9}".as_bytes()).expect("utf8 header bytes"), + ); + assert_eq!(header_string(&headers, "amz-sdk-request"), None); + assert_eq!(header_string(&headers, "amz-sdk-invocation-id"), None); + // A space and a tab are within what `to_str` accepts, so the value reads + // as sent. + headers.insert("amz-sdk-request", "a\tb c".parse().expect("header value")); + assert_eq!( + header_string(&headers, "amz-sdk-request").as_deref(), + Some("a\tb c") + ); +} + +#[test] +fn a_header_longer_than_the_cap_reads_as_absent() { + let mut headers = HeaderMap::new(); + let at_cap = "a".repeat(MAX_SDK_HEADER_LEN); + let over_cap = "a".repeat(MAX_SDK_HEADER_LEN + 1); + headers.insert( + "amz-sdk-invocation-id", + at_cap.parse().expect("header value"), + ); + headers.insert("amz-sdk-request", over_cap.parse().expect("header value")); + assert_eq!( + header_string(&headers, "amz-sdk-invocation-id").as_deref(), + Some(at_cap.as_str()) + ); + assert_eq!(header_string(&headers, "amz-sdk-request"), None); +} diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 2fdaf598b..737998054 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -56,15 +56,23 @@ fn cache_cfg(name: &'static str) -> extenddb_cache::SwrCacheConfig { /// catalog, the stub auth bound to the default account, throttling on, and /// `dev_mode` on. Returns the state and the account id the stub answers with, /// so the expected ARN can be formed. -async fn build_state() -> (Arc, String) { - build_state_on(None).await +pub(super) async fn build_state() -> (Arc, String) { + build_state_with(None, stub_auth).await +} + +/// The stub auth provider bound to `account_id`: `build_state`'s provider, +/// and the one for a test that replaces the storage but not the auth. +pub(super) fn stub_auth(account_id: String) -> Arc { + Arc::new(StubAuth { account_id }) } /// `build_state` with `storage`, when given, in place of the SQLite engine -/// for the table and item calls. The catalog and the authorization stores -/// stay on SQLite. -async fn build_state_on( +/// for the table and item calls (the catalog and the authorization stores +/// stay on SQLite), and with the auth provider built by `auth` from the +/// bootstrapped default account id, for a test that needs its own provider. +pub(super) async fn build_state_with( storage: Option>, + auth: impl FnOnce(String) -> Arc, ) -> (Arc, String) { let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); let config = extenddb_storage_sqlite::SqliteConfig { @@ -111,9 +119,7 @@ async fn build_state_on( let state = Arc::new(AppState { storage: engine, backup_runtime: Arc::new(extenddb_engine::BackupRuntime::new(1)), - auth: Arc::new(StubAuth { - account_id: account_id.clone(), - }), + auth: auth(account_id.clone()), throttle, limits, region: Arc::from("us-east-1"), @@ -136,7 +142,7 @@ async fn build_state_on( (state, account_id) } -async fn call(state: &Arc, operation: &str, body: Value) -> (u16, Value) { +pub(super) async fn call(state: &Arc, operation: &str, body: Value) -> (u16, Value) { let mut headers = HeaderMap::new(); headers.insert( "x-amz-target", @@ -533,7 +539,7 @@ async fn a_batch_a_backend_throttled_records_the_throttle_metrics() { let store = failing_store::FailingStore::throttling() .with_items(&["k1", "k2", "k3"]) .failing_on(&["k2", "k3"]); - let (state, account_id) = build_state_on(Some(Arc::new(store))).await; + let (state, account_id) = build_state_with(Some(Arc::new(store)), stub_auth).await; let (got, body) = call(&state, operation, request).await; assert_eq!(got, status, "{operation}: {body}"); for (metric, want) in [ diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 7580c0bc1..fcce6966c 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -37,6 +37,7 @@ pub mod migrations; pub mod operations; pub mod password; pub mod policy_migration; +pub mod request_scope; pub mod restore_engine; pub mod secret_cipher; pub mod secret_keys; @@ -61,6 +62,7 @@ pub use backup_catalog::{ pub use backup_definition::{ BackupRestoreSource, RestoreRequest, RestoreSource, RestoreTableOverrides, }; +pub use request_scope::RequestScope; pub use restore_engine::{BulkLoadFile, Finished, RestoreEngine}; pub use snapshot::{SnapshotEngine, SnapshotInfo, TableSnapshot}; diff --git a/crates/storage/src/request_scope.rs b/crates/storage/src/request_scope.rs new file mode 100644 index 000000000..57ce390b6 --- /dev/null +++ b/crates/storage/src/request_scope.rs @@ -0,0 +1,229 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Request-scoped correlation data for storage backends and the engine. +//! +//! The server sets a [`RequestScope`] from the start of authentication to the +//! end of dispatch for each client request. A storage backend or an engine +//! error mapper running inside that span reads it with [`current`] or +//! [`with_current`] to put the request id the client received in +//! `x-amzn-RequestId` on its own log lines. +//! +//! The scope is a Tokio task-local. It is visible to every `.await` reached +//! inline on the request's task, including nested and boxed futures. A task +//! started with `tokio::spawn` or `spawn_blocking` does not inherit it, so +//! [`current`] returns `None` there, as it does in queue workers, in tests and +//! in any task running outside a request. Code that spawns a task on behalf of +//! a request and wants the task's log lines correlated reads [`current`] +//! before the spawn and re-enters the scope inside it with +//! [`with_scope_opt`]. The engine makes most of its storage calls inline on +//! the request task, so a backend serving the request sees the scope. A task +//! the request starts does not see it unless the engine carries it in: the +//! detached restore of `RestoreTableFromBackup` re-enters the scope. The job +//! tasks of a store-backed `CreateBackup` and of `RestoreTableFromBackup`'s +//! registration answer the request from a task without the scope, so a +//! storage fault there carries no request id. The backup and restore jobs +//! after the answer and the TTL index backfill that `UpdateTimeToLive` +//! spawns on a backend reporting ENABLING run without it as well. +//! +//! The two SDK fields are header values the client chose. Treat them as +//! untrusted text: write them to a log line if useful, never into a query, a +//! key or a file name. + +/// Correlation data for the client request a task is serving. +/// +/// Construct it with [`RequestScope::new`] and [`RequestScope::with_sdk_headers`]; +/// the struct may gain fields in a minor release. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct RequestScope { + /// The server's request id, the value returned to the client in + /// `x-amzn-RequestId`. + pub request_id: String, + /// The DynamoDB operation name from `X-Amz-Target`, for example `PutItem`. + pub operation: String, + /// `amz-sdk-invocation-id` when the client sent it. The AWS SDKs set one + /// value per call and resend it on each retry of that call. + pub sdk_invocation_id: Option, + /// `amz-sdk-request` when the client sent it. The AWS SDKs send their + /// attempt counter here, as in `attempt=1; max=3`. Once botocore has + /// received a response, it puts a `ttl` field first, as in + /// `ttl=20261124T190559Z; attempt=2; max=3`: the time after which the + /// client no longer waits for the answer. + pub sdk_request: Option, +} + +impl RequestScope { + /// A scope for `request_id` and `operation` with no SDK headers. + #[must_use] + pub fn new(request_id: String, operation: String) -> Self { + Self { + request_id, + operation, + sdk_invocation_id: None, + sdk_request: None, + } + } + + /// The same scope with the two SDK correlation headers set. + #[must_use] + pub fn with_sdk_headers( + mut self, + sdk_invocation_id: Option, + sdk_request: Option, + ) -> Self { + self.sdk_invocation_id = sdk_invocation_id; + self.sdk_request = sdk_request; + self + } +} + +tokio::task_local! { + static SCOPE: RequestScope; +} + +/// Run `fut` with `scope` visible to every [`current`] and [`with_current`] +/// call made from inside it on the same task. +pub async fn with_scope(scope: RequestScope, fut: F) -> F::Output { + SCOPE.scope(scope, fut).await +} + +/// Run `fut` inside `scope` when there is one, plainly when there is none. +/// For a task spawned on behalf of a request: read [`current`] before the +/// spawn and pass it here inside the task. +pub async fn with_scope_opt( + scope: Option, + fut: F, +) -> F::Output { + match scope { + Some(scope) => SCOPE.scope(scope, fut).await, + None => fut.await, + } +} + +/// The scope of the request this task is serving, cloned, or `None` outside a +/// request (workers, tests, spawned tasks). +pub fn current() -> Option { + SCOPE.try_with(RequestScope::clone).ok() +} + +/// Borrow the scope without cloning and map it with `f`; `None` outside a +/// request. +pub fn with_current(f: impl FnOnce(&RequestScope) -> R) -> Option { + SCOPE.try_with(f).ok() +} + +/// The request id and operation of the current request, for a log line. Both +/// are `None` outside a request; `tracing` records nothing for a `None`, so a +/// line written from a worker carries neither field rather than a fabricated +/// value. +pub fn log_fields() -> (Option, Option) { + with_current(|s| (s.request_id.clone(), s.operation.clone())).unzip() +} + +#[cfg(test)] +mod tests { + use super::{RequestScope, current, log_fields, with_current, with_scope, with_scope_opt}; + + fn scope(request_id: &str) -> RequestScope { + RequestScope::new(request_id.to_owned(), "PutItem".to_owned()) + .with_sdk_headers(Some("inv-1".to_owned()), None) + } + + #[tokio::test] + async fn current_is_none_outside_a_scope() { + assert_eq!(current(), None); + assert_eq!(with_current(|s| s.request_id.clone()), None); + assert_eq!(log_fields(), (None, None)); + } + + #[tokio::test] + async fn current_is_some_and_equal_inside_a_scope() { + let expected = scope("req-eq"); + let seen = with_scope(expected.clone(), async { current() }).await; + assert_eq!(seen, Some(expected)); + } + + #[tokio::test] + async fn the_constructors_set_the_fields_they_name() { + let plain = RequestScope::new("req-c".to_owned(), "Query".to_owned()); + assert_eq!(plain.request_id, "req-c"); + assert_eq!(plain.operation, "Query"); + assert_eq!(plain.sdk_invocation_id, None); + assert_eq!(plain.sdk_request, None); + let full = + plain.with_sdk_headers(Some("inv".to_owned()), Some("attempt=1; max=3".to_owned())); + assert_eq!(full.sdk_invocation_id.as_deref(), Some("inv")); + assert_eq!(full.sdk_request.as_deref(), Some("attempt=1; max=3")); + } + + #[tokio::test] + async fn log_fields_carry_the_id_and_operation_inside_a_scope() { + let seen = with_scope(scope("req-log"), async { log_fields() }).await; + assert_eq!( + seen, + (Some("req-log".to_owned()), Some("PutItem".to_owned())) + ); + } + + #[tokio::test] + async fn visible_through_nested_awaits_and_a_boxed_future() { + async fn inner() -> Option { + tokio::task::yield_now().await; + with_current(|s| s.request_id.clone()) + } + let boxed: std::pin::Pin>>> = + Box::pin(inner()); + let seen = with_scope(scope("req-nested"), boxed).await; + assert_eq!(seen.as_deref(), Some("req-nested")); + } + + #[tokio::test] + async fn a_spawned_task_does_not_inherit_the_scope() { + let seen = with_scope(scope("req-spawn"), async { + tokio::spawn(async { current() }) + .await + .expect("spawned task joins") + }) + .await; + assert_eq!(seen, None); + } + + #[tokio::test] + async fn a_spawned_task_re_enters_the_scope_it_was_handed() { + let seen = with_scope(scope("req-carry"), async { + let carried = current(); + tokio::spawn(with_scope_opt(carried, async { current() })) + .await + .expect("spawned task joins") + }) + .await; + assert_eq!(seen, Some(scope("req-carry"))); + } + + #[tokio::test] + async fn with_scope_opt_without_a_scope_runs_plainly() { + let seen = with_scope_opt(None, async { current() }).await; + assert_eq!(seen, None); + } + + #[tokio::test] + async fn two_concurrent_scopes_each_see_their_own_value() { + async fn observe(id: &str) -> String { + // Yield between reads so the two futures interleave on the task. + let first = with_current(|s| s.request_id.clone()).expect("scope present"); + tokio::task::yield_now().await; + let second = with_current(|s| s.request_id.clone()).expect("scope present"); + assert_eq!(first, second, "scope stayed stable across the yield"); + assert_eq!(first, id); + first + } + let a = with_scope(scope("req-a"), observe("req-a")); + let b = with_scope(scope("req-b"), observe("req-b")); + let (ra, rb) = tokio::join!(a, b); + assert_eq!(ra, "req-a"); + assert_eq!(rb, "req-b"); + // Outside both scopes again. + assert_eq!(current(), None); + } +} diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index 81c335606..29be47fd3 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -238,6 +238,12 @@ at build time. Auth providers implement the `AuthProvider` trait using `#[async_trait]` for object safety. The provider is selected at startup and stored as `Arc`. The `BuiltinAuthProvider` uses a `CredentialStore` trait (also `#[async_trait]`) for credential lookup, with a database-backed implementation. +### Request scope + +The server sets `extenddb_storage::request_scope::RequestScope` around each request from authentication through dispatch. It holds the request id the client receives in the `x-amzn-RequestId` response header, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A storage backend or an engine error mapper running inline on the request task reads it with `request_scope::current()` or `request_scope::with_current()`. The scope is a Tokio task-local, absent in background workers and in tasks started with `tokio::spawn`. The detached restore of `RestoreTableFromBackup` carries it across by hand. The job tasks of a store-backed `CreateBackup` and of `RestoreTableFromBackup`'s registration answer the request from a task without it, and the TTL index backfill that `UpdateTimeToLive` spawns runs without it. + +The engine's fault log lines carry `request_id` and `operation` from the scope next to the redacted error text, so an operator can match the line to the request id the client received: `storage internal error` and `backup storage error`, the shared error mapper's lines for an unexpected already-exists error, an idempotency fault, a transient error, an expired snapshot and a connection error, the restore's line for a backup store read that fails, DeleteBackup's line for a catalog id that cannot be read and the BatchWriteItem line for the requests a batch did not apply. Outside a request the line carries neither field. At trace level the engine writes one `dispatch` event per request under the target `extenddb_engine::dispatch`, inside the scope, with the operation. + ## Security Architecture ### Authentication diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index d1d23f38a..f16d4dba2 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -427,6 +427,14 @@ session signs in as it, and a membership puts it in a group. So: checks these properties against a real database; each backend's test suite runs it. +### Request Correlation + +The server sets `extenddb_storage::request_scope::RequestScope` around each client request, from authentication through dispatch. It holds the request id the client receives in `x-amzn-RequestId`, the operation name from `X-Amz-Target`, and the `amz-sdk-invocation-id` and `amz-sdk-request` headers when the client sent them. A backend method running inline on the request task reads it with `request_scope::current()` (a clone) or `request_scope::with_current(|s| ...)` (a borrow). Put `s.request_id` on a log line the backend writes for a failure it is about to return as `StorageError::Internal`, `Connection` or `Transient`, so an operator can match the line to the client's request id. + +The scope is a Tokio task-local. Both accessors return `None` in a task started with `tokio::spawn` or `spawn_blocking`, in background workers and in tests. A backend does not keep the scope beyond the call that read it. A backend that spawns a task on behalf of a request and wants that task's lines correlated reads `current()` before the spawn and runs the task's future through `request_scope::with_scope_opt`. The two SDK fields are header values the client chose, each at most 256 bytes of printable ASCII (space through tilde) or tab, which cannot hold a line break; treat them as untrusted text and do not use them in a query, a key or a file name. + +Construct a scope only through `RequestScope::new` and `with_sdk_headers`; the struct is `#[non_exhaustive]` and may gain fields in a minor release. The engine's own fault lines carry `request_id` and `operation`: `storage internal error` and `backup storage error`, the `storage connection error` and `transient storage error` lines of the shared error mapper, the line for a backup store read that fails during a restore, DeleteBackup's line for a catalog id that cannot be read, and the BatchWriteItem line for the requests a batch did not apply. A backend that returns `Internal`, `Connection` or `Transient` without logging gets one correlated line, except where the engine answers from a task without the scope: a store-backed CreateBackup, and the registration of RestoreTableFromBackup. + ## PostgreSQL-isms in the Default Backend The PostgreSQL implementation makes backend-specific choices. These are implementation details inside `storage-postgres`, not leaks in the trait abstraction: diff --git a/docs/rfcs/0002-backend-plugin-policy.md b/docs/rfcs/0002-backend-plugin-policy.md index 07ea9bd51..b83367269 100644 --- a/docs/rfcs/0002-backend-plugin-policy.md +++ b/docs/rfcs/0002-backend-plugin-policy.md @@ -255,7 +255,7 @@ cargo build --no-default-features --bin extenddb ### Release model -ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Variants may be added to `StorageError` in a minor release; a backend crate that matches on it exhaustively must carry a catch-all arm. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. +ExtendDB will move to a release model that includes releases through Crates.io. All crates follow semantic versioning. Breaking changes to `extenddb-storage` trigger coordinated releases. Variants may be added to `StorageError` in a minor release; a backend crate that matches on it exhaustively must carry a catch-all arm. Fields may be added to `RequestScope` in a minor release; a backend crate constructs it through `RequestScope::new`, never a struct literal. Binaries will also be available as GitHub releases. The project will also prioritize releasing images through Docker Hub. ### Third-party backends outside ExtendDB organization diff --git a/docs/rfcs/0003-backend-acceptance-criteria.md b/docs/rfcs/0003-backend-acceptance-criteria.md index 8d2692b52..41265bee3 100644 --- a/docs/rfcs/0003-backend-acceptance-criteria.md +++ b/docs/rfcs/0003-backend-acceptance-criteria.md @@ -135,6 +135,8 @@ If implementing pushdown, numeric comparisons must be numeric (not string-lexico **10.3. UpdateTable idempotency.** Repeated `UpdateTable` calls with the same specification must not corrupt state (duplicate shards, broken ARNs, phantom index entries). Either reject the redundant call with the appropriate error, or make it a no-op. +**10.4. Request correlation.** A log line the backend writes for a failure it returns as `StorageError::Internal`, `Connection` or `Transient` carries the request id from `extenddb_storage::request_scope` when one is current, so an operator can match the line to the `x-amzn-RequestId` the client received. See the Request Correlation section of the storage extension manual for the accessors and the cases where no scope is current. + ## Conformance Verification ### Required test suites