client.cpp 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674
  1. #include "smartbotic/database/client.hpp"
  2. #include <database.grpc.pb.h>
  3. #include <grpcpp/grpcpp.h>
  4. #include <grpcpp/security/credentials.h>
  5. #include <grpcpp/security/tls_certificate_verifier.h>
  6. #include <grpcpp/security/tls_credentials_options.h>
  7. #include <spdlog/spdlog.h>
  8. #include <atomic>
  9. #include <chrono>
  10. #include <cstdlib>
  11. #include <cstring>
  12. #include <fstream>
  13. #include <mutex>
  14. #include <sstream>
  15. #include <thread>
  16. namespace smartbotic::database {
  17. // v2.11.4 - defined out of line on purpose. An exception type whose members
  18. // are all inline has its typeinfo emitted in every object that uses it; with
  19. // the destructors here it lives in this library, so a throw inside the .so
  20. // and a catch in the consumer agree on the type by construction.
  21. Client::Error::Error(ErrorCode code, const std::string& message)
  22. : std::runtime_error(message), code_(code) {}
  23. Client::Error::~Error() = default;
  24. Client::AlreadyExists::AlreadyExists(const std::string& message)
  25. : Error(ErrorCode::AlreadyExists, message) {}
  26. Client::AlreadyExists::~AlreadyExists() = default;
  27. Client::FailedPrecondition::FailedPrecondition(const std::string& message)
  28. : Error(ErrorCode::FailedPrecondition, message) {}
  29. Client::FailedPrecondition::~FailedPrecondition() = default;
  30. Client::PermissionDenied::PermissionDenied(const std::string& message)
  31. : Error(ErrorCode::PermissionDenied, message) {}
  32. Client::PermissionDenied::~PermissionDenied() = default;
  33. namespace {
  34. // v2.11.4 - Client::ErrorCode mirrors grpc::StatusCode number for number, so
  35. // the conversion is a cast. The asserts pin the values callers branch on; the
  36. // gRPC status codes are fixed by its wire protocol and have never been
  37. // renumbered.
  38. static_assert(static_cast<int>(Client::ErrorCode::NotFound) == grpc::StatusCode::NOT_FOUND);
  39. static_assert(static_cast<int>(Client::ErrorCode::AlreadyExists) == grpc::StatusCode::ALREADY_EXISTS);
  40. static_assert(static_cast<int>(Client::ErrorCode::PermissionDenied) == grpc::StatusCode::PERMISSION_DENIED);
  41. static_assert(static_cast<int>(Client::ErrorCode::FailedPrecondition) == grpc::StatusCode::FAILED_PRECONDITION);
  42. static_assert(static_cast<int>(Client::ErrorCode::Unavailable) == grpc::StatusCode::UNAVAILABLE);
  43. static_assert(static_cast<int>(Client::ErrorCode::Unauthenticated) == grpc::StatusCode::UNAUTHENTICATED);
  44. Client::ErrorCode toErrorCode(grpc::StatusCode code) {
  45. return static_cast<Client::ErrorCode>(static_cast<int>(code));
  46. }
  47. // v2.12.0 - the refusal detail the server attaches as trailing metadata (see
  48. // `service DatabaseService` in database.proto). Empty when absent.
  49. constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin";
  50. #ifndef SMARTBOTIC_DB_VERSION_STRING
  51. #define SMARTBOTIC_DB_VERSION_STRING "unknown"
  52. #endif
  53. std::string trailerDetail(const grpc::ClientContext& context) {
  54. const auto& md = context.GetServerTrailingMetadata();
  55. auto it = md.find(kErrorDetailKey);
  56. if (it == md.end()) return {};
  57. return std::string(it->second.data(), it->second.size());
  58. }
  59. // Build a FailureDetail from a code, a message and the trailer JSON. A detail
  60. // that does not parse is ignored rather than allowed to turn a refusal into a
  61. // crash: the code and message still stand.
  62. Client::FailureDetail makeDetail(Client::ErrorCode code, const std::string& message,
  63. const std::string& detailJson) {
  64. Client::FailureDetail d;
  65. d.code = code;
  66. d.message = message;
  67. // v2.13.0 - gRPC refuses an oversized message itself (either side, before
  68. // our server code runs), with RESOURCE_EXHAUSTED and no detail, so a size
  69. // refusal looked exactly like a rate limit or memory pressure - and the
  70. // remedies differ: retrying never shrinks a payload. The library names it,
  71. // so no consumer has to match gRPC's text. The text is gRPC core's own
  72. // ("Sent message larger than max (N vs. M)", also "Received message
  73. // larger than max"), stable across the gRPC versions this is built with;
  74. // test_export pins it.
  75. if (detailJson.empty() && code == Client::ErrorCode::ResourceExhausted &&
  76. message.find("message larger than max") != std::string::npos) {
  77. d.reason = "message_too_large";
  78. }
  79. if (detailJson.empty()) return d;
  80. try {
  81. const auto j = nlohmann::json::parse(detailJson);
  82. if (!j.is_object()) return d;
  83. d.reason = j.value("reason", std::string{});
  84. if (auto it = j.find("fields"); it != j.end() && it->is_array()) {
  85. for (const auto& f : *it) if (f.is_string()) d.fields.push_back(f.get<std::string>());
  86. }
  87. if (auto it = j.find("values"); it != j.end()) d.values = *it;
  88. d.conflictingId = j.value("conflicting_id", std::string{});
  89. d.relation = j.value("relation", std::string{});
  90. if (auto it = j.find("current_version"); it != j.end() && it->is_number_unsigned()) {
  91. d.currentVersion = it->get<uint64_t>();
  92. }
  93. } catch (const std::exception&) {
  94. // keep code + message
  95. }
  96. return d;
  97. }
  98. // The exceptions this client throws carry a FailureDetail by deriving from the
  99. // public type AND this internal carrier; Client::errorDetail() cross-casts to
  100. // it. Internal types, so no public class changes size, and a consumer that
  101. // catches the public base sees exactly what it always did.
  102. struct DetailCarrier {
  103. explicit DetailCarrier(Client::FailureDetail d) : detail(std::move(d)) {}
  104. virtual ~DetailCarrier() = default;
  105. Client::FailureDetail detail;
  106. };
  107. struct DetailedError : Client::Error, DetailCarrier {
  108. DetailedError(Client::ErrorCode c, const std::string& m, Client::FailureDetail d)
  109. : Client::Error(c, m), DetailCarrier(std::move(d)) {}
  110. };
  111. struct DetailedAlreadyExists : Client::AlreadyExists, DetailCarrier {
  112. DetailedAlreadyExists(const std::string& m, Client::FailureDetail d)
  113. : Client::AlreadyExists(m), DetailCarrier(std::move(d)) {}
  114. };
  115. struct DetailedFailedPrecondition : Client::FailedPrecondition, DetailCarrier {
  116. DetailedFailedPrecondition(const std::string& m, Client::FailureDetail d)
  117. : Client::FailedPrecondition(m), DetailCarrier(std::move(d)) {}
  118. };
  119. struct DetailedPermissionDenied : Client::PermissionDenied, DetailCarrier {
  120. DetailedPermissionDenied(const std::string& m, Client::FailureDetail d)
  121. : Client::PermissionDenied(m), DetailCarrier(std::move(d)) {}
  122. };
  123. // v2.12.4 - THE RULE FOR READS: a read whose "nothing there" value (nullopt,
  124. // false, 0, an empty list, a default config) is also a valid answer must THROW
  125. // on a failed status, never return that value. Returning it made a transport
  126. // blip (UNAVAILABLE, DEADLINE_EXCEEDED) indistinguishable from absence, so a
  127. // consumer reported a definite 404 for a collection that existed and lost a
  128. // six-minute ingest to it. v2.4.2 (find on a missing collection) and v2.8.0
  129. // (permission denials) applied this rule one status code at a time; it now
  130. // applies to every code. Absence is always reported IN-BAND by the server
  131. // (found=false, exists=false, an empty list); only Find uses a NOT_FOUND
  132. // status, and that already threw. Exempt, deliberately: healthCheck /
  133. // getHealthInfo / getStats (their job is to answer "unreachable"),
  134. // getRelationsEnforced (fails toward enforced) and tryGetRelationsEnforced
  135. // (declines to answer). Writes keep returning false/0 - false already means
  136. // "did not happen", and they have Failure& overloads carrying the code.
  137. //
  138. // Throw the Client::Error subtype matching a failed status. `message` becomes
  139. // what(): every site passes what it threw before 2.11.4, so the text an
  140. // existing consumer logs or matches on is unchanged. v2.12.0: the thrown
  141. // object also carries the detail - see Client::errorDetail().
  142. [[noreturn]] void throwStatus(const grpc::Status& status, const std::string& message,
  143. const std::string& detailJson = {}) {
  144. auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(), detailJson);
  145. switch (status.error_code()) {
  146. case grpc::StatusCode::ALREADY_EXISTS: throw DetailedAlreadyExists(message, std::move(d));
  147. case grpc::StatusCode::FAILED_PRECONDITION: throw DetailedFailedPrecondition(message, std::move(d));
  148. case grpc::StatusCode::PERMISSION_DENIED: throw DetailedPermissionDenied(message, std::move(d));
  149. default: throw DetailedError(toErrorCode(status.error_code()), message, std::move(d));
  150. }
  151. }
  152. // Where a non-throwing call reports its failure: the 2.11.4 Failure, the
  153. // 2.12.0 FailureDetail, or neither (the original overloads). One sink so every
  154. // method records a failure once and both overload families stay identical.
  155. struct FailureSink {
  156. FailureSink() = default;
  157. FailureSink(Client::Failure* f) : failure(f) {} // NOLINT: implicit on purpose
  158. FailureSink(Client::FailureDetail* d) : detail(d) {} // NOLINT
  159. Client::Failure* failure = nullptr;
  160. Client::FailureDetail* detail = nullptr;
  161. void reset() const {
  162. if (failure) *failure = Client::Failure{};
  163. if (detail) *detail = Client::FailureDetail{};
  164. }
  165. void record(Client::ErrorCode code, const std::string& message,
  166. const std::string& detailJson = {}) const {
  167. if (failure) { failure->code = code; failure->message = message; }
  168. if (detail) *detail = makeDetail(code, message, detailJson);
  169. }
  170. void record(const grpc::Status& status, const std::string& detailJson = {}) const {
  171. record(toErrorCode(status.error_code()), status.error_message(), detailJson);
  172. }
  173. // An in-band refusal (status OK, success=false): the code is in the
  174. // response from a 2.12.0+ server, Unknown from an older one.
  175. // Copy a reason a nested call already recorded (v2.13.1).
  176. void copy(const Client::FailureDetail& d) const {
  177. if (failure) { failure->code = d.code; failure->message = d.message; }
  178. if (detail) *detail = d;
  179. }
  180. void recordInBand(int32_t errorCode, const std::string& message,
  181. const std::string& detailJson) const {
  182. record(errorCode != 0 ? static_cast<Client::ErrorCode>(errorCode) : Client::ErrorCode::Unknown,
  183. message, detailJson);
  184. }
  185. };
  186. // The JSON a read hands back: the stored fields plus the read metadata, and
  187. // (v2.13.0) "_vector" when the server sent the stored vector, which it does
  188. // only when the caller asked. The bytes are float32 little-endian.
  189. nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
  190. auto json = nlohmann::json::parse(doc.data());
  191. json["_id"] = doc.id();
  192. json["_version"] = doc.version();
  193. json["_created_at"] = doc.created_at();
  194. json["_updated_at"] = doc.updated_at();
  195. json["_created_by"] = doc.created_by();
  196. json["_updated_by"] = doc.updated_by();
  197. if (!doc.vector().empty()) {
  198. if (doc.vector().size() % sizeof(float) != 0) {
  199. throw DetailedError(Client::ErrorCode::DataLoss,
  200. "stored vector is not a whole number of float32 values",
  201. makeDetail(Client::ErrorCode::DataLoss, "bad vector bytes", {}));
  202. }
  203. std::vector<float> v(doc.vector().size() / sizeof(float));
  204. std::memcpy(v.data(), doc.vector().data(), doc.vector().size());
  205. json["_vector"] = v;
  206. }
  207. return json;
  208. }
  209. // v1.7.0 T11 — transient transport errors that are safe to retry for idempotent
  210. // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch).
  211. // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are
  212. // final — no retry.
  213. //
  214. // v2.13.1 - DEADLINE_EXCEEDED is retried only for an IDEMPOTENT write. The
  215. // deadline can expire while the server finishes the write (seen by
  216. // smartbotic-vectorapi on large patches: every one reported failure and had
  217. // been applied), so a retry repeats a write that already happened: an id-less
  218. // insert duplicates the row, an increment counts twice, and an insert with an
  219. // id, a conditional write or a delete reports a false AlreadyExists / version
  220. // conflict / not-found. Those are not retried; the failure carries reason
  221. // outcome_unknown (see outcomeUnknownDetail). UNAVAILABLE and
  222. // RESOURCE_EXHAUSTED still retry: the server did not act on the request.
  223. bool retryableStatus(const grpc::Status& s, bool idempotent) {
  224. switch (s.error_code()) {
  225. case grpc::StatusCode::DEADLINE_EXCEEDED: // may have been applied
  226. return idempotent;
  227. case grpc::StatusCode::RESOURCE_EXHAUSTED: // admission control or gRPC concurrency cap
  228. case grpc::StatusCode::UNAVAILABLE: // transient connection issue
  229. return true;
  230. default:
  231. return false;
  232. }
  233. }
  234. // v2.13.1 - a write that ended in DEADLINE_EXCEEDED may or may not have been
  235. // applied; say so in the reason, so a caller checks before redoing it instead
  236. // of reading "the write failed". Leaves a server-supplied detail alone.
  237. std::string outcomeUnknownDetail(const grpc::Status& s, const std::string& detailJson) {
  238. if (s.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && detailJson.empty()) {
  239. return R"({"reason":"outcome_unknown"})";
  240. }
  241. return detailJson;
  242. }
  243. // Exponential backoff with jitter. attempt=0 => baseMs; attempt=1 => baseMs*2; ...
  244. uint32_t computeBackoffMs(uint32_t baseMs, uint32_t attempt, uint32_t capMs, double jitterPct) {
  245. uint64_t exp = static_cast<uint64_t>(baseMs) << attempt;
  246. if (exp > capMs) exp = capMs;
  247. // ±jitterPct jitter; std::rand() is fine here — not a security sensitive RNG.
  248. double jitter = 1.0 + ((double(std::rand()) / RAND_MAX) * 2.0 - 1.0) * jitterPct;
  249. if (jitter < 0.1) jitter = 0.1;
  250. return static_cast<uint32_t>(exp * jitter);
  251. }
  252. // v2.4 — slurp a PEM-encoded CA cert file into a string. Returns empty
  253. // string on read failure; caller logs the surrounding context.
  254. std::string readCaCertFile(const std::string& path) {
  255. std::ifstream in(path, std::ios::binary);
  256. if (!in.is_open()) return {};
  257. std::ostringstream buf;
  258. buf << in.rdbuf();
  259. return buf.str();
  260. }
  261. } // anonymous namespace
  262. const Client::FailureDetail* Client::errorDetail(const Error& e) noexcept {
  263. const auto* carrier = dynamic_cast<const DetailCarrier*>(&e);
  264. return carrier != nullptr ? &carrier->detail : nullptr;
  265. }
  266. // ===== PIMPL Implementation =====
  267. class Client::Impl {
  268. public:
  269. explicit Impl(Config config) : config_(std::move(config)) {
  270. if (config_.project.empty()) config_.project = "default";
  271. }
  272. // v2.3 — qualify a collection name with Config::project unless the
  273. // caller already supplied a "<project>:<collection>" qualified form.
  274. // The qualified form always wins. Server-side parseProjectCollection
  275. // is strict on edge cases (leading colon, double colon, etc.) so
  276. // we just delegate the validation to the server.
  277. std::string qualify(std::string_view collection) const {
  278. if (collection.find(':') != std::string_view::npos) {
  279. return std::string(collection);
  280. }
  281. // v2.7.0 — system collections (`_views`, `_collection_meta`,
  282. // `_policies`, `_files`) are GLOBAL, not per-project: their rows are
  283. // already keyed by a project-qualified id. Qualifying the collection
  284. // name too produced `default:_policies`, which does not exist, so
  285. // reads silently found nothing while writes succeeded (the server
  286. // tolerates both spellings on the policy write path). That asymmetry
  287. // is exactly how a management command can look like it worked and
  288. // then show stale state.
  289. if (!collection.empty() && collection.front() == '_') {
  290. return std::string(collection);
  291. }
  292. std::string out;
  293. out.reserve(config_.project.size() + 1 + collection.size());
  294. out.append(config_.project);
  295. out.push_back(':');
  296. out.append(collection.data(), collection.size());
  297. return out;
  298. }
  299. // Inverse of qualify() for values coming back off the wire. Strips only
  300. // OUR project's prefix, so a name from another namespace stays visibly
  301. // qualified rather than being silently flattened into ours.
  302. std::string unqualify(const std::string& qualified) const {
  303. const std::string prefix = config_.project + ":";
  304. if (qualified.rfind(prefix, 0) == 0) {
  305. return qualified.substr(prefix.size());
  306. }
  307. return qualified;
  308. }
  309. ~Impl() {
  310. disconnect();
  311. }
  312. bool connect() {
  313. try {
  314. auto channelArgs = grpc::ChannelArguments();
  315. // Use longer keepalive intervals to avoid "too_many_pings" errors from server
  316. channelArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, 60000); // 60 seconds
  317. channelArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 20000); // 20 seconds
  318. channelArgs.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0); // Only ping when there are active calls
  319. // Set max message size to match server (100MB for file uploads)
  320. channelArgs.SetMaxReceiveMessageSize(100 * 1024 * 1024);
  321. channelArgs.SetMaxSendMessageSize(100 * 1024 * 1024);
  322. std::shared_ptr<grpc::ChannelCredentials> creds = buildChannelCredentials();
  323. if (!creds) {
  324. spdlog::error("Database client connection failed: could not build channel credentials");
  325. return false;
  326. }
  327. channel_ = grpc::CreateCustomChannel(
  328. config_.address,
  329. creds,
  330. channelArgs
  331. );
  332. stub_ = smartbotic::databasepb::DatabaseService::NewStub(channel_);
  333. connected_ = true;
  334. const char* scheme = config_.tls_enabled ? "tls" : "plaintext";
  335. const char* authed = config_.auth_token.empty() ? "no-auth" : "bearer-auth";
  336. // v2.13.1 - actually try. Creating a gRPC channel opens nothing, so
  337. // this used to return true and log "connected" against a dead port
  338. // (reported by smartbotic): connect() and isConnected() were not
  339. // reachability checks at all. Now it waits up to timeoutMs for the
  340. // channel to connect. On failure the client stays usable - gRPC
  341. // keeps reconnecting on later calls - but the answer is honest.
  342. const bool reachable = channel_->WaitForConnected(
  343. std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs));
  344. reached_ = reachable;
  345. if (!reachable) {
  346. spdlog::warn("Database client could not reach {} ({}, {}) within {} ms; "
  347. "it will keep trying on later calls",
  348. config_.address, scheme, authed, config_.timeoutMs);
  349. return false;
  350. }
  351. spdlog::info("Database client connected to {} ({}, {})",
  352. config_.address, scheme, authed);
  353. return true;
  354. } catch (const std::exception& e) {
  355. spdlog::error("Database client connection failed: {}", e.what());
  356. return false;
  357. }
  358. }
  359. // v2.4 — build the ChannelCredentials matching Config's TLS settings.
  360. //
  361. // Three cases:
  362. // 1. !tls_enabled → InsecureChannelCredentials
  363. // (v2.3 back-compat default).
  364. // 2. tls_enabled && !insecure_skip_verify → SslCredentials with
  365. // pem_root_certs read from tls_ca_cert_path, or empty (= system
  366. // trust roots) when the path is unset.
  367. // 3. tls_enabled && insecure_skip_verify → experimental
  368. // TlsChannelCredentialsOptions with NoOpCertificateVerifier and
  369. // set_verify_server_certs(false). Loud WARN on every connect.
  370. std::shared_ptr<grpc::ChannelCredentials> buildChannelCredentials() {
  371. if (!config_.tls_enabled) {
  372. return grpc::InsecureChannelCredentials();
  373. }
  374. if (config_.tls_insecure_skip_verify) {
  375. spdlog::warn(
  376. "Database client: connecting with tls_insecure_skip_verify — "
  377. "DEV ONLY. Server certificate will NOT be validated against any "
  378. "trust root. Drop the server's self-signed cert at "
  379. "tls_ca_cert_path for any production-shaped use.");
  380. // Route through gRPC's experimental TLS API. This is the path
  381. // gRPC documents for "accept any cert" — combine
  382. // NoOpCertificateVerifier with set_verify_server_certs(false).
  383. grpc::experimental::TlsChannelCredentialsOptions tlsOpts;
  384. tlsOpts.set_certificate_verifier(
  385. std::make_shared<grpc::experimental::NoOpCertificateVerifier>());
  386. tlsOpts.set_verify_server_certs(false);
  387. tlsOpts.set_check_call_host(false);
  388. auto creds = grpc::experimental::TlsCredentials(tlsOpts);
  389. if (!creds) {
  390. // No fallback that "trusts everything" without
  391. // experimental TLS — if the build/runtime can't produce
  392. // experimental TlsCredentials, refuse to silently degrade
  393. // to system-trust mode (which would reject the
  394. // self-signed cert anyway). The operator should bake the
  395. // server's self-signed cert into tls_ca_cert_path.
  396. spdlog::error(
  397. "Database client: tls_insecure_skip_verify requested but "
  398. "experimental TlsCredentials returned null. Set "
  399. "tls_ca_cert_path to the server's self-signed PEM "
  400. "instead.");
  401. return nullptr;
  402. }
  403. return creds;
  404. }
  405. grpc::SslCredentialsOptions sslOpts;
  406. if (!config_.tls_ca_cert_path.empty()) {
  407. sslOpts.pem_root_certs = readCaCertFile(config_.tls_ca_cert_path);
  408. if (sslOpts.pem_root_certs.empty()) {
  409. spdlog::error(
  410. "Database client: could not read tls_ca_cert_path '{}'",
  411. config_.tls_ca_cert_path);
  412. return nullptr;
  413. }
  414. }
  415. // Else leave pem_root_certs empty → gRPC uses system trust roots
  416. // (or GRPC_DEFAULT_SSL_ROOTS_FILE_PATH env var, per gRPC docs).
  417. return grpc::SslCredentials(sslOpts);
  418. }
  419. void disconnect() {
  420. connected_ = false;
  421. reached_ = false;
  422. stub_.reset();
  423. channel_.reset();
  424. }
  425. bool isConnected() const {
  426. if (!connected_ || !channel_) {
  427. return false;
  428. }
  429. // READY is connected. IDLE (no calls for a while) and CONNECTING
  430. // count only if the last connection attempt succeeded (v2.13.1):
  431. // against a frozen server the kernel accepts the TCP connection and
  432. // the channel sits in CONNECTING forever, which used to read as true.
  433. auto state = channel_->GetState(false);
  434. if (state == GRPC_CHANNEL_READY) return true;
  435. return reached_ && (state == GRPC_CHANNEL_IDLE || state == GRPC_CHANNEL_CONNECTING);
  436. }
  437. // ===== Document Operations =====
  438. std::string insert(const std::string& collection, const nlohmann::json& data,
  439. const std::string& id, uint32_t ttlSeconds,
  440. const std::string& actor) {
  441. smartbotic::databasepb::InsertRequest request;
  442. request.set_collection(qualify(collection));
  443. request.set_data(data.dump());
  444. if (!id.empty()) {
  445. request.set_id(id);
  446. }
  447. if (ttlSeconds > 0) {
  448. request.set_ttl_seconds(ttlSeconds);
  449. }
  450. if (!actor.empty()) {
  451. request.set_actor(actor);
  452. }
  453. smartbotic::databasepb::InsertResponse response;
  454. grpc::Status status;
  455. std::string detailJson; // v2.12.0 - the refusal detail, if any
  456. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  457. grpc::ClientContext context;
  458. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  459. response.Clear();
  460. status = stub_->Insert(&context, request, &response);
  461. detailJson = trailerDetail(context); // v2.12.0
  462. if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
  463. break;
  464. }
  465. if (attempt < config_.writeRetries) {
  466. uint32_t backoffMs = computeBackoffMs(
  467. config_.writeRetryBackoffMs, attempt,
  468. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
  469. spdlog::warn("Client::insert {}; retrying in {}ms (attempt {}/{})",
  470. status.error_message(), backoffMs,
  471. attempt + 1, config_.writeRetries);
  472. std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
  473. }
  474. }
  475. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  476. if (!status.ok()) {
  477. spdlog::error("Client::insert failed after retries: {}", status.error_message());
  478. throwStatus(status, status.error_message(), detailJson);
  479. }
  480. return response.id();
  481. }
  482. std::optional<nlohmann::json> get(const std::string& collection, const std::string& id,
  483. bool includeVector = false) {
  484. smartbotic::databasepb::GetRequest request;
  485. request.set_collection(qualify(collection));
  486. request.set_id(id);
  487. request.set_include_vector(includeVector); // v2.13.0
  488. smartbotic::databasepb::GetResponse response;
  489. grpc::ClientContext context;
  490. setDeadline(context);
  491. auto status = stub_->Get(&context, request, &response);
  492. if (!status.ok()) {
  493. // v2.8.0 — a permission denial must NOT look like "no data".
  494. // Returning empty here would leave an application unable to tell
  495. // "you may not see this" from "there is nothing to see", so it
  496. // would silently take the wrong branch. Same reasoning as the
  497. // v2.4.2 change that stopped Find returning empty for a missing
  498. // collection.
  499. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
  500. throw Client::PermissionDenied("access denied: get");
  501. }
  502. spdlog::error("Client::get failed: {}", status.error_message());
  503. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  504. }
  505. if (!response.found()) {
  506. return std::nullopt;
  507. }
  508. return documentToJson(response.document());
  509. }
  510. bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
  511. const std::string& actor, FailureSink failureOut = {}) {
  512. // Strip metadata fields from data — callers pass the JSON from get() which
  513. // includes _version, _id, etc. We use _version for optimistic locking.
  514. auto cleanData = data;
  515. cleanData.erase("_id");
  516. cleanData.erase("_version");
  517. cleanData.erase("_created_at");
  518. cleanData.erase("_updated_at");
  519. cleanData.erase("_created_by");
  520. cleanData.erase("_updated_by");
  521. // Optimistic locking with automatic retry:
  522. // 1. Read current version
  523. // 2. Call updateIfVersion
  524. // 3. On version conflict (another writer), re-read and retry
  525. for (uint32_t attempt = 0; attempt <= config_.maxRetries; ++attempt) {
  526. // Get current version. v2.12.4: get() now throws on a failed read
  527. // instead of returning nullopt. Before, an unreachable database
  528. // was reported here as "document not found" - the same conflation
  529. // get() had. update() still reports failure by returning false,
  530. // so the real code is recorded instead. A permission denial threw
  531. // out of here before 2.12.4 too, and still does.
  532. std::optional<nlohmann::json> current;
  533. try {
  534. current = get(collection, id);
  535. } catch (const Client::PermissionDenied&) {
  536. throw;
  537. } catch (const Client::Error& e) {
  538. failureOut.record(e.code(), e.what());
  539. return false;
  540. }
  541. if (!current) {
  542. // The one failure here the client can name itself, without
  543. // reading a server message: get() just said there is no
  544. // such document.
  545. failureOut.record(Client::ErrorCode::NotFound,
  546. "document not found: " + collection + "/" + id,
  547. R"({"reason":"not_found"})");
  548. return false; // document doesn't exist
  549. }
  550. uint64_t version = (*current)["_version"].get<uint64_t>();
  551. // Attempt version-checked update. Each attempt overwrites
  552. // failureOut, so what the caller reads is the LAST attempt's
  553. // reason, and a success leaves it clean.
  554. Client::FailureDetail attemptFailure;
  555. if (updateIfVersion(collection, id, cleanData, version, actor, &attemptFailure)) {
  556. failureOut.reset();
  557. return true;
  558. }
  559. failureOut.copy(attemptFailure);
  560. // v2.13.1 - only a version conflict (another writer between our
  561. // get() and this write) is worth another round. Every other
  562. // refusal - read-only, memory pressure, a document too large, an
  563. // outage - was retried here too and then logged as "version
  564. // conflicts", though no retry could change the answer.
  565. // A pre-2.12.0 server reports the conflict in-band with no code
  566. // (Unknown) and the text "Version conflict".
  567. const bool conflict =
  568. attemptFailure.code == Client::ErrorCode::Aborted ||
  569. (attemptFailure.code == Client::ErrorCode::Unknown &&
  570. attemptFailure.message.find("ersion conflict") != std::string::npos);
  571. if (!conflict) {
  572. return false;
  573. }
  574. // Version conflict — another client wrote between our get() and update
  575. if (attempt < config_.maxRetries) {
  576. spdlog::debug("Client::update version conflict on {}/{}, retry {}/{}",
  577. collection, id, attempt + 1, config_.maxRetries);
  578. }
  579. }
  580. spdlog::warn("Client::update failed after {} retries due to version conflicts on {}/{}",
  581. config_.maxRetries, collection, id);
  582. return false;
  583. }
  584. bool updateIfVersion(const std::string& collection, const std::string& id,
  585. const nlohmann::json& data, uint64_t expectedVersion,
  586. const std::string& actor,
  587. FailureSink failureOut = {}) {
  588. failureOut.reset();
  589. smartbotic::databasepb::UpdateRequest request;
  590. request.set_collection(qualify(collection));
  591. request.set_id(id);
  592. request.set_data(data.dump());
  593. request.set_expected_version(expectedVersion);
  594. if (!actor.empty()) {
  595. request.set_actor(actor);
  596. }
  597. smartbotic::databasepb::UpdateResponse response;
  598. grpc::Status status;
  599. std::string detailJson; // v2.12.0 - the refusal detail, if any
  600. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  601. grpc::ClientContext context;
  602. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  603. response.Clear();
  604. status = stub_->Update(&context, request, &response);
  605. detailJson = trailerDetail(context); // v2.12.0
  606. if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
  607. break;
  608. }
  609. if (attempt < config_.writeRetries) {
  610. uint32_t backoffMs = computeBackoffMs(
  611. config_.writeRetryBackoffMs, attempt,
  612. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
  613. spdlog::warn("Client::updateIfVersion {}; retrying in {}ms (attempt {}/{})",
  614. status.error_message(), backoffMs,
  615. attempt + 1, config_.writeRetries);
  616. std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
  617. }
  618. }
  619. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  620. if (!status.ok()) {
  621. spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message());
  622. failureOut.record(status, detailJson);
  623. return false;
  624. }
  625. if (!response.success()) {
  626. // Refused in-band: status OK. Since 2.12.0 the response carries the
  627. // code the refusal would have as a status; before, Unknown.
  628. failureOut.recordInBand(response.error_code(), response.error(), detailJson);
  629. }
  630. return response.success();
  631. }
  632. uint64_t patch(const std::string& collection, const std::string& id,
  633. const nlohmann::json& fields, const std::string& actor,
  634. std::optional<uint32_t> ttlSeconds = std::nullopt,
  635. FailureSink failureOut = {},
  636. std::optional<uint64_t> expectedVersion = std::nullopt, // v2.12.0
  637. const nlohmann::json* increments = nullptr, // v2.12.0
  638. nlohmann::json* incrementedOut = nullptr) { // v2.12.0
  639. failureOut.reset();
  640. smartbotic::databasepb::PatchDocumentRequest request;
  641. request.set_collection(qualify(collection));
  642. // v2.8.0 — presence distinguishes "leave the expiry alone" (absent) from
  643. // "clear it" (0) from "set it" (N).
  644. if (ttlSeconds.has_value()) request.set_ttl_seconds(*ttlSeconds);
  645. request.set_id(id);
  646. // v2.12.0 - an increment-only call sends no merge patch.
  647. if (!(increments != nullptr && fields.is_object() && fields.empty())) {
  648. request.set_patch_json(fields.dump());
  649. }
  650. if (expectedVersion.has_value()) request.set_expected_version(*expectedVersion);
  651. if (increments != nullptr) request.set_increments_json(increments->dump());
  652. if (!actor.empty()) {
  653. request.set_actor(actor);
  654. }
  655. smartbotic::databasepb::PatchDocumentResponse response;
  656. grpc::Status status;
  657. std::string detailJson; // v2.12.0 - the refusal detail, if any
  658. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  659. grpc::ClientContext context;
  660. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  661. response.Clear();
  662. status = stub_->PatchDocument(&context, request, &response);
  663. detailJson = trailerDetail(context); // v2.12.0
  664. if (status.ok() || !retryableStatus(status, /*idempotent=*/!request.has_expected_version() && request.increments_json().empty())) {
  665. break;
  666. }
  667. if (attempt < config_.writeRetries) {
  668. uint32_t backoffMs = computeBackoffMs(
  669. config_.writeRetryBackoffMs, attempt,
  670. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
  671. spdlog::warn("Client::patch {}; retrying in {}ms (attempt {}/{})",
  672. status.error_message(), backoffMs,
  673. attempt + 1, config_.writeRetries);
  674. std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
  675. }
  676. }
  677. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  678. if (!status.ok()) {
  679. spdlog::error("Client::patch failed after retries: {}", status.error_message());
  680. failureOut.record(status, detailJson);
  681. return 0;
  682. }
  683. if (!response.success()) {
  684. spdlog::error("Client::patch failed: {}", response.error());
  685. failureOut.recordInBand(response.error_code(), response.error(), detailJson);
  686. return 0;
  687. }
  688. if (incrementedOut != nullptr) {
  689. *incrementedOut = response.incremented_json().empty()
  690. ? nlohmann::json::object()
  691. : nlohmann::json::parse(response.incremented_json());
  692. }
  693. return response.new_version();
  694. }
  695. std::pair<std::string, bool> upsert(const std::string& collection, const nlohmann::json& data,
  696. const std::string& id, uint32_t ttlSeconds,
  697. const std::string& actor) {
  698. smartbotic::databasepb::UpsertRequest request;
  699. request.set_collection(qualify(collection));
  700. request.set_data(data.dump());
  701. if (!id.empty()) {
  702. request.set_id(id);
  703. }
  704. if (ttlSeconds > 0) {
  705. request.set_ttl_seconds(ttlSeconds);
  706. }
  707. if (!actor.empty()) {
  708. request.set_actor(actor);
  709. }
  710. smartbotic::databasepb::UpsertResponse response;
  711. grpc::Status status;
  712. std::string detailJson; // v2.12.0 - the refusal detail, if any
  713. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  714. grpc::ClientContext context;
  715. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  716. response.Clear();
  717. status = stub_->Upsert(&context, request, &response);
  718. detailJson = trailerDetail(context); // v2.12.0
  719. if (status.ok() || !retryableStatus(status, /*idempotent=*/!id.empty())) {
  720. break;
  721. }
  722. if (attempt < config_.writeRetries) {
  723. uint32_t backoffMs = computeBackoffMs(
  724. config_.writeRetryBackoffMs, attempt,
  725. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
  726. spdlog::warn("Client::upsert {}; retrying in {}ms (attempt {}/{})",
  727. status.error_message(), backoffMs,
  728. attempt + 1, config_.writeRetries);
  729. std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
  730. }
  731. }
  732. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  733. if (!status.ok()) {
  734. spdlog::error("Client::upsert failed after retries: {}", status.error_message());
  735. throwStatus(status, status.error_message(), detailJson);
  736. }
  737. return {response.id(), response.inserted()};
  738. }
  739. // errorOut is optional: nullptr keeps the old single-value remove()'s
  740. // behaviour (log at spdlog::error and swallow the message). Non-null is
  741. // what lets a caller distinguish "already gone" from "blocked" - a
  742. // relation with on_delete=restrict/no_action refuses via a real gRPC
  743. // FAILED_PRECONDITION, not deleted=false, and that message is the only
  744. // way an operator learns WHAT blocked the delete.
  745. bool removeImpl(const std::string& collection, const std::string& id,
  746. std::string* errorOut, FailureSink failureOut = {},
  747. const std::string& actor = {}) {
  748. failureOut.reset();
  749. smartbotic::databasepb::DeleteRequest request;
  750. request.set_collection(qualify(collection));
  751. request.set_id(id);
  752. if (!actor.empty()) {
  753. request.set_actor(actor);
  754. }
  755. smartbotic::databasepb::DeleteResponse response;
  756. grpc::Status status;
  757. std::string detailJson; // v2.12.0 - the refusal detail, if any
  758. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  759. grpc::ClientContext context;
  760. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  761. response.Clear();
  762. status = stub_->Delete(&context, request, &response);
  763. detailJson = trailerDetail(context); // v2.12.0
  764. if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
  765. break;
  766. }
  767. if (attempt < config_.writeRetries) {
  768. uint32_t backoffMs = computeBackoffMs(
  769. config_.writeRetryBackoffMs, attempt,
  770. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter);
  771. spdlog::warn("Client::remove {}; retrying in {}ms (attempt {}/{})",
  772. status.error_message(), backoffMs,
  773. attempt + 1, config_.writeRetries);
  774. std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
  775. }
  776. }
  777. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  778. if (!status.ok()) {
  779. spdlog::error("Client::remove failed after retries: {}", status.error_message());
  780. if (errorOut != nullptr) *errorOut = status.error_message();
  781. failureOut.record(status, detailJson);
  782. return false;
  783. }
  784. return response.deleted();
  785. }
  786. bool remove(const std::string& collection, const std::string& id) {
  787. return removeImpl(collection, id, nullptr);
  788. }
  789. bool remove(const std::string& collection, const std::string& id, std::string& errorOut) {
  790. errorOut.clear();
  791. return removeImpl(collection, id, &errorOut);
  792. }
  793. bool remove(const std::string& collection, const std::string& id, Client::Failure& failureOut) {
  794. return removeImpl(collection, id, nullptr, &failureOut);
  795. }
  796. bool removeAs(const std::string& collection, const std::string& id,
  797. const std::string& actor, FailureSink failureOut) {
  798. return removeImpl(collection, id, nullptr, failureOut, actor);
  799. }
  800. // v2.12.0 - BatchDelete, which the client never exposed.
  801. std::optional<Client::BatchRemoveResult> removeManyAs(const std::string& collection,
  802. const std::vector<std::string>& ids,
  803. const std::string& actor,
  804. FailureSink failureOut) {
  805. failureOut.reset();
  806. smartbotic::databasepb::BatchDeleteRequest request;
  807. request.set_collection(qualify(collection));
  808. for (const auto& id : ids) request.add_ids(id);
  809. if (!actor.empty()) request.set_actor(actor);
  810. smartbotic::databasepb::BatchDeleteResponse response;
  811. grpc::Status status;
  812. std::string detailJson;
  813. // v2.13.1 - retried only when the server cannot have acted (UNAVAILABLE,
  814. // RESOURCE_EXHAUSTED). After a DEADLINE_EXCEEDED the first attempt may
  815. // have deleted the ids, and a retry would report them as not found, so
  816. // that failure is returned with reason outcome_unknown instead.
  817. for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
  818. grpc::ClientContext context;
  819. setWriteDeadline(context, request.ByteSizeLong()); // v2.13.1
  820. response.Clear();
  821. status = stub_->BatchDelete(&context, request, &response);
  822. detailJson = trailerDetail(context);
  823. if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) break;
  824. if (attempt < config_.writeRetries) {
  825. std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs(
  826. config_.writeRetryBackoffMs, attempt,
  827. config_.writeRetryMaxBackoffMs, config_.writeRetryJitter)));
  828. }
  829. }
  830. detailJson = outcomeUnknownDetail(status, detailJson); // v2.13.1
  831. if (!status.ok()) {
  832. spdlog::error("Client::removeManyAs failed: {}", status.error_message());
  833. failureOut.record(status, detailJson);
  834. return std::nullopt;
  835. }
  836. Client::BatchRemoveResult out;
  837. out.deletedCount = response.deleted_count();
  838. out.deletedIds.assign(response.deleted_ids().begin(), response.deleted_ids().end());
  839. return out;
  840. }
  841. bool exists(const std::string& collection, const std::string& id) {
  842. smartbotic::databasepb::ExistsRequest request;
  843. request.set_collection(qualify(collection));
  844. request.set_id(id);
  845. smartbotic::databasepb::ExistsResponse response;
  846. grpc::ClientContext context;
  847. setDeadline(context);
  848. auto status = stub_->Exists(&context, request, &response);
  849. if (!status.ok()) {
  850. // v2.8.0 — a permission denial must NOT look like "no data".
  851. // Returning empty here would leave an application unable to tell
  852. // "you may not see this" from "there is nothing to see", so it
  853. // would silently take the wrong branch. Same reasoning as the
  854. // v2.4.2 change that stopped Find returning empty for a missing
  855. // collection.
  856. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
  857. throw Client::PermissionDenied("access denied: exists");
  858. }
  859. spdlog::error("Client::exists failed: {}", status.error_message());
  860. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  861. }
  862. return response.exists();
  863. }
  864. // ===== Query Operations =====
  865. std::vector<nlohmann::json> find(const std::string& collection,
  866. const Client::QueryOptions& options,
  867. const std::vector<std::string>& projection = {},
  868. bool includeVector = false) {
  869. smartbotic::databasepb::FindRequest request;
  870. request.set_collection(qualify(collection));
  871. // Set filters
  872. for (const auto& filter : options.filters) {
  873. auto* pb = request.add_filters();
  874. pb->set_field(filter.field);
  875. pb->set_value(filter.value.dump());
  876. pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
  877. }
  878. // Set sorting
  879. if (!options.sortField.empty()) {
  880. auto* sort = request.mutable_sort();
  881. sort->set_field(options.sortField);
  882. sort->set_descending(options.sortDescending);
  883. }
  884. // Set pagination
  885. request.set_limit(options.limit);
  886. request.set_offset(options.offset);
  887. // v2.7.1 — field projection, passed alongside QueryOptions rather than
  888. // inside it: adding a member would change the struct size, and with an
  889. // unchanged soname an installed consumer crashes. See client.hpp.
  890. for (const auto& f : projection) {
  891. request.add_projection(f);
  892. }
  893. request.set_include_vector(includeVector); // v2.13.0
  894. smartbotic::databasepb::FindResponse response;
  895. grpc::ClientContext context;
  896. setDeadline(context);
  897. auto status = stub_->Find(&context, request, &response);
  898. if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
  899. // Surfaced rather than logged: an unknown collection or view is a
  900. // caller bug, and returning {} here is indistinguishable from a
  901. // legitimately empty result. Since v2.12.4 every other failure
  902. // throws too (below).
  903. throwStatus(status, status.error_message());
  904. }
  905. if (!status.ok()) {
  906. // v2.8.0 — a permission denial must NOT look like "no data".
  907. // Returning empty here would leave an application unable to tell
  908. // "you may not see this" from "there is nothing to see", so it
  909. // would silently take the wrong branch. Same reasoning as the
  910. // v2.4.2 change that stopped Find returning empty for a missing
  911. // collection.
  912. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
  913. throw Client::PermissionDenied("access denied: find");
  914. }
  915. spdlog::error("Client::find failed: {}", status.error_message());
  916. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  917. }
  918. std::vector<nlohmann::json> results;
  919. results.reserve(response.documents_size());
  920. for (const auto& doc : response.documents()) {
  921. results.push_back(documentToJson(doc));
  922. }
  923. return results;
  924. }
  925. Client::FindResult findWithMetrics(const std::string& collection,
  926. const Client::QueryOptions& options,
  927. const std::vector<std::string>& projection = {}) {
  928. smartbotic::databasepb::FindRequest request;
  929. request.set_collection(qualify(collection));
  930. // Set filters
  931. for (const auto& filter : options.filters) {
  932. auto* pb = request.add_filters();
  933. pb->set_field(filter.field);
  934. pb->set_value(filter.value.dump());
  935. pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
  936. }
  937. // Set sorting
  938. if (!options.sortField.empty()) {
  939. auto* sort = request.mutable_sort();
  940. sort->set_field(options.sortField);
  941. sort->set_descending(options.sortDescending);
  942. }
  943. // Set pagination
  944. request.set_limit(options.limit);
  945. request.set_offset(options.offset);
  946. // v2.7.1 — field projection, passed alongside QueryOptions rather than
  947. // inside it: adding a member would change the struct size, and with an
  948. // unchanged soname an installed consumer crashes. See client.hpp.
  949. for (const auto& f : projection) {
  950. request.add_projection(f);
  951. }
  952. smartbotic::databasepb::FindResponse response;
  953. grpc::ClientContext context;
  954. setDeadline(context);
  955. auto status = stub_->Find(&context, request, &response);
  956. if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
  957. throwStatus(status, status.error_message()); // see find()
  958. }
  959. if (!status.ok()) {
  960. // v2.8.0 — a permission denial must NOT look like "no data".
  961. // Returning empty here would leave an application unable to tell
  962. // "you may not see this" from "there is nothing to see", so it
  963. // would silently take the wrong branch. Same reasoning as the
  964. // v2.4.2 change that stopped Find returning empty for a missing
  965. // collection.
  966. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
  967. throw Client::PermissionDenied("access denied: findWithMetrics");
  968. }
  969. spdlog::error("Client::findWithMetrics failed: {}", status.error_message());
  970. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  971. }
  972. Client::FindResult result;
  973. result.totalCount = response.total_count();
  974. result.hasMore = response.has_more();
  975. result.usedWalFallback = response.used_wal_fallback();
  976. result.memoryMatchCount = response.memory_match_count();
  977. result.walMatchCount = response.wal_match_count();
  978. result.memorySearchMicros = response.memory_search_micros();
  979. result.walSearchMicros = response.wal_search_micros();
  980. result.documents.reserve(response.documents_size());
  981. for (const auto& doc : response.documents()) {
  982. auto json = nlohmann::json::parse(doc.data());
  983. json["_id"] = doc.id();
  984. json["_version"] = doc.version();
  985. json["_created_at"] = doc.created_at();
  986. json["_updated_at"] = doc.updated_at();
  987. json["_created_by"] = doc.created_by();
  988. json["_updated_by"] = doc.updated_by();
  989. result.documents.push_back(json);
  990. }
  991. return result;
  992. }
  993. uint64_t count(const std::string& collection,
  994. const std::vector<Client::Filter>& filters) {
  995. smartbotic::databasepb::CountRequest request;
  996. request.set_collection(qualify(collection));
  997. for (const auto& filter : filters) {
  998. auto* pb = request.add_filters();
  999. pb->set_field(filter.field);
  1000. pb->set_value(filter.value.dump());
  1001. pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
  1002. }
  1003. smartbotic::databasepb::CountResponse response;
  1004. grpc::ClientContext context;
  1005. setDeadline(context);
  1006. auto status = stub_->Count(&context, request, &response);
  1007. if (!status.ok()) {
  1008. // v2.8.0 — a permission denial must NOT look like "no data".
  1009. // Returning empty here would leave an application unable to tell
  1010. // "you may not see this" from "there is nothing to see", so it
  1011. // would silently take the wrong branch. Same reasoning as the
  1012. // v2.4.2 change that stopped Find returning empty for a missing
  1013. // collection.
  1014. if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
  1015. throw Client::PermissionDenied("access denied: count");
  1016. }
  1017. spdlog::error("Client::count failed: {}", status.error_message());
  1018. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1019. }
  1020. return response.count();
  1021. }
  1022. // ===== Set Operations =====
  1023. bool setAdd(const std::string& collection, const std::string& setId, const std::string& member) {
  1024. smartbotic::databasepb::SetAddRequest request;
  1025. request.set_collection(qualify(collection));
  1026. request.set_set_id(setId);
  1027. request.set_member(member);
  1028. smartbotic::databasepb::SetAddResponse response;
  1029. grpc::ClientContext context;
  1030. setDeadline(context);
  1031. auto status = stub_->SetAdd(&context, request, &response);
  1032. if (!status.ok()) {
  1033. spdlog::error("Client::setAdd failed: {}", status.error_message());
  1034. return false;
  1035. }
  1036. return response.added();
  1037. }
  1038. bool setRemove(const std::string& collection, const std::string& setId, const std::string& member) {
  1039. smartbotic::databasepb::SetRemoveRequest request;
  1040. request.set_collection(qualify(collection));
  1041. request.set_set_id(setId);
  1042. request.set_member(member);
  1043. smartbotic::databasepb::SetRemoveResponse response;
  1044. grpc::ClientContext context;
  1045. setDeadline(context);
  1046. auto status = stub_->SetRemove(&context, request, &response);
  1047. if (!status.ok()) {
  1048. spdlog::error("Client::setRemove failed: {}", status.error_message());
  1049. return false;
  1050. }
  1051. return response.removed();
  1052. }
  1053. std::vector<std::string> setMembers(const std::string& collection, const std::string& setId) {
  1054. smartbotic::databasepb::SetMembersRequest request;
  1055. request.set_collection(qualify(collection));
  1056. request.set_set_id(setId);
  1057. smartbotic::databasepb::SetMembersResponse response;
  1058. grpc::ClientContext context;
  1059. setDeadline(context);
  1060. auto status = stub_->SetMembers(&context, request, &response);
  1061. if (!status.ok()) {
  1062. spdlog::error("Client::setMembers failed: {}", status.error_message());
  1063. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1064. }
  1065. return {response.members().begin(), response.members().end()};
  1066. }
  1067. bool setIsMember(const std::string& collection, const std::string& setId, const std::string& member) {
  1068. smartbotic::databasepb::SetIsMemberRequest request;
  1069. request.set_collection(qualify(collection));
  1070. request.set_set_id(setId);
  1071. request.set_member(member);
  1072. smartbotic::databasepb::SetIsMemberResponse response;
  1073. grpc::ClientContext context;
  1074. setDeadline(context);
  1075. auto status = stub_->SetIsMember(&context, request, &response);
  1076. if (!status.ok()) {
  1077. spdlog::error("Client::setIsMember failed: {}", status.error_message());
  1078. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1079. }
  1080. return response.is_member();
  1081. }
  1082. // ===== Collection Management =====
  1083. std::vector<Client::SimilarityResult> similaritySearch(
  1084. const std::string& collection, const std::vector<float>& queryVector,
  1085. uint32_t topK, float minScore,
  1086. const std::vector<Client::Filter>& filters = {}) {
  1087. // v2.15.0 - a server that answers GetServerInfo and lacks the feature
  1088. // is refused before sending. A pre-2.15.0 server cannot say, so for it
  1089. // the response's filters_applied (below) remains the guard.
  1090. if (!filters.empty()) {
  1091. const auto si = serverInfo(false);
  1092. if (si && std::find(si->capabilities.begin(), si->capabilities.end(),
  1093. Client::Capability::kFilteredSimilarity) ==
  1094. si->capabilities.end()) {
  1095. requireCapability(Client::Capability::kFilteredSimilarity, "similaritySearch");
  1096. }
  1097. }
  1098. smartbotic::databasepb::SimilaritySearchRequest request;
  1099. request.set_collection(qualify(collection));
  1100. for (float v : queryVector) {
  1101. request.add_query_vector(v);
  1102. }
  1103. request.set_top_k(topK);
  1104. request.set_min_score(minScore);
  1105. for (const auto& filter : filters) {
  1106. auto* pb = request.add_filters();
  1107. pb->set_field(filter.field);
  1108. pb->set_value(filter.value.dump());
  1109. pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(filter.op));
  1110. }
  1111. smartbotic::databasepb::SimilaritySearchResponse response;
  1112. grpc::ClientContext context;
  1113. setDeadline(context);
  1114. auto status = stub_->SimilaritySearch(&context, request, &response);
  1115. if (!status.ok()) {
  1116. spdlog::error("Client::similaritySearch failed: {}", status.error_message());
  1117. throwStatus(status, status.error_message());
  1118. }
  1119. // v2.14.0 - a pre-2.14.0 server ignores the filters and ranks the
  1120. // whole collection. Those rows look exactly like a filtered answer, so
  1121. // they are refused rather than returned.
  1122. if (!filters.empty() && !response.filters_applied()) {
  1123. const std::string msg =
  1124. "similaritySearch: the server does not support filters (needs >= 2.14.0); "
  1125. "its answer would be unfiltered";
  1126. spdlog::error("Client::{}", msg);
  1127. throw DetailedFailedPrecondition(
  1128. msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg,
  1129. R"({"reason":"filters_unsupported"})"));
  1130. }
  1131. std::vector<Client::SimilarityResult> results;
  1132. results.reserve(response.results_size());
  1133. for (const auto& r : response.results()) {
  1134. Client::SimilarityResult entry;
  1135. entry.id = r.id();
  1136. entry.score = r.score();
  1137. if (!r.data().empty()) {
  1138. entry.data = nlohmann::json::parse(r.data());
  1139. }
  1140. results.push_back(std::move(entry));
  1141. }
  1142. return results;
  1143. }
  1144. bool createCollection(const std::string& name, uint32_t defaultTtlSeconds, bool encrypted,
  1145. uint32_t maxVersions, uint32_t vectorDimension) {
  1146. smartbotic::databasepb::CreateCollectionRequest request;
  1147. // v2.4.5 — MUST qualify. Sending a bare name here while insert/get/
  1148. // find all qualify created TWO collections from one call site: the
  1149. // bare one received the options (encrypted, maxVersions,
  1150. // vectorDimension, TTL) and stayed empty, while the qualified one
  1151. // was created implicitly by the first insert with DEFAULTS. Silent,
  1152. // and unrecoverable for vectorDimension, which is immutable after
  1153. // creation. Same class of bug as the v2.4.2 createView break.
  1154. request.set_name(qualify(name));
  1155. auto* options = request.mutable_options();
  1156. if (defaultTtlSeconds > 0) {
  1157. options->set_default_ttl_seconds(defaultTtlSeconds);
  1158. }
  1159. options->set_encrypted(encrypted);
  1160. if (maxVersions > 0) {
  1161. options->set_max_versions(maxVersions);
  1162. }
  1163. if (vectorDimension > 0) {
  1164. options->set_vector_dimension(vectorDimension);
  1165. }
  1166. smartbotic::databasepb::CreateCollectionResponse response;
  1167. grpc::ClientContext context;
  1168. setDeadline(context);
  1169. auto status = stub_->CreateCollection(&context, request, &response);
  1170. if (!status.ok()) {
  1171. spdlog::error("Client::createCollection failed: {}", status.error_message());
  1172. return false;
  1173. }
  1174. return response.created();
  1175. }
  1176. bool dropCollection(const std::string& name) {
  1177. smartbotic::databasepb::DropCollectionRequest request;
  1178. // v2.4.5 — MUST qualify. Unqualified, this dropped the empty phantom
  1179. // created by createCollection and returned TRUE while every document
  1180. // in <project>:<name> remained readable — a deletion request that
  1181. // reports success and deletes nothing.
  1182. request.set_name(qualify(name));
  1183. smartbotic::databasepb::DropCollectionResponse response;
  1184. grpc::ClientContext context;
  1185. setDeadline(context);
  1186. auto status = stub_->DropCollection(&context, request, &response);
  1187. if (!status.ok()) {
  1188. spdlog::error("Client::dropCollection failed: {}", status.error_message());
  1189. return false;
  1190. }
  1191. return response.dropped();
  1192. }
  1193. std::vector<std::string> listCollections() {
  1194. smartbotic::databasepb::ListCollectionsRequest request;
  1195. // v2.8.0 — scope the listing to this client's project, so a workspace
  1196. // never sees another workspace's collection names.
  1197. request.set_project(config_.project);
  1198. smartbotic::databasepb::ListCollectionsResponse response;
  1199. grpc::ClientContext context;
  1200. setDeadline(context);
  1201. auto status = stub_->ListCollections(&context, request, &response);
  1202. if (!status.ok()) {
  1203. spdlog::error("Client::listCollections failed: {}", status.error_message());
  1204. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1205. }
  1206. // v2.4.5 — round-trip the naming: callers pass bare names in, so they
  1207. // get bare names back for their OWN project. Names belonging to other
  1208. // projects stay visibly qualified rather than being flattened into
  1209. // ours (same rule as listViews). Note the server still returns every
  1210. // project's collections; ListCollectionsRequest has no project filter
  1211. // yet, unlike ListViewsRequest.
  1212. std::vector<std::string> out;
  1213. out.reserve(static_cast<size_t>(response.names_size()));
  1214. for (const auto& n : response.names()) {
  1215. out.push_back(unqualify(n));
  1216. }
  1217. return out;
  1218. }
  1219. std::optional<Client::CollectionInfo> getCollectionInfo(const std::string& name) {
  1220. smartbotic::databasepb::GetCollectionInfoRequest request;
  1221. // v2.4.5 — MUST qualify, else this reports on the phantom (0 docs)
  1222. // rather than the collection the caller reads and writes.
  1223. request.set_name(qualify(name));
  1224. smartbotic::databasepb::GetCollectionInfoResponse response;
  1225. grpc::ClientContext context;
  1226. setDeadline(context);
  1227. auto status = stub_->GetCollectionInfo(&context, request, &response);
  1228. if (!status.ok()) {
  1229. spdlog::error("Client::getCollectionInfo failed: {}", status.error_message());
  1230. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1231. }
  1232. if (!response.found()) {
  1233. return std::nullopt;
  1234. }
  1235. const auto& info = response.info();
  1236. Client::CollectionInfo result;
  1237. result.name = info.name();
  1238. result.documentCount = info.document_count();
  1239. result.sizeBytes = info.size_bytes();
  1240. result.defaultTtlSeconds = info.options().default_ttl_seconds();
  1241. result.encrypted = info.options().encrypted();
  1242. result.maxVersions = info.options().max_versions();
  1243. result.createdAt = info.created_at();
  1244. result.updatedAt = info.updated_at();
  1245. return result;
  1246. }
  1247. // ===== Project Management (v2.3 Stage F) =====
  1248. std::vector<std::string> listProjects() {
  1249. smartbotic::databasepb::ListProjectsRequest request;
  1250. smartbotic::databasepb::ListProjectsResponse response;
  1251. grpc::ClientContext context;
  1252. setDeadline(context);
  1253. auto status = stub_->ListProjects(&context, request, &response);
  1254. if (!status.ok()) {
  1255. spdlog::error("Client::listProjects failed: {}", status.error_message());
  1256. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1257. }
  1258. return {response.projects().begin(), response.projects().end()};
  1259. }
  1260. bool createProject(const std::string& name) {
  1261. smartbotic::databasepb::CreateProjectRequest request;
  1262. request.set_name(name);
  1263. smartbotic::databasepb::CreateProjectResponse response;
  1264. grpc::ClientContext context;
  1265. setDeadline(context);
  1266. auto status = stub_->CreateProject(&context, request, &response);
  1267. if (!status.ok()) {
  1268. spdlog::error("Client::createProject failed: {}", status.error_message());
  1269. throwStatus(status, "createProject transport failure: " + status.error_message());
  1270. }
  1271. if (!response.error().empty()) {
  1272. // Validation error (invalid name etc.) — surfaced via the
  1273. // response field, not the gRPC status.
  1274. throw std::runtime_error("createProject('" + name + "') rejected: " +
  1275. response.error());
  1276. }
  1277. return response.created();
  1278. }
  1279. void dropProject(const std::string& name) {
  1280. smartbotic::databasepb::DropProjectRequest request;
  1281. request.set_name(name);
  1282. smartbotic::databasepb::DropProjectResponse response;
  1283. grpc::ClientContext context;
  1284. setDeadline(context);
  1285. auto status = stub_->DropProject(&context, request, &response);
  1286. if (!status.ok()) {
  1287. spdlog::error("Client::dropProject failed: {}", status.error_message());
  1288. throwStatus(status, "dropProject transport failure: " + status.error_message());
  1289. }
  1290. if (!response.error().empty()) {
  1291. throw std::runtime_error("dropProject('" + name + "') refused: " +
  1292. response.error());
  1293. }
  1294. // dropped() may still be false here defensively — but the
  1295. // server-side contract is dropped==true iff error is empty.
  1296. }
  1297. // ===== Collection Configuration =====
  1298. bool configureCollection(const std::string& collection, const Client::CollectionConfig& cfg) {
  1299. smartbotic::databasepb::ConfigureCollectionRequest request;
  1300. request.set_collection(qualify(collection));
  1301. request.mutable_config()->set_timestamp_precision(cfg.timestampPrecision);
  1302. // v2.4.5 — only send versioning when the caller actually set it, so
  1303. // the server's partial update leaves it alone otherwise.
  1304. if (cfg.versioningEnabled.has_value()) {
  1305. request.mutable_config()->set_versioning_enabled(*cfg.versioningEnabled);
  1306. }
  1307. smartbotic::databasepb::ConfigureCollectionResponse response;
  1308. grpc::ClientContext context;
  1309. setDeadline(context);
  1310. auto status = stub_->ConfigureCollection(&context, request, &response);
  1311. if (!status.ok()) {
  1312. spdlog::error("Client::configureCollection failed: {}", status.error_message());
  1313. return false;
  1314. }
  1315. if (!response.success()) {
  1316. spdlog::error("Client::configureCollection rejected: {}", response.error());
  1317. return false;
  1318. }
  1319. return true;
  1320. }
  1321. Client::CollectionConfig getCollectionConfig(const std::string& collection) {
  1322. smartbotic::databasepb::GetCollectionConfigRequest request;
  1323. request.set_collection(qualify(collection));
  1324. smartbotic::databasepb::GetCollectionConfigResponse response;
  1325. grpc::ClientContext context;
  1326. setDeadline(context);
  1327. Client::CollectionConfig out;
  1328. auto status = stub_->GetCollectionConfig(&context, request, &response);
  1329. if (!status.ok()) {
  1330. spdlog::error("Client::getCollectionConfig failed: {}", status.error_message());
  1331. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1332. }
  1333. out.timestampPrecision = response.config().timestamp_precision();
  1334. if (out.timestampPrecision.empty()) out.timestampPrecision = "ms";
  1335. // v2.4.5 — always populated on read, so callers get the effective
  1336. // value rather than the "leave unchanged" sentinel. A server older
  1337. // than 2.4.5 omits the field; treat that as versioning on, which is
  1338. // what those builds always did.
  1339. out.versioningEnabled = response.config().has_versioning_enabled()
  1340. ? response.config().versioning_enabled()
  1341. : true;
  1342. return out;
  1343. }
  1344. bool hasCollectionConfig(const std::string& collection) {
  1345. smartbotic::databasepb::GetCollectionConfigRequest request;
  1346. request.set_collection(qualify(collection));
  1347. smartbotic::databasepb::GetCollectionConfigResponse response;
  1348. grpc::ClientContext context;
  1349. setDeadline(context);
  1350. auto status = stub_->GetCollectionConfig(&context, request, &response);
  1351. if (!status.ok()) {
  1352. spdlog::error("Client::hasCollectionConfig failed: {}", status.error_message());
  1353. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1354. }
  1355. return response.found();
  1356. }
  1357. // v2.11.0 T6b — a METHOD, not a CollectionConfig member (see the header
  1358. // doc comment for why). Sends a partial update touching ONLY
  1359. // relations_enforced: timestamp_precision is left unset (empty string,
  1360. // the server's "leave unchanged" sentinel) and versioning_enabled is
  1361. // left absent (proto3 field presence), so neither is disturbed.
  1362. bool setRelationsEnforced(const std::string& collection, bool enforced) {
  1363. smartbotic::databasepb::ConfigureCollectionRequest request;
  1364. request.set_collection(qualify(collection));
  1365. request.mutable_config()->set_relations_enforced(enforced);
  1366. smartbotic::databasepb::ConfigureCollectionResponse response;
  1367. grpc::ClientContext context;
  1368. setDeadline(context);
  1369. auto status = stub_->ConfigureCollection(&context, request, &response);
  1370. if (!status.ok()) {
  1371. spdlog::error("Client::setRelationsEnforced failed: {}", status.error_message());
  1372. return false;
  1373. }
  1374. if (!response.success()) {
  1375. spdlog::error("Client::setRelationsEnforced rejected: {}", response.error());
  1376. return false;
  1377. }
  1378. return true;
  1379. }
  1380. bool getRelationsEnforced(const std::string& collection) {
  1381. smartbotic::databasepb::GetCollectionConfigRequest request;
  1382. request.set_collection(qualify(collection));
  1383. smartbotic::databasepb::GetCollectionConfigResponse response;
  1384. grpc::ClientContext context;
  1385. setDeadline(context);
  1386. auto status = stub_->GetCollectionConfig(&context, request, &response);
  1387. if (!status.ok()) {
  1388. spdlog::error("Client::getRelationsEnforced failed: {}", status.error_message());
  1389. return true; // fail toward the safe (enforced) default
  1390. }
  1391. // Defaults to true (enforced) when never explicitly configured -
  1392. // mirrors the server's CollectionCfg default.
  1393. return !response.config().has_relations_enforced()
  1394. || response.config().relations_enforced();
  1395. }
  1396. // v2.11.4 - decides what a relations_enforced read REPORTS, given what
  1397. // the RPC returned. Split out from the transport so the policy is one
  1398. // small function with no gRPC plumbing around it.
  1399. //
  1400. // Every way of not knowing collapses to nullopt, and nothing throws:
  1401. //
  1402. // - A failed status, whatever the code. get()/find()/count() throw on
  1403. // PERMISSION_DENIED (v2.8.0) because their empty result is a VALID
  1404. // answer, so a denial returned as empty would be read as "no data".
  1405. // That hazard does not exist here: nullopt is not a setting, it is
  1406. // the absence of one, and a caller cannot mistake it for on or off.
  1407. // One failure channel is also what the name promises.
  1408. //
  1409. // - A successful reply WITHOUT the field. A 2.11.0+ server writes it
  1410. // on every GetCollectionConfig reply - the handler sets it
  1411. // unconditionally, including for a collection never configured or
  1412. // not yet created, both of which report the default (true). So an
  1413. // absent field can only be a server older than 2.11.0, which has no
  1414. // relations. `true` there would claim enforcement that does not
  1415. // exist, and `false` would offer a switch that server silently
  1416. // ignores; the honest reading is that the setting is not there.
  1417. // getRelationsEnforced() answers true for this case and is left
  1418. // alone - it is the fail-toward-enforced read by contract.
  1419. static std::optional<bool> interpretRelationsEnforcedRead(
  1420. const grpc::Status& status,
  1421. const smartbotic::databasepb::GetCollectionConfigResponse& response
  1422. ) {
  1423. if (!status.ok()) return std::nullopt;
  1424. if (!response.config().has_relations_enforced()) return std::nullopt;
  1425. return response.config().relations_enforced();
  1426. }
  1427. std::optional<bool> tryGetRelationsEnforced(const std::string& collection) {
  1428. smartbotic::databasepb::GetCollectionConfigRequest request;
  1429. request.set_collection(qualify(collection));
  1430. smartbotic::databasepb::GetCollectionConfigResponse response;
  1431. grpc::ClientContext context;
  1432. setDeadline(context);
  1433. auto status = stub_->GetCollectionConfig(&context, request, &response);
  1434. if (!status.ok()) {
  1435. spdlog::error("Client::tryGetRelationsEnforced failed: {}", status.error_message());
  1436. }
  1437. return interpretRelationsEnforcedRead(status, response);
  1438. }
  1439. Client::TimestampMigrationResult migrateCollectionTimestamps(
  1440. const std::string& collection,
  1441. const std::string& fromPrecision,
  1442. const std::string& toPrecision
  1443. ) {
  1444. smartbotic::databasepb::MigrateCollectionTimestampsRequest request;
  1445. request.set_collection(qualify(collection));
  1446. request.set_from_precision(fromPrecision);
  1447. request.set_to_precision(toPrecision);
  1448. smartbotic::databasepb::MigrateCollectionTimestampsResponse response;
  1449. grpc::ClientContext context;
  1450. // Longer deadline — can iterate many rows
  1451. auto deadline = std::chrono::system_clock::now() + std::chrono::minutes(10);
  1452. context.set_deadline(deadline);
  1453. attachAuth(context);
  1454. Client::TimestampMigrationResult out;
  1455. auto status = stub_->MigrateCollectionTimestamps(&context, request, &response);
  1456. if (!status.ok()) {
  1457. out.success = false;
  1458. out.error = status.error_message();
  1459. return out;
  1460. }
  1461. out.success = response.success();
  1462. out.error = response.error();
  1463. out.rowsMigrated = response.rows_migrated();
  1464. out.rowsSkipped = response.rows_skipped();
  1465. return out;
  1466. }
  1467. // ===== View Management =====
  1468. bool createView(const std::string& name,
  1469. const std::string& collection,
  1470. const std::vector<std::string>& include,
  1471. const std::vector<std::string>& exclude,
  1472. const std::vector<Client::Filter>& where,
  1473. const std::optional<Client::Sort>& defaultSort) {
  1474. smartbotic::databasepb::CreateViewRequest request;
  1475. // Both fields are namespaced. Qualifying `collection` but not `name`
  1476. // is what broke view lookups in v2.3: the registry keyed on the bare
  1477. // name while every read path sent the qualified one, so the keys
  1478. // could never meet.
  1479. request.set_name(qualify(name));
  1480. request.set_collection(qualify(collection));
  1481. for (const auto& p : include) request.add_include(p);
  1482. for (const auto& p : exclude) request.add_exclude(p);
  1483. for (const auto& f : where) {
  1484. auto* pb = request.add_where();
  1485. pb->set_field(f.field);
  1486. pb->set_op(static_cast<smartbotic::databasepb::FilterOp>(f.op));
  1487. pb->set_value(f.value.dump());
  1488. }
  1489. if (defaultSort) {
  1490. auto* s = request.mutable_default_sort();
  1491. s->set_field(defaultSort->field);
  1492. s->set_descending(defaultSort->descending);
  1493. }
  1494. smartbotic::databasepb::CreateViewResponse response;
  1495. grpc::ClientContext context;
  1496. setDeadline(context);
  1497. auto status = stub_->CreateView(&context, request, &response);
  1498. if (!status.ok()) {
  1499. spdlog::error("Client::createView failed: {}", status.error_message());
  1500. return false;
  1501. }
  1502. if (!response.success()) {
  1503. spdlog::error("Client::createView rejected: {}", response.error());
  1504. return false;
  1505. }
  1506. return true;
  1507. }
  1508. // v2.9.0 — secondary indexes.
  1509. bool createIndex(const std::string& collection, const std::string& field,
  1510. uint64_t* rowsIndexed) {
  1511. smartbotic::databasepb::CreateIndexRequest request;
  1512. request.set_collection(qualify(collection));
  1513. request.set_field(field);
  1514. smartbotic::databasepb::CreateIndexResponse response;
  1515. grpc::ClientContext context;
  1516. setDeadline(context);
  1517. auto status = stub_->CreateIndex(&context, request, &response);
  1518. if (!status.ok()) {
  1519. spdlog::error("Client::createIndex failed: {}", status.error_message());
  1520. return false;
  1521. }
  1522. if (!response.success()) {
  1523. spdlog::error("Client::createIndex rejected: {}", response.error());
  1524. return false;
  1525. }
  1526. if (rowsIndexed != nullptr) *rowsIndexed = response.rows_indexed();
  1527. return true;
  1528. }
  1529. bool dropIndex(const std::string& collection, const std::string& field) {
  1530. smartbotic::databasepb::DropIndexRequest request;
  1531. request.set_collection(qualify(collection));
  1532. request.set_field(field);
  1533. smartbotic::databasepb::DropIndexResponse response;
  1534. grpc::ClientContext context;
  1535. setDeadline(context);
  1536. auto status = stub_->DropIndex(&context, request, &response);
  1537. if (!status.ok()) {
  1538. spdlog::error("Client::dropIndex failed: {}", status.error_message());
  1539. return false;
  1540. }
  1541. return response.success();
  1542. }
  1543. // v2.11.0 T11 — unique constraints.
  1544. Client::CreateIndexResult createUniqueIndex(const std::string& collection,
  1545. const std::string& field) {
  1546. smartbotic::databasepb::CreateIndexRequest request;
  1547. request.set_collection(qualify(collection));
  1548. request.set_field(field);
  1549. request.set_unique(true);
  1550. smartbotic::databasepb::CreateIndexResponse response;
  1551. grpc::ClientContext context;
  1552. setDeadline(context);
  1553. Client::CreateIndexResult out;
  1554. auto status = stub_->CreateIndex(&context, request, &response);
  1555. if (!status.ok()) {
  1556. out.error = status.error_message();
  1557. spdlog::error("Client::createUniqueIndex failed: {}", out.error);
  1558. return out;
  1559. }
  1560. out.success = response.success();
  1561. out.error = response.error();
  1562. out.rowsIndexed = response.rows_indexed();
  1563. out.alreadyExisted = response.already_existed();
  1564. out.duplicateExamples.assign(response.duplicate_examples().begin(),
  1565. response.duplicate_examples().end());
  1566. if (!out.success) {
  1567. spdlog::error("Client::createUniqueIndex rejected: {}", out.error);
  1568. }
  1569. return out;
  1570. }
  1571. // ===== Collection schema (v2.16.0) =====
  1572. Client::SchemaChangeResult schemaChange(const std::string& collection, const std::string& schemaJson,
  1573. Client::SchemaMode mode) {
  1574. Client::SchemaChangeResult out;
  1575. try {
  1576. requireCapability(Client::Capability::kCollectionSchema, "setCollectionSchema");
  1577. } catch (const Client::Error& e) {
  1578. out.error = e.what();
  1579. if (const auto* d = Client::errorDetail(e)) out.reason = d->reason;
  1580. return out;
  1581. }
  1582. smartbotic::databasepb::SetCollectionSchemaRequest request;
  1583. request.set_collection(qualify(collection));
  1584. request.set_schema_json(schemaJson);
  1585. request.set_mode(mode == Client::SchemaMode::Audit ? "audit" : "enforce");
  1586. smartbotic::databasepb::SetCollectionSchemaResponse response;
  1587. grpc::ClientContext context;
  1588. // The existing-row check scans the collection: give it the export cap,
  1589. // not a unary deadline.
  1590. context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
  1591. attachAuth(context);
  1592. auto status = stub_->SetCollectionSchema(&context, request, &response);
  1593. if (!status.ok()) {
  1594. const auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(),
  1595. trailerDetail(context));
  1596. out.error = status.error_message();
  1597. out.reason = d.reason;
  1598. spdlog::error("Client::setCollectionSchema failed: {}", out.error);
  1599. return out;
  1600. }
  1601. out.success = response.success();
  1602. out.error = response.error();
  1603. out.rowsChecked = response.rows_checked();
  1604. out.violatingRows = response.violating_rows();
  1605. for (const auto& ex : response.examples()) {
  1606. out.examples.push_back({ex.id(), ex.message(), {ex.fields().begin(), ex.fields().end()}});
  1607. }
  1608. if (!out.success) spdlog::error("Client::setCollectionSchema refused: {}", out.error);
  1609. return out;
  1610. }
  1611. std::optional<Client::CollectionSchema> getCollectionSchema(const std::string& collection) {
  1612. requireCapability(Client::Capability::kCollectionSchema, "getCollectionSchema");
  1613. smartbotic::databasepb::GetCollectionSchemaRequest request;
  1614. request.set_collection(qualify(collection));
  1615. smartbotic::databasepb::GetCollectionSchemaResponse response;
  1616. grpc::ClientContext context;
  1617. setDeadline(context);
  1618. auto status = stub_->GetCollectionSchema(&context, request, &response);
  1619. if (!status.ok()) {
  1620. throwStatus(status, "getCollectionSchema: " + status.error_message(), trailerDetail(context));
  1621. }
  1622. if (!response.has_schema()) return std::nullopt;
  1623. Client::CollectionSchema out;
  1624. out.schema = nlohmann::json::parse(response.schema_json());
  1625. out.mode = response.mode() == "audit" ? Client::SchemaMode::Audit : Client::SchemaMode::Enforce;
  1626. out.auditViolations = response.audit_violations();
  1627. out.refusals = response.refusals();
  1628. out.armed = response.armed();
  1629. return out;
  1630. }
  1631. Client::SchemaSuggestion suggestCollectionSchema(const std::string& collection, uint64_t sampleLimit) {
  1632. requireCapability(Client::Capability::kCollectionSchema, "suggestCollectionSchema");
  1633. smartbotic::databasepb::SuggestCollectionSchemaRequest request;
  1634. request.set_collection(qualify(collection));
  1635. request.set_sample_limit(sampleLimit);
  1636. smartbotic::databasepb::SuggestCollectionSchemaResponse response;
  1637. grpc::ClientContext context;
  1638. context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
  1639. attachAuth(context);
  1640. auto status = stub_->SuggestCollectionSchema(&context, request, &response);
  1641. if (!status.ok()) {
  1642. throwStatus(status, "suggestCollectionSchema: " + status.error_message(), trailerDetail(context));
  1643. }
  1644. Client::SchemaSuggestion out;
  1645. out.schema = nlohmann::json::parse(response.schema_json());
  1646. out.rowsScanned = response.rows_scanned();
  1647. out.complete = response.complete();
  1648. return out;
  1649. }
  1650. std::vector<Client::IndexDefinition> listIndexes(const std::string& collection,
  1651. std::vector<bool>* uniqueFlags) {
  1652. smartbotic::databasepb::ListIndexesRequest request;
  1653. request.set_collection(qualify(collection));
  1654. smartbotic::databasepb::ListIndexesResponse response;
  1655. grpc::ClientContext context;
  1656. setDeadline(context);
  1657. std::vector<Client::IndexDefinition> out;
  1658. auto status = stub_->ListIndexes(&context, request, &response);
  1659. if (!status.ok()) {
  1660. spdlog::error("Client::listIndexes failed: {}", status.error_message());
  1661. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1662. }
  1663. out.reserve(response.indexes_size());
  1664. if (uniqueFlags != nullptr) {
  1665. uniqueFlags->clear();
  1666. uniqueFlags->reserve(response.indexes_size());
  1667. }
  1668. for (const auto& i : response.indexes()) {
  1669. // v2.12.0 - a composite unique constraint is not an index on a
  1670. // field; its `field` is only a display form ("a+b"). Reported by
  1671. // listCompositeUniqueIndexes() instead, so nothing here can be
  1672. // mistaken for a real field.
  1673. if (i.fields_size() > 0) continue;
  1674. Client::IndexDefinition d;
  1675. d.field = i.field();
  1676. d.distinctValues = i.distinct_values();
  1677. d.entries = i.entries();
  1678. out.push_back(std::move(d));
  1679. if (uniqueFlags != nullptr) uniqueFlags->push_back(i.unique());
  1680. }
  1681. return out;
  1682. }
  1683. // v2.12.0 - composite unique constraints.
  1684. Client::CreateIndexResult createCompositeUniqueIndex(const std::string& collection,
  1685. const std::vector<std::string>& fields) {
  1686. smartbotic::databasepb::CreateIndexRequest request;
  1687. request.set_collection(qualify(collection));
  1688. for (const auto& f : fields) request.add_fields(f);
  1689. request.set_unique(true);
  1690. smartbotic::databasepb::CreateIndexResponse response;
  1691. grpc::ClientContext context;
  1692. setDeadline(context);
  1693. Client::CreateIndexResult out;
  1694. auto status = stub_->CreateIndex(&context, request, &response);
  1695. if (!status.ok()) {
  1696. out.error = status.error_message();
  1697. spdlog::error("Client::createCompositeUniqueIndex failed: {}", out.error);
  1698. return out;
  1699. }
  1700. out.success = response.success();
  1701. out.error = response.error();
  1702. out.rowsIndexed = response.rows_indexed();
  1703. out.alreadyExisted = response.already_existed();
  1704. out.duplicateExamples.assign(response.duplicate_examples().begin(),
  1705. response.duplicate_examples().end());
  1706. if (!out.success) {
  1707. spdlog::error("Client::createCompositeUniqueIndex rejected: {}", out.error);
  1708. }
  1709. return out;
  1710. }
  1711. bool dropCompositeUniqueIndex(const std::string& collection,
  1712. const std::vector<std::string>& fields) {
  1713. smartbotic::databasepb::DropIndexRequest request;
  1714. request.set_collection(qualify(collection));
  1715. for (const auto& f : fields) request.add_fields(f);
  1716. smartbotic::databasepb::DropIndexResponse response;
  1717. grpc::ClientContext context;
  1718. setDeadline(context);
  1719. auto status = stub_->DropIndex(&context, request, &response);
  1720. if (!status.ok()) {
  1721. spdlog::error("Client::dropCompositeUniqueIndex failed: {}", status.error_message());
  1722. return false;
  1723. }
  1724. if (!response.success()) {
  1725. spdlog::error("Client::dropCompositeUniqueIndex rejected: {}", response.error());
  1726. }
  1727. return response.success();
  1728. }
  1729. std::vector<std::vector<std::string>> listCompositeUniqueIndexes(const std::string& collection) {
  1730. smartbotic::databasepb::ListIndexesRequest request;
  1731. request.set_collection(qualify(collection));
  1732. smartbotic::databasepb::ListIndexesResponse response;
  1733. grpc::ClientContext context;
  1734. setDeadline(context);
  1735. std::vector<std::vector<std::string>> out;
  1736. auto status = stub_->ListIndexes(&context, request, &response);
  1737. if (!status.ok()) {
  1738. spdlog::error("Client::listCompositeUniqueIndexes failed: {}", status.error_message());
  1739. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1740. }
  1741. for (const auto& i : response.indexes()) {
  1742. if (i.fields_size() > 0) out.emplace_back(i.fields().begin(), i.fields().end());
  1743. }
  1744. return out;
  1745. }
  1746. std::vector<Client::IndexValue> indexValues(const std::string& collection,
  1747. const std::string& field,
  1748. uint32_t limit, bool ascending) {
  1749. smartbotic::databasepb::GetIndexValuesRequest request;
  1750. request.set_collection(qualify(collection));
  1751. request.set_field(field);
  1752. request.set_limit(limit);
  1753. request.set_ascending(ascending);
  1754. smartbotic::databasepb::GetIndexValuesResponse response;
  1755. grpc::ClientContext context;
  1756. setDeadline(context);
  1757. std::vector<Client::IndexValue> out;
  1758. auto status = stub_->GetIndexValues(&context, request, &response);
  1759. if (!status.ok()) {
  1760. spdlog::error("Client::indexValues failed: {}", status.error_message());
  1761. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1762. }
  1763. out.reserve(response.values_size());
  1764. for (const auto& v : response.values()) {
  1765. Client::IndexValue iv;
  1766. try {
  1767. iv.value = nlohmann::json::parse(v.value());
  1768. } catch (const nlohmann::json::exception&) {
  1769. continue;
  1770. }
  1771. iv.count = v.count();
  1772. out.push_back(std::move(iv));
  1773. }
  1774. return out;
  1775. }
  1776. bool dropView(const std::string& name) {
  1777. smartbotic::databasepb::DropViewRequest request;
  1778. request.set_name(qualify(name));
  1779. smartbotic::databasepb::DropViewResponse response;
  1780. grpc::ClientContext context;
  1781. setDeadline(context);
  1782. auto status = stub_->DropView(&context, request, &response);
  1783. if (!status.ok()) {
  1784. spdlog::error("Client::dropView failed: {}", status.error_message());
  1785. return false;
  1786. }
  1787. return response.success();
  1788. }
  1789. std::vector<Client::ViewDefinition> listViews() {
  1790. smartbotic::databasepb::ListViewsRequest request;
  1791. // Scope the listing to this client's workspace.
  1792. request.set_project(config_.project);
  1793. smartbotic::databasepb::ListViewsResponse response;
  1794. grpc::ClientContext context;
  1795. setDeadline(context);
  1796. std::vector<Client::ViewDefinition> out;
  1797. auto status = stub_->ListViews(&context, request, &response);
  1798. if (!status.ok()) {
  1799. spdlog::error("Client::listViews failed: {}", status.error_message());
  1800. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1801. }
  1802. for (const auto& pb : response.views()) {
  1803. Client::ViewDefinition v;
  1804. // Round-trip: the caller created "adults", so list it as "adults".
  1805. v.name = unqualify(pb.name());
  1806. v.collection = unqualify(pb.collection());
  1807. for (const auto& p : pb.include()) v.include.push_back(p);
  1808. for (const auto& p : pb.exclude()) v.exclude.push_back(p);
  1809. for (const auto& pbf : pb.where()) {
  1810. Client::Filter f;
  1811. f.field = pbf.field();
  1812. f.op = static_cast<Client::FilterOp>(pbf.op());
  1813. try { f.value = nlohmann::json::parse(pbf.value()); }
  1814. catch (...) { f.value = pbf.value(); }
  1815. v.where.push_back(f);
  1816. }
  1817. if (pb.has_default_sort()) {
  1818. Client::Sort s;
  1819. s.field = pb.default_sort().field();
  1820. s.descending = pb.default_sort().descending();
  1821. v.defaultSort = s;
  1822. }
  1823. v.createdAt = pb.created_at();
  1824. v.updatedAt = pb.updated_at();
  1825. out.push_back(std::move(v));
  1826. }
  1827. return out;
  1828. }
  1829. std::optional<Client::ViewDefinition> getViewInfo(const std::string& name) {
  1830. smartbotic::databasepb::GetViewInfoRequest request;
  1831. request.set_name(qualify(name));
  1832. smartbotic::databasepb::GetViewInfoResponse response;
  1833. grpc::ClientContext context;
  1834. setDeadline(context);
  1835. auto status = stub_->GetViewInfo(&context, request, &response);
  1836. if (!status.ok()) {
  1837. spdlog::error("Client::getViewInfo failed: {}", status.error_message());
  1838. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1839. }
  1840. if (!response.found()) {
  1841. return std::nullopt;
  1842. }
  1843. Client::ViewDefinition v;
  1844. v.name = unqualify(response.view().name());
  1845. v.collection = unqualify(response.view().collection());
  1846. for (const auto& p : response.view().include()) v.include.push_back(p);
  1847. for (const auto& p : response.view().exclude()) v.exclude.push_back(p);
  1848. for (const auto& pbf : response.view().where()) {
  1849. Client::Filter f;
  1850. f.field = pbf.field();
  1851. f.op = static_cast<Client::FilterOp>(pbf.op());
  1852. try { f.value = nlohmann::json::parse(pbf.value()); }
  1853. catch (...) { f.value = pbf.value(); }
  1854. v.where.push_back(f);
  1855. }
  1856. if (response.view().has_default_sort()) {
  1857. Client::Sort s;
  1858. s.field = response.view().default_sort().field();
  1859. s.descending = response.view().default_sort().descending();
  1860. v.defaultSort = s;
  1861. }
  1862. v.createdAt = response.view().created_at();
  1863. v.updatedAt = response.view().updated_at();
  1864. return v;
  1865. }
  1866. // ===== v2.11.0 T6b — relation (referential integrity) management =====
  1867. Client::RelationDefinition relationFromProto(
  1868. const smartbotic::databasepb::RelationDefinition& pb) const {
  1869. Client::RelationDefinition r;
  1870. // Round-trip like listViews(): the caller declared "posts_by_user",
  1871. // it should list back as "posts_by_user", not "myproject:posts_by_user".
  1872. r.name = unqualify(pb.name());
  1873. r.child = unqualify(pb.child());
  1874. r.childField = pb.child_field();
  1875. r.parent = unqualify(pb.parent());
  1876. r.onDelete = pb.on_delete().empty() ? "restrict" : pb.on_delete();
  1877. r.validateOnWrite = pb.validate_on_write();
  1878. r.createdAt = pb.created_at();
  1879. r.updatedAt = pb.updated_at();
  1880. return r;
  1881. }
  1882. bool createRelation(const std::string& name, const std::string& childCollection,
  1883. const std::string& childField, const std::string& parentCollection,
  1884. const std::string& onDelete, bool validateOnWrite,
  1885. uint64_t* rowsIndexed) {
  1886. smartbotic::databasepb::CreateRelationRequest request;
  1887. // name, child AND parent all need qualifying - qualifying only
  1888. // `child`/`parent` but not `name` is exactly the v2.4.2 createView
  1889. // bug (registry keyed on the bare name, every lookup sent the
  1890. // qualified one, the keys never met).
  1891. request.set_name(qualify(name));
  1892. request.set_child(qualify(childCollection));
  1893. request.set_child_field(childField);
  1894. request.set_parent(qualify(parentCollection));
  1895. request.set_on_delete(onDelete);
  1896. request.set_validate_on_write(validateOnWrite);
  1897. smartbotic::databasepb::CreateRelationResponse response;
  1898. grpc::ClientContext context;
  1899. setDeadline(context);
  1900. auto status = stub_->CreateRelation(&context, request, &response);
  1901. if (!status.ok()) {
  1902. spdlog::error("Client::createRelation failed: {}", status.error_message());
  1903. return false;
  1904. }
  1905. if (!response.success()) {
  1906. spdlog::error("Client::createRelation rejected: {}", response.error());
  1907. return false;
  1908. }
  1909. // v2.11.0 T7 - the server's bootstrap scan already backfilled the
  1910. // reverse index over any rows present in childCollection.
  1911. if (rowsIndexed != nullptr) *rowsIndexed = response.rows_indexed();
  1912. return true;
  1913. }
  1914. bool dropRelation(const std::string& name) {
  1915. smartbotic::databasepb::DropRelationRequest request;
  1916. request.set_name(qualify(name));
  1917. smartbotic::databasepb::DropRelationResponse response;
  1918. grpc::ClientContext context;
  1919. setDeadline(context);
  1920. auto status = stub_->DropRelation(&context, request, &response);
  1921. if (!status.ok()) {
  1922. spdlog::error("Client::dropRelation failed: {}", status.error_message());
  1923. return false;
  1924. }
  1925. if (!response.success()) {
  1926. spdlog::error("Client::dropRelation rejected: {}", response.error());
  1927. return false;
  1928. }
  1929. return true;
  1930. }
  1931. std::vector<Client::RelationDefinition> listRelations() {
  1932. // Scope the listing to this client's workspace, like listViews().
  1933. return listRelationsIn(config_.project);
  1934. }
  1935. // v2.11.1 — empty `project` means every project, which is what the wire
  1936. // contract has always said and what an operator tool needs.
  1937. std::vector<Client::RelationDefinition> listRelationsIn(const std::string& project) {
  1938. smartbotic::databasepb::ListRelationsRequest request;
  1939. request.set_project(project);
  1940. smartbotic::databasepb::ListRelationsResponse response;
  1941. grpc::ClientContext context;
  1942. setDeadline(context);
  1943. std::vector<Client::RelationDefinition> out;
  1944. auto status = stub_->ListRelations(&context, request, &response);
  1945. if (!status.ok()) {
  1946. spdlog::error("Client::listRelations failed: {}", status.error_message());
  1947. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1948. }
  1949. out.reserve(response.relations_size());
  1950. for (const auto& pb : response.relations()) {
  1951. out.push_back(relationFromProto(pb));
  1952. }
  1953. return out;
  1954. }
  1955. std::optional<Client::RelationDefinition> getRelationInfo(const std::string& name) {
  1956. smartbotic::databasepb::GetRelationInfoRequest request;
  1957. request.set_name(qualify(name));
  1958. smartbotic::databasepb::GetRelationInfoResponse response;
  1959. grpc::ClientContext context;
  1960. setDeadline(context);
  1961. auto status = stub_->GetRelationInfo(&context, request, &response);
  1962. if (!status.ok()) {
  1963. spdlog::error("Client::getRelationInfo failed: {}", status.error_message());
  1964. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  1965. }
  1966. if (!response.found()) {
  1967. return std::nullopt;
  1968. }
  1969. return relationFromProto(response.relation());
  1970. }
  1971. // v2.11.0 T5 — "what would happen if I deleted this?" Gated as an
  1972. // ordinary read server-side, so `collection` is qualified the same way
  1973. // get()/find() qualify theirs - not the admin-only qualify() used by
  1974. // the relation-management calls above (which is the same call, just a
  1975. // reminder this one follows the read family, not the admin family).
  1976. Client::DescribeDeleteResult describeDelete(const std::string& collection,
  1977. const std::string& id) {
  1978. smartbotic::databasepb::DescribeDeleteRequest request;
  1979. request.set_collection(qualify(collection));
  1980. request.set_id(id);
  1981. smartbotic::databasepb::DescribeDeleteResponse response;
  1982. grpc::ClientContext context;
  1983. setDeadline(context);
  1984. Client::DescribeDeleteResult out;
  1985. auto status = stub_->DescribeDelete(&context, request, &response);
  1986. if (!status.ok()) {
  1987. spdlog::error("Client::describeDelete failed: {}", status.error_message());
  1988. out.success = false;
  1989. out.error = status.error_message();
  1990. return out;
  1991. }
  1992. out.success = response.success();
  1993. out.error = response.error();
  1994. out.wouldBeBlocked = response.would_be_blocked();
  1995. out.impacts.reserve(response.impacts_size());
  1996. for (const auto& pbImpact : response.impacts()) {
  1997. Client::RelationImpact impact;
  1998. impact.relation = unqualify(pbImpact.relation());
  1999. impact.childCollection = unqualify(pbImpact.child_collection());
  2000. impact.childField = pbImpact.child_field();
  2001. impact.onDelete = pbImpact.on_delete();
  2002. impact.childCount = pbImpact.child_count();
  2003. impact.sampleChildIds.assign(pbImpact.sample_child_ids().begin(),
  2004. pbImpact.sample_child_ids().end());
  2005. impact.blocks = pbImpact.blocks();
  2006. out.impacts.push_back(std::move(impact));
  2007. }
  2008. return out;
  2009. }
  2010. // v2.11.0 T7 - "does this relation's reverse index actually match live
  2011. // data?" Read-only; qualified like the other relation-management calls
  2012. // (getRelationInfo etc.), since a relation name is admin-scoped the same
  2013. // way regardless of which call reads it.
  2014. Client::CheckRelationResult checkRelation(const std::string& name) {
  2015. smartbotic::databasepb::CheckRelationRequest request;
  2016. request.set_name(qualify(name));
  2017. smartbotic::databasepb::CheckRelationResponse response;
  2018. grpc::ClientContext context;
  2019. setDeadline(context);
  2020. Client::CheckRelationResult out;
  2021. auto status = stub_->CheckRelation(&context, request, &response);
  2022. if (!status.ok()) {
  2023. spdlog::error("Client::checkRelation failed: {}", status.error_message());
  2024. out.success = false;
  2025. out.error = status.error_message();
  2026. return out;
  2027. }
  2028. out.success = response.success();
  2029. out.error = response.error();
  2030. out.totalDangling = response.total_dangling();
  2031. out.dangling.reserve(response.dangling_size());
  2032. for (const auto& pbd : response.dangling()) {
  2033. Client::DanglingReference d;
  2034. d.parentId = pbd.parent_id();
  2035. d.childCount = pbd.child_count();
  2036. d.sampleChildIds.assign(pbd.sample_child_ids().begin(), pbd.sample_child_ids().end());
  2037. out.dangling.push_back(std::move(d));
  2038. }
  2039. return out;
  2040. }
  2041. // ===== Event Subscription =====
  2042. class SubscriptionHandle {
  2043. public:
  2044. SubscriptionHandle(std::shared_ptr<grpc::ClientContext> ctx,
  2045. std::unique_ptr<grpc::ClientReader<smartbotic::databasepb::DatabaseEvent>> reader,
  2046. std::thread readerThread)
  2047. : context_(std::move(ctx))
  2048. , reader_(std::move(reader))
  2049. , readerThread_(std::move(readerThread))
  2050. , active_(true) {}
  2051. ~SubscriptionHandle() {
  2052. cancel();
  2053. }
  2054. void cancel() {
  2055. if (active_.exchange(false)) {
  2056. context_->TryCancel();
  2057. if (readerThread_.joinable()) {
  2058. readerThread_.join();
  2059. }
  2060. }
  2061. }
  2062. private:
  2063. std::shared_ptr<grpc::ClientContext> context_;
  2064. std::unique_ptr<grpc::ClientReader<smartbotic::databasepb::DatabaseEvent>> reader_;
  2065. std::thread readerThread_;
  2066. std::atomic<bool> active_;
  2067. };
  2068. // v2.12.0 - the original callback shape, delivered from the one reader
  2069. // loop below so both subscription forms decode events identically.
  2070. std::shared_ptr<void> subscribe(const std::vector<std::string>& collections,
  2071. Client::EventCallback callback) {
  2072. return subscribeEvents(collections, [callback = std::move(callback)](const Client::Event& e) {
  2073. callback(e.collection, e.id, e.eventType, e.data);
  2074. });
  2075. }
  2076. std::shared_ptr<void> subscribeEvents(const std::vector<std::string>& collections,
  2077. Client::EventHandler handler) {
  2078. auto context = std::make_shared<grpc::ClientContext>();
  2079. // Subscribe is a long-running stream — no deadline — but the auth
  2080. // metadata still has to land on the initial request headers.
  2081. attachAuth(*context);
  2082. smartbotic::databasepb::SubscribeRequest request;
  2083. // v2.8.0 — subscribe was the one call left unqualified while every
  2084. // document call qualified. Two consequences, both cross-project leaks:
  2085. //
  2086. // * a bare name matched nothing, because events carry the qualified
  2087. // collection - so subscriptions silently never fired;
  2088. // * an EMPTY list means "every collection" server-side, which meant
  2089. // every collection in every PROJECT.
  2090. //
  2091. // Named collections are qualified like any other. For the "everything"
  2092. // case we send a `<project>:*` pattern instead of an empty request, so
  2093. // "all" means all of MY project. That needs no proto change - the
  2094. // pattern field already existed.
  2095. for (const auto& coll : collections) {
  2096. request.add_collections(qualify(coll));
  2097. }
  2098. if (collections.empty()) {
  2099. request.add_patterns(config_.project + ":*");
  2100. }
  2101. request.set_include_data(true);
  2102. auto reader = stub_->Subscribe(context.get(), request);
  2103. // Create reader thread
  2104. auto readerThread = std::thread([reader = reader.get(), handler = std::move(handler)]() {
  2105. smartbotic::databasepb::DatabaseEvent event;
  2106. while (reader->Read(&event)) {
  2107. // v2.13.0 - nothing may escape this thread: an exception leaving a
  2108. // std::thread calls std::terminate, so one throwing handler (or one
  2109. // event body that does not parse) used to take the whole consumer
  2110. // process down. The event is logged and dropped; the stream goes on.
  2111. try {
  2112. std::optional<nlohmann::json> data;
  2113. if (!event.data().empty()) {
  2114. data = nlohmann::json::parse(event.data());
  2115. }
  2116. // Convert proto event type to string
  2117. std::string eventType;
  2118. switch (event.type()) {
  2119. case smartbotic::databasepb::EVENT_INSERT: eventType = "insert"; break;
  2120. case smartbotic::databasepb::EVENT_UPDATE: eventType = "update"; break;
  2121. case smartbotic::databasepb::EVENT_DELETE: eventType = "delete"; break;
  2122. case smartbotic::databasepb::EVENT_EXPIRE: eventType = "expire"; break;
  2123. case smartbotic::databasepb::EVENT_INVALIDATE: eventType = "invalidate"; break;
  2124. default: eventType = "unknown"; break;
  2125. }
  2126. Client::Event out;
  2127. out.collection = event.collection();
  2128. out.id = event.document_id();
  2129. out.eventType = std::move(eventType);
  2130. out.data = std::move(data);
  2131. out.actor = event.actor();
  2132. out.timestamp = event.timestamp();
  2133. out.nodeId = event.node_id();
  2134. handler(out);
  2135. } catch (const std::exception& e) {
  2136. spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
  2137. "or its parse threw: {}", event.collection(),
  2138. event.document_id(), e.what());
  2139. } catch (...) {
  2140. spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
  2141. "threw a non-std exception", event.collection(),
  2142. event.document_id());
  2143. }
  2144. }
  2145. });
  2146. return std::make_shared<SubscriptionHandle>(
  2147. std::move(context),
  2148. std::move(reader),
  2149. std::move(readerThread)
  2150. );
  2151. }
  2152. // ===== Export (v2.13.0) =====
  2153. //
  2154. // The server's contract is in the proto, above ExportRequest. What this
  2155. // side adds: a stream that ends without its trailer THROWS (it is not a
  2156. // complete export, whatever it delivered); an unrecognised vector dtype
  2157. // THROWS rather than being reinterpreted; and a handler returning false
  2158. // stops the export AFTER that row, which therefore counts as delivered
  2159. // (lastId names it, so a resume starts after it).
  2160. Client::ExportSummary exportCollection(
  2161. const std::string& collection, bool includeVectors, const std::string& afterId,
  2162. const std::function<void(const Client::ExportHeader&)>& onHeader,
  2163. const std::function<bool(Client::ExportRow&&)>& onRow,
  2164. uint32_t batchRows) {
  2165. smartbotic::databasepb::ExportRequest request;
  2166. request.set_collection(qualify(collection));
  2167. request.set_include_vectors(includeVectors);
  2168. request.set_after_id(afterId);
  2169. request.set_batch_rows(batchRows);
  2170. // Not the per-call timeout: an export is long by design. The server
  2171. // ends a stream at its own cap (header.max_stream_seconds, 600) with a
  2172. // resume cursor; this deadline is only the backstop for a server that
  2173. // stops answering.
  2174. grpc::ClientContext context;
  2175. context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(900));
  2176. attachAuth(context);
  2177. auto reader = stub_->ExportCollection(&context, request);
  2178. auto abandon = [&]() {
  2179. context.TryCancel();
  2180. smartbotic::databasepb::ExportChunk drain;
  2181. while (reader->Read(&drain)) {}
  2182. (void)reader->Finish();
  2183. };
  2184. Client::ExportSummary summary;
  2185. bool sawHeader = false;
  2186. bool sawTrailer = false;
  2187. smartbotic::databasepb::ExportTrailer trailer;
  2188. smartbotic::databasepb::ExportChunk chunk;
  2189. while (reader->Read(&chunk)) {
  2190. if (chunk.has_header()) {
  2191. const auto& h = chunk.header();
  2192. if (h.vector_dtype() != "float32-le") {
  2193. abandon();
  2194. const std::string msg = "export: unrecognised vector dtype '" +
  2195. h.vector_dtype() + "'; refusing to reinterpret the bytes";
  2196. throw DetailedError(Client::ErrorCode::Unimplemented, msg,
  2197. makeDetail(Client::ErrorCode::Unimplemented, msg, {}));
  2198. }
  2199. sawHeader = true;
  2200. Client::ExportHeader out;
  2201. out.collection = unqualify(h.collection());
  2202. out.vectorDimension = h.vector_dimension();
  2203. out.vectorDtype = h.vector_dtype();
  2204. out.rowsAtSnapshot = h.rows_at_snapshot();
  2205. out.batchRowsCap = h.batch_rows_cap();
  2206. out.maxStreamSeconds = h.max_stream_seconds();
  2207. if (onHeader) {
  2208. try { onHeader(out); } catch (...) { abandon(); throw; }
  2209. }
  2210. } else if (chunk.has_rows()) {
  2211. for (auto& r : *chunk.mutable_rows()->mutable_rows()) {
  2212. Client::ExportRow row;
  2213. row.id = r.document().id();
  2214. row.vectorState = static_cast<Client::VectorState>(r.vector_state());
  2215. const std::string& bytes = r.document().vector();
  2216. if (!bytes.empty()) {
  2217. if (bytes.size() % sizeof(float) != 0) {
  2218. abandon();
  2219. const std::string msg = "export: vector of '" + row.id +
  2220. "' is not a whole number of float32 values";
  2221. throw DetailedError(Client::ErrorCode::DataLoss, msg,
  2222. makeDetail(Client::ErrorCode::DataLoss, msg, {}));
  2223. }
  2224. row.vector.resize(bytes.size() / sizeof(float));
  2225. std::memcpy(row.vector.data(), bytes.data(), bytes.size());
  2226. r.mutable_document()->clear_vector(); // the vector is row.vector, not "_vector"
  2227. }
  2228. row.document = documentToJson(r.document());
  2229. std::string id = row.id;
  2230. bool more = true;
  2231. try { more = onRow(std::move(row)); } catch (...) { abandon(); throw; }
  2232. ++summary.rowsSent;
  2233. summary.lastId = std::move(id);
  2234. if (!more) {
  2235. abandon();
  2236. summary.complete = false;
  2237. return summary;
  2238. }
  2239. }
  2240. } else if (chunk.has_trailer()) {
  2241. sawTrailer = true;
  2242. trailer = chunk.trailer();
  2243. }
  2244. }
  2245. auto status = reader->Finish();
  2246. if (!status.ok()) {
  2247. spdlog::error("Client::exportCollection failed: {}", status.error_message());
  2248. throwStatus(status, status.error_message(), trailerDetail(context));
  2249. }
  2250. if (!sawHeader || !sawTrailer) {
  2251. const std::string msg = "export of '" + collection + "' ended without its trailer "
  2252. "after " + std::to_string(summary.rowsSent) +
  2253. " rows; it did not complete";
  2254. throw DetailedError(Client::ErrorCode::Unavailable, msg,
  2255. makeDetail(Client::ErrorCode::Unavailable, msg, {}));
  2256. }
  2257. if (trailer.rows_sent() != summary.rowsSent) {
  2258. const std::string msg = "export of '" + collection + "': server reports " +
  2259. std::to_string(trailer.rows_sent()) + " rows sent, " +
  2260. std::to_string(summary.rowsSent) + " arrived";
  2261. throw DetailedError(Client::ErrorCode::DataLoss, msg,
  2262. makeDetail(Client::ErrorCode::DataLoss, msg, {}));
  2263. }
  2264. summary.complete = trailer.complete();
  2265. return summary;
  2266. }
  2267. // ===== Version History =====
  2268. Client::VersionHistoryResult getVersionHistory(const std::string& collection,
  2269. const std::string& id, uint32_t limit, uint32_t offset) {
  2270. smartbotic::databasepb::GetVersionHistoryRequest request;
  2271. request.set_collection(qualify(collection));
  2272. request.set_id(id);
  2273. if (limit > 0) request.set_limit(limit);
  2274. if (offset > 0) request.set_offset(offset);
  2275. smartbotic::databasepb::GetVersionHistoryResponse response;
  2276. grpc::ClientContext context;
  2277. setDeadline(context);
  2278. auto status = stub_->GetVersionHistory(&context, request, &response);
  2279. if (!status.ok()) {
  2280. spdlog::error("Client::getVersionHistory failed: {}", status.error_message());
  2281. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  2282. }
  2283. Client::VersionHistoryResult result;
  2284. result.currentVersion = response.current_version();
  2285. result.totalCount = response.total_count();
  2286. result.documentDeleted = response.document_deleted();
  2287. result.versions.reserve(response.versions_size());
  2288. for (const auto& ver : response.versions()) {
  2289. Client::VersionEntry entry;
  2290. entry.version = ver.version();
  2291. entry.timestamp = ver.timestamp();
  2292. entry.updatedBy = ver.updated_by();
  2293. if (!ver.data().empty()) {
  2294. entry.data = nlohmann::json::parse(ver.data());
  2295. }
  2296. result.versions.push_back(std::move(entry));
  2297. }
  2298. return result;
  2299. }
  2300. std::optional<Client::VersionEntry> getDocumentVersion(const std::string& collection,
  2301. const std::string& id, uint64_t version) {
  2302. smartbotic::databasepb::GetDocumentVersionRequest request;
  2303. request.set_collection(qualify(collection));
  2304. request.set_id(id);
  2305. request.set_version(version);
  2306. smartbotic::databasepb::GetDocumentVersionResponse response;
  2307. grpc::ClientContext context;
  2308. setDeadline(context);
  2309. auto status = stub_->GetDocumentVersion(&context, request, &response);
  2310. if (!status.ok()) {
  2311. spdlog::error("Client::getDocumentVersion failed: {}", status.error_message());
  2312. throwStatus(status, status.error_message()); // v2.12.4: never empty on failure
  2313. }
  2314. if (!response.found()) {
  2315. return std::nullopt;
  2316. }
  2317. Client::VersionEntry entry;
  2318. entry.version = response.version_entry().version();
  2319. entry.timestamp = response.version_entry().timestamp();
  2320. entry.updatedBy = response.version_entry().updated_by();
  2321. if (!response.version_entry().data().empty()) {
  2322. entry.data = nlohmann::json::parse(response.version_entry().data());
  2323. }
  2324. return entry;
  2325. }
  2326. uint64_t restoreVersion(const std::string& collection, const std::string& id,
  2327. uint64_t version, const std::string& actor) {
  2328. smartbotic::databasepb::RestoreVersionRequest request;
  2329. request.set_collection(qualify(collection));
  2330. request.set_id(id);
  2331. request.set_version(version);
  2332. if (!actor.empty()) request.set_actor(actor);
  2333. smartbotic::databasepb::RestoreVersionResponse response;
  2334. grpc::ClientContext context;
  2335. setDeadline(context);
  2336. auto status = stub_->RestoreVersion(&context, request, &response);
  2337. if (!status.ok()) {
  2338. spdlog::error("Client::restoreVersion failed: {}", status.error_message());
  2339. return 0;
  2340. }
  2341. if (!response.success()) {
  2342. spdlog::error("Client::restoreVersion: {}", response.error());
  2343. return 0;
  2344. }
  2345. return response.new_version();
  2346. }
  2347. std::pair<uint64_t, uint64_t> restoreToDate(const std::string& collection,
  2348. const std::string& id, uint64_t timestamp, const std::string& actor) {
  2349. smartbotic::databasepb::RestoreToDateRequest request;
  2350. request.set_collection(qualify(collection));
  2351. request.set_id(id);
  2352. request.set_timestamp(timestamp);
  2353. if (!actor.empty()) request.set_actor(actor);
  2354. smartbotic::databasepb::RestoreToDateResponse response;
  2355. grpc::ClientContext context;
  2356. setDeadline(context);
  2357. auto status = stub_->RestoreToDate(&context, request, &response);
  2358. if (!status.ok()) {
  2359. spdlog::error("Client::restoreToDate failed: {}", status.error_message());
  2360. return {0, 0};
  2361. }
  2362. if (!response.success()) {
  2363. spdlog::error("Client::restoreToDate: {}", response.error());
  2364. return {0, 0};
  2365. }
  2366. return {response.restored_version(), response.new_version()};
  2367. }
  2368. // ===== Health =====
  2369. bool healthCheck() {
  2370. smartbotic::databasepb::HealthCheckRequest request;
  2371. smartbotic::databasepb::HealthCheckResponse response;
  2372. grpc::ClientContext context;
  2373. setDeadline(context);
  2374. auto status = stub_->HealthCheck(&context, request, &response);
  2375. if (!status.ok()) {
  2376. return false;
  2377. }
  2378. return response.healthy();
  2379. }
  2380. std::optional<Client::HealthInfo> getHealthInfo() {
  2381. smartbotic::databasepb::HealthCheckRequest request;
  2382. smartbotic::databasepb::HealthCheckResponse response;
  2383. grpc::ClientContext context;
  2384. setDeadline(context);
  2385. auto status = stub_->HealthCheck(&context, request, &response);
  2386. if (!status.ok()) {
  2387. return std::nullopt;
  2388. }
  2389. Client::HealthInfo info;
  2390. info.healthy = response.healthy();
  2391. info.uptimeMs = response.uptime_seconds() * 1000;
  2392. info.documentCount = response.document_count();
  2393. info.memoryUsedBytes = response.memory_used_bytes();
  2394. info.walSizeBytes = response.wal_size_bytes();
  2395. return info;
  2396. }
  2397. std::optional<Client::StatsInfo> getStats() {
  2398. smartbotic::databasepb::GetStatsRequest request;
  2399. smartbotic::databasepb::GetStatsResponse response;
  2400. grpc::ClientContext context;
  2401. setDeadline(context);
  2402. auto status = stub_->GetStats(&context, request, &response);
  2403. if (!status.ok()) {
  2404. return std::nullopt;
  2405. }
  2406. Client::StatsInfo info;
  2407. info.totalDocuments = response.total_documents();
  2408. info.totalCollections = response.total_collections();
  2409. info.memoryUsedBytes = response.memory_used_bytes();
  2410. info.walSequence = response.wal_sequence();
  2411. info.walSizeBytes = response.wal_size_bytes();
  2412. info.snapshotCount = response.snapshot_count();
  2413. info.lastSnapshotSequence = response.last_snapshot_sequence();
  2414. info.insertCount = response.insert_count();
  2415. info.updateCount = response.update_count();
  2416. info.deleteCount = response.delete_count();
  2417. info.queryCount = response.query_count();
  2418. // Memory eviction stats
  2419. info.evictedDocuments = response.evicted_documents();
  2420. info.totalEvictions = response.total_evictions();
  2421. info.recoveryCount = response.recovery_count();
  2422. // Memory configuration
  2423. info.maxMemoryBytes = response.max_memory_bytes();
  2424. info.evictionThresholdPercent = response.eviction_threshold_percent();
  2425. info.evictionTargetPercent = response.eviction_target_percent();
  2426. // Operation timing (microseconds) - for performance monitoring
  2427. info.getCount = response.get_count();
  2428. info.getTotalMicros = response.get_total_micros();
  2429. info.getMaxMicros = response.get_max_micros();
  2430. info.insertTotalMicros = response.insert_total_micros();
  2431. info.insertMaxMicros = response.insert_max_micros();
  2432. info.updateTotalMicros = response.update_total_micros();
  2433. info.updateMaxMicros = response.update_max_micros();
  2434. info.queryTotalMicros = response.query_total_micros();
  2435. info.queryMaxMicros = response.query_max_micros();
  2436. return info;
  2437. }
  2438. Client::MemoryStats getMemoryStats() {
  2439. smartbotic::databasepb::GetMemoryStatsRequest request;
  2440. smartbotic::databasepb::GetMemoryStatsResponse response;
  2441. grpc::ClientContext context;
  2442. setDeadline(context);
  2443. Client::MemoryStats out;
  2444. auto status = stub_->GetMemoryStats(&context, request, &response);
  2445. if (!status.ok()) {
  2446. spdlog::error("Client::getMemoryStats failed: {}", status.error_message());
  2447. return out;
  2448. }
  2449. out.totalMemoryBytes = response.total_memory_bytes();
  2450. out.maxMemoryBytes = response.max_memory_bytes();
  2451. out.pressurePercent = response.pressure_percent();
  2452. out.pressureLevel = response.pressure_level();
  2453. out.lastEvictionTimestamp = response.last_eviction_timestamp();
  2454. out.lastEvictionDocs = response.last_eviction_docs();
  2455. out.lastEvictionBytesFreed = response.last_eviction_bytes_freed();
  2456. out.collections.reserve(response.collections_size());
  2457. for (const auto& pbc : response.collections()) {
  2458. Client::MemoryCollectionStats c;
  2459. c.collection = pbc.collection();
  2460. c.documentCount = pbc.document_count();
  2461. c.estimatedBytes = pbc.estimated_bytes();
  2462. c.evictedStubCount = pbc.evicted_stub_count();
  2463. switch (pbc.priority()) {
  2464. case smartbotic::databasepb::MEMORY_PRIORITY_LOW: c.priority = "low"; break;
  2465. case smartbotic::databasepb::MEMORY_PRIORITY_NORMAL: c.priority = "normal"; break;
  2466. case smartbotic::databasepb::MEMORY_PRIORITY_HIGH: c.priority = "high"; break;
  2467. default: c.priority = "normal"; break;
  2468. }
  2469. out.collections.push_back(std::move(c));
  2470. }
  2471. return out;
  2472. }
  2473. // ===== Read-Only Control =====
  2474. bool setReadOnly(bool readOnly) {
  2475. smartbotic::databasepb::SetReadOnlyRequest request;
  2476. request.set_read_only(readOnly);
  2477. smartbotic::databasepb::SetReadOnlyResponse response;
  2478. grpc::ClientContext context;
  2479. setDeadline(context);
  2480. auto status = stub_->SetReadOnly(&context, request, &response);
  2481. if (!status.ok()) {
  2482. spdlog::error("Client::setReadOnly failed: {}", status.error_message());
  2483. return false;
  2484. }
  2485. return response.success();
  2486. }
  2487. Client::ReadOnlyStatus getReadOnlyStatus() {
  2488. smartbotic::databasepb::GetReadOnlyStatusRequest request;
  2489. smartbotic::databasepb::GetReadOnlyStatusResponse response;
  2490. grpc::ClientContext context;
  2491. setDeadline(context);
  2492. Client::ReadOnlyStatus out;
  2493. auto status = stub_->GetReadOnlyStatus(&context, request, &response);
  2494. if (!status.ok()) {
  2495. spdlog::error("Client::getReadOnlyStatus failed: {}", status.error_message());
  2496. return out;
  2497. }
  2498. out.readOnly = response.read_only();
  2499. out.reason = response.reason();
  2500. out.recoveryOutcome = response.recovery_outcome();
  2501. out.expectedSnapshot = response.expected_snapshot();
  2502. out.snapshotUsed = response.snapshot_used();
  2503. out.failureReason = response.failure_reason();
  2504. out.walEntriesReplayed = response.wal_entries_replayed();
  2505. out.snapshotsAttempted = response.snapshots_attempted();
  2506. return out;
  2507. }
  2508. // ===== File Operations =====
  2509. Client::FileUploadResult uploadFile(const std::vector<uint8_t>& data,
  2510. const Client::FileUploadMeta& meta,
  2511. uint32_t ttlSeconds = 0,
  2512. bool explicitTtl = false) {
  2513. grpc::ClientContext context;
  2514. auto timeout_ms = config_.timeoutMs + (data.size() / (1024 * 1024)) * 1000;
  2515. context.set_deadline(
  2516. std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_ms));
  2517. attachAuth(context);
  2518. smartbotic::databasepb::UploadFileResponse response;
  2519. auto writer = stub_->UploadFile(&context, &response);
  2520. // First chunk: metadata
  2521. smartbotic::databasepb::FileChunk metaChunk;
  2522. auto* m = metaChunk.mutable_metadata();
  2523. m->set_name(meta.name);
  2524. m->set_mime_type(meta.mime_type);
  2525. m->set_file_type(meta.file_type);
  2526. m->set_related_id(meta.related_id);
  2527. m->set_is_public(meta.is_public);
  2528. // v2.6.0 — files are namespaced like collections. Filled from
  2529. // Config::project so callers keep passing bare ids and names.
  2530. m->set_project(config_.project);
  2531. // v2.8.0 — relative TTL; the server converts it to an absolute expiry.
  2532. // Set unconditionally on this overload: calling it IS the explicit
  2533. // choice, and 0 therefore means "never expire, ignore any configured
  2534. // default for this file type". The two-argument uploadFile() leaves the
  2535. // field absent so the default applies.
  2536. if (explicitTtl) m->set_ttl_seconds(ttlSeconds);
  2537. for (const auto& [key, value] : meta.metadata) {
  2538. (*m->mutable_metadata())[key] = value;
  2539. }
  2540. writer->Write(metaChunk);
  2541. // Data chunks (64KB each)
  2542. constexpr size_t CHUNK_SIZE = 64 * 1024;
  2543. for (size_t offset = 0; offset < data.size(); offset += CHUNK_SIZE) {
  2544. smartbotic::databasepb::FileChunk dataChunk;
  2545. size_t chunkSize = std::min(CHUNK_SIZE, data.size() - offset);
  2546. dataChunk.set_data(data.data() + offset, chunkSize);
  2547. if (!writer->Write(dataChunk)) break;
  2548. }
  2549. writer->WritesDone();
  2550. auto status = writer->Finish();
  2551. if (!status.ok()) {
  2552. spdlog::error("Client::uploadFile failed: {}", status.error_message());
  2553. throwStatus(status, status.error_message(), trailerDetail(context)); // v2.12.3: reason file_too_large / mime_type_not_allowed
  2554. }
  2555. return {response.id(), response.size(), response.checksum(), response.deduplicated()};
  2556. }
  2557. std::vector<uint8_t> downloadFile(const std::string& id) {
  2558. // v2.6.0 — see note in uploadFile; project scopes every file call.
  2559. smartbotic::databasepb::DownloadFileRequest request;
  2560. request.set_id(id);
  2561. request.set_project(config_.project);
  2562. grpc::ClientContext context;
  2563. context.set_deadline(
  2564. std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs * 10));
  2565. attachAuth(context);
  2566. auto reader = stub_->DownloadFile(&context, request);
  2567. std::vector<uint8_t> fileData;
  2568. smartbotic::databasepb::FileChunk chunk;
  2569. while (reader->Read(&chunk)) {
  2570. if (chunk.has_data()) {
  2571. const auto& d = chunk.data();
  2572. fileData.insert(fileData.end(), d.begin(), d.end());
  2573. }
  2574. }
  2575. auto status = reader->Finish();
  2576. if (!status.ok()) {
  2577. spdlog::error("Client::downloadFile failed: {}", status.error_message());
  2578. throwStatus(status, status.error_message());
  2579. }
  2580. return fileData;
  2581. }
  2582. std::optional<Client::FileRecord> getFileInfo(const std::string& id) {
  2583. smartbotic::databasepb::GetFileInfoRequest request;
  2584. request.set_id(id);
  2585. request.set_project(config_.project);
  2586. smartbotic::databasepb::FileInfo response;
  2587. grpc::ClientContext context;
  2588. setDeadline(context);
  2589. auto status = stub_->GetFileInfo(&context, request, &response);
  2590. if (!status.ok()) {
  2591. if (status.error_code() == grpc::StatusCode::NOT_FOUND) return std::nullopt;
  2592. spdlog::error("Client::getFileInfo failed: {}", status.error_message());
  2593. throwStatus(status, status.error_message());
  2594. }
  2595. Client::FileRecord record;
  2596. record.id = response.id();
  2597. record.name = response.name();
  2598. record.mime_type = response.mime_type();
  2599. record.size = response.size();
  2600. record.file_type = response.file_type();
  2601. record.related_id = response.related_id();
  2602. record.checksum = response.checksum();
  2603. record.is_public = response.is_public();
  2604. record.ref_count = response.ref_count();
  2605. record.created_at = response.created_at();
  2606. record.project = response.project();
  2607. for (const auto& [key, value] : response.metadata()) {
  2608. record.metadata[key] = value;
  2609. }
  2610. return record;
  2611. }
  2612. // v2.13.0 - `failureOut` tells "no such file" (NotFound, answered in-band
  2613. // by the server) from a call that failed (the real code). The bool-only
  2614. // public form passes no sink and behaves exactly as before.
  2615. bool deleteFile(const std::string& id, FailureSink failureOut = {}) {
  2616. failureOut.reset();
  2617. smartbotic::databasepb::DeleteFileRequest request;
  2618. request.set_id(id);
  2619. request.set_project(config_.project);
  2620. smartbotic::databasepb::DeleteFileResponse response;
  2621. grpc::ClientContext context;
  2622. setDeadline(context);
  2623. auto status = stub_->DeleteFile(&context, request, &response);
  2624. if (!status.ok()) {
  2625. spdlog::error("Client::deleteFile failed: {}", status.error_message());
  2626. failureOut.record(status);
  2627. return false;
  2628. }
  2629. if (!response.deleted()) {
  2630. failureOut.record(Client::ErrorCode::NotFound, "no such file in this project");
  2631. }
  2632. return response.deleted();
  2633. }
  2634. // v2.13.0 - same contract as deleteFile above.
  2635. bool setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureSink failureOut = {}) {
  2636. failureOut.reset();
  2637. smartbotic::databasepb::SetFileTtlRequest request;
  2638. request.set_id(id);
  2639. request.set_project(config_.project);
  2640. request.set_ttl_seconds(ttlSeconds);
  2641. smartbotic::databasepb::SetFileTtlResponse response;
  2642. grpc::ClientContext context;
  2643. setDeadline(context);
  2644. auto status = stub_->SetFileTtl(&context, request, &response);
  2645. if (!status.ok()) {
  2646. spdlog::error("Client::setFileTtl failed: {}", status.error_message());
  2647. failureOut.record(status);
  2648. return false;
  2649. }
  2650. if (!response.updated()) {
  2651. failureOut.record(Client::ErrorCode::NotFound,
  2652. "no such file in this project, or it has already expired");
  2653. }
  2654. return response.updated();
  2655. }
  2656. Client::FileListResult listFiles(const std::string& file_type,
  2657. const std::string& related_id,
  2658. uint32_t limit, uint32_t offset,
  2659. const std::string& checksum,
  2660. const std::string& name) {
  2661. smartbotic::databasepb::ListFilesRequest request;
  2662. if (!file_type.empty()) request.set_file_type(file_type);
  2663. if (!related_id.empty()) request.set_related_id(related_id);
  2664. request.set_limit(limit);
  2665. request.set_offset(offset);
  2666. if (!checksum.empty()) request.set_checksum(checksum);
  2667. if (!name.empty()) request.set_name(name);
  2668. request.set_project(config_.project);
  2669. smartbotic::databasepb::ListFilesResponse response;
  2670. grpc::ClientContext context;
  2671. setDeadline(context);
  2672. auto status = stub_->ListFiles(&context, request, &response);
  2673. if (!status.ok()) {
  2674. spdlog::error("Client::listFiles failed: {}", status.error_message());
  2675. throwStatus(status, status.error_message());
  2676. }
  2677. Client::FileListResult result;
  2678. result.total_count = response.total_count();
  2679. result.has_more = response.has_more();
  2680. for (const auto& f : response.files()) {
  2681. Client::FileRecord record;
  2682. record.id = f.id();
  2683. record.name = f.name();
  2684. record.mime_type = f.mime_type();
  2685. record.size = f.size();
  2686. record.file_type = f.file_type();
  2687. record.related_id = f.related_id();
  2688. record.checksum = f.checksum();
  2689. record.is_public = f.is_public();
  2690. record.created_at = f.created_at();
  2691. record.project = f.project();
  2692. for (const auto& [key, value] : f.metadata()) {
  2693. record.metadata[key] = value;
  2694. }
  2695. result.files.push_back(std::move(record));
  2696. }
  2697. return result;
  2698. }
  2699. private:
  2700. // Per-context setup: deadline + (v2.4) bearer-token auth metadata.
  2701. //
  2702. // Most RPC call sites in this library funnel through this helper —
  2703. // unary (insert, get, update, ...) plus the unary file ops that need
  2704. // the default deadline. Long-running streams (Subscribe) and the
  2705. // file-streaming RPCs (UploadFile/DownloadFile) compute their own
  2706. // deadlines and call `attachAuth()` separately so the auth metadata
  2707. // still lands on every outbound RPC. Centralising both concerns here
  2708. // means we don't need a gRPC ClientInterceptorFactoryInterface — the
  2709. // interceptor route is also offered by gRPC++ but it sits in
  2710. // grpc::experimental:: and would need to be re-validated on every
  2711. // grpc minor; the per-context style keeps Stage E independent of
  2712. // gRPC's TLS/interceptor experimental flux.
  2713. void setDeadline(grpc::ClientContext& context) {
  2714. context.set_deadline(
  2715. std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs)
  2716. );
  2717. attachAuth(context);
  2718. }
  2719. // v2.13.1 - a write's deadline grows with its size: timeoutMs plus one
  2720. // second per 4 MiB sent. A 20 MiB patch on a 60 MiB row legitimately takes
  2721. // longer than a small write, and a fixed deadline made it time out while the
  2722. // server completed it - the shape that produced "failed" writes that had
  2723. // been applied.
  2724. void setWriteDeadline(grpc::ClientContext& context, size_t requestBytes) {
  2725. const auto extraMs = static_cast<uint64_t>(requestBytes / (4u * 1024 * 1024)) * 1000;
  2726. context.set_deadline(std::chrono::system_clock::now() +
  2727. std::chrono::milliseconds(config_.timeoutMs + extraMs));
  2728. attachAuth(context);
  2729. }
  2730. // v2.4 — attach the bearer-token authorization metadata if configured.
  2731. // Use this on contexts that set their own deadline (streams,
  2732. // long-running ops) so the auth metadata still lands.
  2733. //
  2734. // v2.15.0 - every call also carries this library's version, so a server can
  2735. // keep an old behaviour for an old client if a meaning ever has to change.
  2736. // Every context passes through here (setDeadline, setWriteDeadline, the
  2737. // streams), which is why the header is attached here and not elsewhere.
  2738. void attachAuth(grpc::ClientContext& context) {
  2739. context.AddMetadata("sbdb-client-version", SMARTBOTIC_DB_VERSION_STRING);
  2740. if (!config_.auth_token.empty()) {
  2741. context.AddMetadata("authorization", "Bearer " + config_.auth_token);
  2742. }
  2743. }
  2744. public:
  2745. // ===== Server info and capabilities (v2.15.0) =====
  2746. std::optional<Client::ServerInfo> serverInfo(bool refresh) {
  2747. {
  2748. std::lock_guard<std::mutex> lk(infoMu_);
  2749. if (!refresh && infoFetched_ &&
  2750. std::chrono::steady_clock::now() - infoAt_ < std::chrono::seconds(60)) {
  2751. return info_;
  2752. }
  2753. }
  2754. smartbotic::databasepb::GetServerInfoRequest request;
  2755. smartbotic::databasepb::GetServerInfoResponse response;
  2756. grpc::ClientContext context;
  2757. setDeadline(context);
  2758. auto status = stub_->GetServerInfo(&context, request, &response);
  2759. std::optional<Client::ServerInfo> got;
  2760. if (status.ok()) {
  2761. Client::ServerInfo si;
  2762. si.version = response.version();
  2763. si.commit = response.commit();
  2764. si.capabilities.assign(response.capabilities().begin(), response.capabilities().end());
  2765. si.clientVersionSeen = response.client_version();
  2766. got = std::move(si);
  2767. } else if (status.error_code() != grpc::StatusCode::UNIMPLEMENTED) {
  2768. // An outage is not "an old server": answering nullopt here would
  2769. // make every 2.15.0+ feature look unsupported during a blip.
  2770. throwStatus(status, "serverInfo: " + status.error_message(), trailerDetail(context));
  2771. }
  2772. // UNIMPLEMENTED: a pre-2.15.0 server. Cached like an answer.
  2773. std::lock_guard<std::mutex> lk(infoMu_);
  2774. info_ = got;
  2775. infoFetched_ = true;
  2776. infoAt_ = std::chrono::steady_clock::now();
  2777. return got;
  2778. }
  2779. bool serverSupports(const std::string& capability) {
  2780. const auto si = serverInfo(false);
  2781. if (!si) return false;
  2782. return std::find(si->capabilities.begin(), si->capabilities.end(), capability) !=
  2783. si->capabilities.end();
  2784. }
  2785. // For client methods that need a feature introduced in 2.15.0 or later:
  2786. // refuse BEFORE sending, because an old server ignores what it does not
  2787. // understand and answers something that looks right.
  2788. void requireCapability(const char* capability, const char* what) {
  2789. if (serverSupports(capability)) return;
  2790. const auto si = serverInfo(false);
  2791. const std::string msg = std::string(what) + ": the server does not support '" +
  2792. capability + "' (server " +
  2793. (si ? si->version : std::string("older than 2.15.0")) + ")";
  2794. spdlog::error("Client::{}", msg);
  2795. throw DetailedFailedPrecondition(
  2796. msg, makeDetail(Client::ErrorCode::FailedPrecondition, msg,
  2797. R"({"reason":"server_unsupported"})"));
  2798. }
  2799. private:
  2800. std::mutex infoMu_;
  2801. bool infoFetched_ = false;
  2802. std::optional<Client::ServerInfo> info_;
  2803. std::chrono::steady_clock::time_point infoAt_{};
  2804. Config config_;
  2805. std::shared_ptr<grpc::Channel> channel_;
  2806. std::unique_ptr<smartbotic::databasepb::DatabaseService::Stub> stub_;
  2807. std::atomic<bool> connected_{false};
  2808. std::atomic<bool> reached_{false}; // v2.13.1 - the last connect() attempt succeeded
  2809. };
  2810. // ===== Client Public Interface Implementation =====
  2811. Client::Client(Config config)
  2812. : impl_(std::make_unique<Impl>(std::move(config))) {}
  2813. Client::~Client() = default;
  2814. Client::Client(Client&&) noexcept = default;
  2815. Client& Client::operator=(Client&&) noexcept = default;
  2816. bool Client::connect() {
  2817. return impl_->connect();
  2818. }
  2819. bool Client::isConnected() const {
  2820. return impl_->isConnected();
  2821. }
  2822. std::string Client::insert(const std::string& collection, const nlohmann::json& data,
  2823. const std::string& id, uint32_t ttlSeconds,
  2824. const std::string& actor) {
  2825. return impl_->insert(collection, data, id, ttlSeconds, actor);
  2826. }
  2827. std::optional<nlohmann::json> Client::get(const std::string& collection, const std::string& id) {
  2828. return impl_->get(collection, id);
  2829. }
  2830. bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data,
  2831. const std::string& actor) {
  2832. return impl_->update(collection, id, data, actor);
  2833. }
  2834. bool Client::updateIfVersion(const std::string& collection, const std::string& id,
  2835. const nlohmann::json& data, uint64_t expectedVersion,
  2836. const std::string& actor) {
  2837. return impl_->updateIfVersion(collection, id, data, expectedVersion, actor);
  2838. }
  2839. bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data,
  2840. Failure& failureOut, const std::string& actor) {
  2841. failureOut = Failure{};
  2842. return impl_->update(collection, id, data, actor, &failureOut);
  2843. }
  2844. bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data,
  2845. FailureDetail& failureOut, const std::string& actor) {
  2846. failureOut = FailureDetail{};
  2847. return impl_->update(collection, id, data, actor, &failureOut);
  2848. }
  2849. bool Client::updateIfVersion(const std::string& collection, const std::string& id,
  2850. const nlohmann::json& data, uint64_t expectedVersion,
  2851. FailureDetail& failureOut, const std::string& actor) {
  2852. return impl_->updateIfVersion(collection, id, data, expectedVersion, actor, &failureOut);
  2853. }
  2854. uint64_t Client::patch(const std::string& collection, const std::string& id,
  2855. const nlohmann::json& fields, FailureDetail& failureOut,
  2856. const std::string& actor) {
  2857. return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut);
  2858. }
  2859. uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id,
  2860. const nlohmann::json& fields, uint32_t ttlSeconds,
  2861. FailureDetail& failureOut, const std::string& actor) {
  2862. return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut);
  2863. }
  2864. uint64_t Client::patchIfVersion(const std::string& collection, const std::string& id,
  2865. const nlohmann::json& fields, uint64_t expectedVersion,
  2866. FailureDetail& failureOut, const std::string& actor) {
  2867. return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut,
  2868. expectedVersion);
  2869. }
  2870. std::optional<nlohmann::json> Client::increment(const std::string& collection, const std::string& id,
  2871. const nlohmann::json& deltas,
  2872. FailureDetail& failureOut,
  2873. const std::string& actor) {
  2874. nlohmann::json incremented;
  2875. const uint64_t v = impl_->patch(collection, id, nlohmann::json::object(), actor, std::nullopt,
  2876. &failureOut, std::nullopt, &deltas, &incremented);
  2877. if (v == 0) return std::nullopt;
  2878. return incremented;
  2879. }
  2880. bool Client::updateIfVersion(const std::string& collection, const std::string& id,
  2881. const nlohmann::json& data, uint64_t expectedVersion,
  2882. Failure& failureOut, const std::string& actor) {
  2883. return impl_->updateIfVersion(collection, id, data, expectedVersion, actor, &failureOut);
  2884. }
  2885. uint64_t Client::patch(const std::string& collection, const std::string& id,
  2886. const nlohmann::json& fields, Failure& failureOut,
  2887. const std::string& actor) {
  2888. return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut);
  2889. }
  2890. uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id,
  2891. const nlohmann::json& fields, uint32_t ttlSeconds,
  2892. Failure& failureOut, const std::string& actor) {
  2893. return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut);
  2894. }
  2895. uint64_t Client::patch(const std::string& collection, const std::string& id,
  2896. const nlohmann::json& fields, const std::string& actor) {
  2897. return impl_->patch(collection, id, fields, actor);
  2898. }
  2899. uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id,
  2900. const nlohmann::json& fields, uint32_t ttlSeconds,
  2901. const std::string& actor) {
  2902. return impl_->patch(collection, id, fields, actor, ttlSeconds);
  2903. }
  2904. std::pair<std::string, bool> Client::upsert(const std::string& collection, const nlohmann::json& data,
  2905. const std::string& id, uint32_t ttlSeconds,
  2906. const std::string& actor) {
  2907. return impl_->upsert(collection, data, id, ttlSeconds, actor);
  2908. }
  2909. bool Client::remove(const std::string& collection, const std::string& id) {
  2910. return impl_->remove(collection, id);
  2911. }
  2912. bool Client::remove(const std::string& collection, const std::string& id, std::string& errorOut) {
  2913. return impl_->remove(collection, id, errorOut);
  2914. }
  2915. bool Client::remove(const std::string& collection, const std::string& id, Failure& failureOut) {
  2916. return impl_->remove(collection, id, failureOut);
  2917. }
  2918. bool Client::removeAs(const std::string& collection, const std::string& id,
  2919. const std::string& actor) {
  2920. return impl_->removeAs(collection, id, actor, FailureSink{});
  2921. }
  2922. bool Client::removeAs(const std::string& collection, const std::string& id,
  2923. const std::string& actor, Failure& failureOut) {
  2924. return impl_->removeAs(collection, id, actor, &failureOut);
  2925. }
  2926. bool Client::removeAs(const std::string& collection, const std::string& id,
  2927. const std::string& actor, FailureDetail& failureOut) {
  2928. return impl_->removeAs(collection, id, actor, &failureOut);
  2929. }
  2930. std::optional<Client::BatchRemoveResult>
  2931. Client::removeManyAs(const std::string& collection, const std::vector<std::string>& ids,
  2932. const std::string& actor, FailureDetail& failureOut) {
  2933. return impl_->removeManyAs(collection, ids, actor, &failureOut);
  2934. }
  2935. bool Client::exists(const std::string& collection, const std::string& id) {
  2936. return impl_->exists(collection, id);
  2937. }
  2938. Client::VersionHistoryResult Client::getVersionHistory(const std::string& collection,
  2939. const std::string& id, uint32_t limit, uint32_t offset) {
  2940. return impl_->getVersionHistory(collection, id, limit, offset);
  2941. }
  2942. std::optional<Client::VersionEntry> Client::getDocumentVersion(const std::string& collection,
  2943. const std::string& id, uint64_t version) {
  2944. return impl_->getDocumentVersion(collection, id, version);
  2945. }
  2946. uint64_t Client::restoreVersion(const std::string& collection, const std::string& id,
  2947. uint64_t version, const std::string& actor) {
  2948. return impl_->restoreVersion(collection, id, version, actor);
  2949. }
  2950. std::pair<uint64_t, uint64_t> Client::restoreToDate(const std::string& collection,
  2951. const std::string& id, uint64_t timestamp, const std::string& actor) {
  2952. return impl_->restoreToDate(collection, id, timestamp, actor);
  2953. }
  2954. std::vector<nlohmann::json> Client::find(const std::string& collection,
  2955. const QueryOptions& options) {
  2956. return impl_->find(collection, options);
  2957. }
  2958. std::vector<nlohmann::json> Client::find(const std::string& collection,
  2959. const QueryOptions& options,
  2960. const std::vector<std::string>& projection) {
  2961. return impl_->find(collection, options, projection);
  2962. }
  2963. std::vector<nlohmann::json> Client::find(const std::string& collection,
  2964. const QueryOptions& options, WithVector) {
  2965. return impl_->find(collection, options, {}, /*includeVector=*/true);
  2966. }
  2967. std::optional<nlohmann::json> Client::get(const std::string& collection,
  2968. const std::string& id, WithVector) {
  2969. return impl_->get(collection, id, /*includeVector=*/true);
  2970. }
  2971. Client::ExportSummary Client::exportCollection(
  2972. const std::string& collection, bool includeVectors, const std::string& afterId,
  2973. const std::function<void(const ExportHeader&)>& onHeader,
  2974. const std::function<bool(ExportRow&&)>& onRow, uint32_t batchRows) {
  2975. return impl_->exportCollection(collection, includeVectors, afterId, onHeader, onRow,
  2976. batchRows);
  2977. }
  2978. Client::FindResult Client::findWithMetrics(const std::string& collection,
  2979. const QueryOptions& options) {
  2980. return impl_->findWithMetrics(collection, options);
  2981. }
  2982. uint64_t Client::count(const std::string& collection,
  2983. const std::vector<Filter>& filters) {
  2984. return impl_->count(collection, filters);
  2985. }
  2986. uint64_t Client::count(const std::string& collection) {
  2987. return impl_->count(collection, {});
  2988. }
  2989. bool Client::setAdd(const std::string& collection, const std::string& setId, const std::string& member) {
  2990. return impl_->setAdd(collection, setId, member);
  2991. }
  2992. bool Client::setRemove(const std::string& collection, const std::string& setId, const std::string& member) {
  2993. return impl_->setRemove(collection, setId, member);
  2994. }
  2995. std::vector<std::string> Client::setMembers(const std::string& collection, const std::string& setId) {
  2996. return impl_->setMembers(collection, setId);
  2997. }
  2998. bool Client::setIsMember(const std::string& collection, const std::string& setId, const std::string& member) {
  2999. return impl_->setIsMember(collection, setId, member);
  3000. }
  3001. std::vector<Client::SimilarityResult> Client::similaritySearch(
  3002. const std::string& collection, const std::vector<float>& queryVector,
  3003. uint32_t topK, float minScore) {
  3004. return impl_->similaritySearch(collection, queryVector, topK, minScore);
  3005. }
  3006. std::vector<Client::SimilarityResult> Client::similaritySearch(
  3007. const std::string& collection, const std::vector<float>& queryVector,
  3008. uint32_t topK, float minScore, const std::vector<Filter>& filters) {
  3009. return impl_->similaritySearch(collection, queryVector, topK, minScore, filters);
  3010. }
  3011. bool Client::createCollection(const std::string& name, uint32_t defaultTtlSeconds,
  3012. bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) {
  3013. return impl_->createCollection(name, defaultTtlSeconds, encrypted, maxVersions, vectorDimension);
  3014. }
  3015. bool Client::dropCollection(const std::string& name) {
  3016. return impl_->dropCollection(name);
  3017. }
  3018. std::vector<std::string> Client::listCollections() {
  3019. return impl_->listCollections();
  3020. }
  3021. std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
  3022. return impl_->getCollectionInfo(name);
  3023. }
  3024. // ===== Project Management (v2.3 Stage F) =====
  3025. std::vector<std::string> Client::listProjects() {
  3026. return impl_->listProjects();
  3027. }
  3028. bool Client::createProject(const std::string& name) {
  3029. return impl_->createProject(name);
  3030. }
  3031. void Client::dropProject(const std::string& name) {
  3032. impl_->dropProject(name);
  3033. }
  3034. bool Client::configureCollection(const std::string& collection, const CollectionConfig& cfg) {
  3035. return impl_->configureCollection(collection, cfg);
  3036. }
  3037. Client::CollectionConfig Client::getCollectionConfig(const std::string& collection) {
  3038. return impl_->getCollectionConfig(collection);
  3039. }
  3040. bool Client::hasCollectionConfig(const std::string& collection) {
  3041. return impl_->hasCollectionConfig(collection);
  3042. }
  3043. Client::TimestampMigrationResult Client::migrateCollectionTimestamps(
  3044. const std::string& collection,
  3045. const std::string& fromPrecision,
  3046. const std::string& toPrecision
  3047. ) {
  3048. return impl_->migrateCollectionTimestamps(collection, fromPrecision, toPrecision);
  3049. }
  3050. bool Client::createView(const std::string& name,
  3051. const std::string& collection,
  3052. const std::vector<std::string>& include,
  3053. const std::vector<std::string>& exclude,
  3054. const std::vector<Filter>& where,
  3055. const std::optional<Sort>& defaultSort) {
  3056. return impl_->createView(name, collection, include, exclude, where, defaultSort);
  3057. }
  3058. bool Client::dropView(const std::string& name) {
  3059. return impl_->dropView(name);
  3060. }
  3061. bool Client::createIndex(const std::string& collection, const std::string& field) {
  3062. return impl_->createIndex(collection, field, nullptr);
  3063. }
  3064. bool Client::createIndex(const std::string& collection, const std::string& field,
  3065. uint64_t& rowsIndexed) {
  3066. return impl_->createIndex(collection, field, &rowsIndexed);
  3067. }
  3068. bool Client::dropIndex(const std::string& collection, const std::string& field) {
  3069. return impl_->dropIndex(collection, field);
  3070. }
  3071. Client::CreateIndexResult Client::createUniqueIndex(const std::string& collection,
  3072. const std::string& field) {
  3073. return impl_->createUniqueIndex(collection, field);
  3074. }
  3075. Client::CreateIndexResult Client::createCompositeUniqueIndex(const std::string& collection,
  3076. const std::vector<std::string>& fields) {
  3077. return impl_->createCompositeUniqueIndex(collection, fields);
  3078. }
  3079. bool Client::dropCompositeUniqueIndex(const std::string& collection,
  3080. const std::vector<std::string>& fields) {
  3081. return impl_->dropCompositeUniqueIndex(collection, fields);
  3082. }
  3083. std::vector<std::vector<std::string>>
  3084. Client::listCompositeUniqueIndexes(const std::string& collection) {
  3085. return impl_->listCompositeUniqueIndexes(collection);
  3086. }
  3087. std::vector<Client::IndexDefinition> Client::listIndexes(const std::string& collection) {
  3088. return impl_->listIndexes(collection, nullptr);
  3089. }
  3090. std::vector<Client::IndexDefinition> Client::listIndexes(const std::string& collection,
  3091. std::vector<bool>& uniqueFlags) {
  3092. return impl_->listIndexes(collection, &uniqueFlags);
  3093. }
  3094. std::vector<Client::IndexValue> Client::indexValues(const std::string& collection,
  3095. const std::string& field,
  3096. uint32_t limit, bool ascending) {
  3097. return impl_->indexValues(collection, field, limit, ascending);
  3098. }
  3099. std::vector<Client::ViewDefinition> Client::listViews() {
  3100. return impl_->listViews();
  3101. }
  3102. std::optional<Client::ViewDefinition> Client::getViewInfo(const std::string& name) {
  3103. return impl_->getViewInfo(name);
  3104. }
  3105. bool Client::createRelation(const std::string& name, const std::string& childCollection,
  3106. const std::string& childField, const std::string& parentCollection,
  3107. const std::string& onDelete, bool validateOnWrite) {
  3108. return impl_->createRelation(name, childCollection, childField, parentCollection,
  3109. onDelete, validateOnWrite, nullptr);
  3110. }
  3111. bool Client::createRelation(const std::string& name, const std::string& childCollection,
  3112. const std::string& childField, const std::string& parentCollection,
  3113. const std::string& onDelete, bool validateOnWrite,
  3114. uint64_t& rowsIndexed) {
  3115. return impl_->createRelation(name, childCollection, childField, parentCollection,
  3116. onDelete, validateOnWrite, &rowsIndexed);
  3117. }
  3118. bool Client::dropRelation(const std::string& name) {
  3119. return impl_->dropRelation(name);
  3120. }
  3121. std::vector<Client::RelationDefinition> Client::listRelations() {
  3122. return impl_->listRelations();
  3123. }
  3124. std::vector<Client::RelationDefinition> Client::listRelations(const std::string& project) {
  3125. return impl_->listRelationsIn(project);
  3126. }
  3127. std::optional<Client::RelationDefinition> Client::getRelationInfo(const std::string& name) {
  3128. return impl_->getRelationInfo(name);
  3129. }
  3130. bool Client::setRelationsEnforced(const std::string& collection, bool enforced) {
  3131. return impl_->setRelationsEnforced(collection, enforced);
  3132. }
  3133. bool Client::getRelationsEnforced(const std::string& collection) {
  3134. return impl_->getRelationsEnforced(collection);
  3135. }
  3136. std::optional<bool> Client::tryGetRelationsEnforced(const std::string& collection) {
  3137. return impl_->tryGetRelationsEnforced(collection);
  3138. }
  3139. Client::DescribeDeleteResult Client::describeDelete(const std::string& collection,
  3140. const std::string& id) {
  3141. return impl_->describeDelete(collection, id);
  3142. }
  3143. Client::CheckRelationResult Client::checkRelation(const std::string& name) {
  3144. return impl_->checkRelation(name);
  3145. }
  3146. std::shared_ptr<void> Client::subscribe(const std::vector<std::string>& collections, EventCallback callback) {
  3147. return impl_->subscribe(collections, std::move(callback));
  3148. }
  3149. std::shared_ptr<void> Client::subscribeEvents(const std::vector<std::string>& collections,
  3150. EventHandler handler) {
  3151. return impl_->subscribeEvents(collections, std::move(handler));
  3152. }
  3153. bool Client::healthCheck() {
  3154. return impl_->healthCheck();
  3155. }
  3156. std::optional<Client::HealthInfo> Client::getHealthInfo() {
  3157. return impl_->getHealthInfo();
  3158. }
  3159. std::optional<Client::StatsInfo> Client::getStats() {
  3160. return impl_->getStats();
  3161. }
  3162. Client::MemoryStats Client::getMemoryStats() {
  3163. return impl_->getMemoryStats();
  3164. }
  3165. bool Client::setReadOnly(bool readOnly) {
  3166. return impl_->setReadOnly(readOnly);
  3167. }
  3168. Client::ReadOnlyStatus Client::getReadOnlyStatus() {
  3169. return impl_->getReadOnlyStatus();
  3170. }
  3171. Client::FileUploadResult Client::uploadFile(const std::vector<uint8_t>& data, const FileUploadMeta& meta) {
  3172. return impl_->uploadFile(data, meta);
  3173. }
  3174. Client::FileUploadResult Client::uploadFile(const std::vector<uint8_t>& data,
  3175. const FileUploadMeta& meta,
  3176. uint32_t ttlSeconds) {
  3177. return impl_->uploadFile(data, meta, ttlSeconds, /*explicitTtl=*/true);
  3178. }
  3179. std::vector<uint8_t> Client::downloadFile(const std::string& id) {
  3180. return impl_->downloadFile(id);
  3181. }
  3182. std::optional<Client::FileRecord> Client::getFileInfo(const std::string& id) {
  3183. return impl_->getFileInfo(id);
  3184. }
  3185. bool Client::deleteFile(const std::string& id) {
  3186. return impl_->deleteFile(id);
  3187. }
  3188. bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds) {
  3189. return impl_->setFileTtl(id, ttlSeconds);
  3190. }
  3191. bool Client::deleteFile(const std::string& id, Failure& failureOut) {
  3192. return impl_->deleteFile(id, &failureOut);
  3193. }
  3194. bool Client::deleteFile(const std::string& id, FailureDetail& failureOut) {
  3195. return impl_->deleteFile(id, &failureOut);
  3196. }
  3197. bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, Failure& failureOut) {
  3198. return impl_->setFileTtl(id, ttlSeconds, &failureOut);
  3199. }
  3200. bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureDetail& failureOut) {
  3201. return impl_->setFileTtl(id, ttlSeconds, &failureOut);
  3202. }
  3203. Client::FileListResult Client::listFiles(const std::string& file_type,
  3204. const std::string& related_id,
  3205. uint32_t limit, uint32_t offset,
  3206. const std::string& checksum,
  3207. const std::string& name) {
  3208. return impl_->listFiles(file_type, related_id, limit, offset, checksum, name);
  3209. }
  3210. // v2.11.1 — see the header. The macros are defined on this target from the
  3211. // top-level VERSION file and BUILD_GIT_COMMIT, exactly as the service and CLI
  3212. // get theirs, so all three binaries answer the same question the same way.
  3213. #ifndef SMARTBOTIC_DB_VERSION_STRING
  3214. #define SMARTBOTIC_DB_VERSION_STRING "unknown"
  3215. #endif
  3216. #ifndef SMARTBOTIC_DB_GIT_COMMIT_STRING
  3217. #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
  3218. #endif
  3219. Client::SchemaChangeResult Client::setCollectionSchema(const std::string& collection,
  3220. const nlohmann::json& schema,
  3221. SchemaMode mode) {
  3222. return impl_->schemaChange(collection, schema.dump(), mode);
  3223. }
  3224. Client::SchemaChangeResult Client::removeCollectionSchema(const std::string& collection) {
  3225. return impl_->schemaChange(collection, "", SchemaMode::Enforce);
  3226. }
  3227. std::optional<Client::CollectionSchema> Client::getCollectionSchema(const std::string& collection) {
  3228. return impl_->getCollectionSchema(collection);
  3229. }
  3230. Client::SchemaSuggestion Client::suggestCollectionSchema(const std::string& collection,
  3231. uint64_t sampleLimit) {
  3232. return impl_->suggestCollectionSchema(collection, sampleLimit);
  3233. }
  3234. std::optional<Client::ServerInfo> Client::serverInfo(bool refresh) {
  3235. return impl_->serverInfo(refresh);
  3236. }
  3237. bool Client::serverSupports(const std::string& capability) {
  3238. return impl_->serverSupports(capability);
  3239. }
  3240. std::string clientLibraryVersion() { return SMARTBOTIC_DB_VERSION_STRING; }
  3241. std::string clientLibraryCommit() { return SMARTBOTIC_DB_GIT_COMMIT_STRING; }
  3242. } // namespace smartbotic::database