document.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. #pragma once
  2. #include <string>
  3. #include <string_view>
  4. #include <vector>
  5. #include <chrono>
  6. #include <optional>
  7. #include <nlohmann/json.hpp>
  8. #include "doc_binary.hpp"
  9. namespace smartbotic::database {
  10. /**
  11. * v2.13.0 - the metadata names a read attaches to every document. They live
  12. * on the Document, never in its data, so a write body carrying them (a row read
  13. * back and written again, which is exactly what an export -> import does) must
  14. * not store them. Before 2.13.0 insert/upsert/update/patch stored them as
  15. * ordinary user fields that every read then hid by overwriting them with the
  16. * real metadata: invisible, unfilterable (a filter on `_version` resolves to
  17. * the metadata), and carried into every later export. Nothing could depend on
  18. * the stored copies, since no read path ever showed them.
  19. */
  20. inline bool isReservedField(std::string_view key) {
  21. return key == "_id" || key == "_version" || key == "_created_at" ||
  22. key == "_updated_at" || key == "_created_by" || key == "_updated_by";
  23. }
  24. /** Remove the reserved metadata names from a top-level write body. */
  25. inline void stripReservedFields(nlohmann::json& body) {
  26. if (!body.is_object()) return;
  27. for (auto it = body.begin(); it != body.end();) {
  28. if (isReservedField(it.key())) it = body.erase(it); else ++it;
  29. }
  30. }
  31. /**
  32. * Represents a document stored in a collection.
  33. * Documents are JSON objects with metadata for versioning, TTL, and encryption.
  34. * Named Document to avoid conflict with proto-generated Document message.
  35. */
  36. struct Document {
  37. std::string id; // Unique document ID within collection
  38. std::string collection; // Collection name
  39. // v1.11+ — Binary in-memory storage. The canonical state lives in
  40. // data_binary (yyjson mut_doc-backed). data_view is a lazily-materialised
  41. // nlohmann::json cache for full-tree access; invalidated on set_data().
  42. // See docs/superpowers/specs/2026-05-15-binary-doc-format-decision.md.
  43. smartbotic::db::doc_binary::Doc data_binary;
  44. mutable std::optional<nlohmann::json> data_view;
  45. uint64_t version = 1; // Monotonic version for optimistic locking
  46. uint64_t createdAt = 0; // Creation timestamp (ms since epoch)
  47. uint64_t updatedAt = 0; // Last modification timestamp (ms since epoch)
  48. uint64_t expiresAt = 0; // TTL expiration (0 = no expiration)
  49. std::string nodeId; // Origin node for replication
  50. bool encrypted = false; // Whether sensitive fields are encrypted
  51. std::vector<std::string> encryptedFields; // List of encrypted field paths
  52. std::string createdBy; // User ID who created the document
  53. std::string updatedBy; // User ID who last updated the document
  54. uint64_t lastAccessedAt = 0; // Last read access timestamp (for LRU eviction)
  55. // v2.13.0 - whether this document's last write left it with a stored
  56. // vector. Recorded only in collections with a vector dimension; absent on
  57. // rows written before 2.13.0. It lets an export tell a row that never had a
  58. // vector (false) from one whose vector entry is gone (true, no entry) - the
  59. // stored body alone cannot, because `_vector` is stripped on write.
  60. std::optional<bool> hasVector;
  61. // Lazy full-tree accessor. Materialises on first call, returns cached
  62. // reference thereafter. Cost: one decode() pass plus the cache memory.
  63. // Prefer field() for single-field reads.
  64. [[nodiscard]] const nlohmann::json& data() const {
  65. if (!data_view) {
  66. data_view = smartbotic::db::doc_binary::decode(data_binary);
  67. }
  68. return *data_view;
  69. }
  70. // Replace the binary payload from an nlohmann::json tree. Invalidates the
  71. // cached view so subsequent data() materialises fresh from data_binary.
  72. void set_data(const nlohmann::json& j) {
  73. data_binary = smartbotic::db::doc_binary::encode(j);
  74. data_view.reset();
  75. }
  76. // Fast-path single-field read. No full-tree materialise. Returns nullopt
  77. // if the field is absent or the root is not an object.
  78. [[nodiscard]] std::optional<nlohmann::json> field(std::string_view name) const {
  79. return smartbotic::db::doc_binary::get_field(data_binary, name);
  80. }
  81. // Check if document has expired
  82. [[nodiscard]] bool isExpired() const {
  83. if (expiresAt == 0) return false;
  84. auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
  85. std::chrono::system_clock::now().time_since_epoch()
  86. ).count();
  87. return static_cast<uint64_t>(now) >= expiresAt;
  88. }
  89. // Set TTL in seconds from now
  90. void setTtlSeconds(uint32_t seconds) {
  91. if (seconds == 0) {
  92. expiresAt = 0;
  93. } else {
  94. auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
  95. std::chrono::system_clock::now().time_since_epoch()
  96. ).count();
  97. expiresAt = static_cast<uint64_t>(now) + (seconds * 1000ULL);
  98. }
  99. }
  100. // Get remaining TTL in seconds (0 if expired or no TTL)
  101. [[nodiscard]] uint32_t getRemainingTtlSeconds() const {
  102. if (expiresAt == 0) return 0;
  103. auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
  104. std::chrono::system_clock::now().time_since_epoch()
  105. ).count();
  106. if (static_cast<uint64_t>(now) >= expiresAt) return 0;
  107. return static_cast<uint32_t>((expiresAt - static_cast<uint64_t>(now)) / 1000);
  108. }
  109. // JSON serialization — unchanged on disk; decodes the binary back to
  110. // nlohmann::json for the "data" field. WAL/snapshot serializers call this.
  111. [[nodiscard]] nlohmann::json toJson() const {
  112. nlohmann::json j;
  113. j["id"] = id;
  114. j["collection"] = collection;
  115. j["data"] = smartbotic::db::doc_binary::decode(data_binary);
  116. j["version"] = version;
  117. j["createdAt"] = createdAt;
  118. j["updatedAt"] = updatedAt;
  119. j["expiresAt"] = expiresAt;
  120. j["nodeId"] = nodeId;
  121. j["encrypted"] = encrypted;
  122. j["encryptedFields"] = encryptedFields;
  123. j["createdBy"] = createdBy;
  124. j["updatedBy"] = updatedBy;
  125. j["lastAccessedAt"] = lastAccessedAt;
  126. if (hasVector) j["hasVector"] = *hasVector; // v2.13.0
  127. return j;
  128. }
  129. // JSON deserialization — unchanged on disk; encodes the "data" field
  130. // into the binary representation. WAL replay / snapshot load call this.
  131. static Document fromJson(const nlohmann::json& j) {
  132. Document doc;
  133. doc.id = j.value("id", "");
  134. doc.collection = j.value("collection", "");
  135. doc.set_data(j.value("data", nlohmann::json::object()));
  136. doc.version = j.value("version", 1ULL);
  137. doc.createdAt = j.value("createdAt", 0ULL);
  138. doc.updatedAt = j.value("updatedAt", 0ULL);
  139. doc.expiresAt = j.value("expiresAt", 0ULL);
  140. doc.nodeId = j.value("nodeId", "");
  141. doc.encrypted = j.value("encrypted", false);
  142. doc.encryptedFields = j.value("encryptedFields", std::vector<std::string>{});
  143. doc.createdBy = j.value("createdBy", "");
  144. doc.updatedBy = j.value("updatedBy", "");
  145. // Backward-compatible: default to updatedAt (or createdAt) for existing documents
  146. if (j.contains("lastAccessedAt")) {
  147. doc.lastAccessedAt = j.value("lastAccessedAt", 0ULL);
  148. } else {
  149. doc.lastAccessedAt = doc.updatedAt > 0 ? doc.updatedAt : doc.createdAt;
  150. }
  151. if (auto h = j.find("hasVector"); h != j.end() && h->is_boolean()) {
  152. doc.hasVector = h->get<bool>(); // v2.13.0
  153. }
  154. return doc;
  155. }
  156. };
  157. /**
  158. * Represents a historical snapshot of a document at a specific version.
  159. * Stored in version history when a document is updated or deleted.
  160. */
  161. struct DocumentVersion {
  162. uint64_t version = 0; // Version number
  163. // v1.11+ — Binary in-memory storage. See Document::data_binary for the
  164. // canonical-state/lazy-view contract; same lifecycle applies here.
  165. smartbotic::db::doc_binary::Doc data_binary;
  166. mutable std::optional<nlohmann::json> data_view;
  167. uint64_t timestamp = 0; // updatedAt when this version was saved
  168. std::string updatedBy; // Who made this change
  169. bool encrypted = false; // Whether fields were encrypted
  170. std::vector<std::string> encryptedFields; // Encrypted field paths at time of save
  171. uint64_t createdAt = 0; // Original document createdAt (for restore after delete)
  172. std::string createdBy; // Original document createdBy (for restore after delete)
  173. // Lazy full-tree accessor. Materialises on first call, returns cached
  174. // reference thereafter. Cost: one decode() pass plus the cache memory.
  175. // Prefer field() for single-field reads.
  176. [[nodiscard]] const nlohmann::json& data() const {
  177. if (!data_view) {
  178. data_view = smartbotic::db::doc_binary::decode(data_binary);
  179. }
  180. return *data_view;
  181. }
  182. // Replace the binary payload from an nlohmann::json tree. Invalidates the
  183. // cached view so subsequent data() materialises fresh from data_binary.
  184. void set_data(const nlohmann::json& j) {
  185. data_binary = smartbotic::db::doc_binary::encode(j);
  186. data_view.reset();
  187. }
  188. // Fast-path single-field read. No full-tree materialise. Returns nullopt
  189. // if the field is absent or the root is not an object.
  190. [[nodiscard]] std::optional<nlohmann::json> field(std::string_view name) const {
  191. return smartbotic::db::doc_binary::get_field(data_binary, name);
  192. }
  193. [[nodiscard]] nlohmann::json toJson() const {
  194. nlohmann::json j;
  195. j["version"] = version;
  196. j["data"] = smartbotic::db::doc_binary::decode(data_binary);
  197. j["timestamp"] = timestamp;
  198. j["updatedBy"] = updatedBy;
  199. j["encrypted"] = encrypted;
  200. j["encryptedFields"] = encryptedFields;
  201. j["createdAt"] = createdAt;
  202. j["createdBy"] = createdBy;
  203. return j;
  204. }
  205. static DocumentVersion fromJson(const nlohmann::json& j) {
  206. DocumentVersion v;
  207. v.version = j.value("version", 0ULL);
  208. v.set_data(j.value("data", nlohmann::json::object()));
  209. v.timestamp = j.value("timestamp", 0ULL);
  210. v.updatedBy = j.value("updatedBy", "");
  211. v.encrypted = j.value("encrypted", false);
  212. v.encryptedFields = j.value("encryptedFields", std::vector<std::string>{});
  213. v.createdAt = j.value("createdAt", 0ULL);
  214. v.createdBy = j.value("createdBy", "");
  215. return v;
  216. }
  217. };
  218. /**
  219. * Per-collection eviction priority. Added in v1.7.0 to let operators
  220. * bias the eviction selector: Low collections are evicted first, High
  221. * collections last. Normal is the default and preserves v1.6.x behavior.
  222. */
  223. enum class MemoryPriority {
  224. Low = 0,
  225. Normal = 1, // default — preserves existing behavior
  226. High = 2
  227. };
  228. inline std::string memoryPriorityToString(MemoryPriority p) {
  229. switch (p) {
  230. case MemoryPriority::Low: return "low";
  231. case MemoryPriority::Normal: return "normal";
  232. case MemoryPriority::High: return "high";
  233. }
  234. return "normal";
  235. }
  236. inline MemoryPriority memoryPriorityFromString(const std::string& s) {
  237. if (s == "low") return MemoryPriority::Low;
  238. if (s == "high") return MemoryPriority::High;
  239. return MemoryPriority::Normal; // default for unknown/"normal"
  240. }
  241. /**
  242. * Options for creating a collection.
  243. * Named CollectionOptions to avoid conflict with proto-generated type.
  244. */
  245. struct CollectionOptions {
  246. bool autoCreateId = true; // Auto-generate IDs if not provided
  247. uint32_t defaultTtlSeconds = 0; // Default TTL for documents (0 = none)
  248. bool encrypted = false; // Encrypt all documents by default
  249. std::vector<std::string> sensitiveFields; // Fields to always encrypt
  250. uint32_t maxVersions = 0; // Max version history per document (0 = unlimited)
  251. bool pinned = false; // If true, never evict documents from this collection
  252. uint32_t vectorDimension = 0; // Vector dimension for vector search (0 = disabled)
  253. MemoryPriority memoryPriority = MemoryPriority::Normal; // v1.7.0 eviction bias
  254. [[nodiscard]] nlohmann::json toJson() const {
  255. nlohmann::json j;
  256. j["autoCreateId"] = autoCreateId;
  257. j["defaultTtlSeconds"] = defaultTtlSeconds;
  258. j["encrypted"] = encrypted;
  259. j["sensitiveFields"] = sensitiveFields;
  260. j["maxVersions"] = maxVersions;
  261. j["pinned"] = pinned;
  262. j["vector_dimension"] = vectorDimension;
  263. j["memory_priority"] = memoryPriorityToString(memoryPriority);
  264. return j;
  265. }
  266. static CollectionOptions fromJson(const nlohmann::json& j) {
  267. CollectionOptions opts;
  268. opts.autoCreateId = j.value("autoCreateId", true);
  269. opts.defaultTtlSeconds = j.value("defaultTtlSeconds", 0U);
  270. opts.encrypted = j.value("encrypted", false);
  271. opts.sensitiveFields = j.value("sensitiveFields", std::vector<std::string>{});
  272. opts.maxVersions = j.value("maxVersions", 0U);
  273. opts.pinned = j.value("pinned", false); // Backward-compatible default
  274. if (j.contains("vector_dimension") && j["vector_dimension"].is_number())
  275. opts.vectorDimension = j["vector_dimension"].get<uint32_t>();
  276. if (j.contains("memory_priority") && j["memory_priority"].is_string())
  277. opts.memoryPriority = memoryPriorityFromString(j["memory_priority"].get<std::string>());
  278. return opts;
  279. }
  280. };
  281. /**
  282. * Collection metadata.
  283. */
  284. struct CollectionInfo {
  285. std::string name;
  286. uint64_t documentCount = 0;
  287. uint64_t sizeBytes = 0;
  288. CollectionOptions options;
  289. uint64_t createdAt = 0;
  290. uint64_t updatedAt = 0;
  291. [[nodiscard]] nlohmann::json toJson() const {
  292. nlohmann::json j;
  293. j["name"] = name;
  294. j["documentCount"] = documentCount;
  295. j["sizeBytes"] = sizeBytes;
  296. j["options"] = options.toJson();
  297. j["createdAt"] = createdAt;
  298. j["updatedAt"] = updatedAt;
  299. return j;
  300. }
  301. };
  302. /**
  303. * Filter operator for queries.
  304. */
  305. enum class FilterOp {
  306. EQ, // Equal
  307. NE, // Not equal
  308. GT, // Greater than
  309. GTE, // Greater than or equal
  310. LT, // Less than
  311. LTE, // Less than or equal
  312. IN, // Value in array
  313. CONTAINS, // Array contains value
  314. EXISTS, // Field exists
  315. REGEX, // Regex match
  316. SEARCH // Full-text search across ID and string fields
  317. };
  318. /**
  319. * Query filter.
  320. */
  321. struct Filter {
  322. std::string field; // JSON path (e.g., "status" or "user.email")
  323. FilterOp op = FilterOp::EQ;
  324. nlohmann::json value;
  325. [[nodiscard]] nlohmann::json toJson() const {
  326. nlohmann::json j;
  327. j["field"] = field;
  328. j["op"] = static_cast<int>(op);
  329. j["value"] = value;
  330. return j;
  331. }
  332. static Filter fromJson(const nlohmann::json& j) {
  333. Filter f;
  334. f.field = j.value("field", "");
  335. f.op = static_cast<FilterOp>(j.value("op", 0));
  336. f.value = j.value("value", nlohmann::json());
  337. return f;
  338. }
  339. };
  340. /**
  341. * Sort specification.
  342. */
  343. struct Sort {
  344. std::string field;
  345. bool descending = false;
  346. [[nodiscard]] nlohmann::json toJson() const {
  347. nlohmann::json j;
  348. j["field"] = field;
  349. j["descending"] = descending;
  350. return j;
  351. }
  352. static Sort fromJson(const nlohmann::json& j) {
  353. Sort s;
  354. s.field = j.value("field", "");
  355. s.descending = j.value("descending", false);
  356. return s;
  357. }
  358. };
  359. /**
  360. * Query specification.
  361. */
  362. struct Query {
  363. std::vector<Filter> filters;
  364. std::optional<Sort> sort;
  365. uint32_t limit = 100;
  366. uint32_t offset = 0;
  367. std::vector<std::string> projection; // Fields to include (empty = all)
  368. [[nodiscard]] nlohmann::json toJson() const {
  369. nlohmann::json j;
  370. j["filters"] = nlohmann::json::array();
  371. for (const auto& f : filters) {
  372. j["filters"].push_back(f.toJson());
  373. }
  374. if (sort) {
  375. j["sort"] = sort->toJson();
  376. }
  377. j["limit"] = limit;
  378. j["offset"] = offset;
  379. j["projection"] = projection;
  380. return j;
  381. }
  382. static Query fromJson(const nlohmann::json& j) {
  383. Query q;
  384. if (j.contains("filters") && j["filters"].is_array()) {
  385. for (const auto& f : j["filters"]) {
  386. q.filters.push_back(Filter::fromJson(f));
  387. }
  388. }
  389. if (j.contains("sort") && !j["sort"].is_null()) {
  390. q.sort = Sort::fromJson(j["sort"]);
  391. }
  392. q.limit = j.value("limit", 100U);
  393. q.offset = j.value("offset", 0U);
  394. q.projection = j.value("projection", std::vector<std::string>{});
  395. return q;
  396. }
  397. };
  398. /**
  399. * Result of a find query.
  400. */
  401. struct QueryResult {
  402. std::vector<Document> documents;
  403. uint64_t totalCount = 0;
  404. bool hasMore = false;
  405. // WAL fallback metrics (for queries that include evicted documents)
  406. bool usedWalFallback = false; // True if WAL was scanned for evicted docs
  407. uint32_t memoryMatchCount = 0; // Documents matched from memory
  408. uint32_t walMatchCount = 0; // Documents matched from WAL
  409. uint64_t memorySearchMicros = 0; // Time spent searching memory
  410. uint64_t walSearchMicros = 0; // Time spent loading/searching WAL
  411. };
  412. /**
  413. * Storage event types.
  414. *
  415. * Integer ordering matters: database_grpc_impl.cpp converts to pb::EventType
  416. * with a `+1` offset (pb::EVENT_UNKNOWN == 0 is the wire-level default).
  417. * When adding entries, also add them to proto EventType in matching order.
  418. */
  419. enum class EventType {
  420. INSERT, // pb::EVENT_INSERT
  421. UPDATE, // pb::EVENT_UPDATE
  422. DELETE, // pb::EVENT_DELETE
  423. EXPIRE, // pb::EVENT_EXPIRE
  424. INVALIDATE, // pb::EVENT_INVALIDATE
  425. // v1.7.0 — memory-pressure observability events (T10).
  426. // System-level: collection="" and documentId="". Payload in `data` carries
  427. // pressure level, percent, and (for bursts) doc count and bytes freed.
  428. MEMORY_PRESSURE_HIGH, // pb::EVENT_MEMORY_PRESSURE_HIGH
  429. MEMORY_EVICTION_BURST // pb::EVENT_MEMORY_EVICTION_BURST
  430. };
  431. /**
  432. * Storage event for pub/sub.
  433. */
  434. struct DatabaseEvent {
  435. EventType type;
  436. std::string collection;
  437. std::string documentId;
  438. uint64_t timestamp = 0;
  439. std::string nodeId;
  440. std::optional<nlohmann::json> data; // Document data (if included)
  441. std::string actor; // v2.12.0 - who caused it; see DatabaseEvent.actor in the proto
  442. [[nodiscard]] nlohmann::json toJson() const {
  443. nlohmann::json j;
  444. j["type"] = static_cast<int>(type);
  445. j["collection"] = collection;
  446. j["documentId"] = documentId;
  447. j["timestamp"] = timestamp;
  448. j["nodeId"] = nodeId;
  449. if (!actor.empty()) {
  450. j["actor"] = actor;
  451. }
  452. if (data) {
  453. j["data"] = *data;
  454. }
  455. return j;
  456. }
  457. };
  458. } // namespace smartbotic::database