client.cpp 145 KB

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