wal.hpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #pragma once
  2. #include "../document.hpp"
  3. #include <atomic>
  4. #include <cstdint>
  5. #include <filesystem>
  6. #include <fstream>
  7. #include <functional>
  8. #include <mutex>
  9. #include <optional>
  10. #include <string>
  11. #include <vector>
  12. namespace smartbotic::database {
  13. /**
  14. * Operation type for WAL entries.
  15. */
  16. enum class WalOpType : uint8_t {
  17. INSERT = 1,
  18. UPDATE = 2,
  19. DELETE = 3,
  20. UPSERT = 4,
  21. CREATE_COLLECTION = 5,
  22. DROP_COLLECTION = 6,
  23. SET_ADD = 7,
  24. SET_REMOVE = 8,
  25. VEC_PUT = 9,
  26. VEC_DELETE = 10
  27. };
  28. /**
  29. * WAL entry structure.
  30. * Binary format for efficient serialization.
  31. *
  32. * v1.8.0 added `nodeId` (origin node) at the end of the entry to fix
  33. * replicated-doc eviction loss on followers. Format is forward-compatible:
  34. * older readers stop before the optional trailer, and newer readers see
  35. * an empty `nodeId` for legacy entries (which the persistence layer
  36. * treats as "origin unknown — assume local").
  37. */
  38. struct WalEntry {
  39. uint64_t sequence = 0; // Monotonic sequence number
  40. uint64_t timestamp = 0; // Wall clock time (ms)
  41. WalOpType opType = WalOpType::INSERT;
  42. std::string collection;
  43. std::string documentId;
  44. std::optional<nlohmann::json> data; // For INSERT/UPDATE/UPSERT
  45. std::optional<CollectionOptions> collectionOptions; // For CREATE_COLLECTION
  46. std::optional<std::vector<float>> vectorData; // For VEC_PUT
  47. std::string nodeId; // v1.8.0 — origin node for this write (empty in pre-v1.8 entries)
  48. uint32_t checksum = 0; // CRC32 for integrity
  49. // Serialize entry to binary
  50. [[nodiscard]] std::vector<uint8_t> serialize() const;
  51. // Deserialize entry from binary
  52. static std::optional<WalEntry> deserialize(const std::vector<uint8_t>& data);
  53. // Calculate CRC32 checksum
  54. [[nodiscard]] uint32_t calculateChecksum() const;
  55. };
  56. /**
  57. * Write-Ahead Log for durability.
  58. *
  59. * All mutations are written to the WAL before being applied to memory.
  60. * The WAL ensures durability by persisting operations to disk.
  61. *
  62. * File format:
  63. * - Header (16 bytes): magic, version, sequence
  64. * - Entries: [length(4) | entry_data | crc32(4)] ...
  65. */
  66. class WriteAheadLog {
  67. public:
  68. struct Config {
  69. std::filesystem::path walDir;
  70. uint32_t syncIntervalMs = 100; // fsync interval
  71. uint64_t maxFileSizeBytes = 100ULL * 1024 * 1024; // 100MB max per file
  72. bool syncOnWrite = false; // fsync after each write (slow but safe)
  73. };
  74. explicit WriteAheadLog(Config config);
  75. ~WriteAheadLog();
  76. // Non-copyable, non-movable
  77. WriteAheadLog(const WriteAheadLog&) = delete;
  78. WriteAheadLog& operator=(const WriteAheadLog&) = delete;
  79. WriteAheadLog(WriteAheadLog&&) = delete;
  80. WriteAheadLog& operator=(WriteAheadLog&&) = delete;
  81. /**
  82. * Open the WAL for writing.
  83. * Creates the WAL directory if it doesn't exist.
  84. */
  85. bool open();
  86. /**
  87. * Close the WAL, ensuring all data is flushed.
  88. */
  89. void close();
  90. /**
  91. * Append an entry to the WAL.
  92. * @return The sequence number assigned to the entry
  93. */
  94. uint64_t append(WalEntry entry);
  95. /**
  96. * Force sync to disk.
  97. */
  98. void sync();
  99. /**
  100. * Replay WAL entries from a sequence number.
  101. * @param fromSequence Start replaying from this sequence (exclusive)
  102. * @param callback Called for each entry
  103. * @return Number of entries replayed
  104. */
  105. uint64_t replay(uint64_t fromSequence, std::function<void(const WalEntry&)> callback);
  106. /**
  107. * Get the current sequence number.
  108. */
  109. [[nodiscard]] uint64_t currentSequence() const { return sequence_.load(); }
  110. /**
  111. * Raise the sequence floor to at least `seq`. Monotonic — calls
  112. * with a value ≤ current sequence are no-ops.
  113. *
  114. * Called by the recovery path with the snapshot's `walSequence`
  115. * after a snapshot loads. Without this, the WAL's `sequence_`
  116. * would stay at 0 whenever the previous run's snapshot truncated
  117. * all WAL files (which is the steady-state outcome of
  118. * `truncateBefore(walSeq)` after every snapshot — it deletes every
  119. * file because all entries have sequence ≤ walSeq). The next boot
  120. * with no WAL files leaves the in-memory counter at 0; subsequent
  121. * appends produce sequence 1, 2, 3, … which look "older than the
  122. * snapshot" to recovery and get silently discarded on the boot
  123. * after that. This setter closes the gap.
  124. */
  125. void setSequenceFloor(uint64_t seq);
  126. /**
  127. * Get the total size of all WAL files.
  128. */
  129. [[nodiscard]] uint64_t totalSizeBytes() const;
  130. /**
  131. * Truncate WAL files before a sequence number.
  132. * Used after snapshot to remove old entries.
  133. */
  134. void truncateBefore(uint64_t sequence);
  135. /**
  136. * v2.17.0 - close the current file as an archive and start a new one, so
  137. * everything written so far can be removed once a snapshot covers it.
  138. */
  139. void rotateNow();
  140. /**
  141. * v2.17.0 - delete every archived WAL file (all but the current one).
  142. * Only valid right after a snapshot that covers the whole log, taken after
  143. * rotateNow(): the at-rest encryption seal, which must not leave old
  144. * plaintext entries on disk. Returns the number of files removed.
  145. */
  146. size_t removeArchivedFiles();
  147. /**
  148. * Check if WAL is open.
  149. */
  150. [[nodiscard]] bool isOpen() const { return isOpen_.load(); }
  151. // Helper methods for creating entries.
  152. // `originNodeId` (v1.8.0) tags the entry with the originating node so
  153. // replicated entries replayed from a peer's WAL keep their leader as
  154. // origin instead of being re-attributed to whichever node serves the
  155. // sync request. Empty = defer to caller's local node id.
  156. static WalEntry makeInsertEntry(const std::string& collection, const Document& doc,
  157. const std::string& originNodeId = "");
  158. static WalEntry makeUpdateEntry(const std::string& collection, const Document& doc,
  159. const std::string& originNodeId = "");
  160. static WalEntry makeDeleteEntry(const std::string& collection, const std::string& id,
  161. const std::string& originNodeId = "");
  162. static WalEntry makeUpsertEntry(const std::string& collection, const Document& doc,
  163. const std::string& originNodeId = "");
  164. static WalEntry makeCreateCollectionEntry(const std::string& collection, const CollectionOptions& options,
  165. const std::string& originNodeId = "");
  166. static WalEntry makeDropCollectionEntry(const std::string& collection,
  167. const std::string& originNodeId = "");
  168. static WalEntry makeVecPutEntry(const std::string& collection,
  169. const std::string& docId, const std::vector<float>& vec,
  170. const std::string& originNodeId = "");
  171. static WalEntry makeVecDeleteEntry(const std::string& collection,
  172. const std::string& docId,
  173. const std::string& originNodeId = "");
  174. private:
  175. // WAL file header
  176. struct Header {
  177. char magic[8] = {'C', 'A', 'L', 'W', 'A', 'L', '0', '1'};
  178. uint64_t startSequence = 0;
  179. };
  180. // Get current WAL file path
  181. [[nodiscard]] std::filesystem::path currentFilePath() const;
  182. // Get all WAL file paths sorted by sequence
  183. [[nodiscard]] std::vector<std::filesystem::path> getWalFiles() const;
  184. // Rotate to a new WAL file
  185. void rotate();
  186. // Read header from file
  187. static std::optional<Header> readHeader(std::ifstream& file);
  188. // Write header to file
  189. void writeHeader();
  190. // Read entries from a file
  191. uint64_t replayFile(const std::filesystem::path& path, uint64_t fromSequence,
  192. const std::function<void(const WalEntry&)>& callback);
  193. Config config_;
  194. std::atomic<bool> isOpen_{false};
  195. std::atomic<uint64_t> sequence_{0};
  196. std::ofstream currentFile_;
  197. uint64_t currentFileSize_ = 0;
  198. uint64_t currentFileStartSequence_ = 0;
  199. mutable std::mutex writeMutex_;
  200. };
  201. /**
  202. * CRC32 utility functions.
  203. */
  204. namespace crc32 {
  205. uint32_t calculate(const void* data, size_t length);
  206. uint32_t calculate(const std::string& str);
  207. // Continue a CRC over more bytes: extend(calculate(a), b) == calculate(a + b),
  208. // and extend(0, x) == calculate(x). Lets a writer checksum a body it never
  209. // holds whole (the 2.21.0 streaming snapshot writer).
  210. uint32_t extend(uint32_t crc, const void* data, size_t length);
  211. }
  212. } // namespace smartbotic::database