Repository navigation
fix(mongodb): answer 503 when the key-info lookup cannot reach the backend #486
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
f1aaa95
1b7430d
0048aad
2ed233e
8ba7e56
828ffe4
a6bdd00
19c5314
84b3a79
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,245 @@ | ||
| // Copyright 2026 ExtendDB contributors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| //! Classification of mongodb driver errors raised by catalog reads. | ||
| //! | ||
| //! A read that cannot reach the deployment is [`StorageError::Transient`], | ||
| //! which `storage_err_to_dynamo` answers as `ServiceUnavailable` (503), the | ||
| //! status of a fault that clears when the deployment comes back. Everything | ||
| //! else stays [`StorageError::Internal`] and answers as `InternalServerError` | ||
| //! (500), the status of a server fault. | ||
| //! | ||
| //! The driver has predicates for this (`is_network_error`, `is_read_retryable`) | ||
| //! but they are `pub(crate)` to the driver, so the classification is written | ||
| //! out here against `ErrorKind` and the driver's documented retryable-read | ||
| //! code set. | ||
|
|
||
| use extenddb_storage::error::StorageError; | ||
| use mongodb::error::{Error as DriverError, ErrorKind}; | ||
|
|
||
| /// Server error codes that make a read retryable, from the driver's own | ||
| /// `RETRYABLE_READ_CODES` (mongodb 3.8.0 `src/error.rs`): HostUnreachable, | ||
| /// HostNotFound, NetworkTimeout, ShutdownInProgress, PrimarySteppedDown, | ||
| /// ExceededTimeLimit, SocketException, NotWritablePrimary, | ||
| /// InterruptedAtShutdown, InterruptedDueToReplStateChange, | ||
| /// NotPrimaryNoSecondaryOk, NotPrimaryOrSecondary, and | ||
| /// ReadConcernMajorityNotAvailableYet. | ||
| const RETRYABLE_READ_CODES: [i32; 13] = [ | ||
| 6, 7, 89, 91, 134, 189, 262, 9001, 10107, 11600, 11602, 13435, 13436, | ||
| ]; | ||
|
|
||
| /// Whether `e` means the read could not reach a server that could serve it. | ||
| /// | ||
| /// `ServerSelection` is the one a stopped or unreachable deployment produces: | ||
| /// the driver marks the server Unknown and server selection then times out. | ||
| /// Its own label set is empty, because the `RetryableError` label sits on the | ||
| /// inner per-server error, so a label check does not see it; the kind does. | ||
| /// `Io` and `ConnectionPoolCleared` are what the driver itself calls a network | ||
| /// error. `DnsResolve` is a name lookup that did not answer. | ||
| /// | ||
| /// The classification errs narrow, for the reason `map_sqlx_err` gives: a | ||
| /// fault wrongly called transient is retried by a client that cannot succeed. | ||
| /// On the SQLite backend the queue workers also retry a `Transient` row | ||
| /// instead of dropping it, so a permanent fault called transient stalls that | ||
| /// queue; this backend's GSI and TTL workers log every error and continue. | ||
| fn is_unreachable(e: &DriverError) -> bool { | ||
| match &*e.kind { | ||
| ErrorKind::Io(_) | ||
| | ErrorKind::ConnectionPoolCleared { .. } | ||
| | ErrorKind::ServerSelection { .. } | ||
| | ErrorKind::DnsResolve { .. } => true, | ||
| ErrorKind::Command(command) => RETRYABLE_READ_CODES.contains(&command.code), | ||
| _ => false, | ||
| } | ||
| } | ||
|
|
||
| /// Map a driver error from a catalog read to a `StorageError`. | ||
| /// | ||
| /// Used by the key-info and index-info lookups, whose result decides the wire | ||
| /// status on two paths: the server's authorization path reads key info before | ||
| /// dispatch (`key_info_for_authz`) and the engine reads it again for the | ||
| /// operation itself. Both run the result through `storage_err_to_dynamo`, so | ||
| /// this classification is what the client sees. | ||
| pub(crate) fn catalog_read_err(e: &DriverError) -> StorageError { | ||
| if is_unreachable(e) { | ||
| StorageError::Transient(e.to_string()) | ||
| } else { | ||
| StorageError::Internal(e.to_string()) | ||
| } | ||
| } | ||
|
|
||
| /// A connection string nothing listens on: port 1 on loopback refuses the | ||
| /// connection, and a read fails within the 50 ms server-selection timeout. | ||
| #[cfg(test)] | ||
| pub(crate) const CLOSED_PORT_URI: &str = | ||
| "mongodb://127.0.0.1:1/?directConnection=true&serverSelectionTimeoutMS=50"; | ||
|
|
||
| #[cfg(test)] | ||
| pub(crate) async fn engine_on_a_closed_port() -> crate::MongoEngine { | ||
| crate::MongoEngine::new( | ||
| CLOSED_PORT_URI, | ||
| "us-east-1", | ||
| None, | ||
| mongodb::options::ReadConcern::local(), | ||
| ) | ||
| .await | ||
| .expect("building the engine performs no I/O") | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::{CLOSED_PORT_URI, RETRYABLE_READ_CODES, catalog_read_err, engine_on_a_closed_port}; | ||
| use extenddb_storage::error::StorageError; | ||
| use mongodb::bson::doc; | ||
| use mongodb::error::{Error as DriverError, ErrorKind}; | ||
| use std::sync::Arc; | ||
|
|
||
| /// A labelless server command error with the given code. The struct | ||
| /// variants of `ErrorKind` are `#[non_exhaustive]`, so a synthetic one is | ||
| /// built through deserialization, as the data-engine tests do. | ||
| fn command(code: i32) -> DriverError { | ||
| let command_error: mongodb::error::CommandError = bson::from_document(doc! { | ||
| "code": code, | ||
| "codeName": "SyntheticTestError", | ||
| "errmsg": "synthetic command error", | ||
| }) | ||
| .expect("static CommandError document deserializes"); | ||
| ErrorKind::Command(command_error).into() | ||
| } | ||
|
|
||
| /// The error a stopped deployment produces, taken from the driver rather | ||
| /// than built by hand: a client whose only server is not listening answers | ||
| /// a catalog read with `ErrorKind::ServerSelection`. The variant is | ||
| /// `#[non_exhaustive]` and cannot be constructed outside the driver, so | ||
| /// this is the only way to assert on the real thing. | ||
| #[tokio::test] | ||
| async fn a_deployment_that_is_not_listening_is_transient() { | ||
| let client = mongodb::Client::with_uri_str(CLOSED_PORT_URI) | ||
| .await | ||
| .expect("a syntactically valid connection string"); | ||
| let error = client | ||
| .database("extenddb_catalog") | ||
| .collection::<mongodb::bson::Document>("tables") | ||
| .find_one(doc! { "table_id": "whatever" }) | ||
| .await | ||
| .expect_err("no server is listening on port 1"); | ||
| assert!( | ||
| matches!(*error.kind, ErrorKind::ServerSelection { .. }), | ||
| "driver reported {:?}, the test's premise no longer holds", | ||
| error.kind | ||
| ); | ||
| assert!( | ||
| matches!(catalog_read_err(&error), StorageError::Transient(_)), | ||
| "a deployment that cannot be reached must be Transient, got {:?}", | ||
| catalog_read_err(&error) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_dropped_socket_is_transient() { | ||
| let e: DriverError = ErrorKind::Io(Arc::new(std::io::Error::new( | ||
| std::io::ErrorKind::ConnectionReset, | ||
| "reset by peer", | ||
| ))) | ||
| .into(); | ||
| assert!(matches!(catalog_read_err(&e), StorageError::Transient(_))); | ||
| } | ||
|
|
||
| /// A node that is shutting down, stepping down or recovering answers the | ||
| /// read with one of these codes. The deployment is reachable, so the | ||
| /// driver does not call it a network error, but the read can succeed on | ||
| /// retry once a new primary is elected. | ||
| #[test] | ||
| fn a_node_that_cannot_serve_the_read_is_transient() { | ||
| for code in RETRYABLE_READ_CODES { | ||
| assert!( | ||
| matches!(catalog_read_err(&command(code)), StorageError::Transient(_)), | ||
| "code {code} must be Transient" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /// Anything not positively identified as unreachable stays Internal, so a | ||
| /// permanent fault is not retried forever by a client, and the GSI and TTL | ||
| /// queue workers do not hold a row that can never be applied. | ||
| #[test] | ||
| fn other_faults_stay_internal() { | ||
| // Unauthorized (13), NamespaceNotFound (26), BadValue (2), | ||
| // WriteConflict (112). | ||
| for code in [13, 26, 2, 112] { | ||
| assert!( | ||
| matches!(catalog_read_err(&command(code)), StorageError::Internal(_)), | ||
| "code {code} must be Internal" | ||
| ); | ||
| } | ||
| for e in [ | ||
| DriverError::from(ErrorKind::SessionsNotSupported), | ||
| DriverError::from(ErrorKind::MissingResumeToken), | ||
| DriverError::from(ErrorKind::Shutdown), | ||
| ] { | ||
| let what = e.to_string(); | ||
| assert!( | ||
| matches!(catalog_read_err(&e), StorageError::Internal(_)), | ||
| "{what} must be Internal" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /// The driver's message is kept whichever way the error is classified, so | ||
| /// the log line and the server's diagnostics do not lose it. | ||
| #[test] | ||
| fn the_driver_message_survives_classification() { | ||
| let e: DriverError = ErrorKind::Io(Arc::new(std::io::Error::new( | ||
| std::io::ErrorKind::ConnectionRefused, | ||
| "connection refused", | ||
| ))) | ||
| .into(); | ||
| let StorageError::Transient(message) = catalog_read_err(&e) else { | ||
| panic!("expected Transient"); | ||
| }; | ||
| assert!(message.contains("connection refused"), "{message}"); | ||
| } | ||
|
|
||
| /// The key-info lookups themselves, not only the classifier. Each fails at | ||
| /// its first read on the closed-port engine. `key_info_for_authz` in the | ||
| /// server and the engine both run the result through | ||
| /// `storage_err_to_dynamo`, which answers `Transient` as | ||
| /// `ServiceUnavailable`; that mapping has its own test in | ||
| /// `crates/server/src/request_helpers.rs`, so what is asserted here is the | ||
| /// classification this backend produces. | ||
| /// | ||
| /// Needs no MongoDB, so it runs in `cargo test --workspace` on every job. | ||
| #[tokio::test] | ||
| async fn an_unreachable_deployment_makes_the_key_info_lookups_transient() { | ||
| use extenddb_storage::TableEngine; | ||
|
|
||
| let engine = engine_on_a_closed_port().await; | ||
|
|
||
| let by_name = engine | ||
| .table_key_info("123456789012", "any-table") | ||
| .await | ||
| .expect_err("no server is listening on port 1"); | ||
| assert!( | ||
| matches!(by_name, StorageError::Transient(_)), | ||
| "table_key_info must report an unreachable deployment as Transient, got {by_name:?}" | ||
| ); | ||
|
|
||
| let by_id = engine | ||
| .table_key_info_by_table_id_impl("any-table-id") | ||
| .await | ||
| .expect_err("no server is listening on port 1"); | ||
| assert!( | ||
| matches!(by_id, StorageError::Transient(_)), | ||
| "table_key_info_by_table_id must report it as Transient, got {by_id:?}" | ||
| ); | ||
|
|
||
| let index = engine | ||
| .index_info_by_table_id("any-table-id", "any-index") | ||
| .await | ||
| .expect_err("no server is listening on port 1"); | ||
| assert!( | ||
| matches!(index, StorageError::Transient(_)), | ||
| "index_info_by_table_id must report it as Transient, got {index:?}" | ||
| ); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1299,7 +1299,7 @@ impl MongoEngine { | |
| let table_doc = tables_coll | ||
| .find_one(doc! { "_id": { "account_id": account_id, "table_name": table_name } }) | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))? | ||
| .map_err(|e| crate::error_class::catalog_read_err(&e))? | ||
| .ok_or_else(|| StorageError::TableNotFound(table_name.to_string()))?; | ||
|
|
||
| self.table_key_info_from_doc(&table_doc, true).await | ||
|
|
@@ -1320,7 +1320,7 @@ impl MongoEngine { | |
| let table_doc = tables_coll | ||
| .find_one(doc! { "table_id": table_id }) | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))? | ||
| .map_err(|e| crate::error_class::catalog_read_err(&e))? | ||
| .ok_or_else(|| StorageError::TableNotFound(table_id.to_string()))?; | ||
|
|
||
| self.table_key_info_from_doc(&table_doc, false).await | ||
|
|
@@ -1388,12 +1388,12 @@ impl MongoEngine { | |
| let mut idx_cursor = indexes_coll | ||
| .find(doc! { "_id.table_id": &table_id }) | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))?; | ||
| .map_err(|e| crate::error_class::catalog_read_err(&e))?; | ||
| let mut infos = Vec::new(); | ||
| while let Some(idx_doc) = idx_cursor | ||
| .try_next() | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))? | ||
| .map_err(|e| crate::error_class::catalog_read_err(&e))? | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Optional. With this
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks. I'll leave this line as it is. It makes the same |
||
| { | ||
| infos.push(index_info_from_doc(&idx_doc)?); | ||
| } | ||
|
|
@@ -1451,7 +1451,7 @@ impl MongoEngine { | |
| let index_doc = indexes_coll | ||
| .find_one(doc! { "_id": { "table_id": table_id, "index_name": index_name } }) | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))? | ||
| .map_err(|e| crate::error_class::catalog_read_err(&e))? | ||
| .ok_or_else(|| StorageError::IndexNotFound(index_name.to_string()))?; | ||
|
|
||
| let index_id = index_doc | ||
|
|
@@ -2004,7 +2004,7 @@ fn active_table_filter(filter: &Document) -> Document { | |
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::active_table_filter; | ||
| use super::{StorageError, active_table_filter}; | ||
| use mongodb::bson::doc; | ||
|
|
||
| #[test] | ||
|
|
@@ -2015,4 +2015,28 @@ mod tests { | |
| assert_eq!(active.get_document("_id"), filter.get_document("_id")); | ||
| assert_eq!(active.len(), 2); | ||
| } | ||
|
|
||
| /// The `indexes` read of `table_key_info_from_doc`. Through the lookups | ||
| /// the closed-port engine fails at the `tables` read before it, so this | ||
| /// test hands the function a catalog document as `create_table` writes | ||
| /// one, and the index list is then the first read that reaches the driver. | ||
| #[tokio::test] | ||
| async fn an_unreachable_deployment_makes_the_index_list_read_transient() { | ||
| let engine = crate::error_class::engine_on_a_closed_port().await; | ||
| let table_doc = doc! { | ||
| "_id": { "account_id": "444455556666", "table_name": "t" }, | ||
| "table_id": "t-id", | ||
| "table_status": "ACTIVE", | ||
| "key_schema": [{ "AttributeName": "pk", "KeyType": "HASH" }], | ||
| "attribute_definitions": [{ "AttributeName": "pk", "AttributeType": "S" }], | ||
| }; | ||
| let err = engine | ||
| .table_key_info_from_doc(&table_doc, true) | ||
| .await | ||
| .expect_err("no server is listening on port 1"); | ||
| assert!( | ||
| matches!(err, StorageError::Transient(_)), | ||
| "the index list read must report an unreachable deployment as Transient, got {err:?}" | ||
| ); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The test guards 3 of the 6 changed sites. With
require_active_table(table_engine.rs:1147) and the twoindexescursor sites (:1255,:1260) reverted, alone and together, the 6error_classtests and the fullstorage-mongodbandserversuites pass (368 passed). The closed-port engine fails on the firsttablesread, so it never reaches them. TheConnectionPoolClearedandDnsResolvearms have no test either.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The guard site is gone with the UpdateTable change (2ed233e). The
indexesfind now has a test of its own (8ba7e56). It handstable_key_info_from_docon the closed-port engine a catalog document ascreate_tablewrites one, so the function fails at that read. With the site reverted the test fails.The
try_nextsite cannot see a network fault under the default limits. A table has at most 25 index documents (20 GSIs and 5 LSIs), and the first batch of afindholds 101. The cursor never sends agetMore. It stays so both reads of the cursor map alike.ConnectionPoolClearedandDnsResolveare#[non_exhaustive]struct variants in mongodb 3.8.0 (src/error.rs:767and:747), so a test cannot build them, and a stopped loopback server surfaces asServerSelection. The arms stay because the driver itself countsConnectionPoolClearedas a network error (is_network_error,src/error.rs:384). It raisesDnsResolvewhen a host name gets no DNS answer while it opens a connection (src/runtime/stream.rs:117).