client.cpp 134 KB

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