#pragma once #include "../document.hpp" #include #include #include #include #include #include #include #include #include namespace smartbotic::database { /** * Operation type for WAL entries. */ enum class WalOpType : uint8_t { INSERT = 1, UPDATE = 2, DELETE = 3, UPSERT = 4, CREATE_COLLECTION = 5, DROP_COLLECTION = 6, SET_ADD = 7, SET_REMOVE = 8, VEC_PUT = 9, VEC_DELETE = 10 }; /** * WAL entry structure. * Binary format for efficient serialization. * * v1.8.0 added `nodeId` (origin node) at the end of the entry to fix * replicated-doc eviction loss on followers. Format is forward-compatible: * older readers stop before the optional trailer, and newer readers see * an empty `nodeId` for legacy entries (which the persistence layer * treats as "origin unknown — assume local"). */ struct WalEntry { uint64_t sequence = 0; // Monotonic sequence number uint64_t timestamp = 0; // Wall clock time (ms) WalOpType opType = WalOpType::INSERT; std::string collection; std::string documentId; std::optional data; // For INSERT/UPDATE/UPSERT std::optional collectionOptions; // For CREATE_COLLECTION std::optional> vectorData; // For VEC_PUT std::string nodeId; // v1.8.0 — origin node for this write (empty in pre-v1.8 entries) uint32_t checksum = 0; // CRC32 for integrity // Serialize entry to binary [[nodiscard]] std::vector serialize() const; // Deserialize entry from binary static std::optional deserialize(const std::vector& data); // Calculate CRC32 checksum [[nodiscard]] uint32_t calculateChecksum() const; }; /** * Write-Ahead Log for durability. * * All mutations are written to the WAL before being applied to memory. * The WAL ensures durability by persisting operations to disk. * * File format: * - Header (16 bytes): magic, version, sequence * - Entries: [length(4) | entry_data | crc32(4)] ... */ class WriteAheadLog { public: struct Config { std::filesystem::path walDir; uint32_t syncIntervalMs = 100; // fsync interval uint64_t maxFileSizeBytes = 100ULL * 1024 * 1024; // 100MB max per file bool syncOnWrite = false; // fsync after each write (slow but safe) }; explicit WriteAheadLog(Config config); ~WriteAheadLog(); // Non-copyable, non-movable WriteAheadLog(const WriteAheadLog&) = delete; WriteAheadLog& operator=(const WriteAheadLog&) = delete; WriteAheadLog(WriteAheadLog&&) = delete; WriteAheadLog& operator=(WriteAheadLog&&) = delete; /** * Open the WAL for writing. * Creates the WAL directory if it doesn't exist. */ bool open(); /** * Close the WAL, ensuring all data is flushed. */ void close(); /** * Append an entry to the WAL. * @return The sequence number assigned to the entry */ uint64_t append(WalEntry entry); /** * Force sync to disk. */ void sync(); /** * Replay WAL entries from a sequence number. * @param fromSequence Start replaying from this sequence (exclusive) * @param callback Called for each entry * @return Number of entries replayed */ uint64_t replay(uint64_t fromSequence, std::function callback); /** * Get the current sequence number. */ [[nodiscard]] uint64_t currentSequence() const { return sequence_.load(); } /** * Raise the sequence floor to at least `seq`. Monotonic — calls * with a value ≤ current sequence are no-ops. * * Called by the recovery path with the snapshot's `walSequence` * after a snapshot loads. Without this, the WAL's `sequence_` * would stay at 0 whenever the previous run's snapshot truncated * all WAL files (which is the steady-state outcome of * `truncateBefore(walSeq)` after every snapshot — it deletes every * file because all entries have sequence ≤ walSeq). The next boot * with no WAL files leaves the in-memory counter at 0; subsequent * appends produce sequence 1, 2, 3, … which look "older than the * snapshot" to recovery and get silently discarded on the boot * after that. This setter closes the gap. */ void setSequenceFloor(uint64_t seq); /** * Get the total size of all WAL files. */ [[nodiscard]] uint64_t totalSizeBytes() const; /** * Truncate WAL files before a sequence number. * Used after snapshot to remove old entries. */ void truncateBefore(uint64_t sequence); /** * v2.17.0 - close the current file as an archive and start a new one, so * everything written so far can be removed once a snapshot covers it. */ void rotateNow(); /** * v2.17.0 - delete every archived WAL file (all but the current one). * Only valid right after a snapshot that covers the whole log, taken after * rotateNow(): the at-rest encryption seal, which must not leave old * plaintext entries on disk. Returns the number of files removed. */ size_t removeArchivedFiles(); /** * Check if WAL is open. */ [[nodiscard]] bool isOpen() const { return isOpen_.load(); } // Helper methods for creating entries. // `originNodeId` (v1.8.0) tags the entry with the originating node so // replicated entries replayed from a peer's WAL keep their leader as // origin instead of being re-attributed to whichever node serves the // sync request. Empty = defer to caller's local node id. static WalEntry makeInsertEntry(const std::string& collection, const Document& doc, const std::string& originNodeId = ""); static WalEntry makeUpdateEntry(const std::string& collection, const Document& doc, const std::string& originNodeId = ""); static WalEntry makeDeleteEntry(const std::string& collection, const std::string& id, const std::string& originNodeId = ""); static WalEntry makeUpsertEntry(const std::string& collection, const Document& doc, const std::string& originNodeId = ""); static WalEntry makeCreateCollectionEntry(const std::string& collection, const CollectionOptions& options, const std::string& originNodeId = ""); static WalEntry makeDropCollectionEntry(const std::string& collection, const std::string& originNodeId = ""); static WalEntry makeVecPutEntry(const std::string& collection, const std::string& docId, const std::vector& vec, const std::string& originNodeId = ""); static WalEntry makeVecDeleteEntry(const std::string& collection, const std::string& docId, const std::string& originNodeId = ""); private: // WAL file header struct Header { char magic[8] = {'C', 'A', 'L', 'W', 'A', 'L', '0', '1'}; uint64_t startSequence = 0; }; // Get current WAL file path [[nodiscard]] std::filesystem::path currentFilePath() const; // Get all WAL file paths sorted by sequence [[nodiscard]] std::vector getWalFiles() const; // Rotate to a new WAL file void rotate(); // Read header from file static std::optional
readHeader(std::ifstream& file); // Write header to file void writeHeader(); // Read entries from a file uint64_t replayFile(const std::filesystem::path& path, uint64_t fromSequence, const std::function& callback); Config config_; std::atomic isOpen_{false}; std::atomic sequence_{0}; std::ofstream currentFile_; uint64_t currentFileSize_ = 0; uint64_t currentFileStartSequence_ = 0; mutable std::mutex writeMutex_; }; /** * CRC32 utility functions. */ namespace crc32 { uint32_t calculate(const void* data, size_t length); uint32_t calculate(const std::string& str); // Continue a CRC over more bytes: extend(calculate(a), b) == calculate(a + b), // and extend(0, x) == calculate(x). Lets a writer checksum a body it never // holds whole (the 2.21.0 streaming snapshot writer). uint32_t extend(uint32_t crc, const void* data, size_t length); } } // namespace smartbotic::database