Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
slot_store.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <array>
5#include <atomic>
6#include <cstddef>
7#include <cstdint>
8#include <cstring>
9#include <string>
10#include <string_view>
11#include <type_traits>
12#include <vector>
13
14namespace slick::trader {
15
16// What a broker's state file is: its magic, layout version, and the name its log lines
17// and errors go by.
19 char magic[8];
20 uint32_t version;
21 const char* name;
22};
23
24namespace detail {
25
26// The untyped half of SlotStore: opens, checks and lays out the file.
27//
28// The header is 128 bytes: magic@0, version@8, slot size@12, identity@16 (16 bytes),
29// then the broker's session state@32 (96 bytes). The slots follow it.
30class SlotFile {
31public:
32 static constexpr size_t HEADER_SIZE = 128;
33 static constexpr size_t IDENTITY_SIZE = 16;
34 static constexpr size_t STATE_OFFSET = 32;
35 static constexpr size_t STATE_SIZE = HEADER_SIZE - STATE_OFFSET;
36
37 // `fresh_state` is copied into a file that is new. Throws std::runtime_error for a
38 // file of another format, layout or identity.
39 SlotFile(const std::string& path, const SlotStoreFormat& format, const std::array<char, IDENTITY_SIZE>& identity,
40 std::string_view identity_text, size_t slot_size, size_t max_slots, const void* fresh_state,
41 size_t state_size);
42
43 [[nodiscard]] uint8_t* state() noexcept { return file_.data() + STATE_OFFSET; }
44 [[nodiscard]] uint8_t* slot(uint32_t index) noexcept {
45 return file_.data() + HEADER_SIZE + static_cast<size_t>(index) * slot_size_;
46 }
47 [[nodiscard]] const uint8_t* slot(uint32_t index) const noexcept {
48 return file_.data() + HEADER_SIZE + static_cast<size_t>(index) * slot_size_;
49 }
50 [[nodiscard]] uint32_t capacity() const noexcept { return capacity_; }
51 [[nodiscard]] bool created() const noexcept { return created_; }
52 [[nodiscard]] const std::string& path() const noexcept { return path_; }
53 [[nodiscard]] const char* name() const noexcept { return name_; }
54
55private:
56 std::string path_;
57 const char* name_;
58 MappedFile file_;
59 size_t slot_size_;
60 uint32_t capacity_ = 0;
61 bool created_ = false;
62};
63
64} // namespace detail
65
66// A session's state kept across restarts: the broker's own `State` (its sequence numbers,
67// say) and a fixed number of `Record` slots (its working orders).
68//
69// The file is memory-mapped: saving a record or a sequence number is a store to memory,
70// never a wait for the disk, and what was stored is in the file even if the process is
71// killed the next instant. A slot holds two copies of its record and a byte saying which
72// is current: an update writes the other copy whole, then flips the byte, so a process
73// that dies mid-update leaves the record as it was.
74//
75// `identity` (16 bytes) names whose state this is: opening another session's file
76// throws, since its sequence numbers and orders would be worse than none.
77//
78// Single-threaded: owned by the order worker.
79template <typename State, typename Record>
80class SlotStore {
81 static_assert(std::is_trivially_copyable_v<State> && std::is_trivially_copyable_v<Record>);
82 static_assert(sizeof(State) <= detail::SlotFile::STATE_SIZE, "State must fit the header's 96 bytes");
83 static_assert(alignof(State) <= 8 && alignof(Record) <= 8);
84
85public:
86 static constexpr uint32_t NO_SLOT = UINT32_MAX;
87 static constexpr size_t DEFAULT_MAX_RECORDS = 4096;
88 using Identity = std::array<char, detail::SlotFile::IDENTITY_SIZE>;
89
90 SlotStore(const std::string& path, const SlotStoreFormat& format, const Identity& identity,
91 std::string_view identity_text, size_t max_records = DEFAULT_MAX_RECORDS)
92 : file_(path, format, identity, identity_text, sizeof(Slot), max_records, &fresh_state_, sizeof(State))
93 {
94 free_.reserve(file_.capacity());
95 for (uint32_t index = file_.capacity(); index-- > 0;) {
96 Slot& s = slot(index);
97 if (s.state != SLOT_RECORD_0 && s.state != SLOT_RECORD_1) {
98 s.state = SLOT_FREE;
99 free_.push_back(index);
100 }
101 }
102 }
103
104 // The session's state, in the file.
105 [[nodiscard]] State& state() noexcept { return *reinterpret_cast<State*>(file_.state()); }
106
107 // Calls `f(slot, const Record&)` for each slot in use.
108 template <typename F>
109 void for_each(F&& f) const {
110 for (uint32_t index = 0; index < file_.capacity(); ++index) {
111 const Slot& s = slot(index);
112 if (s.state == SLOT_RECORD_0 || s.state == SLOT_RECORD_1) {
113 f(index, s.records[s.state - SLOT_RECORD_0]);
114 }
115 }
116 }
117
118 // Records `record` in `slot`, or with NO_SLOT in a free one. Returns the slot, or
119 // NO_SLOT when the store is full: the record is then not kept across a restart.
120 uint32_t save(uint32_t index, const Record& record) {
121 if (index == NO_SLOT) {
122 if (free_.empty()) {
123 report_full();
124 return NO_SLOT;
125 }
126 index = free_.back();
127 free_.pop_back();
128 } else if (index >= file_.capacity()) {
129 return NO_SLOT;
130 }
131 // The copy that is not current is written whole, then made current by one byte:
132 // a process that dies in between leaves the record as it was, or a free slot free.
133 Slot& s = slot(index);
134 const uint8_t next = s.state == SLOT_RECORD_0 ? SLOT_RECORD_1 : SLOT_RECORD_0;
135 std::memcpy(static_cast<void*>(&s.records[next - SLOT_RECORD_0]), &record, sizeof(Record));
136 std::atomic_signal_fence(std::memory_order_seq_cst); // the compiler keeps that order too
137 s.state = next;
138 return index;
139 }
140
141 void release(uint32_t index) noexcept {
142 if (index < file_.capacity() && slot(index).state != SLOT_FREE) {
143 slot(index).state = SLOT_FREE;
144 free_.push_back(index);
145 }
146 }
147
148 [[nodiscard]] size_t capacity() const noexcept { return file_.capacity(); }
149 [[nodiscard]] size_t size() const noexcept { return file_.capacity() - free_.size(); }
150 [[nodiscard]] const std::string& path() const noexcept { return file_.path(); }
151 // True when the file was created by this run: there was nothing to resume.
152 [[nodiscard]] bool created() const noexcept { return file_.created(); }
153
154private:
155 static constexpr uint8_t SLOT_FREE = 0;
156 static constexpr uint8_t SLOT_RECORD_0 = 1;
157 static constexpr uint8_t SLOT_RECORD_1 = 2;
158
159 struct Slot {
160 uint8_t state;
161 uint8_t reserved[7];
162 Record records[2];
163 };
164 static_assert(offsetof(Slot, records) == 8);
165
166 [[nodiscard]] Slot& slot(uint32_t index) noexcept { return *reinterpret_cast<Slot*>(file_.slot(index)); }
167 [[nodiscard]] const Slot& slot(uint32_t index) const noexcept {
168 return *reinterpret_cast<const Slot*>(file_.slot(index));
169 }
170
171 void report_full();
172
173 inline static const State fresh_state_{};
174 detail::SlotFile file_;
175 std::vector<uint32_t> free_;
176 bool full_logged_ = false;
177};
178
179namespace detail {
180void report_slot_store_full(const char* name, const std::string& path, size_t capacity);
181}
182
183template <typename State, typename Record>
184void SlotStore<State, Record>::report_full() {
185 if (!full_logged_) {
186 full_logged_ = true;
187 detail::report_slot_store_full(file_.name(), file_.path(), file_.capacity());
188 }
189}
190
191} // namespace slick::trader
size_t size() const noexcept
bool created() const noexcept
const std::string & path() const noexcept
static constexpr uint32_t NO_SLOT
size_t capacity() const noexcept
void release(uint32_t index) noexcept
std::array< char, detail::SlotFile::IDENTITY_SIZE > Identity
void for_each(F &&f) const
SlotStore(const std::string &path, const SlotStoreFormat &format, const Identity &identity, std::string_view identity_text, size_t max_records=DEFAULT_MAX_RECORDS)
State & state() noexcept
static constexpr size_t DEFAULT_MAX_RECORDS
uint32_t save(uint32_t index, const Record &record)
uint8_t * state() noexcept
const uint8_t * slot(uint32_t index) const noexcept
static constexpr size_t STATE_SIZE
uint32_t capacity() const noexcept
bool created() const noexcept
SlotFile(const std::string &path, const SlotStoreFormat &format, const std::array< char, IDENTITY_SIZE > &identity, std::string_view identity_text, size_t slot_size, size_t max_slots, const void *fresh_state, size_t state_size)
uint8_t * slot(uint32_t index) noexcept
const char * name() const noexcept
static constexpr size_t HEADER_SIZE
static constexpr size_t IDENTITY_SIZE
static constexpr size_t STATE_OFFSET
const std::string & path() const noexcept
void report_slot_store_full(const char *name, const std::string &path, size_t capacity)