database_service.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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 (BUG-memory-leak-zoe.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. // Run migrations if enabled
  175. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  176. if (!runMigrations()) {
  177. if (config_.migrations.failOnError) {
  178. spdlog::error("Failed to run migrations");
  179. return false;
  180. }
  181. spdlog::warn("Some migrations failed, continuing anyway");
  182. }
  183. }
  184. // v2.0 Stage 4 — synchronous backfill into doc_store_ before
  185. // serving. Without this, only post-boot writes land in LMDB and
  186. // the read-flip downstream would see an empty mirror.
  187. backfillIntoDocStore();
  188. // v2.4.4 — placement audit. Reports documents sitting in a sub-db
  189. // other than the one they declare, which is the signature of a
  190. // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
  191. // advisory: it never blocks startup, because a misplacement is a
  192. // data-location problem an operator repairs offline with
  193. // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
  194. // service on the other 99% of the dataset.
  195. auditSubdbPlacement();
  196. // v2.6.0 — stamp `project: "default"` onto file records written before
  197. // files were namespaced. Idempotent, and advisory: a file-metadata
  198. // stamp is not a reason to refuse service, so failures warn only.
  199. if (files_) {
  200. try {
  201. const uint32_t stamped = files_->stampMissingProjects();
  202. if (stamped > 0) {
  203. spdlog::info("v2.6.0 file migration: stamped {} legacy file "
  204. "record(s) with project 'default'", stamped);
  205. } else {
  206. spdlog::debug("v2.6.0 file migration: no legacy file records");
  207. }
  208. } catch (const std::exception& e) {
  209. spdlog::warn("v2.6.0 file migration failed: {}", e.what());
  210. }
  211. }
  212. spdlog::info("Database service initialized successfully");
  213. return true;
  214. } catch (const std::exception& e) {
  215. spdlog::error("Failed to initialize database service: {}", e.what());
  216. return false;
  217. }
  218. }
  219. void DatabaseService::migrateLegacyEnvToDefaultProject() {
  220. const auto legacy = config_.dataDirectory / "env";
  221. const auto target = config_.dataDirectory / "projects" /
  222. smartbotic::database::kDefaultProject / "env";
  223. std::error_code ec;
  224. const bool legacy_exists = std::filesystem::exists(legacy, ec);
  225. const bool target_exists = std::filesystem::exists(target, ec);
  226. if (!legacy_exists) return; // fresh install or already migrated
  227. if (target_exists) {
  228. spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
  229. "refusing to start. Inspect manually; the safe move is "
  230. "to either delete the legacy dir (if you confirm it's a "
  231. "leftover) or stop and contact ops.",
  232. legacy.string(), target.string());
  233. throw std::runtime_error("v2.3 storage migration: ambiguous layout");
  234. }
  235. std::filesystem::create_directories(target.parent_path(), ec);
  236. if (ec) {
  237. throw std::runtime_error("v2.3 storage migration: cannot create '"
  238. + target.parent_path().string() + "': " + ec.message());
  239. }
  240. std::filesystem::rename(legacy, target, ec);
  241. if (ec) {
  242. throw std::runtime_error("v2.3 storage migration: rename '"
  243. + legacy.string() + "' -> '"
  244. + target.string() + "' failed: " + ec.message());
  245. }
  246. spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
  247. legacy.string(), target.string());
  248. }
  249. smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
  250. return docStore(smartbotic::database::kDefaultProject);
  251. }
  252. smartbotic::db::storage::DocumentStore*
  253. DatabaseService::docStore(std::string_view project) noexcept {
  254. if (!projects_) return nullptr;
  255. return projects_->get(project);
  256. }
  257. std::vector<std::string> DatabaseService::listProjects() const {
  258. if (!projects_) return {};
  259. return projects_->listOnDisk();
  260. }
  261. bool DatabaseService::createProject(const std::string& name, std::string& error) {
  262. if (!projects_) {
  263. error = "project registry not initialized";
  264. return false;
  265. }
  266. return projects_->create(name, error);
  267. }
  268. bool DatabaseService::dropProject(const std::string& name, std::string& error) {
  269. if (!projects_) {
  270. error = "project registry not initialized";
  271. return false;
  272. }
  273. return projects_->drop(name, error);
  274. }
  275. bool DatabaseService::runMigrations() {
  276. if (!config_.migrations.enabled) {
  277. return true;
  278. }
  279. MigrationRunner::Config migrationConfig;
  280. migrationConfig.directory = config_.migrations.directory;
  281. migrationConfig.autoApply = config_.migrations.autoApply;
  282. migrationConfig.failOnError = config_.migrations.failOnError;
  283. migrationRunner_ = std::make_unique<MigrationRunner>(*store_, *view_manager_, migrationConfig);
  284. return migrationRunner_->runMigrations();
  285. }
  286. void DatabaseService::auditSubdbPlacement() {
  287. if (!projects_) return;
  288. for (const auto& name : projects_->listOpen()) {
  289. auto h = projects_->getHandle(name);
  290. if (!h.env) continue;
  291. try {
  292. // audit_env(), NOT audit(). The path-taking overload opens a
  293. // second MDB_env on the same file; closing it would drop the
  294. // POSIX record locks this process already holds for `h.env`
  295. // (POSIX locks are per-process, and closing any fd on a file
  296. // releases all of them), leaving every later mdb_txn_begin
  297. // failing EINVAL. Borrow the open handle instead.
  298. const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
  299. if (rep.misplaced.empty()) {
  300. spdlog::debug("placement audit: project '{}' consistent ({} rows)",
  301. name, rep.rows_scanned);
  302. continue;
  303. }
  304. // Summarise per (physical -> declared home) pair; one line per
  305. // affected document would be unreadable at scale.
  306. std::map<std::string, uint64_t> pairs;
  307. for (const auto& m : rep.misplaced) {
  308. ++pairs[m.physical_subdb + " -> " + m.home_subdb];
  309. }
  310. spdlog::error("placement audit: project '{}' has {} document(s) in the "
  311. "wrong sub-db. Reads served from LMDB will not find them "
  312. "under their own collection. Repair offline with: "
  313. "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
  314. name, rep.misplaced.size(), h.env->path(), name);
  315. for (const auto& [pair, count] : pairs) {
  316. spdlog::error("placement audit: {} document(s) {}", count, pair);
  317. }
  318. } catch (const std::exception& e) {
  319. // Advisory only — a failed audit must not take the service down.
  320. spdlog::warn("placement audit: project '{}' could not be audited: {}",
  321. name, e.what());
  322. }
  323. }
  324. }
  325. bool DatabaseService::backfillIntoDocStore() {
  326. if (!projects_) {
  327. // Registry open failed earlier; nothing to back-fill into.
  328. return true;
  329. }
  330. // v2.3 — MemoryStore stores collection keys in qualified form
  331. // ("project:collection"). For the default project (back-compat
  332. // path) the marker check operates on the default env. Skip when
  333. // already migrated.
  334. auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
  335. if (handle.env) {
  336. try {
  337. if (smartbotic::db::storage::migration_complete(*handle.env)) {
  338. spdlog::info("v2.3 backfill: default project already migrated, skipping");
  339. return true;
  340. }
  341. } catch (const std::exception& e) {
  342. spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
  343. "treating default env as fresh and proceeding",
  344. e.what());
  345. }
  346. }
  347. const auto collections = store_->listCollections();
  348. uint64_t total_docs = 0;
  349. uint64_t total_failures = 0;
  350. auto t0 = std::chrono::steady_clock::now();
  351. for (const auto& qualified : collections) {
  352. if (qualified.empty() || qualified[0] == '_') continue;
  353. // Each qualified key parses to (project, collection); route the
  354. // mirror write to the right project's env.
  355. smartbotic::database::ProjectCollection pc;
  356. try {
  357. pc = smartbotic::database::parseProjectCollection(qualified);
  358. } catch (const std::exception&) {
  359. // Legacy unqualified key — treat as default project.
  360. pc = {std::string(smartbotic::database::kDefaultProject), qualified};
  361. }
  362. auto* ds = projects_->getOrCreate(pc.project);
  363. if (!ds) {
  364. ++total_failures;
  365. continue;
  366. }
  367. const auto docs = store_->getAllDocuments(qualified);
  368. for (const auto& doc : docs) {
  369. std::optional<Document> opt_doc(doc);
  370. const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
  371. smartbotic::db::storage::applyDualWriteMirror(
  372. ds, mirror_healthy_, mirror_drift_count_,
  373. pc.collection, doc.id, opt_doc, EventType::INSERT);
  374. if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
  375. ++total_failures;
  376. }
  377. ++total_docs;
  378. if (total_docs % 10000 == 0) {
  379. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  380. const std::string status = "STATUS=v2.3 backfill: " +
  381. std::to_string(total_docs) + " docs mirrored";
  382. sd_notify(0, status.c_str());
  383. spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
  384. total_docs, total_failures);
  385. }
  386. }
  387. }
  388. const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  389. std::chrono::steady_clock::now() - t0).count();
  390. if (total_failures == 0) {
  391. // Stamp schema_version=2 on every opened project env. Subsequent
  392. // boots short-circuit at migration_complete().
  393. for (const auto& name : projects_->listOpen()) {
  394. auto h = projects_->getHandle(name);
  395. if (!h.env) continue;
  396. try {
  397. smartbotic::db::storage::mark_migration_complete(*h.env);
  398. } catch (const std::exception& e) {
  399. spdlog::warn("v2.3 backfill: schema_version marker write failed for "
  400. "project '{}': {}", name, e.what());
  401. }
  402. }
  403. spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
  404. total_docs, collections.size(), elapsed);
  405. } else {
  406. spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
  407. "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
  408. total_failures, total_docs, elapsed);
  409. }
  410. return true;
  411. }
  412. void DatabaseService::start() {
  413. if (running_.exchange(true)) {
  414. return;
  415. }
  416. spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
  417. // Start components
  418. store_->start();
  419. persistence_->start();
  420. events_->start();
  421. files_->start();
  422. if (config_.replicationEnabled) {
  423. replication_->start();
  424. // Set initial local collections for discovery
  425. replication_->setLocalCollections(store_->listCollections());
  426. }
  427. // Start gRPC server
  428. startGrpcServer();
  429. spdlog::info("Database service started");
  430. }
  431. void DatabaseService::stop() {
  432. if (!running_.exchange(false)) {
  433. return;
  434. }
  435. spdlog::info("Stopping database service...");
  436. // Stop gRPC server first
  437. stopGrpcServer();
  438. // Stop components in reverse order
  439. if (replication_) {
  440. replication_->stop();
  441. }
  442. if (files_) {
  443. files_->stop();
  444. }
  445. if (events_) {
  446. events_->stop();
  447. }
  448. if (persistence_ && store_) {
  449. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  450. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  451. // replay" which trips auto-readonly mode. This makes ordinary
  452. // restarts pass through cleanly without needing
  453. // `smartbotic-db-cli unlock`.
  454. //
  455. // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
  456. // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
  457. // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
  458. // RSS hit 11 GB (live state + uncompressed serialize buffer), and
  459. // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
  460. // tells systemd we're working — same protocol the recovery path
  461. // uses during startup. Paired with TimeoutStopSec=300 in the unit
  462. // file as the static cap.
  463. #ifdef HAVE_SYSTEMD
  464. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  465. sd_notify(0, "STATUS=Writing final snapshot");
  466. #endif
  467. try {
  468. persistence_->forceSnapshot(*store_);
  469. spdlog::info("Final snapshot taken on shutdown");
  470. } catch (const std::exception& e) {
  471. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  472. "boot may be WAL-only and trip auto-readonly mode", e.what());
  473. }
  474. }
  475. if (persistence_) {
  476. persistence_->stop();
  477. }
  478. if (store_) {
  479. store_->stop();
  480. }
  481. spdlog::info("Database service stopped");
  482. }
  483. void DatabaseService::wait() {
  484. if (serverThread_.joinable()) {
  485. serverThread_.join();
  486. }
  487. }
  488. void DatabaseService::signalStop() {
  489. stopRequested_ = true;
  490. stop();
  491. }
  492. nlohmann::json DatabaseService::getStats() const {
  493. nlohmann::json stats;
  494. if (store_) {
  495. auto storeStats = store_->getStats();
  496. stats["documents"] = storeStats.totalDocuments;
  497. stats["collections"] = storeStats.totalCollections;
  498. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  499. stats["inserts"] = storeStats.insertCount;
  500. stats["updates"] = storeStats.updateCount;
  501. stats["deletes"] = storeStats.deleteCount;
  502. stats["queries"] = storeStats.queryCount;
  503. }
  504. if (persistence_) {
  505. auto persistStats = persistence_->getStats();
  506. stats["wal_sequence"] = persistStats.walSequence;
  507. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  508. stats["snapshot_count"] = persistStats.snapshotCount;
  509. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  510. }
  511. if (events_) {
  512. stats["subscriptions"] = events_->subscriptionCount();
  513. }
  514. return stats;
  515. }
  516. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  517. std::ifstream file(configPath);
  518. if (!file) {
  519. throw std::runtime_error("Failed to open config file: " + configPath.string());
  520. }
  521. nlohmann::json json;
  522. file >> json;
  523. return parseConfig(json);
  524. }
  525. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  526. Config config;
  527. // Check for both "storage" and "database" keys for backward compatibility
  528. const nlohmann::json* dbConfig = nullptr;
  529. if (json.contains("database")) {
  530. dbConfig = &json["database"];
  531. } else if (json.contains("storage")) {
  532. dbConfig = &json["storage"];
  533. }
  534. if (dbConfig) {
  535. const auto& db = *dbConfig;
  536. config.nodeId = db.value("node_id", config.nodeId);
  537. config.bindAddress = db.value("bind_address", config.bindAddress);
  538. config.rpcPort = db.value("rpc_port", config.rpcPort);
  539. // v2.4 — parse the per-listener fleet. If "listeners" is set,
  540. // it overrides the legacy bind_address+rpc_port. Otherwise we
  541. // synthesise one listener below using those legacy fields.
  542. if (db.contains("listeners") && db["listeners"].is_array()) {
  543. for (const auto& l : db["listeners"]) {
  544. ListenerConfig lc;
  545. lc.bind = l.value("bind", lc.bind);
  546. lc.port = l.value("port", lc.port);
  547. if (l.contains("tls") && l["tls"].is_object()) {
  548. const auto& t = l["tls"];
  549. lc.tls.enabled = t.value("enabled", false);
  550. lc.tls.cert_path = t.value("cert_path", std::string{});
  551. lc.tls.key_path = t.value("key_path", std::string{});
  552. lc.tls.auto_self_signed_if_missing =
  553. t.value("auto_self_signed_if_missing", true);
  554. }
  555. if (l.contains("auth") && l["auth"].is_object()) {
  556. const auto& a = l["auth"];
  557. lc.auth.required = a.value("required", false);
  558. if (a.contains("keys") && a["keys"].is_array()) {
  559. for (const auto& k : a["keys"]) {
  560. // v2.7.0 — a key is either a bare token (v2.4-v2.6
  561. // shape) or {"name","key"}. The name becomes the
  562. // principal that policy is written against; a bare
  563. // token maps to the reserved `unnamed`, so old
  564. // configs keep authenticating but cannot be told
  565. // apart in a policy until they are named.
  566. if (k.is_string()) {
  567. lc.auth.keys.push_back(
  568. {smartbotic::database::auth::kPrincipalUnnamed,
  569. k.get<std::string>()});
  570. } else if (k.is_object()) {
  571. const std::string name = k.value("name", std::string{});
  572. const std::string key = k.value("key", std::string{});
  573. if (key.empty()) {
  574. spdlog::warn("auth: listener {}:{} has a key entry "
  575. "with no `key` value - skipped",
  576. lc.bind, lc.port);
  577. continue;
  578. }
  579. lc.auth.keys.push_back(
  580. {name.empty()
  581. ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
  582. : name,
  583. key});
  584. }
  585. }
  586. }
  587. }
  588. config.listeners.push_back(std::move(lc));
  589. }
  590. }
  591. // Expand environment variables in data directory
  592. std::string dataDir = db.value("data_directory", "");
  593. if (dataDir.find("${HOME}") != std::string::npos) {
  594. const char* home = std::getenv("HOME");
  595. if (home) {
  596. size_t pos = dataDir.find("${HOME}");
  597. dataDir.replace(pos, 7, home);
  598. }
  599. }
  600. config.dataDirectory = dataDir;
  601. // Migrations settings
  602. if (db.contains("migrations")) {
  603. auto& migrations = db["migrations"];
  604. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  605. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  606. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  607. std::string migDir = migrations.value("directory", "");
  608. if (migDir.find("${HOME}") != std::string::npos) {
  609. const char* home = std::getenv("HOME");
  610. if (home) {
  611. size_t pos = migDir.find("${HOME}");
  612. migDir.replace(pos, 7, home);
  613. }
  614. }
  615. config.migrations.directory = migDir;
  616. }
  617. // Memory eviction settings
  618. if (db.contains("memory")) {
  619. auto& memory = db["memory"];
  620. // v2.0 Stage 8 — deprecation log. These knobs control MemoryStore
  621. // eviction, which is still active for the MemoryStore-side mirror
  622. // but does NOT bound RSS in v2.0 (LMDB mmap is the dominant RSS
  623. // contributor). The substrate-level equivalent is the LMDB env
  624. // mapsize and OS page cache. v2.1 will rename `max_memory_mb` to
  625. // `buffer_pool_size_mb` per the Phase C plan.
  626. for (const char* deprecated : {"max_memory_mb",
  627. "eviction_threshold_percent",
  628. "eviction_target_percent",
  629. "eviction_check_interval_ms",
  630. "eviction_chunk_size",
  631. "eviction_chunk_pause_ms",
  632. "max_eviction_passes_per_trigger",
  633. "hot_write_floor_ms",
  634. "memory_priority"}) {
  635. if (memory.contains(deprecated)) {
  636. spdlog::warn("v2.0 deprecation: storage.memory.{} is deprecated "
  637. "and will be removed in v2.1. v2.0 RSS is bounded "
  638. "by the LMDB env mapsize + OS page cache, not by "
  639. "MemoryStore eviction. Setting still applied to "
  640. "the MemoryStore mirror for back-compat.",
  641. deprecated);
  642. }
  643. }
  644. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  645. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  646. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  647. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  648. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  649. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  650. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  651. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  652. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  653. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  654. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  655. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  656. // v1.7.0 T10 — eviction burst event threshold
  657. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  658. // v2.4.3 — eviction drain cap (0 disables)
  659. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  660. }
  661. // Persistence settings
  662. if (db.contains("persistence")) {
  663. auto& persistence = db["persistence"];
  664. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  665. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  666. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  667. // Snapshot durability (NEW in v1.6.1)
  668. if (persistence.contains("snapshots")) {
  669. const auto& snap = persistence["snapshots"];
  670. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  671. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  672. }
  673. // Recovery (NEW in v1.6.1)
  674. if (persistence.contains("recovery")) {
  675. const auto& rec = persistence["recovery"];
  676. std::string modeStr = rec.value("mode", std::string("normal"));
  677. try {
  678. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  679. } catch (const std::exception& e) {
  680. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  681. modeStr, e.what());
  682. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  683. }
  684. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  685. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  686. }
  687. }
  688. // File settings
  689. if (db.contains("files")) {
  690. auto& files = db["files"];
  691. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  692. config.fileCleanupIntervalSec = files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  693. if (files.contains("allowed_types")) {
  694. for (const auto& type : files["allowed_types"]) {
  695. config.allowedFileTypes.push_back(type.get<std::string>());
  696. }
  697. }
  698. }
  699. // Encryption settings
  700. if (db.contains("encryption")) {
  701. auto& encryption = db["encryption"];
  702. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  703. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  704. std::string keyFile = encryption.value("key_file", "");
  705. if (keyFile.find("${HOME}") != std::string::npos) {
  706. const char* home = std::getenv("HOME");
  707. if (home) {
  708. size_t pos = keyFile.find("${HOME}");
  709. keyFile.replace(pos, 7, home);
  710. }
  711. }
  712. config.keyFilePath = keyFile;
  713. }
  714. // Replication settings
  715. if (db.contains("replication")) {
  716. auto& replication = db["replication"];
  717. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  718. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  719. if (replication.contains("peers")) {
  720. for (const auto& peer : replication["peers"]) {
  721. config.peerAddresses.push_back(peer.get<std::string>());
  722. }
  723. }
  724. }
  725. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  726. if (db.contains("grpc")) {
  727. const auto& grpc = db["grpc"];
  728. config.grpc.maxReceiveMessageSizeMb =
  729. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  730. config.grpc.maxSendMessageSizeMb =
  731. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  732. config.grpc.resourceQuotaMemoryMb =
  733. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  734. config.grpc.maxConcurrentSubscribeStreams =
  735. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  736. config.grpc.maxConcurrentFileStreams =
  737. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  738. }
  739. }
  740. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  741. // one from the legacy bind_address + rpc_port fields. This is what
  742. // every existing v2.3 deployment will hit on first v2.4 boot —
  743. // their configs don't know about listeners[] yet, and they get
  744. // exactly the same listener they had before.
  745. if (config.listeners.empty()) {
  746. ListenerConfig legacy;
  747. legacy.bind = config.bindAddress;
  748. legacy.port = config.rpcPort;
  749. legacy.tls.enabled = false;
  750. legacy.auth.required = false;
  751. config.listeners.push_back(std::move(legacy));
  752. }
  753. return config;
  754. }
  755. void DatabaseService::setupComponents() {
  756. // v2.3 multi-project storage substrate.
  757. //
  758. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  759. // project always exists and is what v2.0-v2.2 clients (which don't
  760. // address projects) implicitly use.
  761. //
  762. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  763. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  764. // atomically moves it under `projects/default/env/` before the
  765. // registry opens.
  766. migrateLegacyEnvToDefaultProject();
  767. try {
  768. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  769. constexpr uint32_t kMaxDbs = 1024;
  770. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  771. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  772. const auto opened = projects_->openExisting();
  773. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  774. opened.size(),
  775. [&opened]() {
  776. std::string s;
  777. for (size_t i = 0; i < opened.size(); ++i) {
  778. if (i) s += ", ";
  779. s += opened[i];
  780. }
  781. return s;
  782. }());
  783. } catch (const std::exception& e) {
  784. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  785. "service cannot start without LMDB; bailing",
  786. (config_.dataDirectory / "projects").string(), e.what());
  787. projects_.reset();
  788. throw;
  789. }
  790. // Create memory store with eviction config
  791. MemoryStore::Config storeConfig;
  792. storeConfig.nodeId = config_.nodeId;
  793. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  794. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  795. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  796. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  797. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  798. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  799. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  800. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  801. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  802. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  803. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  804. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  805. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  806. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  807. store_ = std::make_unique<MemoryStore>(storeConfig);
  808. // Create view manager (cache loaded in initialize() after persistence recovery)
  809. view_manager_ = std::make_unique<ViewManager>(*store_);
  810. // Create per-collection config manager and attach it to the store so the
  811. // write paths route document timestamp stamps through it.
  812. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  813. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  814. // recovery alongside the view and collection-config caches.
  815. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  816. store_->setConfigManager(config_manager_.get());
  817. // v1.9.0 — disk-resident version history. Replaces the in-heap
  818. // `CollectionData::versionHistory` deques that were the dominant
  819. // source of the Zoe untracked-RSS gap. One file per collection at
  820. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  821. // here, wired into the store immediately so snapshot deserializer
  822. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  823. HistoryStore::Config histConfig;
  824. histConfig.dataDir = config_.dataDirectory;
  825. history_store_ = std::make_unique<HistoryStore>(histConfig);
  826. store_->setHistoryStore(history_store_.get());
  827. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  828. // resolver. Every write that flows through store_ commits to the
  829. // right per-project LMDB env BEFORE the per-collection lock releases.
  830. if (projects_) {
  831. auto* registry = projects_.get();
  832. store_->setDocumentStoreMirror(
  833. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  834. return registry->getOrCreate(project);
  835. },
  836. &mirror_healthy_,
  837. &mirror_drift_count_);
  838. }
  839. // Create persistence manager. Start from any persistenceConfig values the
  840. // caller (config loader / CLI parser) has already populated — including
  841. // recoveryMode — and overlay the top-level convenience fields.
  842. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  843. persistConfig.dataDir = config_.dataDirectory;
  844. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  845. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  846. persistConfig.compressionEnabled = config_.compressionEnabled;
  847. persistConfig.nodeId = config_.nodeId;
  848. // Mirror the resolved recoveryMode back into our Config so downstream code
  849. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  850. // without having to reach into the PersistenceManager.
  851. config_.persistenceConfig = persistConfig;
  852. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  853. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  854. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  855. const std::optional<Document>& doc, EventType eventType) {
  856. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  857. // sequence and record it on the store so eviction stubs can carry
  858. // a real seq (instead of doc.version, which was useless as a
  859. // `fromSequence` hint and forced a full WAL scan on every fault).
  860. uint64_t walSeq = 0;
  861. switch (eventType) {
  862. case EventType::INSERT:
  863. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  864. break;
  865. case EventType::UPDATE:
  866. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  867. break;
  868. case EventType::DELETE:
  869. persistence_->logDelete(collection, id);
  870. break;
  871. default:
  872. break;
  873. }
  874. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  875. store_->recordWalSequence(collection, id, walSeq);
  876. }
  877. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  878. // that it runs UNDER the per-collection write lock. That closes the
  879. // race window where readers could see a doc in MemoryStore but not
  880. // yet in LMDB. The callback now does only WAL + replication + events.
  881. // Queue for replication broadcast
  882. if (replication_ && config_.replicationEnabled) {
  883. databasepb::ReplicationEntry entry;
  884. entry.set_collection(collection);
  885. entry.set_document_id(id);
  886. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  887. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  888. // is now treated by receivers as "legacy / unknown origin".
  889. entry.set_node_id(config_.nodeId);
  890. entry.set_global_timestamp(
  891. std::chrono::duration_cast<std::chrono::milliseconds>(
  892. std::chrono::system_clock::now().time_since_epoch()
  893. ).count());
  894. switch (eventType) {
  895. case EventType::INSERT:
  896. entry.set_op(databasepb::OP_INSERT);
  897. // Send the full Document envelope (id, collection, data,
  898. // version, timestamps, encryption state). The follower's
  899. // applyReplicatedEntry uses Document::fromJson() which
  900. // expects this envelope — sending only doc->data silently
  901. // dropped every user field on the other side.
  902. if (doc) entry.set_data(doc->toJson().dump());
  903. break;
  904. case EventType::UPDATE:
  905. entry.set_op(databasepb::OP_UPDATE);
  906. if (doc) entry.set_data(doc->toJson().dump());
  907. break;
  908. case EventType::DELETE:
  909. entry.set_op(databasepb::OP_DELETE);
  910. break;
  911. default:
  912. break;
  913. }
  914. replication_->queueForReplication(entry);
  915. }
  916. // Publish event
  917. if (events_) {
  918. DatabaseEvent event;
  919. event.type = eventType;
  920. event.collection = collection;
  921. event.documentId = id;
  922. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  923. std::chrono::system_clock::now().time_since_epoch()
  924. ).count();
  925. event.nodeId = config_.nodeId;
  926. if (doc) {
  927. event.data = doc->data();
  928. }
  929. events_->publish(event);
  930. }
  931. });
  932. // Set up document load callback for LRU eviction recovery.
  933. //
  934. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  935. // callback below at append time, not the per-doc version counter).
  936. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  937. // returns entries with seq >= walSequence — the doc's last write is
  938. // exactly at walSequence, so the very first hit is the one we want.
  939. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  940. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  941. store_->setDocumentLoadCallback([this](const std::string& collection,
  942. const std::string& id,
  943. uint64_t walSequence) -> std::optional<Document> {
  944. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  945. return persistence_->loadDocument(collection, id, fromSequence);
  946. });
  947. // Create encryption manager
  948. EncryptionManager::Config encryptConfig;
  949. encryptConfig.enabled = config_.encryptionEnabled;
  950. encryptConfig.keyFilePath = config_.keyFilePath;
  951. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  952. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  953. // Create event manager
  954. EventManager::Config eventConfig;
  955. eventConfig.nodeId = config_.nodeId;
  956. events_ = std::make_unique<EventManager>(eventConfig);
  957. // Create file manager
  958. FileManager::Config fileConfig;
  959. fileConfig.filesDir = config_.dataDirectory / "files";
  960. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  961. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  962. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  963. files_ = std::make_unique<FileManager>(fileConfig);
  964. // Create replication manager
  965. ReplicationManager::Config replConfig;
  966. replConfig.nodeId = config_.nodeId;
  967. replConfig.peerAddresses = config_.peerAddresses;
  968. replConfig.conflictResolution = config_.conflictResolution;
  969. replication_ = std::make_unique<ReplicationManager>(replConfig);
  970. // Wire replication entry apply callback
  971. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  972. applyReplicatedEntry(entry);
  973. });
  974. // Create gRPC implementations
  975. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  976. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  977. *policy_manager_
  978. );
  979. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  980. storageImpl_->setStreamLimits(
  981. config_.grpc.maxConcurrentSubscribeStreams,
  982. config_.grpc.maxConcurrentFileStreams);
  983. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  984. *store_, *replication_, *persistence_
  985. );
  986. }
  987. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  988. try {
  989. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  990. // with the originating node's id. This is what makes follower-side
  991. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  992. // replicated documents. Echo amplification is prevented by:
  993. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  994. // - SyncProtocol skipping entries whose origin is the peer itself
  995. // both implemented in the same v1.8.0 cycle.
  996. const std::string origin = entry.node_id().empty()
  997. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  998. : entry.node_id();
  999. switch (entry.op()) {
  1000. case databasepb::OP_INSERT:
  1001. case databasepb::OP_UPDATE:
  1002. case databasepb::OP_UPSERT: {
  1003. if (entry.data().empty()) {
  1004. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  1005. return;
  1006. }
  1007. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  1008. Document doc = Document::fromJson(json);
  1009. doc.id = entry.document_id();
  1010. doc.nodeId = entry.node_id();
  1011. // loadDocument bypasses the persist-and-broadcast callback to avoid
  1012. // re-replicating; we explicitly write to the WAL right after with
  1013. // the origin-aware overload so eviction/WAL recovery still works.
  1014. store_->loadDocument(entry.collection(), doc);
  1015. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  1016. // MemoryStore persist callback that normally drives the
  1017. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  1018. // channel and reads still hit MemoryStore, so the bypass
  1019. // was harmless. In v2.3 reads are LMDB-first, so a
  1020. // follower that only filled MemoryStore would return
  1021. // empty Find/Get for every replicated doc. Route the
  1022. // entry through the same project-aware mirror the write
  1023. // handlers use.
  1024. if (projects_) {
  1025. auto pc = smartbotic::database::parseProjectCollection(
  1026. entry.collection());
  1027. if (auto* ds = projects_->getOrCreate(pc.project)) {
  1028. std::optional<Document> opt_doc(doc);
  1029. smartbotic::db::storage::applyDualWriteMirror(
  1030. ds, mirror_healthy_, mirror_drift_count_,
  1031. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1032. }
  1033. }
  1034. if (persistence_) {
  1035. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  1036. ? persistence_->logInsert(entry.collection(), doc, origin)
  1037. : persistence_->logUpdate(entry.collection(), doc, origin);
  1038. if (walSeq > 0) {
  1039. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  1040. }
  1041. }
  1042. spdlog::trace("Applied replicated {} to {}/{} from {}",
  1043. entry.op() == databasepb::OP_INSERT ? "insert" :
  1044. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  1045. entry.collection(), entry.document_id(), entry.node_id());
  1046. break;
  1047. }
  1048. case databasepb::OP_DELETE: {
  1049. store_->remove(entry.collection(), entry.document_id());
  1050. if (persistence_) {
  1051. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  1052. }
  1053. spdlog::trace("Applied replicated delete to {}/{} from {}",
  1054. entry.collection(), entry.document_id(), entry.node_id());
  1055. break;
  1056. }
  1057. case databasepb::OP_CREATE_COLLECTION: {
  1058. CollectionOptions options;
  1059. store_->createCollection(entry.collection(), options);
  1060. if (persistence_) {
  1061. persistence_->logCreateCollection(entry.collection(), options, origin);
  1062. }
  1063. spdlog::trace("Applied replicated create collection {} from {}",
  1064. entry.collection(), entry.node_id());
  1065. break;
  1066. }
  1067. case databasepb::OP_DROP_COLLECTION: {
  1068. store_->dropCollection(entry.collection());
  1069. if (persistence_) {
  1070. persistence_->logDropCollection(entry.collection(), origin);
  1071. }
  1072. spdlog::trace("Applied replicated drop collection {} from {}",
  1073. entry.collection(), entry.node_id());
  1074. break;
  1075. }
  1076. default:
  1077. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  1078. break;
  1079. }
  1080. } catch (const std::exception& e) {
  1081. spdlog::error("Failed to apply replicated entry: {}", e.what());
  1082. }
  1083. }
  1084. void DatabaseService::startGrpcServer() {
  1085. if (config_.listeners.empty()) {
  1086. // Should never hit — parseConfig's back-compat shim always
  1087. // synthesises at least one. Defend anyway.
  1088. throw std::runtime_error("startGrpcServer: no listeners configured");
  1089. }
  1090. const int64_t mb = 1024 * 1024;
  1091. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  1092. config_.grpc.maxReceiveMessageSizeMb,
  1093. config_.grpc.maxSendMessageSizeMb,
  1094. config_.grpc.resourceQuotaMemoryMb,
  1095. config_.grpc.maxConcurrentSubscribeStreams,
  1096. config_.grpc.maxConcurrentFileStreams);
  1097. grpcServers_.reserve(config_.listeners.size());
  1098. for (const auto& listener : config_.listeners) {
  1099. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  1100. grpc::ServerBuilder builder;
  1101. // v2.4 — choose credentials per listener. Plaintext for
  1102. // tls.enabled=false; SslServerCredentials with the operator's
  1103. // cert+key (or an auto-generated self-signed pair) for true.
  1104. std::shared_ptr<grpc::ServerCredentials> creds;
  1105. if (listener.tls.enabled) {
  1106. std::filesystem::path cert_path = listener.tls.cert_path;
  1107. std::filesystem::path key_path = listener.tls.key_path;
  1108. // Resolve cert+key. If either is missing/unreadable AND
  1109. // auto_self_signed_if_missing is set, generate a pair.
  1110. const bool cert_ok = !cert_path.empty()
  1111. && std::filesystem::exists(cert_path);
  1112. const bool key_ok = !key_path.empty()
  1113. && std::filesystem::exists(key_path);
  1114. if (!cert_ok || !key_ok) {
  1115. if (!listener.tls.auto_self_signed_if_missing) {
  1116. throw std::runtime_error(
  1117. "TLS listener " + addr +
  1118. ": cert or key missing and auto_self_signed_if_missing=false");
  1119. }
  1120. const auto out_dir = config_.dataDirectory / "tls";
  1121. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  1122. out_dir, listener.bind);
  1123. cert_path = gen.cert_path;
  1124. key_path = gen.key_path;
  1125. spdlog::warn(
  1126. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  1127. "auto-generated self-signed cert at '{}' (key '{}'). "
  1128. "OK for dev. For production, drop a real cert + key at "
  1129. "the configured cert_path/key_path.",
  1130. addr,
  1131. listener.tls.cert_path.string(),
  1132. listener.tls.key_path.string(),
  1133. cert_path.string(),
  1134. key_path.string());
  1135. }
  1136. auto slurp = [](const std::filesystem::path& p) {
  1137. std::ifstream f(p);
  1138. if (!f) throw std::runtime_error("read " + p.string());
  1139. std::stringstream ss; ss << f.rdbuf();
  1140. return ss.str();
  1141. };
  1142. grpc::SslServerCredentialsOptions sslOpts;
  1143. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  1144. kp.private_key = slurp(key_path);
  1145. kp.cert_chain = slurp(cert_path);
  1146. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  1147. creds = grpc::SslServerCredentials(sslOpts);
  1148. } else {
  1149. creds = grpc::InsecureServerCredentials();
  1150. }
  1151. // v2.4 Stage D — attach the bearer-token auth processor when
  1152. // the listener requires it. The processor validates the
  1153. // `authorization: Bearer <key>` metadata against the listener's
  1154. // configured keys list. gRPC rejects with UNAUTHENTICATED
  1155. // (no per-handler code needed).
  1156. if (listener.auth.required) {
  1157. if (listener.auth.keys.empty()) {
  1158. throw std::runtime_error(
  1159. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  1160. }
  1161. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  1162. // Refuse at startup rather than resolving a policy against a name
  1163. // that means two different callers.
  1164. {
  1165. std::set<std::string> seen;
  1166. for (const auto& k : listener.auth.keys) {
  1167. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  1168. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  1169. throw std::runtime_error(
  1170. "Listener " + addr + ": auth key name '" + k.name +
  1171. "' is reserved. `anonymous` denotes an unauthenticated "
  1172. "caller and `unnamed` denotes a legacy bare key; a real "
  1173. "key must not be able to impersonate either in a policy.");
  1174. }
  1175. if (!seen.insert(k.name).second &&
  1176. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  1177. throw std::runtime_error(
  1178. "Listener " + addr + ": duplicate auth key name '" +
  1179. k.name + "'. A principal must identify one caller, "
  1180. "otherwise a policy written against it is ambiguous.");
  1181. }
  1182. }
  1183. }
  1184. if (!listener.tls.enabled) {
  1185. spdlog::warn(
  1186. "Listener {}: auth.required=true but tls.enabled=false — "
  1187. "the bearer token is sent in cleartext over the wire. "
  1188. "Consider enabling TLS for any non-loopback listener.",
  1189. addr);
  1190. }
  1191. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  1192. nk.reserve(listener.auth.keys.size());
  1193. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  1194. creds->SetAuthMetadataProcessor(
  1195. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  1196. std::move(nk)));
  1197. }
  1198. builder.AddListeningPort(addr, creds);
  1199. builder.RegisterService(storageImpl_.get());
  1200. builder.RegisterService(replicationImpl_.get());
  1201. builder.SetMaxReceiveMessageSize(
  1202. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  1203. builder.SetMaxSendMessageSize(
  1204. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  1205. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  1206. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  1207. builder.SetResourceQuota(quota);
  1208. auto server = builder.BuildAndStart();
  1209. if (!server) {
  1210. throw std::runtime_error("Failed to start gRPC server on " + addr);
  1211. }
  1212. // v2.4 Stage B log line — listener identity printed so operators
  1213. // know exactly which interface is exposed with which policy.
  1214. // Stage C/D will extend with TLS + auth status.
  1215. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  1216. addr,
  1217. listener.tls.enabled ? "true" : "false",
  1218. listener.auth.required ? "true" : "false");
  1219. grpcServers_.push_back(std::move(server));
  1220. }
  1221. }
  1222. void DatabaseService::stopGrpcServer() {
  1223. for (auto& server : grpcServers_) {
  1224. if (server) server->Shutdown();
  1225. }
  1226. grpcServers_.clear();
  1227. }
  1228. } // namespace smartbotic::database