database_service.hpp 23 KB

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