| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248 |
- #pragma once
- #include "../document.hpp"
- #include <atomic>
- #include <cstdint>
- #include <filesystem>
- #include <fstream>
- #include <functional>
- #include <mutex>
- #include <optional>
- #include <string>
- #include <vector>
- 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<nlohmann::json> data; // For INSERT/UPDATE/UPSERT
- std::optional<CollectionOptions> collectionOptions; // For CREATE_COLLECTION
- std::optional<std::vector<float>> 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<uint8_t> serialize() const;
- // Deserialize entry from binary
- static std::optional<WalEntry> deserialize(const std::vector<uint8_t>& 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<void(const WalEntry&)> 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<float>& 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<std::filesystem::path> getWalFiles() const;
- // Rotate to a new WAL file
- void rotate();
- // Read header from file
- static std::optional<Header> 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<void(const WalEntry&)>& callback);
- Config config_;
- std::atomic<bool> isOpen_{false};
- std::atomic<uint64_t> 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
|