FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
param_publisher.hpp
Go to the documentation of this file.
1#pragma once
2// ParamPublisher: builds ParamUpdate messages for a running engine, off the engine thread
3// (ADR-0013).
4//
5// MsgRing ring(1U << 16); // one of the engine's RingFeed rings
6// ParamPublisher pub(ParamSink::to_ring(ring), strategy.params());
7// pub.publish({{"half_spread_bps", "7.5"}}); // false: no room in the ring
8//
9// A publish parses the named values into a copy of the parameters with the schema's parsers and
10// ranges, then runs the params struct's validate(). An unknown name, a name given twice, a value
11// that does not parse or is out of range, a failed validate() and more than
12// ParamUpdateMsg::kMaxFields values throw std::invalid_argument; nothing is sent then. The engine
13// copies the raw values without checks.
14//
15// The copy starts from the parameters passed to the constructor (read them before the engine thread
16// starts) and follows every update that was sent, so it equals what the engine holds once it has
17// consumed the ring. Parameters an update does not name keep their values. With `instruments` > 0
18// the publisher keeps one copy per instrument, and one of the set the updates for every instrument
19// built, and an update may name one instrument, whose values then stay its own until a reset
20// (strategies/param_overrides.hpp); a strategy that keeps one parameter set (ParamScope::Shared)
21// publishes to all instruments.
22//
23// Calls may come from any thread; a mutex serialises them, so the publisher is the ring's only
24// producer. Not for the engine thread: publish allocates.
26#include "fastmm/core/msg_ring.hpp"
28#include "fastmm/core/time.hpp"
29#include "fastmm/strategies/param_overrides.hpp"
31
32#include <cstddef>
33#include <cstdint>
34#include <memory>
35#include <mutex>
36#include <optional>
37#include <span>
38#include <stdexcept>
39#include <string>
40#include <string_view>
41#include <utility>
42#include <vector>
43
44namespace fastmm {
45
46// Where a built update goes; push returns false when it was not accepted (full).
47struct ParamSink {
48 void* ctx = nullptr;
49 bool (*push)(void* ctx, const ParamUpdateMsg& m) noexcept = nullptr;
51 // The SPSC ring an engine's RingFeed polls.
52 [[nodiscard]] static ParamSink to_ring(MsgRing& ring) noexcept {
53 return {&ring, [](void* c, const ParamUpdateMsg& m) noexcept {
54 return static_cast<MsgRing*>(c)->try_push(&m.hdr, m.hdr.len);
55 }};
56 }
57};
58
59class ParamPublisher {
60 public:
61 using ParamValue = std::pair<std::string, std::string>; // name, value as ParamDesc::parse takes
64 // Copying and freeing a parameter block whose layout is known only at run time
65 // (strategies/hot_params.hpp); validate runs after the schema's parsers.
66 struct BlockOps {
67 void* (*clone)(const void* src);
68 void (*destroy)(void* p) noexcept;
69 std::optional<std::string> (*validate)(const void* p);
70 };
71
72 template <class Params>
73 ParamPublisher(ParamSink sink, const Params& current, std::size_t instruments = 0)
74 : ParamPublisher(sink, Params::schema(), block_ops<Params>(), &current, instruments) {}
75 // `schema`'s parsers and `ops` work on blocks like `current`; `schema` must outlive the
76 // publisher.
78 const ParamSchema& schema,
79 const BlockOps& ops,
80 const void* current,
81 std::size_t instruments = 0)
82 : sink_(sink), schema_(&schema), ops_(ops), per_instrument_(instruments != 0) {
83 const std::size_t n = instruments == 0 ? 1 : instruments + 1; // + the shared set, last
84 blocks_.reserve(n);
85 for (std::size_t i = 0; i < n; ++i) blocks_.push_back(clone(current));
86 own_.assign(instruments, ParamMask{});
87 }
88 ParamPublisher(const ParamPublisher&) = delete;
89 ParamPublisher& operator=(const ParamPublisher&) = delete;
92 ~ParamPublisher() = default;
94 // Validates and sends one update. Throws std::invalid_argument when it is invalid; returns false
95 // when the sink refused it (ring full) or the publisher is closed.
96 bool publish(const std::vector<ParamValue>& values, InstrumentId inst = kAllInstruments) {
98 }
99 // publish() with the update's origin, source (ParamUpdateMsg::source, cut to 39 bytes), [ab]
100 // arm (ParamUpdateMsg::arm) and flags. With ParamUpdateMsg::kReset and an instrument, the values
101 // are ignored: the named parameters take the shared values again. The update's publish_seq, 0
102 // when the sink refused it or the publisher is closed.
103 std::uint64_t publish_as(const std::vector<ParamValue>& values,
104 InstrumentId inst,
106 std::string_view source,
107 std::uint8_t arm = ParamUpdateMsg::kArmKeep,
108 std::uint8_t flags = 0) {
109 const std::lock_guard<std::mutex> lock(mutex_);
110 if (closed_) return 0;
111 ParamUpdateMsg m{};
112 Next next;
113 if (auto err = build_locked(values, inst, arm, flags, m, &next))
114 throw std::invalid_argument(*err);
115 m.publish_seq = seq_ + 1;
116 m.origin = origin;
117 m.set_source(source);
118 m.hdr.recv_ts = wall_now();
119 if (!sink_.push(sink_.ctx, m)) {
120 ++refused_;
121 return 0;
122 }
123 ++seq_;
124 for (auto& [k, block] : next.blocks) blocks_[k] = std::move(block);
125 own_ = std::move(next.own);
126 return seq_;
127 }
128 // The named parameters of `inst` take the shared values again; for kAllInstruments, every
129 // instrument does: publish_as() with ParamUpdateMsg::kReset.
130 std::uint64_t reset(const std::vector<std::string>& names,
131 InstrumentId inst,
133 std::string_view source) {
134 std::vector<ParamValue> values;
135 values.reserve(names.size());
136 {
137 const std::lock_guard<std::mutex> lock(mutex_);
138 for (const std::string& name : names) {
139 const ParamDesc* d = schema_->find(name);
140 values.emplace_back(name, d == nullptr ? std::string() : d->format(blocks_.back().get()));
141 }
142 }
143 return publish_as(
145 }
146
147 // The update publish() would send, without sending it or changing the copy; the error message
148 // when it is invalid. `out.publish_seq` and `out.hdr.recv_ts` stay zero.
149 [[nodiscard]] std::optional<std::string> build(const std::vector<ParamValue>& values,
150 InstrumentId inst,
152 std::uint8_t arm = ParamUpdateMsg::kArmKeep,
153 std::uint8_t flags = 0) const {
154 const std::lock_guard<std::mutex> lock(mutex_);
155 return build_locked(values, inst, arm, flags, out, nullptr);
156 }
157
158 // Later publishes return false (the session has stopped).
159 void close() {
160 const std::lock_guard<std::mutex> lock(mutex_);
161 closed_ = true;
162 }
163 [[nodiscard]] bool closed() const {
164 const std::lock_guard<std::mutex> lock(mutex_);
165 return closed_;
166 }
167 // Updates sent, and updates the sink refused.
168 [[nodiscard]] std::uint64_t published() const {
169 const std::lock_guard<std::mutex> lock(mutex_);
170 return seq_;
171 }
172 [[nodiscard]] std::uint64_t refused() const {
173 const std::lock_guard<std::mutex> lock(mutex_);
174 return refused_;
175 }
176 [[nodiscard]] const ParamSchema& schema() const { return *schema_; }
177 // An update may name one instrument: the strategy keeps a parameter set per instrument.
178 [[nodiscard]] bool per_instrument() const noexcept { return per_instrument_; }
179 // Every parameter of the copy, in schema order: one instrument's, or the shared set.
180 struct Value {
181 std::string name;
183 std::int64_t raw; // ParamDesc::get_raw
184 std::string text; // ParamDesc::format
185 };
186 [[nodiscard]] std::vector<Value> values(InstrumentId inst = kAllInstruments) const {
187 const std::lock_guard<std::mutex> lock(mutex_);
188 const std::size_t k = block_of(inst);
189 std::vector<Value> out;
190 out.reserve(schema_->size());
191 for (const ParamDesc& d : *schema_)
192 out.push_back({d.name, d.type, d.get_raw(blocks_[k].get()), d.format(blocks_[k].get())});
193 return out;
194 }
195 // `name=value` pairs of the copy: one instrument's, or the shared set.
196 [[nodiscard]] std::string describe(InstrumentId inst = kAllInstruments) const {
197 const std::lock_guard<std::mutex> lock(mutex_);
198 return detail::describe_params(*schema_, blocks_[block_of(inst)].get());
199 }
200 // The parameters the instrument holds values of its own for, in schema order; none for
201 // kAllInstruments.
202 [[nodiscard]] std::vector<std::string> own(InstrumentId inst) const {
203 const std::lock_guard<std::mutex> lock(mutex_);
204 std::vector<std::string> out;
205 if (!inst.valid() || inst.value >= own_.size()) return out;
206 for (std::size_t f = 0; f < schema_->size(); ++f) {
207 if (own_[inst.value].test(f)) out.emplace_back(schema_->begin()[f].name);
208 }
209 return out;
210 }
211
212 private:
213 template <class P>
214 static const BlockOps& block_ops() {
215 static constexpr BlockOps kOps{
216 [](const void* src) -> void* { return new P(*static_cast<const P*>(src)); },
217 [](void* p) noexcept { delete static_cast<P*>(p); },
218 [](const void* p) { return detail::validate_params(*static_cast<const P*>(p)); }};
219 return kOps;
220 }
221 // The copy of one instrument, or the shared set.
222 [[nodiscard]] std::size_t block_of(InstrumentId inst) const noexcept {
223 if (!per_instrument_) return 0;
224 return inst.valid() && inst.value + 1 < blocks_.size() ? inst.value : blocks_.size() - 1;
225 }
226 struct Deleter {
227 void (*destroy)(void*) noexcept;
228 void operator()(void* p) const noexcept { destroy(p); }
229 };
230 using Block = std::unique_ptr<void, Deleter>;
231
232 [[nodiscard]] Block clone(const void* src) const {
233 return Block(ops_.clone(src), Deleter{ops_.destroy});
234 }
235
236 struct Next {
237 std::vector<std::pair<std::size_t, Block>> blocks;
238 std::vector<ParamMask> own;
239 };
240
241 std::optional<std::string> build_locked(const std::vector<ParamValue>& values,
242 InstrumentId inst,
243 std::uint8_t arm,
244 std::uint8_t flags,
245 ParamUpdateMsg& out,
246 Next* next) const {
247 const ParamSchema& schema = *schema_;
248 if (values.size() > ParamUpdateMsg::kMaxFields) {
249 return "at most " + std::to_string(ParamUpdateMsg::kMaxFields) +
250 " parameters per update, got " + std::to_string(values.size());
251 }
252 const std::size_t shared = blocks_.size() - 1;
253 if (inst.valid()) {
254 if (!per_instrument_) {
255 return std::string(
256 "the strategy keeps one parameter set for all instruments; publish "
257 "without an instrument");
258 }
259 if (inst.value >= shared)
260 return "instrument " + std::to_string(inst.value) + " is not in the instrument table";
261 }
262 out = ParamUpdateMsg{};
264 out.hdr.flags = EventHeader::kSynthetic;
265 out.count = static_cast<std::uint32_t>(values.size());
266 out.arm = arm;
267 out.flags = flags;
268 // The pairs: parsed on a copy of the shared set, or for a reset of one instrument, the shared
269 // set's values.
270 const bool reset_one = inst.valid() && (flags & ParamUpdateMsg::kReset) != 0;
271 const Block scratch = clone(blocks_[shared].get());
272 for (std::size_t i = 0; i < values.size(); ++i) {
273 const auto& [name, value] = values[i];
274 const ParamDesc* d = schema.find(name);
275 if (d == nullptr) return "unknown parameter '" + name + "'";
276 for (std::size_t j = 0; j < i; ++j) {
277 if (values[j].first == name) return "parameter '" + name + "' given twice";
278 }
279 if (!reset_one) {
280 if (auto err = d->parse(scratch.get(), value)) return "parameter '" + name + "': " + *err;
281 }
282 out.field[i] = static_cast<std::uint16_t>(d - schema.begin());
283 out.value[i] = d->get_raw(reset_one ? blocks_[shared].get() : scratch.get());
284 }
285 // The copies the update changes, by the engine's rule (apply_param_pairs).
286 std::vector<std::pair<std::size_t, Block>> changed;
287 std::vector<ParamMask> own = own_;
288 if (per_instrument_) {
289 std::vector<void*> copy(shared, nullptr);
290 apply_param_pairs(
291 out, std::span<ParamMask>(own), schema.size(), [&](std::size_t k, std::size_t i) {
292 if (copy[k] == nullptr) {
293 changed.emplace_back(k, clone(blocks_[k].get()));
294 copy[k] = changed.back().second.get();
295 }
296 schema.begin()[out.field[i]].set_raw(copy[k], out.value[i]);
297 });
298 }
299 if (!inst.valid()) {
300 changed.emplace_back(shared, clone(blocks_[shared].get()));
301 for (std::size_t i = 0; i < values.size(); ++i)
302 schema.begin()[out.field[i]].set_raw(changed.back().second.get(), out.value[i]);
303 }
304 for (const auto& [k, block] : changed) {
305 if (auto err = ops_.validate(block.get())) {
306 if (k < shared) return "instrument " + std::to_string(k) + ": " + *err;
307 return err;
308 }
309 }
310 if (next != nullptr) {
311 next->blocks = std::move(changed);
312 next->own = std::move(own);
313 }
314 return std::nullopt;
315 }
316
317 ParamSink sink_;
318 const ParamSchema* schema_;
319 BlockOps ops_;
320 bool per_instrument_;
321 std::vector<Block> blocks_; // one per instrument and the shared set last, or the shared set
322 std::vector<ParamMask> own_; // per instrument: the parameters it holds as its own
323 mutable std::mutex mutex_;
324 std::uint64_t seq_ = 0;
325 std::uint64_t refused_ = 0;
326 bool closed_ = false;
327};
328
329} // namespace fastmm
Definition param_publisher.hpp:61
bool closed() const
Definition param_publisher.hpp:165
std::string describe(InstrumentId inst=kAllInstruments) const
name=value pairs of the copy: one instrument's, or the shared set.
Definition param_publisher.hpp:198
bool publish(const std::vector< ParamValue > &values, InstrumentId inst=kAllInstruments)
Validates and sends one update.
Definition param_publisher.hpp:98
std::uint64_t reset(const std::vector< std::string > &names, InstrumentId inst, ParamUpdateMsg::Origin origin, std::string_view source)
The named parameters of inst take the shared values again; for kAllInstruments, every instrument does...
Definition param_publisher.hpp:132
std::optional< std::string > build(const std::vector< ParamValue > &values, InstrumentId inst, ParamUpdateMsg &out, std::uint8_t arm=ParamUpdateMsg::kArmKeep, std::uint8_t flags=0) const
The update publish() would send, without sending it or changing the copy; the error message when it i...
Definition param_publisher.hpp:151
std::vector< std::string > own(InstrumentId inst) const
The parameters the instrument holds values of its own for, in schema order; none for kAllInstruments.
Definition param_publisher.hpp:204
ParamPublisher(const ParamPublisher &)=delete
void close()
Later publishes return false (the session has stopped).
Definition param_publisher.hpp:161
ParamPublisher & operator=(const ParamPublisher &)=delete
std::uint64_t publish_as(const std::vector< ParamValue > &values, InstrumentId inst, ParamUpdateMsg::Origin origin, std::string_view source, std::uint8_t arm=ParamUpdateMsg::kArmKeep, std::uint8_t flags=0)
publish() with the update's origin, source (ParamUpdateMsg::source, cut to 39 bytes),...
Definition param_publisher.hpp:105
std::vector< Value > values(InstrumentId inst=kAllInstruments) const
Definition param_publisher.hpp:188
const ParamSchema & schema() const
Definition param_publisher.hpp:178
std::uint64_t refused() const
Definition param_publisher.hpp:174
bool per_instrument() const noexcept
An update may name one instrument: the strategy keeps a parameter set per instrument.
Definition param_publisher.hpp:180
static constexpr InstrumentId kAllInstruments
Definition param_publisher.hpp:64
std::uint64_t published() const
Updates sent, and updates the sink refused.
Definition param_publisher.hpp:170
std::pair< std::string, std::string > ParamValue
name, value as ParamDesc::parse takes
Definition param_publisher.hpp:63
Definition params.hpp:102
const ParamDesc * begin() const noexcept
Definition params.hpp:112
std::size_t size() const noexcept
Definition params.hpp:111
const ParamDesc * find(std::string_view name) const noexcept
Definition params.hpp:105
Event bus message structs (5.5).
Definition strategy.hpp:23
@ ParamUpdate
new strategy parameter values (ParamUpdateMsg)
Timestamp wall_now() noexcept
CLOCK_REALTIME via vDSO (~20 ns). Implemented in src/core/time.cpp.
constexpr void init_header(M &m, EventType type, InstrumentId inst={}, VenueId venue={}, std::uint32_t len=static_cast< std::uint32_t >(sizeof(M))) noexcept
For fixed-size messages len defaults to sizeof(M); BookDeltaMsg passes size_for().
Definition messages.hpp:76
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
ParamType
Definition params.hpp:55
Strategy parameter schema (8.6, ADR-0012).
Strongly typed identifiers.
@ kSynthetic
generated locally (reconcile fill, sim), not from the venue
Definition messages.hpp:40
Definition params.hpp:81
std::string(* format)(const void *obj)
The field's current value in a form parse() accepts ("0.01", "2.5", "true", "2000").
Definition params.hpp:92
std::int64_t(* get_raw)(const void *obj) noexcept
The field as the int64 a ParamUpdateMsg carries, and back (engine thread: no checks).
Definition params.hpp:96
const char * name
Definition params.hpp:82
void(* set_raw)(void *obj, std::int64_t raw) noexcept
Definition params.hpp:97
Copying and freeing a parameter block whose layout is known only at run time (strategies/hot_params....
Definition param_publisher.hpp:68
std::optional< std::string >(* validate)(const void *p)
Definition param_publisher.hpp:71
void(* destroy)(void *p) noexcept
Definition param_publisher.hpp:70
void *(* clone)(const void *src)
Definition param_publisher.hpp:69
Every parameter of the copy, in schema order: one instrument's, or the shared set.
Definition param_publisher.hpp:182
ParamType type
Definition param_publisher.hpp:184
std::string name
Definition param_publisher.hpp:183
std::string text
ParamDesc::format.
Definition param_publisher.hpp:186
std::int64_t raw
ParamDesc::get_raw.
Definition param_publisher.hpp:185
Where a built update goes; push returns false when it was not accepted (full).
Definition param_publisher.hpp:49
static ParamSink to_ring(MsgRing &ring) noexcept
The SPSC ring an engine's RingFeed polls.
Definition param_publisher.hpp:54
bool(* push)(void *ctx, const ParamUpdateMsg &m) noexcept
Definition param_publisher.hpp:51
void * ctx
Definition param_publisher.hpp:50
New strategy parameter values (ADR-0013): up to kMaxFields (field index, raw value) pairs,...
Definition messages.hpp:795
Origin
Definition messages.hpp:802
@ Strategy
the strategy's own publisher (a slow tier, a model), or not recorded
static constexpr std::uint8_t kReset
flags.
Definition messages.hpp:811
static constexpr std::uint8_t kArmKeep
Definition messages.hpp:798
static constexpr std::size_t kMaxFields
Definition messages.hpp:796
static constexpr InstrumentId kAllInstruments
hdr.instrument of an update for every instrument: the invalid id.
Definition messages.hpp:801
Rep value
Definition strong_id.hpp:26
constexpr bool valid() const noexcept
Definition strong_id.hpp:31
Time primitives.