database_service.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. #include "database_service.hpp"
  2. #include "json_parse.hpp"
  3. #include "project_addressing.hpp"
  4. #include "storage/secondary_index.hpp"
  5. #include "storage/document_store.hpp"
  6. #include "storage/document_store_lmdb.hpp"
  7. #include "storage/dual_write_mirror.hpp"
  8. #include "relations/relation_cascade.hpp"
  9. #include "relations/relation_enforcement.hpp"
  10. #include "auth/auth_interceptor.hpp"
  11. #include "auth/principal.hpp"
  12. #include "tls/cert_generator.hpp"
  13. #include <fstream>
  14. #include <sstream>
  15. #include <map>
  16. #include <set>
  17. #include "storage/lmdb_env.hpp"
  18. #include "storage/migrate_v1_to_v2.hpp"
  19. #include "storage/project_store.hpp"
  20. #include "storage/subdb_placement.hpp"
  21. #include <grpcpp/grpcpp.h>
  22. #include <grpcpp/resource_quota.h>
  23. #include <spdlog/spdlog.h>
  24. #include <fstream>
  25. #ifdef HAVE_SYSTEMD
  26. #include <systemd/sd-daemon.h>
  27. #endif
  28. #if defined(__GLIBC__) && !defined(__APPLE__)
  29. #include <malloc.h>
  30. #endif
  31. namespace smartbotic::database {
  32. DatabaseService::DatabaseService(Config config)
  33. : config_(std::move(config))
  34. {
  35. }
  36. DatabaseService::~DatabaseService() {
  37. stop();
  38. }
  39. std::string DatabaseService::readOnlyReason() const {
  40. std::lock_guard<std::mutex> lock(reason_mutex_);
  41. return read_only_reason_;
  42. }
  43. void DatabaseService::setReadOnly(bool value, const std::string& reason) {
  44. {
  45. std::lock_guard<std::mutex> lock(reason_mutex_);
  46. read_only_reason_ = value ? reason : "";
  47. }
  48. bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
  49. if (prev != value) {
  50. if (value) {
  51. spdlog::error("Database entered READ-ONLY mode: {}", reason);
  52. } else {
  53. spdlog::info("Database unlocked -- writes accepted");
  54. }
  55. }
  56. }
  57. bool DatabaseService::initialize() {
  58. spdlog::info("Initializing database service (node: {})", config_.nodeId);
  59. try {
  60. // Create data directory if needed
  61. std::error_code ec;
  62. std::filesystem::create_directories(config_.dataDirectory, ec);
  63. if (ec) {
  64. spdlog::error("Failed to create data directory: {}", ec.message());
  65. return false;
  66. }
  67. setupComponents();
  68. // Initialize encryption
  69. if (config_.encryptionEnabled) {
  70. if (!encryption_->initialize()) {
  71. spdlog::error("Failed to initialize encryption");
  72. return false;
  73. }
  74. }
  75. // Recover from persistence
  76. recovery_outcome_ = persistence_->recover(*store_);
  77. #if defined(__GLIBC__) && !defined(__APPLE__)
  78. // v1.9.3 — release freelist pages accumulated during recovery. v1.9.1
  79. // added trim at end of loadSnapshot, but the WAL replay phase that
  80. // runs afterward (`persistence_->recover`'s `replayWal` step) also
  81. // burns through GBs of small Document JSON allocations whose pages
  82. // sit on the per-thread freelist with no subsequent allocation to
  83. // shake them loose. On Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md update 15:05)
  84. // this was 5.7 GB at 23 min uptime — fully reclaimable via
  85. // malloc_trim, just nothing called it. Paired with the periodic
  86. // every-5-minute trim in MemoryStore::logMemoryCheck, so any
  87. // post-boot bloat that escapes this trim gets cleaned up shortly.
  88. ::malloc_trim(0);
  89. #endif
  90. if (recovery_outcome_.isFailure()) {
  91. const std::string modeStr =
  92. recoveryModeToString(config_.persistenceConfig.recoveryMode);
  93. spdlog::error("");
  94. spdlog::error("+------------------------------------------------------------------+");
  95. spdlog::error("| RECOVERY REFUSED |");
  96. spdlog::error("| |");
  97. spdlog::error("| Mode: {}", modeStr);
  98. spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
  99. spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
  100. spdlog::error("| |");
  101. spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
  102. spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
  103. spdlog::error("| |");
  104. spdlog::error("| To escalate, restart with one of: |");
  105. spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
  106. spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
  107. spdlog::error("| --recovery-mode=best_effort Try all of the above |");
  108. spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
  109. spdlog::error("| |");
  110. spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
  111. spdlog::error("| |");
  112. spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
  113. spdlog::error("+------------------------------------------------------------------+");
  114. throw std::runtime_error("recovery failed; refusing to start");
  115. }
  116. // Auto-readonly mode on non-trivial recovery
  117. if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
  118. std::string reason;
  119. switch (recovery_outcome_.kind) {
  120. case RecoveryOutcome::Kind::SnapshotFellBack:
  121. reason = "fell back to snapshot " +
  122. recovery_outcome_.snapshotUsed.filename().string() +
  123. " because " +
  124. recovery_outcome_.expectedSnapshot.filename().string() +
  125. " failed: " + recovery_outcome_.failureReason;
  126. break;
  127. case RecoveryOutcome::Kind::WalOnlyReplay:
  128. reason = "WAL-only replay, no snapshot loaded (" +
  129. std::to_string(recovery_outcome_.walEntriesReplayed) +
  130. " entries)";
  131. break;
  132. case RecoveryOutcome::Kind::ForcedEmpty:
  133. reason = "forced empty by operator (--recovery-mode=force_empty)";
  134. break;
  135. default:
  136. reason = "non-trivial recovery";
  137. break;
  138. }
  139. reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
  140. "or restart with --force-readwrite to bypass this check.";
  141. setReadOnly(true, reason);
  142. spdlog::error("");
  143. spdlog::error("+------------------------------------------------------------------+");
  144. spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
  145. spdlog::error("| recovery. |");
  146. spdlog::error("| |");
  147. spdlog::error("| Reason: {}", reason);
  148. spdlog::error("| |");
  149. spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
  150. spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
  151. spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
  152. spdlog::error("+------------------------------------------------------------------+");
  153. }
  154. // Set replication sequence after recovery (WAL sequence is now known)
  155. replication_->setSequence(persistence_->currentWalSequence());
  156. // v1.8.0 — start the persistence manager before loadFromStore /
  157. // migrations so any system-collection writes those phases produce
  158. // (view docs, _collection_meta entries, _migrations recordings)
  159. // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
  160. // started later in start(), which silently dropped those writes
  161. // (running_=false → logInsert no-op). That meant migrated views
  162. // only "survived" because the runner re-created them every boot,
  163. // and a manually-created view that landed during the racy startup
  164. // window (before full readiness) could be lost.
  165. if (!persistence_->start()) {
  166. spdlog::error("Failed to start persistence manager before migrations");
  167. return false;
  168. }
  169. // Load view definitions from the _views system collection (which is now
  170. // populated by the persistence recovery above).
  171. view_manager_->loadFromStore();
  172. // Load per-collection configs from the _collection_meta system collection.
  173. // Must happen AFTER persistence recovery and BEFORE migrations so any
  174. // migration-created documents are stamped with the correct precision.
  175. config_manager_->loadFromStore();
  176. policy_manager_->loadFromStore();
  177. relation_manager_->loadFromStore();
  178. applyRelationDeclarations();
  179. // v2.11.0 close-out — teach the TTL sweeper about relations. Installed
  180. // HERE, after loadFromStore() and the arming pass, deliberately: the
  181. // hook consults the declaration cache and the reverse index, and an
  182. // expiry that fired before either was ready would have decided from an
  183. // empty cache. Until this line the sweeper behaves exactly as it did
  184. // pre-v2.11.0 (which is also what every unit fixture that never
  185. // installs the hook keeps doing).
  186. store_->setTtlExpiryRelationHook(
  187. [this](const std::string& qualifiedCollection, const std::string& id,
  188. bool firstAttempt) {
  189. return ttlExpiryRelationDecision(qualifiedCollection, id, firstAttempt);
  190. });
  191. // v2.9.0 — re-apply persisted index declarations to each project's LMDB
  192. // store. This is load-bearing, not bookkeeping: the declaration is what
  193. // makes the write path maintain an index, and the planner consults an
  194. // index purely on the declaration's word. If this step were skipped, a
  195. // restart would leave indexes recorded but unmaintained, and queries
  196. // would be served from a frozen index - stale rows returned as current,
  197. // with nothing logged.
  198. applyIndexDeclarations();
  199. // v2.11.0 final review (finding 4) — THE POST-REPLAY RE-MIRROR PASS
  200. // RUNS HERE, and the position is load-bearing.
  201. //
  202. // PersistenceManager::recover() (above, before any of the arming
  203. // steps) only collects the id list. The pass writes documents through
  204. // LmdbDocumentStore::put(), which reads indexed_fields(),
  205. // unique_fields() and relations() LIVE and maintains every index
  206. // inside the document's own write transaction. Run from inside
  207. // recover(), all three maps were still empty, so it repaired the
  208. // document and left every posting derived from it stale: an
  209. // index-served query then returns the row under its OLD value and
  210. // misses it under its new one - silently wrong rows, which is exactly
  211. // what putting maintainIndexes() inside the transaction exists to
  212. // prevent, and which bit any install with a v2.9 index declared
  213. // whether or not it uses relations. It also made the reverse-index
  214. // half of relation_cascade.hpp's convergence claim false, and made
  215. // UniqueViolation (and therefore the pass's own retry phase)
  216. // unreachable.
  217. //
  218. // Must be after applyRelationDeclarations() AND
  219. // applyIndexDeclarations(); backfillIntoDocStore() below already sits
  220. // at this point for the same reason. Never throws.
  221. persistence_->runPendingRemirror(*store_, recovery_outcome_);
  222. // Run migrations if enabled
  223. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  224. if (!runMigrations()) {
  225. if (config_.migrations.failOnError) {
  226. spdlog::error("Failed to run migrations");
  227. return false;
  228. }
  229. spdlog::warn("Some migrations failed, continuing anyway");
  230. }
  231. }
  232. // v2.0 Stage 4 — synchronous backfill into doc_store_ before
  233. // serving. Without this, only post-boot writes land in LMDB and
  234. // the read-flip downstream would see an empty mirror.
  235. backfillIntoDocStore();
  236. // v2.4.4 — placement audit. Reports documents sitting in a sub-db
  237. // other than the one they declare, which is the signature of a
  238. // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
  239. // advisory: it never blocks startup, because a misplacement is a
  240. // data-location problem an operator repairs offline with
  241. // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
  242. // service on the other 99% of the dataset.
  243. auditSubdbPlacement();
  244. // v2.6.0 — stamp `project: "default"` onto file records written before
  245. // files were namespaced. Idempotent, and advisory: a file-metadata
  246. // stamp is not a reason to refuse service, so failures warn only.
  247. if (files_) {
  248. try {
  249. const uint32_t stamped = files_->stampMissingProjects();
  250. if (stamped > 0) {
  251. spdlog::info("v2.6.0 file migration: stamped {} legacy file "
  252. "record(s) with project 'default'", stamped);
  253. } else {
  254. spdlog::debug("v2.6.0 file migration: no legacy file records");
  255. }
  256. } catch (const std::exception& e) {
  257. spdlog::warn("v2.6.0 file migration failed: {}", e.what());
  258. }
  259. }
  260. // v2.11.0 close-out — LAST ACT OF THE BOOT PATH, and the position is
  261. // load-bearing. Everything above that can bump the drift counter (the
  262. // post-replay re-mirror pass, backfillIntoDocStore(), a malformed
  263. // legacy collection key) is now behind the baseline, so
  264. // mirrorDriftSinceReady() reports only drift a LIVE write caused.
  265. // Destructive relation policies gate on that, not on the raw counter:
  266. // see MemoryStore::markMirrorDriftBaseline() for the trap this closes
  267. // (one unrepairable row disabling every cascade/set_null delete and
  268. // every CreateRelation for the process's life, with an error message
  269. // telling the operator to restart, which re-incurs it). Reads keep
  270. // gating on the RAW counter - a stale row genuinely means MemoryStore
  271. // is ahead, and that fallback must stay.
  272. store_->markMirrorDriftBaseline();
  273. if (store_->mirrorDriftBaseline() > 0) {
  274. spdlog::warn("mirror drift at READY: {} - accrued on the boot path (see the "
  275. "ERROR lines above for the exact rows). Reads for this process "
  276. "will be served from MemoryStore rather than LMDB. Destructive "
  277. "relation policies are NOT disabled by this, but the rows named "
  278. "above are still stale in LMDB until each is rewritten through "
  279. "an ordinary write; a restart re-attempts and, if the cause "
  280. "persists, re-incurs the same count.",
  281. store_->mirrorDriftBaseline());
  282. }
  283. spdlog::info("Database service initialized successfully");
  284. return true;
  285. } catch (const std::exception& e) {
  286. spdlog::error("Failed to initialize database service: {}", e.what());
  287. return false;
  288. }
  289. }
  290. void DatabaseService::migrateLegacyEnvToDefaultProject() {
  291. const auto legacy = config_.dataDirectory / "env";
  292. const auto target = config_.dataDirectory / "projects" /
  293. smartbotic::database::kDefaultProject / "env";
  294. std::error_code ec;
  295. const bool legacy_exists = std::filesystem::exists(legacy, ec);
  296. const bool target_exists = std::filesystem::exists(target, ec);
  297. if (!legacy_exists) return; // fresh install or already migrated
  298. if (target_exists) {
  299. spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
  300. "refusing to start. Inspect manually; the safe move is "
  301. "to either delete the legacy dir (if you confirm it's a "
  302. "leftover) or stop and contact ops.",
  303. legacy.string(), target.string());
  304. throw std::runtime_error("v2.3 storage migration: ambiguous layout");
  305. }
  306. std::filesystem::create_directories(target.parent_path(), ec);
  307. if (ec) {
  308. throw std::runtime_error("v2.3 storage migration: cannot create '"
  309. + target.parent_path().string() + "': " + ec.message());
  310. }
  311. std::filesystem::rename(legacy, target, ec);
  312. if (ec) {
  313. throw std::runtime_error("v2.3 storage migration: rename '"
  314. + legacy.string() + "' -> '"
  315. + target.string() + "' failed: " + ec.message());
  316. }
  317. spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
  318. legacy.string(), target.string());
  319. }
  320. smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
  321. return docStore(smartbotic::database::kDefaultProject);
  322. }
  323. smartbotic::db::storage::DocumentStore*
  324. DatabaseService::docStore(std::string_view project) noexcept {
  325. if (!projects_) return nullptr;
  326. return projects_->get(project);
  327. }
  328. std::vector<std::string> DatabaseService::listProjects() const {
  329. if (!projects_) return {};
  330. return projects_->listOnDisk();
  331. }
  332. bool DatabaseService::createProject(const std::string& name, std::string& error) {
  333. if (!projects_) {
  334. error = "project registry not initialized";
  335. return false;
  336. }
  337. return projects_->create(name, error);
  338. }
  339. bool DatabaseService::dropProject(const std::string& name, std::string& error) {
  340. if (!projects_) {
  341. error = "project registry not initialized";
  342. return false;
  343. }
  344. // v2.11.0 close-out — capture the relation declarations belonging to this
  345. // project BEFORE the drop. Relations are validated same-project at
  346. // creation (no LMDB transaction spans two envs), so `child` and `parent`
  347. // are always in the same project as `name` itself; listRelations(name)
  348. // therefore names every declaration the drop invalidates. Captured first
  349. // because listRelations needs the project to still be nameable and, more
  350. // importantly, because un-arming needs the store to still exist.
  351. std::vector<RelationInfo> doomed;
  352. if (relation_manager_) {
  353. try {
  354. doomed = relation_manager_->listRelations(name);
  355. } catch (const std::exception& e) {
  356. spdlog::warn("v2.11 relations: could not enumerate relations of project '{}' "
  357. "before dropping it ({}); its declarations may be left behind",
  358. name, e.what());
  359. }
  360. }
  361. if (!projects_->drop(name, error)) return false;
  362. // ---- The drop succeeded; the declarations now point at a namespace that
  363. // no longer exists. Sweep them out of the global `_relations` collection
  364. // and un-arm each affected child collection.
  365. //
  366. // Order (drop first, sweep second) is deliberate: the registry is the one
  367. // that refuses "default" and rejects unknown names, so sweeping first would
  368. // destroy declarations for a project whose drop then failed. The cost of
  369. // this order is that the per-project store is usually already gone by the
  370. // time we try to un-arm, which makes the un-arm a no-op - correct, since a
  371. // store that no longer exists cannot be maintaining a reverse index. It
  372. // still runs, because ProjectStoreRegistry may hold a live
  373. // LmdbDocumentStore for a re-created project of the same name.
  374. //
  375. // ⚠ Advisory, never fatal: the project IS dropped at this point, and a
  376. // leftover declaration is litter, not corruption (its child and parent
  377. // collections are both gone, so nothing can be enforced against them). A
  378. // failure here must not report the drop as failed.
  379. for (const auto& r : doomed) {
  380. try {
  381. std::string err;
  382. if (!relation_manager_->dropRelation(r.name, err)) {
  383. spdlog::warn("v2.11 relations: could not drop declaration '{}' left by "
  384. "dropped project '{}': {}", r.name, name, err);
  385. continue;
  386. }
  387. const auto rc = resolveCollection(r.child);
  388. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  389. docStore(rc.project));
  390. if (lmdb != nullptr) {
  391. // Empty list = "this collection has no relations", which is what
  392. // set_relations replaces the previous list with. Every relation
  393. // of a dropped project goes, so clearing the child wholesale is
  394. // exactly right here (unlike DropRelation, which must re-arm the
  395. // survivors).
  396. lmdb->set_relations(rc.collection, {});
  397. }
  398. spdlog::info("v2.11 relations: dropped declaration '{}' with the project '{}'",
  399. r.name, name);
  400. } catch (const std::exception& e) {
  401. spdlog::warn("v2.11 relations: could not clean up declaration '{}' after "
  402. "dropping project '{}': {}", r.name, name, e.what());
  403. }
  404. }
  405. // ⚠ KNOWN, NOT FIXED HERE (v2.11.0 close-out): _views, _policies and
  406. // _collection_meta have the SAME gap - ProjectStoreRegistry::drop() removes
  407. // the project's env and nothing else, so a dropped project leaves its view
  408. // definitions, access policies and per-collection configs behind in those
  409. // global system collections too. Not a shared fix: each manager keys and
  410. // caches differently (ViewManager keys `<project>:<name>`, PolicyManager
  411. // `<project>:<principal>`, CollectionConfigManager `<project>:<collection>`
  412. // and canonicalises the cache key only), so each needs its own sweep, and
  413. // PolicyManager's has a security dimension this one does not (a re-created
  414. // project inheriting a stale policy). Scoped out deliberately; recorded so
  415. // it is not rediscovered as new.
  416. return true;
  417. }
  418. bool DatabaseService::runMigrations() {
  419. if (!config_.migrations.enabled) {
  420. return true;
  421. }
  422. MigrationRunner::Config migrationConfig;
  423. migrationConfig.directory = config_.migrations.directory;
  424. migrationConfig.autoApply = config_.migrations.autoApply;
  425. migrationConfig.failOnError = config_.migrations.failOnError;
  426. migrationRunner_ = std::make_unique<MigrationRunner>(
  427. *store_, *view_manager_, *relation_manager_, migrationConfig);
  428. const bool ok = migrationRunner_->runMigrations();
  429. // v2.11.0 close-out — a `create_relation` migration op only PERSISTS the
  430. // declaration. Arming the write path and building the reverse index over
  431. // rows that already exist is what applyRelationDeclarations() does, and it
  432. // has already run for this boot (initialize() calls it before migrations),
  433. // so without this a migration-declared relation would maintain no reverse
  434. // index and enforce nothing until the NEXT restart - the "declared but not
  435. // enforcing" state this feature's self-heal exists to make unreachable.
  436. // Idempotent and cheap: re-arming an already-armed child replaces an
  437. // identical list, and the bootstrap loop skips any relation whose index
  438. // sub-db already exists. Runs even when the migration run reported failure,
  439. // because a partially-applied run may still have created a relation.
  440. applyRelationDeclarations(/*afterMigrations=*/true);
  441. return ok;
  442. }
  443. void DatabaseService::applyIndexDeclarations() {
  444. size_t applied = 0;
  445. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  446. if (cfg.indexedFields.empty() && cfg.compositeUniques.empty()) continue;
  447. try {
  448. const auto rc = resolveCollection(qualified);
  449. auto* ds = docStore(rc.project);
  450. auto* lmdb =
  451. dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  452. if (lmdb == nullptr) continue;
  453. lmdb->set_indexed_fields(rc.collection, cfg.indexedFields);
  454. // v2.11.0 T11 — arm uniqueFields the same way. This is the fix
  455. // for the exact failure mode the type was built to avoid:
  456. // uniqueFields has been persisted since T8 with no RPC or proto
  457. // surface, which was safe (nothing consulted it); now that
  458. // set_unique_fields is reachable, a restart that skipped this
  459. // call would silently stop enforcing a constraint every write
  460. // handler still advertises as active.
  461. lmdb->set_unique_fields(rc.collection, cfg.uniqueFields);
  462. // v2.12.0 — composite constraints, armed the same way and for the
  463. // same reason: skipping this would stop enforcing a constraint the
  464. // record still declares. Self-healed below if its sub-db is gone.
  465. lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
  466. for (const auto& cf : cfg.compositeUniques) {
  467. if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
  468. uint64_t rows = 0;
  469. auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
  470. if (dupes.empty()) {
  471. spdlog::warn("v2.12 composite unique: rebuilt {}#({}) over {} row(s) - "
  472. "declared but its sub-db was absent",
  473. qualified, smartbotic::db::storage::composite_display_name(cf), rows);
  474. } else {
  475. // Cannot happen through the API (declaring over duplicates is
  476. // refused). If it does, say so loudly: the constraint stays
  477. // declared and armed, but rows already violating it exist.
  478. spdlog::error("v2.12 composite unique: {}#({}) is declared but {} "
  479. "existing value combination(s) violate it (e.g. document "
  480. "'{}'); its index could not be rebuilt. Writes that would "
  481. "add another duplicate are still refused.",
  482. qualified, smartbotic::db::storage::composite_display_name(cf),
  483. dupes.size(), dupes.front().sample_id);
  484. }
  485. }
  486. ++applied;
  487. spdlog::info("v2.9 index: {} field(s) active on {} ({} unique)",
  488. cfg.indexedFields.size(), qualified, cfg.uniqueFields.size());
  489. // Self-heal a declared index whose sub-db is absent. That happens
  490. // when the KEY FORMAT VERSION in the sub-db prefix changes (v2.9.1
  491. // unified the numeric encoding, so `_idx_` became `_idx2_`), and it
  492. // would otherwise leave the declaration pointing at nothing: writes
  493. // would maintain the new index correctly, but rows written BEFORE the
  494. // upgrade would have no postings, so an indexed query would silently
  495. // return only the newer ones. Rebuilding is the only safe reading.
  496. for (const auto& field : cfg.indexedFields) {
  497. if (lmdb->index_stats(rc.collection, field).has_value()) continue;
  498. const uint64_t rows = lmdb->build_index(rc.collection, field);
  499. spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "
  500. "was declared but its sub-db was absent (key format "
  501. "change or a manual removal)",
  502. qualified, field, rows);
  503. }
  504. } catch (const std::exception& e) {
  505. // Advisory per collection: one unparseable name must not stop the
  506. // rest from being armed. Loud, because a missing declaration means
  507. // that collection's index silently stops being maintained.
  508. spdlog::error("v2.9 index: could not apply declarations for {}: {}",
  509. qualified, e.what());
  510. }
  511. }
  512. if (applied > 0) {
  513. spdlog::info("v2.9 index: applied declarations for {} collection(s)", applied);
  514. }
  515. }
  516. MemoryStore::TtlExpiryAction DatabaseService::ttlExpiryRelationDecision(
  517. const std::string& qualifiedCollection, const std::string& id, bool firstAttempt) {
  518. using Action = MemoryStore::TtlExpiryAction;
  519. // Thin binder over relations/relation_cascade.cpp's ttlExpiryDecision() -
  520. // the policy itself lives there so it is unit-testable against the same
  521. // fixtures the cascade tests use, without a DatabaseService. All this does
  522. // is resolve the per-project LMDB store and supply the replication/events
  523. // notifier.
  524. if (!relation_manager_ || !config_manager_ || !store_ || !persistence_) {
  525. return Action::Proceed;
  526. }
  527. if (qualifiedCollection.empty() || qualifiedCollection[0] == '_') return Action::Proceed;
  528. try {
  529. const auto rc = resolveCollection(qualifiedCollection);
  530. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  531. docStore(rc.project));
  532. // No LMDB substrate means no reverse index to consult, so the
  533. // pre-v2.11.0 behaviour is all that is available.
  534. if (lmdb == nullptr) return Action::Proceed;
  535. // Replication + Subscribe events, driven per mutation - the same wiring
  536. // DatabaseGrpcImpl::performRelationCascade() uses. Without it a
  537. // TTL-driven cascade would be invisible to followers and subscribers,
  538. // and a follower that never saw the child deletions diverges
  539. // permanently (the v2.3.1 class of bug).
  540. // v2.12.0 - an expiry has no caller, so every event this cascade
  541. // produces carries an explicitly EMPTY actor. Letting it default
  542. // would report a nulled child's previous writer as the cause.
  543. auto notify = [this](const std::string& coll, const std::string& docId,
  544. const std::optional<Document>& doc, EventType eventType) {
  545. notifyReplicationAndEvents(coll, docId, doc, eventType, std::string{});
  546. };
  547. // firstAttempt -> the refusal (if any) is logged at WARN; a retry of an
  548. // already-reported document logs at DEBUG. The sweeper owns that
  549. // decision because it is the only thing that knows the document has
  550. // been refused before.
  551. return smartbotic::database::ttlExpiryDecision(
  552. *relation_manager_, *lmdb, *persistence_, *store_, *config_manager_,
  553. qualifiedCollection, id, notify, firstAttempt);
  554. } catch (const std::exception& e) {
  555. // Never expire a parent whose children could not be evaluated.
  556. spdlog::error("TTL expiry of '{}/{}': could not resolve its storage ({}) - the "
  557. "document is left in place and will be retried",
  558. qualifiedCollection, id, e.what());
  559. return Action::Skip;
  560. }
  561. }
  562. void DatabaseService::applyRelationDeclarations(bool afterMigrations) {
  563. // Group by (project, bare child collection) — set_relations() is a
  564. // per-collection call on that project's LmdbDocumentStore and replaces
  565. // whatever was declared before, so every relation sharing a child
  566. // collection must land in one call.
  567. std::unordered_map<std::string,
  568. std::vector<smartbotic::db::storage::RelationRef>> byChild;
  569. // Track which project each grouping key belongs to alongside the bare
  570. // collection name, since the map key alone doesn't carry it.
  571. std::unordered_map<std::string, std::pair<std::string, std::string>> keyToProjectCollection;
  572. for (const auto& r : relation_manager_->listRelations()) {
  573. try {
  574. const auto rn = resolveCollection(r.name);
  575. const auto rc = resolveCollection(r.child);
  576. // v2.11.0 T13 — parent resolved to its bare name, same reasoning
  577. // as armRelationsForChild's mirror of this construction.
  578. const auto pc = resolveCollection(r.parent);
  579. const std::string key = rc.project + ":" + rc.collection;
  580. // v2.11.0 T13 round 2 — snapshot relationsEnforced at boot-time
  581. // arming, same reasoning as armRelationsForChild's mirror of
  582. // this construction. `key` is already the qualified child name
  583. // configFor expects.
  584. const bool enforced = config_manager_->configFor(key).relationsEnforced;
  585. byChild[key].push_back(smartbotic::db::storage::RelationRef{
  586. rn.collection, r.childField, pc.collection, r.validateOnWrite, enforced});
  587. keyToProjectCollection[key] = {rc.project, rc.collection};
  588. } catch (const std::exception& e) {
  589. // Advisory per relation: one unparseable declaration must not
  590. // stop the rest from being armed. Loud, because a skipped
  591. // relation silently maintains no reverse index for its child.
  592. spdlog::error("v2.11 relations: could not apply declaration '{}': {}",
  593. r.name, e.what());
  594. }
  595. }
  596. size_t applied = 0;
  597. for (const auto& [key, refs] : byChild) {
  598. const auto& [project, collection] = keyToProjectCollection[key];
  599. try {
  600. // ⚠ v2.11.0 close-out — getOrCreate, not get(), on the POST-MIGRATION
  601. // pass. docStore() is projects_->get(), which does NOT create an env,
  602. // and a `create_relation` migration in a project that has never been
  603. // written to has no env yet: the declaration persisted, this pass
  604. // skipped it, and the relation maintained no reverse index and
  605. // enforced NOTHING until the next restart - the exact
  606. // "declared but not enforcing" state the op was added to avoid, just
  607. // narrowed to new projects. A migration declaring a relation IS a
  608. // statement that the project exists, and the mirror resolver would
  609. // getOrCreate the same env on the first write anyway.
  610. //
  611. // The BOOT pass deliberately keeps get(): creating envs there would
  612. // resurrect the env of a project whose declarations are merely stale.
  613. auto* ds = (afterMigrations && projects_)
  614. ? projects_->getOrCreate(project)
  615. : docStore(project);
  616. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  617. if (lmdb == nullptr) continue;
  618. lmdb->set_relations(collection, refs);
  619. ++applied;
  620. spdlog::info("v2.11 relations: {} relation(s) active with child '{}:{}'",
  621. refs.size(), project, collection);
  622. // v2.11.0 T7 self-heal — mirrors applyIndexDeclarations()'s
  623. // rebuild of a declared-but-absent index sub-db, for the same
  624. // reason: a relation whose reverse index sub-db is missing is
  625. // exactly the "declared but not enforcing" bug this task exists
  626. // to close. Reachable paths that leave a relation in this state:
  627. // a snapshot/backup restored from before the sub-db existed, or
  628. // an operator manually dropping the `_relidx1_*` sub-db (there
  629. // is no dropRelation-only-the-index tool). CreateRelation's own
  630. // bootstrap scan (see database_grpc_impl.cpp) covers the normal
  631. // declare-time path; this covers everything else.
  632. //
  633. // ⚠ v2.11.0 close-out (review minor 2) — the SAME code path is the
  634. // NORMAL, expected one for a relation a migration just declared:
  635. // migrations run after this pass, so runMigrations() calls it again
  636. // and the brand-new relation legitimately has no sub-db yet. Logging
  637. // "declared but its sub-db was absent (restored snapshot or a manual
  638. // removal)" at WARN there describes a fault that did not happen.
  639. // `afterMigrations` distinguishes the two so the text and the level
  640. // match the event.
  641. for (const auto& ref : refs) {
  642. if (lmdb->relation_index_exists(ref.name)) continue;
  643. const uint64_t rows =
  644. lmdb->build_relation_index(ref.name, collection, ref.childField);
  645. if (afterMigrations) {
  646. spdlog::info("v2.11 relations: built the reverse index for '{}' over {} "
  647. "existing row(s) in '{}:{}' - a migration declared this "
  648. "relation on this boot",
  649. ref.name, rows, project, collection);
  650. } else {
  651. spdlog::warn("v2.11 relations: rebuilt '{}' over {} row(s) in '{}:{}' - the "
  652. "relation was declared but its reverse index sub-db was absent "
  653. "(restored snapshot predating it, or a manual removal)",
  654. ref.name, rows, project, collection);
  655. }
  656. }
  657. } catch (const std::exception& e) {
  658. spdlog::error("v2.11 relations: could not apply declarations for '{}:{}': {}",
  659. project, collection, e.what());
  660. }
  661. }
  662. if (applied > 0) {
  663. spdlog::info("v2.11 relations: applied declarations for {} child collection(s)", applied);
  664. }
  665. }
  666. void DatabaseService::auditSubdbPlacement() {
  667. if (!projects_) return;
  668. for (const auto& name : projects_->listOpen()) {
  669. auto h = projects_->getHandle(name);
  670. if (!h.env) continue;
  671. try {
  672. // audit_env(), NOT audit(). The path-taking overload opens a
  673. // second MDB_env on the same file; closing it would drop the
  674. // POSIX record locks this process already holds for `h.env`
  675. // (POSIX locks are per-process, and closing any fd on a file
  676. // releases all of them), leaving every later mdb_txn_begin
  677. // failing EINVAL. Borrow the open handle instead.
  678. const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
  679. if (rep.misplaced.empty()) {
  680. spdlog::debug("placement audit: project '{}' consistent ({} rows)",
  681. name, rep.rows_scanned);
  682. continue;
  683. }
  684. // Summarise per (physical -> declared home) pair; one line per
  685. // affected document would be unreadable at scale.
  686. std::map<std::string, uint64_t> pairs;
  687. for (const auto& m : rep.misplaced) {
  688. ++pairs[m.physical_subdb + " -> " + m.home_subdb];
  689. }
  690. spdlog::error("placement audit: project '{}' has {} document(s) in the "
  691. "wrong sub-db. Reads served from LMDB will not find them "
  692. "under their own collection. Repair offline with: "
  693. "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
  694. name, rep.misplaced.size(), h.env->path(), name);
  695. for (const auto& [pair, count] : pairs) {
  696. spdlog::error("placement audit: {} document(s) {}", count, pair);
  697. }
  698. } catch (const std::exception& e) {
  699. // Advisory only — a failed audit must not take the service down.
  700. spdlog::warn("placement audit: project '{}' could not be audited: {}",
  701. name, e.what());
  702. }
  703. }
  704. }
  705. bool DatabaseService::backfillIntoDocStore() {
  706. if (!projects_) {
  707. // Registry open failed earlier; nothing to back-fill into.
  708. return true;
  709. }
  710. // v2.3 — MemoryStore stores collection keys in qualified form
  711. // ("project:collection"). For the default project (back-compat
  712. // path) the marker check operates on the default env. Skip when
  713. // already migrated.
  714. auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
  715. if (handle.env) {
  716. try {
  717. if (smartbotic::db::storage::migration_complete(*handle.env)) {
  718. spdlog::info("v2.3 backfill: default project already migrated, skipping");
  719. return true;
  720. }
  721. } catch (const std::exception& e) {
  722. spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
  723. "treating default env as fresh and proceeding",
  724. e.what());
  725. }
  726. }
  727. const auto collections = store_->listCollections();
  728. uint64_t total_docs = 0;
  729. uint64_t total_failures = 0;
  730. auto t0 = std::chrono::steady_clock::now();
  731. for (const auto& qualified : collections) {
  732. if (qualified.empty() || qualified[0] == '_') continue;
  733. // Each qualified key parses to (project, collection); route the
  734. // mirror write to the right project's env.
  735. smartbotic::database::ProjectCollection pc;
  736. try {
  737. pc = smartbotic::database::parseProjectCollection(qualified);
  738. } catch (const std::exception&) {
  739. // Legacy unqualified key — treat as default project.
  740. pc = {std::string(smartbotic::database::kDefaultProject), qualified};
  741. }
  742. auto* ds = projects_->getOrCreate(pc.project);
  743. if (!ds) {
  744. ++total_failures;
  745. continue;
  746. }
  747. const auto docs = store_->getAllDocuments(qualified);
  748. for (const auto& doc : docs) {
  749. std::optional<Document> opt_doc(doc);
  750. const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
  751. // v2.11.0 T13 round 2 — UniqueViolation/MissingParentReference are
  752. // rethrown UNCAUGHT by applyDualWriteMirror (deliberately - see
  753. // both exceptions' header comments), unlike a genuine mirror
  754. // fault which is swallowed and only shows up as a drift bump
  755. // below. Uncaught here would escape this loop, backfillIntoDocStore
  756. // and initialize() itself, refusing startup over one rejected row.
  757. // Practically unreachable today - backfill only runs migrating a
  758. // v1.x dataset, which predates both `_relations` and unique-index
  759. // declarations - but catching removes that reasoning burden for
  760. // the next reader, same as any other row here that fails.
  761. try {
  762. smartbotic::db::storage::applyDualWriteMirror(
  763. ds, mirror_healthy_, mirror_drift_count_,
  764. pc.collection, doc.id, opt_doc, EventType::INSERT);
  765. } catch (const std::exception& e) {
  766. spdlog::error("v2.3 backfill: mirror rejected {}/{}: {} - row stays "
  767. "in MemoryStore only, LMDB does not have it",
  768. qualified, doc.id, e.what());
  769. ++total_failures;
  770. }
  771. if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
  772. ++total_failures;
  773. }
  774. ++total_docs;
  775. if (total_docs % 10000 == 0) {
  776. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  777. const std::string status = "STATUS=v2.3 backfill: " +
  778. std::to_string(total_docs) + " docs mirrored";
  779. sd_notify(0, status.c_str());
  780. spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
  781. total_docs, total_failures);
  782. }
  783. }
  784. }
  785. const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  786. std::chrono::steady_clock::now() - t0).count();
  787. if (total_failures == 0) {
  788. // Stamp schema_version=2 on every opened project env. Subsequent
  789. // boots short-circuit at migration_complete().
  790. for (const auto& name : projects_->listOpen()) {
  791. auto h = projects_->getHandle(name);
  792. if (!h.env) continue;
  793. try {
  794. smartbotic::db::storage::mark_migration_complete(*h.env);
  795. } catch (const std::exception& e) {
  796. spdlog::warn("v2.3 backfill: schema_version marker write failed for "
  797. "project '{}': {}", name, e.what());
  798. }
  799. }
  800. spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
  801. total_docs, collections.size(), elapsed);
  802. } else {
  803. spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
  804. "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
  805. total_failures, total_docs, elapsed);
  806. }
  807. return true;
  808. }
  809. void DatabaseService::start() {
  810. if (running_.exchange(true)) {
  811. return;
  812. }
  813. spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
  814. // Start components
  815. store_->start();
  816. persistence_->start();
  817. events_->start();
  818. files_->start();
  819. if (config_.replicationEnabled) {
  820. replication_->start();
  821. // Set initial local collections for discovery
  822. replication_->setLocalCollections(store_->listCollections());
  823. }
  824. // Start gRPC server
  825. startGrpcServer();
  826. spdlog::info("Database service started");
  827. }
  828. void DatabaseService::stop() {
  829. if (!running_.exchange(false)) {
  830. return;
  831. }
  832. spdlog::info("Stopping database service...");
  833. // Stop gRPC server first
  834. stopGrpcServer();
  835. // Stop components in reverse order
  836. if (replication_) {
  837. replication_->stop();
  838. }
  839. if (files_) {
  840. files_->stop();
  841. }
  842. if (events_) {
  843. events_->stop();
  844. }
  845. if (persistence_ && store_) {
  846. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  847. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  848. // replay" which trips auto-readonly mode. This makes ordinary
  849. // restarts pass through cleanly without needing
  850. // `smartbotic-db-cli unlock`.
  851. //
  852. // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
  853. // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
  854. // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
  855. // RSS hit 11 GB (live state + uncompressed serialize buffer), and
  856. // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
  857. // tells systemd we're working — same protocol the recovery path
  858. // uses during startup. Paired with TimeoutStopSec=300 in the unit
  859. // file as the static cap.
  860. #ifdef HAVE_SYSTEMD
  861. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  862. sd_notify(0, "STATUS=Writing final snapshot");
  863. #endif
  864. try {
  865. persistence_->forceSnapshot(*store_);
  866. spdlog::info("Final snapshot taken on shutdown");
  867. } catch (const std::exception& e) {
  868. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  869. "boot may be WAL-only and trip auto-readonly mode", e.what());
  870. }
  871. }
  872. if (persistence_) {
  873. persistence_->stop();
  874. }
  875. if (store_) {
  876. store_->stop();
  877. }
  878. spdlog::info("Database service stopped");
  879. }
  880. void DatabaseService::wait() {
  881. if (serverThread_.joinable()) {
  882. serverThread_.join();
  883. }
  884. }
  885. void DatabaseService::signalStop() {
  886. stopRequested_ = true;
  887. stop();
  888. }
  889. nlohmann::json DatabaseService::getStats() const {
  890. nlohmann::json stats;
  891. if (store_) {
  892. auto storeStats = store_->getStats();
  893. stats["documents"] = storeStats.totalDocuments;
  894. stats["collections"] = storeStats.totalCollections;
  895. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  896. stats["inserts"] = storeStats.insertCount;
  897. stats["updates"] = storeStats.updateCount;
  898. stats["deletes"] = storeStats.deleteCount;
  899. stats["queries"] = storeStats.queryCount;
  900. }
  901. if (persistence_) {
  902. auto persistStats = persistence_->getStats();
  903. stats["wal_sequence"] = persistStats.walSequence;
  904. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  905. stats["snapshot_count"] = persistStats.snapshotCount;
  906. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  907. }
  908. if (events_) {
  909. stats["subscriptions"] = events_->subscriptionCount();
  910. }
  911. return stats;
  912. }
  913. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  914. std::ifstream file(configPath);
  915. if (!file) {
  916. throw std::runtime_error("Failed to open config file: " + configPath.string());
  917. }
  918. nlohmann::json json;
  919. file >> json;
  920. return parseConfig(json);
  921. }
  922. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  923. Config config;
  924. // Check for both "storage" and "database" keys for backward compatibility
  925. const nlohmann::json* dbConfig = nullptr;
  926. if (json.contains("database")) {
  927. dbConfig = &json["database"];
  928. } else if (json.contains("storage")) {
  929. dbConfig = &json["storage"];
  930. }
  931. if (dbConfig) {
  932. const auto& db = *dbConfig;
  933. config.nodeId = db.value("node_id", config.nodeId);
  934. config.bindAddress = db.value("bind_address", config.bindAddress);
  935. config.rpcPort = db.value("rpc_port", config.rpcPort);
  936. // v2.4 — parse the per-listener fleet. If "listeners" is set,
  937. // it overrides the legacy bind_address+rpc_port. Otherwise we
  938. // synthesise one listener below using those legacy fields.
  939. if (db.contains("listeners") && db["listeners"].is_array()) {
  940. for (const auto& l : db["listeners"]) {
  941. ListenerConfig lc;
  942. lc.bind = l.value("bind", lc.bind);
  943. lc.port = l.value("port", lc.port);
  944. if (l.contains("tls") && l["tls"].is_object()) {
  945. const auto& t = l["tls"];
  946. lc.tls.enabled = t.value("enabled", false);
  947. lc.tls.cert_path = t.value("cert_path", std::string{});
  948. lc.tls.key_path = t.value("key_path", std::string{});
  949. lc.tls.auto_self_signed_if_missing =
  950. t.value("auto_self_signed_if_missing", true);
  951. }
  952. if (l.contains("auth") && l["auth"].is_object()) {
  953. const auto& a = l["auth"];
  954. lc.auth.required = a.value("required", false);
  955. if (a.contains("keys") && a["keys"].is_array()) {
  956. for (const auto& k : a["keys"]) {
  957. // v2.7.0 — a key is either a bare token (v2.4-v2.6
  958. // shape) or {"name","key"}. The name becomes the
  959. // principal that policy is written against; a bare
  960. // token maps to the reserved `unnamed`, so old
  961. // configs keep authenticating but cannot be told
  962. // apart in a policy until they are named.
  963. if (k.is_string()) {
  964. lc.auth.keys.push_back(
  965. {smartbotic::database::auth::kPrincipalUnnamed,
  966. k.get<std::string>()});
  967. } else if (k.is_object()) {
  968. const std::string name = k.value("name", std::string{});
  969. const std::string key = k.value("key", std::string{});
  970. if (key.empty()) {
  971. spdlog::warn("auth: listener {}:{} has a key entry "
  972. "with no `key` value - skipped",
  973. lc.bind, lc.port);
  974. continue;
  975. }
  976. lc.auth.keys.push_back(
  977. {name.empty()
  978. ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
  979. : name,
  980. key});
  981. }
  982. }
  983. }
  984. }
  985. config.listeners.push_back(std::move(lc));
  986. }
  987. }
  988. // Expand environment variables in data directory
  989. std::string dataDir = db.value("data_directory", "");
  990. if (dataDir.find("${HOME}") != std::string::npos) {
  991. const char* home = std::getenv("HOME");
  992. if (home) {
  993. size_t pos = dataDir.find("${HOME}");
  994. dataDir.replace(pos, 7, home);
  995. }
  996. }
  997. config.dataDirectory = dataDir;
  998. // Migrations settings
  999. if (db.contains("migrations")) {
  1000. auto& migrations = db["migrations"];
  1001. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  1002. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  1003. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  1004. std::string migDir = migrations.value("directory", "");
  1005. if (migDir.find("${HOME}") != std::string::npos) {
  1006. const char* home = std::getenv("HOME");
  1007. if (home) {
  1008. size_t pos = migDir.find("${HOME}");
  1009. migDir.replace(pos, 7, home);
  1010. }
  1011. }
  1012. config.migrations.directory = migDir;
  1013. }
  1014. // Memory eviction settings
  1015. if (db.contains("memory")) {
  1016. auto& memory = db["memory"];
  1017. // Deprecation log. These knobs control MemoryStore eviction, which
  1018. // is still active for the MemoryStore-side mirror but does NOT bound
  1019. // RSS since v2.0 (LMDB mmap is the dominant RSS contributor). The
  1020. // substrate-level equivalent is the LMDB env mapsize and the OS page
  1021. // cache.
  1022. //
  1023. // They disappear when the write-handler migration deletes MemoryStore
  1024. // (docs/ROADMAP.md, "Pending"). An earlier revision of this comment
  1025. // promised a v2.1 rename to `buffer_pool_size_mb` "per the Phase C
  1026. // plan"; that plan was superseded by LMDB before it was written, no
  1027. // such knob exists, and the rename is not planned.
  1028. for (const char* deprecated : {"max_memory_mb",
  1029. "eviction_threshold_percent",
  1030. "eviction_target_percent",
  1031. "eviction_check_interval_ms",
  1032. "eviction_chunk_size",
  1033. "eviction_chunk_pause_ms",
  1034. "max_eviction_passes_per_trigger",
  1035. "hot_write_floor_ms",
  1036. "memory_priority"}) {
  1037. if (memory.contains(deprecated)) {
  1038. spdlog::warn("v2.0 deprecation: storage.memory.{} is deprecated "
  1039. "and will be removed in v2.1. v2.0 RSS is bounded "
  1040. "by the LMDB env mapsize + OS page cache, not by "
  1041. "MemoryStore eviction. Setting still applied to "
  1042. "the MemoryStore mirror for back-compat.",
  1043. deprecated);
  1044. }
  1045. }
  1046. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  1047. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  1048. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  1049. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  1050. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  1051. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  1052. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  1053. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  1054. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  1055. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  1056. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  1057. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  1058. // v1.7.0 T10 — eviction burst event threshold
  1059. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  1060. // v2.4.3 — eviction drain cap (0 disables)
  1061. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  1062. }
  1063. // v2.11.0 close-out — TTL sweep budgets. Its own block rather than
  1064. // `memory`, because these bound expiry work per sweep, not memory.
  1065. if (db.contains("ttl")) {
  1066. auto& ttl = db["ttl"];
  1067. config.ttlMaxCandidatesPerSweep =
  1068. ttl.value("max_candidates_per_sweep", config.ttlMaxCandidatesPerSweep);
  1069. config.ttlMaxBlockedRetriesPerSweep =
  1070. ttl.value("max_blocked_retries_per_sweep", config.ttlMaxBlockedRetriesPerSweep);
  1071. config.ttlBlockedRetrySweeps =
  1072. ttl.value("blocked_retry_sweeps", config.ttlBlockedRetrySweeps);
  1073. config.ttlBlockedSummarySweeps =
  1074. ttl.value("blocked_summary_sweeps", config.ttlBlockedSummarySweeps);
  1075. }
  1076. // Persistence settings
  1077. if (db.contains("persistence")) {
  1078. auto& persistence = db["persistence"];
  1079. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  1080. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  1081. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  1082. // Snapshot durability (NEW in v1.6.1)
  1083. if (persistence.contains("snapshots")) {
  1084. const auto& snap = persistence["snapshots"];
  1085. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  1086. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  1087. }
  1088. // Recovery (NEW in v1.6.1)
  1089. if (persistence.contains("recovery")) {
  1090. const auto& rec = persistence["recovery"];
  1091. std::string modeStr = rec.value("mode", std::string("normal"));
  1092. try {
  1093. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  1094. } catch (const std::exception& e) {
  1095. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  1096. modeStr, e.what());
  1097. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  1098. }
  1099. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  1100. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  1101. }
  1102. }
  1103. // File settings
  1104. if (db.contains("files")) {
  1105. auto& files = db["files"];
  1106. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  1107. // v2.8.0 — this interval now drives the file EXPIRY sweep as well
  1108. // as orphan cleanup, so accept the plainer name too. The original
  1109. // key kept working; nothing read either of them before 2.8.0
  1110. // because there was no sweeper thread at all.
  1111. config.fileCleanupIntervalSec =
  1112. files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  1113. config.fileCleanupIntervalSec =
  1114. files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
  1115. // v2.8.0 — default retention per file type. The analogue of a
  1116. // collection's defaultTtlSeconds, so retention is an operator
  1117. // setting rather than something every uploader must remember.
  1118. //
  1119. // "default_ttl_seconds": {
  1120. // "acme:generated": 86400, // one project, one type
  1121. // "generated": 604800, // any project
  1122. // "acme:*": 2592000, // every type in one project
  1123. // "*": 0 // everything (0 = keep)
  1124. // }
  1125. if (files.contains("default_ttl_seconds") &&
  1126. files["default_ttl_seconds"].is_object()) {
  1127. for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
  1128. if (v.is_number_unsigned()) {
  1129. config.fileDefaultTtlByType[k] = v.get<uint32_t>();
  1130. }
  1131. }
  1132. }
  1133. if (files.contains("allowed_types")) {
  1134. for (const auto& type : files["allowed_types"]) {
  1135. config.allowedFileTypes.push_back(type.get<std::string>());
  1136. }
  1137. }
  1138. }
  1139. // Encryption settings
  1140. if (db.contains("encryption")) {
  1141. auto& encryption = db["encryption"];
  1142. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  1143. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  1144. std::string keyFile = encryption.value("key_file", "");
  1145. if (keyFile.find("${HOME}") != std::string::npos) {
  1146. const char* home = std::getenv("HOME");
  1147. if (home) {
  1148. size_t pos = keyFile.find("${HOME}");
  1149. keyFile.replace(pos, 7, home);
  1150. }
  1151. }
  1152. config.keyFilePath = keyFile;
  1153. }
  1154. // Replication settings
  1155. if (db.contains("replication")) {
  1156. auto& replication = db["replication"];
  1157. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  1158. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  1159. if (replication.contains("peers")) {
  1160. for (const auto& peer : replication["peers"]) {
  1161. config.peerAddresses.push_back(peer.get<std::string>());
  1162. }
  1163. }
  1164. }
  1165. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  1166. if (db.contains("grpc")) {
  1167. const auto& grpc = db["grpc"];
  1168. config.grpc.maxReceiveMessageSizeMb =
  1169. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  1170. config.grpc.maxSendMessageSizeMb =
  1171. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  1172. config.grpc.resourceQuotaMemoryMb =
  1173. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  1174. config.grpc.maxConcurrentSubscribeStreams =
  1175. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  1176. config.grpc.maxConcurrentFileStreams =
  1177. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  1178. }
  1179. }
  1180. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  1181. // one from the legacy bind_address + rpc_port fields. This is what
  1182. // every existing v2.3 deployment will hit on first v2.4 boot —
  1183. // their configs don't know about listeners[] yet, and they get
  1184. // exactly the same listener they had before.
  1185. if (config.listeners.empty()) {
  1186. ListenerConfig legacy;
  1187. legacy.bind = config.bindAddress;
  1188. legacy.port = config.rpcPort;
  1189. legacy.tls.enabled = false;
  1190. legacy.auth.required = false;
  1191. config.listeners.push_back(std::move(legacy));
  1192. }
  1193. return config;
  1194. }
  1195. void DatabaseService::setupComponents() {
  1196. // v2.3 multi-project storage substrate.
  1197. //
  1198. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  1199. // project always exists and is what v2.0-v2.2 clients (which don't
  1200. // address projects) implicitly use.
  1201. //
  1202. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  1203. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  1204. // atomically moves it under `projects/default/env/` before the
  1205. // registry opens.
  1206. migrateLegacyEnvToDefaultProject();
  1207. try {
  1208. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  1209. constexpr uint32_t kMaxDbs = 1024;
  1210. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  1211. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  1212. const auto opened = projects_->openExisting();
  1213. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  1214. opened.size(),
  1215. [&opened]() {
  1216. std::string s;
  1217. for (size_t i = 0; i < opened.size(); ++i) {
  1218. if (i) s += ", ";
  1219. s += opened[i];
  1220. }
  1221. return s;
  1222. }());
  1223. } catch (const std::exception& e) {
  1224. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  1225. "service cannot start without LMDB; bailing",
  1226. (config_.dataDirectory / "projects").string(), e.what());
  1227. projects_.reset();
  1228. throw;
  1229. }
  1230. // Create memory store with eviction config
  1231. MemoryStore::Config storeConfig;
  1232. storeConfig.nodeId = config_.nodeId;
  1233. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  1234. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  1235. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  1236. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  1237. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  1238. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  1239. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  1240. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  1241. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  1242. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  1243. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  1244. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  1245. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  1246. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  1247. // v2.11.0 close-out — TTL sweep budgets (storage.ttl).
  1248. storeConfig.ttlMaxCandidatesPerSweep = config_.ttlMaxCandidatesPerSweep;
  1249. storeConfig.ttlMaxBlockedRetriesPerSweep = config_.ttlMaxBlockedRetriesPerSweep;
  1250. storeConfig.ttlBlockedRetrySweeps = config_.ttlBlockedRetrySweeps;
  1251. storeConfig.ttlBlockedSummarySweeps = config_.ttlBlockedSummarySweeps;
  1252. store_ = std::make_unique<MemoryStore>(storeConfig);
  1253. // Create view manager (cache loaded in initialize() after persistence recovery)
  1254. view_manager_ = std::make_unique<ViewManager>(*store_);
  1255. // Create per-collection config manager and attach it to the store so the
  1256. // write paths route document timestamp stamps through it.
  1257. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  1258. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  1259. // recovery alongside the view and collection-config caches.
  1260. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  1261. // v2.11.0 T6a — relation declarations. Constructed here; its cache is
  1262. // loaded after recovery alongside the view/config/policy caches.
  1263. relation_manager_ = std::make_unique<RelationManager>(*store_);
  1264. store_->setConfigManager(config_manager_.get());
  1265. // v1.9.0 — disk-resident version history. Replaces the in-heap
  1266. // `CollectionData::versionHistory` deques that were the dominant
  1267. // source of the Zoe untracked-RSS gap. One file per collection at
  1268. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  1269. // here, wired into the store immediately so snapshot deserializer
  1270. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  1271. HistoryStore::Config histConfig;
  1272. histConfig.dataDir = config_.dataDirectory;
  1273. history_store_ = std::make_unique<HistoryStore>(histConfig);
  1274. store_->setHistoryStore(history_store_.get());
  1275. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  1276. // resolver. Every write that flows through store_ commits to the
  1277. // right per-project LMDB env BEFORE the per-collection lock releases.
  1278. if (projects_) {
  1279. auto* registry = projects_.get();
  1280. store_->setDocumentStoreMirror(
  1281. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  1282. return registry->getOrCreate(project);
  1283. },
  1284. &mirror_healthy_,
  1285. &mirror_drift_count_);
  1286. }
  1287. // Create persistence manager. Start from any persistenceConfig values the
  1288. // caller (config loader / CLI parser) has already populated — including
  1289. // recoveryMode — and overlay the top-level convenience fields.
  1290. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  1291. persistConfig.dataDir = config_.dataDirectory;
  1292. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  1293. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  1294. persistConfig.compressionEnabled = config_.compressionEnabled;
  1295. persistConfig.nodeId = config_.nodeId;
  1296. // Mirror the resolved recoveryMode back into our Config so downstream code
  1297. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  1298. // without having to reach into the PersistenceManager.
  1299. config_.persistenceConfig = persistConfig;
  1300. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  1301. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  1302. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  1303. const std::optional<Document>& doc, EventType eventType,
  1304. const std::optional<std::string>& actor) {
  1305. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  1306. // sequence and record it on the store so eviction stubs can carry
  1307. // a real seq (instead of doc.version, which was useless as a
  1308. // `fromSequence` hint and forced a full WAL scan on every fault).
  1309. uint64_t walSeq = 0;
  1310. switch (eventType) {
  1311. case EventType::INSERT:
  1312. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  1313. break;
  1314. case EventType::UPDATE:
  1315. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  1316. break;
  1317. case EventType::DELETE:
  1318. persistence_->logDelete(collection, id);
  1319. break;
  1320. default:
  1321. break;
  1322. }
  1323. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  1324. store_->recordWalSequence(collection, id, walSeq);
  1325. }
  1326. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  1327. // that it runs UNDER the per-collection write lock. That closes the
  1328. // race window where readers could see a doc in MemoryStore but not
  1329. // yet in LMDB. The callback now does only WAL + replication + events.
  1330. // v2.11.0 T12 review (C2) — replication + events extracted into
  1331. // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
  1332. // drive them explicitly too. See that method's doc comment.
  1333. notifyReplicationAndEvents(collection, id, doc, eventType, actor);
  1334. });
  1335. // Set up document load callback for LRU eviction recovery.
  1336. //
  1337. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  1338. // callback below at append time, not the per-doc version counter).
  1339. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  1340. // returns entries with seq >= walSequence — the doc's last write is
  1341. // exactly at walSequence, so the very first hit is the one we want.
  1342. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  1343. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  1344. store_->setDocumentLoadCallback([this](const std::string& collection,
  1345. const std::string& id,
  1346. uint64_t walSequence) -> std::optional<Document> {
  1347. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  1348. return persistence_->loadDocument(collection, id, fromSequence);
  1349. });
  1350. // Create encryption manager
  1351. EncryptionManager::Config encryptConfig;
  1352. encryptConfig.enabled = config_.encryptionEnabled;
  1353. encryptConfig.keyFilePath = config_.keyFilePath;
  1354. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  1355. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  1356. // Create event manager
  1357. EventManager::Config eventConfig;
  1358. eventConfig.nodeId = config_.nodeId;
  1359. events_ = std::make_unique<EventManager>(eventConfig);
  1360. // Create file manager
  1361. FileManager::Config fileConfig;
  1362. fileConfig.filesDir = config_.dataDirectory / "files";
  1363. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  1364. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  1365. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  1366. fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
  1367. files_ = std::make_unique<FileManager>(fileConfig);
  1368. // Create replication manager
  1369. ReplicationManager::Config replConfig;
  1370. replConfig.nodeId = config_.nodeId;
  1371. replConfig.peerAddresses = config_.peerAddresses;
  1372. replConfig.conflictResolution = config_.conflictResolution;
  1373. replication_ = std::make_unique<ReplicationManager>(replConfig);
  1374. // Wire replication entry apply callback
  1375. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  1376. applyReplicatedEntry(entry);
  1377. });
  1378. // Create gRPC implementations
  1379. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  1380. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  1381. *policy_manager_, *relation_manager_
  1382. );
  1383. // v2.7.0 — hand the impl the union of every listener's keys so it can
  1384. // resolve a principal per call. A token is only accepted if some listener's
  1385. // auth processor accepted it, so the union cannot widen authentication; it
  1386. // only names what was already authenticated.
  1387. {
  1388. std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
  1389. for (const auto& l : config_.listeners) {
  1390. for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
  1391. }
  1392. storageImpl_->setPrincipalKeys(std::move(all));
  1393. }
  1394. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  1395. storageImpl_->setStreamLimits(
  1396. config_.grpc.maxConcurrentSubscribeStreams,
  1397. config_.grpc.maxConcurrentFileStreams);
  1398. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  1399. *store_, *replication_, *persistence_
  1400. );
  1401. }
  1402. void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
  1403. const std::string& id,
  1404. const std::optional<Document>& doc,
  1405. EventType eventType,
  1406. const std::optional<std::string>& actor) {
  1407. // Queue for replication broadcast
  1408. if (replication_ && config_.replicationEnabled) {
  1409. databasepb::ReplicationEntry entry;
  1410. entry.set_collection(collection);
  1411. entry.set_document_id(id);
  1412. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  1413. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  1414. // is now treated by receivers as "legacy / unknown origin".
  1415. entry.set_node_id(config_.nodeId);
  1416. entry.set_global_timestamp(
  1417. std::chrono::duration_cast<std::chrono::milliseconds>(
  1418. std::chrono::system_clock::now().time_since_epoch()
  1419. ).count());
  1420. switch (eventType) {
  1421. case EventType::INSERT:
  1422. entry.set_op(databasepb::OP_INSERT);
  1423. // Send the full Document envelope (id, collection, data,
  1424. // version, timestamps, encryption state). The follower's
  1425. // applyReplicatedEntry uses Document::fromJson() which
  1426. // expects this envelope — sending only doc->data silently
  1427. // dropped every user field on the other side.
  1428. if (doc) entry.set_data(doc->toJson().dump());
  1429. break;
  1430. case EventType::UPDATE:
  1431. entry.set_op(databasepb::OP_UPDATE);
  1432. if (doc) entry.set_data(doc->toJson().dump());
  1433. break;
  1434. case EventType::DELETE:
  1435. entry.set_op(databasepb::OP_DELETE);
  1436. break;
  1437. default:
  1438. break;
  1439. }
  1440. replication_->queueForReplication(entry);
  1441. }
  1442. // Publish event
  1443. if (events_) {
  1444. DatabaseEvent event;
  1445. event.type = eventType;
  1446. event.collection = collection;
  1447. event.documentId = id;
  1448. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  1449. std::chrono::system_clock::now().time_since_epoch()
  1450. ).count();
  1451. event.nodeId = config_.nodeId;
  1452. if (actor) {
  1453. event.actor = *actor;
  1454. } else if (doc) {
  1455. event.actor = doc->updatedBy;
  1456. }
  1457. if (doc) {
  1458. event.data = doc->data();
  1459. }
  1460. events_->publish(event);
  1461. }
  1462. }
  1463. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  1464. try {
  1465. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  1466. // with the originating node's id. This is what makes follower-side
  1467. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  1468. // replicated documents. Echo amplification is prevented by:
  1469. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  1470. // - SyncProtocol skipping entries whose origin is the peer itself
  1471. // both implemented in the same v1.8.0 cycle.
  1472. const std::string origin = entry.node_id().empty()
  1473. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  1474. : entry.node_id();
  1475. switch (entry.op()) {
  1476. case databasepb::OP_INSERT:
  1477. case databasepb::OP_UPDATE:
  1478. case databasepb::OP_UPSERT: {
  1479. if (entry.data().empty()) {
  1480. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  1481. return;
  1482. }
  1483. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  1484. Document doc = Document::fromJson(json);
  1485. doc.id = entry.document_id();
  1486. doc.nodeId = entry.node_id();
  1487. // loadDocument bypasses the persist-and-broadcast callback to avoid
  1488. // re-replicating; we explicitly write to the WAL right after with
  1489. // the origin-aware overload so eviction/WAL recovery still works.
  1490. store_->loadDocument(entry.collection(), doc);
  1491. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  1492. // MemoryStore persist callback that normally drives the
  1493. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  1494. // channel and reads still hit MemoryStore, so the bypass
  1495. // was harmless. In v2.3 reads are LMDB-first, so a
  1496. // follower that only filled MemoryStore would return
  1497. // empty Find/Get for every replicated doc. Route the
  1498. // entry through the same project-aware mirror the write
  1499. // handlers use.
  1500. if (projects_) {
  1501. auto pc = smartbotic::database::parseProjectCollection(
  1502. entry.collection());
  1503. if (auto* ds = projects_->getOrCreate(pc.project)) {
  1504. std::optional<Document> opt_doc(doc);
  1505. try {
  1506. smartbotic::db::storage::applyDualWriteMirror(
  1507. ds, mirror_healthy_, mirror_drift_count_,
  1508. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1509. } catch (const smartbotic::db::storage::UniqueViolation& e) {
  1510. // v2.11.0 T11 finding 1 — deliberate choice, not an
  1511. // accident of the generic catch below. By this
  1512. // point store_->loadDocument() above has ALREADY
  1513. // put the row into MemoryStore (loadDocument
  1514. // bypasses the persist callback specifically to
  1515. // avoid re-replicating), so unlike every
  1516. // client-facing write path there is no "reject the
  1517. // whole operation" available: the origin node
  1518. // already committed this write and every other
  1519. // follower is expected to converge to it too.
  1520. // Undoing loadDocument here would silently diverge
  1521. // this follower's data from the rest of the
  1522. // cluster over a constraint that may not even
  1523. // exist on the origin (this follower could have
  1524. // declared the unique field locally, after the
  1525. // fact — replication carries no guarantee the
  1526. // origin shares this node's config). So
  1527. // MemoryStore keeps the row — it is the true
  1528. // record of what replication decided — and the
  1529. // mirror is marked unhealthy ON PURPOSE: this is
  1530. // exactly the pre-T11 swallow-and-flip outcome,
  1531. // chosen deliberately for this one caller so an
  1532. // operator sees the drift (and LMDB-first reads
  1533. // fall back to MemoryStore, which has the answer)
  1534. // rather than nothing signalling a permanent gap
  1535. // between the two stores.
  1536. spdlog::error(
  1537. "v2.11 replication: unique constraint violated applying "
  1538. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  1539. "marking the mirror unhealthy so reads fall back instead "
  1540. "of silently disagreeing with MemoryStore",
  1541. entry.collection(), doc.id, e.what());
  1542. mirror_healthy_.store(false, std::memory_order_release);
  1543. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  1544. } catch (const smartbotic::db::storage::MissingParentReference& e) {
  1545. // v2.11.0 T13 — same deliberate swallow-and-flip as
  1546. // the UniqueViolation catch just above, for the same
  1547. // reason: loadDocument() has already committed this
  1548. // row into MemoryStore, the origin already accepted
  1549. // the write, and this follower may not even have the
  1550. // same validate_on_write declaration (or the same
  1551. // parent data) as the origin did at the time it
  1552. // wrote. MemoryStore keeps the row; the mirror is
  1553. // marked unhealthy on purpose so an operator sees
  1554. // the drift and reads fall back to MemoryStore
  1555. // rather than the two stores silently disagreeing.
  1556. spdlog::error(
  1557. "v2.11 replication: validate_on_write rejected applying "
  1558. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  1559. "marking the mirror unhealthy so reads fall back instead "
  1560. "of silently disagreeing with MemoryStore",
  1561. entry.collection(), doc.id, e.what());
  1562. mirror_healthy_.store(false, std::memory_order_release);
  1563. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  1564. }
  1565. }
  1566. }
  1567. if (persistence_) {
  1568. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  1569. ? persistence_->logInsert(entry.collection(), doc, origin)
  1570. : persistence_->logUpdate(entry.collection(), doc, origin);
  1571. if (walSeq > 0) {
  1572. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  1573. }
  1574. }
  1575. spdlog::trace("Applied replicated {} to {}/{} from {}",
  1576. entry.op() == databasepb::OP_INSERT ? "insert" :
  1577. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  1578. entry.collection(), entry.document_id(), entry.node_id());
  1579. break;
  1580. }
  1581. case databasepb::OP_DELETE: {
  1582. store_->remove(entry.collection(), entry.document_id());
  1583. if (persistence_) {
  1584. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  1585. }
  1586. spdlog::trace("Applied replicated delete to {}/{} from {}",
  1587. entry.collection(), entry.document_id(), entry.node_id());
  1588. break;
  1589. }
  1590. case databasepb::OP_CREATE_COLLECTION: {
  1591. CollectionOptions options;
  1592. store_->createCollection(entry.collection(), options);
  1593. if (persistence_) {
  1594. persistence_->logCreateCollection(entry.collection(), options, origin);
  1595. }
  1596. spdlog::trace("Applied replicated create collection {} from {}",
  1597. entry.collection(), entry.node_id());
  1598. break;
  1599. }
  1600. case databasepb::OP_DROP_COLLECTION: {
  1601. store_->dropCollection(entry.collection());
  1602. if (persistence_) {
  1603. persistence_->logDropCollection(entry.collection(), origin);
  1604. }
  1605. spdlog::trace("Applied replicated drop collection {} from {}",
  1606. entry.collection(), entry.node_id());
  1607. break;
  1608. }
  1609. default:
  1610. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  1611. break;
  1612. }
  1613. } catch (const std::exception& e) {
  1614. spdlog::error("Failed to apply replicated entry: {}", e.what());
  1615. }
  1616. }
  1617. void DatabaseService::startGrpcServer() {
  1618. if (config_.listeners.empty()) {
  1619. // Should never hit — parseConfig's back-compat shim always
  1620. // synthesises at least one. Defend anyway.
  1621. throw std::runtime_error("startGrpcServer: no listeners configured");
  1622. }
  1623. const int64_t mb = 1024 * 1024;
  1624. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  1625. config_.grpc.maxReceiveMessageSizeMb,
  1626. config_.grpc.maxSendMessageSizeMb,
  1627. config_.grpc.resourceQuotaMemoryMb,
  1628. config_.grpc.maxConcurrentSubscribeStreams,
  1629. config_.grpc.maxConcurrentFileStreams);
  1630. grpcServers_.reserve(config_.listeners.size());
  1631. for (const auto& listener : config_.listeners) {
  1632. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  1633. grpc::ServerBuilder builder;
  1634. // v2.4 — choose credentials per listener. Plaintext for
  1635. // tls.enabled=false; SslServerCredentials with the operator's
  1636. // cert+key (or an auto-generated self-signed pair) for true.
  1637. std::shared_ptr<grpc::ServerCredentials> creds;
  1638. if (listener.tls.enabled) {
  1639. std::filesystem::path cert_path = listener.tls.cert_path;
  1640. std::filesystem::path key_path = listener.tls.key_path;
  1641. // Resolve cert+key. If either is missing/unreadable AND
  1642. // auto_self_signed_if_missing is set, generate a pair.
  1643. const bool cert_ok = !cert_path.empty()
  1644. && std::filesystem::exists(cert_path);
  1645. const bool key_ok = !key_path.empty()
  1646. && std::filesystem::exists(key_path);
  1647. if (!cert_ok || !key_ok) {
  1648. if (!listener.tls.auto_self_signed_if_missing) {
  1649. throw std::runtime_error(
  1650. "TLS listener " + addr +
  1651. ": cert or key missing and auto_self_signed_if_missing=false");
  1652. }
  1653. const auto out_dir = config_.dataDirectory / "tls";
  1654. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  1655. out_dir, listener.bind);
  1656. cert_path = gen.cert_path;
  1657. key_path = gen.key_path;
  1658. spdlog::warn(
  1659. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  1660. "auto-generated self-signed cert at '{}' (key '{}'). "
  1661. "OK for dev. For production, drop a real cert + key at "
  1662. "the configured cert_path/key_path.",
  1663. addr,
  1664. listener.tls.cert_path.string(),
  1665. listener.tls.key_path.string(),
  1666. cert_path.string(),
  1667. key_path.string());
  1668. }
  1669. auto slurp = [](const std::filesystem::path& p) {
  1670. std::ifstream f(p);
  1671. if (!f) throw std::runtime_error("read " + p.string());
  1672. std::stringstream ss; ss << f.rdbuf();
  1673. return ss.str();
  1674. };
  1675. grpc::SslServerCredentialsOptions sslOpts;
  1676. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  1677. kp.private_key = slurp(key_path);
  1678. kp.cert_chain = slurp(cert_path);
  1679. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  1680. creds = grpc::SslServerCredentials(sslOpts);
  1681. } else {
  1682. creds = grpc::InsecureServerCredentials();
  1683. }
  1684. // v2.4 Stage D — attach the bearer-token auth processor when
  1685. // the listener requires it. The processor validates the
  1686. // `authorization: Bearer <key>` metadata against the listener's
  1687. // configured keys list. gRPC rejects with UNAUTHENTICATED
  1688. // (no per-handler code needed).
  1689. if (listener.auth.required) {
  1690. if (listener.auth.keys.empty()) {
  1691. throw std::runtime_error(
  1692. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  1693. }
  1694. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  1695. // Refuse at startup rather than resolving a policy against a name
  1696. // that means two different callers.
  1697. {
  1698. std::set<std::string> seen;
  1699. for (const auto& k : listener.auth.keys) {
  1700. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  1701. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  1702. throw std::runtime_error(
  1703. "Listener " + addr + ": auth key name '" + k.name +
  1704. "' is reserved. `anonymous` denotes an unauthenticated "
  1705. "caller and `unnamed` denotes a legacy bare key; a real "
  1706. "key must not be able to impersonate either in a policy.");
  1707. }
  1708. if (!seen.insert(k.name).second &&
  1709. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  1710. throw std::runtime_error(
  1711. "Listener " + addr + ": duplicate auth key name '" +
  1712. k.name + "'. A principal must identify one caller, "
  1713. "otherwise a policy written against it is ambiguous.");
  1714. }
  1715. }
  1716. }
  1717. if (!listener.tls.enabled) {
  1718. // gRPC ABORTS the process if an auth metadata processor is
  1719. // attached to insecure credentials
  1720. // (insecure_server_credentials.cc: "assertion failed: 0").
  1721. // This used to be a WARN, which meant a plaintext+auth listener
  1722. // looked merely inadvisable in the config and then killed the
  1723. // server on start with an unexplained assert. Refuse it here
  1724. // with a message that says what to do instead.
  1725. throw std::runtime_error(
  1726. "Listener " + addr + ": auth.required=true requires "
  1727. "tls.enabled=true. gRPC does not support an auth metadata "
  1728. "processor on insecure credentials and will abort the "
  1729. "process. Enable TLS for this listener (set "
  1730. "tls.auto_self_signed_if_missing for a local dev cert), or "
  1731. "drop auth and rely on binding to loopback.");
  1732. }
  1733. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  1734. nk.reserve(listener.auth.keys.size());
  1735. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  1736. creds->SetAuthMetadataProcessor(
  1737. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  1738. std::move(nk)));
  1739. }
  1740. builder.AddListeningPort(addr, creds);
  1741. builder.RegisterService(storageImpl_.get());
  1742. builder.RegisterService(replicationImpl_.get());
  1743. builder.SetMaxReceiveMessageSize(
  1744. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  1745. builder.SetMaxSendMessageSize(
  1746. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  1747. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  1748. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  1749. builder.SetResourceQuota(quota);
  1750. auto server = builder.BuildAndStart();
  1751. if (!server) {
  1752. throw std::runtime_error("Failed to start gRPC server on " + addr);
  1753. }
  1754. // v2.4 Stage B log line — listener identity printed so operators
  1755. // know exactly which interface is exposed with which policy.
  1756. // Stage C/D will extend with TLS + auth status.
  1757. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  1758. addr,
  1759. listener.tls.enabled ? "true" : "false",
  1760. listener.auth.required ? "true" : "false");
  1761. grpcServers_.push_back(std::move(server));
  1762. }
  1763. }
  1764. void DatabaseService::stopGrpcServer() {
  1765. // ⚠ Shutdown() WITHOUT a deadline waits for every in-flight RPC to return,
  1766. // and it does NOT cancel them. `Subscribe` never returns on its own: its
  1767. // handler parks in `while (!context->IsCancelled())`, and that context is
  1768. // cancelled only when the client goes away or a shutdown DEADLINE expires.
  1769. // So a single connected subscriber - the normal state of any consumer using
  1770. // events - hung this call forever.
  1771. //
  1772. // The cost is not just a slow stop. `stop()` calls this FIRST and takes the
  1773. // final snapshot AFTER it, so the hang blocked the snapshot; systemd then
  1774. // SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only
  1775. // replay, which trips auto read-only mode and needs an operator `unlock`.
  1776. // A graceful restart therefore looked like a crash to the next boot.
  1777. //
  1778. // With a deadline, gRPC cancels whatever is still running once it expires,
  1779. // the Subscribe loops observe IsCancelled() and unwind, and shutdown
  1780. // proceeds. The deadline is ABSOLUTE and shared across listeners, so the
  1781. // total wait is bounded by the grace period rather than by
  1782. // grace × listener count.
  1783. //
  1784. // Five seconds: long enough for an ordinary unary RPC in flight to finish
  1785. // (they are milliseconds), short enough that it is invisible next to the
  1786. // final snapshot, which is the part of shutdown that legitimately takes
  1787. // time (~70 s on the largest known dataset).
  1788. // v2.11.2 — tell the parked streaming handlers to return BEFORE asking gRPC
  1789. // to shut down. Subscribe has no work of its own; it waits for the stream to
  1790. // end. Without this signal it learned of the stop only when the deadline
  1791. // below expired and gRPC cancelled it, so every stop paid the full grace
  1792. // period. With it, the streams are usually gone before Shutdown is even
  1793. // called and the deadline is what it should be: a backstop, not the
  1794. // mechanism.
  1795. if (storageImpl_) {
  1796. storageImpl_->beginShutdown();
  1797. }
  1798. constexpr auto kShutdownGrace = std::chrono::seconds(5);
  1799. const auto deadline = std::chrono::system_clock::now() + kShutdownGrace;
  1800. for (auto& server : grpcServers_) {
  1801. if (server) server->Shutdown(deadline);
  1802. }
  1803. grpcServers_.clear();
  1804. }
  1805. } // namespace smartbotic::database