client.cpp 114 KB

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