Repository navigation
Expand file tree
/
Copy pathWalWriter.cpp
More file actions
86 lines (69 loc) · 2.44 KB
/
Copy pathWalWriter.cpp
File metadata and controls
86 lines (69 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
*
* @file WalWriter.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*
*/
#include <vix/sync/wal/WalWriter.hpp>
#include <stdexcept>
namespace vix::sync::wal
{
static constexpr std::uint32_t kMagic = 0x56495857; // 'VIXW'
static constexpr std::uint16_t kVersion = 1;
WalWriter::WalWriter(Config cfg) : cfg_(std::move(cfg)) { open_(); }
WalWriter::~WalWriter() { flush(); }
void WalWriter::open_()
{
std::filesystem::create_directories(cfg_.file_path.parent_path());
out_.open(cfg_.file_path, std::ios::binary | std::ios::app);
if (!out_)
throw std::runtime_error("WalWriter: cannot open file");
}
std::int64_t WalWriter::tell_()
{
return static_cast<std::int64_t>(out_.tellp());
}
std::int64_t WalWriter::append(const WalRecord &r)
{
if (!out_)
open_();
const auto offset = tell_();
const std::uint32_t id_len = static_cast<std::uint32_t>(r.id.size());
const std::uint32_t payload_len = static_cast<std::uint32_t>(r.payload.size());
const std::uint32_t error_len = static_cast<std::uint32_t>(r.error.size());
// header
out_.write(reinterpret_cast<const char *>(&kMagic), sizeof(kMagic));
out_.write(reinterpret_cast<const char *>(&kVersion), sizeof(kVersion));
const std::uint8_t type = static_cast<std::uint8_t>(r.type);
out_.write(reinterpret_cast<const char *>(&type), sizeof(type));
const std::uint8_t reserved = 0;
out_.write(reinterpret_cast<const char *>(&reserved), sizeof(reserved));
out_.write(reinterpret_cast<const char *>(&r.ts_ms), sizeof(r.ts_ms));
out_.write(reinterpret_cast<const char *>(&id_len), sizeof(id_len));
out_.write(reinterpret_cast<const char *>(&payload_len), sizeof(payload_len));
out_.write(reinterpret_cast<const char *>(&error_len), sizeof(error_len));
out_.write(reinterpret_cast<const char *>(&r.next_retry_at_ms), sizeof(r.next_retry_at_ms));
// body
if (id_len)
out_.write(r.id.data(), id_len);
if (payload_len)
out_.write(reinterpret_cast<const char *>(r.payload.data()), payload_len);
if (error_len)
out_.write(r.error.data(), error_len);
flush();
return offset;
}
void WalWriter::flush()
{
if (!out_)
return;
out_.flush();
}
} // namespace vix::sync::wal