database_service.hpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. #pragma once
  2. #include "document.hpp"
  3. #include "memory_store.hpp"
  4. #include "storage/mirror_pending.hpp"
  5. #include "database_grpc_impl.hpp"
  6. #include "persistence/persistence_manager.hpp"
  7. #include "persistence/history_store.hpp"
  8. #include "encryption/encryption_manager.hpp"
  9. #include "events/event_manager.hpp"
  10. #include "files/file_manager.hpp"
  11. #include "replication/replication_manager.hpp"
  12. #include "migrations/migration_runner.hpp"
  13. #include "schema/schema_registry.hpp"
  14. #include "views/view_manager.hpp"
  15. #include "config/collection_config_manager.hpp"
  16. #include "security/policy_manager.hpp"
  17. #include "relations/relation_manager.hpp"
  18. // LMDB storage substrate (v2.0+). DocumentStore + LmdbEnv live alongside the
  19. // v1.x MemoryStore, which is still the write entry point and a bounded read
  20. // cache; writes are mirrored into LMDB under MemoryStore's per-collection lock
  21. // and reads are LMDB-first while the mirror is healthy.
  22. //
  23. // This coexistence is deliberate and still current. Retiring MemoryStore means
  24. // migrating the write handlers onto a WriteCoordinator - see the "Pending"
  25. // section of docs/ROADMAP.md. Older comments call that "Stage 4"; the "Phase C"
  26. // label they sometimes carry refers to a homegrown page engine that was never
  27. // built (LMDB replaced it).
  28. namespace smartbotic::db::storage {
  29. class LmdbEnv;
  30. class DocumentStore;
  31. class ProjectStoreRegistry;
  32. }
  33. #include <nlohmann/json.hpp>
  34. #include <atomic>
  35. #include <filesystem>
  36. #include <memory>
  37. #include <mutex>
  38. #include <string>
  39. #include <string_view>
  40. #include <unordered_map>
  41. #include <thread>
  42. #include <vector>
  43. namespace grpc {
  44. class Server;
  45. }
  46. namespace smartbotic::database {
  47. /**
  48. * Main storage service application.
  49. * Coordinates all components and manages the gRPC server.
  50. */
  51. class DatabaseService {
  52. public:
  53. // v2.4 — per-listener configuration. Each binding can have its own
  54. // TLS material and auth policy. The default 127.0.0.1 listener
  55. // preserves v2.3 behaviour (plaintext, no auth) so existing local
  56. // consumers keep working without code change.
  57. struct ListenerConfig {
  58. std::string bind = "127.0.0.1";
  59. uint16_t port = 9004;
  60. struct TlsConfig {
  61. bool enabled = false;
  62. std::filesystem::path cert_path;
  63. std::filesystem::path key_path;
  64. // When TLS is enabled but cert+key are missing/unreadable, the
  65. // server auto-generates a 10-year self-signed cert to
  66. // <dataDir>/tls/auto_self_signed.{pem,key}. Operators who run
  67. // a real PKI override by dropping their cert at cert_path.
  68. bool auto_self_signed_if_missing = true;
  69. } tls;
  70. struct AuthConfig {
  71. bool required = false;
  72. // v2.7.0 — a key now carries a name, which becomes the
  73. // PRINCIPAL that access policy is written against.
  74. //
  75. // Config accepts either form:
  76. // "keys": [ {"name": "shadowman", "key": "<base64>"} ]
  77. // "keys": [ "<base64>" ] // v2.4-v2.6 shape
  78. //
  79. // A bare string still authenticates and maps to the reserved
  80. // principal `unnamed`, so existing deployments keep working; they
  81. // simply cannot be told apart in a policy until they are named.
  82. struct NamedKey {
  83. std::string name; // principal; "unnamed" when config gave a bare string
  84. std::string key; // the bearer token itself
  85. };
  86. // Bearer tokens accepted by this listener. Constant-time
  87. // compared against the value of the `authorization` gRPC
  88. // metadata header. Rotation = add new key, distribute,
  89. // remove old key. Empty list with required=true is a config
  90. // error caught at startup.
  91. std::vector<NamedKey> keys;
  92. } auth;
  93. };
  94. struct Config {
  95. std::string nodeId = "storage-1";
  96. // v2.4 — listener fleet. Empty means "synthesize a single
  97. // back-compat listener from the legacy bindAddress + rpcPort
  98. // fields below". Once any listener is configured here, the
  99. // legacy fields are ignored.
  100. std::vector<ListenerConfig> listeners;
  101. // v2.3 legacy single-listener fields. Kept so existing
  102. // config.json files continue to work — the config loader
  103. // synthesises a ListenerConfig from these when `listeners` is
  104. // empty. Operators who want TLS or auth must use the
  105. // `listeners[]` schema instead of these.
  106. std::string bindAddress = "0.0.0.0";
  107. uint16_t rpcPort = 9004;
  108. // v2.21.0 - `storage.consistency`: what the boot key audit does about
  109. // rows MemoryStore and LMDB disagree on whose cause is unknown (rows
  110. // whose LMDB copy is KNOWN to have failed are repaired from the
  111. // mirror-pending log regardless). disk_only: adopt | report | remove;
  112. // memory_only: report | write | remove. An unknown value means report.
  113. std::string consistencyDiskOnly = "adopt";
  114. std::string consistencyMemoryOnly = "report";
  115. // v2.21.7 - what the boot version audit does with a row memory holds
  116. // in a NEWER version than LMDB (a write whose LMDB copy failed before
  117. // 2.21.0 recorded such failures): report (leave it; reads show LMDB's
  118. // older copy until the next write) | write (copy memory's version to
  119. // LMDB at boot).
  120. std::string consistencyMemoryNewer = "report";
  121. // Bootstrap/service registration
  122. std::string webapiUrl;
  123. std::string serviceKey;
  124. uint32_t heartbeatIntervalSec = 30;
  125. std::filesystem::path dataDirectory;
  126. std::filesystem::path keyFilePath;
  127. // Memory eviction settings
  128. uint64_t maxMemoryMb = 800; // Max memory before eviction
  129. uint32_t evictionThresholdPercent = 80; // Start evicting at this %
  130. uint32_t evictionTargetPercent = 60; // Evict down to this %
  131. uint32_t evictionCheckIntervalMs = 5000; // How often to check
  132. // NEW v1.7.0 eviction tuning — mirrors MemoryStore::Config fields.
  133. // Plumbed here so the config loader can set them and setupComponents()
  134. // can copy them into the MemoryStore. Schema-only in T2; behavior lands
  135. // in T3/T4.
  136. uint32_t evictionChunkSize = 1000;
  137. uint32_t evictionChunkPauseMs = 50;
  138. uint32_t maxEvictionPassesPerTrigger = 20;
  139. uint32_t hotWriteFloorMs = 30000;
  140. uint32_t memorySoftPercent = 70;
  141. uint32_t memoryHardPercent = 85;
  142. uint32_t memoryEmergencyPercent = 95;
  143. // v1.7.0 T10 — eviction burst event threshold (docs per tick).
  144. uint32_t evictionBurstThreshold = 10000;
  145. // v2.4.3 — cap on the share of the resident set one pressure episode
  146. // may evict. 0 disables. See MemoryStore::Config for the rationale.
  147. uint32_t evictionMaxEpisodePercent = 50;
  148. // v2.11.0 close-out (round-3 review, item 5) — TTL sweep budgets, under
  149. // `storage.ttl` in config.json. Mirrors of MemoryStore::Config's fields
  150. // of the same name; see there for what each one bounds and why the
  151. // blocked-document budget is separate from the fresh one. Present here
  152. // because a header calling them tunable while nothing read them from
  153. // config meant production always ran the defaults and an operator facing
  154. // a blocked-document flood could not change the cadence without a
  155. // rebuild.
  156. uint32_t ttlMaxCandidatesPerSweep = 10000;
  157. uint32_t ttlMaxBlockedRetriesPerSweep = 100;
  158. uint32_t ttlBlockedRetrySweeps = 60;
  159. uint32_t ttlBlockedSummarySweeps = 300;
  160. // Persistence settings
  161. uint32_t walSyncIntervalMs = 100;
  162. uint32_t snapshotIntervalSec = 3600;
  163. bool compressionEnabled = true;
  164. // Full persistence manager config (recovery mode, etc.).
  165. // DatabaseService::setupComponents() overlays the simpler fields above
  166. // onto this struct before constructing PersistenceManager.
  167. PersistenceManager::Config persistenceConfig;
  168. // File storage settings
  169. uint64_t maxFileSizeMb = 500;
  170. std::vector<std::string> allowedFileTypes;
  171. uint32_t fileCleanupIntervalSec = 3600;
  172. // v2.8.0 — default file retention per type. See
  173. // FileManager::Config::defaultTtlSecondsByType for the key syntax.
  174. std::unordered_map<std::string, uint32_t> fileDefaultTtlByType;
  175. // Encryption settings
  176. bool encryptionEnabled = true;
  177. bool autoGenerateKey = true;
  178. // Replication settings
  179. bool replicationEnabled = true;
  180. std::vector<std::string> peerAddresses;
  181. std::string conflictResolution = "last_writer_wins";
  182. // Migration settings
  183. struct MigrationsConfig {
  184. bool enabled = true;
  185. std::filesystem::path directory;
  186. bool autoApply = true;
  187. bool failOnError = true;
  188. } migrations;
  189. // gRPC server settings (v1.6.2 — concurrency cap + configurable sizes)
  190. struct GrpcConfig {
  191. uint32_t maxReceiveMessageSizeMb = 100;
  192. uint32_t maxSendMessageSizeMb = 100;
  193. uint32_t resourceQuotaMemoryMb = 256;
  194. uint32_t maxConcurrentSubscribeStreams = 50;
  195. uint32_t maxConcurrentFileStreams = 10;
  196. };
  197. GrpcConfig grpc;
  198. };
  199. explicit DatabaseService(Config config);
  200. ~DatabaseService();
  201. /**
  202. * Initialize the service.
  203. * Loads configuration, initializes components, and prepares for startup.
  204. */
  205. bool initialize();
  206. /**
  207. * Start the service.
  208. * Starts the gRPC server and all background threads.
  209. */
  210. void start();
  211. /**
  212. * Stop the service.
  213. * Gracefully shuts down all components.
  214. */
  215. void stop();
  216. /**
  217. * Wait for the service to stop.
  218. */
  219. void wait();
  220. /**
  221. * Check if the service is running.
  222. */
  223. [[nodiscard]] bool isRunning() const { return running_; }
  224. /**
  225. * Signal the service to stop (for signal handlers).
  226. */
  227. void signalStop();
  228. /**
  229. * Get service statistics.
  230. */
  231. [[nodiscard]] nlohmann::json getStats() const;
  232. /**
  233. * Access the view manager (for RPC handlers, migrations, etc.).
  234. */
  235. ViewManager& viewManager() { return *view_manager_; }
  236. PolicyManager& policyManager() { return *policy_manager_; }
  237. /** Current read-only state (atomic, lock-free read). */
  238. bool isReadOnly() const { return read_only_.load(std::memory_order_acquire); }
  239. /** Human-readable reason the DB is read-only (empty when writable). */
  240. std::string readOnlyReason() const;
  241. /** Toggle read-only state. Called by SetReadOnly RPC and startup logic. */
  242. void setReadOnly(bool value, const std::string& reason);
  243. /** Recovery outcome from the last recover() call. Used by GetReadOnlyStatus RPC. */
  244. const RecoveryOutcome& recoveryOutcome() const { return recovery_outcome_; }
  245. /** Set the force-readwrite flag (from --force-readwrite CLI arg). */
  246. void setForceReadwrite(bool value) { force_readwrite_ = value; }
  247. /**
  248. * Load configuration from a JSON file.
  249. */
  250. static Config loadConfig(const std::filesystem::path& configPath);
  251. /**
  252. * Parse configuration from an already-loaded JSON object. Used by the
  253. * conf.d drop-in loader (see config/config_loader.hpp) after it has
  254. * merged /etc/smartbotic-database/config.json with every *.json in
  255. * /etc/smartbotic-database/conf.d/.
  256. */
  257. static Config parseConfig(const nlohmann::json& json);
  258. // v2.3 — project-aware read accessors. `docStore(project)` returns
  259. // the per-project LmdbDocumentStore or nullptr if the project isn't
  260. // open (rare unless someone dropped it concurrently). The no-arg
  261. // `docStore()` defaults to the "default" project for callers still
  262. // on the v2.0-v2.2 API shape (Stage D will retire it). Health +
  263. // drift atomics gate any LMDB-first read path.
  264. smartbotic::db::storage::DocumentStore* docStore() noexcept;
  265. smartbotic::db::storage::DocumentStore* docStore(std::string_view project) noexcept;
  266. smartbotic::db::storage::ProjectStoreRegistry* projects() noexcept {
  267. return projects_.get();
  268. }
  269. bool mirrorHealthy() const noexcept {
  270. return mirror_healthy_.load(std::memory_order_acquire);
  271. }
  272. uint64_t mirrorDriftCount() const noexcept {
  273. return mirror_drift_count_.load(std::memory_order_relaxed);
  274. }
  275. // v2.11.0 close-out — drift accrued AFTER the boot path finished. What
  276. // destructive relation policies gate on; every READ gate keeps using
  277. // mirrorDriftCount() above. See MemoryStore::markMirrorDriftBaseline().
  278. uint64_t mirrorDriftSinceReady() const noexcept {
  279. return store_ == nullptr ? 0 : store_->mirrorDriftSinceBaseline();
  280. }
  281. uint64_t mirrorDriftAtReady() const noexcept {
  282. return store_ == nullptr ? 0 : store_->mirrorDriftBaseline();
  283. }
  284. // v2.11.0 T12 review (C2) — replication queueing + Subscribe event
  285. // publication, extracted out of the MemoryStore persistCallback_
  286. // lambda (setupComponents()) so a caller that deliberately bypasses
  287. // that callback can still drive both explicitly, in the same shape
  288. // the callback itself uses. This is what a cascade's `executeCascade`
  289. // (relations/relation_cascade.cpp) calls once per child mutation and
  290. // once for the parent delete, AFTER MemoryStore has been updated —
  291. // mirroring how v2.3.1 fixed replicated-entry apply by explicitly
  292. // driving `applyDualWriteMirror` rather than relying on a callback
  293. // that had already been bypassed for the same "don't double up on
  294. // WAL/mirror" reason. `collection` is the QUALIFIED name (what
  295. // `ReplicationEntry`/`DatabaseEvent` both expect); `doc` is null for a
  296. // delete. Does NOT touch WAL or the LMDB mirror — those are the
  297. // caller's job, done separately, and calling this a second time for
  298. // the same mutation would double-queue replication and double-publish
  299. // the event, so callers must call it exactly once per mutation.
  300. //
  301. // v2.12.0 - `actor` fills DatabaseEvent::actor. std::nullopt takes it
  302. // from doc->updatedBy, which every insert/update stamps from its request;
  303. // a value is used as given. Cascade callers MUST pass one: a child the
  304. // cascade nulled still carries its previous writer in updatedBy, and the
  305. // event has to name the caller whose delete caused it.
  306. void notifyReplicationAndEvents(const std::string& collection,
  307. const std::string& id,
  308. const std::optional<Document>& doc,
  309. EventType eventType,
  310. const std::optional<std::string>& actor = std::nullopt);
  311. // v2.3 Stage F — project CRUD entry points (delegate to registry).
  312. // The registry is the source of truth for listing / creating / dropping.
  313. // CreateProject is idempotent. DropProject refuses "default". The
  314. // gRPC handlers in database_grpc_impl.cpp call these.
  315. std::vector<std::string> listProjects() const;
  316. bool createProject(const std::string& name, std::string& error);
  317. bool dropProject(const std::string& name, std::string& error);
  318. private:
  319. void setupComponents();
  320. void startGrpcServer();
  321. void stopGrpcServer();
  322. void applyReplicatedEntry(const databasepb::ReplicationEntry& entry);
  323. bool runMigrations();
  324. // v2.0 Stage 4 — synchronous backfill of MemoryStore into doc_store_.
  325. // Runs once at boot, after recovery + migrations, before gRPC accepts
  326. // traffic. Skips when _meta.schema_version=2 marker exists (the env
  327. // is already populated by migrate_v1_to_v2). Returns false only on
  328. // catastrophic failure; per-doc errors flip mirror_healthy_=false but
  329. // do not abort boot (the read-flip downstream is the gate).
  330. bool backfillIntoDocStore();
  331. // v2.4.4 — audit every open project env for documents whose declared
  332. // `collection` disagrees with the sub-db they occupy. Logs ERROR per
  333. // affected project and leaves a summary; never fails startup.
  334. void auditSubdbPlacement();
  335. // v2.20.2 - read-only: compares each collection's LMDB ids with
  336. // MemoryStore's (resident + evicted) and logs both differences.
  337. void auditMemoryDiskKeys();
  338. // v2.21.4 - reload from LMDB every resident row whose _version or
  339. // _updated_at differs from LMDB's (memory left behind by an incomplete
  340. // WAL replay). Returns the number of rows reloaded.
  341. uint64_t repairStaleResidentRows();
  342. // v2.21.0 - re-mirror the rows whose LMDB copy failed (mirror-pending log).
  343. void replayMirrorPending();
  344. void recordMirrorFailure(const std::string& collection, const std::string& id);
  345. // v2.9.0 — arm the write path and query planner with the index declarations
  346. // persisted in _collection_meta. Must run at boot, after config load.
  347. void applyIndexDeclarations();
  348. // v2.16.0 - compile and arm the collection schemas persisted in
  349. // _collection_meta. Runs at boot after config load; a schema that no longer
  350. // compiles (a newer binary's keyword read by an older one cannot happen -
  351. // records only ever hold schemas this binary accepted - but a hand-edited
  352. // record can) is logged and NOT armed.
  353. void applySchemaDeclarations();
  354. // v2.17.0 - the one-time at-rest encryption migration and the seal that
  355. // removes old plaintext copies. Runs at the end of initialize(), before any
  356. // background thread or listener starts.
  357. void migrateEncryptionAtRest();
  358. public:
  359. // v2.16.0 - the armed schemas; the gRPC handlers change them.
  360. smartbotic::db::schema::SchemaRegistry& schemaRegistry() { return schemas_; }
  361. // A stored body as a schema judges it: read metadata and `_vector` removed,
  362. // sensitive fields decrypted. A copy; used by the write check, the
  363. // existing-row check and the suggester alike, so they cannot disagree.
  364. nlohmann::json schemaView(const nlohmann::json& body) const;
  365. // v2.17.0 - encrypt, in place, every stored body of `collection` (live
  366. // rows, LMDB-only rows and history versions) that holds plaintext its rule
  367. // requires encrypted. Idempotent: ciphertext is never encrypted again.
  368. struct AtRestStats {
  369. uint64_t scanned = 0, rewritten = 0, lmdbOnly = 0, versions = 0;
  370. };
  371. AtRestStats encryptCollectionAtRest(const std::string& collection);
  372. // v2.17.0 - old plaintext copies (WAL, older snapshots, LMDB free pages)
  373. // can only be removed at boot; ask the next boot to do it.
  374. // v2.17.2: `project` names the one project whose env must be compacted;
  375. // empty means every project (the failure paths). Requests accumulate, one
  376. // line per request, until a boot performs the seal.
  377. void requestResealAtNextBoot(const std::string& project = "");
  378. // v2.17.0 - the one-time migration ran and no reseal is pending.
  379. bool atRestSealed() const {
  380. std::error_code ec;
  381. return std::filesystem::exists(config_.dataDirectory / "encryption-at-rest.v1", ec) &&
  382. !std::filesystem::exists(config_.dataDirectory / "encryption-reseal.pending", ec);
  383. }
  384. HistoryStore* historyStore() { return history_store_.get(); }
  385. // v2.17.0 - which values of `collection` are stored encrypted.
  386. EncryptionRule encryptionRuleFor(const std::string& collection) const {
  387. EncryptionRule r;
  388. store_->encryptionOptionsFor(collection, r.wholeDocument, r.paths);
  389. return r;
  390. }
  391. bool isSensitivePath(const std::string& path) const { return encryption_->isSensitiveField(path); }
  392. private:
  393. // v2.11.0 close-out — MemoryStore::TtlExpiryRelationHook. Decides what the
  394. // TTL sweeper must do about an expiring parent's children, and PERFORMS the
  395. // cascade itself when one is required, by calling the ordinary
  396. // relations/relation_cascade.cpp machinery (WAL-before-LMDB) rather than a
  397. // second, sweeper-local implementation - a hand-rolled cascade that wrote
  398. // only LMDB would have its child deletions resurrected by the next boot's
  399. // WAL replay, since MemoryStore is rebuilt from snapshot + WAL and NOT from
  400. // LMDB.
  401. //
  402. // Runs on the cleanup thread with NO MemoryStore lock held (that is
  403. // MemoryStore::expireDocuments()' phase-2 contract, and it is what makes
  404. // calling back into MemoryStore here safe). Installed in setupComponents();
  405. // must never throw (the sweeper catches, but a throw per document would
  406. // stop expiry making progress).
  407. MemoryStore::TtlExpiryAction ttlExpiryRelationDecision(
  408. const std::string& qualifiedCollection, const std::string& id, bool firstAttempt);
  409. // v2.11.0 T6a — arm each project's LmdbDocumentStore with the relation
  410. // declarations loaded by relation_manager_->loadFromStore(), grouped by
  411. // CHILD collection. LmdbDocumentStore has no knowledge of RelationManager
  412. // and maintains the reverse index for nothing until told to via
  413. // set_relations() (see Task 3's report) — this is what tells it, once at
  414. // boot. Task 6b's createRelation/dropRelation RPCs must call
  415. // set_relations() again on live mutation; this only covers what was
  416. // already persisted at startup.
  417. // `afterMigrations` only affects LOGGING (see the self-heal block): a
  418. // relation whose reverse index sub-db is absent is a fault at boot and the
  419. // expected state for a relation a migration just declared, and the same code
  420. // handles both.
  421. void applyRelationDeclarations(bool afterMigrations = false);
  422. // v2.3 Stage C — atomic rename of <dataDir>/env/ into
  423. // <dataDir>/projects/default/env/ when the v2.2 layout is detected
  424. // and the new layout doesn't yet exist. Idempotent. Refuses to start
  425. // if both exist (likely operator hand-mess); the operator must
  426. // resolve manually.
  427. void migrateLegacyEnvToDefaultProject();
  428. Config config_;
  429. std::atomic<bool> running_{false};
  430. std::atomic<bool> stopRequested_{false};
  431. // Components
  432. std::unique_ptr<MemoryStore> store_;
  433. // v2.3 — multi-project storage substrate. Each project is one
  434. // LmdbEnv at `<dataDir>/projects/<name>/env/`. The registry holds
  435. // them in a map keyed by project name, lazy-opens new projects on
  436. // first write, and is the single source of truth for "which projects
  437. // exist." Old v2.0-v2.2 installs auto-migrate the legacy
  438. // `<dataDir>/env/` into `<dataDir>/projects/default/env/` at first
  439. // boot (see migrateLegacyEnvToDefaultProject).
  440. std::unique_ptr<smartbotic::db::storage::ProjectStoreRegistry> projects_;
  441. // v2.0 dual-write health. The persist callback mirrors every user-
  442. // collection write into doc_store_; on failure we log ERROR, bump the
  443. // drift counter, and flip mirror_healthy_ to false. Downstream Stage 4
  444. // tasks that flip reads onto doc_store_ MUST check mirror_healthy_
  445. // before engaging — a degraded mirror means LMDB is missing writes.
  446. std::atomic<bool> mirror_healthy_{true};
  447. std::atomic<uint64_t> mirror_drift_count_{0};
  448. // v2.21.0 - rows whose LMDB mirror write failed, kept until a boot
  449. // re-mirrors them (storage/mirror_pending.hpp).
  450. std::unique_ptr<smartbotic::db::storage::MirrorPendingLog> mirror_pending_;
  451. std::unique_ptr<PersistenceManager> persistence_;
  452. std::unique_ptr<HistoryStore> history_store_; // v1.9.0 — disk-resident history
  453. std::unique_ptr<EncryptionManager> encryption_;
  454. std::unique_ptr<EventManager> events_;
  455. std::unique_ptr<FileManager> files_;
  456. std::unique_ptr<ReplicationManager> replication_;
  457. std::unique_ptr<ViewManager> view_manager_;
  458. std::unique_ptr<CollectionConfigManager> config_manager_;
  459. smartbotic::db::schema::SchemaRegistry schemas_; // v2.16.0
  460. // v2.8.0 — per-project access policy. Owned here so its cache is loaded
  461. // once, after recovery, alongside ViewManager and CollectionConfigManager.
  462. std::unique_ptr<PolicyManager> policy_manager_;
  463. // v2.11.0 T6a — relation declarations. Owned here so its cache is loaded
  464. // once, after recovery, alongside ViewManager/CollectionConfigManager/PolicyManager.
  465. std::unique_ptr<RelationManager> relation_manager_;
  466. // gRPC
  467. std::unique_ptr<DatabaseGrpcImpl> storageImpl_;
  468. std::unique_ptr<DatabaseReplicationGrpcImpl> replicationImpl_;
  469. // v2.4 — one gRPC Server per listener (each one ports.json entry
  470. // builds a separate Server instance with its own TLS / auth
  471. // policy). Pre-2.4 there was a single grpcServer_ wired to
  472. // bindAddress + rpcPort; the back-compat shim in parseConfig
  473. // synthesises exactly one entry for v2.3-shape configs so the
  474. // observable behavior is unchanged on upgrade.
  475. std::vector<std::unique_ptr<grpc::Server>> grpcServers_;
  476. std::thread serverThread_;
  477. // Migration runner
  478. std::unique_ptr<MigrationRunner> migrationRunner_;
  479. // Read-only runtime state (v1.6.1 — auto-readonly on non-trivial recovery)
  480. std::atomic<bool> read_only_{false};
  481. mutable std::mutex reason_mutex_;
  482. std::string read_only_reason_;
  483. RecoveryOutcome recovery_outcome_;
  484. bool force_readwrite_ = false;
  485. };
  486. } // namespace smartbotic::database