client.cpp 144 KB

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