| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674 |
- #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 <cstring>
- #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";
- #ifndef SMARTBOTIC_DB_VERSION_STRING
- #define SMARTBOTIC_DB_VERSION_STRING "unknown"
- #endif
- std::string trailerDetail(const grpc::ClientContext& context) {
- const auto& md = context.GetServerTrailingMetadata();
- auto it = md.find(kErrorDetailKey);
- if (it == md.end()) return {};
- return std::string(it->second.data(), it->second.size());
- }
- // Build a FailureDetail from a code, a message and the trailer JSON. A detail
- // that does not parse is ignored rather than allowed to turn a refusal into a
- // crash: the code and message still stand.
- Client::FailureDetail makeDetail(Client::ErrorCode code, const std::string& message,
- const std::string& detailJson) {
- Client::FailureDetail d;
- d.code = code;
- d.message = message;
- // v2.13.0 - gRPC refuses an oversized message itself (either side, before
- // our server code runs), with RESOURCE_EXHAUSTED and no detail, so a size
- // refusal looked exactly like a rate limit or memory pressure - and the
- // remedies differ: retrying never shrinks a payload. The library names it,
- // so no consumer has to match gRPC's text. The text is gRPC core's own
- // ("Sent message larger than max (N vs. M)", also "Received message
- // larger than max"), stable across the gRPC versions this is built with;
- // test_export pins it.
- if (detailJson.empty() && code == Client::ErrorCode::ResourceExhausted &&
- message.find("message larger than max") != std::string::npos) {
- d.reason = "message_too_large";
- }
- if (detailJson.empty()) return d;
- try {
- const auto j = nlohmann::json::parse(detailJson);
- if (!j.is_object()) return d;
- d.reason = j.value("reason", std::string{});
- if (auto it = j.find("fields"); it != j.end() && it->is_array()) {
- for (const auto& f : *it) if (f.is_string()) d.fields.push_back(f.get<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.
- // Copy a reason a nested call already recorded (v2.13.1).
- void copy(const Client::FailureDetail& d) const {
- if (failure) { failure->code = d.code; failure->message = d.message; }
- if (detail) *detail = d;
- }
- void recordInBand(int32_t errorCode, const std::string& message,
- const std::string& detailJson) const {
- record(errorCode != 0 ? static_cast<Client::ErrorCode>(errorCode) : Client::ErrorCode::Unknown,
- message, detailJson);
- }
- };
- // The JSON a read hands back: the stored fields plus the read metadata, and
- // (v2.13.0) "_vector" when the server sent the stored vector, which it does
- // only when the caller asked. The bytes are float32 little-endian.
- nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
- auto json = nlohmann::json::parse(doc.data());
- json["_id"] = doc.id();
- json["_version"] = doc.version();
- json["_created_at"] = doc.created_at();
- json["_updated_at"] = doc.updated_at();
- json["_created_by"] = doc.created_by();
- json["_updated_by"] = doc.updated_by();
- if (!doc.vector().empty()) {
- if (doc.vector().size() % sizeof(float) != 0) {
- throw DetailedError(Client::ErrorCode::DataLoss,
- "stored vector is not a whole number of float32 values",
- makeDetail(Client::ErrorCode::DataLoss, "bad vector bytes", {}));
- }
- std::vector<float> v(doc.vector().size() / sizeof(float));
- std::memcpy(v.data(), doc.vector().data(), doc.vector().size());
- json["_vector"] = v;
- }
- return json;
- }
- // v1.7.0 T11 — transient transport errors that are safe to retry for idempotent
- // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch).
- // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are
- // final — no retry.
- //
- // v2.13.1 - DEADLINE_EXCEEDED is retried only for an IDEMPOTENT write. The
- // deadline can expire while the server finishes the write (seen by
- // smartbotic-vectorapi on large patches: every one reported failure and had
- // been applied), so a retry repeats a write that already happened: an id-less
- // insert duplicates the row, an increment counts twice, and an insert with an
- // id, a conditional write or a delete reports a false AlreadyExists / version
- // conflict / not-found. Those are not retried; the failure carries reason
- // outcome_unknown (see outcomeUnknownDetail). UNAVAILABLE and
- // RESOURCE_EXHAUSTED still retry: the server did not act on the request.
- bool retryableStatus(const grpc::Status& s, bool idempotent) {
- switch (s.error_code()) {
- case grpc::StatusCode::DEADLINE_EXCEEDED: // may have been applied
- return idempotent;
- case grpc::StatusCode::RESOURCE_EXHAUSTED: // admission control or gRPC concurrency cap
- case grpc::StatusCode::UNAVAILABLE: // transient connection issue
- return true;
- default:
- return false;
- }
- }
- // v2.13.1 - a write that ended in DEADLINE_EXCEEDED may or may not have been
- // applied; say so in the reason, so a caller checks before redoing it instead
- // of reading "the write failed". Leaves a server-supplied detail alone.
- std::string outcomeUnknownDetail(const grpc::Status& s, const std::string& detailJson) {
- if (s.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && detailJson.empty()) {
- return R"({"reason":"outcome_unknown"})";
- }
- return detailJson;
- }
- // Exponential backoff with jitter. attempt=0 => baseMs; attempt=1 => baseMs*2; ...
- uint32_t computeBackoffMs(uint32_t baseMs, uint32_t attempt, uint32_t capMs, double jitterPct) {
- uint64_t exp = static_cast<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";
- // v2.13.1 - actually try. Creating a gRPC channel opens nothing, so
- // this used to return true and log "connected" against a dead port
- // (reported by smartbotic): connect() and isConnected() were not
- // reachability checks at all. Now it waits up to timeoutMs for the
- // channel to connect. On failure the client stays usable - gRPC
- // keeps reconnecting on later calls - but the answer is honest.
- const bool reachable = channel_->WaitForConnected(
- std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs));
- reached_ = reachable;
- if (!reachable) {
- spdlog::warn("Database client could not reach {} ({}, {}) within {} ms; "
- "it will keep trying on later calls",
- config_.address, scheme, authed, config_.timeoutMs);
- return false;
- }
- spdlog::info("Database client connected to {} ({}, {})",
- config_.address, scheme, authed);
- return true;
- } catch (const std::exception& e) {
- spdlog::error("Database client connection failed: {}", e.what());
- return false;
- }
- }
- // v2.4 — build the ChannelCredentials matching Config's TLS settings.
- //
- // Three cases:
- // 1. !tls_enabled → InsecureChannelCredentials
- // (v2.3 back-compat default).
- // 2. tls_enabled && !insecure_skip_verify → SslCredentials with
- // pem_root_certs read from tls_ca_cert_path, or empty (= system
- // trust roots) when the path is unset.
- // 3. tls_enabled && insecure_skip_verify → experimental
- // TlsChannelCredentialsOptions with NoOpCertificateVerifier and
- // set_verify_server_certs(false). Loud WARN on every connect.
- std::shared_ptr<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;
- reached_ = false;
- stub_.reset();
- channel_.reset();
- }
- bool isConnected() const {
- if (!connected_ || !channel_) {
- return false;
- }
- // READY is connected. IDLE (no calls for a while) and CONNECTING
- // count only if the last connection attempt succeeded (v2.13.1):
- // against a frozen server the kernel accepts the TCP connection and
- // the channel sits in CONNECTING forever, which used to read as true.
- auto state = channel_->GetState(false);
- if (state == GRPC_CHANNEL_READY) return true;
- return reached_ && (state == GRPC_CHANNEL_IDLE || state == GRPC_CHANNEL_CONNECTING);
- }
- // ===== Document Operations =====
- std::string insert(const std::string& collection, const nlohmann::json& data,
- const std::string& id, uint32_t ttlSeconds,
- const std::string& actor) {
- smartbotic::databasepb::InsertRequest request;
- request.set_collection(qualify(collection));
- request.set_data(data.dump());
- if (!id.empty()) {
- request.set_id(id);
- }
- if (ttlSeconds > 0) {
- request.set_ttl_seconds(ttlSeconds);
- }
- if (!actor.empty()) {
- request.set_actor(actor);
- }
- smartbotic::databasepb::InsertResponse response;
- grpc::Status status;
- std::string detailJson; // v2.12.0 - the refusal detail, if any
- for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
- grpc::ClientContext context;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->Insert(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
- break;
- }
- if (attempt < config_.writeRetries) {
- uint32_t backoffMs = computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
- spdlog::warn("Client::insert {}; retrying in {}ms (attempt {}/{})",
- status.error_message(), backoffMs,
- attempt + 1, config_.writeRetries);
- std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::insert failed after retries: {}", status.error_message());
- throwStatus(status, status.error_message(), detailJson);
- }
- return response.id();
- }
- std::optional<nlohmann::json> get(const std::string& collection, const std::string& id,
- bool includeVector = false) {
- smartbotic::databasepb::GetRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- request.set_include_vector(includeVector); // v2.13.0
- smartbotic::databasepb::GetResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->Get(&context, request, &response);
- if (!status.ok()) {
- // v2.8.0 — a permission denial must NOT look like "no data".
- // Returning empty here would leave an application unable to tell
- // "you may not see this" from "there is nothing to see", so it
- // would silently take the wrong branch. Same reasoning as the
- // v2.4.2 change that stopped Find returning empty for a missing
- // collection.
- if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
- throw Client::PermissionDenied("access denied: get");
- }
- spdlog::error("Client::get failed: {}", status.error_message());
- throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
- }
- if (!response.found()) {
- return std::nullopt;
- }
- return documentToJson(response.document());
- }
- bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
- const std::string& actor, FailureSink failureOut = {}) {
- // Strip metadata fields from data — callers pass the JSON from get() which
- // includes _version, _id, etc. We use _version for optimistic locking.
- auto cleanData = data;
- cleanData.erase("_id");
- cleanData.erase("_version");
- cleanData.erase("_created_at");
- cleanData.erase("_updated_at");
- cleanData.erase("_created_by");
- cleanData.erase("_updated_by");
- // Optimistic locking with automatic retry:
- // 1. Read current version
- // 2. Call updateIfVersion
- // 3. On version conflict (another writer), re-read and retry
- for (uint32_t attempt = 0; attempt <= config_.maxRetries; ++attempt) {
- // Get current version. v2.12.4: get() now throws on a failed read
- // instead of returning nullopt. Before, an unreachable database
- // was reported here as "document not found" - the same conflation
- // get() had. update() still reports failure by returning false,
- // so the real code is recorded instead. A permission denial threw
- // out of here before 2.12.4 too, and still does.
- std::optional<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.
- Client::FailureDetail attemptFailure;
- if (updateIfVersion(collection, id, cleanData, version, actor, &attemptFailure)) {
- failureOut.reset();
- return true;
- }
- failureOut.copy(attemptFailure);
- // v2.13.1 - only a version conflict (another writer between our
- // get() and this write) is worth another round. Every other
- // refusal - read-only, memory pressure, a document too large, an
- // outage - was retried here too and then logged as "version
- // conflicts", though no retry could change the answer.
- // A pre-2.12.0 server reports the conflict in-band with no code
- // (Unknown) and the text "Version conflict".
- const bool conflict =
- attemptFailure.code == Client::ErrorCode::Aborted ||
- (attemptFailure.code == Client::ErrorCode::Unknown &&
- attemptFailure.message.find("ersion conflict") != std::string::npos);
- if (!conflict) {
- return false;
- }
- // Version conflict — another client wrote between our get() and update
- if (attempt < config_.maxRetries) {
- spdlog::debug("Client::update version conflict on {}/{}, retry {}/{}",
- collection, id, attempt + 1, config_.maxRetries);
- }
- }
- spdlog::warn("Client::update failed after {} retries due to version conflicts on {}/{}",
- config_.maxRetries, collection, id);
- return false;
- }
- bool updateIfVersion(const std::string& collection, const std::string& id,
- const nlohmann::json& data, uint64_t expectedVersion,
- const std::string& actor,
- FailureSink failureOut = {}) {
- failureOut.reset();
- smartbotic::databasepb::UpdateRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- request.set_data(data.dump());
- request.set_expected_version(expectedVersion);
- if (!actor.empty()) {
- request.set_actor(actor);
- }
- smartbotic::databasepb::UpdateResponse response;
- grpc::Status status;
- std::string detailJson; // v2.12.0 - the refusal detail, if any
- for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
- grpc::ClientContext context;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->Update(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
- break;
- }
- if (attempt < config_.writeRetries) {
- uint32_t backoffMs = computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
- spdlog::warn("Client::updateIfVersion {}; retrying in {}ms (attempt {}/{})",
- status.error_message(), backoffMs,
- attempt + 1, config_.writeRetries);
- std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message());
- failureOut.record(status, detailJson);
- return false;
- }
- if (!response.success()) {
- // Refused in-band: status OK. Since 2.12.0 the response carries the
- // code the refusal would have as a status; before, Unknown.
- failureOut.recordInBand(response.error_code(), response.error(), detailJson);
- }
- return response.success();
- }
- uint64_t patch(const std::string& collection, const std::string& id,
- const nlohmann::json& fields, const std::string& actor,
- std::optional<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;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->PatchDocument(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status, /*idempotent=*/!request.has_expected_version() && request.increments_json().empty())) {
- break;
- }
- if (attempt < config_.writeRetries) {
- uint32_t backoffMs = computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
- spdlog::warn("Client::patch {}; retrying in {}ms (attempt {}/{})",
- status.error_message(), backoffMs,
- attempt + 1, config_.writeRetries);
- std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::patch failed after retries: {}", status.error_message());
- failureOut.record(status, detailJson);
- return 0;
- }
- if (!response.success()) {
- spdlog::error("Client::patch failed: {}", response.error());
- failureOut.recordInBand(response.error_code(), response.error(), detailJson);
- return 0;
- }
- if (incrementedOut != nullptr) {
- *incrementedOut = response.incremented_json().empty()
- ? nlohmann::json::object()
- : nlohmann::json::parse(response.incremented_json());
- }
- return response.new_version();
- }
- std::pair<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;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->Upsert(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status, /*idempotent=*/!id.empty())) {
- break;
- }
- if (attempt < config_.writeRetries) {
- uint32_t backoffMs = computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
- spdlog::warn("Client::upsert {}; retrying in {}ms (attempt {}/{})",
- status.error_message(), backoffMs,
- attempt + 1, config_.writeRetries);
- std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::upsert failed after retries: {}", status.error_message());
- throwStatus(status, status.error_message(), detailJson);
- }
- return {response.id(), response.inserted()};
- }
- // errorOut is optional: nullptr keeps the old single-value remove()'s
- // behaviour (log at spdlog::error and swallow the message). Non-null is
- // what lets a caller distinguish "already gone" from "blocked" - a
- // relation with on_delete=restrict/no_action refuses via a real gRPC
- // FAILED_PRECONDITION, not deleted=false, and that message is the only
- // way an operator learns WHAT blocked the delete.
- bool removeImpl(const std::string& collection, const std::string& id,
- std::string* errorOut, FailureSink failureOut = {},
- const std::string& actor = {}) {
- failureOut.reset();
- smartbotic::databasepb::DeleteRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- if (!actor.empty()) {
- request.set_actor(actor);
- }
- smartbotic::databasepb::DeleteResponse response;
- grpc::Status status;
- std::string detailJson; // v2.12.0 - the refusal detail, if any
- for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
- grpc::ClientContext context;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->Delete(&context, request, &response);
- detailJson = trailerDetail(context); // v2.12.0
- if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
- break;
- }
- if (attempt < config_.writeRetries) {
- uint32_t backoffMs = computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
- spdlog::warn("Client::remove {}; retrying in {}ms (attempt {}/{})",
- status.error_message(), backoffMs,
- attempt + 1, config_.writeRetries);
- std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::remove failed after retries: {}", status.error_message());
- if (errorOut != nullptr) *errorOut = status.error_message();
- failureOut.record(status, detailJson);
- return false;
- }
- return response.deleted();
- }
- bool remove(const std::string& collection, const std::string& id) {
- return removeImpl(collection, id, nullptr);
- }
- bool remove(const std::string& collection, const std::string& id, std::string& errorOut) {
- errorOut.clear();
- return removeImpl(collection, id, &errorOut);
- }
- bool remove(const std::string& collection, const std::string& id, Client::Failure& failureOut) {
- return removeImpl(collection, id, nullptr, &failureOut);
- }
- bool removeAs(const std::string& collection, const std::string& id,
- const std::string& actor, FailureSink failureOut) {
- return removeImpl(collection, id, nullptr, failureOut, actor);
- }
- // v2.12.0 - BatchDelete, which the client never exposed.
- std::optional<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;
- // v2.13.1 - retried only when the server cannot have acted (UNAVAILABLE,
- // RESOURCE_EXHAUSTED). After a DEADLINE_EXCEEDED the first attempt may
- // have deleted the ids, and a retry would report them as not found, so
- // that failure is returned with reason outcome_unknown instead.
- for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
- grpc::ClientContext context;
- setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
- response.Clear();
- status = stub_->BatchDelete(&context, request, &response);
- detailJson = trailerDetail(context);
- if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) break;
- if (attempt < config_.writeRetries) {
- std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs(
- config_.writeRetryBackoffMs, attempt,
- config_.writeRetryMaxBackoffMs, config_.writeRetryJitter)));
- }
- }
- detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
- if (!status.ok()) {
- spdlog::error("Client::removeManyAs failed: {}", status.error_message());
- failureOut.record(status, detailJson);
- return std::nullopt;
- }
- Client::BatchRemoveResult out;
- out.deletedCount = response.deleted_count();
- out.deletedIds.assign(response.deleted_ids().begin(), response.deleted_ids().end());
- return out;
- }
- bool exists(const std::string& collection, const std::string& id) {
- smartbotic::databasepb::ExistsRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- smartbotic::databasepb::ExistsResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->Exists(&context, request, &response);
- if (!status.ok()) {
- // v2.8.0 — a permission denial must NOT look like "no data".
- // Returning empty here would leave an application unable to tell
- // "you may not see this" from "there is nothing to see", so it
- // would silently take the wrong branch. Same reasoning as the
- // v2.4.2 change that stopped Find returning empty for a missing
- // collection.
- if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
- throw Client::PermissionDenied("access denied: exists");
- }
- spdlog::error("Client::exists failed: {}", status.error_message());
- throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
- }
- return response.exists();
- }
- // ===== Query Operations =====
- std::vector<nlohmann::json> find(const std::string& collection,
- const Client::QueryOptions& options,
- const std::vector<std::string>& projection = {},
- bool includeVector = false) {
- smartbotic::databasepb::FindRequest request;
- request.set_collection(qualify(collection));
- // Set filters
- for (const auto& filter : options.filters) {
- auto* pb = request.add_filters();
- pb->set_field(filter.field);
- pb->set_value(filter.value.dump());
- pb->set_op(static_cast<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);
- }
- request.set_include_vector(includeVector); // v2.13.0
- smartbotic::databasepb::FindResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->Find(&context, request, &response);
- if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
- // Surfaced rather than logged: an unknown collection or view is a
- // caller bug, and returning {} here is indistinguishable from a
- // legitimately empty result. Since v2.12.4 every other failure
- // throws too (below).
- throwStatus(status, status.error_message());
- }
- if (!status.ok()) {
- // v2.8.0 — a permission denial must NOT look like "no data".
- // Returning empty here would leave an application unable to tell
- // "you may not see this" from "there is nothing to see", so it
- // would silently take the wrong branch. Same reasoning as the
- // v2.4.2 change that stopped Find returning empty for a missing
- // collection.
- if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
- throw Client::PermissionDenied("access denied: find");
- }
- spdlog::error("Client::find failed: {}", status.error_message());
- throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
- }
- std::vector<nlohmann::json> results;
- results.reserve(response.documents_size());
- for (const auto& doc : response.documents()) {
- results.push_back(documentToJson(doc));
- }
- return results;
- }
- Client::FindResult findWithMetrics(const std::string& collection,
- const Client::QueryOptions& options,
- const std::vector<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,
- const std::vector<Client::Filter>& filters = {}) {
- // v2.15.0 - a server that answers GetServerInfo and lacks the feature
- // is refused before sending. A pre-2.15.0 server cannot say, so for it
- // the response's filters_applied (below) remains the guard.
- if (!filters.empty()) {
- const auto si = serverInfo(false);
- if (si && std::find(si->capabilities.begin(), si->capabilities.end(),
- Client::Capability::kFilteredSimilarity) ==
- si->capabilities.end()) {
- requireCapability(Client::Capability::kFilteredSimilarity, "similaritySearch");
- }
- }
- smartbotic::databasepb::SimilaritySearchRequest request;
- request.set_collection(qualify(collection));
- for (float v : queryVector) {
- request.add_query_vector(v);
- }
- request.set_top_k(topK);
- request.set_min_score(minScore);
- for (const auto& filter : filters) {
- auto* pb = request.add_filters();
- pb->set_field(filter.field);
- pb->set_value(filter.value.dump());
- pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
- }
- smartbotic::databasepb::SimilaritySearchResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->SimilaritySearch(&context, request, &response);
- if (!status.ok()) {
- spdlog::error("Client::similaritySearch failed: {}", status.error_message());
- throwStatus(status, status.error_message());
- }
- // v2.14.0 - a pre-2.14.0 server ignores the filters and ranks the
- // whole collection. Those rows look exactly like a filtered answer, so
- // they are refused rather than returned.
- if (!filters.empty() && !response.filters_applied()) {
- const std::string msg =
- "similaritySearch: the server does not support filters (needs >= 2.14.0); "
- "its answer would be unfiltered";
- spdlog::error("Client::{}", msg);
- throw DetailedFailedPrecondition(
- msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg,
- R"({"reason":"filters_unsupported"})"));
- }
- std::vector<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;
- }
- // ===== Collection schema (v2.16.0) =====
- Client::SchemaChangeResult schemaChange(const std::string& collection, const std::string& schemaJson,
- Client::SchemaMode mode) {
- Client::SchemaChangeResult out;
- try {
- requireCapability(Client::Capability::kCollectionSchema, "setCollectionSchema");
- } catch (const Client::Error& e) {
- out.error = e.what();
- if (const auto* d = Client::errorDetail(e)) out.reason = d->reason;
- return out;
- }
- smartbotic::databasepb::SetCollectionSchemaRequest request;
- request.set_collection(qualify(collection));
- request.set_schema_json(schemaJson);
- request.set_mode(mode == Client::SchemaMode::Audit ? "audit" : "enforce");
- smartbotic::databasepb::SetCollectionSchemaResponse response;
- grpc::ClientContext context;
- // The existing-row check scans the collection: give it the export cap,
- // not a unary deadline.
- context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
- attachAuth(context);
- auto status = stub_->SetCollectionSchema(&context, request, &response);
- if (!status.ok()) {
- const auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(),
- trailerDetail(context));
- out.error = status.error_message();
- out.reason = d.reason;
- spdlog::error("Client::setCollectionSchema failed: {}", out.error);
- return out;
- }
- out.success = response.success();
- out.error = response.error();
- out.rowsChecked = response.rows_checked();
- out.violatingRows = response.violating_rows();
- for (const auto& ex : response.examples()) {
- out.examples.push_back({ex.id(), ex.message(), {ex.fields().begin(), ex.fields().end()}});
- }
- if (!out.success) spdlog::error("Client::setCollectionSchema refused: {}", out.error);
- return out;
- }
- std::optional<Client::CollectionSchema> getCollectionSchema(const std::string& collection) {
- requireCapability(Client::Capability::kCollectionSchema, "getCollectionSchema");
- smartbotic::databasepb::GetCollectionSchemaRequest request;
- request.set_collection(qualify(collection));
- smartbotic::databasepb::GetCollectionSchemaResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->GetCollectionSchema(&context, request, &response);
- if (!status.ok()) {
- throwStatus(status, "getCollectionSchema: " + status.error_message(), trailerDetail(context));
- }
- if (!response.has_schema()) return std::nullopt;
- Client::CollectionSchema out;
- out.schema = nlohmann::json::parse(response.schema_json());
- out.mode = response.mode() == "audit" ? Client::SchemaMode::Audit : Client::SchemaMode::Enforce;
- out.auditViolations = response.audit_violations();
- out.refusals = response.refusals();
- out.armed = response.armed();
- return out;
- }
- Client::SchemaSuggestion suggestCollectionSchema(const std::string& collection, uint64_t sampleLimit) {
- requireCapability(Client::Capability::kCollectionSchema, "suggestCollectionSchema");
- smartbotic::databasepb::SuggestCollectionSchemaRequest request;
- request.set_collection(qualify(collection));
- request.set_sample_limit(sampleLimit);
- smartbotic::databasepb::SuggestCollectionSchemaResponse response;
- grpc::ClientContext context;
- context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
- attachAuth(context);
- auto status = stub_->SuggestCollectionSchema(&context, request, &response);
- if (!status.ok()) {
- throwStatus(status, "suggestCollectionSchema: " + status.error_message(), trailerDetail(context));
- }
- Client::SchemaSuggestion out;
- out.schema = nlohmann::json::parse(response.schema_json());
- out.rowsScanned = response.rows_scanned();
- out.complete = response.complete();
- return out;
- }
- std::vector<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)) {
- // v2.13.0 - nothing may escape this thread: an exception leaving a
- // std::thread calls std::terminate, so one throwing handler (or one
- // event body that does not parse) used to take the whole consumer
- // process down. The event is logged and dropped; the stream goes on.
- try {
- std::optional<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);
- } catch (const std::exception& e) {
- spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
- "or its parse threw: {}", event.collection(),
- event.document_id(), e.what());
- } catch (...) {
- spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
- "threw a non-std exception", event.collection(),
- event.document_id());
- }
- }
- });
- return std::make_shared<SubscriptionHandle>(
- std::move(context),
- std::move(reader),
- std::move(readerThread)
- );
- }
- // ===== Export (v2.13.0) =====
- //
- // The server's contract is in the proto, above ExportRequest. What this
- // side adds: a stream that ends without its trailer THROWS (it is not a
- // complete export, whatever it delivered); an unrecognised vector dtype
- // THROWS rather than being reinterpreted; and a handler returning false
- // stops the export AFTER that row, which therefore counts as delivered
- // (lastId names it, so a resume starts after it).
- Client::ExportSummary exportCollection(
- const std::string& collection, bool includeVectors, const std::string& afterId,
- const std::function<void(const Client::ExportHeader&)>& onHeader,
- const std::function<bool(Client::ExportRow&&)>& onRow,
- uint32_t batchRows) {
- smartbotic::databasepb::ExportRequest request;
- request.set_collection(qualify(collection));
- request.set_include_vectors(includeVectors);
- request.set_after_id(afterId);
- request.set_batch_rows(batchRows);
- // Not the per-call timeout: an export is long by design. The server
- // ends a stream at its own cap (header.max_stream_seconds, 600) with a
- // resume cursor; this deadline is only the backstop for a server that
- // stops answering.
- grpc::ClientContext context;
- context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(900));
- attachAuth(context);
- auto reader = stub_->ExportCollection(&context, request);
- auto abandon = [&]() {
- context.TryCancel();
- smartbotic::databasepb::ExportChunk drain;
- while (reader->Read(&drain)) {}
- (void)reader->Finish();
- };
- Client::ExportSummary summary;
- bool sawHeader = false;
- bool sawTrailer = false;
- smartbotic::databasepb::ExportTrailer trailer;
- smartbotic::databasepb::ExportChunk chunk;
- while (reader->Read(&chunk)) {
- if (chunk.has_header()) {
- const auto& h = chunk.header();
- if (h.vector_dtype() != "float32-le") {
- abandon();
- const std::string msg = "export: unrecognised vector dtype '" +
- h.vector_dtype() + "'; refusing to reinterpret the bytes";
- throw DetailedError(Client::ErrorCode::Unimplemented, msg,
- makeDetail(Client::ErrorCode::Unimplemented, msg, {}));
- }
- sawHeader = true;
- Client::ExportHeader out;
- out.collection = unqualify(h.collection());
- out.vectorDimension = h.vector_dimension();
- out.vectorDtype = h.vector_dtype();
- out.rowsAtSnapshot = h.rows_at_snapshot();
- out.batchRowsCap = h.batch_rows_cap();
- out.maxStreamSeconds = h.max_stream_seconds();
- if (onHeader) {
- try { onHeader(out); } catch (...) { abandon(); throw; }
- }
- } else if (chunk.has_rows()) {
- for (auto& r : *chunk.mutable_rows()->mutable_rows()) {
- Client::ExportRow row;
- row.id = r.document().id();
- row.vectorState = static_cast<Client::VectorState>(r.vector_state());
- const std::string& bytes = r.document().vector();
- if (!bytes.empty()) {
- if (bytes.size() % sizeof(float) != 0) {
- abandon();
- const std::string msg = "export: vector of '" + row.id +
- "' is not a whole number of float32 values";
- throw DetailedError(Client::ErrorCode::DataLoss, msg,
- makeDetail(Client::ErrorCode::DataLoss, msg, {}));
- }
- row.vector.resize(bytes.size() / sizeof(float));
- std::memcpy(row.vector.data(), bytes.data(), bytes.size());
- r.mutable_document()->clear_vector(); // the vector is row.vector, not "_vector"
- }
- row.document = documentToJson(r.document());
- std::string id = row.id;
- bool more = true;
- try { more = onRow(std::move(row)); } catch (...) { abandon(); throw; }
- ++summary.rowsSent;
- summary.lastId = std::move(id);
- if (!more) {
- abandon();
- summary.complete = false;
- return summary;
- }
- }
- } else if (chunk.has_trailer()) {
- sawTrailer = true;
- trailer = chunk.trailer();
- }
- }
- auto status = reader->Finish();
- if (!status.ok()) {
- spdlog::error("Client::exportCollection failed: {}", status.error_message());
- throwStatus(status, status.error_message(), trailerDetail(context));
- }
- if (!sawHeader || !sawTrailer) {
- const std::string msg = "export of '" + collection + "' ended without its trailer "
- "after " + std::to_string(summary.rowsSent) +
- " rows; it did not complete";
- throw DetailedError(Client::ErrorCode::Unavailable, msg,
- makeDetail(Client::ErrorCode::Unavailable, msg, {}));
- }
- if (trailer.rows_sent() != summary.rowsSent) {
- const std::string msg = "export of '" + collection + "': server reports " +
- std::to_string(trailer.rows_sent()) + " rows sent, " +
- std::to_string(summary.rowsSent) + " arrived";
- throw DetailedError(Client::ErrorCode::DataLoss, msg,
- makeDetail(Client::ErrorCode::DataLoss, msg, {}));
- }
- summary.complete = trailer.complete();
- return summary;
- }
- // ===== Version History =====
- Client::VersionHistoryResult getVersionHistory(const std::string& collection,
- const std::string& id, uint32_t limit, uint32_t offset) {
- smartbotic::databasepb::GetVersionHistoryRequest request;
- request.set_collection(qualify(collection));
- request.set_id(id);
- if (limit > 0) request.set_limit(limit);
- if (offset > 0) request.set_offset(offset);
- smartbotic::databasepb::GetVersionHistoryResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->GetVersionHistory(&context, request, &response);
- if (!status.ok()) {
- spdlog::error("Client::getVersionHistory failed: {}", status.error_message());
- throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
- }
- Client::VersionHistoryResult result;
- result.currentVersion = response.current_version();
- result.totalCount = response.total_count();
- result.documentDeleted = response.document_deleted();
- result.versions.reserve(response.versions_size());
- for (const auto& ver : response.versions()) {
- Client::VersionEntry entry;
- entry.version = ver.version();
- entry.timestamp = ver.timestamp();
- entry.updatedBy = ver.updated_by();
- if (!ver.data().empty()) {
- entry.data = nlohmann::json::parse(ver.data());
- }
- result.versions.push_back(std::move(entry));
- }
- return result;
- }
- std::optional<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;
- }
- // v2.13.0 - `failureOut` tells "no such file" (NotFound, answered in-band
- // by the server) from a call that failed (the real code). The bool-only
- // public form passes no sink and behaves exactly as before.
- bool deleteFile(const std::string& id, FailureSink failureOut = {}) {
- failureOut.reset();
- smartbotic::databasepb::DeleteFileRequest request;
- request.set_id(id);
- request.set_project(config_.project);
- smartbotic::databasepb::DeleteFileResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->DeleteFile(&context, request, &response);
- if (!status.ok()) {
- spdlog::error("Client::deleteFile failed: {}", status.error_message());
- failureOut.record(status);
- return false;
- }
- if (!response.deleted()) {
- failureOut.record(Client::ErrorCode::NotFound, "no such file in this project");
- }
- return response.deleted();
- }
- // v2.13.0 - same contract as deleteFile above.
- bool setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureSink failureOut = {}) {
- failureOut.reset();
- smartbotic::databasepb::SetFileTtlRequest request;
- request.set_id(id);
- request.set_project(config_.project);
- request.set_ttl_seconds(ttlSeconds);
- smartbotic::databasepb::SetFileTtlResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->SetFileTtl(&context, request, &response);
- if (!status.ok()) {
- spdlog::error("Client::setFileTtl failed: {}", status.error_message());
- failureOut.record(status);
- return false;
- }
- if (!response.updated()) {
- failureOut.record(Client::ErrorCode::NotFound,
- "no such file in this project, or it has already expired");
- }
- return response.updated();
- }
- Client::FileListResult listFiles(const std::string& file_type,
- const std::string& related_id,
- uint32_t limit, uint32_t offset,
- const std::string& checksum,
- const std::string& name) {
- smartbotic::databasepb::ListFilesRequest request;
- if (!file_type.empty()) request.set_file_type(file_type);
- if (!related_id.empty()) request.set_related_id(related_id);
- request.set_limit(limit);
- request.set_offset(offset);
- if (!checksum.empty()) request.set_checksum(checksum);
- if (!name.empty()) request.set_name(name);
- request.set_project(config_.project);
- smartbotic::databasepb::ListFilesResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->ListFiles(&context, request, &response);
- if (!status.ok()) {
- spdlog::error("Client::listFiles failed: {}", status.error_message());
- throwStatus(status, status.error_message());
- }
- Client::FileListResult result;
- result.total_count = response.total_count();
- result.has_more = response.has_more();
- for (const auto& f : response.files()) {
- Client::FileRecord record;
- record.id = f.id();
- record.name = f.name();
- record.mime_type = f.mime_type();
- record.size = f.size();
- record.file_type = f.file_type();
- record.related_id = f.related_id();
- record.checksum = f.checksum();
- record.is_public = f.is_public();
- record.created_at = f.created_at();
- record.project = f.project();
- for (const auto& [key, value] : f.metadata()) {
- record.metadata[key] = value;
- }
- result.files.push_back(std::move(record));
- }
- return result;
- }
- private:
- // Per-context setup: deadline + (v2.4) bearer-token auth metadata.
- //
- // Most RPC call sites in this library funnel through this helper —
- // unary (insert, get, update, ...) plus the unary file ops that need
- // the default deadline. Long-running streams (Subscribe) and the
- // file-streaming RPCs (UploadFile/DownloadFile) compute their own
- // deadlines and call `attachAuth()` separately so the auth metadata
- // still lands on every outbound RPC. Centralising both concerns here
- // means we don't need a gRPC ClientInterceptorFactoryInterface — the
- // interceptor route is also offered by gRPC++ but it sits in
- // grpc::experimental:: and would need to be re-validated on every
- // grpc minor; the per-context style keeps Stage E independent of
- // gRPC's TLS/interceptor experimental flux.
- void setDeadline(grpc::ClientContext& context) {
- context.set_deadline(
- std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs)
- );
- attachAuth(context);
- }
- // v2.13.1 - a write's deadline grows with its size: timeoutMs plus one
- // second per 4 MiB sent. A 20 MiB patch on a 60 MiB row legitimately takes
- // longer than a small write, and a fixed deadline made it time out while the
- // server completed it - the shape that produced "failed" writes that had
- // been applied.
- void setWriteDeadline(grpc::ClientContext& context, size_t requestBytes) {
- const auto extraMs = static_cast<uint64_t>(requestBytes / (4u * 1024 * 1024)) * 1000;
- context.set_deadline(std::chrono::system_clock::now() +
- std::chrono::milliseconds(config_.timeoutMs + extraMs));
- attachAuth(context);
- }
- // v2.4 — attach the bearer-token authorization metadata if configured.
- // Use this on contexts that set their own deadline (streams,
- // long-running ops) so the auth metadata still lands.
- //
- // v2.15.0 - every call also carries this library's version, so a server can
- // keep an old behaviour for an old client if a meaning ever has to change.
- // Every context passes through here (setDeadline, setWriteDeadline, the
- // streams), which is why the header is attached here and not elsewhere.
- void attachAuth(grpc::ClientContext& context) {
- context.AddMetadata("sbdb-client-version", SMARTBOTIC_DB_VERSION_STRING);
- if (!config_.auth_token.empty()) {
- context.AddMetadata("authorization", "Bearer " + config_.auth_token);
- }
- }
- public:
- // ===== Server info and capabilities (v2.15.0) =====
- std::optional<Client::ServerInfo> serverInfo(bool refresh) {
- {
- std::lock_guard<std::mutex> lk(infoMu_);
- if (!refresh && infoFetched_ &&
- std::chrono::steady_clock::now() - infoAt_ < std::chrono::seconds(60)) {
- return info_;
- }
- }
- smartbotic::databasepb::GetServerInfoRequest request;
- smartbotic::databasepb::GetServerInfoResponse response;
- grpc::ClientContext context;
- setDeadline(context);
- auto status = stub_->GetServerInfo(&context, request, &response);
- std::optional<Client::ServerInfo> got;
- if (status.ok()) {
- Client::ServerInfo si;
- si.version = response.version();
- si.commit = response.commit();
- si.capabilities.assign(response.capabilities().begin(), response.capabilities().end());
- si.clientVersionSeen = response.client_version();
- got = std::move(si);
- } else if (status.error_code() != grpc::StatusCode::UNIMPLEMENTED) {
- // An outage is not "an old server": answering nullopt here would
- // make every 2.15.0+ feature look unsupported during a blip.
- throwStatus(status, "serverInfo: " + status.error_message(), trailerDetail(context));
- }
- // UNIMPLEMENTED: a pre-2.15.0 server. Cached like an answer.
- std::lock_guard<std::mutex> lk(infoMu_);
- info_ = got;
- infoFetched_ = true;
- infoAt_ = std::chrono::steady_clock::now();
- return got;
- }
- bool serverSupports(const std::string& capability) {
- const auto si = serverInfo(false);
- if (!si) return false;
- return std::find(si->capabilities.begin(), si->capabilities.end(), capability) !=
- si->capabilities.end();
- }
- // For client methods that need a feature introduced in 2.15.0 or later:
- // refuse BEFORE sending, because an old server ignores what it does not
- // understand and answers something that looks right.
- void requireCapability(const char* capability, const char* what) {
- if (serverSupports(capability)) return;
- const auto si = serverInfo(false);
- const std::string msg = std::string(what) + ": the server does not support '" +
- capability + "' (server " +
- (si ? si->version : std::string("older than 2.15.0")) + ")";
- spdlog::error("Client::{}", msg);
- throw DetailedFailedPrecondition(
- msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg,
- R"({"reason":"server_unsupported"})"));
- }
- private:
- std::mutex infoMu_;
- bool infoFetched_ = false;
- std::optional<Client::ServerInfo> info_;
- std::chrono::steady_clock::time_point infoAt_{};
- Config config_;
- std::shared_ptr<grpc::Channel> channel_;
- std::unique_ptr<smartbotic::databasepb::DatabaseService::Stub> stub_;
- std::atomic<bool> connected_{false};
- std::atomic<bool> reached_{false}; // v2.13.1 - the last connect() attempt succeeded
- };
- // ===== 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);
- }
- std::vector<nlohmann::json> Client::find(const std::string& collection,
- const QueryOptions& options, WithVector) {
- return impl_->find(collection, options, {}, /*includeVector=*/true);
- }
- std::optional<nlohmann::json> Client::get(const std::string& collection,
- const std::string& id, WithVector) {
- return impl_->get(collection, id, /*includeVector=*/true);
- }
- Client::ExportSummary Client::exportCollection(
- const std::string& collection, bool includeVectors, const std::string& afterId,
- const std::function<void(const ExportHeader&)>& onHeader,
- const std::function<bool(ExportRow&&)>& onRow, uint32_t batchRows) {
- return impl_->exportCollection(collection, includeVectors, afterId, onHeader, onRow,
- batchRows);
- }
- Client::FindResult Client::findWithMetrics(const std::string& collection,
- const QueryOptions& options) {
- return impl_->findWithMetrics(collection, options);
- }
- uint64_t Client::count(const std::string& collection,
- const std::vector<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);
- }
- std::vector<Client::SimilarityResult> Client::similaritySearch(
- const std::string& collection, const std::vector<float>& queryVector,
- uint32_t topK, float minScore, const std::vector<Filter>& filters) {
- return impl_->similaritySearch(collection, queryVector, topK, minScore, filters);
- }
- bool Client::createCollection(const std::string& name, uint32_t defaultTtlSeconds,
- bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) {
- return impl_->createCollection(name, defaultTtlSeconds, encrypted, maxVersions, vectorDimension);
- }
- bool Client::dropCollection(const std::string& name) {
- return impl_->dropCollection(name);
- }
- std::vector<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);
- }
- bool Client::deleteFile(const std::string& id, Failure& failureOut) {
- return impl_->deleteFile(id, &failureOut);
- }
- bool Client::deleteFile(const std::string& id, FailureDetail& failureOut) {
- return impl_->deleteFile(id, &failureOut);
- }
- bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, Failure& failureOut) {
- return impl_->setFileTtl(id, ttlSeconds, &failureOut);
- }
- bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureDetail& failureOut) {
- return impl_->setFileTtl(id, ttlSeconds, &failureOut);
- }
- Client::FileListResult Client::listFiles(const std::string& file_type,
- const std::string& related_id,
- uint32_t limit, uint32_t offset,
- const std::string& checksum,
- const std::string& name) {
- return impl_->listFiles(file_type, related_id, limit, offset, checksum, name);
- }
- // v2.11.1 — see the header. The macros are defined on this target from the
- // top-level VERSION file and BUILD_GIT_COMMIT, exactly as the service and CLI
- // get theirs, so all three binaries answer the same question the same way.
- #ifndef SMARTBOTIC_DB_VERSION_STRING
- #define SMARTBOTIC_DB_VERSION_STRING "unknown"
- #endif
- #ifndef SMARTBOTIC_DB_GIT_COMMIT_STRING
- #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
- #endif
- Client::SchemaChangeResult Client::setCollectionSchema(const std::string& collection,
- const nlohmann::json& schema,
- SchemaMode mode) {
- return impl_->schemaChange(collection, schema.dump(), mode);
- }
- Client::SchemaChangeResult Client::removeCollectionSchema(const std::string& collection) {
- return impl_->schemaChange(collection, "", SchemaMode::Enforce);
- }
- std::optional<Client::CollectionSchema> Client::getCollectionSchema(const std::string& collection) {
- return impl_->getCollectionSchema(collection);
- }
- Client::SchemaSuggestion Client::suggestCollectionSchema(const std::string& collection,
- uint64_t sampleLimit) {
- return impl_->suggestCollectionSchema(collection, sampleLimit);
- }
- std::optional<Client::ServerInfo> Client::serverInfo(bool refresh) {
- return impl_->serverInfo(refresh);
- }
- bool Client::serverSupports(const std::string& capability) {
- return impl_->serverSupports(capability);
- }
- std::string clientLibraryVersion() { return SMARTBOTIC_DB_VERSION_STRING; }
- std::string clientLibraryCommit() { return SMARTBOTIC_DB_GIT_COMMIT_STRING; }
- } // namespace smartbotic::database
|