database_service.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. #include "database_service.hpp"
  2. #include "json_parse.hpp"
  3. #include "project_addressing.hpp"
  4. #include "storage/document_store.hpp"
  5. #include "storage/document_store_lmdb.hpp"
  6. #include "storage/dual_write_mirror.hpp"
  7. #include "auth/auth_interceptor.hpp"
  8. #include "auth/principal.hpp"
  9. #include "tls/cert_generator.hpp"
  10. #include <fstream>
  11. #include <sstream>
  12. #include <map>
  13. #include <set>
  14. #include "storage/lmdb_env.hpp"
  15. #include "storage/migrate_v1_to_v2.hpp"
  16. #include "storage/project_store.hpp"
  17. #include "storage/subdb_placement.hpp"
  18. #include <grpcpp/grpcpp.h>
  19. #include <grpcpp/resource_quota.h>
  20. #include <spdlog/spdlog.h>
  21. #include <fstream>
  22. #ifdef HAVE_SYSTEMD
  23. #include <systemd/sd-daemon.h>
  24. #endif
  25. #if defined(__GLIBC__) && !defined(__APPLE__)
  26. #include <malloc.h>
  27. #endif
  28. namespace smartbotic::database {
  29. DatabaseService::DatabaseService(Config config)
  30. : config_(std::move(config))
  31. {
  32. }
  33. DatabaseService::~DatabaseService() {
  34. stop();
  35. }
  36. std::string DatabaseService::readOnlyReason() const {
  37. std::lock_guard<std::mutex> lock(reason_mutex_);
  38. return read_only_reason_;
  39. }
  40. void DatabaseService::setReadOnly(bool value, const std::string& reason) {
  41. {
  42. std::lock_guard<std::mutex> lock(reason_mutex_);
  43. read_only_reason_ = value ? reason : "";
  44. }
  45. bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
  46. if (prev != value) {
  47. if (value) {
  48. spdlog::error("Database entered READ-ONLY mode: {}", reason);
  49. } else {
  50. spdlog::info("Database unlocked -- writes accepted");
  51. }
  52. }
  53. }
  54. bool DatabaseService::initialize() {
  55. spdlog::info("Initializing database service (node: {})", config_.nodeId);
  56. try {
  57. // Create data directory if needed
  58. std::error_code ec;
  59. std::filesystem::create_directories(config_.dataDirectory, ec);
  60. if (ec) {
  61. spdlog::error("Failed to create data directory: {}", ec.message());
  62. return false;
  63. }
  64. setupComponents();
  65. // Initialize encryption
  66. if (config_.encryptionEnabled) {
  67. if (!encryption_->initialize()) {
  68. spdlog::error("Failed to initialize encryption");
  69. return false;
  70. }
  71. }
  72. // Recover from persistence
  73. recovery_outcome_ = persistence_->recover(*store_);
  74. #if defined(__GLIBC__) && !defined(__APPLE__)
  75. // v1.9.3 — release freelist pages accumulated during recovery. v1.9.1
  76. // added trim at end of loadSnapshot, but the WAL replay phase that
  77. // runs afterward (`persistence_->recover`'s `replayWal` step) also
  78. // burns through GBs of small Document JSON allocations whose pages
  79. // sit on the per-thread freelist with no subsequent allocation to
  80. // shake them loose. On Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md update 15:05)
  81. // this was 5.7 GB at 23 min uptime — fully reclaimable via
  82. // malloc_trim, just nothing called it. Paired with the periodic
  83. // every-5-minute trim in MemoryStore::logMemoryCheck, so any
  84. // post-boot bloat that escapes this trim gets cleaned up shortly.
  85. ::malloc_trim(0);
  86. #endif
  87. if (recovery_outcome_.isFailure()) {
  88. const std::string modeStr =
  89. recoveryModeToString(config_.persistenceConfig.recoveryMode);
  90. spdlog::error("");
  91. spdlog::error("+------------------------------------------------------------------+");
  92. spdlog::error("| RECOVERY REFUSED |");
  93. spdlog::error("| |");
  94. spdlog::error("| Mode: {}", modeStr);
  95. spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
  96. spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
  97. spdlog::error("| |");
  98. spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
  99. spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
  100. spdlog::error("| |");
  101. spdlog::error("| To escalate, restart with one of: |");
  102. spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
  103. spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
  104. spdlog::error("| --recovery-mode=best_effort Try all of the above |");
  105. spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
  106. spdlog::error("| |");
  107. spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
  108. spdlog::error("| |");
  109. spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
  110. spdlog::error("+------------------------------------------------------------------+");
  111. throw std::runtime_error("recovery failed; refusing to start");
  112. }
  113. // Auto-readonly mode on non-trivial recovery
  114. if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
  115. std::string reason;
  116. switch (recovery_outcome_.kind) {
  117. case RecoveryOutcome::Kind::SnapshotFellBack:
  118. reason = "fell back to snapshot " +
  119. recovery_outcome_.snapshotUsed.filename().string() +
  120. " because " +
  121. recovery_outcome_.expectedSnapshot.filename().string() +
  122. " failed: " + recovery_outcome_.failureReason;
  123. break;
  124. case RecoveryOutcome::Kind::WalOnlyReplay:
  125. reason = "WAL-only replay, no snapshot loaded (" +
  126. std::to_string(recovery_outcome_.walEntriesReplayed) +
  127. " entries)";
  128. break;
  129. case RecoveryOutcome::Kind::ForcedEmpty:
  130. reason = "forced empty by operator (--recovery-mode=force_empty)";
  131. break;
  132. default:
  133. reason = "non-trivial recovery";
  134. break;
  135. }
  136. reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
  137. "or restart with --force-readwrite to bypass this check.";
  138. setReadOnly(true, reason);
  139. spdlog::error("");
  140. spdlog::error("+------------------------------------------------------------------+");
  141. spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
  142. spdlog::error("| recovery. |");
  143. spdlog::error("| |");
  144. spdlog::error("| Reason: {}", reason);
  145. spdlog::error("| |");
  146. spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
  147. spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
  148. spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
  149. spdlog::error("+------------------------------------------------------------------+");
  150. }
  151. // Set replication sequence after recovery (WAL sequence is now known)
  152. replication_->setSequence(persistence_->currentWalSequence());
  153. // v1.8.0 — start the persistence manager before loadFromStore /
  154. // migrations so any system-collection writes those phases produce
  155. // (view docs, _collection_meta entries, _migrations recordings)
  156. // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
  157. // started later in start(), which silently dropped those writes
  158. // (running_=false → logInsert no-op). That meant migrated views
  159. // only "survived" because the runner re-created them every boot,
  160. // and a manually-created view that landed during the racy startup
  161. // window (before full readiness) could be lost.
  162. if (!persistence_->start()) {
  163. spdlog::error("Failed to start persistence manager before migrations");
  164. return false;
  165. }
  166. // Load view definitions from the _views system collection (which is now
  167. // populated by the persistence recovery above).
  168. view_manager_->loadFromStore();
  169. // Load per-collection configs from the _collection_meta system collection.
  170. // Must happen AFTER persistence recovery and BEFORE migrations so any
  171. // migration-created documents are stamped with the correct precision.
  172. config_manager_->loadFromStore();
  173. policy_manager_->loadFromStore();
  174. relation_manager_->loadFromStore();
  175. applyRelationDeclarations();
  176. // v2.9.0 — re-apply persisted index declarations to each project's LMDB
  177. // store. This is load-bearing, not bookkeeping: the declaration is what
  178. // makes the write path maintain an index, and the planner consults an
  179. // index purely on the declaration's word. If this step were skipped, a
  180. // restart would leave indexes recorded but unmaintained, and queries
  181. // would be served from a frozen index - stale rows returned as current,
  182. // with nothing logged.
  183. applyIndexDeclarations();
  184. // Run migrations if enabled
  185. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  186. if (!runMigrations()) {
  187. if (config_.migrations.failOnError) {
  188. spdlog::error("Failed to run migrations");
  189. return false;
  190. }
  191. spdlog::warn("Some migrations failed, continuing anyway");
  192. }
  193. }
  194. // v2.0 Stage 4 — synchronous backfill into doc_store_ before
  195. // serving. Without this, only post-boot writes land in LMDB and
  196. // the read-flip downstream would see an empty mirror.
  197. backfillIntoDocStore();
  198. // v2.4.4 — placement audit. Reports documents sitting in a sub-db
  199. // other than the one they declare, which is the signature of a
  200. // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
  201. // advisory: it never blocks startup, because a misplacement is a
  202. // data-location problem an operator repairs offline with
  203. // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
  204. // service on the other 99% of the dataset.
  205. auditSubdbPlacement();
  206. // v2.6.0 — stamp `project: "default"` onto file records written before
  207. // files were namespaced. Idempotent, and advisory: a file-metadata
  208. // stamp is not a reason to refuse service, so failures warn only.
  209. if (files_) {
  210. try {
  211. const uint32_t stamped = files_->stampMissingProjects();
  212. if (stamped > 0) {
  213. spdlog::info("v2.6.0 file migration: stamped {} legacy file "
  214. "record(s) with project 'default'", stamped);
  215. } else {
  216. spdlog::debug("v2.6.0 file migration: no legacy file records");
  217. }
  218. } catch (const std::exception& e) {
  219. spdlog::warn("v2.6.0 file migration failed: {}", e.what());
  220. }
  221. }
  222. spdlog::info("Database service initialized successfully");
  223. return true;
  224. } catch (const std::exception& e) {
  225. spdlog::error("Failed to initialize database service: {}", e.what());
  226. return false;
  227. }
  228. }
  229. void DatabaseService::migrateLegacyEnvToDefaultProject() {
  230. const auto legacy = config_.dataDirectory / "env";
  231. const auto target = config_.dataDirectory / "projects" /
  232. smartbotic::database::kDefaultProject / "env";
  233. std::error_code ec;
  234. const bool legacy_exists = std::filesystem::exists(legacy, ec);
  235. const bool target_exists = std::filesystem::exists(target, ec);
  236. if (!legacy_exists) return; // fresh install or already migrated
  237. if (target_exists) {
  238. spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
  239. "refusing to start. Inspect manually; the safe move is "
  240. "to either delete the legacy dir (if you confirm it's a "
  241. "leftover) or stop and contact ops.",
  242. legacy.string(), target.string());
  243. throw std::runtime_error("v2.3 storage migration: ambiguous layout");
  244. }
  245. std::filesystem::create_directories(target.parent_path(), ec);
  246. if (ec) {
  247. throw std::runtime_error("v2.3 storage migration: cannot create '"
  248. + target.parent_path().string() + "': " + ec.message());
  249. }
  250. std::filesystem::rename(legacy, target, ec);
  251. if (ec) {
  252. throw std::runtime_error("v2.3 storage migration: rename '"
  253. + legacy.string() + "' -> '"
  254. + target.string() + "' failed: " + ec.message());
  255. }
  256. spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
  257. legacy.string(), target.string());
  258. }
  259. smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
  260. return docStore(smartbotic::database::kDefaultProject);
  261. }
  262. smartbotic::db::storage::DocumentStore*
  263. DatabaseService::docStore(std::string_view project) noexcept {
  264. if (!projects_) return nullptr;
  265. return projects_->get(project);
  266. }
  267. std::vector<std::string> DatabaseService::listProjects() const {
  268. if (!projects_) return {};
  269. return projects_->listOnDisk();
  270. }
  271. bool DatabaseService::createProject(const std::string& name, std::string& error) {
  272. if (!projects_) {
  273. error = "project registry not initialized";
  274. return false;
  275. }
  276. return projects_->create(name, error);
  277. }
  278. bool DatabaseService::dropProject(const std::string& name, std::string& error) {
  279. if (!projects_) {
  280. error = "project registry not initialized";
  281. return false;
  282. }
  283. return projects_->drop(name, error);
  284. }
  285. bool DatabaseService::runMigrations() {
  286. if (!config_.migrations.enabled) {
  287. return true;
  288. }
  289. MigrationRunner::Config migrationConfig;
  290. migrationConfig.directory = config_.migrations.directory;
  291. migrationConfig.autoApply = config_.migrations.autoApply;
  292. migrationConfig.failOnError = config_.migrations.failOnError;
  293. migrationRunner_ = std::make_unique<MigrationRunner>(*store_, *view_manager_, migrationConfig);
  294. return migrationRunner_->runMigrations();
  295. }
  296. void DatabaseService::applyIndexDeclarations() {
  297. size_t applied = 0;
  298. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  299. if (cfg.indexedFields.empty()) continue;
  300. try {
  301. const auto rc = resolveCollection(qualified);
  302. auto* ds = docStore(rc.project);
  303. auto* lmdb =
  304. dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  305. if (lmdb == nullptr) continue;
  306. lmdb->set_indexed_fields(rc.collection, cfg.indexedFields);
  307. ++applied;
  308. spdlog::info("v2.9 index: {} field(s) active on {}",
  309. cfg.indexedFields.size(), qualified);
  310. // Self-heal a declared index whose sub-db is absent. That happens
  311. // when the KEY FORMAT VERSION in the sub-db prefix changes (v2.9.1
  312. // unified the numeric encoding, so `_idx_` became `_idx2_`), and it
  313. // would otherwise leave the declaration pointing at nothing: writes
  314. // would maintain the new index correctly, but rows written BEFORE the
  315. // upgrade would have no postings, so an indexed query would silently
  316. // return only the newer ones. Rebuilding is the only safe reading.
  317. for (const auto& field : cfg.indexedFields) {
  318. if (lmdb->index_stats(rc.collection, field).has_value()) continue;
  319. const uint64_t rows = lmdb->build_index(rc.collection, field);
  320. spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "
  321. "was declared but its sub-db was absent (key format "
  322. "change or a manual removal)",
  323. qualified, field, rows);
  324. }
  325. } catch (const std::exception& e) {
  326. // Advisory per collection: one unparseable name must not stop the
  327. // rest from being armed. Loud, because a missing declaration means
  328. // that collection's index silently stops being maintained.
  329. spdlog::error("v2.9 index: could not apply declarations for {}: {}",
  330. qualified, e.what());
  331. }
  332. }
  333. if (applied > 0) {
  334. spdlog::info("v2.9 index: applied declarations for {} collection(s)", applied);
  335. }
  336. }
  337. void DatabaseService::applyRelationDeclarations() {
  338. // Group by (project, bare child collection) — set_relations() is a
  339. // per-collection call on that project's LmdbDocumentStore and replaces
  340. // whatever was declared before, so every relation sharing a child
  341. // collection must land in one call.
  342. std::unordered_map<std::string,
  343. std::vector<smartbotic::db::storage::RelationRef>> byChild;
  344. // Track which project each grouping key belongs to alongside the bare
  345. // collection name, since the map key alone doesn't carry it.
  346. std::unordered_map<std::string, std::pair<std::string, std::string>> keyToProjectCollection;
  347. for (const auto& r : relation_manager_->listRelations()) {
  348. try {
  349. const auto rn = resolveCollection(r.name);
  350. const auto rc = resolveCollection(r.child);
  351. const std::string key = rc.project + ":" + rc.collection;
  352. byChild[key].push_back(
  353. smartbotic::db::storage::RelationRef{rn.collection, r.childField});
  354. keyToProjectCollection[key] = {rc.project, rc.collection};
  355. } catch (const std::exception& e) {
  356. // Advisory per relation: one unparseable declaration must not
  357. // stop the rest from being armed. Loud, because a skipped
  358. // relation silently maintains no reverse index for its child.
  359. spdlog::error("v2.11 relations: could not apply declaration '{}': {}",
  360. r.name, e.what());
  361. }
  362. }
  363. size_t applied = 0;
  364. for (const auto& [key, refs] : byChild) {
  365. const auto& [project, collection] = keyToProjectCollection[key];
  366. try {
  367. auto* ds = docStore(project);
  368. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  369. if (lmdb == nullptr) continue;
  370. lmdb->set_relations(collection, refs);
  371. ++applied;
  372. spdlog::info("v2.11 relations: {} relation(s) active with child '{}:{}'",
  373. refs.size(), project, collection);
  374. } catch (const std::exception& e) {
  375. spdlog::error("v2.11 relations: could not apply declarations for '{}:{}': {}",
  376. project, collection, e.what());
  377. }
  378. }
  379. if (applied > 0) {
  380. spdlog::info("v2.11 relations: applied declarations for {} child collection(s)", applied);
  381. }
  382. }
  383. void DatabaseService::auditSubdbPlacement() {
  384. if (!projects_) return;
  385. for (const auto& name : projects_->listOpen()) {
  386. auto h = projects_->getHandle(name);
  387. if (!h.env) continue;
  388. try {
  389. // audit_env(), NOT audit(). The path-taking overload opens a
  390. // second MDB_env on the same file; closing it would drop the
  391. // POSIX record locks this process already holds for `h.env`
  392. // (POSIX locks are per-process, and closing any fd on a file
  393. // releases all of them), leaving every later mdb_txn_begin
  394. // failing EINVAL. Borrow the open handle instead.
  395. const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
  396. if (rep.misplaced.empty()) {
  397. spdlog::debug("placement audit: project '{}' consistent ({} rows)",
  398. name, rep.rows_scanned);
  399. continue;
  400. }
  401. // Summarise per (physical -> declared home) pair; one line per
  402. // affected document would be unreadable at scale.
  403. std::map<std::string, uint64_t> pairs;
  404. for (const auto& m : rep.misplaced) {
  405. ++pairs[m.physical_subdb + " -> " + m.home_subdb];
  406. }
  407. spdlog::error("placement audit: project '{}' has {} document(s) in the "
  408. "wrong sub-db. Reads served from LMDB will not find them "
  409. "under their own collection. Repair offline with: "
  410. "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
  411. name, rep.misplaced.size(), h.env->path(), name);
  412. for (const auto& [pair, count] : pairs) {
  413. spdlog::error("placement audit: {} document(s) {}", count, pair);
  414. }
  415. } catch (const std::exception& e) {
  416. // Advisory only — a failed audit must not take the service down.
  417. spdlog::warn("placement audit: project '{}' could not be audited: {}",
  418. name, e.what());
  419. }
  420. }
  421. }
  422. bool DatabaseService::backfillIntoDocStore() {
  423. if (!projects_) {
  424. // Registry open failed earlier; nothing to back-fill into.
  425. return true;
  426. }
  427. // v2.3 — MemoryStore stores collection keys in qualified form
  428. // ("project:collection"). For the default project (back-compat
  429. // path) the marker check operates on the default env. Skip when
  430. // already migrated.
  431. auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
  432. if (handle.env) {
  433. try {
  434. if (smartbotic::db::storage::migration_complete(*handle.env)) {
  435. spdlog::info("v2.3 backfill: default project already migrated, skipping");
  436. return true;
  437. }
  438. } catch (const std::exception& e) {
  439. spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
  440. "treating default env as fresh and proceeding",
  441. e.what());
  442. }
  443. }
  444. const auto collections = store_->listCollections();
  445. uint64_t total_docs = 0;
  446. uint64_t total_failures = 0;
  447. auto t0 = std::chrono::steady_clock::now();
  448. for (const auto& qualified : collections) {
  449. if (qualified.empty() || qualified[0] == '_') continue;
  450. // Each qualified key parses to (project, collection); route the
  451. // mirror write to the right project's env.
  452. smartbotic::database::ProjectCollection pc;
  453. try {
  454. pc = smartbotic::database::parseProjectCollection(qualified);
  455. } catch (const std::exception&) {
  456. // Legacy unqualified key — treat as default project.
  457. pc = {std::string(smartbotic::database::kDefaultProject), qualified};
  458. }
  459. auto* ds = projects_->getOrCreate(pc.project);
  460. if (!ds) {
  461. ++total_failures;
  462. continue;
  463. }
  464. const auto docs = store_->getAllDocuments(qualified);
  465. for (const auto& doc : docs) {
  466. std::optional<Document> opt_doc(doc);
  467. const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
  468. smartbotic::db::storage::applyDualWriteMirror(
  469. ds, mirror_healthy_, mirror_drift_count_,
  470. pc.collection, doc.id, opt_doc, EventType::INSERT);
  471. if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
  472. ++total_failures;
  473. }
  474. ++total_docs;
  475. if (total_docs % 10000 == 0) {
  476. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  477. const std::string status = "STATUS=v2.3 backfill: " +
  478. std::to_string(total_docs) + " docs mirrored";
  479. sd_notify(0, status.c_str());
  480. spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
  481. total_docs, total_failures);
  482. }
  483. }
  484. }
  485. const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  486. std::chrono::steady_clock::now() - t0).count();
  487. if (total_failures == 0) {
  488. // Stamp schema_version=2 on every opened project env. Subsequent
  489. // boots short-circuit at migration_complete().
  490. for (const auto& name : projects_->listOpen()) {
  491. auto h = projects_->getHandle(name);
  492. if (!h.env) continue;
  493. try {
  494. smartbotic::db::storage::mark_migration_complete(*h.env);
  495. } catch (const std::exception& e) {
  496. spdlog::warn("v2.3 backfill: schema_version marker write failed for "
  497. "project '{}': {}", name, e.what());
  498. }
  499. }
  500. spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
  501. total_docs, collections.size(), elapsed);
  502. } else {
  503. spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
  504. "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
  505. total_failures, total_docs, elapsed);
  506. }
  507. return true;
  508. }
  509. void DatabaseService::start() {
  510. if (running_.exchange(true)) {
  511. return;
  512. }
  513. spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
  514. // Start components
  515. store_->start();
  516. persistence_->start();
  517. events_->start();
  518. files_->start();
  519. if (config_.replicationEnabled) {
  520. replication_->start();
  521. // Set initial local collections for discovery
  522. replication_->setLocalCollections(store_->listCollections());
  523. }
  524. // Start gRPC server
  525. startGrpcServer();
  526. spdlog::info("Database service started");
  527. }
  528. void DatabaseService::stop() {
  529. if (!running_.exchange(false)) {
  530. return;
  531. }
  532. spdlog::info("Stopping database service...");
  533. // Stop gRPC server first
  534. stopGrpcServer();
  535. // Stop components in reverse order
  536. if (replication_) {
  537. replication_->stop();
  538. }
  539. if (files_) {
  540. files_->stop();
  541. }
  542. if (events_) {
  543. events_->stop();
  544. }
  545. if (persistence_ && store_) {
  546. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  547. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  548. // replay" which trips auto-readonly mode. This makes ordinary
  549. // restarts pass through cleanly without needing
  550. // `smartbotic-db-cli unlock`.
  551. //
  552. // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
  553. // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
  554. // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
  555. // RSS hit 11 GB (live state + uncompressed serialize buffer), and
  556. // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
  557. // tells systemd we're working — same protocol the recovery path
  558. // uses during startup. Paired with TimeoutStopSec=300 in the unit
  559. // file as the static cap.
  560. #ifdef HAVE_SYSTEMD
  561. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  562. sd_notify(0, "STATUS=Writing final snapshot");
  563. #endif
  564. try {
  565. persistence_->forceSnapshot(*store_);
  566. spdlog::info("Final snapshot taken on shutdown");
  567. } catch (const std::exception& e) {
  568. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  569. "boot may be WAL-only and trip auto-readonly mode", e.what());
  570. }
  571. }
  572. if (persistence_) {
  573. persistence_->stop();
  574. }
  575. if (store_) {
  576. store_->stop();
  577. }
  578. spdlog::info("Database service stopped");
  579. }
  580. void DatabaseService::wait() {
  581. if (serverThread_.joinable()) {
  582. serverThread_.join();
  583. }
  584. }
  585. void DatabaseService::signalStop() {
  586. stopRequested_ = true;
  587. stop();
  588. }
  589. nlohmann::json DatabaseService::getStats() const {
  590. nlohmann::json stats;
  591. if (store_) {
  592. auto storeStats = store_->getStats();
  593. stats["documents"] = storeStats.totalDocuments;
  594. stats["collections"] = storeStats.totalCollections;
  595. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  596. stats["inserts"] = storeStats.insertCount;
  597. stats["updates"] = storeStats.updateCount;
  598. stats["deletes"] = storeStats.deleteCount;
  599. stats["queries"] = storeStats.queryCount;
  600. }
  601. if (persistence_) {
  602. auto persistStats = persistence_->getStats();
  603. stats["wal_sequence"] = persistStats.walSequence;
  604. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  605. stats["snapshot_count"] = persistStats.snapshotCount;
  606. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  607. }
  608. if (events_) {
  609. stats["subscriptions"] = events_->subscriptionCount();
  610. }
  611. return stats;
  612. }
  613. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  614. std::ifstream file(configPath);
  615. if (!file) {
  616. throw std::runtime_error("Failed to open config file: " + configPath.string());
  617. }
  618. nlohmann::json json;
  619. file >> json;
  620. return parseConfig(json);
  621. }
  622. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  623. Config config;
  624. // Check for both "storage" and "database" keys for backward compatibility
  625. const nlohmann::json* dbConfig = nullptr;
  626. if (json.contains("database")) {
  627. dbConfig = &json["database"];
  628. } else if (json.contains("storage")) {
  629. dbConfig = &json["storage"];
  630. }
  631. if (dbConfig) {
  632. const auto& db = *dbConfig;
  633. config.nodeId = db.value("node_id", config.nodeId);
  634. config.bindAddress = db.value("bind_address", config.bindAddress);
  635. config.rpcPort = db.value("rpc_port", config.rpcPort);
  636. // v2.4 — parse the per-listener fleet. If "listeners" is set,
  637. // it overrides the legacy bind_address+rpc_port. Otherwise we
  638. // synthesise one listener below using those legacy fields.
  639. if (db.contains("listeners") && db["listeners"].is_array()) {
  640. for (const auto& l : db["listeners"]) {
  641. ListenerConfig lc;
  642. lc.bind = l.value("bind", lc.bind);
  643. lc.port = l.value("port", lc.port);
  644. if (l.contains("tls") && l["tls"].is_object()) {
  645. const auto& t = l["tls"];
  646. lc.tls.enabled = t.value("enabled", false);
  647. lc.tls.cert_path = t.value("cert_path", std::string{});
  648. lc.tls.key_path = t.value("key_path", std::string{});
  649. lc.tls.auto_self_signed_if_missing =
  650. t.value("auto_self_signed_if_missing", true);
  651. }
  652. if (l.contains("auth") && l["auth"].is_object()) {
  653. const auto& a = l["auth"];
  654. lc.auth.required = a.value("required", false);
  655. if (a.contains("keys") && a["keys"].is_array()) {
  656. for (const auto& k : a["keys"]) {
  657. // v2.7.0 — a key is either a bare token (v2.4-v2.6
  658. // shape) or {"name","key"}. The name becomes the
  659. // principal that policy is written against; a bare
  660. // token maps to the reserved `unnamed`, so old
  661. // configs keep authenticating but cannot be told
  662. // apart in a policy until they are named.
  663. if (k.is_string()) {
  664. lc.auth.keys.push_back(
  665. {smartbotic::database::auth::kPrincipalUnnamed,
  666. k.get<std::string>()});
  667. } else if (k.is_object()) {
  668. const std::string name = k.value("name", std::string{});
  669. const std::string key = k.value("key", std::string{});
  670. if (key.empty()) {
  671. spdlog::warn("auth: listener {}:{} has a key entry "
  672. "with no `key` value - skipped",
  673. lc.bind, lc.port);
  674. continue;
  675. }
  676. lc.auth.keys.push_back(
  677. {name.empty()
  678. ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
  679. : name,
  680. key});
  681. }
  682. }
  683. }
  684. }
  685. config.listeners.push_back(std::move(lc));
  686. }
  687. }
  688. // Expand environment variables in data directory
  689. std::string dataDir = db.value("data_directory", "");
  690. if (dataDir.find("${HOME}") != std::string::npos) {
  691. const char* home = std::getenv("HOME");
  692. if (home) {
  693. size_t pos = dataDir.find("${HOME}");
  694. dataDir.replace(pos, 7, home);
  695. }
  696. }
  697. config.dataDirectory = dataDir;
  698. // Migrations settings
  699. if (db.contains("migrations")) {
  700. auto& migrations = db["migrations"];
  701. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  702. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  703. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  704. std::string migDir = migrations.value("directory", "");
  705. if (migDir.find("${HOME}") != std::string::npos) {
  706. const char* home = std::getenv("HOME");
  707. if (home) {
  708. size_t pos = migDir.find("${HOME}");
  709. migDir.replace(pos, 7, home);
  710. }
  711. }
  712. config.migrations.directory = migDir;
  713. }
  714. // Memory eviction settings
  715. if (db.contains("memory")) {
  716. auto& memory = db["memory"];
  717. // Deprecation log. These knobs control MemoryStore eviction, which
  718. // is still active for the MemoryStore-side mirror but does NOT bound
  719. // RSS since v2.0 (LMDB mmap is the dominant RSS contributor). The
  720. // substrate-level equivalent is the LMDB env mapsize and the OS page
  721. // cache.
  722. //
  723. // They disappear when the write-handler migration deletes MemoryStore
  724. // (docs/ROADMAP.md, "Pending"). An earlier revision of this comment
  725. // promised a v2.1 rename to `buffer_pool_size_mb` "per the Phase C
  726. // plan"; that plan was superseded by LMDB before it was written, no
  727. // such knob exists, and the rename is not planned.
  728. for (const char* deprecated : {"max_memory_mb",
  729. "eviction_threshold_percent",
  730. "eviction_target_percent",
  731. "eviction_check_interval_ms",
  732. "eviction_chunk_size",
  733. "eviction_chunk_pause_ms",
  734. "max_eviction_passes_per_trigger",
  735. "hot_write_floor_ms",
  736. "memory_priority"}) {
  737. if (memory.contains(deprecated)) {
  738. spdlog::warn("v2.0 deprecation: storage.memory.{} is deprecated "
  739. "and will be removed in v2.1. v2.0 RSS is bounded "
  740. "by the LMDB env mapsize + OS page cache, not by "
  741. "MemoryStore eviction. Setting still applied to "
  742. "the MemoryStore mirror for back-compat.",
  743. deprecated);
  744. }
  745. }
  746. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  747. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  748. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  749. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  750. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  751. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  752. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  753. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  754. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  755. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  756. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  757. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  758. // v1.7.0 T10 — eviction burst event threshold
  759. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  760. // v2.4.3 — eviction drain cap (0 disables)
  761. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  762. }
  763. // Persistence settings
  764. if (db.contains("persistence")) {
  765. auto& persistence = db["persistence"];
  766. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  767. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  768. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  769. // Snapshot durability (NEW in v1.6.1)
  770. if (persistence.contains("snapshots")) {
  771. const auto& snap = persistence["snapshots"];
  772. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  773. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  774. }
  775. // Recovery (NEW in v1.6.1)
  776. if (persistence.contains("recovery")) {
  777. const auto& rec = persistence["recovery"];
  778. std::string modeStr = rec.value("mode", std::string("normal"));
  779. try {
  780. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  781. } catch (const std::exception& e) {
  782. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  783. modeStr, e.what());
  784. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  785. }
  786. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  787. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  788. }
  789. }
  790. // File settings
  791. if (db.contains("files")) {
  792. auto& files = db["files"];
  793. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  794. // v2.8.0 — this interval now drives the file EXPIRY sweep as well
  795. // as orphan cleanup, so accept the plainer name too. The original
  796. // key kept working; nothing read either of them before 2.8.0
  797. // because there was no sweeper thread at all.
  798. config.fileCleanupIntervalSec =
  799. files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  800. config.fileCleanupIntervalSec =
  801. files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
  802. // v2.8.0 — default retention per file type. The analogue of a
  803. // collection's defaultTtlSeconds, so retention is an operator
  804. // setting rather than something every uploader must remember.
  805. //
  806. // "default_ttl_seconds": {
  807. // "acme:generated": 86400, // one project, one type
  808. // "generated": 604800, // any project
  809. // "acme:*": 2592000, // every type in one project
  810. // "*": 0 // everything (0 = keep)
  811. // }
  812. if (files.contains("default_ttl_seconds") &&
  813. files["default_ttl_seconds"].is_object()) {
  814. for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
  815. if (v.is_number_unsigned()) {
  816. config.fileDefaultTtlByType[k] = v.get<uint32_t>();
  817. }
  818. }
  819. }
  820. if (files.contains("allowed_types")) {
  821. for (const auto& type : files["allowed_types"]) {
  822. config.allowedFileTypes.push_back(type.get<std::string>());
  823. }
  824. }
  825. }
  826. // Encryption settings
  827. if (db.contains("encryption")) {
  828. auto& encryption = db["encryption"];
  829. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  830. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  831. std::string keyFile = encryption.value("key_file", "");
  832. if (keyFile.find("${HOME}") != std::string::npos) {
  833. const char* home = std::getenv("HOME");
  834. if (home) {
  835. size_t pos = keyFile.find("${HOME}");
  836. keyFile.replace(pos, 7, home);
  837. }
  838. }
  839. config.keyFilePath = keyFile;
  840. }
  841. // Replication settings
  842. if (db.contains("replication")) {
  843. auto& replication = db["replication"];
  844. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  845. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  846. if (replication.contains("peers")) {
  847. for (const auto& peer : replication["peers"]) {
  848. config.peerAddresses.push_back(peer.get<std::string>());
  849. }
  850. }
  851. }
  852. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  853. if (db.contains("grpc")) {
  854. const auto& grpc = db["grpc"];
  855. config.grpc.maxReceiveMessageSizeMb =
  856. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  857. config.grpc.maxSendMessageSizeMb =
  858. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  859. config.grpc.resourceQuotaMemoryMb =
  860. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  861. config.grpc.maxConcurrentSubscribeStreams =
  862. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  863. config.grpc.maxConcurrentFileStreams =
  864. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  865. }
  866. }
  867. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  868. // one from the legacy bind_address + rpc_port fields. This is what
  869. // every existing v2.3 deployment will hit on first v2.4 boot —
  870. // their configs don't know about listeners[] yet, and they get
  871. // exactly the same listener they had before.
  872. if (config.listeners.empty()) {
  873. ListenerConfig legacy;
  874. legacy.bind = config.bindAddress;
  875. legacy.port = config.rpcPort;
  876. legacy.tls.enabled = false;
  877. legacy.auth.required = false;
  878. config.listeners.push_back(std::move(legacy));
  879. }
  880. return config;
  881. }
  882. void DatabaseService::setupComponents() {
  883. // v2.3 multi-project storage substrate.
  884. //
  885. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  886. // project always exists and is what v2.0-v2.2 clients (which don't
  887. // address projects) implicitly use.
  888. //
  889. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  890. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  891. // atomically moves it under `projects/default/env/` before the
  892. // registry opens.
  893. migrateLegacyEnvToDefaultProject();
  894. try {
  895. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  896. constexpr uint32_t kMaxDbs = 1024;
  897. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  898. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  899. const auto opened = projects_->openExisting();
  900. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  901. opened.size(),
  902. [&opened]() {
  903. std::string s;
  904. for (size_t i = 0; i < opened.size(); ++i) {
  905. if (i) s += ", ";
  906. s += opened[i];
  907. }
  908. return s;
  909. }());
  910. } catch (const std::exception& e) {
  911. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  912. "service cannot start without LMDB; bailing",
  913. (config_.dataDirectory / "projects").string(), e.what());
  914. projects_.reset();
  915. throw;
  916. }
  917. // Create memory store with eviction config
  918. MemoryStore::Config storeConfig;
  919. storeConfig.nodeId = config_.nodeId;
  920. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  921. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  922. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  923. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  924. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  925. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  926. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  927. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  928. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  929. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  930. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  931. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  932. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  933. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  934. store_ = std::make_unique<MemoryStore>(storeConfig);
  935. // Create view manager (cache loaded in initialize() after persistence recovery)
  936. view_manager_ = std::make_unique<ViewManager>(*store_);
  937. // Create per-collection config manager and attach it to the store so the
  938. // write paths route document timestamp stamps through it.
  939. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  940. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  941. // recovery alongside the view and collection-config caches.
  942. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  943. // v2.11.0 T6a — relation declarations. Constructed here; its cache is
  944. // loaded after recovery alongside the view/config/policy caches.
  945. relation_manager_ = std::make_unique<RelationManager>(*store_);
  946. store_->setConfigManager(config_manager_.get());
  947. // v1.9.0 — disk-resident version history. Replaces the in-heap
  948. // `CollectionData::versionHistory` deques that were the dominant
  949. // source of the Zoe untracked-RSS gap. One file per collection at
  950. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  951. // here, wired into the store immediately so snapshot deserializer
  952. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  953. HistoryStore::Config histConfig;
  954. histConfig.dataDir = config_.dataDirectory;
  955. history_store_ = std::make_unique<HistoryStore>(histConfig);
  956. store_->setHistoryStore(history_store_.get());
  957. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  958. // resolver. Every write that flows through store_ commits to the
  959. // right per-project LMDB env BEFORE the per-collection lock releases.
  960. if (projects_) {
  961. auto* registry = projects_.get();
  962. store_->setDocumentStoreMirror(
  963. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  964. return registry->getOrCreate(project);
  965. },
  966. &mirror_healthy_,
  967. &mirror_drift_count_);
  968. }
  969. // Create persistence manager. Start from any persistenceConfig values the
  970. // caller (config loader / CLI parser) has already populated — including
  971. // recoveryMode — and overlay the top-level convenience fields.
  972. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  973. persistConfig.dataDir = config_.dataDirectory;
  974. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  975. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  976. persistConfig.compressionEnabled = config_.compressionEnabled;
  977. persistConfig.nodeId = config_.nodeId;
  978. // Mirror the resolved recoveryMode back into our Config so downstream code
  979. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  980. // without having to reach into the PersistenceManager.
  981. config_.persistenceConfig = persistConfig;
  982. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  983. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  984. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  985. const std::optional<Document>& doc, EventType eventType) {
  986. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  987. // sequence and record it on the store so eviction stubs can carry
  988. // a real seq (instead of doc.version, which was useless as a
  989. // `fromSequence` hint and forced a full WAL scan on every fault).
  990. uint64_t walSeq = 0;
  991. switch (eventType) {
  992. case EventType::INSERT:
  993. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  994. break;
  995. case EventType::UPDATE:
  996. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  997. break;
  998. case EventType::DELETE:
  999. persistence_->logDelete(collection, id);
  1000. break;
  1001. default:
  1002. break;
  1003. }
  1004. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  1005. store_->recordWalSequence(collection, id, walSeq);
  1006. }
  1007. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  1008. // that it runs UNDER the per-collection write lock. That closes the
  1009. // race window where readers could see a doc in MemoryStore but not
  1010. // yet in LMDB. The callback now does only WAL + replication + events.
  1011. // Queue for replication broadcast
  1012. if (replication_ && config_.replicationEnabled) {
  1013. databasepb::ReplicationEntry entry;
  1014. entry.set_collection(collection);
  1015. entry.set_document_id(id);
  1016. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  1017. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  1018. // is now treated by receivers as "legacy / unknown origin".
  1019. entry.set_node_id(config_.nodeId);
  1020. entry.set_global_timestamp(
  1021. std::chrono::duration_cast<std::chrono::milliseconds>(
  1022. std::chrono::system_clock::now().time_since_epoch()
  1023. ).count());
  1024. switch (eventType) {
  1025. case EventType::INSERT:
  1026. entry.set_op(databasepb::OP_INSERT);
  1027. // Send the full Document envelope (id, collection, data,
  1028. // version, timestamps, encryption state). The follower's
  1029. // applyReplicatedEntry uses Document::fromJson() which
  1030. // expects this envelope — sending only doc->data silently
  1031. // dropped every user field on the other side.
  1032. if (doc) entry.set_data(doc->toJson().dump());
  1033. break;
  1034. case EventType::UPDATE:
  1035. entry.set_op(databasepb::OP_UPDATE);
  1036. if (doc) entry.set_data(doc->toJson().dump());
  1037. break;
  1038. case EventType::DELETE:
  1039. entry.set_op(databasepb::OP_DELETE);
  1040. break;
  1041. default:
  1042. break;
  1043. }
  1044. replication_->queueForReplication(entry);
  1045. }
  1046. // Publish event
  1047. if (events_) {
  1048. DatabaseEvent event;
  1049. event.type = eventType;
  1050. event.collection = collection;
  1051. event.documentId = id;
  1052. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  1053. std::chrono::system_clock::now().time_since_epoch()
  1054. ).count();
  1055. event.nodeId = config_.nodeId;
  1056. if (doc) {
  1057. event.data = doc->data();
  1058. }
  1059. events_->publish(event);
  1060. }
  1061. });
  1062. // Set up document load callback for LRU eviction recovery.
  1063. //
  1064. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  1065. // callback below at append time, not the per-doc version counter).
  1066. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  1067. // returns entries with seq >= walSequence — the doc's last write is
  1068. // exactly at walSequence, so the very first hit is the one we want.
  1069. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  1070. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  1071. store_->setDocumentLoadCallback([this](const std::string& collection,
  1072. const std::string& id,
  1073. uint64_t walSequence) -> std::optional<Document> {
  1074. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  1075. return persistence_->loadDocument(collection, id, fromSequence);
  1076. });
  1077. // Create encryption manager
  1078. EncryptionManager::Config encryptConfig;
  1079. encryptConfig.enabled = config_.encryptionEnabled;
  1080. encryptConfig.keyFilePath = config_.keyFilePath;
  1081. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  1082. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  1083. // Create event manager
  1084. EventManager::Config eventConfig;
  1085. eventConfig.nodeId = config_.nodeId;
  1086. events_ = std::make_unique<EventManager>(eventConfig);
  1087. // Create file manager
  1088. FileManager::Config fileConfig;
  1089. fileConfig.filesDir = config_.dataDirectory / "files";
  1090. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  1091. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  1092. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  1093. fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
  1094. files_ = std::make_unique<FileManager>(fileConfig);
  1095. // Create replication manager
  1096. ReplicationManager::Config replConfig;
  1097. replConfig.nodeId = config_.nodeId;
  1098. replConfig.peerAddresses = config_.peerAddresses;
  1099. replConfig.conflictResolution = config_.conflictResolution;
  1100. replication_ = std::make_unique<ReplicationManager>(replConfig);
  1101. // Wire replication entry apply callback
  1102. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  1103. applyReplicatedEntry(entry);
  1104. });
  1105. // Create gRPC implementations
  1106. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  1107. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  1108. *policy_manager_, *relation_manager_
  1109. );
  1110. // v2.7.0 — hand the impl the union of every listener's keys so it can
  1111. // resolve a principal per call. A token is only accepted if some listener's
  1112. // auth processor accepted it, so the union cannot widen authentication; it
  1113. // only names what was already authenticated.
  1114. {
  1115. std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
  1116. for (const auto& l : config_.listeners) {
  1117. for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
  1118. }
  1119. storageImpl_->setPrincipalKeys(std::move(all));
  1120. }
  1121. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  1122. storageImpl_->setStreamLimits(
  1123. config_.grpc.maxConcurrentSubscribeStreams,
  1124. config_.grpc.maxConcurrentFileStreams);
  1125. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  1126. *store_, *replication_, *persistence_
  1127. );
  1128. }
  1129. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  1130. try {
  1131. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  1132. // with the originating node's id. This is what makes follower-side
  1133. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  1134. // replicated documents. Echo amplification is prevented by:
  1135. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  1136. // - SyncProtocol skipping entries whose origin is the peer itself
  1137. // both implemented in the same v1.8.0 cycle.
  1138. const std::string origin = entry.node_id().empty()
  1139. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  1140. : entry.node_id();
  1141. switch (entry.op()) {
  1142. case databasepb::OP_INSERT:
  1143. case databasepb::OP_UPDATE:
  1144. case databasepb::OP_UPSERT: {
  1145. if (entry.data().empty()) {
  1146. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  1147. return;
  1148. }
  1149. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  1150. Document doc = Document::fromJson(json);
  1151. doc.id = entry.document_id();
  1152. doc.nodeId = entry.node_id();
  1153. // loadDocument bypasses the persist-and-broadcast callback to avoid
  1154. // re-replicating; we explicitly write to the WAL right after with
  1155. // the origin-aware overload so eviction/WAL recovery still works.
  1156. store_->loadDocument(entry.collection(), doc);
  1157. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  1158. // MemoryStore persist callback that normally drives the
  1159. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  1160. // channel and reads still hit MemoryStore, so the bypass
  1161. // was harmless. In v2.3 reads are LMDB-first, so a
  1162. // follower that only filled MemoryStore would return
  1163. // empty Find/Get for every replicated doc. Route the
  1164. // entry through the same project-aware mirror the write
  1165. // handlers use.
  1166. if (projects_) {
  1167. auto pc = smartbotic::database::parseProjectCollection(
  1168. entry.collection());
  1169. if (auto* ds = projects_->getOrCreate(pc.project)) {
  1170. std::optional<Document> opt_doc(doc);
  1171. smartbotic::db::storage::applyDualWriteMirror(
  1172. ds, mirror_healthy_, mirror_drift_count_,
  1173. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1174. }
  1175. }
  1176. if (persistence_) {
  1177. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  1178. ? persistence_->logInsert(entry.collection(), doc, origin)
  1179. : persistence_->logUpdate(entry.collection(), doc, origin);
  1180. if (walSeq > 0) {
  1181. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  1182. }
  1183. }
  1184. spdlog::trace("Applied replicated {} to {}/{} from {}",
  1185. entry.op() == databasepb::OP_INSERT ? "insert" :
  1186. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  1187. entry.collection(), entry.document_id(), entry.node_id());
  1188. break;
  1189. }
  1190. case databasepb::OP_DELETE: {
  1191. store_->remove(entry.collection(), entry.document_id());
  1192. if (persistence_) {
  1193. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  1194. }
  1195. spdlog::trace("Applied replicated delete to {}/{} from {}",
  1196. entry.collection(), entry.document_id(), entry.node_id());
  1197. break;
  1198. }
  1199. case databasepb::OP_CREATE_COLLECTION: {
  1200. CollectionOptions options;
  1201. store_->createCollection(entry.collection(), options);
  1202. if (persistence_) {
  1203. persistence_->logCreateCollection(entry.collection(), options, origin);
  1204. }
  1205. spdlog::trace("Applied replicated create collection {} from {}",
  1206. entry.collection(), entry.node_id());
  1207. break;
  1208. }
  1209. case databasepb::OP_DROP_COLLECTION: {
  1210. store_->dropCollection(entry.collection());
  1211. if (persistence_) {
  1212. persistence_->logDropCollection(entry.collection(), origin);
  1213. }
  1214. spdlog::trace("Applied replicated drop collection {} from {}",
  1215. entry.collection(), entry.node_id());
  1216. break;
  1217. }
  1218. default:
  1219. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  1220. break;
  1221. }
  1222. } catch (const std::exception& e) {
  1223. spdlog::error("Failed to apply replicated entry: {}", e.what());
  1224. }
  1225. }
  1226. void DatabaseService::startGrpcServer() {
  1227. if (config_.listeners.empty()) {
  1228. // Should never hit — parseConfig's back-compat shim always
  1229. // synthesises at least one. Defend anyway.
  1230. throw std::runtime_error("startGrpcServer: no listeners configured");
  1231. }
  1232. const int64_t mb = 1024 * 1024;
  1233. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  1234. config_.grpc.maxReceiveMessageSizeMb,
  1235. config_.grpc.maxSendMessageSizeMb,
  1236. config_.grpc.resourceQuotaMemoryMb,
  1237. config_.grpc.maxConcurrentSubscribeStreams,
  1238. config_.grpc.maxConcurrentFileStreams);
  1239. grpcServers_.reserve(config_.listeners.size());
  1240. for (const auto& listener : config_.listeners) {
  1241. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  1242. grpc::ServerBuilder builder;
  1243. // v2.4 — choose credentials per listener. Plaintext for
  1244. // tls.enabled=false; SslServerCredentials with the operator's
  1245. // cert+key (or an auto-generated self-signed pair) for true.
  1246. std::shared_ptr<grpc::ServerCredentials> creds;
  1247. if (listener.tls.enabled) {
  1248. std::filesystem::path cert_path = listener.tls.cert_path;
  1249. std::filesystem::path key_path = listener.tls.key_path;
  1250. // Resolve cert+key. If either is missing/unreadable AND
  1251. // auto_self_signed_if_missing is set, generate a pair.
  1252. const bool cert_ok = !cert_path.empty()
  1253. && std::filesystem::exists(cert_path);
  1254. const bool key_ok = !key_path.empty()
  1255. && std::filesystem::exists(key_path);
  1256. if (!cert_ok || !key_ok) {
  1257. if (!listener.tls.auto_self_signed_if_missing) {
  1258. throw std::runtime_error(
  1259. "TLS listener " + addr +
  1260. ": cert or key missing and auto_self_signed_if_missing=false");
  1261. }
  1262. const auto out_dir = config_.dataDirectory / "tls";
  1263. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  1264. out_dir, listener.bind);
  1265. cert_path = gen.cert_path;
  1266. key_path = gen.key_path;
  1267. spdlog::warn(
  1268. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  1269. "auto-generated self-signed cert at '{}' (key '{}'). "
  1270. "OK for dev. For production, drop a real cert + key at "
  1271. "the configured cert_path/key_path.",
  1272. addr,
  1273. listener.tls.cert_path.string(),
  1274. listener.tls.key_path.string(),
  1275. cert_path.string(),
  1276. key_path.string());
  1277. }
  1278. auto slurp = [](const std::filesystem::path& p) {
  1279. std::ifstream f(p);
  1280. if (!f) throw std::runtime_error("read " + p.string());
  1281. std::stringstream ss; ss << f.rdbuf();
  1282. return ss.str();
  1283. };
  1284. grpc::SslServerCredentialsOptions sslOpts;
  1285. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  1286. kp.private_key = slurp(key_path);
  1287. kp.cert_chain = slurp(cert_path);
  1288. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  1289. creds = grpc::SslServerCredentials(sslOpts);
  1290. } else {
  1291. creds = grpc::InsecureServerCredentials();
  1292. }
  1293. // v2.4 Stage D — attach the bearer-token auth processor when
  1294. // the listener requires it. The processor validates the
  1295. // `authorization: Bearer <key>` metadata against the listener's
  1296. // configured keys list. gRPC rejects with UNAUTHENTICATED
  1297. // (no per-handler code needed).
  1298. if (listener.auth.required) {
  1299. if (listener.auth.keys.empty()) {
  1300. throw std::runtime_error(
  1301. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  1302. }
  1303. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  1304. // Refuse at startup rather than resolving a policy against a name
  1305. // that means two different callers.
  1306. {
  1307. std::set<std::string> seen;
  1308. for (const auto& k : listener.auth.keys) {
  1309. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  1310. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  1311. throw std::runtime_error(
  1312. "Listener " + addr + ": auth key name '" + k.name +
  1313. "' is reserved. `anonymous` denotes an unauthenticated "
  1314. "caller and `unnamed` denotes a legacy bare key; a real "
  1315. "key must not be able to impersonate either in a policy.");
  1316. }
  1317. if (!seen.insert(k.name).second &&
  1318. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  1319. throw std::runtime_error(
  1320. "Listener " + addr + ": duplicate auth key name '" +
  1321. k.name + "'. A principal must identify one caller, "
  1322. "otherwise a policy written against it is ambiguous.");
  1323. }
  1324. }
  1325. }
  1326. if (!listener.tls.enabled) {
  1327. // gRPC ABORTS the process if an auth metadata processor is
  1328. // attached to insecure credentials
  1329. // (insecure_server_credentials.cc: "assertion failed: 0").
  1330. // This used to be a WARN, which meant a plaintext+auth listener
  1331. // looked merely inadvisable in the config and then killed the
  1332. // server on start with an unexplained assert. Refuse it here
  1333. // with a message that says what to do instead.
  1334. throw std::runtime_error(
  1335. "Listener " + addr + ": auth.required=true requires "
  1336. "tls.enabled=true. gRPC does not support an auth metadata "
  1337. "processor on insecure credentials and will abort the "
  1338. "process. Enable TLS for this listener (set "
  1339. "tls.auto_self_signed_if_missing for a local dev cert), or "
  1340. "drop auth and rely on binding to loopback.");
  1341. }
  1342. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  1343. nk.reserve(listener.auth.keys.size());
  1344. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  1345. creds->SetAuthMetadataProcessor(
  1346. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  1347. std::move(nk)));
  1348. }
  1349. builder.AddListeningPort(addr, creds);
  1350. builder.RegisterService(storageImpl_.get());
  1351. builder.RegisterService(replicationImpl_.get());
  1352. builder.SetMaxReceiveMessageSize(
  1353. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  1354. builder.SetMaxSendMessageSize(
  1355. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  1356. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  1357. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  1358. builder.SetResourceQuota(quota);
  1359. auto server = builder.BuildAndStart();
  1360. if (!server) {
  1361. throw std::runtime_error("Failed to start gRPC server on " + addr);
  1362. }
  1363. // v2.4 Stage B log line — listener identity printed so operators
  1364. // know exactly which interface is exposed with which policy.
  1365. // Stage C/D will extend with TLS + auth status.
  1366. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  1367. addr,
  1368. listener.tls.enabled ? "true" : "false",
  1369. listener.auth.required ? "true" : "false");
  1370. grpcServers_.push_back(std::move(server));
  1371. }
  1372. }
  1373. void DatabaseService::stopGrpcServer() {
  1374. for (auto& server : grpcServers_) {
  1375. if (server) server->Shutdown();
  1376. }
  1377. grpcServers_.clear();
  1378. }
  1379. } // namespace smartbotic::database