| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163 |
- #include "smartbotic/database/client.hpp"
- #include <database.grpc.pb.h>
- #include <grpcpp/grpcpp.h>
- #include <grpcpp/security/credentials.h>
- #include <grpcpp/security/tls_certificate_verifier.h>
- #include <grpcpp/security/tls_credentials_options.h>
- #include <spdlog/spdlog.h>
- #include <atomic>
- #include <chrono>
- #include <cstdlib>
- #include <fstream>
- #include <mutex>
- #include <sstream>
- #include <thread>
- 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<int>(Client::ErrorCode::NotFound) == grpc::StatusCode::NOT_FOUND);
- static_assert(static_cast<int>(Client::ErrorCode::AlreadyExists) == grpc::StatusCode::ALREADY_EXISTS);
- static_assert(static_cast<int>(Client::ErrorCode::PermissionDenied) == grpc::StatusCode::PERMISSION_DENIED);
- static_assert(static_cast<int>(Client::ErrorCode::FailedPrecondition) == grpc::StatusCode::FAILED_PRECONDITION);
- static_assert(static_cast<int>(Client::ErrorCode::Unavailable) == grpc::StatusCode::UNAVAILABLE);
- static_assert(static_cast<int>(Client::ErrorCode::Unauthenticated) == grpc::StatusCode::UNAUTHENTICATED);
- Client::ErrorCode toErrorCode(grpc::StatusCode code) {
- return static_cast<Client::ErrorCode>(static_cast<int>(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";
- 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;
- 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<std::string>());
- }
- 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<uint64_t>();
- }
- } 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.
- void recordInBand(int32_t errorCode, const std::string& message,
- const std::string& detailJson) const {
- record(errorCode != 0 ? static_cast<Client::ErrorCode>(errorCode) : Client::ErrorCode::Unknown,
- message, detailJson);
- }
- };
- // 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.
- bool retryableStatus(const grpc::Status& s) {
- switch (s.error_code()) {
- case grpc::StatusCode::DEADLINE_EXCEEDED: // server queued behind eviction/WAL
- case grpc::StatusCode::RESOURCE_EXHAUSTED: // admission control or gRPC concurrency cap
- case grpc::StatusCode::UNAVAILABLE: // transient connection issue
- return true;
- default:
- return false;
- }
- }
- // 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<uint64_t>(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<uint32_t>(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<const DetailCarrier*>(&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 "<project>:<collection>" 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<grpc::ChannelCredentials> 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";
- 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<grpc::ChannelCredentials> 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<grpc::experimental::NoOpCertificateVerifier>());
- 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;
- stub_.reset();
- channel_.reset();
- }
- bool isConnected() const {
- if (!connected_ || !channel_) {
- return false;
- }
- // Check if channel is in a usable state (not failed or shutdown)
- auto state = channel_->GetState(false);
- return state == GRPC_CHANNEL_READY ||
- 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;
- setDeadline(context);
- response.Clear();
- status = stub_->Insert(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status)) {
- 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));
- }
- }
- if (!status.ok()) {
- spdlog::error("Client::insert failed after retries: {}", status.error_message());
- throwStatus(status, status.error_message(), detailJson);
- }
- return response.id();
- }
- std::optional<nlohmann::json> get(const std::string& collection, const std::string& id) {
- smartbotic::databasepb::GetRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- 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;
- }
- auto json = nlohmann::json::parse(response.document().data());
- json["_id"] = response.document().id();
- json["_version"] = response.document().version();
- json["_created_at"] = response.document().created_at();
- json["_updated_at"] = response.document().updated_at();
- json["_created_by"] = response.document().created_by();
- json["_updated_by"] = response.document().updated_by();
- return json;
- }
- 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<nlohmann::json> 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<uint64_t>();
- // 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.
- if (updateIfVersion(collection, id, cleanData, version, actor, failureOut)) {
- return true;
- }
- // 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;
- setDeadline(context);
- response.Clear();
- status = stub_->Update(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status)) {
- 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));
- }
- }
- 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<uint32_t> ttlSeconds = std::nullopt,
- FailureSink failureOut = {},
- std::optional<uint64_t> 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;
- setDeadline(context);
- response.Clear();
- status = stub_->PatchDocument(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status)) {
- 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));
- }
- }
- 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<std::string, bool> 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;
- setDeadline(context);
- response.Clear();
- status = stub_->Upsert(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status)) {
- 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));
- }
- }
- 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;
- setDeadline(context);
- response.Clear();
- status = stub_->Delete(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status)) {
- 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));
- }
- }
- 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<Client::BatchRemoveResult> removeManyAs(const std::string& collection,
- const std::vector<std::string>& 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;
- // Retried like the other deletes: deleting an id twice is harmless, and
- // a retry after a lost reply reports the ids the first attempt removed
- // as not found - which is why deletedIds is "what THIS call removed".
- for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
- grpc::ClientContext context;
- setDeadline(context);
- response.Clear();
- status = stub_->BatchDelete(&context, request, &response);
- detailJson = trailerDetail(context);
- if (status.ok() || !retryableStatus(status)) break;
- if (attempt < config_.writeRetries) {
- std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter)));
- }
- }
- 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<nlohmann::json> find(const std::string& collection,
- const Client::QueryOptions& options,
- const std::vector<std::string>& 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<smartbotic::databasepb::FilterOp>(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) {
- // 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<nlohmann::json> results;
- results.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();
- results.push_back(json);
- }
- return results;
- }
- Client::FindResult findWithMetrics(const std::string& collection,
- const Client::QueryOptions& options,
- const std::vector<std::string>& 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<smartbotic::databasepb::FilterOp>(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<Client::Filter>& 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<smartbotic::databasepb::FilterOp>(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<std::string> 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<Client::SimilarityResult> similaritySearch(
- const std::string& collection, const std::vector<float>& queryVector,
- uint32_t topK, float minScore) {
- 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);
- 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());
- }
- std::vector<Client::SimilarityResult> 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 <project>:<name> 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<std::string> 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<std::string> out;
- out.reserve(static_cast<size_t>(response.names_size()));
- for (const auto& n : response.names()) {
- out.push_back(unqualify(n));
- }
- return out;
- }
- std::optional<Client::CollectionInfo> 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<std::string> 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<bool> 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<bool> 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<std::string>& include,
- const std::vector<std::string>& exclude,
- const std::vector<Client::Filter>& where,
- const std::optional<Client::Sort>& 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<smartbotic::databasepb::FilterOp>(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;
- }
- std::vector<Client::IndexDefinition> listIndexes(const std::string& collection,
- std::vector<bool>* uniqueFlags) {
- smartbotic::databasepb::ListIndexesRequest request;
- request.set_collection(qualify(collection));
- smartbotic::databasepb::ListIndexesResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- std::vector<Client::IndexDefinition> 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<std::string>& 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<std::string>& 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<std::vector<std::string>> 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<std::vector<std::string>> 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<Client::IndexValue> 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<Client::IndexValue> 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<Client::ViewDefinition> 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<Client::ViewDefinition> 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<Client::FilterOp>(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<Client::ViewDefinition> 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<Client::FilterOp>(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<Client::RelationDefinition> 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<Client::RelationDefinition> listRelationsIn(const std::string& project) {
- smartbotic::databasepb::ListRelationsRequest request;
- request.set_project(project);
- smartbotic::databasepb::ListRelationsResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- std::vector<Client::RelationDefinition> 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<Client::RelationDefinition> 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<grpc::ClientContext> ctx,
- std::unique_ptr<grpc::ClientReader<smartbotic::databasepb::DatabaseEvent>> 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<grpc::ClientContext> context_;
- std::unique_ptr<grpc::ClientReader<smartbotic::databasepb::DatabaseEvent>> reader_;
- std::thread readerThread_;
- std::atomic<bool> 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<void> subscribe(const std::vector<std::string>& 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<void> subscribeEvents(const std::vector<std::string>& collections,
- Client::EventHandler handler) {
- auto context = std::make_shared<grpc::ClientContext>();
- // 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 `<project>:*` 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)) {
- std::optional<nlohmann::json> 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);
- }
- });
- return std::make_shared<SubscriptionHandle>(
- std::move(context),
- std::move(reader),
- std::move(readerThread)
- );
- }
- // ===== 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<Client::VersionEntry> 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<uint64_t, uint64_t> 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<Client::HealthInfo> 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<Client::StatsInfo> 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<uint8_t>& 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<uint8_t> 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<uint8_t> 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<Client::FileRecord> 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;
- }
- bool deleteFile(const std::string& id) {
- 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());
- return false;
- }
- return response.deleted();
- }
- bool setFileTtl(const std::string& id, uint32_t ttlSeconds) {
- 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());
- return false;
- }
- 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.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.
- void attachAuth(grpc::ClientContext& context) {
- if (!config_.auth_token.empty()) {
- context.AddMetadata("authorization", "Bearer " + config_.auth_token);
- }
- }
- Config config_;
- std::shared_ptr<grpc::Channel> channel_;
- std::unique_ptr<smartbotic::databasepb::DatabaseService::Stub> stub_;
- std::atomic<bool> connected_{false};
- };
- // ===== Client Public Interface Implementation =====
- Client::Client(Config config)
- : impl_(std::make_unique<Impl>(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<nlohmann::json> 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<nlohmann::json> 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<std::string, bool> 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::BatchRemoveResult>
- Client::removeManyAs(const std::string& collection, const std::vector<std::string>& 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::VersionEntry> 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<uint64_t, uint64_t> 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<nlohmann::json> Client::find(const std::string& collection,
- const QueryOptions& options) {
- return impl_->find(collection, options);
- }
- std::vector<nlohmann::json> Client::find(const std::string& collection,
- const QueryOptions& options,
- const std::vector<std::string>& projection) {
- return impl_->find(collection, options, projection);
- }
- 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<Filter>& 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<std::string> 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::SimilarityResult> Client::similaritySearch(
- const std::string& collection, const std::vector<float>& queryVector,
- uint32_t topK, float minScore) {
- return impl_->similaritySearch(collection, queryVector, topK, minScore);
- }
- 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<std::string> Client::listCollections() {
- return impl_->listCollections();
- }
- std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
- return impl_->getCollectionInfo(name);
- }
- // ===== Project Management (v2.3 Stage F) =====
- std::vector<std::string> 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<std::string>& include,
- const std::vector<std::string>& exclude,
- const std::vector<Filter>& where,
- const std::optional<Sort>& 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<std::string>& fields) {
- return impl_->createCompositeUniqueIndex(collection, fields);
- }
- bool Client::dropCompositeUniqueIndex(const std::string& collection,
- const std::vector<std::string>& fields) {
- return impl_->dropCompositeUniqueIndex(collection, fields);
- }
- std::vector<std::vector<std::string>>
- Client::listCompositeUniqueIndexes(const std::string& collection) {
- return impl_->listCompositeUniqueIndexes(collection);
- }
- std::vector<Client::IndexDefinition> Client::listIndexes(const std::string& collection) {
- return impl_->listIndexes(collection, nullptr);
- }
- std::vector<Client::IndexDefinition> Client::listIndexes(const std::string& collection,
- std::vector<bool>& uniqueFlags) {
- return impl_->listIndexes(collection, &uniqueFlags);
- }
- std::vector<Client::IndexValue> 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::ViewDefinition> Client::listViews() {
- return impl_->listViews();
- }
- std::optional<Client::ViewDefinition> 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::RelationDefinition> Client::listRelations() {
- return impl_->listRelations();
- }
- std::vector<Client::RelationDefinition> Client::listRelations(const std::string& project) {
- return impl_->listRelationsIn(project);
- }
- std::optional<Client::RelationDefinition> 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<bool> 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<void> Client::subscribe(const std::vector<std::string>& collections, EventCallback callback) {
- return impl_->subscribe(collections, std::move(callback));
- }
- std::shared_ptr<void> Client::subscribeEvents(const std::vector<std::string>& collections,
- EventHandler handler) {
- return impl_->subscribeEvents(collections, std::move(handler));
- }
- bool Client::healthCheck() {
- return impl_->healthCheck();
- }
- std::optional<Client::HealthInfo> Client::getHealthInfo() {
- return impl_->getHealthInfo();
- }
- std::optional<Client::StatsInfo> 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<uint8_t>& data, const FileUploadMeta& meta) {
- return impl_->uploadFile(data, meta);
- }
- Client::FileUploadResult Client::uploadFile(const std::vector<uint8_t>& data,
- const FileUploadMeta& meta,
- uint32_t ttlSeconds) {
- return impl_->uploadFile(data, meta, ttlSeconds, /*explicitTtl=*/true);
- }
- std::vector<uint8_t> Client::downloadFile(const std::string& id) {
- return impl_->downloadFile(id);
- }
- std::optional<Client::FileRecord> 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);
- }
- 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
- std::string clientLibraryVersion() { return SMARTBOTIC_DB_VERSION_STRING; }
- std::string clientLibraryCommit() { return SMARTBOTIC_DB_GIT_COMMIT_STRING; }
- } // namespace smartbotic::database
|