Explorar o código

fix: an uncaught database failure keeps its status instead of becoming 500

The global exception handler had arms for our own ApiError and for
std::exception, and nothing between them. Client::Error derives from
std::runtime_error, so any database failure not caught at its call site
landed on the catch-all as 500 "internal" carrying a gRPC sentence.

That is the wrong instruction twice over: 500 tells a caller we are
broken and it should not retry, where a transport failure means wait
and retry, and a 429 from a database under pressure lost its
Retry-After. The mapping already existed in db_errors.hpp and was
simply never reached from here.

This matters now because client 2.12.4 makes about twenty reads THROW
on a failed gRPC status instead of answering empty - exists, count,
find, listCollections, listProjects, getCollectionInfo and the rest.
Without this arm, taking that client would have turned every outage
answer on six handler files from 503 into 500. The arm has to precede
the std::exception one or it would never run, which is now stated where
someone might otherwise reorder them.

Both arms share one sender, so a database-raised rate limit carries
Retry-After exactly as one of ours does.

Tests: the existing ones all drive the FailureDetail overload, which is
plain data. Four more cover the THROWN path the handler actually uses,
including a guard over the whole code table so nothing reaches 500 just
because the switch forgot it.

Also corrects a gotcha that blamed the client for our own behaviour:
"DB client strips an `id` field from stored doc bodies" is false on
2.12.1, measured - the body field is stored verbatim and reads back
beside the real `_id` metadata. The stripping is ours, in
documentBody(), and it must stay: the database keeps a reserved key as
an ordinary user field while every read overwrites it with the real
metadata, so a body carrying `_version` leaves an invisible shadow copy
on disk. Our layer is why stored documents are clean.
fszontagh hai 1 mes
pai
achega
4d4fa8c885
Modificáronse 3 ficheiros con 84 adicións e 4 borrados
  1. 1 1
      CLAUDE.md
  2. 19 3
      src/server.cpp
  3. 64 0
      tests/test_db_errors.cpp

+ 1 - 1
CLAUDE.md

@@ -94,7 +94,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`dropCollection` left the collection's indexes declared, before database 2.12.2.** The documents and the metadata went; the declared indexes, unique ones included, stayed. A collection later created under the same name inherited a constraint nobody declared - a legitimate write refused as a duplicate, measured directly: a recycled name on 2.12.0 answered `unique constraint violated on recyc#sku`. Collection-create and collection-delete therefore undeclare indexes explicitly, which is idempotent on 2.12.2 and the correct behaviour against anything older. **The create-time repair must be gated on "is anything still attached to this name", NOT on `getCollectionInfo`** (`anythingAttachedTo()` in `handlers/collections.cpp`): a poisoned name has no collection, so a presence check skips the repair in exactly the case that needs it. 2.12.2 also made `dropIndex` work on an absent collection, which is what lets an already-poisoned name be repaired at all - on 2.12.1 nothing could clear one.
 - **The ApiFixture tests share one database and a FIXED project name** (`svapitest_apiproj`), so `ctest` must run **serially** - `-j` makes them delete each other's state - and the fixture has to purge the previous run itself. It drops each of the project's indexes before its collection, because neither `dropProject` nor `dropCollection` does (see the two caveats here). None of this shows up in `packaging/devstack`, whose database is new every time; it only appears once the suite runs against a persistent one, which the native host build now does.
 - **DB v2.3.1: `dropProject` does not physically purge collection data.** A recycled project name is otherwise blocked by stale collections/registry → the project-delete handler drops the registry + collections first, and collection-create drops invisible orphans (after the registry "exists" check).
-- **DB client strips an `id` field from stored doc bodies.** So API keys store their stable id as `key_id` in the body (exposed as `id` externally); document handlers strip `id` before insert and use the separate id param.
+- **WE strip `id` from a document body, not the database client.** This note used to say the client did it, and that is measured as false on client 2.12.1: inserting `{"id":"body-id-value"}` with an explicit document id stores the body field verbatim and it reads back alongside the real `_id` metadata. The stripping is ours, in `documentBody()` (`documents_util.hpp`), which erases `id` and then calls `stripDbMetadata()` to drop the six reserved keys. Keep doing it: the database stores a reserved key as an ordinary user field while every read overwrites it with the real metadata, so a body carrying `_version` would put an invisible shadow copy on disk that no read ever shows and no filter can reach. Our layer is what keeps stored documents clean (the database is fixing this server-side in 2.13.0, for every other client). API keys store their stable id as `key_id` in the body (exposed as `id` externally) - that predates this and the stored rows are not worth migrating, but it was never forced by the client.
 - **Debian 13 (trixie) gRPC cmake config is broken** unless `protobuf-compiler-grpc` + `libgrpc++-dev` + `libprotobuf-dev` are installed - `find_package(gRPC CONFIG)` (used transitively by `smartbotic-db-clientConfig.cmake`) fails on a `gRPCTargets.cmake` referencing missing plugin files. The Docker base installs them.
 - **Abseil ABI:** `smartbotic-database`/client debs must be built against the system's current Abseil; a stale build crash-loops on `libabsl_*.so.<old>`. Rebuild the DB if it won't start.
 - **`--rebuild-base` is required when `DB_CLIENT_VERSION` moves.** The client version is baked into the Docker BASE image, so bumping the variable alone leaves the release build compiling against the old headers - it fails on the new entry points, or worse, silently links the old ones. Note `devstack/run-tests.sh` installs the client debs explicitly, so the TEST path can be on a newer client than the RELEASE path: a green suite is not evidence about the packages.

+ 19 - 3
src/server.cpp

@@ -1,5 +1,6 @@
 #include "server.hpp"
 #include "captcha.hpp"
+#include "db_errors.hpp"
 #include "errors.hpp"
 #include "json_http.hpp"
 #include "rate_limiter.hpp"
@@ -95,11 +96,26 @@ void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& r
 
 void ApiServer::registerRoutes() {
     svr_.set_exception_handler([](const httplib::Request&, httplib::Response& res, std::exception_ptr ep) {
-        try { std::rethrow_exception(ep); }
-        catch (const ApiError& e) {
+        // One sender for every classified failure, so a database-raised 429
+        // carries Retry-After exactly as one of ours does.
+        auto send = [&res](const ApiError& e) {
             if (e.code == ErrCode::TooManyRequests) res.set_header("Retry-After", "60");
             sendJson(res, httpStatus(e.code), errorBody(e.slug, e.what(), e.details));
-        }
+        };
+        try { std::rethrow_exception(ep); }
+        catch (const ApiError& e) { send(e); }
+        // A database failure that nothing caught at the call site. This arm is
+        // the difference between 503 and 500 for a whole class of reads: the
+        // client answers empty for a failed read on some calls and THROWS on
+        // others, and a read whose "nothing there" value is also a valid answer
+        // throws rather than lying. Without this arm an outage would reach the
+        // caller as 500 "internal" carrying a gRPC sentence, which says "we are
+        // broken, do not retry" where the truth is "wait and retry".
+        //
+        // MUST precede the std::exception arm: Client::Error derives from
+        // std::runtime_error, so a more general arm placed first would swallow
+        // every one of these and the mapping would silently never run.
+        catch (const smartbotic::database::Client::Error& e) { send(apiErrorFor(e)); }
         catch (const std::exception& e) { sendJson(res, 500, errorBody("internal", e.what())); }
     });
 

+ 64 - 0
tests/test_db_errors.cpp

@@ -128,4 +128,68 @@ TEST(DbErrors, TheDatabaseMessageIsCarriedThroughWhereItIsTheUsefulOne) {
     EXPECT_EQ(denied.what(), std::string("collection is read-protected"));
 }
 
+// --- the THROWN path, which the global exception handler now maps -----------
+//
+// Everything above drives the FailureDetail overload, which is plain data. But
+// the arm added to the global exception handler catches a thrown Client::Error,
+// and a caught-by-reference exception may or may not carry a FailureDetail
+// alongside it. These assert the exception entry point directly, because that
+// is the one an uncaught database failure actually travels through.
+
+TEST(DbErrors, AThrownTransportFailureIs503NotA500) {
+    // The reason this arm exists. Client 2.12.4 makes about twenty reads THROW
+    // on a failed gRPC status instead of answering empty, so during an outage
+    // these reach the global handler. With no Client::Error arm they would land
+    // on the std::exception arm as 500 "internal" plus a gRPC sentence - which
+    // tells a caller we are broken and it should not retry, when the truth is
+    // the opposite.
+    for (const Code c : {Code::Unavailable, Code::DeadlineExceeded}) {
+        const smartbotic::database::Client::Error e(c, "failed to connect to all addresses");
+        const svapi::ApiError a = svapi::apiErrorFor(e);
+        EXPECT_EQ(svapi::httpStatus(a.code), 503) << static_cast<int>(c);
+        EXPECT_EQ(a.slug, "db_unavailable") << static_cast<int>(c);
+    }
+}
+
+TEST(DbErrors, AThrownErrorWithNoDetailStillUsesItsCode) {
+    // errorDetail() returns null when the exception was sliced (caught by
+    // value) or raised somewhere that attached none. The mapping must fall back
+    // to code() rather than to the catch-all.
+    const smartbotic::database::Client::Error denied(Code::PermissionDenied,
+                                                     "collection is read-protected");
+    const svapi::ApiError a = svapi::apiErrorFor(denied);
+    EXPECT_EQ(svapi::httpStatus(a.code), 403);
+    EXPECT_EQ(a.what(), std::string("collection is read-protected"));
+}
+
+TEST(DbErrors, AThrownErrorNeverLandsOnTheUnclassified500ByAccident) {
+    // A guard on the whole table: every code the database can raise must map to
+    // something deliberate. Internal and DataLoss ARE 500 - that is correct,
+    // they are genuine faults - but nothing should reach 500 merely because the
+    // switch forgot it.
+    const struct { Code c; int status; } expected[] = {
+        {Code::Ok, 404},                 {Code::NotFound, 404},
+        {Code::AlreadyExists, 409},      {Code::Aborted, 409},
+        {Code::PermissionDenied, 403},   {Code::InvalidArgument, 422},
+        {Code::OutOfRange, 422},         {Code::ResourceExhausted, 429},
+        {Code::Unavailable, 503},        {Code::DeadlineExceeded, 503},
+        {Code::Unknown, 503},
+    };
+    for (const auto& e : expected) {
+        const smartbotic::database::Client::Error err(e.c, "boom");
+        EXPECT_EQ(svapi::httpStatus(svapi::apiErrorFor(err).code), e.status)
+            << "code " << static_cast<int>(e.c);
+    }
+}
+
+TEST(DbErrors, ARateLimitFromTheDatabaseIsA429SoItCanCarryRetryAfter) {
+    // The global handler sets Retry-After for TooManyRequests, and it now does
+    // so for a database-raised one as well as for our own. That only works if
+    // ResourceExhausted really maps to the same ErrCode.
+    const smartbotic::database::Client::Error e(Code::ResourceExhausted, "too many requests");
+    const svapi::ApiError a = svapi::apiErrorFor(e);
+    EXPECT_EQ(a.code, svapi::ErrCode::TooManyRequests);
+    EXPECT_EQ(svapi::httpStatus(a.code), 429);
+}
+
 } // namespace