database_service.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. #include "database_service.hpp"
  2. #include <grpcpp/grpcpp.h>
  3. #include <grpcpp/resource_quota.h>
  4. #include <spdlog/spdlog.h>
  5. #include <fstream>
  6. namespace smartbotic::database {
  7. DatabaseService::DatabaseService(Config config)
  8. : config_(std::move(config))
  9. {
  10. }
  11. DatabaseService::~DatabaseService() {
  12. stop();
  13. }
  14. std::string DatabaseService::readOnlyReason() const {
  15. std::lock_guard<std::mutex> lock(reason_mutex_);
  16. return read_only_reason_;
  17. }
  18. void DatabaseService::setReadOnly(bool value, const std::string& reason) {
  19. {
  20. std::lock_guard<std::mutex> lock(reason_mutex_);
  21. read_only_reason_ = value ? reason : "";
  22. }
  23. bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
  24. if (prev != value) {
  25. if (value) {
  26. spdlog::error("Database entered READ-ONLY mode: {}", reason);
  27. } else {
  28. spdlog::info("Database unlocked -- writes accepted");
  29. }
  30. }
  31. }
  32. bool DatabaseService::initialize() {
  33. spdlog::info("Initializing database service (node: {})", config_.nodeId);
  34. try {
  35. // Create data directory if needed
  36. std::error_code ec;
  37. std::filesystem::create_directories(config_.dataDirectory, ec);
  38. if (ec) {
  39. spdlog::error("Failed to create data directory: {}", ec.message());
  40. return false;
  41. }
  42. setupComponents();
  43. // Initialize encryption
  44. if (config_.encryptionEnabled) {
  45. if (!encryption_->initialize()) {
  46. spdlog::error("Failed to initialize encryption");
  47. return false;
  48. }
  49. }
  50. // Recover from persistence
  51. recovery_outcome_ = persistence_->recover(*store_);
  52. if (recovery_outcome_.isFailure()) {
  53. const std::string modeStr =
  54. recoveryModeToString(config_.persistenceConfig.recoveryMode);
  55. spdlog::error("");
  56. spdlog::error("+------------------------------------------------------------------+");
  57. spdlog::error("| RECOVERY REFUSED |");
  58. spdlog::error("| |");
  59. spdlog::error("| Mode: {}", modeStr);
  60. spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
  61. spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
  62. spdlog::error("| |");
  63. spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
  64. spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
  65. spdlog::error("| |");
  66. spdlog::error("| To escalate, restart with one of: |");
  67. spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
  68. spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
  69. spdlog::error("| --recovery-mode=best_effort Try all of the above |");
  70. spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
  71. spdlog::error("| |");
  72. spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
  73. spdlog::error("| |");
  74. spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
  75. spdlog::error("+------------------------------------------------------------------+");
  76. throw std::runtime_error("recovery failed; refusing to start");
  77. }
  78. // Auto-readonly mode on non-trivial recovery
  79. if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
  80. std::string reason;
  81. switch (recovery_outcome_.kind) {
  82. case RecoveryOutcome::Kind::SnapshotFellBack:
  83. reason = "fell back to snapshot " +
  84. recovery_outcome_.snapshotUsed.filename().string() +
  85. " because " +
  86. recovery_outcome_.expectedSnapshot.filename().string() +
  87. " failed: " + recovery_outcome_.failureReason;
  88. break;
  89. case RecoveryOutcome::Kind::WalOnlyReplay:
  90. reason = "WAL-only replay, no snapshot loaded (" +
  91. std::to_string(recovery_outcome_.walEntriesReplayed) +
  92. " entries)";
  93. break;
  94. case RecoveryOutcome::Kind::ForcedEmpty:
  95. reason = "forced empty by operator (--recovery-mode=force_empty)";
  96. break;
  97. default:
  98. reason = "non-trivial recovery";
  99. break;
  100. }
  101. reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
  102. "or restart with --force-readwrite to bypass this check.";
  103. setReadOnly(true, reason);
  104. spdlog::error("");
  105. spdlog::error("+------------------------------------------------------------------+");
  106. spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
  107. spdlog::error("| recovery. |");
  108. spdlog::error("| |");
  109. spdlog::error("| Reason: {}", reason);
  110. spdlog::error("| |");
  111. spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
  112. spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
  113. spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
  114. spdlog::error("+------------------------------------------------------------------+");
  115. }
  116. // Set replication sequence after recovery (WAL sequence is now known)
  117. replication_->setSequence(persistence_->currentWalSequence());
  118. // v1.8.0 — start the persistence manager before loadFromStore /
  119. // migrations so any system-collection writes those phases produce
  120. // (view docs, _collection_meta entries, _migrations recordings)
  121. // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
  122. // started later in start(), which silently dropped those writes
  123. // (running_=false → logInsert no-op). That meant migrated views
  124. // only "survived" because the runner re-created them every boot,
  125. // and a manually-created view that landed during the racy startup
  126. // window (before full readiness) could be lost.
  127. if (!persistence_->start()) {
  128. spdlog::error("Failed to start persistence manager before migrations");
  129. return false;
  130. }
  131. // Load view definitions from the _views system collection (which is now
  132. // populated by the persistence recovery above).
  133. view_manager_->loadFromStore();
  134. // Load per-collection configs from the _collection_meta system collection.
  135. // Must happen AFTER persistence recovery and BEFORE migrations so any
  136. // migration-created documents are stamped with the correct precision.
  137. config_manager_->loadFromStore();
  138. // Run migrations if enabled
  139. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  140. if (!runMigrations()) {
  141. if (config_.migrations.failOnError) {
  142. spdlog::error("Failed to run migrations");
  143. return false;
  144. }
  145. spdlog::warn("Some migrations failed, continuing anyway");
  146. }
  147. }
  148. spdlog::info("Database service initialized successfully");
  149. return true;
  150. } catch (const std::exception& e) {
  151. spdlog::error("Failed to initialize database service: {}", e.what());
  152. return false;
  153. }
  154. }
  155. bool DatabaseService::runMigrations() {
  156. if (!config_.migrations.enabled) {
  157. return true;
  158. }
  159. MigrationRunner::Config migrationConfig;
  160. migrationConfig.directory = config_.migrations.directory;
  161. migrationConfig.autoApply = config_.migrations.autoApply;
  162. migrationConfig.failOnError = config_.migrations.failOnError;
  163. migrationRunner_ = std::make_unique<MigrationRunner>(*store_, *view_manager_, migrationConfig);
  164. return migrationRunner_->runMigrations();
  165. }
  166. void DatabaseService::start() {
  167. if (running_.exchange(true)) {
  168. return;
  169. }
  170. spdlog::info("Starting database service on {}:{}", config_.bindAddress, config_.rpcPort);
  171. // Start components
  172. store_->start();
  173. persistence_->start();
  174. events_->start();
  175. files_->start();
  176. if (config_.replicationEnabled) {
  177. replication_->start();
  178. // Set initial local collections for discovery
  179. replication_->setLocalCollections(store_->listCollections());
  180. }
  181. // Start gRPC server
  182. startGrpcServer();
  183. spdlog::info("Database service started");
  184. }
  185. void DatabaseService::stop() {
  186. if (!running_.exchange(false)) {
  187. return;
  188. }
  189. spdlog::info("Stopping database service...");
  190. // Stop gRPC server first
  191. stopGrpcServer();
  192. // Stop components in reverse order
  193. if (replication_) {
  194. replication_->stop();
  195. }
  196. if (files_) {
  197. files_->stop();
  198. }
  199. if (events_) {
  200. events_->stop();
  201. }
  202. if (persistence_ && store_) {
  203. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  204. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  205. // replay" which trips auto-readonly mode. This makes ordinary
  206. // restarts pass through cleanly without needing
  207. // `smartbotic-db-cli unlock`.
  208. try {
  209. persistence_->forceSnapshot(*store_);
  210. spdlog::info("Final snapshot taken on shutdown");
  211. } catch (const std::exception& e) {
  212. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  213. "boot may be WAL-only and trip auto-readonly mode", e.what());
  214. }
  215. }
  216. if (persistence_) {
  217. persistence_->stop();
  218. }
  219. if (store_) {
  220. store_->stop();
  221. }
  222. spdlog::info("Database service stopped");
  223. }
  224. void DatabaseService::wait() {
  225. if (serverThread_.joinable()) {
  226. serverThread_.join();
  227. }
  228. }
  229. void DatabaseService::signalStop() {
  230. stopRequested_ = true;
  231. stop();
  232. }
  233. nlohmann::json DatabaseService::getStats() const {
  234. nlohmann::json stats;
  235. if (store_) {
  236. auto storeStats = store_->getStats();
  237. stats["documents"] = storeStats.totalDocuments;
  238. stats["collections"] = storeStats.totalCollections;
  239. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  240. stats["inserts"] = storeStats.insertCount;
  241. stats["updates"] = storeStats.updateCount;
  242. stats["deletes"] = storeStats.deleteCount;
  243. stats["queries"] = storeStats.queryCount;
  244. }
  245. if (persistence_) {
  246. auto persistStats = persistence_->getStats();
  247. stats["wal_sequence"] = persistStats.walSequence;
  248. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  249. stats["snapshot_count"] = persistStats.snapshotCount;
  250. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  251. }
  252. if (events_) {
  253. stats["subscriptions"] = events_->subscriptionCount();
  254. }
  255. return stats;
  256. }
  257. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  258. std::ifstream file(configPath);
  259. if (!file) {
  260. throw std::runtime_error("Failed to open config file: " + configPath.string());
  261. }
  262. nlohmann::json json;
  263. file >> json;
  264. return parseConfig(json);
  265. }
  266. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  267. Config config;
  268. // Check for both "storage" and "database" keys for backward compatibility
  269. const nlohmann::json* dbConfig = nullptr;
  270. if (json.contains("database")) {
  271. dbConfig = &json["database"];
  272. } else if (json.contains("storage")) {
  273. dbConfig = &json["storage"];
  274. }
  275. if (dbConfig) {
  276. const auto& db = *dbConfig;
  277. config.nodeId = db.value("node_id", config.nodeId);
  278. config.bindAddress = db.value("bind_address", config.bindAddress);
  279. config.rpcPort = db.value("rpc_port", config.rpcPort);
  280. // Expand environment variables in data directory
  281. std::string dataDir = db.value("data_directory", "");
  282. if (dataDir.find("${HOME}") != std::string::npos) {
  283. const char* home = std::getenv("HOME");
  284. if (home) {
  285. size_t pos = dataDir.find("${HOME}");
  286. dataDir.replace(pos, 7, home);
  287. }
  288. }
  289. config.dataDirectory = dataDir;
  290. // Migrations settings
  291. if (db.contains("migrations")) {
  292. auto& migrations = db["migrations"];
  293. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  294. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  295. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  296. std::string migDir = migrations.value("directory", "");
  297. if (migDir.find("${HOME}") != std::string::npos) {
  298. const char* home = std::getenv("HOME");
  299. if (home) {
  300. size_t pos = migDir.find("${HOME}");
  301. migDir.replace(pos, 7, home);
  302. }
  303. }
  304. config.migrations.directory = migDir;
  305. }
  306. // Memory eviction settings
  307. if (db.contains("memory")) {
  308. auto& memory = db["memory"];
  309. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  310. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  311. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  312. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  313. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  314. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  315. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  316. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  317. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  318. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  319. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  320. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  321. // v1.7.0 T10 — eviction burst event threshold
  322. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  323. }
  324. // Persistence settings
  325. if (db.contains("persistence")) {
  326. auto& persistence = db["persistence"];
  327. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  328. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  329. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  330. // Snapshot durability (NEW in v1.6.1)
  331. if (persistence.contains("snapshots")) {
  332. const auto& snap = persistence["snapshots"];
  333. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  334. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  335. }
  336. // Recovery (NEW in v1.6.1)
  337. if (persistence.contains("recovery")) {
  338. const auto& rec = persistence["recovery"];
  339. std::string modeStr = rec.value("mode", std::string("normal"));
  340. try {
  341. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  342. } catch (const std::exception& e) {
  343. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  344. modeStr, e.what());
  345. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  346. }
  347. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  348. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  349. }
  350. }
  351. // File settings
  352. if (db.contains("files")) {
  353. auto& files = db["files"];
  354. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  355. config.fileCleanupIntervalSec = files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  356. if (files.contains("allowed_types")) {
  357. for (const auto& type : files["allowed_types"]) {
  358. config.allowedFileTypes.push_back(type.get<std::string>());
  359. }
  360. }
  361. }
  362. // Encryption settings
  363. if (db.contains("encryption")) {
  364. auto& encryption = db["encryption"];
  365. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  366. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  367. std::string keyFile = encryption.value("key_file", "");
  368. if (keyFile.find("${HOME}") != std::string::npos) {
  369. const char* home = std::getenv("HOME");
  370. if (home) {
  371. size_t pos = keyFile.find("${HOME}");
  372. keyFile.replace(pos, 7, home);
  373. }
  374. }
  375. config.keyFilePath = keyFile;
  376. }
  377. // Replication settings
  378. if (db.contains("replication")) {
  379. auto& replication = db["replication"];
  380. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  381. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  382. if (replication.contains("peers")) {
  383. for (const auto& peer : replication["peers"]) {
  384. config.peerAddresses.push_back(peer.get<std::string>());
  385. }
  386. }
  387. }
  388. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  389. if (db.contains("grpc")) {
  390. const auto& grpc = db["grpc"];
  391. config.grpc.maxReceiveMessageSizeMb =
  392. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  393. config.grpc.maxSendMessageSizeMb =
  394. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  395. config.grpc.resourceQuotaMemoryMb =
  396. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  397. config.grpc.maxConcurrentSubscribeStreams =
  398. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  399. config.grpc.maxConcurrentFileStreams =
  400. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  401. }
  402. }
  403. return config;
  404. }
  405. void DatabaseService::setupComponents() {
  406. // Create memory store with eviction config
  407. MemoryStore::Config storeConfig;
  408. storeConfig.nodeId = config_.nodeId;
  409. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  410. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  411. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  412. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  413. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  414. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  415. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  416. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  417. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  418. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  419. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  420. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  421. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  422. store_ = std::make_unique<MemoryStore>(storeConfig);
  423. // Create view manager (cache loaded in initialize() after persistence recovery)
  424. view_manager_ = std::make_unique<ViewManager>(*store_);
  425. // Create per-collection config manager and attach it to the store so the
  426. // write paths route document timestamp stamps through it.
  427. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  428. store_->setConfigManager(config_manager_.get());
  429. // Create persistence manager. Start from any persistenceConfig values the
  430. // caller (config loader / CLI parser) has already populated — including
  431. // recoveryMode — and overlay the top-level convenience fields.
  432. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  433. persistConfig.dataDir = config_.dataDirectory;
  434. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  435. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  436. persistConfig.compressionEnabled = config_.compressionEnabled;
  437. persistConfig.nodeId = config_.nodeId;
  438. // Mirror the resolved recoveryMode back into our Config so downstream code
  439. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  440. // without having to reach into the PersistenceManager.
  441. config_.persistenceConfig = persistConfig;
  442. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  443. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  444. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  445. const std::optional<Document>& doc, EventType eventType) {
  446. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  447. // sequence and record it on the store so eviction stubs can carry
  448. // a real seq (instead of doc.version, which was useless as a
  449. // `fromSequence` hint and forced a full WAL scan on every fault).
  450. uint64_t walSeq = 0;
  451. switch (eventType) {
  452. case EventType::INSERT:
  453. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  454. break;
  455. case EventType::UPDATE:
  456. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  457. break;
  458. case EventType::DELETE:
  459. persistence_->logDelete(collection, id);
  460. break;
  461. default:
  462. break;
  463. }
  464. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  465. store_->recordWalSequence(collection, id, walSeq);
  466. }
  467. // Queue for replication broadcast
  468. if (replication_ && config_.replicationEnabled) {
  469. databasepb::ReplicationEntry entry;
  470. entry.set_collection(collection);
  471. entry.set_document_id(id);
  472. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  473. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  474. // is now treated by receivers as "legacy / unknown origin".
  475. entry.set_node_id(config_.nodeId);
  476. entry.set_global_timestamp(
  477. std::chrono::duration_cast<std::chrono::milliseconds>(
  478. std::chrono::system_clock::now().time_since_epoch()
  479. ).count());
  480. switch (eventType) {
  481. case EventType::INSERT:
  482. entry.set_op(databasepb::OP_INSERT);
  483. // Send the full Document envelope (id, collection, data,
  484. // version, timestamps, encryption state). The follower's
  485. // applyReplicatedEntry uses Document::fromJson() which
  486. // expects this envelope — sending only doc->data silently
  487. // dropped every user field on the other side.
  488. if (doc) entry.set_data(doc->toJson().dump());
  489. break;
  490. case EventType::UPDATE:
  491. entry.set_op(databasepb::OP_UPDATE);
  492. if (doc) entry.set_data(doc->toJson().dump());
  493. break;
  494. case EventType::DELETE:
  495. entry.set_op(databasepb::OP_DELETE);
  496. break;
  497. default:
  498. break;
  499. }
  500. replication_->queueForReplication(entry);
  501. }
  502. // Publish event
  503. if (events_) {
  504. DatabaseEvent event;
  505. event.type = eventType;
  506. event.collection = collection;
  507. event.documentId = id;
  508. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  509. std::chrono::system_clock::now().time_since_epoch()
  510. ).count();
  511. event.nodeId = config_.nodeId;
  512. if (doc) {
  513. event.data = doc->data;
  514. }
  515. events_->publish(event);
  516. }
  517. });
  518. // Set up document load callback for LRU eviction recovery.
  519. //
  520. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  521. // callback below at append time, not the per-doc version counter).
  522. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  523. // returns entries with seq >= walSequence — the doc's last write is
  524. // exactly at walSequence, so the very first hit is the one we want.
  525. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  526. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  527. store_->setDocumentLoadCallback([this](const std::string& collection,
  528. const std::string& id,
  529. uint64_t walSequence) -> std::optional<Document> {
  530. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  531. return persistence_->loadDocument(collection, id, fromSequence);
  532. });
  533. // Create encryption manager
  534. EncryptionManager::Config encryptConfig;
  535. encryptConfig.enabled = config_.encryptionEnabled;
  536. encryptConfig.keyFilePath = config_.keyFilePath;
  537. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  538. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  539. // Create event manager
  540. EventManager::Config eventConfig;
  541. eventConfig.nodeId = config_.nodeId;
  542. events_ = std::make_unique<EventManager>(eventConfig);
  543. // Create file manager
  544. FileManager::Config fileConfig;
  545. fileConfig.filesDir = config_.dataDirectory / "files";
  546. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  547. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  548. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  549. files_ = std::make_unique<FileManager>(fileConfig);
  550. // Create replication manager
  551. ReplicationManager::Config replConfig;
  552. replConfig.nodeId = config_.nodeId;
  553. replConfig.peerAddresses = config_.peerAddresses;
  554. replConfig.conflictResolution = config_.conflictResolution;
  555. replication_ = std::make_unique<ReplicationManager>(replConfig);
  556. // Wire replication entry apply callback
  557. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  558. applyReplicatedEntry(entry);
  559. });
  560. // Create gRPC implementations
  561. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  562. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_
  563. );
  564. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  565. storageImpl_->setStreamLimits(
  566. config_.grpc.maxConcurrentSubscribeStreams,
  567. config_.grpc.maxConcurrentFileStreams);
  568. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  569. *store_, *replication_, *persistence_
  570. );
  571. }
  572. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  573. try {
  574. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  575. // with the originating node's id. This is what makes follower-side
  576. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  577. // replicated documents. Echo amplification is prevented by:
  578. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  579. // - SyncProtocol skipping entries whose origin is the peer itself
  580. // both implemented in the same v1.8.0 cycle.
  581. const std::string origin = entry.node_id().empty()
  582. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  583. : entry.node_id();
  584. switch (entry.op()) {
  585. case databasepb::OP_INSERT:
  586. case databasepb::OP_UPDATE:
  587. case databasepb::OP_UPSERT: {
  588. if (entry.data().empty()) {
  589. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  590. return;
  591. }
  592. auto json = nlohmann::json::parse(entry.data());
  593. Document doc = Document::fromJson(json);
  594. doc.id = entry.document_id();
  595. doc.nodeId = entry.node_id();
  596. // loadDocument bypasses the persist-and-broadcast callback to avoid
  597. // re-replicating; we explicitly write to the WAL right after with
  598. // the origin-aware overload so eviction/WAL recovery still works.
  599. store_->loadDocument(entry.collection(), doc);
  600. if (persistence_) {
  601. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  602. ? persistence_->logInsert(entry.collection(), doc, origin)
  603. : persistence_->logUpdate(entry.collection(), doc, origin);
  604. if (walSeq > 0) {
  605. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  606. }
  607. }
  608. spdlog::trace("Applied replicated {} to {}/{} from {}",
  609. entry.op() == databasepb::OP_INSERT ? "insert" :
  610. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  611. entry.collection(), entry.document_id(), entry.node_id());
  612. break;
  613. }
  614. case databasepb::OP_DELETE: {
  615. store_->remove(entry.collection(), entry.document_id());
  616. if (persistence_) {
  617. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  618. }
  619. spdlog::trace("Applied replicated delete to {}/{} from {}",
  620. entry.collection(), entry.document_id(), entry.node_id());
  621. break;
  622. }
  623. case databasepb::OP_CREATE_COLLECTION: {
  624. CollectionOptions options;
  625. store_->createCollection(entry.collection(), options);
  626. if (persistence_) {
  627. persistence_->logCreateCollection(entry.collection(), options, origin);
  628. }
  629. spdlog::trace("Applied replicated create collection {} from {}",
  630. entry.collection(), entry.node_id());
  631. break;
  632. }
  633. case databasepb::OP_DROP_COLLECTION: {
  634. store_->dropCollection(entry.collection());
  635. if (persistence_) {
  636. persistence_->logDropCollection(entry.collection(), origin);
  637. }
  638. spdlog::trace("Applied replicated drop collection {} from {}",
  639. entry.collection(), entry.node_id());
  640. break;
  641. }
  642. default:
  643. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  644. break;
  645. }
  646. } catch (const std::exception& e) {
  647. spdlog::error("Failed to apply replicated entry: {}", e.what());
  648. }
  649. }
  650. void DatabaseService::startGrpcServer() {
  651. std::string serverAddress = config_.bindAddress + ":" + std::to_string(config_.rpcPort);
  652. grpc::ServerBuilder builder;
  653. builder.AddListeningPort(serverAddress, grpc::InsecureServerCredentials());
  654. builder.RegisterService(storageImpl_.get());
  655. builder.RegisterService(replicationImpl_.get());
  656. // Configurable message sizes (default 100 MB for file uploads)
  657. const int64_t mb = 1024 * 1024;
  658. builder.SetMaxReceiveMessageSize(
  659. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  660. builder.SetMaxSendMessageSize(
  661. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  662. // ResourceQuota bounds total inbound buffer memory across all RPCs
  663. grpc::ResourceQuota quota("smartbotic-db");
  664. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  665. builder.SetResourceQuota(quota);
  666. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  667. config_.grpc.maxReceiveMessageSizeMb,
  668. config_.grpc.maxSendMessageSizeMb,
  669. config_.grpc.resourceQuotaMemoryMb,
  670. config_.grpc.maxConcurrentSubscribeStreams,
  671. config_.grpc.maxConcurrentFileStreams);
  672. grpcServer_ = builder.BuildAndStart();
  673. if (!grpcServer_) {
  674. throw std::runtime_error("Failed to start gRPC server on " + serverAddress);
  675. }
  676. spdlog::info("gRPC server listening on {}", serverAddress);
  677. }
  678. void DatabaseService::stopGrpcServer() {
  679. if (grpcServer_) {
  680. grpcServer_->Shutdown();
  681. grpcServer_.reset();
  682. }
  683. }
  684. } // namespace smartbotic::database