#include "smartbotic/database/client.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace smartbotic::database { // v2.11.4 - defined out of line on purpose. An exception type whose members // are all inline has its typeinfo emitted in every object that uses it; with // the destructors here it lives in this library, so a throw inside the .so // and a catch in the consumer agree on the type by construction. Client::Error::Error(ErrorCode code, const std::string& message) : std::runtime_error(message), code_(code) {} Client::Error::~Error() = default; Client::AlreadyExists::AlreadyExists(const std::string& message) : Error(ErrorCode::AlreadyExists, message) {} Client::AlreadyExists::~AlreadyExists() = default; Client::FailedPrecondition::FailedPrecondition(const std::string& message) : Error(ErrorCode::FailedPrecondition, message) {} Client::FailedPrecondition::~FailedPrecondition() = default; Client::PermissionDenied::PermissionDenied(const std::string& message) : Error(ErrorCode::PermissionDenied, message) {} Client::PermissionDenied::~PermissionDenied() = default; namespace { // v2.11.4 - Client::ErrorCode mirrors grpc::StatusCode number for number, so // the conversion is a cast. The asserts pin the values callers branch on; the // gRPC status codes are fixed by its wire protocol and have never been // renumbered. static_assert(static_cast(Client::ErrorCode::NotFound) == grpc::StatusCode::NOT_FOUND); static_assert(static_cast(Client::ErrorCode::AlreadyExists) == grpc::StatusCode::ALREADY_EXISTS); static_assert(static_cast(Client::ErrorCode::PermissionDenied) == grpc::StatusCode::PERMISSION_DENIED); static_assert(static_cast(Client::ErrorCode::FailedPrecondition) == grpc::StatusCode::FAILED_PRECONDITION); static_assert(static_cast(Client::ErrorCode::Unavailable) == grpc::StatusCode::UNAVAILABLE); static_assert(static_cast(Client::ErrorCode::Unauthenticated) == grpc::StatusCode::UNAUTHENTICATED); Client::ErrorCode toErrorCode(grpc::StatusCode code) { return static_cast(static_cast(code)); } // v2.12.0 - the refusal detail the server attaches as trailing metadata (see // `service DatabaseService` in database.proto). Empty when absent. constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin"; #ifndef SMARTBOTIC_DB_VERSION_STRING #define SMARTBOTIC_DB_VERSION_STRING "unknown" #endif std::string trailerDetail(const grpc::ClientContext& context) { const auto& md = context.GetServerTrailingMetadata(); auto it = md.find(kErrorDetailKey); if (it == md.end()) return {}; return std::string(it->second.data(), it->second.size()); } // Build a FailureDetail from a code, a message and the trailer JSON. A detail // that does not parse is ignored rather than allowed to turn a refusal into a // crash: the code and message still stand. Client::FailureDetail makeDetail(Client::ErrorCode code, const std::string& message, const std::string& detailJson) { Client::FailureDetail d; d.code = code; d.message = message; // v2.13.0 - gRPC refuses an oversized message itself (either side, before // our server code runs), with RESOURCE_EXHAUSTED and no detail, so a size // refusal looked exactly like a rate limit or memory pressure - and the // remedies differ: retrying never shrinks a payload. The library names it, // so no consumer has to match gRPC's text. The text is gRPC core's own // ("Sent message larger than max (N vs. M)", also "Received message // larger than max"), stable across the gRPC versions this is built with; // test_export pins it. if (detailJson.empty() && code == Client::ErrorCode::ResourceExhausted && message.find("message larger than max") != std::string::npos) { d.reason = "message_too_large"; } if (detailJson.empty()) return d; try { const auto j = nlohmann::json::parse(detailJson); if (!j.is_object()) return d; d.reason = j.value("reason", std::string{}); if (auto it = j.find("fields"); it != j.end() && it->is_array()) { for (const auto& f : *it) if (f.is_string()) d.fields.push_back(f.get()); } if (auto it = j.find("values"); it != j.end()) d.values = *it; d.conflictingId = j.value("conflicting_id", std::string{}); d.relation = j.value("relation", std::string{}); if (auto it = j.find("current_version"); it != j.end() && it->is_number_unsigned()) { d.currentVersion = it->get(); } } catch (const std::exception&) { // keep code + message } return d; } // The exceptions this client throws carry a FailureDetail by deriving from the // public type AND this internal carrier; Client::errorDetail() cross-casts to // it. Internal types, so no public class changes size, and a consumer that // catches the public base sees exactly what it always did. struct DetailCarrier { explicit DetailCarrier(Client::FailureDetail d) : detail(std::move(d)) {} virtual ~DetailCarrier() = default; Client::FailureDetail detail; }; struct DetailedError : Client::Error, DetailCarrier { DetailedError(Client::ErrorCode c, const std::string& m, Client::FailureDetail d) : Client::Error(c, m), DetailCarrier(std::move(d)) {} }; struct DetailedAlreadyExists : Client::AlreadyExists, DetailCarrier { DetailedAlreadyExists(const std::string& m, Client::FailureDetail d) : Client::AlreadyExists(m), DetailCarrier(std::move(d)) {} }; struct DetailedFailedPrecondition : Client::FailedPrecondition, DetailCarrier { DetailedFailedPrecondition(const std::string& m, Client::FailureDetail d) : Client::FailedPrecondition(m), DetailCarrier(std::move(d)) {} }; struct DetailedPermissionDenied : Client::PermissionDenied, DetailCarrier { DetailedPermissionDenied(const std::string& m, Client::FailureDetail d) : Client::PermissionDenied(m), DetailCarrier(std::move(d)) {} }; // v2.12.4 - THE RULE FOR READS: a read whose "nothing there" value (nullopt, // false, 0, an empty list, a default config) is also a valid answer must THROW // on a failed status, never return that value. Returning it made a transport // blip (UNAVAILABLE, DEADLINE_EXCEEDED) indistinguishable from absence, so a // consumer reported a definite 404 for a collection that existed and lost a // six-minute ingest to it. v2.4.2 (find on a missing collection) and v2.8.0 // (permission denials) applied this rule one status code at a time; it now // applies to every code. Absence is always reported IN-BAND by the server // (found=false, exists=false, an empty list); only Find uses a NOT_FOUND // status, and that already threw. Exempt, deliberately: healthCheck / // getHealthInfo / getStats (their job is to answer "unreachable"), // getRelationsEnforced (fails toward enforced) and tryGetRelationsEnforced // (declines to answer). Writes keep returning false/0 - false already means // "did not happen", and they have Failure& overloads carrying the code. // // Throw the Client::Error subtype matching a failed status. `message` becomes // what(): every site passes what it threw before 2.11.4, so the text an // existing consumer logs or matches on is unchanged. v2.12.0: the thrown // object also carries the detail - see Client::errorDetail(). [[noreturn]] void throwStatus(const grpc::Status& status, const std::string& message, const std::string& detailJson = {}) { auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(), detailJson); switch (status.error_code()) { case grpc::StatusCode::ALREADY_EXISTS: throw DetailedAlreadyExists(message, std::move(d)); case grpc::StatusCode::FAILED_PRECONDITION: throw DetailedFailedPrecondition(message, std::move(d)); case grpc::StatusCode::PERMISSION_DENIED: throw DetailedPermissionDenied(message, std::move(d)); default: throw DetailedError(toErrorCode(status.error_code()), message, std::move(d)); } } // Where a non-throwing call reports its failure: the 2.11.4 Failure, the // 2.12.0 FailureDetail, or neither (the original overloads). One sink so every // method records a failure once and both overload families stay identical. struct FailureSink { FailureSink() = default; FailureSink(Client::Failure* f) : failure(f) {} // NOLINT: implicit on purpose FailureSink(Client::FailureDetail* d) : detail(d) {} // NOLINT Client::Failure* failure = nullptr; Client::FailureDetail* detail = nullptr; void reset() const { if (failure) *failure = Client::Failure{}; if (detail) *detail = Client::FailureDetail{}; } void record(Client::ErrorCode code, const std::string& message, const std::string& detailJson = {}) const { if (failure) { failure->code = code; failure->message = message; } if (detail) *detail = makeDetail(code, message, detailJson); } void record(const grpc::Status& status, const std::string& detailJson = {}) const { record(toErrorCode(status.error_code()), status.error_message(), detailJson); } // An in-band refusal (status OK, success=false): the code is in the // response from a 2.12.0+ server, Unknown from an older one. // Copy a reason a nested call already recorded (v2.13.1). void copy(const Client::FailureDetail& d) const { if (failure) { failure->code = d.code; failure->message = d.message; } if (detail) *detail = d; } void recordInBand(int32_t errorCode, const std::string& message, const std::string& detailJson) const { record(errorCode != 0 ? static_cast(errorCode) : Client::ErrorCode::Unknown, message, detailJson); } }; // The JSON a read hands back: the stored fields plus the read metadata, and // (v2.13.0) "_vector" when the server sent the stored vector, which it does // only when the caller asked. The bytes are float32 little-endian. nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) { auto json = nlohmann::json::parse(doc.data()); json["_id"] = doc.id(); json["_version"] = doc.version(); json["_created_at"] = doc.created_at(); json["_updated_at"] = doc.updated_at(); json["_created_by"] = doc.created_by(); json["_updated_by"] = doc.updated_by(); if (!doc.vector().empty()) { if (doc.vector().size() % sizeof(float) != 0) { throw DetailedError(Client::ErrorCode::DataLoss, "stored vector is not a whole number of float32 values", makeDetail(Client::ErrorCode::DataLoss, "bad vector bytes", {})); } std::vector v(doc.vector().size() / sizeof(float)); std::memcpy(v.data(), doc.vector().data(), doc.vector().size()); json["_vector"] = v; } return json; } // v1.7.0 T11 — transient transport errors that are safe to retry for idempotent // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch). // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are // final — no retry. // // v2.13.1 - DEADLINE_EXCEEDED is retried only for an IDEMPOTENT write. The // deadline can expire while the server finishes the write (seen by // smartbotic-vectorapi on large patches: every one reported failure and had // been applied), so a retry repeats a write that already happened: an id-less // insert duplicates the row, an increment counts twice, and an insert with an // id, a conditional write or a delete reports a false AlreadyExists / version // conflict / not-found. Those are not retried; the failure carries reason // outcome_unknown (see outcomeUnknownDetail). UNAVAILABLE and // RESOURCE_EXHAUSTED still retry: the server did not act on the request. bool retryableStatus(const grpc::Status& s, bool idempotent) { switch (s.error_code()) { case grpc::StatusCode::DEADLINE_EXCEEDED: // may have been applied return idempotent; case grpc::StatusCode::RESOURCE_EXHAUSTED: // admission control or gRPC concurrency cap case grpc::StatusCode::UNAVAILABLE: // transient connection issue return true; default: return false; } } // v2.13.1 - a write that ended in DEADLINE_EXCEEDED may or may not have been // applied; say so in the reason, so a caller checks before redoing it instead // of reading "the write failed". Leaves a server-supplied detail alone. std::string outcomeUnknownDetail(const grpc::Status& s, const std::string& detailJson) { if (s.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && detailJson.empty()) { return R"({"reason":"outcome_unknown"})"; } return detailJson; } // Exponential backoff with jitter. attempt=0 => baseMs; attempt=1 => baseMs*2; ... uint32_t computeBackoffMs(uint32_t baseMs, uint32_t attempt, uint32_t capMs, double jitterPct) { uint64_t exp = static_cast(baseMs) << attempt; if (exp > capMs) exp = capMs; // ±jitterPct jitter; std::rand() is fine here — not a security sensitive RNG. double jitter = 1.0 + ((double(std::rand()) / RAND_MAX) * 2.0 - 1.0) * jitterPct; if (jitter < 0.1) jitter = 0.1; return static_cast(exp * jitter); } // v2.4 — slurp a PEM-encoded CA cert file into a string. Returns empty // string on read failure; caller logs the surrounding context. std::string readCaCertFile(const std::string& path) { std::ifstream in(path, std::ios::binary); if (!in.is_open()) return {}; std::ostringstream buf; buf << in.rdbuf(); return buf.str(); } } // anonymous namespace const Client::FailureDetail* Client::errorDetail(const Error& e) noexcept { const auto* carrier = dynamic_cast(&e); return carrier != nullptr ? &carrier->detail : nullptr; } // ===== PIMPL Implementation ===== class Client::Impl { public: explicit Impl(Config config) : config_(std::move(config)) { if (config_.project.empty()) config_.project = "default"; } // v2.3 — qualify a collection name with Config::project unless the // caller already supplied a ":" qualified form. // The qualified form always wins. Server-side parseProjectCollection // is strict on edge cases (leading colon, double colon, etc.) so // we just delegate the validation to the server. std::string qualify(std::string_view collection) const { if (collection.find(':') != std::string_view::npos) { return std::string(collection); } // v2.7.0 — system collections (`_views`, `_collection_meta`, // `_policies`, `_files`) are GLOBAL, not per-project: their rows are // already keyed by a project-qualified id. Qualifying the collection // name too produced `default:_policies`, which does not exist, so // reads silently found nothing while writes succeeded (the server // tolerates both spellings on the policy write path). That asymmetry // is exactly how a management command can look like it worked and // then show stale state. if (!collection.empty() && collection.front() == '_') { return std::string(collection); } std::string out; out.reserve(config_.project.size() + 1 + collection.size()); out.append(config_.project); out.push_back(':'); out.append(collection.data(), collection.size()); return out; } // Inverse of qualify() for values coming back off the wire. Strips only // OUR project's prefix, so a name from another namespace stays visibly // qualified rather than being silently flattened into ours. std::string unqualify(const std::string& qualified) const { const std::string prefix = config_.project + ":"; if (qualified.rfind(prefix, 0) == 0) { return qualified.substr(prefix.size()); } return qualified; } ~Impl() { disconnect(); } bool connect() { try { auto channelArgs = grpc::ChannelArguments(); // Use longer keepalive intervals to avoid "too_many_pings" errors from server channelArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, 60000); // 60 seconds channelArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 20000); // 20 seconds channelArgs.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0); // Only ping when there are active calls // Set max message size to match server (100MB for file uploads) channelArgs.SetMaxReceiveMessageSize(100 * 1024 * 1024); channelArgs.SetMaxSendMessageSize(100 * 1024 * 1024); std::shared_ptr creds = buildChannelCredentials(); if (!creds) { spdlog::error("Database client connection failed: could not build channel credentials"); return false; } channel_ = grpc::CreateCustomChannel( config_.address, creds, channelArgs ); stub_ = smartbotic::databasepb::DatabaseService::NewStub(channel_); connected_ = true; const char* scheme = config_.tls_enabled ? "tls" : "plaintext"; const char* authed = config_.auth_token.empty() ? "no-auth" : "bearer-auth"; // v2.13.1 - actually try. Creating a gRPC channel opens nothing, so // this used to return true and log "connected" against a dead port // (reported by smartbotic): connect() and isConnected() were not // reachability checks at all. Now it waits up to timeoutMs for the // channel to connect. On failure the client stays usable - gRPC // keeps reconnecting on later calls - but the answer is honest. const bool reachable = channel_->WaitForConnected( std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs)); reached_ = reachable; if (!reachable) { spdlog::warn("Database client could not reach {} ({}, {}) within {} ms; " "it will keep trying on later calls", config_.address, scheme, authed, config_.timeoutMs); return false; } spdlog::info("Database client connected to {} ({}, {})", config_.address, scheme, authed); return true; } catch (const std::exception& e) { spdlog::error("Database client connection failed: {}", e.what()); return false; } } // v2.4 — build the ChannelCredentials matching Config's TLS settings. // // Three cases: // 1. !tls_enabled → InsecureChannelCredentials // (v2.3 back-compat default). // 2. tls_enabled && !insecure_skip_verify → SslCredentials with // pem_root_certs read from tls_ca_cert_path, or empty (= system // trust roots) when the path is unset. // 3. tls_enabled && insecure_skip_verify → experimental // TlsChannelCredentialsOptions with NoOpCertificateVerifier and // set_verify_server_certs(false). Loud WARN on every connect. std::shared_ptr buildChannelCredentials() { if (!config_.tls_enabled) { return grpc::InsecureChannelCredentials(); } if (config_.tls_insecure_skip_verify) { spdlog::warn( "Database client: connecting with tls_insecure_skip_verify — " "DEV ONLY. Server certificate will NOT be validated against any " "trust root. Drop the server's self-signed cert at " "tls_ca_cert_path for any production-shaped use."); // Route through gRPC's experimental TLS API. This is the path // gRPC documents for "accept any cert" — combine // NoOpCertificateVerifier with set_verify_server_certs(false). grpc::experimental::TlsChannelCredentialsOptions tlsOpts; tlsOpts.set_certificate_verifier( std::make_shared()); tlsOpts.set_verify_server_certs(false); tlsOpts.set_check_call_host(false); auto creds = grpc::experimental::TlsCredentials(tlsOpts); if (!creds) { // No fallback that "trusts everything" without // experimental TLS — if the build/runtime can't produce // experimental TlsCredentials, refuse to silently degrade // to system-trust mode (which would reject the // self-signed cert anyway). The operator should bake the // server's self-signed cert into tls_ca_cert_path. spdlog::error( "Database client: tls_insecure_skip_verify requested but " "experimental TlsCredentials returned null. Set " "tls_ca_cert_path to the server's self-signed PEM " "instead."); return nullptr; } return creds; } grpc::SslCredentialsOptions sslOpts; if (!config_.tls_ca_cert_path.empty()) { sslOpts.pem_root_certs = readCaCertFile(config_.tls_ca_cert_path); if (sslOpts.pem_root_certs.empty()) { spdlog::error( "Database client: could not read tls_ca_cert_path '{}'", config_.tls_ca_cert_path); return nullptr; } } // Else leave pem_root_certs empty → gRPC uses system trust roots // (or GRPC_DEFAULT_SSL_ROOTS_FILE_PATH env var, per gRPC docs). return grpc::SslCredentials(sslOpts); } void disconnect() { connected_ = false; reached_ = false; stub_.reset(); channel_.reset(); } bool isConnected() const { if (!connected_ || !channel_) { return false; } // READY is connected. IDLE (no calls for a while) and CONNECTING // count only if the last connection attempt succeeded (v2.13.1): // against a frozen server the kernel accepts the TCP connection and // the channel sits in CONNECTING forever, which used to read as true. auto state = channel_->GetState(false); if (state == GRPC_CHANNEL_READY) return true; return reached_ && (state == GRPC_CHANNEL_IDLE || state == GRPC_CHANNEL_CONNECTING); } // ===== Document Operations ===== std::string insert(const std::string& collection, const nlohmann::json& data, const std::string& id, uint32_t ttlSeconds, const std::string& actor) { smartbotic::databasepb::InsertRequest request; request.set_collection(qualify(collection)); request.set_data(data.dump()); if (!id.empty()) { request.set_id(id); } if (ttlSeconds > 0) { request.set_ttl_seconds(ttlSeconds); } if (!actor.empty()) { request.set_actor(actor); } smartbotic::databasepb::InsertResponse response; grpc::Status status; std::string detailJson; // v2.12.0 - the refusal detail, if any for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->Insert(&context, request, &response); detailJson = trailerDetail(context); // v2.12.0 if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) { break; } if (attempt < config_.writeRetries) { uint32_t backoffMs = computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter); spdlog::warn("Client::insert {}; retrying in {}ms (attempt {}/{})", status.error_message(), backoffMs, attempt + 1, config_.writeRetries); std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs)); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::insert failed after retries: {}", status.error_message()); throwStatus(status, status.error_message(), detailJson); } return response.id(); } std::optional get(const std::string& collection, const std::string& id, bool includeVector = false) { smartbotic::databasepb::GetRequest request; request.set_collection(qualify(collection)); request.set_id(id); request.set_include_vector(includeVector); // v2.13.0 smartbotic::databasepb::GetResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->Get(&context, request, &response); if (!status.ok()) { // v2.8.0 — a permission denial must NOT look like "no data". // Returning empty here would leave an application unable to tell // "you may not see this" from "there is nothing to see", so it // would silently take the wrong branch. Same reasoning as the // v2.4.2 change that stopped Find returning empty for a missing // collection. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) { throw Client::PermissionDenied("access denied: get"); } spdlog::error("Client::get failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } if (!response.found()) { return std::nullopt; } return documentToJson(response.document()); } bool update(const std::string& collection, const std::string& id, const nlohmann::json& data, const std::string& actor, FailureSink failureOut = {}) { // Strip metadata fields from data — callers pass the JSON from get() which // includes _version, _id, etc. We use _version for optimistic locking. auto cleanData = data; cleanData.erase("_id"); cleanData.erase("_version"); cleanData.erase("_created_at"); cleanData.erase("_updated_at"); cleanData.erase("_created_by"); cleanData.erase("_updated_by"); // Optimistic locking with automatic retry: // 1. Read current version // 2. Call updateIfVersion // 3. On version conflict (another writer), re-read and retry for (uint32_t attempt = 0; attempt <= config_.maxRetries; ++attempt) { // Get current version. v2.12.4: get() now throws on a failed read // instead of returning nullopt. Before, an unreachable database // was reported here as "document not found" - the same conflation // get() had. update() still reports failure by returning false, // so the real code is recorded instead. A permission denial threw // out of here before 2.12.4 too, and still does. std::optional current; try { current = get(collection, id); } catch (const Client::PermissionDenied&) { throw; } catch (const Client::Error& e) { failureOut.record(e.code(), e.what()); return false; } if (!current) { // The one failure here the client can name itself, without // reading a server message: get() just said there is no // such document. failureOut.record(Client::ErrorCode::NotFound, "document not found: " + collection + "/" + id, R"({"reason":"not_found"})"); return false; // document doesn't exist } uint64_t version = (*current)["_version"].get(); // Attempt version-checked update. Each attempt overwrites // failureOut, so what the caller reads is the LAST attempt's // reason, and a success leaves it clean. Client::FailureDetail attemptFailure; if (updateIfVersion(collection, id, cleanData, version, actor, &attemptFailure)) { failureOut.reset(); return true; } failureOut.copy(attemptFailure); // v2.13.1 - only a version conflict (another writer between our // get() and this write) is worth another round. Every other // refusal - read-only, memory pressure, a document too large, an // outage - was retried here too and then logged as "version // conflicts", though no retry could change the answer. // A pre-2.12.0 server reports the conflict in-band with no code // (Unknown) and the text "Version conflict". const bool conflict = attemptFailure.code == Client::ErrorCode::Aborted || (attemptFailure.code == Client::ErrorCode::Unknown && attemptFailure.message.find("ersion conflict") != std::string::npos); if (!conflict) { return false; } // Version conflict — another client wrote between our get() and update if (attempt < config_.maxRetries) { spdlog::debug("Client::update version conflict on {}/{}, retry {}/{}", collection, id, attempt + 1, config_.maxRetries); } } spdlog::warn("Client::update failed after {} retries due to version conflicts on {}/{}", config_.maxRetries, collection, id); return false; } bool updateIfVersion(const std::string& collection, const std::string& id, const nlohmann::json& data, uint64_t expectedVersion, const std::string& actor, FailureSink failureOut = {}) { failureOut.reset(); smartbotic::databasepb::UpdateRequest request; request.set_collection(qualify(collection)); request.set_id(id); request.set_data(data.dump()); request.set_expected_version(expectedVersion); if (!actor.empty()) { request.set_actor(actor); } smartbotic::databasepb::UpdateResponse response; grpc::Status status; std::string detailJson; // v2.12.0 - the refusal detail, if any for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->Update(&context, request, &response); detailJson = trailerDetail(context); // v2.12.0 if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) { break; } if (attempt < config_.writeRetries) { uint32_t backoffMs = computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter); spdlog::warn("Client::updateIfVersion {}; retrying in {}ms (attempt {}/{})", status.error_message(), backoffMs, attempt + 1, config_.writeRetries); std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs)); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message()); failureOut.record(status, detailJson); return false; } if (!response.success()) { // Refused in-band: status OK. Since 2.12.0 the response carries the // code the refusal would have as a status; before, Unknown. failureOut.recordInBand(response.error_code(), response.error(), detailJson); } return response.success(); } uint64_t patch(const std::string& collection, const std::string& id, const nlohmann::json& fields, const std::string& actor, std::optional ttlSeconds = std::nullopt, FailureSink failureOut = {}, std::optional expectedVersion = std::nullopt, // v2.12.0 const nlohmann::json* increments = nullptr, // v2.12.0 nlohmann::json* incrementedOut = nullptr) { // v2.12.0 failureOut.reset(); smartbotic::databasepb::PatchDocumentRequest request; request.set_collection(qualify(collection)); // v2.8.0 — presence distinguishes "leave the expiry alone" (absent) from // "clear it" (0) from "set it" (N). if (ttlSeconds.has_value()) request.set_ttl_seconds(*ttlSeconds); request.set_id(id); // v2.12.0 - an increment-only call sends no merge patch. if (!(increments != nullptr && fields.is_object() && fields.empty())) { request.set_patch_json(fields.dump()); } if (expectedVersion.has_value()) request.set_expected_version(*expectedVersion); if (increments != nullptr) request.set_increments_json(increments->dump()); if (!actor.empty()) { request.set_actor(actor); } smartbotic::databasepb::PatchDocumentResponse response; grpc::Status status; std::string detailJson; // v2.12.0 - the refusal detail, if any for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->PatchDocument(&context, request, &response); detailJson = trailerDetail(context); // v2.12.0 if (status.ok() || !retryableStatus(status, /*idempotent=*/!request.has_expected_version() && request.increments_json().empty())) { break; } if (attempt < config_.writeRetries) { uint32_t backoffMs = computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter); spdlog::warn("Client::patch {}; retrying in {}ms (attempt {}/{})", status.error_message(), backoffMs, attempt + 1, config_.writeRetries); std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs)); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::patch failed after retries: {}", status.error_message()); failureOut.record(status, detailJson); return 0; } if (!response.success()) { spdlog::error("Client::patch failed: {}", response.error()); failureOut.recordInBand(response.error_code(), response.error(), detailJson); return 0; } if (incrementedOut != nullptr) { *incrementedOut = response.incremented_json().empty() ? nlohmann::json::object() : nlohmann::json::parse(response.incremented_json()); } return response.new_version(); } std::pair upsert(const std::string& collection, const nlohmann::json& data, const std::string& id, uint32_t ttlSeconds, const std::string& actor) { smartbotic::databasepb::UpsertRequest request; request.set_collection(qualify(collection)); request.set_data(data.dump()); if (!id.empty()) { request.set_id(id); } if (ttlSeconds > 0) { request.set_ttl_seconds(ttlSeconds); } if (!actor.empty()) { request.set_actor(actor); } smartbotic::databasepb::UpsertResponse response; grpc::Status status; std::string detailJson; // v2.12.0 - the refusal detail, if any for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->Upsert(&context, request, &response); detailJson = trailerDetail(context); // v2.12.0 if (status.ok() || !retryableStatus(status, /*idempotent=*/!id.empty())) { break; } if (attempt < config_.writeRetries) { uint32_t backoffMs = computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter); spdlog::warn("Client::upsert {}; retrying in {}ms (attempt {}/{})", status.error_message(), backoffMs, attempt + 1, config_.writeRetries); std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs)); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::upsert failed after retries: {}", status.error_message()); throwStatus(status, status.error_message(), detailJson); } return {response.id(), response.inserted()}; } // errorOut is optional: nullptr keeps the old single-value remove()'s // behaviour (log at spdlog::error and swallow the message). Non-null is // what lets a caller distinguish "already gone" from "blocked" - a // relation with on_delete=restrict/no_action refuses via a real gRPC // FAILED_PRECONDITION, not deleted=false, and that message is the only // way an operator learns WHAT blocked the delete. bool removeImpl(const std::string& collection, const std::string& id, std::string* errorOut, FailureSink failureOut = {}, const std::string& actor = {}) { failureOut.reset(); smartbotic::databasepb::DeleteRequest request; request.set_collection(qualify(collection)); request.set_id(id); if (!actor.empty()) { request.set_actor(actor); } smartbotic::databasepb::DeleteResponse response; grpc::Status status; std::string detailJson; // v2.12.0 - the refusal detail, if any for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->Delete(&context, request, &response); detailJson = trailerDetail(context); // v2.12.0 if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) { break; } if (attempt < config_.writeRetries) { uint32_t backoffMs = computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter); spdlog::warn("Client::remove {}; retrying in {}ms (attempt {}/{})", status.error_message(), backoffMs, attempt + 1, config_.writeRetries); std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs)); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::remove failed after retries: {}", status.error_message()); if (errorOut != nullptr) *errorOut = status.error_message(); failureOut.record(status, detailJson); return false; } return response.deleted(); } bool remove(const std::string& collection, const std::string& id) { return removeImpl(collection, id, nullptr); } bool remove(const std::string& collection, const std::string& id, std::string& errorOut) { errorOut.clear(); return removeImpl(collection, id, &errorOut); } bool remove(const std::string& collection, const std::string& id, Client::Failure& failureOut) { return removeImpl(collection, id, nullptr, &failureOut); } bool removeAs(const std::string& collection, const std::string& id, const std::string& actor, FailureSink failureOut) { return removeImpl(collection, id, nullptr, failureOut, actor); } // v2.12.0 - BatchDelete, which the client never exposed. std::optional removeManyAs(const std::string& collection, const std::vector& ids, const std::string& actor, FailureSink failureOut) { failureOut.reset(); smartbotic::databasepb::BatchDeleteRequest request; request.set_collection(qualify(collection)); for (const auto& id : ids) request.add_ids(id); if (!actor.empty()) request.set_actor(actor); smartbotic::databasepb::BatchDeleteResponse response; grpc::Status status; std::string detailJson; // v2.13.1 - retried only when the server cannot have acted (UNAVAILABLE, // RESOURCE_EXHAUSTED). After a DEADLINE_EXCEEDED the first attempt may // have deleted the ids, and a retry would report them as not found, so // that failure is returned with reason outcome_unknown instead. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) { grpc::ClientContext context; setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1 response.Clear(); status = stub_->BatchDelete(&context, request, &response); detailJson = trailerDetail(context); if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) break; if (attempt < config_.writeRetries) { std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs( config_.writeRetryBackoffMs, attempt, config_.writeRetryMaxBackoffMs, config_.writeRetryJitter))); } } detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1 if (!status.ok()) { spdlog::error("Client::removeManyAs failed: {}", status.error_message()); failureOut.record(status, detailJson); return std::nullopt; } Client::BatchRemoveResult out; out.deletedCount = response.deleted_count(); out.deletedIds.assign(response.deleted_ids().begin(), response.deleted_ids().end()); return out; } bool exists(const std::string& collection, const std::string& id) { smartbotic::databasepb::ExistsRequest request; request.set_collection(qualify(collection)); request.set_id(id); smartbotic::databasepb::ExistsResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->Exists(&context, request, &response); if (!status.ok()) { // v2.8.0 — a permission denial must NOT look like "no data". // Returning empty here would leave an application unable to tell // "you may not see this" from "there is nothing to see", so it // would silently take the wrong branch. Same reasoning as the // v2.4.2 change that stopped Find returning empty for a missing // collection. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) { throw Client::PermissionDenied("access denied: exists"); } spdlog::error("Client::exists failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return response.exists(); } // ===== Query Operations ===== std::vector find(const std::string& collection, const Client::QueryOptions& options, const std::vector& projection = {}, bool includeVector = false) { smartbotic::databasepb::FindRequest request; request.set_collection(qualify(collection)); // Set filters for (const auto& filter : options.filters) { auto* pb = request.add_filters(); pb->set_field(filter.field); pb->set_value(filter.value.dump()); pb->set_op(static_cast(filter.op)); } // Set sorting if (!options.sortField.empty()) { auto* sort = request.mutable_sort(); sort->set_field(options.sortField); sort->set_descending(options.sortDescending); } // Set pagination request.set_limit(options.limit); request.set_offset(options.offset); // v2.7.1 — field projection, passed alongside QueryOptions rather than // inside it: adding a member would change the struct size, and with an // unchanged soname an installed consumer crashes. See client.hpp. for (const auto& f : projection) { request.add_projection(f); } request.set_include_vector(includeVector); // v2.13.0 smartbotic::databasepb::FindResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->Find(&context, request, &response); if (status.error_code() == grpc::StatusCode::NOT_FOUND) { // Surfaced rather than logged: an unknown collection or view is a // caller bug, and returning {} here is indistinguishable from a // legitimately empty result. Since v2.12.4 every other failure // throws too (below). throwStatus(status, status.error_message()); } if (!status.ok()) { // v2.8.0 — a permission denial must NOT look like "no data". // Returning empty here would leave an application unable to tell // "you may not see this" from "there is nothing to see", so it // would silently take the wrong branch. Same reasoning as the // v2.4.2 change that stopped Find returning empty for a missing // collection. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) { throw Client::PermissionDenied("access denied: find"); } spdlog::error("Client::find failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } std::vector results; results.reserve(response.documents_size()); for (const auto& doc : response.documents()) { results.push_back(documentToJson(doc)); } return results; } Client::FindResult findWithMetrics(const std::string& collection, const Client::QueryOptions& options, const std::vector& projection = {}) { smartbotic::databasepb::FindRequest request; request.set_collection(qualify(collection)); // Set filters for (const auto& filter : options.filters) { auto* pb = request.add_filters(); pb->set_field(filter.field); pb->set_value(filter.value.dump()); pb->set_op(static_cast(filter.op)); } // Set sorting if (!options.sortField.empty()) { auto* sort = request.mutable_sort(); sort->set_field(options.sortField); sort->set_descending(options.sortDescending); } // Set pagination request.set_limit(options.limit); request.set_offset(options.offset); // v2.7.1 — field projection, passed alongside QueryOptions rather than // inside it: adding a member would change the struct size, and with an // unchanged soname an installed consumer crashes. See client.hpp. for (const auto& f : projection) { request.add_projection(f); } smartbotic::databasepb::FindResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->Find(&context, request, &response); if (status.error_code() == grpc::StatusCode::NOT_FOUND) { throwStatus(status, status.error_message()); // see find() } if (!status.ok()) { // v2.8.0 — a permission denial must NOT look like "no data". // Returning empty here would leave an application unable to tell // "you may not see this" from "there is nothing to see", so it // would silently take the wrong branch. Same reasoning as the // v2.4.2 change that stopped Find returning empty for a missing // collection. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) { throw Client::PermissionDenied("access denied: findWithMetrics"); } spdlog::error("Client::findWithMetrics failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } Client::FindResult result; result.totalCount = response.total_count(); result.hasMore = response.has_more(); result.usedWalFallback = response.used_wal_fallback(); result.memoryMatchCount = response.memory_match_count(); result.walMatchCount = response.wal_match_count(); result.memorySearchMicros = response.memory_search_micros(); result.walSearchMicros = response.wal_search_micros(); result.documents.reserve(response.documents_size()); for (const auto& doc : response.documents()) { auto json = nlohmann::json::parse(doc.data()); json["_id"] = doc.id(); json["_version"] = doc.version(); json["_created_at"] = doc.created_at(); json["_updated_at"] = doc.updated_at(); json["_created_by"] = doc.created_by(); json["_updated_by"] = doc.updated_by(); result.documents.push_back(json); } return result; } uint64_t count(const std::string& collection, const std::vector& filters) { smartbotic::databasepb::CountRequest request; request.set_collection(qualify(collection)); for (const auto& filter : filters) { auto* pb = request.add_filters(); pb->set_field(filter.field); pb->set_value(filter.value.dump()); pb->set_op(static_cast(filter.op)); } smartbotic::databasepb::CountResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->Count(&context, request, &response); if (!status.ok()) { // v2.8.0 — a permission denial must NOT look like "no data". // Returning empty here would leave an application unable to tell // "you may not see this" from "there is nothing to see", so it // would silently take the wrong branch. Same reasoning as the // v2.4.2 change that stopped Find returning empty for a missing // collection. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) { throw Client::PermissionDenied("access denied: count"); } spdlog::error("Client::count failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return response.count(); } // ===== Set Operations ===== bool setAdd(const std::string& collection, const std::string& setId, const std::string& member) { smartbotic::databasepb::SetAddRequest request; request.set_collection(qualify(collection)); request.set_set_id(setId); request.set_member(member); smartbotic::databasepb::SetAddResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetAdd(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setAdd failed: {}", status.error_message()); return false; } return response.added(); } bool setRemove(const std::string& collection, const std::string& setId, const std::string& member) { smartbotic::databasepb::SetRemoveRequest request; request.set_collection(qualify(collection)); request.set_set_id(setId); request.set_member(member); smartbotic::databasepb::SetRemoveResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetRemove(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setRemove failed: {}", status.error_message()); return false; } return response.removed(); } std::vector setMembers(const std::string& collection, const std::string& setId) { smartbotic::databasepb::SetMembersRequest request; request.set_collection(qualify(collection)); request.set_set_id(setId); smartbotic::databasepb::SetMembersResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetMembers(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setMembers failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return {response.members().begin(), response.members().end()}; } bool setIsMember(const std::string& collection, const std::string& setId, const std::string& member) { smartbotic::databasepb::SetIsMemberRequest request; request.set_collection(qualify(collection)); request.set_set_id(setId); request.set_member(member); smartbotic::databasepb::SetIsMemberResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetIsMember(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setIsMember failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return response.is_member(); } // ===== Collection Management ===== std::vector similaritySearch( const std::string& collection, const std::vector& queryVector, uint32_t topK, float minScore, const std::vector& filters = {}) { // v2.15.0 - a server that answers GetServerInfo and lacks the feature // is refused before sending. A pre-2.15.0 server cannot say, so for it // the response's filters_applied (below) remains the guard. if (!filters.empty()) { const auto si = serverInfo(false); if (si && std::find(si->capabilities.begin(), si->capabilities.end(), Client::Capability::kFilteredSimilarity) == si->capabilities.end()) { requireCapability(Client::Capability::kFilteredSimilarity, "similaritySearch"); } } smartbotic::databasepb::SimilaritySearchRequest request; request.set_collection(qualify(collection)); for (float v : queryVector) { request.add_query_vector(v); } request.set_top_k(topK); request.set_min_score(minScore); for (const auto& filter : filters) { auto* pb = request.add_filters(); pb->set_field(filter.field); pb->set_value(filter.value.dump()); pb->set_op(static_cast(filter.op)); } smartbotic::databasepb::SimilaritySearchResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SimilaritySearch(&context, request, &response); if (!status.ok()) { spdlog::error("Client::similaritySearch failed: {}", status.error_message()); throwStatus(status, status.error_message()); } // v2.14.0 - a pre-2.14.0 server ignores the filters and ranks the // whole collection. Those rows look exactly like a filtered answer, so // they are refused rather than returned. if (!filters.empty() && !response.filters_applied()) { const std::string msg = "similaritySearch: the server does not support filters (needs >= 2.14.0); " "its answer would be unfiltered"; spdlog::error("Client::{}", msg); throw DetailedFailedPrecondition( msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg, R"({"reason":"filters_unsupported"})")); } std::vector results; results.reserve(response.results_size()); for (const auto& r : response.results()) { Client::SimilarityResult entry; entry.id = r.id(); entry.score = r.score(); if (!r.data().empty()) { entry.data = nlohmann::json::parse(r.data()); } results.push_back(std::move(entry)); } return results; } bool createCollection(const std::string& name, uint32_t defaultTtlSeconds, bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) { smartbotic::databasepb::CreateCollectionRequest request; // v2.4.5 — MUST qualify. Sending a bare name here while insert/get/ // find all qualify created TWO collections from one call site: the // bare one received the options (encrypted, maxVersions, // vectorDimension, TTL) and stayed empty, while the qualified one // was created implicitly by the first insert with DEFAULTS. Silent, // and unrecoverable for vectorDimension, which is immutable after // creation. Same class of bug as the v2.4.2 createView break. request.set_name(qualify(name)); auto* options = request.mutable_options(); if (defaultTtlSeconds > 0) { options->set_default_ttl_seconds(defaultTtlSeconds); } options->set_encrypted(encrypted); if (maxVersions > 0) { options->set_max_versions(maxVersions); } if (vectorDimension > 0) { options->set_vector_dimension(vectorDimension); } smartbotic::databasepb::CreateCollectionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->CreateCollection(&context, request, &response); if (!status.ok()) { spdlog::error("Client::createCollection failed: {}", status.error_message()); return false; } return response.created(); } bool dropCollection(const std::string& name) { smartbotic::databasepb::DropCollectionRequest request; // v2.4.5 — MUST qualify. Unqualified, this dropped the empty phantom // created by createCollection and returned TRUE while every document // in : remained readable — a deletion request that // reports success and deletes nothing. request.set_name(qualify(name)); smartbotic::databasepb::DropCollectionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropCollection(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropCollection failed: {}", status.error_message()); return false; } return response.dropped(); } std::vector listCollections() { smartbotic::databasepb::ListCollectionsRequest request; // v2.8.0 — scope the listing to this client's project, so a workspace // never sees another workspace's collection names. request.set_project(config_.project); smartbotic::databasepb::ListCollectionsResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->ListCollections(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listCollections failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } // v2.4.5 — round-trip the naming: callers pass bare names in, so they // get bare names back for their OWN project. Names belonging to other // projects stay visibly qualified rather than being flattened into // ours (same rule as listViews). Note the server still returns every // project's collections; ListCollectionsRequest has no project filter // yet, unlike ListViewsRequest. std::vector out; out.reserve(static_cast(response.names_size())); for (const auto& n : response.names()) { out.push_back(unqualify(n)); } return out; } std::optional getCollectionInfo(const std::string& name) { smartbotic::databasepb::GetCollectionInfoRequest request; // v2.4.5 — MUST qualify, else this reports on the phantom (0 docs) // rather than the collection the caller reads and writes. request.set_name(qualify(name)); smartbotic::databasepb::GetCollectionInfoResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetCollectionInfo(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getCollectionInfo failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } if (!response.found()) { return std::nullopt; } const auto& info = response.info(); Client::CollectionInfo result; result.name = info.name(); result.documentCount = info.document_count(); result.sizeBytes = info.size_bytes(); result.defaultTtlSeconds = info.options().default_ttl_seconds(); result.encrypted = info.options().encrypted(); result.maxVersions = info.options().max_versions(); result.createdAt = info.created_at(); result.updatedAt = info.updated_at(); return result; } // ===== Project Management (v2.3 Stage F) ===== std::vector listProjects() { smartbotic::databasepb::ListProjectsRequest request; smartbotic::databasepb::ListProjectsResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->ListProjects(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listProjects failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return {response.projects().begin(), response.projects().end()}; } bool createProject(const std::string& name) { smartbotic::databasepb::CreateProjectRequest request; request.set_name(name); smartbotic::databasepb::CreateProjectResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->CreateProject(&context, request, &response); if (!status.ok()) { spdlog::error("Client::createProject failed: {}", status.error_message()); throwStatus(status, "createProject transport failure: " + status.error_message()); } if (!response.error().empty()) { // Validation error (invalid name etc.) — surfaced via the // response field, not the gRPC status. throw std::runtime_error("createProject('" + name + "') rejected: " + response.error()); } return response.created(); } void dropProject(const std::string& name) { smartbotic::databasepb::DropProjectRequest request; request.set_name(name); smartbotic::databasepb::DropProjectResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropProject(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropProject failed: {}", status.error_message()); throwStatus(status, "dropProject transport failure: " + status.error_message()); } if (!response.error().empty()) { throw std::runtime_error("dropProject('" + name + "') refused: " + response.error()); } // dropped() may still be false here defensively — but the // server-side contract is dropped==true iff error is empty. } // ===== Collection Configuration ===== bool configureCollection(const std::string& collection, const Client::CollectionConfig& cfg) { smartbotic::databasepb::ConfigureCollectionRequest request; request.set_collection(qualify(collection)); request.mutable_config()->set_timestamp_precision(cfg.timestampPrecision); // v2.4.5 — only send versioning when the caller actually set it, so // the server's partial update leaves it alone otherwise. if (cfg.versioningEnabled.has_value()) { request.mutable_config()->set_versioning_enabled(*cfg.versioningEnabled); } smartbotic::databasepb::ConfigureCollectionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->ConfigureCollection(&context, request, &response); if (!status.ok()) { spdlog::error("Client::configureCollection failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::configureCollection rejected: {}", response.error()); return false; } return true; } Client::CollectionConfig getCollectionConfig(const std::string& collection) { smartbotic::databasepb::GetCollectionConfigRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::GetCollectionConfigResponse response; grpc::ClientContext context; setDeadline(context); Client::CollectionConfig out; auto status = stub_->GetCollectionConfig(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getCollectionConfig failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } out.timestampPrecision = response.config().timestamp_precision(); if (out.timestampPrecision.empty()) out.timestampPrecision = "ms"; // v2.4.5 — always populated on read, so callers get the effective // value rather than the "leave unchanged" sentinel. A server older // than 2.4.5 omits the field; treat that as versioning on, which is // what those builds always did. out.versioningEnabled = response.config().has_versioning_enabled() ? response.config().versioning_enabled() : true; return out; } bool hasCollectionConfig(const std::string& collection) { smartbotic::databasepb::GetCollectionConfigRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::GetCollectionConfigResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetCollectionConfig(&context, request, &response); if (!status.ok()) { spdlog::error("Client::hasCollectionConfig failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } return response.found(); } // v2.11.0 T6b — a METHOD, not a CollectionConfig member (see the header // doc comment for why). Sends a partial update touching ONLY // relations_enforced: timestamp_precision is left unset (empty string, // the server's "leave unchanged" sentinel) and versioning_enabled is // left absent (proto3 field presence), so neither is disturbed. bool setRelationsEnforced(const std::string& collection, bool enforced) { smartbotic::databasepb::ConfigureCollectionRequest request; request.set_collection(qualify(collection)); request.mutable_config()->set_relations_enforced(enforced); smartbotic::databasepb::ConfigureCollectionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->ConfigureCollection(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setRelationsEnforced failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::setRelationsEnforced rejected: {}", response.error()); return false; } return true; } bool getRelationsEnforced(const std::string& collection) { smartbotic::databasepb::GetCollectionConfigRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::GetCollectionConfigResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetCollectionConfig(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getRelationsEnforced failed: {}", status.error_message()); return true; // fail toward the safe (enforced) default } // Defaults to true (enforced) when never explicitly configured - // mirrors the server's CollectionCfg default. return !response.config().has_relations_enforced() || response.config().relations_enforced(); } // v2.11.4 - decides what a relations_enforced read REPORTS, given what // the RPC returned. Split out from the transport so the policy is one // small function with no gRPC plumbing around it. // // Every way of not knowing collapses to nullopt, and nothing throws: // // - A failed status, whatever the code. get()/find()/count() throw on // PERMISSION_DENIED (v2.8.0) because their empty result is a VALID // answer, so a denial returned as empty would be read as "no data". // That hazard does not exist here: nullopt is not a setting, it is // the absence of one, and a caller cannot mistake it for on or off. // One failure channel is also what the name promises. // // - A successful reply WITHOUT the field. A 2.11.0+ server writes it // on every GetCollectionConfig reply - the handler sets it // unconditionally, including for a collection never configured or // not yet created, both of which report the default (true). So an // absent field can only be a server older than 2.11.0, which has no // relations. `true` there would claim enforcement that does not // exist, and `false` would offer a switch that server silently // ignores; the honest reading is that the setting is not there. // getRelationsEnforced() answers true for this case and is left // alone - it is the fail-toward-enforced read by contract. static std::optional interpretRelationsEnforcedRead( const grpc::Status& status, const smartbotic::databasepb::GetCollectionConfigResponse& response ) { if (!status.ok()) return std::nullopt; if (!response.config().has_relations_enforced()) return std::nullopt; return response.config().relations_enforced(); } std::optional tryGetRelationsEnforced(const std::string& collection) { smartbotic::databasepb::GetCollectionConfigRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::GetCollectionConfigResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetCollectionConfig(&context, request, &response); if (!status.ok()) { spdlog::error("Client::tryGetRelationsEnforced failed: {}", status.error_message()); } return interpretRelationsEnforcedRead(status, response); } Client::TimestampMigrationResult migrateCollectionTimestamps( const std::string& collection, const std::string& fromPrecision, const std::string& toPrecision ) { smartbotic::databasepb::MigrateCollectionTimestampsRequest request; request.set_collection(qualify(collection)); request.set_from_precision(fromPrecision); request.set_to_precision(toPrecision); smartbotic::databasepb::MigrateCollectionTimestampsResponse response; grpc::ClientContext context; // Longer deadline — can iterate many rows auto deadline = std::chrono::system_clock::now() + std::chrono::minutes(10); context.set_deadline(deadline); attachAuth(context); Client::TimestampMigrationResult out; auto status = stub_->MigrateCollectionTimestamps(&context, request, &response); if (!status.ok()) { out.success = false; out.error = status.error_message(); return out; } out.success = response.success(); out.error = response.error(); out.rowsMigrated = response.rows_migrated(); out.rowsSkipped = response.rows_skipped(); return out; } // ===== View Management ===== bool createView(const std::string& name, const std::string& collection, const std::vector& include, const std::vector& exclude, const std::vector& where, const std::optional& defaultSort) { smartbotic::databasepb::CreateViewRequest request; // Both fields are namespaced. Qualifying `collection` but not `name` // is what broke view lookups in v2.3: the registry keyed on the bare // name while every read path sent the qualified one, so the keys // could never meet. request.set_name(qualify(name)); request.set_collection(qualify(collection)); for (const auto& p : include) request.add_include(p); for (const auto& p : exclude) request.add_exclude(p); for (const auto& f : where) { auto* pb = request.add_where(); pb->set_field(f.field); pb->set_op(static_cast(f.op)); pb->set_value(f.value.dump()); } if (defaultSort) { auto* s = request.mutable_default_sort(); s->set_field(defaultSort->field); s->set_descending(defaultSort->descending); } smartbotic::databasepb::CreateViewResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->CreateView(&context, request, &response); if (!status.ok()) { spdlog::error("Client::createView failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::createView rejected: {}", response.error()); return false; } return true; } // v2.9.0 — secondary indexes. bool createIndex(const std::string& collection, const std::string& field, uint64_t* rowsIndexed) { smartbotic::databasepb::CreateIndexRequest request; request.set_collection(qualify(collection)); request.set_field(field); smartbotic::databasepb::CreateIndexResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->CreateIndex(&context, request, &response); if (!status.ok()) { spdlog::error("Client::createIndex failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::createIndex rejected: {}", response.error()); return false; } if (rowsIndexed != nullptr) *rowsIndexed = response.rows_indexed(); return true; } bool dropIndex(const std::string& collection, const std::string& field) { smartbotic::databasepb::DropIndexRequest request; request.set_collection(qualify(collection)); request.set_field(field); smartbotic::databasepb::DropIndexResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropIndex(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropIndex failed: {}", status.error_message()); return false; } return response.success(); } // v2.11.0 T11 — unique constraints. Client::CreateIndexResult createUniqueIndex(const std::string& collection, const std::string& field) { smartbotic::databasepb::CreateIndexRequest request; request.set_collection(qualify(collection)); request.set_field(field); request.set_unique(true); smartbotic::databasepb::CreateIndexResponse response; grpc::ClientContext context; setDeadline(context); Client::CreateIndexResult out; auto status = stub_->CreateIndex(&context, request, &response); if (!status.ok()) { out.error = status.error_message(); spdlog::error("Client::createUniqueIndex failed: {}", out.error); return out; } out.success = response.success(); out.error = response.error(); out.rowsIndexed = response.rows_indexed(); out.alreadyExisted = response.already_existed(); out.duplicateExamples.assign(response.duplicate_examples().begin(), response.duplicate_examples().end()); if (!out.success) { spdlog::error("Client::createUniqueIndex rejected: {}", out.error); } return out; } // ===== Collection schema (v2.16.0) ===== Client::SchemaChangeResult schemaChange(const std::string& collection, const std::string& schemaJson, Client::SchemaMode mode) { Client::SchemaChangeResult out; try { requireCapability(Client::Capability::kCollectionSchema, "setCollectionSchema"); } catch (const Client::Error& e) { out.error = e.what(); if (const auto* d = Client::errorDetail(e)) out.reason = d->reason; return out; } smartbotic::databasepb::SetCollectionSchemaRequest request; request.set_collection(qualify(collection)); request.set_schema_json(schemaJson); request.set_mode(mode == Client::SchemaMode::Audit ? "audit" : "enforce"); smartbotic::databasepb::SetCollectionSchemaResponse response; grpc::ClientContext context; // The existing-row check scans the collection: give it the export cap, // not a unary deadline. context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600)); attachAuth(context); auto status = stub_->SetCollectionSchema(&context, request, &response); if (!status.ok()) { const auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(), trailerDetail(context)); out.error = status.error_message(); out.reason = d.reason; spdlog::error("Client::setCollectionSchema failed: {}", out.error); return out; } out.success = response.success(); out.error = response.error(); out.rowsChecked = response.rows_checked(); out.violatingRows = response.violating_rows(); for (const auto& ex : response.examples()) { out.examples.push_back({ex.id(), ex.message(), {ex.fields().begin(), ex.fields().end()}}); } if (!out.success) spdlog::error("Client::setCollectionSchema refused: {}", out.error); return out; } std::optional getCollectionSchema(const std::string& collection) { requireCapability(Client::Capability::kCollectionSchema, "getCollectionSchema"); smartbotic::databasepb::GetCollectionSchemaRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::GetCollectionSchemaResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetCollectionSchema(&context, request, &response); if (!status.ok()) { throwStatus(status, "getCollectionSchema: " + status.error_message(), trailerDetail(context)); } if (!response.has_schema()) return std::nullopt; Client::CollectionSchema out; out.schema = nlohmann::json::parse(response.schema_json()); out.mode = response.mode() == "audit" ? Client::SchemaMode::Audit : Client::SchemaMode::Enforce; out.auditViolations = response.audit_violations(); out.refusals = response.refusals(); out.armed = response.armed(); return out; } Client::SchemaSuggestion suggestCollectionSchema(const std::string& collection, uint64_t sampleLimit) { requireCapability(Client::Capability::kCollectionSchema, "suggestCollectionSchema"); smartbotic::databasepb::SuggestCollectionSchemaRequest request; request.set_collection(qualify(collection)); request.set_sample_limit(sampleLimit); smartbotic::databasepb::SuggestCollectionSchemaResponse response; grpc::ClientContext context; context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600)); attachAuth(context); auto status = stub_->SuggestCollectionSchema(&context, request, &response); if (!status.ok()) { throwStatus(status, "suggestCollectionSchema: " + status.error_message(), trailerDetail(context)); } Client::SchemaSuggestion out; out.schema = nlohmann::json::parse(response.schema_json()); out.rowsScanned = response.rows_scanned(); out.complete = response.complete(); return out; } std::vector listIndexes(const std::string& collection, std::vector* uniqueFlags) { smartbotic::databasepb::ListIndexesRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::ListIndexesResponse response; grpc::ClientContext context; setDeadline(context); std::vector out; auto status = stub_->ListIndexes(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listIndexes failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } out.reserve(response.indexes_size()); if (uniqueFlags != nullptr) { uniqueFlags->clear(); uniqueFlags->reserve(response.indexes_size()); } for (const auto& i : response.indexes()) { // v2.12.0 - a composite unique constraint is not an index on a // field; its `field` is only a display form ("a+b"). Reported by // listCompositeUniqueIndexes() instead, so nothing here can be // mistaken for a real field. if (i.fields_size() > 0) continue; Client::IndexDefinition d; d.field = i.field(); d.distinctValues = i.distinct_values(); d.entries = i.entries(); out.push_back(std::move(d)); if (uniqueFlags != nullptr) uniqueFlags->push_back(i.unique()); } return out; } // v2.12.0 - composite unique constraints. Client::CreateIndexResult createCompositeUniqueIndex(const std::string& collection, const std::vector& fields) { smartbotic::databasepb::CreateIndexRequest request; request.set_collection(qualify(collection)); for (const auto& f : fields) request.add_fields(f); request.set_unique(true); smartbotic::databasepb::CreateIndexResponse response; grpc::ClientContext context; setDeadline(context); Client::CreateIndexResult out; auto status = stub_->CreateIndex(&context, request, &response); if (!status.ok()) { out.error = status.error_message(); spdlog::error("Client::createCompositeUniqueIndex failed: {}", out.error); return out; } out.success = response.success(); out.error = response.error(); out.rowsIndexed = response.rows_indexed(); out.alreadyExisted = response.already_existed(); out.duplicateExamples.assign(response.duplicate_examples().begin(), response.duplicate_examples().end()); if (!out.success) { spdlog::error("Client::createCompositeUniqueIndex rejected: {}", out.error); } return out; } bool dropCompositeUniqueIndex(const std::string& collection, const std::vector& fields) { smartbotic::databasepb::DropIndexRequest request; request.set_collection(qualify(collection)); for (const auto& f : fields) request.add_fields(f); smartbotic::databasepb::DropIndexResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropIndex(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropCompositeUniqueIndex failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::dropCompositeUniqueIndex rejected: {}", response.error()); } return response.success(); } std::vector> listCompositeUniqueIndexes(const std::string& collection) { smartbotic::databasepb::ListIndexesRequest request; request.set_collection(qualify(collection)); smartbotic::databasepb::ListIndexesResponse response; grpc::ClientContext context; setDeadline(context); std::vector> out; auto status = stub_->ListIndexes(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listCompositeUniqueIndexes failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } for (const auto& i : response.indexes()) { if (i.fields_size() > 0) out.emplace_back(i.fields().begin(), i.fields().end()); } return out; } std::vector indexValues(const std::string& collection, const std::string& field, uint32_t limit, bool ascending) { smartbotic::databasepb::GetIndexValuesRequest request; request.set_collection(qualify(collection)); request.set_field(field); request.set_limit(limit); request.set_ascending(ascending); smartbotic::databasepb::GetIndexValuesResponse response; grpc::ClientContext context; setDeadline(context); std::vector out; auto status = stub_->GetIndexValues(&context, request, &response); if (!status.ok()) { spdlog::error("Client::indexValues failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } out.reserve(response.values_size()); for (const auto& v : response.values()) { Client::IndexValue iv; try { iv.value = nlohmann::json::parse(v.value()); } catch (const nlohmann::json::exception&) { continue; } iv.count = v.count(); out.push_back(std::move(iv)); } return out; } bool dropView(const std::string& name) { smartbotic::databasepb::DropViewRequest request; request.set_name(qualify(name)); smartbotic::databasepb::DropViewResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropView(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropView failed: {}", status.error_message()); return false; } return response.success(); } std::vector listViews() { smartbotic::databasepb::ListViewsRequest request; // Scope the listing to this client's workspace. request.set_project(config_.project); smartbotic::databasepb::ListViewsResponse response; grpc::ClientContext context; setDeadline(context); std::vector out; auto status = stub_->ListViews(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listViews failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } for (const auto& pb : response.views()) { Client::ViewDefinition v; // Round-trip: the caller created "adults", so list it as "adults". v.name = unqualify(pb.name()); v.collection = unqualify(pb.collection()); for (const auto& p : pb.include()) v.include.push_back(p); for (const auto& p : pb.exclude()) v.exclude.push_back(p); for (const auto& pbf : pb.where()) { Client::Filter f; f.field = pbf.field(); f.op = static_cast(pbf.op()); try { f.value = nlohmann::json::parse(pbf.value()); } catch (...) { f.value = pbf.value(); } v.where.push_back(f); } if (pb.has_default_sort()) { Client::Sort s; s.field = pb.default_sort().field(); s.descending = pb.default_sort().descending(); v.defaultSort = s; } v.createdAt = pb.created_at(); v.updatedAt = pb.updated_at(); out.push_back(std::move(v)); } return out; } std::optional getViewInfo(const std::string& name) { smartbotic::databasepb::GetViewInfoRequest request; request.set_name(qualify(name)); smartbotic::databasepb::GetViewInfoResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetViewInfo(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getViewInfo failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } if (!response.found()) { return std::nullopt; } Client::ViewDefinition v; v.name = unqualify(response.view().name()); v.collection = unqualify(response.view().collection()); for (const auto& p : response.view().include()) v.include.push_back(p); for (const auto& p : response.view().exclude()) v.exclude.push_back(p); for (const auto& pbf : response.view().where()) { Client::Filter f; f.field = pbf.field(); f.op = static_cast(pbf.op()); try { f.value = nlohmann::json::parse(pbf.value()); } catch (...) { f.value = pbf.value(); } v.where.push_back(f); } if (response.view().has_default_sort()) { Client::Sort s; s.field = response.view().default_sort().field(); s.descending = response.view().default_sort().descending(); v.defaultSort = s; } v.createdAt = response.view().created_at(); v.updatedAt = response.view().updated_at(); return v; } // ===== v2.11.0 T6b — relation (referential integrity) management ===== Client::RelationDefinition relationFromProto( const smartbotic::databasepb::RelationDefinition& pb) const { Client::RelationDefinition r; // Round-trip like listViews(): the caller declared "posts_by_user", // it should list back as "posts_by_user", not "myproject:posts_by_user". r.name = unqualify(pb.name()); r.child = unqualify(pb.child()); r.childField = pb.child_field(); r.parent = unqualify(pb.parent()); r.onDelete = pb.on_delete().empty() ? "restrict" : pb.on_delete(); r.validateOnWrite = pb.validate_on_write(); r.createdAt = pb.created_at(); r.updatedAt = pb.updated_at(); return r; } bool createRelation(const std::string& name, const std::string& childCollection, const std::string& childField, const std::string& parentCollection, const std::string& onDelete, bool validateOnWrite, uint64_t* rowsIndexed) { smartbotic::databasepb::CreateRelationRequest request; // name, child AND parent all need qualifying - qualifying only // `child`/`parent` but not `name` is exactly the v2.4.2 createView // bug (registry keyed on the bare name, every lookup sent the // qualified one, the keys never met). request.set_name(qualify(name)); request.set_child(qualify(childCollection)); request.set_child_field(childField); request.set_parent(qualify(parentCollection)); request.set_on_delete(onDelete); request.set_validate_on_write(validateOnWrite); smartbotic::databasepb::CreateRelationResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->CreateRelation(&context, request, &response); if (!status.ok()) { spdlog::error("Client::createRelation failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::createRelation rejected: {}", response.error()); return false; } // v2.11.0 T7 - the server's bootstrap scan already backfilled the // reverse index over any rows present in childCollection. if (rowsIndexed != nullptr) *rowsIndexed = response.rows_indexed(); return true; } bool dropRelation(const std::string& name) { smartbotic::databasepb::DropRelationRequest request; request.set_name(qualify(name)); smartbotic::databasepb::DropRelationResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DropRelation(&context, request, &response); if (!status.ok()) { spdlog::error("Client::dropRelation failed: {}", status.error_message()); return false; } if (!response.success()) { spdlog::error("Client::dropRelation rejected: {}", response.error()); return false; } return true; } std::vector listRelations() { // Scope the listing to this client's workspace, like listViews(). return listRelationsIn(config_.project); } // v2.11.1 — empty `project` means every project, which is what the wire // contract has always said and what an operator tool needs. std::vector listRelationsIn(const std::string& project) { smartbotic::databasepb::ListRelationsRequest request; request.set_project(project); smartbotic::databasepb::ListRelationsResponse response; grpc::ClientContext context; setDeadline(context); std::vector out; auto status = stub_->ListRelations(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listRelations failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } out.reserve(response.relations_size()); for (const auto& pb : response.relations()) { out.push_back(relationFromProto(pb)); } return out; } std::optional getRelationInfo(const std::string& name) { smartbotic::databasepb::GetRelationInfoRequest request; request.set_name(qualify(name)); smartbotic::databasepb::GetRelationInfoResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetRelationInfo(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getRelationInfo failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } if (!response.found()) { return std::nullopt; } return relationFromProto(response.relation()); } // v2.11.0 T5 — "what would happen if I deleted this?" Gated as an // ordinary read server-side, so `collection` is qualified the same way // get()/find() qualify theirs - not the admin-only qualify() used by // the relation-management calls above (which is the same call, just a // reminder this one follows the read family, not the admin family). Client::DescribeDeleteResult describeDelete(const std::string& collection, const std::string& id) { smartbotic::databasepb::DescribeDeleteRequest request; request.set_collection(qualify(collection)); request.set_id(id); smartbotic::databasepb::DescribeDeleteResponse response; grpc::ClientContext context; setDeadline(context); Client::DescribeDeleteResult out; auto status = stub_->DescribeDelete(&context, request, &response); if (!status.ok()) { spdlog::error("Client::describeDelete failed: {}", status.error_message()); out.success = false; out.error = status.error_message(); return out; } out.success = response.success(); out.error = response.error(); out.wouldBeBlocked = response.would_be_blocked(); out.impacts.reserve(response.impacts_size()); for (const auto& pbImpact : response.impacts()) { Client::RelationImpact impact; impact.relation = unqualify(pbImpact.relation()); impact.childCollection = unqualify(pbImpact.child_collection()); impact.childField = pbImpact.child_field(); impact.onDelete = pbImpact.on_delete(); impact.childCount = pbImpact.child_count(); impact.sampleChildIds.assign(pbImpact.sample_child_ids().begin(), pbImpact.sample_child_ids().end()); impact.blocks = pbImpact.blocks(); out.impacts.push_back(std::move(impact)); } return out; } // v2.11.0 T7 - "does this relation's reverse index actually match live // data?" Read-only; qualified like the other relation-management calls // (getRelationInfo etc.), since a relation name is admin-scoped the same // way regardless of which call reads it. Client::CheckRelationResult checkRelation(const std::string& name) { smartbotic::databasepb::CheckRelationRequest request; request.set_name(qualify(name)); smartbotic::databasepb::CheckRelationResponse response; grpc::ClientContext context; setDeadline(context); Client::CheckRelationResult out; auto status = stub_->CheckRelation(&context, request, &response); if (!status.ok()) { spdlog::error("Client::checkRelation failed: {}", status.error_message()); out.success = false; out.error = status.error_message(); return out; } out.success = response.success(); out.error = response.error(); out.totalDangling = response.total_dangling(); out.dangling.reserve(response.dangling_size()); for (const auto& pbd : response.dangling()) { Client::DanglingReference d; d.parentId = pbd.parent_id(); d.childCount = pbd.child_count(); d.sampleChildIds.assign(pbd.sample_child_ids().begin(), pbd.sample_child_ids().end()); out.dangling.push_back(std::move(d)); } return out; } // ===== Event Subscription ===== class SubscriptionHandle { public: SubscriptionHandle(std::shared_ptr ctx, std::unique_ptr> reader, std::thread readerThread) : context_(std::move(ctx)) , reader_(std::move(reader)) , readerThread_(std::move(readerThread)) , active_(true) {} ~SubscriptionHandle() { cancel(); } void cancel() { if (active_.exchange(false)) { context_->TryCancel(); if (readerThread_.joinable()) { readerThread_.join(); } } } private: std::shared_ptr context_; std::unique_ptr> reader_; std::thread readerThread_; std::atomic active_; }; // v2.12.0 - the original callback shape, delivered from the one reader // loop below so both subscription forms decode events identically. std::shared_ptr subscribe(const std::vector& collections, Client::EventCallback callback) { return subscribeEvents(collections, [callback = std::move(callback)](const Client::Event& e) { callback(e.collection, e.id, e.eventType, e.data); }); } std::shared_ptr subscribeEvents(const std::vector& collections, Client::EventHandler handler) { auto context = std::make_shared(); // Subscribe is a long-running stream — no deadline — but the auth // metadata still has to land on the initial request headers. attachAuth(*context); smartbotic::databasepb::SubscribeRequest request; // v2.8.0 — subscribe was the one call left unqualified while every // document call qualified. Two consequences, both cross-project leaks: // // * a bare name matched nothing, because events carry the qualified // collection - so subscriptions silently never fired; // * an EMPTY list means "every collection" server-side, which meant // every collection in every PROJECT. // // Named collections are qualified like any other. For the "everything" // case we send a `:*` pattern instead of an empty request, so // "all" means all of MY project. That needs no proto change - the // pattern field already existed. for (const auto& coll : collections) { request.add_collections(qualify(coll)); } if (collections.empty()) { request.add_patterns(config_.project + ":*"); } request.set_include_data(true); auto reader = stub_->Subscribe(context.get(), request); // Create reader thread auto readerThread = std::thread([reader = reader.get(), handler = std::move(handler)]() { smartbotic::databasepb::DatabaseEvent event; while (reader->Read(&event)) { // v2.13.0 - nothing may escape this thread: an exception leaving a // std::thread calls std::terminate, so one throwing handler (or one // event body that does not parse) used to take the whole consumer // process down. The event is logged and dropped; the stream goes on. try { std::optional data; if (!event.data().empty()) { data = nlohmann::json::parse(event.data()); } // Convert proto event type to string std::string eventType; switch (event.type()) { case smartbotic::databasepb::EVENT_INSERT: eventType = "insert"; break; case smartbotic::databasepb::EVENT_UPDATE: eventType = "update"; break; case smartbotic::databasepb::EVENT_DELETE: eventType = "delete"; break; case smartbotic::databasepb::EVENT_EXPIRE: eventType = "expire"; break; case smartbotic::databasepb::EVENT_INVALIDATE: eventType = "invalidate"; break; default: eventType = "unknown"; break; } Client::Event out; out.collection = event.collection(); out.id = event.document_id(); out.eventType = std::move(eventType); out.data = std::move(data); out.actor = event.actor(); out.timestamp = event.timestamp(); out.nodeId = event.node_id(); handler(out); } catch (const std::exception& e) { spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler " "or its parse threw: {}", event.collection(), event.document_id(), e.what()); } catch (...) { spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler " "threw a non-std exception", event.collection(), event.document_id()); } } }); return std::make_shared( std::move(context), std::move(reader), std::move(readerThread) ); } // ===== Export (v2.13.0) ===== // // The server's contract is in the proto, above ExportRequest. What this // side adds: a stream that ends without its trailer THROWS (it is not a // complete export, whatever it delivered); an unrecognised vector dtype // THROWS rather than being reinterpreted; and a handler returning false // stops the export AFTER that row, which therefore counts as delivered // (lastId names it, so a resume starts after it). Client::ExportSummary exportCollection( const std::string& collection, bool includeVectors, const std::string& afterId, const std::function& onHeader, const std::function& onRow, uint32_t batchRows) { smartbotic::databasepb::ExportRequest request; request.set_collection(qualify(collection)); request.set_include_vectors(includeVectors); request.set_after_id(afterId); request.set_batch_rows(batchRows); // Not the per-call timeout: an export is long by design. The server // ends a stream at its own cap (header.max_stream_seconds, 600) with a // resume cursor; this deadline is only the backstop for a server that // stops answering. grpc::ClientContext context; context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(900)); attachAuth(context); auto reader = stub_->ExportCollection(&context, request); auto abandon = [&]() { context.TryCancel(); smartbotic::databasepb::ExportChunk drain; while (reader->Read(&drain)) {} (void)reader->Finish(); }; Client::ExportSummary summary; bool sawHeader = false; bool sawTrailer = false; smartbotic::databasepb::ExportTrailer trailer; smartbotic::databasepb::ExportChunk chunk; while (reader->Read(&chunk)) { if (chunk.has_header()) { const auto& h = chunk.header(); if (h.vector_dtype() != "float32-le") { abandon(); const std::string msg = "export: unrecognised vector dtype '" + h.vector_dtype() + "'; refusing to reinterpret the bytes"; throw DetailedError(Client::ErrorCode::Unimplemented, msg, makeDetail(Client::ErrorCode::Unimplemented, msg, {})); } sawHeader = true; Client::ExportHeader out; out.collection = unqualify(h.collection()); out.vectorDimension = h.vector_dimension(); out.vectorDtype = h.vector_dtype(); out.rowsAtSnapshot = h.rows_at_snapshot(); out.batchRowsCap = h.batch_rows_cap(); out.maxStreamSeconds = h.max_stream_seconds(); if (onHeader) { try { onHeader(out); } catch (...) { abandon(); throw; } } } else if (chunk.has_rows()) { for (auto& r : *chunk.mutable_rows()->mutable_rows()) { Client::ExportRow row; row.id = r.document().id(); row.vectorState = static_cast(r.vector_state()); const std::string& bytes = r.document().vector(); if (!bytes.empty()) { if (bytes.size() % sizeof(float) != 0) { abandon(); const std::string msg = "export: vector of '" + row.id + "' is not a whole number of float32 values"; throw DetailedError(Client::ErrorCode::DataLoss, msg, makeDetail(Client::ErrorCode::DataLoss, msg, {})); } row.vector.resize(bytes.size() / sizeof(float)); std::memcpy(row.vector.data(), bytes.data(), bytes.size()); r.mutable_document()->clear_vector(); // the vector is row.vector, not "_vector" } row.document = documentToJson(r.document()); std::string id = row.id; bool more = true; try { more = onRow(std::move(row)); } catch (...) { abandon(); throw; } ++summary.rowsSent; summary.lastId = std::move(id); if (!more) { abandon(); summary.complete = false; return summary; } } } else if (chunk.has_trailer()) { sawTrailer = true; trailer = chunk.trailer(); } } auto status = reader->Finish(); if (!status.ok()) { spdlog::error("Client::exportCollection failed: {}", status.error_message()); throwStatus(status, status.error_message(), trailerDetail(context)); } if (!sawHeader || !sawTrailer) { const std::string msg = "export of '" + collection + "' ended without its trailer " "after " + std::to_string(summary.rowsSent) + " rows; it did not complete"; throw DetailedError(Client::ErrorCode::Unavailable, msg, makeDetail(Client::ErrorCode::Unavailable, msg, {})); } if (trailer.rows_sent() != summary.rowsSent) { const std::string msg = "export of '" + collection + "': server reports " + std::to_string(trailer.rows_sent()) + " rows sent, " + std::to_string(summary.rowsSent) + " arrived"; throw DetailedError(Client::ErrorCode::DataLoss, msg, makeDetail(Client::ErrorCode::DataLoss, msg, {})); } summary.complete = trailer.complete(); return summary; } // ===== Version History ===== Client::VersionHistoryResult getVersionHistory(const std::string& collection, const std::string& id, uint32_t limit, uint32_t offset) { smartbotic::databasepb::GetVersionHistoryRequest request; request.set_collection(qualify(collection)); request.set_id(id); if (limit > 0) request.set_limit(limit); if (offset > 0) request.set_offset(offset); smartbotic::databasepb::GetVersionHistoryResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetVersionHistory(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getVersionHistory failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } Client::VersionHistoryResult result; result.currentVersion = response.current_version(); result.totalCount = response.total_count(); result.documentDeleted = response.document_deleted(); result.versions.reserve(response.versions_size()); for (const auto& ver : response.versions()) { Client::VersionEntry entry; entry.version = ver.version(); entry.timestamp = ver.timestamp(); entry.updatedBy = ver.updated_by(); if (!ver.data().empty()) { entry.data = nlohmann::json::parse(ver.data()); } result.versions.push_back(std::move(entry)); } return result; } std::optional getDocumentVersion(const std::string& collection, const std::string& id, uint64_t version) { smartbotic::databasepb::GetDocumentVersionRequest request; request.set_collection(qualify(collection)); request.set_id(id); request.set_version(version); smartbotic::databasepb::GetDocumentVersionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetDocumentVersion(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getDocumentVersion failed: {}", status.error_message()); throwStatus(status, status.error_message()); // v2.12.4: never empty on failure } if (!response.found()) { return std::nullopt; } Client::VersionEntry entry; entry.version = response.version_entry().version(); entry.timestamp = response.version_entry().timestamp(); entry.updatedBy = response.version_entry().updated_by(); if (!response.version_entry().data().empty()) { entry.data = nlohmann::json::parse(response.version_entry().data()); } return entry; } uint64_t restoreVersion(const std::string& collection, const std::string& id, uint64_t version, const std::string& actor) { smartbotic::databasepb::RestoreVersionRequest request; request.set_collection(qualify(collection)); request.set_id(id); request.set_version(version); if (!actor.empty()) request.set_actor(actor); smartbotic::databasepb::RestoreVersionResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->RestoreVersion(&context, request, &response); if (!status.ok()) { spdlog::error("Client::restoreVersion failed: {}", status.error_message()); return 0; } if (!response.success()) { spdlog::error("Client::restoreVersion: {}", response.error()); return 0; } return response.new_version(); } std::pair restoreToDate(const std::string& collection, const std::string& id, uint64_t timestamp, const std::string& actor) { smartbotic::databasepb::RestoreToDateRequest request; request.set_collection(qualify(collection)); request.set_id(id); request.set_timestamp(timestamp); if (!actor.empty()) request.set_actor(actor); smartbotic::databasepb::RestoreToDateResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->RestoreToDate(&context, request, &response); if (!status.ok()) { spdlog::error("Client::restoreToDate failed: {}", status.error_message()); return {0, 0}; } if (!response.success()) { spdlog::error("Client::restoreToDate: {}", response.error()); return {0, 0}; } return {response.restored_version(), response.new_version()}; } // ===== Health ===== bool healthCheck() { smartbotic::databasepb::HealthCheckRequest request; smartbotic::databasepb::HealthCheckResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->HealthCheck(&context, request, &response); if (!status.ok()) { return false; } return response.healthy(); } std::optional getHealthInfo() { smartbotic::databasepb::HealthCheckRequest request; smartbotic::databasepb::HealthCheckResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->HealthCheck(&context, request, &response); if (!status.ok()) { return std::nullopt; } Client::HealthInfo info; info.healthy = response.healthy(); info.uptimeMs = response.uptime_seconds() * 1000; info.documentCount = response.document_count(); info.memoryUsedBytes = response.memory_used_bytes(); info.walSizeBytes = response.wal_size_bytes(); return info; } std::optional getStats() { smartbotic::databasepb::GetStatsRequest request; smartbotic::databasepb::GetStatsResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetStats(&context, request, &response); if (!status.ok()) { return std::nullopt; } Client::StatsInfo info; info.totalDocuments = response.total_documents(); info.totalCollections = response.total_collections(); info.memoryUsedBytes = response.memory_used_bytes(); info.walSequence = response.wal_sequence(); info.walSizeBytes = response.wal_size_bytes(); info.snapshotCount = response.snapshot_count(); info.lastSnapshotSequence = response.last_snapshot_sequence(); info.insertCount = response.insert_count(); info.updateCount = response.update_count(); info.deleteCount = response.delete_count(); info.queryCount = response.query_count(); // Memory eviction stats info.evictedDocuments = response.evicted_documents(); info.totalEvictions = response.total_evictions(); info.recoveryCount = response.recovery_count(); // Memory configuration info.maxMemoryBytes = response.max_memory_bytes(); info.evictionThresholdPercent = response.eviction_threshold_percent(); info.evictionTargetPercent = response.eviction_target_percent(); // Operation timing (microseconds) - for performance monitoring info.getCount = response.get_count(); info.getTotalMicros = response.get_total_micros(); info.getMaxMicros = response.get_max_micros(); info.insertTotalMicros = response.insert_total_micros(); info.insertMaxMicros = response.insert_max_micros(); info.updateTotalMicros = response.update_total_micros(); info.updateMaxMicros = response.update_max_micros(); info.queryTotalMicros = response.query_total_micros(); info.queryMaxMicros = response.query_max_micros(); return info; } Client::MemoryStats getMemoryStats() { smartbotic::databasepb::GetMemoryStatsRequest request; smartbotic::databasepb::GetMemoryStatsResponse response; grpc::ClientContext context; setDeadline(context); Client::MemoryStats out; auto status = stub_->GetMemoryStats(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getMemoryStats failed: {}", status.error_message()); return out; } out.totalMemoryBytes = response.total_memory_bytes(); out.maxMemoryBytes = response.max_memory_bytes(); out.pressurePercent = response.pressure_percent(); out.pressureLevel = response.pressure_level(); out.lastEvictionTimestamp = response.last_eviction_timestamp(); out.lastEvictionDocs = response.last_eviction_docs(); out.lastEvictionBytesFreed = response.last_eviction_bytes_freed(); out.collections.reserve(response.collections_size()); for (const auto& pbc : response.collections()) { Client::MemoryCollectionStats c; c.collection = pbc.collection(); c.documentCount = pbc.document_count(); c.estimatedBytes = pbc.estimated_bytes(); c.evictedStubCount = pbc.evicted_stub_count(); switch (pbc.priority()) { case smartbotic::databasepb::MEMORY_PRIORITY_LOW: c.priority = "low"; break; case smartbotic::databasepb::MEMORY_PRIORITY_NORMAL: c.priority = "normal"; break; case smartbotic::databasepb::MEMORY_PRIORITY_HIGH: c.priority = "high"; break; default: c.priority = "normal"; break; } out.collections.push_back(std::move(c)); } return out; } // ===== Read-Only Control ===== bool setReadOnly(bool readOnly) { smartbotic::databasepb::SetReadOnlyRequest request; request.set_read_only(readOnly); smartbotic::databasepb::SetReadOnlyResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetReadOnly(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setReadOnly failed: {}", status.error_message()); return false; } return response.success(); } Client::ReadOnlyStatus getReadOnlyStatus() { smartbotic::databasepb::GetReadOnlyStatusRequest request; smartbotic::databasepb::GetReadOnlyStatusResponse response; grpc::ClientContext context; setDeadline(context); Client::ReadOnlyStatus out; auto status = stub_->GetReadOnlyStatus(&context, request, &response); if (!status.ok()) { spdlog::error("Client::getReadOnlyStatus failed: {}", status.error_message()); return out; } out.readOnly = response.read_only(); out.reason = response.reason(); out.recoveryOutcome = response.recovery_outcome(); out.expectedSnapshot = response.expected_snapshot(); out.snapshotUsed = response.snapshot_used(); out.failureReason = response.failure_reason(); out.walEntriesReplayed = response.wal_entries_replayed(); out.snapshotsAttempted = response.snapshots_attempted(); return out; } // ===== File Operations ===== Client::FileUploadResult uploadFile(const std::vector& data, const Client::FileUploadMeta& meta, uint32_t ttlSeconds = 0, bool explicitTtl = false) { grpc::ClientContext context; auto timeout_ms = config_.timeoutMs + (data.size() / (1024 * 1024)) * 1000; context.set_deadline( std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_ms)); attachAuth(context); smartbotic::databasepb::UploadFileResponse response; auto writer = stub_->UploadFile(&context, &response); // First chunk: metadata smartbotic::databasepb::FileChunk metaChunk; auto* m = metaChunk.mutable_metadata(); m->set_name(meta.name); m->set_mime_type(meta.mime_type); m->set_file_type(meta.file_type); m->set_related_id(meta.related_id); m->set_is_public(meta.is_public); // v2.6.0 — files are namespaced like collections. Filled from // Config::project so callers keep passing bare ids and names. m->set_project(config_.project); // v2.8.0 — relative TTL; the server converts it to an absolute expiry. // Set unconditionally on this overload: calling it IS the explicit // choice, and 0 therefore means "never expire, ignore any configured // default for this file type". The two-argument uploadFile() leaves the // field absent so the default applies. if (explicitTtl) m->set_ttl_seconds(ttlSeconds); for (const auto& [key, value] : meta.metadata) { (*m->mutable_metadata())[key] = value; } writer->Write(metaChunk); // Data chunks (64KB each) constexpr size_t CHUNK_SIZE = 64 * 1024; for (size_t offset = 0; offset < data.size(); offset += CHUNK_SIZE) { smartbotic::databasepb::FileChunk dataChunk; size_t chunkSize = std::min(CHUNK_SIZE, data.size() - offset); dataChunk.set_data(data.data() + offset, chunkSize); if (!writer->Write(dataChunk)) break; } writer->WritesDone(); auto status = writer->Finish(); if (!status.ok()) { spdlog::error("Client::uploadFile failed: {}", status.error_message()); throwStatus(status, status.error_message(), trailerDetail(context)); // v2.12.3: reason file_too_large / mime_type_not_allowed } return {response.id(), response.size(), response.checksum(), response.deduplicated()}; } std::vector downloadFile(const std::string& id) { // v2.6.0 — see note in uploadFile; project scopes every file call. smartbotic::databasepb::DownloadFileRequest request; request.set_id(id); request.set_project(config_.project); grpc::ClientContext context; context.set_deadline( std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs * 10)); attachAuth(context); auto reader = stub_->DownloadFile(&context, request); std::vector fileData; smartbotic::databasepb::FileChunk chunk; while (reader->Read(&chunk)) { if (chunk.has_data()) { const auto& d = chunk.data(); fileData.insert(fileData.end(), d.begin(), d.end()); } } auto status = reader->Finish(); if (!status.ok()) { spdlog::error("Client::downloadFile failed: {}", status.error_message()); throwStatus(status, status.error_message()); } return fileData; } std::optional getFileInfo(const std::string& id) { smartbotic::databasepb::GetFileInfoRequest request; request.set_id(id); request.set_project(config_.project); smartbotic::databasepb::FileInfo response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetFileInfo(&context, request, &response); if (!status.ok()) { if (status.error_code() == grpc::StatusCode::NOT_FOUND) return std::nullopt; spdlog::error("Client::getFileInfo failed: {}", status.error_message()); throwStatus(status, status.error_message()); } Client::FileRecord record; record.id = response.id(); record.name = response.name(); record.mime_type = response.mime_type(); record.size = response.size(); record.file_type = response.file_type(); record.related_id = response.related_id(); record.checksum = response.checksum(); record.is_public = response.is_public(); record.ref_count = response.ref_count(); record.created_at = response.created_at(); record.project = response.project(); for (const auto& [key, value] : response.metadata()) { record.metadata[key] = value; } return record; } // v2.13.0 - `failureOut` tells "no such file" (NotFound, answered in-band // by the server) from a call that failed (the real code). The bool-only // public form passes no sink and behaves exactly as before. bool deleteFile(const std::string& id, FailureSink failureOut = {}) { failureOut.reset(); smartbotic::databasepb::DeleteFileRequest request; request.set_id(id); request.set_project(config_.project); smartbotic::databasepb::DeleteFileResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->DeleteFile(&context, request, &response); if (!status.ok()) { spdlog::error("Client::deleteFile failed: {}", status.error_message()); failureOut.record(status); return false; } if (!response.deleted()) { failureOut.record(Client::ErrorCode::NotFound, "no such file in this project"); } return response.deleted(); } // v2.13.0 - same contract as deleteFile above. bool setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureSink failureOut = {}) { failureOut.reset(); smartbotic::databasepb::SetFileTtlRequest request; request.set_id(id); request.set_project(config_.project); request.set_ttl_seconds(ttlSeconds); smartbotic::databasepb::SetFileTtlResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->SetFileTtl(&context, request, &response); if (!status.ok()) { spdlog::error("Client::setFileTtl failed: {}", status.error_message()); failureOut.record(status); return false; } if (!response.updated()) { failureOut.record(Client::ErrorCode::NotFound, "no such file in this project, or it has already expired"); } return response.updated(); } Client::FileListResult listFiles(const std::string& file_type, const std::string& related_id, uint32_t limit, uint32_t offset, const std::string& checksum, const std::string& name) { smartbotic::databasepb::ListFilesRequest request; if (!file_type.empty()) request.set_file_type(file_type); if (!related_id.empty()) request.set_related_id(related_id); request.set_limit(limit); request.set_offset(offset); if (!checksum.empty()) request.set_checksum(checksum); if (!name.empty()) request.set_name(name); request.set_project(config_.project); smartbotic::databasepb::ListFilesResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->ListFiles(&context, request, &response); if (!status.ok()) { spdlog::error("Client::listFiles failed: {}", status.error_message()); throwStatus(status, status.error_message()); } Client::FileListResult result; result.total_count = response.total_count(); result.has_more = response.has_more(); for (const auto& f : response.files()) { Client::FileRecord record; record.id = f.id(); record.name = f.name(); record.mime_type = f.mime_type(); record.size = f.size(); record.file_type = f.file_type(); record.related_id = f.related_id(); record.checksum = f.checksum(); record.is_public = f.is_public(); record.created_at = f.created_at(); record.project = f.project(); for (const auto& [key, value] : f.metadata()) { record.metadata[key] = value; } result.files.push_back(std::move(record)); } return result; } private: // Per-context setup: deadline + (v2.4) bearer-token auth metadata. // // Most RPC call sites in this library funnel through this helper — // unary (insert, get, update, ...) plus the unary file ops that need // the default deadline. Long-running streams (Subscribe) and the // file-streaming RPCs (UploadFile/DownloadFile) compute their own // deadlines and call `attachAuth()` separately so the auth metadata // still lands on every outbound RPC. Centralising both concerns here // means we don't need a gRPC ClientInterceptorFactoryInterface — the // interceptor route is also offered by gRPC++ but it sits in // grpc::experimental:: and would need to be re-validated on every // grpc minor; the per-context style keeps Stage E independent of // gRPC's TLS/interceptor experimental flux. void setDeadline(grpc::ClientContext& context) { context.set_deadline( std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs) ); attachAuth(context); } // v2.13.1 - a write's deadline grows with its size: timeoutMs plus one // second per 4 MiB sent. A 20 MiB patch on a 60 MiB row legitimately takes // longer than a small write, and a fixed deadline made it time out while the // server completed it - the shape that produced "failed" writes that had // been applied. void setWriteDeadline(grpc::ClientContext& context, size_t requestBytes) { const auto extraMs = static_cast(requestBytes / (4u * 1024 * 1024)) * 1000; context.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs + extraMs)); attachAuth(context); } // v2.4 — attach the bearer-token authorization metadata if configured. // Use this on contexts that set their own deadline (streams, // long-running ops) so the auth metadata still lands. // // v2.15.0 - every call also carries this library's version, so a server can // keep an old behaviour for an old client if a meaning ever has to change. // Every context passes through here (setDeadline, setWriteDeadline, the // streams), which is why the header is attached here and not elsewhere. void attachAuth(grpc::ClientContext& context) { context.AddMetadata("sbdb-client-version", SMARTBOTIC_DB_VERSION_STRING); if (!config_.auth_token.empty()) { context.AddMetadata("authorization", "Bearer " + config_.auth_token); } } public: // ===== Server info and capabilities (v2.15.0) ===== std::optional serverInfo(bool refresh) { { std::lock_guard lk(infoMu_); if (!refresh && infoFetched_ && std::chrono::steady_clock::now() - infoAt_ < std::chrono::seconds(60)) { return info_; } } smartbotic::databasepb::GetServerInfoRequest request; smartbotic::databasepb::GetServerInfoResponse response; grpc::ClientContext context; setDeadline(context); auto status = stub_->GetServerInfo(&context, request, &response); std::optional got; if (status.ok()) { Client::ServerInfo si; si.version = response.version(); si.commit = response.commit(); si.capabilities.assign(response.capabilities().begin(), response.capabilities().end()); si.clientVersionSeen = response.client_version(); got = std::move(si); } else if (status.error_code() != grpc::StatusCode::UNIMPLEMENTED) { // An outage is not "an old server": answering nullopt here would // make every 2.15.0+ feature look unsupported during a blip. throwStatus(status, "serverInfo: " + status.error_message(), trailerDetail(context)); } // UNIMPLEMENTED: a pre-2.15.0 server. Cached like an answer. std::lock_guard lk(infoMu_); info_ = got; infoFetched_ = true; infoAt_ = std::chrono::steady_clock::now(); return got; } bool serverSupports(const std::string& capability) { const auto si = serverInfo(false); if (!si) return false; return std::find(si->capabilities.begin(), si->capabilities.end(), capability) != si->capabilities.end(); } // For client methods that need a feature introduced in 2.15.0 or later: // refuse BEFORE sending, because an old server ignores what it does not // understand and answers something that looks right. void requireCapability(const char* capability, const char* what) { if (serverSupports(capability)) return; const auto si = serverInfo(false); const std::string msg = std::string(what) + ": the server does not support '" + capability + "' (server " + (si ? si->version : std::string("older than 2.15.0")) + ")"; spdlog::error("Client::{}", msg); throw DetailedFailedPrecondition( msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg, R"({"reason":"server_unsupported"})")); } private: std::mutex infoMu_; bool infoFetched_ = false; std::optional info_; std::chrono::steady_clock::time_point infoAt_{}; Config config_; std::shared_ptr channel_; std::unique_ptr stub_; std::atomic connected_{false}; std::atomic reached_{false}; // v2.13.1 - the last connect() attempt succeeded }; // ===== Client Public Interface Implementation ===== Client::Client(Config config) : impl_(std::make_unique(std::move(config))) {} Client::~Client() = default; Client::Client(Client&&) noexcept = default; Client& Client::operator=(Client&&) noexcept = default; bool Client::connect() { return impl_->connect(); } bool Client::isConnected() const { return impl_->isConnected(); } std::string Client::insert(const std::string& collection, const nlohmann::json& data, const std::string& id, uint32_t ttlSeconds, const std::string& actor) { return impl_->insert(collection, data, id, ttlSeconds, actor); } std::optional Client::get(const std::string& collection, const std::string& id) { return impl_->get(collection, id); } bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data, const std::string& actor) { return impl_->update(collection, id, data, actor); } bool Client::updateIfVersion(const std::string& collection, const std::string& id, const nlohmann::json& data, uint64_t expectedVersion, const std::string& actor) { return impl_->updateIfVersion(collection, id, data, expectedVersion, actor); } bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data, Failure& failureOut, const std::string& actor) { failureOut = Failure{}; return impl_->update(collection, id, data, actor, &failureOut); } bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data, FailureDetail& failureOut, const std::string& actor) { failureOut = FailureDetail{}; return impl_->update(collection, id, data, actor, &failureOut); } bool Client::updateIfVersion(const std::string& collection, const std::string& id, const nlohmann::json& data, uint64_t expectedVersion, FailureDetail& failureOut, const std::string& actor) { return impl_->updateIfVersion(collection, id, data, expectedVersion, actor, &failureOut); } uint64_t Client::patch(const std::string& collection, const std::string& id, const nlohmann::json& fields, FailureDetail& failureOut, const std::string& actor) { return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut); } uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id, const nlohmann::json& fields, uint32_t ttlSeconds, FailureDetail& failureOut, const std::string& actor) { return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut); } uint64_t Client::patchIfVersion(const std::string& collection, const std::string& id, const nlohmann::json& fields, uint64_t expectedVersion, FailureDetail& failureOut, const std::string& actor) { return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut, expectedVersion); } std::optional Client::increment(const std::string& collection, const std::string& id, const nlohmann::json& deltas, FailureDetail& failureOut, const std::string& actor) { nlohmann::json incremented; const uint64_t v = impl_->patch(collection, id, nlohmann::json::object(), actor, std::nullopt, &failureOut, std::nullopt, &deltas, &incremented); if (v == 0) return std::nullopt; return incremented; } bool Client::updateIfVersion(const std::string& collection, const std::string& id, const nlohmann::json& data, uint64_t expectedVersion, Failure& failureOut, const std::string& actor) { return impl_->updateIfVersion(collection, id, data, expectedVersion, actor, &failureOut); } uint64_t Client::patch(const std::string& collection, const std::string& id, const nlohmann::json& fields, Failure& failureOut, const std::string& actor) { return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut); } uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id, const nlohmann::json& fields, uint32_t ttlSeconds, Failure& failureOut, const std::string& actor) { return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut); } uint64_t Client::patch(const std::string& collection, const std::string& id, const nlohmann::json& fields, const std::string& actor) { return impl_->patch(collection, id, fields, actor); } uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id, const nlohmann::json& fields, uint32_t ttlSeconds, const std::string& actor) { return impl_->patch(collection, id, fields, actor, ttlSeconds); } std::pair Client::upsert(const std::string& collection, const nlohmann::json& data, const std::string& id, uint32_t ttlSeconds, const std::string& actor) { return impl_->upsert(collection, data, id, ttlSeconds, actor); } bool Client::remove(const std::string& collection, const std::string& id) { return impl_->remove(collection, id); } bool Client::remove(const std::string& collection, const std::string& id, std::string& errorOut) { return impl_->remove(collection, id, errorOut); } bool Client::remove(const std::string& collection, const std::string& id, Failure& failureOut) { return impl_->remove(collection, id, failureOut); } bool Client::removeAs(const std::string& collection, const std::string& id, const std::string& actor) { return impl_->removeAs(collection, id, actor, FailureSink{}); } bool Client::removeAs(const std::string& collection, const std::string& id, const std::string& actor, Failure& failureOut) { return impl_->removeAs(collection, id, actor, &failureOut); } bool Client::removeAs(const std::string& collection, const std::string& id, const std::string& actor, FailureDetail& failureOut) { return impl_->removeAs(collection, id, actor, &failureOut); } std::optional Client::removeManyAs(const std::string& collection, const std::vector& ids, const std::string& actor, FailureDetail& failureOut) { return impl_->removeManyAs(collection, ids, actor, &failureOut); } bool Client::exists(const std::string& collection, const std::string& id) { return impl_->exists(collection, id); } Client::VersionHistoryResult Client::getVersionHistory(const std::string& collection, const std::string& id, uint32_t limit, uint32_t offset) { return impl_->getVersionHistory(collection, id, limit, offset); } std::optional Client::getDocumentVersion(const std::string& collection, const std::string& id, uint64_t version) { return impl_->getDocumentVersion(collection, id, version); } uint64_t Client::restoreVersion(const std::string& collection, const std::string& id, uint64_t version, const std::string& actor) { return impl_->restoreVersion(collection, id, version, actor); } std::pair Client::restoreToDate(const std::string& collection, const std::string& id, uint64_t timestamp, const std::string& actor) { return impl_->restoreToDate(collection, id, timestamp, actor); } std::vector Client::find(const std::string& collection, const QueryOptions& options) { return impl_->find(collection, options); } std::vector Client::find(const std::string& collection, const QueryOptions& options, const std::vector& projection) { return impl_->find(collection, options, projection); } std::vector Client::find(const std::string& collection, const QueryOptions& options, WithVector) { return impl_->find(collection, options, {}, /*includeVector=*/true); } std::optional Client::get(const std::string& collection, const std::string& id, WithVector) { return impl_->get(collection, id, /*includeVector=*/true); } Client::ExportSummary Client::exportCollection( const std::string& collection, bool includeVectors, const std::string& afterId, const std::function& onHeader, const std::function& onRow, uint32_t batchRows) { return impl_->exportCollection(collection, includeVectors, afterId, onHeader, onRow, batchRows); } Client::FindResult Client::findWithMetrics(const std::string& collection, const QueryOptions& options) { return impl_->findWithMetrics(collection, options); } uint64_t Client::count(const std::string& collection, const std::vector& filters) { return impl_->count(collection, filters); } uint64_t Client::count(const std::string& collection) { return impl_->count(collection, {}); } bool Client::setAdd(const std::string& collection, const std::string& setId, const std::string& member) { return impl_->setAdd(collection, setId, member); } bool Client::setRemove(const std::string& collection, const std::string& setId, const std::string& member) { return impl_->setRemove(collection, setId, member); } std::vector Client::setMembers(const std::string& collection, const std::string& setId) { return impl_->setMembers(collection, setId); } bool Client::setIsMember(const std::string& collection, const std::string& setId, const std::string& member) { return impl_->setIsMember(collection, setId, member); } std::vector Client::similaritySearch( const std::string& collection, const std::vector& queryVector, uint32_t topK, float minScore) { return impl_->similaritySearch(collection, queryVector, topK, minScore); } std::vector Client::similaritySearch( const std::string& collection, const std::vector& queryVector, uint32_t topK, float minScore, const std::vector& filters) { return impl_->similaritySearch(collection, queryVector, topK, minScore, filters); } bool Client::createCollection(const std::string& name, uint32_t defaultTtlSeconds, bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) { return impl_->createCollection(name, defaultTtlSeconds, encrypted, maxVersions, vectorDimension); } bool Client::dropCollection(const std::string& name) { return impl_->dropCollection(name); } std::vector Client::listCollections() { return impl_->listCollections(); } std::optional Client::getCollectionInfo(const std::string& name) { return impl_->getCollectionInfo(name); } // ===== Project Management (v2.3 Stage F) ===== std::vector Client::listProjects() { return impl_->listProjects(); } bool Client::createProject(const std::string& name) { return impl_->createProject(name); } void Client::dropProject(const std::string& name) { impl_->dropProject(name); } bool Client::configureCollection(const std::string& collection, const CollectionConfig& cfg) { return impl_->configureCollection(collection, cfg); } Client::CollectionConfig Client::getCollectionConfig(const std::string& collection) { return impl_->getCollectionConfig(collection); } bool Client::hasCollectionConfig(const std::string& collection) { return impl_->hasCollectionConfig(collection); } Client::TimestampMigrationResult Client::migrateCollectionTimestamps( const std::string& collection, const std::string& fromPrecision, const std::string& toPrecision ) { return impl_->migrateCollectionTimestamps(collection, fromPrecision, toPrecision); } bool Client::createView(const std::string& name, const std::string& collection, const std::vector& include, const std::vector& exclude, const std::vector& where, const std::optional& defaultSort) { return impl_->createView(name, collection, include, exclude, where, defaultSort); } bool Client::dropView(const std::string& name) { return impl_->dropView(name); } bool Client::createIndex(const std::string& collection, const std::string& field) { return impl_->createIndex(collection, field, nullptr); } bool Client::createIndex(const std::string& collection, const std::string& field, uint64_t& rowsIndexed) { return impl_->createIndex(collection, field, &rowsIndexed); } bool Client::dropIndex(const std::string& collection, const std::string& field) { return impl_->dropIndex(collection, field); } Client::CreateIndexResult Client::createUniqueIndex(const std::string& collection, const std::string& field) { return impl_->createUniqueIndex(collection, field); } Client::CreateIndexResult Client::createCompositeUniqueIndex(const std::string& collection, const std::vector& fields) { return impl_->createCompositeUniqueIndex(collection, fields); } bool Client::dropCompositeUniqueIndex(const std::string& collection, const std::vector& fields) { return impl_->dropCompositeUniqueIndex(collection, fields); } std::vector> Client::listCompositeUniqueIndexes(const std::string& collection) { return impl_->listCompositeUniqueIndexes(collection); } std::vector Client::listIndexes(const std::string& collection) { return impl_->listIndexes(collection, nullptr); } std::vector Client::listIndexes(const std::string& collection, std::vector& uniqueFlags) { return impl_->listIndexes(collection, &uniqueFlags); } std::vector Client::indexValues(const std::string& collection, const std::string& field, uint32_t limit, bool ascending) { return impl_->indexValues(collection, field, limit, ascending); } std::vector Client::listViews() { return impl_->listViews(); } std::optional Client::getViewInfo(const std::string& name) { return impl_->getViewInfo(name); } bool Client::createRelation(const std::string& name, const std::string& childCollection, const std::string& childField, const std::string& parentCollection, const std::string& onDelete, bool validateOnWrite) { return impl_->createRelation(name, childCollection, childField, parentCollection, onDelete, validateOnWrite, nullptr); } bool Client::createRelation(const std::string& name, const std::string& childCollection, const std::string& childField, const std::string& parentCollection, const std::string& onDelete, bool validateOnWrite, uint64_t& rowsIndexed) { return impl_->createRelation(name, childCollection, childField, parentCollection, onDelete, validateOnWrite, &rowsIndexed); } bool Client::dropRelation(const std::string& name) { return impl_->dropRelation(name); } std::vector Client::listRelations() { return impl_->listRelations(); } std::vector Client::listRelations(const std::string& project) { return impl_->listRelationsIn(project); } std::optional Client::getRelationInfo(const std::string& name) { return impl_->getRelationInfo(name); } bool Client::setRelationsEnforced(const std::string& collection, bool enforced) { return impl_->setRelationsEnforced(collection, enforced); } bool Client::getRelationsEnforced(const std::string& collection) { return impl_->getRelationsEnforced(collection); } std::optional Client::tryGetRelationsEnforced(const std::string& collection) { return impl_->tryGetRelationsEnforced(collection); } Client::DescribeDeleteResult Client::describeDelete(const std::string& collection, const std::string& id) { return impl_->describeDelete(collection, id); } Client::CheckRelationResult Client::checkRelation(const std::string& name) { return impl_->checkRelation(name); } std::shared_ptr Client::subscribe(const std::vector& collections, EventCallback callback) { return impl_->subscribe(collections, std::move(callback)); } std::shared_ptr Client::subscribeEvents(const std::vector& collections, EventHandler handler) { return impl_->subscribeEvents(collections, std::move(handler)); } bool Client::healthCheck() { return impl_->healthCheck(); } std::optional Client::getHealthInfo() { return impl_->getHealthInfo(); } std::optional Client::getStats() { return impl_->getStats(); } Client::MemoryStats Client::getMemoryStats() { return impl_->getMemoryStats(); } bool Client::setReadOnly(bool readOnly) { return impl_->setReadOnly(readOnly); } Client::ReadOnlyStatus Client::getReadOnlyStatus() { return impl_->getReadOnlyStatus(); } Client::FileUploadResult Client::uploadFile(const std::vector& data, const FileUploadMeta& meta) { return impl_->uploadFile(data, meta); } Client::FileUploadResult Client::uploadFile(const std::vector& data, const FileUploadMeta& meta, uint32_t ttlSeconds) { return impl_->uploadFile(data, meta, ttlSeconds, /*explicitTtl=*/true); } std::vector Client::downloadFile(const std::string& id) { return impl_->downloadFile(id); } std::optional Client::getFileInfo(const std::string& id) { return impl_->getFileInfo(id); } bool Client::deleteFile(const std::string& id) { return impl_->deleteFile(id); } bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds) { return impl_->setFileTtl(id, ttlSeconds); } bool Client::deleteFile(const std::string& id, Failure& failureOut) { return impl_->deleteFile(id, &failureOut); } bool Client::deleteFile(const std::string& id, FailureDetail& failureOut) { return impl_->deleteFile(id, &failureOut); } bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, Failure& failureOut) { return impl_->setFileTtl(id, ttlSeconds, &failureOut); } bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureDetail& failureOut) { return impl_->setFileTtl(id, ttlSeconds, &failureOut); } Client::FileListResult Client::listFiles(const std::string& file_type, const std::string& related_id, uint32_t limit, uint32_t offset, const std::string& checksum, const std::string& name) { return impl_->listFiles(file_type, related_id, limit, offset, checksum, name); } // v2.11.1 — see the header. The macros are defined on this target from the // top-level VERSION file and BUILD_GIT_COMMIT, exactly as the service and CLI // get theirs, so all three binaries answer the same question the same way. #ifndef SMARTBOTIC_DB_VERSION_STRING #define SMARTBOTIC_DB_VERSION_STRING "unknown" #endif #ifndef SMARTBOTIC_DB_GIT_COMMIT_STRING #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown" #endif Client::SchemaChangeResult Client::setCollectionSchema(const std::string& collection, const nlohmann::json& schema, SchemaMode mode) { return impl_->schemaChange(collection, schema.dump(), mode); } Client::SchemaChangeResult Client::removeCollectionSchema(const std::string& collection) { return impl_->schemaChange(collection, "", SchemaMode::Enforce); } std::optional Client::getCollectionSchema(const std::string& collection) { return impl_->getCollectionSchema(collection); } Client::SchemaSuggestion Client::suggestCollectionSchema(const std::string& collection, uint64_t sampleLimit) { return impl_->suggestCollectionSchema(collection, sampleLimit); } std::optional Client::serverInfo(bool refresh) { return impl_->serverInfo(refresh); } bool Client::serverSupports(const std::string& capability) { return impl_->serverSupports(capability); } std::string clientLibraryVersion() { return SMARTBOTIC_DB_VERSION_STRING; } std::string clientLibraryCommit() { return SMARTBOTIC_DB_GIT_COMMIT_STRING; } } // namespace smartbotic::database