Flow 3.0.1
Flow project: Full implementation reference.
cfg_manager.hpp
Go to the documentation of this file.
1/* Flow
2 * Copyright 2023 Akamai Technologies, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the
5 * "License"); you may not use this file except in
6 * compliance with the License. You may obtain a copy
7 * of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in
12 * writing, software distributed under the License is
13 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
14 * CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing
16 * permissions and limitations under the License. */
17
18/// @file
19#pragma once
20
21#include "flow/cfg/cfg_fwd.hpp"
24#include "flow/util/util.hpp"
26#include <boost/array.hpp>
27#include <boost/unordered/unordered_set.hpp>
28
29namespace flow::cfg
30{
31// Types.
32
33/**
34 * Utility/traits type to concisely work with final-validation functions when calling methods like
35 * Config_manager::apply_static().
36 *
37 * @tparam Value_set
38 * See Option_set.
39 */
40template<typename Value_set>
42{
43 // Types.
44
45 /**
46 * Short-hand for a function that takes a parsed config set (meaning all values are individually OK) and returns
47 * what `Config_manager::apply*()` should do to the candidate-for-canonical-state `Value_set` maintained
48 * by Config_manager. Informally its logic should be:
49 * - (Optional) Does `Value_set` indicate that the file that was parsed should be skipped wholesale? If so
50 * yield Final_validator_outcome::S_SKIP. Else:
51 * - If there are no further inter-option problems (given that individually each option value is okay)
52 * yield Final_validator_outcome::S_ACCEPT. Else yield Final_validator_outcome::S_FAIL.
53 */
54 using Type = Function<Final_validator_outcome (const Value_set&)>;
55
56 // Methods.
57
58 /**
59 * Returns a final-validator function that simply always returns Final_validator_outcome::S_ACCEPT.
60 * @return See above.
61 */
62 static Type null();
63}; // struct Final_validator_func
64
65/**
66 * Empty `struct` suitable as a `*_value_set` template arg for Config_manager, when a slot requires a `Value_set`, but
67 * you have no config to actually parse there. In particular, if you have a static `Value_set` but no corresponding
68 * dynamic one, you should provide this as the template arg.
69 *
70 * @see null_declare_opts_func() and null_final_validator_func().
71 */
73 public util::Shared_ptr_alias_holder<boost::shared_ptr<Null_value_set>>
74{
75};
76
77/**
78 * Manages a config setup, intended for a single daemon process, by maintaining
79 * 1 or more set(s) of static config and dynamic config, each, via that number of `Option_set<>`-ready raw value
80 * `struct` types supplied by the user as template arguments. There is an even number of template args (or it will
81 * not compile); each successive pair contains, in order, a *static* `Value_set` followed by a *dynamic* one.
82 * It is possible, for each given pair, to use static config alone or dynamic config alone; in that case pass in
83 * Null_value_set for the unused one:
84 *
85 * ~~~
86 * // First config pair is static-only; second config pair -- for a separate application module perhaps --
87 * // has both a static and dynamic parts.
88 * flow::cfg::Config_manager<Static_config_general, Null_value_set, Static_socket_opts, Dynamic_socket_opts> ...;
89 * ~~~
90 *
91 * @see Static_config_manager for the probably-common use case when you have only static config and only one `struct`
92 * at that. Static_config_manager adapts Config_manager with a very simple API, avoiding parameter packs
93 * and any mention of various dynamic-config complexities.
94 *
95 * @todo Dynamic config support lacks crash rejection; though these features should be an incremental improvement
96 * around the existing code. By crash rejection I mean something like: config file
97 * X comes in; we rename it to X.unparsed; we try to parse it; program crashes -- versus it's fine, so we rename it
98 * X.parsed, and next time X.parsed is what we presumably-safely parse after any restart. Similarly invalid config
99 * may not cause a crash but still shouldn't be repeatedly re-parsed (etc.). Exact design TBD and will be informed
100 * by previous work on other projects (by echan and ygoldfel at least).
101 *
102 * ### When (and how) to use this ###
103 * First see the namespace flow::cfg doc header for a brief overview. If you have chosen to use flow::cfg for (at least
104 * some of) your config needs, what is mandatory to use is the class template Option_set. The choice is to use it
105 * directly (writing your own facilities around it) or to use this Config_manager to maintain a couple of `Option_set`s
106 * for you in a straightforward way. Config_manager supports that one straightforward way, and for daemon programs
107 * it may be a good choice. Otherwise, the idea behind Option_set is to be able to flexibly use them as needed
108 * (Config_manager providing one such way).
109 *
110 * Firstly, you may create a `const` (immutable) Config_manager via its constructor and then just use it to output
111 * a help message (log_help() or help_to_ostream()). This could be used with your program's `--help` option or similar,
112 * and that's it (no parsing takes place).
113 *
114 * ~~~
115 * // Example of a static-config-only Config_manager created just to log the help, and that's it.
116 * flow::cfg::Config_manager<Static_value_set, Null_value_set>
117 * (get_logger(), "cfg", &static_cfg_declare_opts, flow::cfg::null_declare_opts_func())
118 * .log_help();
119 * ~~~
120 *
121 * Orthogonally, of course, you may want to use it to parse things. In which case:
122 *
123 * Config_manager assumes the following setup:
124 * - 1 or more config sets, each applicable perhaps to a different module of your application/library/etc.
125 * For *each* config set, have 1 or both of the following. (Having neither is pointless; so do not. Officially
126 * behavior is undefined if you do this.)
127 * - One set of values, such that it is read from config source(s) once; then no value therein ever changes again.
128 * Call this type `S_value_set` (S for static).
129 * `S_value_set` must be a type suitable for Option_set as its `Value_set` template arg. See Option_set doc
130 * header. Spoiler alert: It essentially needs to be a `struct` of reasonably-copyable,
131 * reasonably-equality-comparable, stream-parseable, stream-printable scalars (possibly nested); it needs to
132 * declare its default values in a no-arg ctor; and it needs an option-declaring function that calls
133 * FLOW_CFG_OPTION_SET_DECLARE_OPTION() for each data member therein. The latter function must be passed to
134 * Config_manager ctor.
135 * - After ctor, static config stored herein will be at its default values. Call apply_static() (or
136 * apply_static_and_dynamic(); see below) to read the static values (from a file, etc.).
137 * - This `S_value_set` is accessible by reference-to-immutable accessor static_values() or by
138 * all_static_values().
139 * - static_values() and all_static_values() are essentially thread-safe, at least after apply_static(), in that
140 * static_values() will always return a reference to the same `S_value_set` and all_static_values() will
141 * always emit the same pointers, and the values within the `S_value_set`(s) shall never change.
142 * - A 2nd set of values, such that it is read from config source(s) at least once; but then potentially
143 * more times, and each time 0 or more of the values may be changed from the original setting.
144 * `D_value_set`, again, must be a type suitable for Option_set as its `Value_set`.
145 * - Initialize the first set of dynamic values by calling either apply_static_and_dynamic() (if your setup allows
146 * for initial dynamic values to be supplied in the same config source(s) (e.g., same file) as static ones)
147 * *and* then apply_dynamic(); or *only* the latter.
148 * - After that initial `apply*_dynamic()`: dynamic_values() returns a ref-counted pointer to the heap-allocated
149 * `D_value_set` canonical at that time. dynamic_values() may return a different pointer each time (and
150 * will, if a dynamic change is detected); but the values *at* a given return pointer will *never* change.
151 * all_dynamic_values() is an alternate approach but essentially the same idea.
152 * - Now, whenever you have reason to believe the dynamic config may have changed, call apply_dynamic().
153 * - apply_dynamic() (after the first one) and dynamic_values() are mutually thread-safe: they can be safely
154 * called concurrently with each other and/or themselves. Internally, an atomic pointer to `D_value_set`
155 * is stored; `apply_dynamic()` makes a single update to it -- after a potentially lengthy successful parse
156 * of config source(s) -- while dynamic_values() makes an atomic read followed by a pointer copy (and
157 * returns the copy). The ref-counted-ptr handle ensures the returned `D_value_set` survives as long
158 * as the user needs it, even if it's immediately replaced by new config within the Config_manager.
159 * - Since dynamic config can change at any time, it is up to the config user how they want to operate on the
160 * ref-counted handle obtained from dynamic_values(). If a potentially new value each time is fine, it's fine
161 * to simply do `cm.dynamic_values()->m_some_opt`. If one needs a consistent set of 2 or more values, or
162 * if one needs values to not change over time, then one can simply save `auto dyn_cfg = cm.dynamic_values()`
163 * and then access values through `dyn_cfg->` as long as consistency is desired. (Again: `*dyn_cfg` can never
164 * change, once `dyn_cfg` is returned through dynamic_values().)
165 * - You may also have hooks executed when dynamic config changes. This is a simple system: before
166 * any relevant `apply*_dynamic()` calls, call register_dynamic_change_listener() for each module that
167 * wants to be informed. Each callback so registered will be *synchronously* executed from `apply*_dynamic()`,
168 * when a relevant change is detected.
169 *
170 * To summarize: This is the assumed order of API calls on a given `*this`; other orders may lead to undefined behavior:
171 * - Config_manager ctor.
172 * - apply_static() or (if using dynamic config, but even so still optional) apply_static_and_dynamic().
173 * - If using dynamic config: apply_dynamic().
174 * - Simultaneously/at various times (thread-safe w/r/t each other):
175 * - static_values() (always returns a reference to the same immutable `S_value_set`).
176 * - all_static_values() (always emits the same pointers to immutable `S_value_set`s).
177 * - If using dynamic config: dynamic_values() (if returned `x`, `*x` is immutable; but may return different `x`es
178 * over time). Alternatively: all_dynamic_values().
179 * - apply_dynamic() (changes ptr returned by dynamic_values() and all_dynamic_values()).
180 * - Config-using modules' destructors/deinitialization code.
181 * - For each such module: Obviously it must run after the last `*ic_values()` call.
182 * - For each such module: It *must* run before Config_manager dtor.
183 * - Config_manager dtor.
184 *
185 * In addition, between Config_manager ctor and dtor:
186 * - (Optional) If using dynamic config: register_dynamic_change_listener() (for each module interested in it);
187 * not thread-safe against concurrent apply_dynamic(), apply_static_and_dynamic(), or
188 * unregister_dynamic_change_listener().
189 * - Functions `register_dynamic_change_listener()`ed earlier may execute synchronously from within
190 * apply_dynamic() and/or apply_static_and_dynamic().
191 * - Such user functions may load async work elsewhere.
192 * - Ensure that thing onto which they load async work exists! See register_dynamic_change_listener() for
193 * useful patterns to ensure this.
194 * - (Optional) If a callback has been registered: unregister_dynamic_change_listener(); not thread-safe against
195 * concurrent apply_dynamic(), apply_static_and_dynamic(), or unregister_dynamic_change_listener().
196 * - Any callback which accesses something which can be invalidated SHOULD be unregistered before that thing becomes
197 * invalid. If there is a chance that apply_dynamic() or apply_static_and_dynamic() might be called after it
198 * has become invalid, then the callback MUST be unregistered (otherwise, undefined behavior could be encountered
199 * when the invalid thing is accessed).
200 *
201 * ### Advanced feature: multi-source parsing and source skipping ###
202 * By default this feature is not in play, as the `bool commit` arg to apply_static_and_dynamic(), apply_static(),
203 * and apply_dynamic() defaults to `true`. The multi-source feature is enabled by the user setting it to `false`
204 * for some calls to `apply_*()`. To explain how it works consider one particular `Value_set` and an attempt
205 * to execute one of `apply_*()` methods w/r/t that `Value_set` (among potentially others to which the same
206 * discussion applies equally). For purposes of discussion assume it is a dynamic `Value_set`, and the operation
207 * in question is apply_dynamic(); the same points apply to static ones and the other two `apply_*()` calls
208 * except where noted below.
209 *
210 * Suppose the canonical (as returned by dynamic_values() or all_dynamic_values()) `Value_set` is in state B,
211 * the baseline state. (If `Value_set` is static, then B is the default state from default-cted `Value_set`, and
212 * the canonical-state accessors are static_values() and all_static_values().)
213 * Normally a single *update* consists of just one call to `apply_dynamic(commit = true)`:
214 * -# `R = apply_dynamic(P, F, true)`, where `P` is a file path, and `F` is your Final_validator_func::Type function.
215 *
216 * If `F() == Final_validator_outcome::S_FAIL`, then `R == false`; state stays at B.
217 * If it's `F() == S_ACCEPT` (and the individual options were all fine), then `R == true`; state becomes B';
218 * and if B does not equal B' (a change was detected), then the dynamic changes listener(s)
219 * (from register_dynamic_change_listener()) are synchronously called before apply_dynamic() returns.
220 * (That listener stuff does not apply to static `Value_set`s in apply_static() and apply_static_and_dynamic().)
221 *
222 * That's the default behavior without engaging this feature. To engage the feature, one has to
223 * call `apply_dynamic(commit = false)` at least once. A single *update* now consists of 2+ calls
224 * to `apply_dynamic()`:
225 * -# `R = apply_dynamic(P1, F, false)`; if `!R`, update failed/exit algorithm; else:
226 * -# `R = apply_dynamic(P2, F, false)`; if `!R`, update failed/exit algorithm; else:
227 * -# ...
228 * -# `R = apply_dynamic(Pn, F, true)`; if `!R`, update failed/exit algorithm; else done.
229 * The `true` arg indicates the final call.
230 *
231 * (`F` can be different each time, though informally we suspect that would be unorthodox. It is allowed formally.)
232 *
233 * Each apply_dynamic() call builds up a *candidate* `Value_set C` which is created (at the top of call 1)
234 * to equal baseline/initial state B and then potentially incrementally morphed by each apply_dynamic() call.
235 * Assuming no error (from individual validator or an `F() == S_FAIL`) at any stage, the effect on the *candidate*
236 * `Value_set C` is as follows:
237 * -# If `F(Cnext) == S_ACCEPT`: Modify the *candidate* by overwriting it: `C = Cnext;`.
238 * -# If `F(Cnext) == S_SKIP`: Keep the *candidate* `Value_set C` unchanged from its current value at entry to that
239 * apply_dynamic() call. `Cnext` is discarded (so the incremental update to the candidate is *skipped*).
240 *
241 * However, and this is the key:
242 * - `apply_dynamic(..., false)` does *not* modify the canonical (as returned by all_dynamic_values(), etc.)
243 * state. It remains equal to B. Hence no dynamic change listeners are invoked. However:
244 * - the final call -- `apply_dynamic(..., true)` -- makes the canonical state equal the *candidate* `Value_set C`
245 * that has been built up. Accordingly, before `apply_dynamic(..., true)` returns, if the canonical
246 * `Value_set B` differs from the candidate `Value_set C` that overwrites it, dynamic change listeners are
247 * invoked.
248 *
249 * (Hence the one-call update scenario (the vanilla one) is merely a degenerate case of the multi-call scenario;
250 * as then the last call is the only call and thus canonicalizes the candidate and calls dynamic change listeners if
251 * appropriate.)
252 *
253 * If at any stage `F(Cnext)` yields Final_validator_outcome::S_FAIL, then apply_dynamic() returns `false`. This means
254 * the entire update has failed; the *candidate* is abandoned, and you should not make the subsequent
255 * apply_dynamic() calls that may be remaining in the update. The next such call will be taken to be the 1st
256 * of another update, with a fresh candidate C created to equal B.
257 *
258 * Why use this? Why use 2+ files for a given update? Indeed you shouldn't, unless there is specifically a good
259 * reason. What might that be? The precipitating use case, and the basic one immediately obvious to the authors,
260 * is where exactly for 1 of the files the final-validator shall return Final_validator_outcome::S_ACCEPT, while
261 * for *all* others it will return Final_validator_outcome::S_SKIP. For example, if your distributed network
262 * consists of 3 sections, and each machine knows to which section it belongs, and each file is aimed at exactly 1
263 * of the 3 and thus specifies it as some option `if-section-is=` (possible values 1 or 2 or 3), then the
264 * final-validator func would:
265 * -# Check `if-section-is` option and return SKIP if the machine's actual section does not match it. Else:
266 * -# Ensure internal consistency of candidate `Value_set` (as usual).
267 * -# Return FAIL or ACCEPT depending on the answer to that (as usual).
268 *
269 * Now you've enabled conditional config in a distributed deployment.
270 *
271 * @warning In this *conditional config* use case, it is likely best to declare any given conditional option
272 * using a `_NO_ACC` variation of your `FLOW_CFG_OPTION_SET_DECLARE_OPTION*()` option of choice;
273 * that is `FLOW_CFG_OPTION_SET_DECLARE_OPTION_NO_ACC()` or similarly-postfixed variation.
274 * You probably do not want such an option's value to persist from an earlier file in the update to a later
275 * one; instead it should probably reset to its default "at the top" of each file; `_NO_ACC` variants
276 * will accomplish this.
277 *
278 * That said the use of SKIP (for all but 1) is not mandatory in such a multi-file-update setup. You can never-SKIP,
279 * or you can ACCEPT (not-SKIP) 2+ files; it is conceivable those setups have use cases as well. Informally though we
280 * reason to you as follows:
281 * - If you never SKIP, then why complicate matters by having updates consist of 2+ files in the first place?
282 * Isn't it simpler (for config deployment and other aspects of the system) to just keep it to 1?
283 * - If you ACCEPT (don't-SKIP) 2+ files, then merely looking at a given file will no longer easily show the resulting
284 * final config, as each individual update is now incremental in nature; a preceding file in the same update
285 * may have changed (versus baseline) some setting not mentioned in that particular file. This may prove to be
286 * confusing.
287 * - If you ACCEPT (don't-SKIP) exactly 1 file, then this no longer the case, and things are simple enough again.
288 * - If you ACCEPT (don't-SKIP) 2+ files, then to mitigate the problem where the final config is not quite clear
289 * just by looking at the input files, it's simple to use state_to_ostream() or log_state() to direct the
290 * result to a file or the logs, for human viewing.
291 *
292 * The above are informal recommendations for maximum simplicity or clarity, but it is entirely conceivable a more
293 * complex situation arises and requires they not be heeded.
294 *
295 * ### Relationship with the rest of your program/threads ###
296 * At this time Config_manager is deliberately simple in that it doesn't start any threads of its own; it doesn't watch
297 * file modifications to detect dynamic changes; and its methods can be called from any thread and always act
298 * entirely synchronously. (The only methods affected by thread considerations are apply_dynamic() and
299 * dynamic_values() + all_dynamic_values(); they are intentionally thread-safe w/r/t each other.)
300 *
301 * To the extent that it uses callbacks -- again, only for dynamic config needs and only optionally -- they, too, are
302 * executed synchronously. However, these callbacks can (of course) `.post()` work onto boost.asio util::Task_engine
303 * or async::Concurrent_task_loop or async::Single_thread_task_loop.
304 *
305 * Informally:
306 * It is, however, possible and perhaps probable that one should build more facilities to detect cfg changes of various
307 * kinds; for this thread(s) may be useful. We suspect it is better to build class(es) that do that and make use of
308 * Config_manager -- not expand Config_manager to do such things. Its simplicity and relative light weight and
309 * flexibility are good properties to conserve and not saddle with baggage (even optional baggage).
310 *
311 * ### Thread safety ###
312 * This is discussed in bits and pieces above and in various doc headers. Here is the overall picture however:
313 * - Separate Config_manager objects are independent of each other, so there are no thread safety issues.
314 * - For a given `*this`:
315 * - By default, no non-`const` method is safe to call concurrently with any other method. Except:
316 * - dynamic_values() / all_dynamic_values() may be called concurrently with itself/each other or any other method
317 * including `apply_dynamic(commit = *)`, as long as either `apply_dynamic(commit = true)` or
318 * `apply_static_and_dynamic(commit = true)` has succeeded at least once prior.
319 *
320 * @tparam S_d_value_set
321 * An even number (at least 2) of settings `struct`s -- see Option_set doc header for requirements for each --
322 * in order static, dynamic, static, dynamic, .... Use Null_value_set as needed; but do not use Null_value_set
323 * for both the static and dynamic parameter in a given pair (e.g., `<Null_value_set, Null_value_set, ...>`
324 * is both useless and formally disallowed).
325 *
326 * @internal
327 * ### Implementation notes ###
328 * I (ygoldfel) wrote this, originally, in 2 stages. At first it only supported exactly 2 template args: one static
329 * and one dynamic `Value_set`. In the next stage I turned it into a parameter pack, so that 4, 6, 8, ... args
330 * can be provided if desired -- to support multiple configurable modules in the application. Before this I had done
331 * some basic parameter-pack coding, but undoubtedly Config_manager is my first foray into this level of
332 * sophistication. Certainly I welcome changes to improve clarity of the implementation and other suggestions.
333 * Generally speaking the code does strike me as complex, though there's a good case to be made to the effect of:
334 * That is just the nature of the beast. It's meta-programming: having the compiler perform loops, of a sort,
335 * at *compile time*. Because `S_d_value_set...` is not homogenous -- within each adjacent pair of tparams the first
336 * and the second are *not* always treated equivalently -- the code has to be tricky at times.
337 *
338 * That said the usability of the API should not be affected by these details much. At times one has to supply
339 * additional `<template args>` -- apply_static() and apply_dynamic() come to mind in particular -- to help the
340 * compiler; but the compiler will complain about being unable to deduce the tparams, and then the next action for the
341 * user is straightforward.
342 *
343 * ### A particular trick explained ###
344 * In C++17 fold expressions are available (https://en.cppreference.com/w/cpp/language/fold), and we use them
345 * to create compile-time loops without the appalling coding/maintenance overhead of the meta-recursive pattern.
346 * (This replaces a much uglier trick involving a dummy `int[]` initializer, though that was still superior to
347 * doing the meta-recursive thing all over the place.)
348 *
349 * Suppose, say, you want to call `f<Value_set>(idx, dyn_else_st)`,
350 * where `idx` runs through [0, #S_N_VALUE_SETS), while `dyn_else_st` alternates between `false` (static) and
351 * `true` (dynamic). E.g., `f()` might parse the `idx`th slot of #m_s_d_opt_sets and do something extra if it's
352 * an odd (dynamic) slot. Note `f()` is a template parameterized on `Value_set`. Then:
353 *
354 * ~~~
355 * size_t idx = 0;
356 * bool dyn_else_st = false;
357 * (
358 * ..., // This indicates the entire (..., expr) is a fold-expression, where...
359 * (
360 * // ...the `S_d_value_set` in the following expression is the kernel of the param-pack expansion;
361 * // due to the fact the class template is: template<typename... S_d_value_set> class Config_manager
362 * f<S_d_value_set>(idx, dyn_else_st),
363 * ++idx,
364 * dyn_else_st = !dyn_else_st)
365 * )
366 * );
367 * ~~~
368 *
369 * `(..., expr)` expands to, ultimately, `(expr1, expr2, ..., expr3)`, where each `expr...i...` is `expr` with
370 * the i-th `S_d_value_set`. In our case `expr...i...` is itself a comma-expression with 3 sub-expressions.
371 * Comma-expression evaluates left-to-right, so at runtime the side effects of each
372 * `expr...i...` are occurring at runtime; in this case this includes incrementing `idx` and repeatedly flipping
373 * `dyn_else_st`.
374 *
375 * In the actual code, often we don't (just) call some helper `f<>()` but rather actually perform some steps in-line
376 * there instead -- similarly to how this example does a couple of simple expressions after calling `f<>()`.
377 * The good thing is the reader need not jump to another function (and all that maintenance overhead). The bad thing
378 * is the language constructions within an expression in C++ (not a functional language) are limited. Loops aren't
379 * possible; `if ()`s have to be replaced by `?:` ternaries or `&&` or `||` expressions; and so on.
380 * It's not always the most readable thing, if one isn't used to it, but the author feels it's doable to get used to it,
381 * and it's worth it for the brevity.
382 */
383template<typename... S_d_value_set>
385 public log::Log_context
386{
387public:
388 // Types.
389
390 /**
391 * Tag type: indicates an `apply_*()` method must *allow* invalid defaults and only complain if the config source
392 * does not explicitly supply a valid value. Otherwise the defaults themselves are also stringently checked
393 * regardless of whether they are overridden. This setting applies only to individual-option-validators.
394 * Final_validator_func validation is orthogonal to this.
395 */
397 {
398 S_ALLOW_INVALID_DEFAULTS ///< Sole value for tag type #allow_invalid_defaults_tag_t.
399 };
400
401 /// Short-hand for a callback to execute on dynamic config change.
403
405
406 // Constants.
407
408 /// The number of template params in this Config_manager instantiation. It must be even and positive.
409 static constexpr size_t S_N_VALUE_SETS = sizeof...(S_d_value_set);
410
411 static_assert((S_N_VALUE_SETS % 2) == 0,
412 "Must have even number of template args to Config_manager; use a trailing Null_value_set if needed.");
413 /// The number of static value sets (including any `Null_value_set`s).
414 static constexpr size_t S_N_S_VALUE_SETS = sizeof...(S_d_value_set) / 2;
415 /// The number of dynamic value sets (including any `Null_value_set`s).
416 static constexpr size_t S_N_D_VALUE_SETS = sizeof...(S_d_value_set) / 2;
417
418 // Constructors/destructor.
419
420 /**
421 * Constructs a Config_manager ready to read initial config via `apply_*()` and other setup methods; and further
422 * capable of both static and dynamic config. See class doc header for class lifecycle instructions.
423 *
424 * ### Logging assumption ###
425 * `*logger_ptr` is a standard logging arg. Note, though, that the class will assume that log verbosity may not have
426 * yet been configured -- since this Config_manager may be the thing configuring it. Informal recommendations:
427 * - You should let through INFO and WARNING messages in `*logger_ptr`.
428 * - If you plan to use `*this` only for log_help() (such as in your `--help` implementation), you should
429 * *not* let through TRACE-or-more-verbose.
430 * - Once (and if) you engage any actual parsing (apply_static(), etc.), TRACE may be helpful
431 * in debugging as usual.
432 *
433 * @param logger_ptr
434 * Logger to use for subsequently logging.
435 * @param nickname
436 * Brief string used for logging subsequently.
437 * @param declare_opts_func_moved
438 * For each `S_d_value_set`, in order, the declare-options callback as required by
439 * `Option_set<S_d_value_set>` constructor; see its doc header for instructions.
440 * For each Null_value_set: use the function returned by `null_declare_opts_func()`.
441 */
442 explicit Config_manager(log::Logger* logger_ptr, util::String_view nickname,
443 typename Option_set<S_d_value_set>::Declare_options_func&&... declare_opts_func_moved);
444
445 // Methods.
446
447 /**
448 * Invoke this after construction to load the permanent set of static config from config sources including
449 * a static config file; if you are also using dynamic config, see apply_static_and_dynamic() as a *potential*
450 * alternative. See also apply_static() overload with #allow_invalid_defaults_tag_t tag.
451 *
452 * After this runs and succeeds, assuming `commit == true`, you may use static_values() and/or
453 * all_static_values() to access the loaded values. After this runs and succeeds, but `commit == false`,
454 * you should call apply_static() again 1+ times, with the last such call having `commit == true` and thus
455 * canonicalizing each progressively-built candidate `Value_set`, so that it becomes available via static_values()
456 * and all_static_values().
457 *
458 * On failure returns `false`; else returns `true`. In the former case the canonical state remains unchanged,
459 * and any candidate built-up via preceding `commit == false` calls (if any) is discarded. The next
460 * `apply_*()` call begins a fresh update.
461 *
462 * Tip: On failure you may want to exit program with error; or you can continue knowing that
463 * static_values() will return a reference to default values (and all_static_values() will emit pointers to
464 * `Value_set`s with default values) according to `Value_set{}` no-arg ctor (for each `Value_set`).
465 * WARNING(s) logged given failure.
466 *
467 * apply_static() will *not* be tolerant of unknown option names appearing in the config source. The reasoning
468 * (and we might change our minds over time): It should be possible to deliver the proper set of static config
469 * along with the binary that supports it.
470 * - Incidentally this also holds for apply_static_and_dynamic().
471 * - However apply_dynamic() is tolerant of unknown option names.
472 *
473 * You must supply exactly #S_N_S_VALUE_SETS `final_validator_func`s. The compiler will likely require you to
474 * explicitly specify the `struct` types as explicit template args; e.g:
475 *
476 * ~~~
477 * Config_manager<S_config1, D_config1, S_config2, D_config2, Null_value_set, D_config3> cfg_mgr(...);
478 * // Explicitly specify the static config struct types. Provide that number of final-validate functions.
479 * // Use null_final_validator_func() for the dummy Null_value_set in particular.
480 * cfg_mgr.apply_static<S_config1, S_config2, Null_value_set>
481 * (file_path, s_final_validator1, s_final_validator2, null_final_validator_func());
482 * ~~~
483 *
484 * For context w/r/t `commit` arg: Please read the section of the class doc header regarding multi-source
485 * updates. Corner case note: Formally: invoking `apply_Y()` immediately after `apply_X(commit = false) == true`,
486 * without reject_candidates() between them, where Y and X differ => `apply_Y()` shall log an INFO message
487 * and invoke reject_candidates() itself; then proceed. In this case `apply_Y()` is apply_static().
488 * Informally we discourage doing this; it is stylistically better to invoke reject_candidates()
489 * explicitly in that scenario which cancels an in-progress update which is unusual though conceivably useful.
490 *
491 * ### Effect of a validator yielding SKIP ###
492 * Consider `Value_set`s in their order of declaration, V1, V2, .... If any one of them fails individual
493 * option validation, or its `final_validator_func()` yields FAIL, then we return `false`
494 * indicating this entire update has failed. If all parsed fine, and `final_validator_func()` yielded ACCEPT for all,
495 * then we return `true`, indicating this update is successful (so far at least, depending on `commit`).
496 *
497 * Now consider the situation where for `Value_set` Vi, `final_validator_func()` yielded SKIP, while all
498 * Vj before Vi yielded ACCEPT.
499 *
500 * Effect 1: The parsed values for that `Value_set` Vi shall be ignored, as-if they were equal to the cumulative
501 * values built in preceding files in this update (or to the baseline values, if this is the first or only
502 * file in this update).
503 *
504 * Effect 2: The same shall hold for *each* `Value_set` Vj *after* Vi: They will not be parsed; they will not be
505 * validated; their `final_validator_func()` shall not be executed; and they shall be ignored, as-if they were equal
506 * to the cumulative values built in preceding files in this update (or to the baseline values, if this is the
507 * first or only file in this update). So, if (e.g.) V2 is the first `Value_set` to yield SKIP, then
508 * it's as-if V2, V3, ... also yielded SKIP (conceptually speaking) -- to the point where their values in
509 * the source are ignored entirely.
510 *
511 * @note Each `final_validator_func()` can be made quite brief by using convenience macro
512 * FLOW_CFG_OPT_CHECK_ASSERT(). This will take care of most logging in most cases.
513 * @note For each Null_value_set: use `final_validator_func = null_final_validator_func()`.
514 * @note A validator function will not be run if there is a failure to parse any preceding `Value_set` (including a
515 * failure of its associated validator function).
516 * @note A validator function may rely on all_static_values_candidates() and static_values_candidate() providing the
517 * parsed (and validated) values candidate for any preceding static value set.
518 *
519 * @todo Add support for command line as a config source in addition to file(s), for static config in
520 * cfg::Config_manager and cfg::Static_config_manager.
521 *
522 * @tparam Value_set
523 * These must be `S_d_value_set` template param pack args 0, 2, ..., numbering
524 * #S_N_S_VALUE_SETS in order.
525 * @param static_cfg_path
526 * File to read.
527 * @param final_validator_func
528 * For each arg:
529 * If parsing and individual-option-validation succeed, the method shall return success if
530 * `final_validator_func(V)` returns Final_validator_outcome::S_ACCEPT or Final_validator_outcome::S_SKIP,
531 * where V is the parsed `Value_set`. (If `apply_static(commit = false) == true` call(s) preceded this
532 * one, V is the cumulative candidate from such call(s) so far, plus values parsed from
533 * `static_cfg_path` on top of that.)
534 * Informally: Please place individual-option validation
535 * into FLOW_CFG_OPTION_SET_DECLARE_OPTION() invocations; only use `final_validator_func()` for
536 * internal consistency checks (if any) and skip conditions (if any).
537 * Plus: if a `final_validator_func()` for a particular `Value_set` returns `S_SKIP`, then
538 * the subsequent ones will not run (nor will those subsequent `Value_set`s be parsed or individually
539 * validated).
540 * @param commit
541 * `true` means that this call being successful (returning `true`) shall cause the promotion of
542 * each candidate `Value_set` built-up so far (via this call and all preceding successful calls with
543 * `commit == false`) to canonical state (accessed via static_values() or all_static_values()).
544 * `false` means that this call being successful shall merely create-and-set (if first such call)
545 * or incrementally update (if 2nd, 3rd, ... such call) each candidate `Value_set`.
546 * @return `true` if and only if successfully parsed config source and validated all settings including
547 * `final_validator_func() != S_FAIL` for *all* (static) config sets; and defaults were also all individually
548 * valid. However, if `true` but `commit == false`, then the canonical values
549 * (accessed via static_values() or all_static_values()) have not been updated.
550 * If `false` with `commit == false`, you should not call apply_static() for the planned
551 * subsequent config sources: this update has failed, and any built-up candidate `Value_set`s are
552 * discarded.
553 */
554 template<typename... Value_set>
555 bool apply_static(const fs::path& static_cfg_path,
556 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
557 bool commit = true);
558
559 /**
560 * Identical to apply_static() overload without #allow_invalid_defaults_tag_t tag; but skips the stringent
561 * check on individual defaults' validity.
562 *
563 * @see #allow_invalid_defaults_tag_t doc header and/or return-value doc just below.
564 *
565 * @tparam Value_set
566 * See other apply_static().
567 * @param static_cfg_path
568 * See other apply_static().
569 * @param final_validator_func
570 * See other apply_static().
571 * @param commit
572 * See other apply_static().
573 * @return See other apply_static(). The difference between the other `apply_static()` and this overload is:
574 * The other overload will return `false` given an invalid default, even if
575 * file `static_cfg_path` explicitly sets it to a valid value. This tagged overload will not fail (return
576 * `false` for that reason) and will let parsing continue instead.
577 */
578 template<typename... Value_set>
580 const fs::path& static_cfg_path,
581 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
582 bool commit = true);
583
584 /**
585 * If you use dynamic config, *and* you allow for initial values for dynamic options to be read from the same file
586 * as the static config values, then invoke this instead of apply_static(). See also apply_static_and_dynamic()
587 * overload with #allow_invalid_defaults_tag_t tag.
588 *
589 * With static config-only use case:
590 * - Just apply_static().
591 * - Then static_values() / all_static_values() whenever needed.
592 *
593 * With dynamic-and-static config use case, *with* allowing baseline dynamic values to be set in static config
594 * file:
595 * - apply_static_and_dynamic(). <-- ATTN
596 * - Initial apply_dynamic(). (Typically it is allowed that there is no dynamic config file present yet though.)
597 * - Then static_values() / all_static_values(), dynamic_values() / all_dynamic_values() whenever needed.
598 * - Further apply_dynamic(), if dynamic config source(s) may have changed.
599 *
600 * With dynamic-and-static config use case, *without* allowing baseline dynamic values to be set in static config
601 * file:
602 * - apply_static().
603 * - Initial apply_dynamic().
604 * - Then static_values() / all_static_values(), dynamic_values() / all_dynamic_values() whenever needed.
605 * - Further apply_dynamic(), if dynamic config source(s) may have changed.
606 *
607 * On failure returns `false`; else returns `true`. In the former case the canonical state remains unchanged,
608 * and any candidate built-up via preceding `commit == false` calls (if any) is discarded. WARNING(s) logged
609 * given failure.
610 *
611 * For context w/r/t `commit` arg: Please read the section of the class doc header regarding multi-source
612 * updates. Corner case note: Formally: invoking `apply_Y()` immediately after `apply_X(commit = false) == true`,
613 * without reject_candidates() between them, where Y and X differ => `apply_Y()` shall log an INFO message
614 * and invoke reject_candidates() itself; then proceed. In this case `apply_Y()` is apply_static_and_dynamic().
615 * Informally we discourage doing this; it is stylistically better to invoke reject_candidates()
616 * explicitly in that scenario which cancels an in-progress update which is unusual though conceivably useful.
617 *
618 * ### Effect of a validator yielding SKIP ###
619 * Identical to apply_static() but across both static and dynamic `Value_set`s, in static/dynamic/static/dynamic/...
620 * order.
621 *
622 * @note By definition this will not compile unless `final_validator_func` count equals #S_N_VALUE_SETS.
623 * However, unlike apply_static() or apply_dynamic(), there are no template args to explicitly supply.
624 *
625 * @param cfg_path
626 * File to read for both static and dynamic config.
627 * @param final_validator_func
628 * See apply_static(); particularly the notes about how a validator function will not be run if there is a
629 * preceding failure and that all_static_values_candidates() and static_values_candidate() can be relied upon.
630 * @param commit
631 * `true` means that this call being successful (returning `true`) shall cause the promotion of
632 * each candidate `Value_set` built-up so far (via this and all preceding successful calls with
633 * `commit == false`) to canonical state (accessed via `*ic_values()` or `all_*ic_values()`);
634 * and all dynamic change listeners are synchronously called.
635 * `false` means that this call being successful shall merely create-and-set (if first such call)
636 * or incrementally update (if 2nd, 3rd, ... such call) each candidate `Value_set`; no dynamic change
637 * listeners are invoked.
638 * @return `true` if and only if successfully parsed config source(s) and validated all settings including
639 * `final_validator_func() != S_FAIL` for *all* (static and dynamic) config sets; and defaults were also all
640 * individually valid. However, if `true` but `commit == false`, then the canonical values
641 * (accessed via `*ic_values()` or `*ic_values()`) have not been updated.
642 * If `false` with `commit == false`, you should not call apply_static_and_dynamic() for the planned
643 * subsequent config sources: this update has failed, and any built-up candidate `Value_set`s are
644 * discarded.
645 */
646 bool apply_static_and_dynamic(const fs::path& cfg_path,
647 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
648 bool commit = true);
649
650 /**
651 * Identical to apply_static_and_dynamic() overload without #allow_invalid_defaults_tag_t tag; but skips the stringent
652 * check on individual defaults' validity.
653 *
654 * @see #allow_invalid_defaults_tag_t doc header and/or return-value doc just below.
655 *
656 * @param cfg_path
657 * See other apply_static_and_dynamic().
658 * @param final_validator_func
659 * See other apply_static_and_dynamic().
660 * @param commit
661 * See other apply_static_and_dynamic().
662 * @return See other apply_static_and_dynamic(). The difference between the other `apply_static_and_dynamic()` and
663 * this overload is:
664 * The other overload will return `false` given an invalid default, even if
665 * file `cfg_path` explicitly sets it to a valid value. This tagged overload will not fail (return
666 * `false` for that reason) and will let parsing continue instead.
667 */
669 const fs::path& cfg_path,
670 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
671 bool commit = true);
672
673 /**
674 * Load the first or subsequent set of dynamic config from config source including a dynamic config file.
675 * If you use dynamic config: You must invoke this, or apply_static_and_dynamic(), once before access via
676 * dynamic_values() / all_dynamic_values(). After that, optionally invoke it whenever there is good reason
677 * to believe new dynamic config is available in the dynamic config source(s).
678 *
679 * See also apply_static_and_dynamic(). If not using apply_static_and_dynamic(), *and* this is the initial
680 * apply_dynamic() invoked, then see also apply_dynamic() overload with #allow_invalid_defaults_tag_t tag.
681 *
682 * After the initial apply_dynamic(): It is safe to call apply_dynamic() concurrently with any number of
683 * `[all_]dynamic_values()`. However behavior is undefined if one calls apply_dynamic() concurrently with itself
684 * or apply_static_and_dynamic() (on the same `*this`).
685 *
686 * On failure returns `false`; else returns `true`. In the former case the canonical state remains unchanged,
687 * and any candidate built-up via preceding `commit == false` calls (if any) is discarded. WARNING(s) logged
688 * given failure.
689 *
690 * apply_dynamic() will be tolerant of unknown option names appearing in the config source, though it will
691 * log about them. The reasoning: Dynamic config must grapple with backward- and forward-compatibility.
692 *
693 * For context w/r/t `commit` arg: Please read the section of the class doc header regarding multi-source
694 * updates. Corner case note: Formally: invoking `apply_Y()` immediately after `apply_X(commit = false) == true`,
695 * without reject_candidates() between them, where Y and X differ => `apply_Y()` shall log an INFO message
696 * and invoke reject_candidates() itself; then proceed. In this case `apply_Y()` is apply_dynamic().
697 * Informally we discourage doing this; it is stylistically better to invoke reject_candidates()
698 * explicitly in that scenario which cancels an in-progress update which is unusual though conceivably useful.
699 *
700 * ### Effect of a validator yielding SKIP ###
701 * Identical to apply_static().
702 *
703 * ### Performance ###
704 * dynamic_values() + all_dynamic_values() locking performance is no worse than: lock mutex,
705 * assign #S_N_D_VALUE_SETS `shared_ptr`s, unlock mutex. The rest of the parse/validate/etc. code is outside any such
706 * critical section. See also Performance section of dynamic_values() doc header.
707 *
708 * Outside that locking critical section, apply_dynamic() may be expensive, in that it performs file input and some
709 * internal copying of option value sets and maps, plus detailed logging. It is, however, not typically called
710 * frequently. Just be aware it will block the calling thread, albeit still only for a split second in normal
711 * conditions.
712 *
713 * @tparam Value_set
714 * These must be `S_d_value_set` template param pack args 1, 3, ..., numbering
715 * #S_N_D_VALUE_SETS in order.
716 * @param dynamic_cfg_path
717 * File to read.
718 * @param final_validator_func
719 * See apply_static_and_dynamic().
720 * @param commit
721 * `true` means that this call being successful (returning `true`) shall cause the promotion of
722 * each candidate `Value_set` built-up so far (via this and all preceding successful calls with
723 * `commit == false`) to canonical state (accessed via dynamic_values() or all_dynamic_values());
724 * and all relevant dynamic change listeners are synchronously called for each `Value_set` for which
725 * the cumulative candidate differs from the canonical state.
726 * `false` means that this call being successful shall merely create-and-set (if first such call)
727 * or incrementally update (if 2nd, 3rd, ... such call) each candidate `Value_set`; no dynamic change
728 * listeners are invoked.
729 * @return `true` if and only if successfully parsed config source(s) and validated all settings including
730 * `final_validator_func() != S_FAIL` for *all* (dynamic) config sets; and defaults were also all
731 * individually valid, in the case of initial apply_dynamic(). However, if `true` but `commit == false`,
732 * then the canonical values (accessed via dynamic_values() or all_dynamic_values()) have not been updated.
733 */
734 template<typename... Value_set>
735 bool apply_dynamic(const fs::path& dynamic_cfg_path,
736 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
737 bool commit = true);
738
739 /**
740 * Identical to apply_dynamic() overload without #allow_invalid_defaults_tag_t tag; except that -- applicably only to
741 * the initial apply_dynamic() without a preceding apply_static_and_dynamic() -- skips the stringent
742 * check on individual defaults' validity.
743 *
744 * @see #allow_invalid_defaults_tag_t doc header and/or return-value doc just below.
745 *
746 * @tparam Value_set
747 * See other apply_dynamic().
748 * @param dynamic_cfg_path
749 * See other apply_dynamic().
750 * @param final_validator_func
751 * See other apply_dynamic().
752 * @param commit
753 * See other apply_dynamic().
754 * @return See other apply_dynamic(). However -- assuming apply_static_and_dynamic() was not used, and
755 * this is the initial apply_dynamic() -- the other apply_dynamic() will return `false` if a default is
756 * invalid, even if file `dynamic_cfg_path` explicitly sets it to a valid value. This tagged overload will
757 * not and let parsing continue. If `apply_static_and_dynamic(commit = true) == true` was used, or
758 * if `apply_dynamic(commit = true) == true` has been called before, then the overloads behave
759 * identically: defaults are not checked; it must occur just before the initial dynamic load or never.
760 */
761 template<typename... Value_set>
763 const fs::path& dynamic_cfg_path,
764 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
765 bool commit = true);
766
767 /**
768 * Cancel a not-yet-canonicalized (incomplete) multi-source update, if one is in progress. If one is not
769 * in-progress, INFO-log but otherwise no-op.
770 *
771 * This method only has effect following apply_static(), apply_static_and_dynamic(), or apply_dynamic() that
772 * - returned `true`; and
773 * - had arg `commit == false`.
774 *
775 * That is, if there are pending *candidate* `Value_set`s that have not yet been upgraded to canonical status
776 * via a `commit == true` `apply_*()` call, this call discards them, making it as-if no such call(s) were
777 * made in the first place.
778 *
779 * Informally we do not expect this to be commonly used; typically `apply_*()` will automatically do this
780 * upon encountering an error (in individual option validation or due to Final_validator_outcome::S_FAIL).
781 * However if there is some outside reason to abort an ongoing, so-far-successful multi-source update
782 * this method will similarly do it.
783 */
785
786 /**
787 * Emit a pointer to each permanently set static config value set; the same pointers are emitted throughout
788 * for each of the #S_N_S_VALUE_SETS static config slots. Tip: It should be sufficient to pass around only `const`
789 * refs (from the pointers obtained here) all around the app -- no `Value_set` copying should be needed.
790 *
791 * @tparam Value_set
792 * These must be `S_d_value_set` template param pack args 0, 2, ..., numbering
793 * #S_N_S_VALUE_SETS in order. The compiler should be able to deduce them automatically from
794 * each `value_set_or_null` type; though when passing in null it may be then necessary to cast `nullptr`
795 * (or `0`) to the appropriate pointer type.
796 * @param value_set_or_null
797 * For each element in the param pack:
798 * `*value_set_or_null` is set to point to the immutable static config set in that slot;
799 * or that slot is ignored if `value_set_or_null` is null.
800 */
801 template<typename... Value_set>
802 void all_static_values(const Value_set**... value_set_or_null) const;
803
804 /**
805 * Similar to all_static_values(), but if called from within a validator function passed to apply_static() or
806 * apply_static_and_dynamic(), then for any static value set for which values have been parsed and validated (but not
807 * yet applied) so far, a pointer to the parsed values *candidate* will be emitted instead. If called from elsewhere,
808 * the behavior is equivalent to all_static_values(). A values candidate consists of what has been parsed and
809 * validated (and not skipped via Final_validator_outcome::S_SKIP) for the value set, but has not yet been applied
810 * such that it would be available through all_static_values().
811 *
812 * This could be useful to provide static values to a final validator function for another value set which depends on
813 * them. During the execution of apply_static() or apply_static_and_dynamic(), the validator function for each value
814 * set will be executed before any are canonicalized. This method can be used by a validator function to obtain the
815 * candidate values which have been parsed and validated (but have not yet been canonicalized) for a preceding static
816 * value set.
817 *
818 * @see all_static_values().
819 *
820 * @tparam Value_set
821 * See all_static_values().
822 * @param value_set_or_null
823 * See all_static_values().
824 */
825 template<typename... Value_set>
826 void all_static_values_candidates(const Value_set**... value_set_or_null) const;
827
828 /**
829 * Similar to all_static_values(), but obtains the static config in *one* specified slot as opposed to all of them.
830 *
831 * @tparam Value_set
832 * This must be `S_d_value_set` template param pack args in position `2 * s_value_set_idx`
833 * (so one of [0, 2, ..., `(2 * S_N_S_VALUE_SETS) - 2`]).
834 * You will need to explicitly specify this `tparam`. E.g.:
835 * `const auto cfg_ptr = cfg_mgr.static_values<S_cfg2>(1)`.
836 * @param s_value_set_idx
837 * The static config slot index; so one of [0, 1, ..., #S_N_S_VALUE_SETS).
838 * @return The immutable, permanently set static config value set in the `s_value_set_idx` slot.
839 */
840 template<typename Value_set>
841 const Value_set& static_values(size_t s_value_set_idx) const;
842
843 /**
844 * Similar to static_values(), but if called from within a validator function passed to apply_static() or
845 * apply_static_and_dynamic(), then the parsed values *candidate* will be returned, instead, if values have been
846 * parsed and validated for the static value set but have not yet been applied. Otherwise, the behavior is equivalent
847 * to static_values().
848 *
849 * @see all_static_values_candidates().
850 *
851 * @tparam Value_set
852 * See static_values().
853 * @param s_value_set_idx
854 * See static_values().
855 * @return See above and static_values().
856 */
857 template<typename Value_set>
858 const Value_set& static_values_candidate(size_t s_value_set_idx) const;
859
860 /**
861 * Obtain ref-counted pointers to each currently-canonical set of dynamic config; each pointed-at `struct` is set
862 * permanently; while another call may return a different pointer if config is changed dynamically in the meantime
863 * (for that slot). For each slot: If you require a consistent set of dynamic config over some period of time or over
864 * some code path, save a copy of the returned ref-counted pointer to the `Value_set` and keep accessing values in
865 * that immutable structure through that ref-counted pointer.
866 *
867 * After the initial apply_dynamic(): It is safe to call all_dynamic_values() concurrently with any number of itself
868 * or of dynamic_values() and/or a call to `apply_dynamic(commit = *)`.
869 *
870 * @note Have each `Value_set` derive from util::Shared_ptr_alias_holder, so that it is endowed with
871 * `Ptr` and `Const_ptr` ref-counted pointer type aliases, for your convenience and as required by
872 * Config_manager and Option_set.
873 *
874 * ### Performance ###
875 * dynamic_values() performance is no worse than: lock mutex,
876 * copy #S_N_D_VALUE_SETS `shared_ptr`s, unlock mutex. See also Performance section of
877 * apply_dynamic() doc header.
878 *
879 * @tparam Value_set
880 * These must be `S_d_value_set` template param pack args 1, 3, ..., numbering
881 * #S_N_D_VALUE_SETS in order. Likely you will need to explicitly specify them, as the compiler will
882 * probably not deduce them. E.g.:
883 * `cfg_mgr.all_dynamic_values<D_cfg1, D_cfg2, Null_value_set>(&d1, &d2, 0)`.
884 * @param value_set_or_null
885 * For each element in the param pack:
886 * `*value_set_or_null` is set to point to the immutable dynamic config set currently canonical in that slot;
887 * or that slot is ignored if `value_set_or_null` is null.
888 * Remember: `**value_set_or_null` is immutable; but another call may yield a different
889 * `*value_set_or_null`.
890 */
891 template<typename... Value_set>
892 void all_dynamic_values(typename Value_set::Const_ptr*... value_set_or_null) const;
893
894 /**
895 * Similar to all_dynamic_values() but obtains the dynamic config in *one* specified slot as opposed to all of them.
896 *
897 * @tparam Value_set
898 * This must be `S_d_value_set` template param pack args in position `1 + 2 * d_value_set_idx`
899 * (so one of [1, 3, ..., `(2 * S_N_D_VALUE_SETS) - 1`]).
900 * You will need to explicitly specify this `tparam`. E.g.:
901 * `const auto cfg_ptr = cfg_mgr.dynamic_values<D_cfg2>(1)`.
902 * @param d_value_set_idx
903 * The dynamic config slot index; so one of [0, 1, ..., #S_N_D_VALUE_SETS).
904 * @return Ref-counted pointer to the immutable dynamic config set currently canonical in that slot.
905 * Remember: if `p` returned, then `*p` is immutable; but another dynamic_values() call may return
906 * a different `p2` not equal to `p`.
907 */
908 template<typename Value_set>
909 typename Value_set::Const_ptr dynamic_values(size_t d_value_set_idx) const;
910
911 /**
912 * Saves the given callback; next time `apply_dynamic(commit = true)` or
913 * `apply_static_and_dynamic(commit = true)` detects at least one changed (or initially set) option value
914 * in the specified slot, it will execute this and any other previously registered such callbacks
915 * synchronously. The callbacks will be called after the pointers to be returned by all_dynamic_values() have all
916 * been updated.
917 *
918 * This is not thread-safe against concurrent calls to itself; nor against concurrent
919 * `apply_dynamic(commit = true)` (against `apply_dynamic(commit = false)` is okay),
920 * `apply_static_and_dynamic(commit = true)` (against `apply_static_and_dynamic(commit = false)` is okay), or
921 * unregister_dynamic_change_listener().
922 *
923 * @note The callback may optionally be unregistered by using unregister_dynamic_change_listener(). This *should* be
924 * done before anything that the callback accesses is invalidated. If there is a chance that `apply*_dynamic()`
925 * might be called later, then the callback *must* be unregistered before anything that it accesses is
926 * invalidated, otherwise there could be undefined behavior when the callback accesses something which is
927 * invalid.
928 *
929 * @tparam Value_set
930 * See dynamic_values().
931 * @param d_value_set_idx
932 * See dynamic_values().
933 * @param on_dynamic_change_func_moved
934 * Function to call synchronously from the next `apply*_dynamic()` that detects a change.
935 * @return A handle which can be used to unregister the callback.
936 */
937 template<typename Value_set>
938 On_dynamic_change_func_handle register_dynamic_change_listener(size_t d_value_set_idx,
939 On_dynamic_change_func&& on_dynamic_change_func_moved);
940
941 /**
942 * Remove a previously registered dynamic change callback. See register_dynamic_change_listener().
943 *
944 * This is not thread-safe against concurrent calls to itself; nor against concurrent
945 * `apply_dynamic(commit = true)` (against `apply_dynamic(commit = false)` is okay),
946 * `apply_static_and_dynamic(commit = true)` (against `apply_static_and_dynamic(commit = false)` is okay), or
947 * register_dynamic_change_listener().
948 *
949 * @param handle
950 * The handle which was returned by register_dynamic_change_listener() when the callback was registered.
951 */
952 void unregister_dynamic_change_listener(const On_dynamic_change_func_handle& handle);
953
954 /**
955 * Prints a human-targeted long-form summary of our contents, doubling as a usage message and a dump of current
956 * values where applicable. This is not thread-safe against several non-`const` methods.
957 *
958 * @param os
959 * Stream to which to serialize.
960 */
961 void state_to_ostream(std::ostream& os) const;
962
963 /**
964 * Logs what state_to_ostream() would print. This is not thread-safe against several non-`const` methods.
965 *
966 * @param sev
967 * Severity to use for the log message(s).
968 */
970
971 /**
972 * Prints a human-targeted long-form usage message that includes all options with their descriptions and defaults.
973 * This is thread-safe against all concurrent methods on `*this` and can be invoked anytime after ctor.
974 *
975 * @param os
976 * Stream to which to serialize.
977 */
978 void help_to_ostream(std::ostream& os) const;
979
980 /**
981 * Logs what help_to_ostream() would print.
982 *
983 * @param sev
984 * Severity to use for the log message(s).
985 */
987
988 // Data.
989
990 /// See `nickname` ctor arg.
991 const std::string m_nickname;
992
993private:
994 // Types.
995
996 /// Short-hand for `shared_ptr`-to-`void` type used to store variable-type values in internal containers.
997 using Void_ptr = boost::shared_ptr<void>;
998
999 /**
1000 * Useful at least in the context of multi-source (`commit == false`) `apply_*()` methods, this distinguishes
1001 * distinct possible public `apply_*()` methods.
1002 */
1003 enum class Update_type
1004 {
1005 /// Indicates no `apply_*()` operation.
1006 S_NONE,
1007 /// Indicates apply_static().
1008 S_STATIC,
1009 /// Indicates apply_static_and_dynamic().
1010 S_STATIC_AND_DYNAMIC,
1011 /// Indicates apply_dynamic().
1012 S_DYNAMIC
1013 }; // enum class Update_type
1014
1015 // Methods.
1016
1017 /**
1018 * Helper that obtains the Option_set in the slot `m_s_d_opt_sets[value_set_idx]`, which
1019 * stores an Option_set<Value_set>.
1020 *
1021 * @tparam Value_set
1022 * `S_d_value_set` in slot `value_set_idx`.
1023 * @param value_set_idx
1024 * One of [0, 1, ..., #S_N_VALUE_SETS).
1025 * @return Pointer to the Option_set.
1026 */
1027 template<typename Value_set>
1028 Option_set<Value_set>* opt_set(size_t value_set_idx);
1029
1030 /**
1031 * Helper that obtains the baseline dynamic `Value_set` in the slot `m_d_baseline_value_sets[value_set_idx]`, which
1032 * stores a `Value_set`.
1033 *
1034 * @tparam Value_set
1035 * `S_d_value_set` in dynamic slot `d_value_set_idx`.
1036 * @param d_value_set_idx
1037 * One of [0, 1, ..., #S_N_D_VALUE_SETS).
1038 * @return Pointer to the `Value_set`.
1039 */
1040 template<typename Value_set>
1041 Value_set* d_baseline_value_set(size_t d_value_set_idx);
1042
1043 /**
1044 * `const` overload of the other opt_set() helper.
1045 * @tparam Value_set
1046 * See other opt_set().
1047 * @param value_set_idx
1048 * See other opt_set().
1049 * @return See other opt_set().
1050 */
1051 template<typename Value_set>
1052 const Option_set<Value_set>* opt_set(size_t value_set_idx) const;
1053
1054 /**
1055 * Helper that executes `opt_set->canonicalize_candidate()` or
1056 * `opt_set->reject_candidate()`. Used in meta-programming. Apply when parsing `*opt_set`,
1057 * assuming `commit == true`.
1058 *
1059 * @tparam Value_set
1060 * See opt_set().
1061 * @param opt_set
1062 * An opt_set() result.
1063 * @param canonicalize_else_reject
1064 * Specifies whether to... well, you know.
1065 * @param changed_or_null
1066 * If not null and canonicalizing (not rejecting), `*changed_or_null` is set to whether
1067 * the `canonicalize_candidate()` detected at least one option's value changed from the previous canonical
1068 * state.
1069 */
1070 template<typename Value_set>
1072 bool canonicalize_else_reject, bool* changed_or_null);
1073
1074 /**
1075 * Implements all apply_static() overloads.
1076 *
1077 * @tparam Value_set
1078 * See apply_static().
1079 * @param allow_invalid_defaults
1080 * `true` if and only if #allow_invalid_defaults_tag_t used.
1081 * @param static_cfg_path
1082 * See apply_static().
1083 * @param final_validator_func
1084 * See apply_static().
1085 * @param commit
1086 * See apply_static().
1087 * @return See apply_static().
1088 */
1089 template<typename... Value_set>
1090 bool apply_static_impl(bool allow_invalid_defaults,
1091 const fs::path& static_cfg_path,
1092 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
1093 bool commit);
1094
1095 /**
1096 * Implements all apply_dynamic() overloads.
1097 *
1098 * @tparam Value_set
1099 * See apply_dynamic().
1100 * @param allow_invalid_defaults
1101 * `true` if and only if #allow_invalid_defaults_tag_t used.
1102 * @param dynamic_cfg_path
1103 * See apply_dynamic().
1104 * @param final_validator_func
1105 * See apply_dynamic().
1106 * @param commit
1107 * See apply_static().
1108 * @return See apply_dynamic().
1109 */
1110 template<typename... Value_set>
1111 bool apply_dynamic_impl(bool allow_invalid_defaults,
1112 const fs::path& dynamic_cfg_path,
1113 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
1114 bool commit);
1115
1116 /**
1117 * Implements all apply_static_and_dynamic() overloads.
1118 *
1119 * @param allow_invalid_defaults
1120 * `true` if and only if #allow_invalid_defaults_tag_t used.
1121 * @param cfg_path
1122 * See apply_static_and_dynamic().
1123 * @param final_validator_func
1124 * See apply_static_and_dynamic().
1125 * @param commit
1126 * See apply_static_and_dynamic().
1127 * @return See apply_static_and_dynamic().
1128 */
1129 bool apply_static_and_dynamic_impl(bool allow_invalid_defaults,
1130 const fs::path& cfg_path,
1131 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
1132 bool commit);
1133
1134 /**
1135 * Work-horse helper that parses either *all* static value sets *or* *all* dynamic value sets from the specified
1136 * file into #m_s_d_opt_sets and returns `true` if and only if all have succeeded. (It stops on first failure.)
1137 * The canonicalize/reject step is not performed: only parsing and (if that worked) `final_validator_func()`.
1138 * Recall that `final_validator_func() == S_SKIP`, even though it will cause us to not have changed that `Value_set`'s
1139 * Option_set::values_candidate(), is still considered success.
1140 *
1141 * @tparam Value_set
1142 * See apply_static() or apply_dynamic() depending on `dyn_else_st`.
1143 * @param dyn_else_st
1144 * Basically whether apply_static() or apply_dynamic() was called.
1145 * @param cfg_path
1146 * See apply_static() or apply_dynamic() depending on `dyn_else_st`.
1147 * @param all_opt_names_or_empty
1148 * Empty if *any* option names may be present in file (such as to support dynamic config compatibility);
1149 * otherwise must contain any option names that are allowed in this file (such as for apply_static()).
1150 * @param final_validator_func
1151 * See apply_static() or apply_dynamic() depending on `dyn_else_st`.
1152 * @return See apply_static() or apply_dynamic() depending on `dyn_else_st`.
1153 */
1154 template<typename... Value_set>
1156 (bool dyn_else_st,
1157 const fs::path& cfg_path, const boost::unordered_set<std::string>& all_opt_names_or_empty,
1158 const typename Final_validator_func<Value_set>::Type&... final_validator_func);
1159
1160 /**
1161 * Work-horse helper that parses into one given Option_set in #m_s_d_opt_sets (from opt_set()) from the specified
1162 * file and returns `true` if and only if successful. The canonicalize/reject step is not performed: only
1163 * parsing and (if that worked) `final_validator_func()`.
1164 * Recall that `final_validator_func() == S_SKIP`, even though it will cause us to not have changed that `Value_set`'s
1165 * Option_set::values_candidate(), is still considered success.
1166 *
1167 * If `opt_set->null() == true`, this completely no-ops and returns `true`.
1168 *
1169 * ### Effect of `skip_parsing` ###
1170 * It is a pointer. If null (or if `opt_set->null() == true`), then the behavior is as written.
1171 *
1172 * If not null, then it has the following added effects -- used as of this writing by apply_dynamic():
1173 * - If and only if, at entry to method, `*skip_parsing == true`, then:
1174 * - The contents of the file shall be ignored, and `final_validator_func()` shall not be called;
1175 * instead we act *as-if* the contents were individually valid, but `final_validator_func()` yielded `S_SKIP`.
1176 * - On return from method: `*skip_parsing` shall be set to `true` if and only if:
1177 * - `*skip_parsing = true` at entry to method; or else if
1178 * - values in file were individually valid, but `final_validator_func()` yielded `S_SKIP`.
1179 *
1180 * More in English: To get the desired SKIP behavior, where a SKIPped `Value_set` also skips all subsequent
1181 * (but not preceding) ones, start with `bool skip_parsing = false`, then pass `&skip_parsing` to each apply_impl().
1182 * (The `skip_parsing == nullptr` mode is still provided, in case it's useful for something later; as of this
1183 * writing all the public `apply_*()` APIs have `skip_parsing != nullptr`, but it could conceivably change.)
1184 *
1185 * @tparam Value_set
1186 * See opt_set().
1187 * @param opt_set
1188 * An opt_set() result.
1189 * @param baseline_value_set_or_null
1190 * If null then ignored; else -- just before attempting to parse and apply values from `cfg_path` -- we
1191 * will set `*opt_set` to contain a copy of `Value_set *baseline_value_set_or_null`. This is to ensure
1192 * a consistent state after each dynamic config update as opposed to working incrementally.
1193 * @param cfg_path
1194 * See apply_static_or_dynamic_impl().
1195 * @param all_opt_names_or_empty
1196 * See apply_static_or_dynamic_impl().
1197 * Technically this need not include the ones actually parsed by `*opt_set`; but including them is harmless
1198 * (and may be helpful to the caller for simplicity).
1199 * @param final_validator_func
1200 * See apply_static() or apply_dynamic() or apply_static_and_dynamic().
1201 * @param skip_parsing
1202 * See above. Recall it can be null.
1203 * @return `true` on success; `false` on failure.
1204 */
1205 template<typename Value_set>
1206 bool apply_impl(Option_set<Value_set>* opt_set, const Value_set* baseline_value_set_or_null, const fs::path& cfg_path,
1207 const boost::unordered_set<std::string>& all_opt_names_or_empty,
1208 const typename Final_validator_func<Value_set>::Type& final_validator_func,
1209 bool* skip_parsing);
1210
1211 /**
1212 * Helper for the top of `apply_*()` that guards against a call to `apply_Y()` following
1213 * `apply_X(commit == false) == true` without a reject_candidates() between them. If this is detected, it
1214 * effectively "inserts" the "missing" reject_candidates() call -- plus an INFO message.
1215 *
1216 * Post-condition: #m_multi_src_update_in_progress equals Update_type::S_NONE.
1217 *
1218 * @param this_update_type
1219 * The type (not NONE, or behavior undefined -- assert may trip) of `apply_*()` calling us.
1220 */
1222
1223 /**
1224 * Little helper that, having assumed #m_d_value_sets_mutex is locked, makes a newly allocated copy of the canonical
1225 * dynamic config at the given slot and saves a (new) ref-counted pointer to it in the proper #m_d_value_sets slot.
1226 *
1227 * @tparam Value_set
1228 * See opt_set().
1229 * @param opt_set
1230 * An opt_set() result (dynamic slot).
1231 * @param d_value_set_idx
1232 * One of [0, 1, ..., #S_N_D_VALUE_SETS).
1233 */
1234 template<typename Value_set>
1236
1237 /**
1238 * Invokes the registered listeners for the given dynamic config slot (synchronously).
1239 *
1240 * @param d_value_set_idx
1241 * One of [0,1, ... #S_N_D_VALUE_SETS).
1242 * @param init
1243 * For logging (as of this writing): whether this is due to the initial parsing of this dynamic config slot
1244 * or a subsequent change.
1245 */
1246 void invoke_dynamic_change_listeners(size_t d_value_set_idx, bool init) const;
1247
1248 /**
1249 * Helper of state_to_ostream() for #m_s_d_opt_sets slot `value_set_idx`.
1250 *
1251 * @param value_set_idx
1252 * One of [0, 1, ..., #S_N_VALUE_SETS).
1253 * @param os
1254 * See state_to_ostream().
1255 */
1256 template<typename Value_set>
1257 void state_to_ostream_impl(size_t value_set_idx, std::ostream& os) const;
1258
1259 /**
1260 * Helper of help_to_ostream() for #m_s_d_opt_sets slot `value_set_idx`.
1261 *
1262 * @param value_set_idx
1263 * One of [0, 1, ..., #S_N_VALUE_SETS).
1264 * @param os
1265 * See help_to_ostream().
1266 */
1267 template<typename Value_set>
1268 void help_to_ostream_impl(size_t value_set_idx, std::ostream& os) const;
1269
1270 // Data.
1271
1272 /**
1273 * The static and dynamic value sets, in the same order as the #S_N_VALUE_SETS
1274 * `S_d_value_set` template args, the specific type for each slot being: `Option_set<S_d_value_set>`.
1275 * This is the main data store managed by Config_manager. Each static `S_d_value_set` (the even slots) is the
1276 * entirety of data having to do with that piece of static config. Each dynamic `S_d_value_set` (the odd slots) is
1277 * the *canonical* dynamic config; and a pointer to a *copy* thereof is also maintained in #m_d_value_sets.
1278 *
1279 * The slots, in order, are hence:
1280 * - Index [0]: static slot 0,
1281 * - Index [1]: dynamic slot 0,
1282 * - Index [2]: static slot 1,
1283 * - Index [3]: dynamic slot 1,
1284 * - ...
1285 * - Index [`.size() - 2`]: static slot `S_N_S_VALUE_SETS - 1`.
1286 * - Index [`.size() - 1`]: dynamic slot `S_N_D_VALUE_SETS - 1`.
1287 *
1288 * The actual type stored is `shared_ptr<void>`, with each slot's held pointer actually being an
1289 * `Option_set<S_d_value_set>*`.
1290 * opt_set() obtains the actual `Option_set<>` at a given slot, performing the required casting.
1291 *
1292 * ### Rationale ###
1293 * Why use an array of `shared_ptr<void>`, which requires a `static_cast` anytime we need to actually
1294 * access a config set? The more compile-time/meta-programm-y approach I (ygoldfel) could conceive of was to use
1295 * `tuple<S_d_value_set...>`. That would be quite elegant and lightning-fast (though compilation might be very slow).
1296 * However then, if I understand correctly, that would prevent any kind of runtime iteration through them.
1297 * This might be absolutely fine, if every slot were treated identically, but in the current setup it's
1298 * static, dynamic, static, dynamic, .... Therefore, by moving some processing to runtime instead of compile-time
1299 * we gain flexibility. (Do note my disclaimer in Implementation section in class doc header -- indicating this is
1300 * my first foray into advanced meta-programming like this. So perhaps I lack imagination/experience.)
1301 *
1302 * So then `shared_ptr<void>` actually stores an `S_d_value_set*` -- `S_d_value_set` being a different type for
1303 * each slot in the array. This uses the type erasure pattern of standard C++ smart pointers, wherein because
1304 * `static_cast<void*>(T*)` is allowed for any type `T`, `shared_ptr<void>` deleter will properly `delete` the `T*`,
1305 * as long as the `shared_ptr` ctor is passed a `T*` raw pointer. Do note this is type-safe only if our code
1306 * knows to cast to the proper `T*` when the pointer is accessed.
1307 *
1308 * Why `shared_ptr` -- not `unique_ptr` (which is nominally faster in that there's no ref-counting)? Answer:
1309 * `unique_ptr` is apparently deliberately simple and lacks aliasing and type-erasure constructors.
1310 * `unique_ptr<T>` can only delete a `T` with the default deleter; and `T` being `void` therefore won't compile.
1311 * It is probably possible to hack it with a custom deleter -- but this seemed like overkill, as these handles
1312 * are never used except inside an `array`, so reference counting shouldn't even happen and thus cost any perf
1313 * cycles outside of `*this` ctor and dtor.
1314 *
1315 * An alternative, which is somewhat more type-safe in that it would have resulted in an RTTI exception if the
1316 * wrong type-cast were used on the stored value, was `any`. However `any` is slower, involving `virtual` lookups
1317 * (at least in a naive implementation of `any`).
1318 */
1319 boost::array<Void_ptr, S_N_VALUE_SETS> m_s_d_opt_sets;
1320
1321 /**
1322 * The baseline dynamic value sets, in the same order as #S_N_D_VALUE_SETS *dynamic*
1323 * `S_d_value_set` template args, the specific type for each slot being `S_d_value_set`.
1324 *
1325 * The actual type stored is `shared_ptr<void>`, with each slot's held pointer actually being `S_d_value_set*`.
1326 * The same type erasure technique used in #m_s_d_opt_sets is used here.
1327 * d_baseline_value_set() obtains the actual `S_d_value_set` at a given slot, performing the required casting.
1328 *
1329 * A null pointer is stored if the corresponding Option_set in #m_s_d_opt_sets is `null()` (a placeholder with 0
1330 * settings).
1331 *
1332 * ### Rationale / explanation ###
1333 * Suppose a dynamic `Value_set` is to be parsed from file F potentially repeatedly, as dynamic updates come in.
1334 * Then its Option_set from `m_s_d_opt_sets[]` would `parse_config_file(F)` each time. However, if that is all
1335 * we did, then the updates would stack on top of each other incrementally: if one looks at F's contents at a given
1336 * time, one cannot tell what the `Value_set` in memory would contain upon parsing it; it would depend on any
1337 * preceding updates. That's bad: the resulting memory `Value_set` must be consistent, regardless of what
1338 * F contained in preceding updates. Therefore, a certain *baseline* state for that `Value_set` must be loaded
1339 * into the Option_set just before the Option_set::parse_config_file() call in each update.
1340 *
1341 * This stores each dynamic slot's baseline `Value_set` state to load as just described.
1342 *
1343 * After construction this payload is just the default-cted `Value_set{}`. If the user chooses to execute
1344 * a one-time apply_static_and_dynamic(), then that payload is replaced by the state after having parsed that
1345 * baseline state. Note, for context, that apply_static_and_dynamic() would be presumably loading *not*
1346 * from file F (which can change repeatedly, as dynamic updates come in) but some other file B, typically storing
1347 * both static value sets' contents as well as the baseline dynamic value sets'.
1348 */
1349 boost::array<Void_ptr, S_N_D_VALUE_SETS> m_d_baseline_value_sets;
1350
1351 /**
1352 * The dynamic config ref-counted handles returned by all_dynamic_values(). Each one is a ref-counted pointer
1353 * to an immutable *copy* of the canonical `S_d_value_set` in that *dynamic* slot of #m_s_d_opt_sets
1354 * (namely `m_s_d_opt_sets[2 * d_idx + 1]`, where `d_idx` is in [0, 1, ..., #S_N_D_VALUE_SETS)).
1355 *
1356 * The actual type stored is `shared_ptr<void>`, with each slot's held pointer actually being
1357 * `S_d_value_set::Const_ptr*`. The same type erasure technique used in #m_s_d_opt_sets is used here.
1358 *
1359 * Protected by #m_d_value_sets_mutex.
1360 *
1361 * apply_dynamic() and apply_static_and_dynamic() set these; all_dynamic_values() and dynamic_values() get them.
1362 *
1363 * ### Rationale ###
1364 * Why is this necessary? Why not just expose a pointer to immutable `S_d_value_set` directly inside
1365 * `m_s_d_opt_sets[d_idx]` as we do (via static_values() and all_static_values()) for the static config? Answer:
1366 * Because with dynamic config it is important that the user be able to retain (if even for a short time, perhaps to
1367 * complete some operation -- *during* which `*this` might process a dynamic update via apply_dynamic()) an immutable
1368 * `S_d_value_set`. Since by definition that's not possible with dynamic config updates, we must create a copy. At
1369 * that point it becomes natural to wrap it in a `shared_ptr`, so that only *one* copy is necessary in the entire
1370 * application -- and it'll disappear once (1) the canonical config has been updated, replacing `m_d_value_sets[]`,
1371 * and (2) all user code has dropped the remaining refs to it.
1372 *
1373 * The ref-counted-pointer-to-dynamic-config is a common pattern. The only thing we add that might not be obvious
1374 * is having the canonical copy be separate from the one we expose via the pointer publicly. The latter is
1375 * the natural consequence of the fact that the `Value_set` managed by `Option_set<Value_set>` lives inside
1376 * the `Option_set` and is not wrapped by any `shared_ptr`. However Option_set::mutable_values_copy() does provide
1377 * easy access to a `shared_ptr`-wrapped copy thereof... so we use it. The perf cost is that of a value-set
1378 * copy at apply_dynamic() time which is negligible in the grand scheme of things.
1379 */
1380 boost::array<Void_ptr, S_N_D_VALUE_SETS> m_d_value_sets;
1381
1382 /// Mutex protecting #m_d_value_sets.
1384
1385 /**
1386 * List of callbacks to execute after #m_d_value_sets members (the pointers) are next assigned: one per
1387 * each of the #S_N_D_VALUE_SETS dynamic config slots. Note we do *not*
1388 * assign a given slot's #m_d_value_sets pointer, unless at least one option has changed within the associated
1389 * canonical value set in #m_s_d_opt_sets.
1390 *
1391 * ### Rationale ###
1392 * A `list<>` is used here so that iterators to callbacks can be stored in `On_dynamic_change_func_handle`s without
1393 * the possibility of them being invalidated by insertions to or removals from the list (which would be the case if
1394 * `vector<>` were used).
1395 */
1396 boost::array<std::list<On_dynamic_change_func>, S_N_D_VALUE_SETS> m_on_dynamic_change_funcs;
1397
1398 /// Starts `false`; set to `true` permanently on successful apply_static_and_dynamic() or apply_dynamic().
1400
1401 /**
1402 * In short, truthy if and only if a `commit == false` update is currently in progress,
1403 * meaning there's an uncommitted *candidate* `Value_set` at the moment. More precisely:
1404 * - If the last-invoked `apply_*()` method (1) returned `false`, or (2) returned `true` but with arg
1405 * `commit == true`, or (3) has never been called, or (4) was followed at any point
1406 * by reject_candidates(), then this equals Update_type::S_NONE. I.e., no multi-source update is
1407 * currently in progress. Otherwise:
1408 * - This indicates which `apply_*(commit = true) == true` method (multi-source update type) it was.
1409 * To the extent the exact type is irrelevant, its being not NONE indicates a multi-source update
1410 * is in progress.
1411 *
1412 * Inside an `apply_*()` method, this is updated to its new value after parsing into #m_s_d_opt_sets. Thus
1413 * during the bulk of such a method's processing we can easily determine whether this is step 1 of a
1414 * (potentially multi-source) update -- rather than step 2+ -- as this will equal NONE in the former
1415 * case only.
1416 *
1417 * When this is not-NONE, an `apply_*()` impl shall skip a couple of steps it would otherwise perform:
1418 * - Individually-validating the default `Value_set{}` values: Skip, as the first `apply_*()` in the sequence
1419 * would have already done it. So it's a waste of compute/entropy.
1420 * - `apply_dynamic()` applying #m_d_baseline_value_sets onto to #m_s_d_opt_sets: Skip, as the first `apply_*()` in
1421 * the sequence would have already done it. So doing it again would be not only redundant but also destructive,
1422 * overwriting any incremental changes made in preceding 1+ `apply_*()` calls.
1423 *
1424 * It would have been enough for it to be a `bool` for those tests. It is an `enum` to be able to detect
1425 * calling `apply_X()` after `apply_Y(commit = false) == true` without reject_candidates() in-between.
1426 */
1428}; // class Config_manager
1429
1430/// Opaque handle for managing a dynamic config change callback.
1431template<typename... S_d_value_set>
1433{
1434 /**
1435 * Opaque handle detail.
1436 * @internal
1437 * The dynamic config slot index for the value set which is associated with the callback. This is used as an index
1438 * into `m_on_dynamic_change_funcs` to specify the list of callbacks which contains the callback.
1439 */
1441
1442 /**
1443 * Opaque handle detail.
1444 * @internal
1445 * Iterator to the callback within the associated callback list.
1446 */
1447 std::list<On_dynamic_change_func>::const_iterator m_pos;
1448};
1449
1450// Free functions: in *_fwd.hpp.
1451
1452// However the following refer to inner type(s) and hence must be declared here and not _fwd.hpp.
1453
1454/**
1455 * Returns a value usable as `final_validator_func` arg to Config_manager::apply_static() and others -- for a
1456 * Null_value_set value set.
1457 *
1458 * @return See above.
1459 */
1461
1462/**
1463 * Returns a value usable as `declare_opts_func_moved` Config_manager ctor arg for a Null_value_set value set.
1464 * Naturally it does nothing.
1465 *
1466 * @return See above.
1467 */
1469
1470// Template implementations.
1471
1472template<typename... S_d_value_set>
1474 (log::Logger* logger_ptr, util::String_view nickname,
1475 typename Option_set<S_d_value_set>::Declare_options_func&&... declare_opts_func_moved) :
1476 log::Log_context(logger_ptr, Flow_log_component::S_CFG),
1477 m_nickname(nickname),
1478 m_dynamic_values_set(false), // Becomes `true` when apply*_dynamic() succeeds once.
1479 m_multi_src_update_in_progress(Update_type::S_NONE)
1480{
1482
1483 /* @todo OK; this is really weird; I wanted to make this a static_assert() (and put it near where this constexpr
1484 * is initialized), but it is then triggered with gcc claiming Config_manager<> (with no tparams!) is
1485 * compiled -- bizarrely due to a simple FLOW_LOG_INFO() line a few hundred lines below this. I find this
1486 * inexplicable; almost seems like a bug, but maybe not. Look into it. -ygoldfel */
1487 assert((S_N_VALUE_SETS != 0)
1488 && "Must have at least 2 template args to Config_manager; otherwise what are you configuring?");
1489
1490 // (See class doc header Implementation section for explanation of fold-expression (..., ) trick.)
1491
1492 /* Set each m_s_d_opt_sets[] to store the Option_set<S_d_value_set>, for each S_d_value_set (class tparam-pack).
1493 * Recall that m_s_d_opt_sets[] stores them in order static, dynamic, static, dynamic, ....
1494 *
1495 * Set each m_d_baseline_value_sets[] to store a default-valued S_d_value_set (for dynamic sets only).
1496 * These may get overwritten optionally (because apply_static_and_dynamic() is optional) once, in
1497 * apply_static_and_dynamic(). For explanation what this is for see m_d_baseline_value_sets doc header.
1498 *
1499 * Initialize each m_d_value_sets[] as well. */
1500 bool dyn_else_st = false;
1501 size_t value_set_idx = 0;
1502 size_t d_value_set_idx = 0;
1503 (
1504 ...,
1505 (
1506 // I (ygoldfel) tried make_shared() here, but it was too much for that gcc. The perf impact is negligible anyway.
1507 m_s_d_opt_sets[value_set_idx]
1508 = Void_ptr
1509 {new Option_set<S_d_value_set> // <-- Parameter pack expansion kernel here.
1510 {get_logger(),
1511 ostream_op_string(m_nickname, dyn_else_st ? "/dynamic" : "/static",
1512 value_set_idx / 2), // 0, 0, 1, 1, ....
1513 std::move(declare_opts_func_moved)}}, // (And here.)
1514
1515 /* As noted above, fill a m_d_baseline_value_sets[] but for dynamic (non-null()) sets only.
1516 * Same deal for initializing m_d_value_sets.
1517 * (This is `if (dyn_else_st) { ... }` in expression form.) */
1518 static_cast<void> // Defeats possible unused-value warning.
1519 (dyn_else_st
1520 // * (This is `if (!(...).null()) { ... }` in expression form.)
1521 && (opt_set<S_d_value_set>(value_set_idx)->null() // (And here.)
1522 || (m_d_baseline_value_sets[d_value_set_idx]
1523 = Void_ptr{new S_d_value_set}, // (And here.)
1524 true),
1525 m_d_value_sets[d_value_set_idx]
1526 = Void_ptr{new typename S_d_value_set::Const_ptr}, // (And here.)
1527 ++d_value_set_idx,
1528 true)),
1529
1530 ++value_set_idx,
1531 dyn_else_st = !dyn_else_st
1532 )
1533 );
1534
1535 FLOW_LOG_TRACE("Config_manager [" << *this << "]: Ready; "
1536 "managing [" << S_N_S_VALUE_SETS << "] dynamic+static option set pairs (some may be null/unused).");
1537} // Config_manager::Config_manager()
1538
1539template<typename... S_d_value_set>
1540template<typename Value_set>
1543{
1544 // Fish out the value stuffed into the ptr<void> at the given slot by the ctor.
1545
1546 assert(value_set_idx < S_N_VALUE_SETS);
1547 return static_cast<Option_set<Value_set>*> // Attn: void* -> T* cast; no RTTI to check our type safety.
1548 (m_s_d_opt_sets[value_set_idx].get());
1549}
1550
1551template<typename... S_d_value_set>
1552template<typename Value_set>
1553Value_set*
1555{
1556 // Fish out the value stuffed into the ptr<void> at the given slot by the ctor.
1557
1558 assert(d_value_set_idx < S_N_D_VALUE_SETS);
1559 return static_cast<Value_set*> // Attn: void* -> T* cast; no RTTI to check our type safety.
1560 (m_d_baseline_value_sets[d_value_set_idx].get());
1561}
1562
1563template<typename... S_d_value_set>
1564template<typename Value_set>
1567{
1568 return const_cast<Config_manager<S_d_value_set...>*>(this)->opt_set<Value_set>(value_set_idx);
1569}
1570
1571template<typename... S_d_value_set>
1572template<typename Value_set>
1574 (Option_set<Value_set>* opt_set, bool canonicalize_else_reject, bool* changed_or_null)
1575{
1576 if (opt_set->null())
1577 {
1578 // If null() then *opt_set wasn't even parse*()d (see apply_impl()), so certainly it hasn't changed.
1579 changed_or_null
1580 && (*changed_or_null = false);
1581 }
1582 else
1583 {
1584 canonicalize_else_reject ? opt_set->canonicalize_candidate(changed_or_null)
1585 : opt_set->reject_candidate();
1586 }
1587}
1588
1589template<typename... S_d_value_set>
1590template<typename Value_set>
1591typename Config_manager<S_d_value_set...>::On_dynamic_change_func_handle
1593 (size_t d_value_set_idx, On_dynamic_change_func&& on_dynamic_change_func_moved)
1594{
1595 FLOW_LOG_INFO("Config_manager [" << *this << "]: Adding dynamic-change listener for dynamic value set "
1596 "[" << d_value_set_idx << "].");
1597
1598 assert((d_value_set_idx < S_N_D_VALUE_SETS) && "Invalid dynamic option set index.");
1599 assert((!opt_set<Value_set>((d_value_set_idx * 2) + 1)->null())
1600 && "Do not register dynamic change listener for Null_value_set or otherwise null value set.");
1601
1602 // Not thread-safe (as advertised) against apply*_dynamic() or unregister_dynamic_change_listener().
1603 m_on_dynamic_change_funcs[d_value_set_idx].emplace_back(std::move(on_dynamic_change_func_moved));
1604 const auto& callback_pos = std::prev(m_on_dynamic_change_funcs[d_value_set_idx].end());
1605
1606 FLOW_LOG_INFO("Config_manager [" << *this << "]: Added dynamic-change listener [@" << &(*callback_pos) <<
1607 "] for dynamic value set [" << d_value_set_idx << "].");
1608
1609 return On_dynamic_change_func_handle{ d_value_set_idx, callback_pos };
1610}
1611
1612template<typename... S_d_value_set>
1614{
1615 // Not thread-safe (as advertised) against apply*_dynamic() or register_dynamic_change_listener().
1616
1617 FLOW_LOG_INFO("Config_manager [" << *this << "]: Removed dynamic-change listener [@" << &(*handle.m_pos) <<
1618 "] for dynamic value set [" << handle.m_d_value_set_idx << "].");
1619
1620 m_on_dynamic_change_funcs[handle.m_d_value_set_idx].erase(handle.m_pos);
1621}
1622
1623template<typename... S_d_value_set>
1624template<typename... Value_set>
1626 (const fs::path& static_cfg_path,
1627 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
1628 bool commit)
1629{
1630 return apply_static_impl<Value_set...>(false, static_cfg_path, final_validator_func..., commit);
1631}
1632
1633template<typename... S_d_value_set>
1634template<typename... Value_set>
1637 const fs::path& static_cfg_path,
1638 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
1639 bool commit)
1640{
1641 return apply_static_impl<Value_set...>(true, static_cfg_path, final_validator_func..., commit);
1642}
1643
1644template<typename... S_d_value_set>
1645template<typename... Value_set>
1647 (bool allow_invalid_defaults,
1648 const fs::path& static_cfg_path,
1649 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
1650 bool commit)
1651{
1652 using boost::unordered_set;
1653 using std::string;
1654 using std::declval;
1655 using std::is_same_v;
1656
1657 FLOW_LOG_INFO("Config_manager [" << *this << "]: Request to apply static config file [" << static_cfg_path << "]. "
1658 "Invalid defaults allowed if explicitly set in file? = [" << allow_invalid_defaults << "]. "
1659 "This application (if successful) shall end with canonicalizing values? = [" << commit << "]; "
1660 "multi-source update already in progress (0=none) = [" << int(m_multi_src_update_in_progress) << "].");
1661
1662 reject_candidates_if_update_type_changed(Update_type::S_STATIC);
1663
1664 /* Even if they're all .null(), they must give some validator functions (they'll be ignored and should just
1665 * be assigned null_final_validator_func() a/k/a Final_validator_func<Null_value_set>::null() anyway,
1666 * though we don't enforce it). */
1667 static_assert(sizeof...(Value_set) == S_N_S_VALUE_SETS,
1668 "You must supply N/2 `final_validator_func`s, where N is # of S_d_value_set params. "
1669 "Use null_final_validator_func() for any Null_value_set.");
1670
1671 /* (See class doc header Implementation section for explanation of fold-expression (..., ) trick.)
1672 *
1673 * Note, though, that (... && expr) (of, say, length 4) evaluates to (((expr1 && expr2) && expr3) && expr4);
1674 * which means it'll run through the `expr...i...`s until one evaluates to false; then it stops and evaluates
1675 * no more past that. */
1676
1677 size_t value_set_idx;
1678 bool success = true;
1679
1680 /* Optionally scan the defaults themselves for individual-option-validator validity if so requested.
1681 * However no need to repeat this, if a multi-source update was already in progress. */
1682 if ((!allow_invalid_defaults) && (m_multi_src_update_in_progress == Update_type::S_NONE))
1683 {
1684 value_set_idx = 0;
1685 [[maybe_unused]] const auto dummy = // Defeats unused-value warning due to trailing `success`.
1686 (
1687 ...
1688 &&
1689 (
1690 opt_set<Value_set>(value_set_idx) // Param pack expansion kernel here.
1691 ->validate_values(&success), // Set `success`...
1692 value_set_idx += 2, // (Skip dynamic ones.)
1693 success // ...and if it's false, the subsequent option sets shall be skipped.
1694 )
1695 );
1696
1697 if (!success) // It would have logged the exact problem, but we still want to clearly say what happened, high-level:
1698 {
1699 FLOW_LOG_WARNING("Config_manager [" << *this << "]: "
1700 "Request to apply static config file [" << static_cfg_path << "]: "
1701 "Will not parse file, because stringent check "
1702 "of defaults detected at least 1 individually-invalid default value. Either correct "
1703 "the default or use apply_static(allow_invalid_defaults_tag_t) overload.");
1704 }
1705 } // if (!allow_invalid_defaults)
1706
1707 // First collect all valid static option names as required by apply_static_or_dynamic_impl().
1708 unordered_set<string> all_opt_names; // The result.
1709 unordered_set<string> const * this_opt_names; // Used for each static slot.
1710 // Ensure Option_set<>::option_names() returns ref-to-const, so this_opt_names can safely point to it.
1711 static_assert(is_same_v<decltype(declval<Option_set<Null_value_set>>().option_names()),
1712 decltype(*this_opt_names)>,
1713 "Option_set<>::option_names() must return ref-to-const. Bug?");
1714 value_set_idx = 0;
1715 if (success) // Skip all this if failed above.
1716 {
1717 (
1718 ...,
1719 (
1720 this_opt_names = &(opt_set<Value_set> // Param pack expansion kernel here.
1721 (value_set_idx)->option_names()),
1722 all_opt_names.insert(this_opt_names->begin(), this_opt_names->end()),
1723 value_set_idx += 2 // Skip dynamic ones.
1724 )
1725 );
1726
1727 // Next do the actual parsing of each static Option_set. Stop at first failure. Return `true` iff total success.
1728 success = apply_static_or_dynamic_impl<Value_set...>
1729 (false, // false => static.
1730 static_cfg_path, all_opt_names, final_validator_func...);
1731 } // if (success) (but it may have become false inside)
1732
1733 if ((!commit) && success)
1734 {
1735 m_multi_src_update_in_progress = Update_type::S_STATIC; // (Was either NONE or already this.)
1736 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update has successfully begun or continued. "
1737 "Expecting more sources before we can canonicalize candidate(s).");
1738 return true;
1739 }
1740 // else if (commit || (!success)):
1741
1742 /* !success => reject, regardless of commit (a failure aborts a multi-source update too).
1743 * commit => accept or reject depending on `success`.
1744 *
1745 * So finally either canonicalize or reject each parse attempt depending on overall `success` (static only).
1746 * For details on what that means see Option_set<> docs. Basically it just finalizes the parsing by updating
1747 * the canonically stored Value_set inside the Option_set<Value_set>. Until then it's stored to the side as the
1748 * *candidate*. */
1749 value_set_idx = 0;
1750 (
1751 ...,
1752 (
1753 option_set_canonicalize_or_reject(opt_set<Value_set>(value_set_idx), // Param pack expansion kernel here.
1754 success, nullptr),
1755 value_set_idx += 2 // Skip dynamic ones.
1756 )
1757 );
1758
1759 if (m_multi_src_update_in_progress != Update_type::S_NONE)
1760 {
1761 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update is now finished.");
1762 m_multi_src_update_in_progress = Update_type::S_NONE;
1763 }
1764 // else { It was NONE and remains so, either due to failure or being a vanilla (single-source) update or both. }
1765
1766 if (!success)
1767 {
1768 return false;
1769 }
1770 // else if (success):
1771 assert(commit && "Maintenance bug? We should have returned above if `!commit` but success==true.");
1772
1773 FLOW_LOG_INFO("Config_manager [" << *this << "]: State that was just made canonical follows.");
1774 log_state(); // Note this will auto-skip dynamic sets which should all be Null_state and hence .null().
1775
1776 return true;
1777} // Config_manager::apply_static_impl()
1778
1779template<typename... S_d_value_set>
1780template<typename... Value_set>
1782 (bool dyn_else_st, const fs::path& cfg_path, const boost::unordered_set<std::string>& all_opt_names_or_empty,
1783 const typename Final_validator_func<Value_set>::Type&... final_validator_func)
1784{
1785 size_t s_d_value_set_idx = 0;
1786 size_t value_set_idx = dyn_else_st ? 1 : 0;
1787
1788 /* Flag for the skipping of parsing and validation. Becomes true and stays true once one of the
1789 * final_validator_func()s yields S_SKIP. */
1790 bool skip_parsing = false;
1791
1792 bool success;
1793 return
1794 (
1795 ...
1796 &&
1797 (
1798 /* 2nd apply_impl() arg: If we're called from apply_dynamic(), supply the pre-parse baseline state, but only
1799 * if this isn't the 2nd/3rd/... apply_dynamic() of a multi-source (commit=false) sequence.
1800 * (If it's a null Option_set, then it'll be ignored by the no-op apply_impl().
1801 * Pass null.)
1802 * If we're called from apply_static(), it only happens once and is not relevant.
1803 * Pass null.
1804 * If it is the 2nd/3rd/... apply_dynamic() of a multi-source (commit=false) sequence, the pre-parse
1805 * baseline state has already been applied; and we don't want to blow away the incrementally built-up candidate
1806 * stored inside Value_set opt_set<>().
1807 * Pass null.
1808 * We are never called from apply_static_and_dynamic() which, itself,
1809 * sets that baseline state for later use in apply_dynamic() and hence here. */
1810 success = apply_impl(opt_set<Value_set> // Param pack expansion kernel here.
1811 (value_set_idx), // 1, 3, 5, ... -or- 0, 2, 4, ....
1812
1813 ((m_multi_src_update_in_progress == Update_type::S_NONE)
1814 && dyn_else_st && (!opt_set<Value_set>(value_set_idx)->null()))
1815 ? d_baseline_value_set<Value_set> // (And here.)
1816 (s_d_value_set_idx)
1817 : static_cast<const Value_set*>(nullptr), // (And here.)
1818
1819 cfg_path, all_opt_names_or_empty,
1820 final_validator_func, // (And here.)
1821 &skip_parsing),
1822 ++s_d_value_set_idx,
1823 value_set_idx += 2,
1824 success // Stop apply_impl()ing on first failure (the `&&` will evaluate to false early).
1825 )
1826 );
1827} // Config_manager::apply_static_or_dynamic_impl()
1828
1829template<typename... S_d_value_set>
1830template<typename Value_set>
1832 (Option_set<Value_set>* opt_set,
1833 const Value_set* baseline_value_set_or_null,
1834 const fs::path& cfg_path,
1835 const boost::unordered_set<std::string>& all_opt_names_or_empty,
1836 const typename Final_validator_func<Value_set>::Type& final_validator_func,
1837 bool* skip_parsing)
1838{
1839 assert(opt_set);
1840 auto& opts = *opt_set;
1841
1842 if (opts.null())
1843 {
1844 return true; // By the way notice, as advertised, final_validator_func is ignored.
1845 }
1846 // else
1847
1848 /* For some sets (namely dynamic ones, at most) we need to pre-apply the full set of baseline values.
1849 * This is explained in m_d_baseline_value_sets doc header; but basically it's so that successive dynamic updates
1850 * always apply the change in the file on top of a consistent state. Otherwise it's impossible to know, just by
1851 * looking at the dynamic config file, what the resulting state will be in memory -- incremental is bad in this
1852 * context. */
1853 if (baseline_value_set_or_null)
1854 {
1855 opts.parse_direct_values(*baseline_value_set_or_null);
1856 }
1857
1858 /* We allow final_validator_func()==SKIP, which means the validator decided the candidate Value_set is not
1859 * erroneous but has something there that means this particular apply_impl() shall have no effect on the candidate
1860 * after all. To make this work we must memorize the pre-parse state; as Option_set doesn't know about
1861 * final-validation or skipping and will have updated .values_candidate() (otherwise) irreversibly. We, however,
1862 * can simply undo it via .parse_direct_values() or .reject_candidate().
1863 *
1864 * Subtlety: If, in this possibly-multi-source update, this is the 1st source, then opt_set->values_candidate() may be
1865 * null (*opt_set is not in PARSING state but CANONICAL still). One option is to do what we do: save the canonical
1866 * value-set instead; then if rewinding below, it'll stay in PARSING state but have the unchanged canonical values.
1867 * Another option is to, instead, save nothing and when rewinding below in that case
1868 * reject_candidate() and thus bring *opt_set to CANONICAL state again. That may seem a bit more complex but more
1869 * elegant, but it leads to a subtle bug: If the possibly-multi-source update's final-validators *all* return SKIP --
1870 * which is arguably unusual but certainly allowed -- then apply_*() near its end will happily attempt to
1871 * opt_set->canonicalize_candidate() -- which will fail (possibly assert-trip) due to being invoked in
1872 * already-CANONICAL state. So our choices are to go with the just-save-values() route, or to -- elsewhere
1873 * in apply_*() themselves -- guard ->canonicalize_candidate() with a check for the everything-SKIPped situation.
1874 * Both are okay, but the former approach is simpler, avoiding at least a couple of if-branches in a couple of
1875 * places. It involves potentially 2 extra copy-ops of a Value_set; but so what? In the grand scheme the perf
1876 * impact is negligible. */
1877 const auto candidate_or_null = opt_set->values_candidate();
1878 const auto pre_parse_candidate = candidate_or_null ? *candidate_or_null : opt_set->values();
1879
1880 /* Ready to parse... but act as-if parse was fine but yielded SKIP, if told we're already in skipping mode
1881 * (from previous `Value_set`s, probably, though formally by contract this method doesn't care why). */
1882 if (skip_parsing && (*skip_parsing))
1883 {
1884 FLOW_LOG_INFO("Config_manager [" << *this << "]: "
1885 "Parsing, individual-option validation, and final-validation are being skipped "
1886 "for this value set, as requested by the caller. This file's values will not be applied. "
1887 "This has happened because this value set is successive to a value set whose "
1888 "final-validation determined that it shall not be applied. This is not an error.");
1889 opts.parse_direct_values(pre_parse_candidate);
1890 return true;
1891 }
1892 // else
1893
1894 /* We allow unknown (to this Option_set<Value_set> `opts`) options in the file during the initial parse -- but
1895 * only the ones that are themselves options but in other Option_sets we're also parsing (since non-hard-coded options
1896 * are not being parsed in this file, no other options should be present -- forward-compatibility, etc., not a
1897 * factor with a hard-coded file). Hence simply pass in all option names (including this one's, but they'll
1898 * just be parsed as belonging to this actual set and hence not be relevant to the unknown-option-name check).
1899 *
1900 * If it's not an initial parse then all_opt_names_or_empty will be empty, meaning simply allow all unknown options;
1901 * due to forward/backward-compatibility we just allow it and log such things but ignore them otherwise. */
1902 bool ok;
1903 opts.parse_config_file(cfg_path, true, &ok, all_opt_names_or_empty);
1904
1905 /* parse_config_file() specifically promises not to individually-validate values not in the actual file.
1906 * So before returning success (likely causing to finalize values via opts.canonicalize_candidate()) ensure
1907 * any invalid defaults don't "fall through." This is unnecessary if defaults were scanned individually
1908 * due to allow_invalid_defaults==false; but in that case it is harmless (as of this writing won't even log). */
1909 if (ok)
1910 {
1911 opts.validate_values_candidate(&ok);
1912 if (!ok) // It would have logged the exact problem, but we still want to clearly say what happened, high-level:
1913 {
1914 FLOW_LOG_WARNING("Config_manager [" << *this << "]: "
1915 "Request to apply config file [" << cfg_path << "] for a particular value set: "
1916 "Individual values present in file were OK, but at least 1 default value (see above) "
1917 "was invalid. Either correct the default or ensure it is properly overridden in file.");
1918 }
1919 } // if (ok) (but it may have become false inside)
1920
1921 if (ok)
1922 {
1923 // Lastly, as promised, run their inter-option validation (which can also specify that we skip).
1924 const auto final_validator_outcome = final_validator_func(*opts.values_candidate());
1925 switch (final_validator_outcome)
1926 {
1928 break; // Cool then.
1930 ok = false; // Uncool. It logged.
1931 break;
1932 case Final_validator_outcome::S_SKIP: // Cool-ish.
1933 FLOW_LOG_INFO("Config_manager [" << *this << "]: "
1934 "Request to apply config file [" << cfg_path << "] for a particular value set: "
1935 "Individual values present in file were OK, but the final-validator logic specified "
1936 "that this file's values not be applied (to skip the file after all). "
1937 "Rewinding the candidate value-set to pre-parse state. This is not an error.");
1938 opts.parse_direct_values(pre_parse_candidate);
1939 if (skip_parsing)
1940 {
1941 assert((!*skip_parsing) && "We should have `return`ed already.");
1942 *skip_parsing = true;
1943 }
1944 } // switch (final_validator_outcome). Compiler should warn if we failed to handle an enum value.
1945 } // if (ok) (but it may have become false inside)
1946
1947 return ok;
1948} // Config_manager::apply_impl()
1949
1950template<typename... S_d_value_set>
1952 (const fs::path& cfg_path,
1953 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
1954 bool commit)
1955{
1956 return apply_static_and_dynamic_impl(false, cfg_path, final_validator_func..., commit);
1957}
1958
1959template<typename... S_d_value_set>
1962 const fs::path& cfg_path,
1963 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
1964 bool commit)
1965{
1966 return apply_static_and_dynamic_impl(true, cfg_path, final_validator_func..., commit);
1967}
1968
1969template<typename... S_d_value_set>
1971 (bool allow_invalid_defaults,
1972 const fs::path& cfg_path,
1973 const typename Final_validator_func<S_d_value_set>::Type&... final_validator_func,
1974 bool commit)
1975{
1976 using util::Lock_guard;
1977 using boost::unordered_set;
1978 using std::string;
1979
1980 FLOW_LOG_INFO("Config_manager [" << *this << "]: Request to apply config file [" << cfg_path << "] as both "
1981 "static config and *baseline* dynamic config. Parsing in that order for each pair. "
1982 "Invalid defaults allowed if explicitly set in file? = [" << allow_invalid_defaults << "]. "
1983 "This application (if successful) shall end with canonicalizing values? = [" << commit << "]; "
1984 "multi-source update already in progress (0=none) = [" << int(m_multi_src_update_in_progress) << "].");
1985
1986 reject_candidates_if_update_type_changed(Update_type::S_STATIC_AND_DYNAMIC);
1987
1988 /* (See class doc header Implementation section for explanation of fold-expression (..., ) trick.)
1989 *
1990 * Note, though, that (... && expr) (of, say, length 4) evaluates to (((expr1 && expr2) && expr3) && expr4);
1991 * which means it'll run through the `expr...i...`s until one evaluates to false; then it stops and evaluates
1992 * no more past that. */
1993
1994 size_t value_set_idx;
1995 bool success = true;
1996
1997 /* Optionally scan the defaults themselves for individual-option-validator validity if so requested.
1998 * However no need to repeat this, if a multi-source update was already in progress. */
1999 if ((!allow_invalid_defaults) && (m_multi_src_update_in_progress == Update_type::S_NONE))
2000 {
2001 value_set_idx = 0;
2002 [[maybe_unused]] const auto dummy = // Defeats unused-value warning due to trailing `success`.
2003 (
2004 ...
2005 &&
2006 (
2007 opt_set<S_d_value_set>(value_set_idx) // Param pack expansion kernel here.
2008 ->validate_values(&success), // Set `success`...
2009 ++value_set_idx,
2010 success // ...and if it's false, the subsequent option sets shall be skipped.
2011 )
2012 );
2013
2014 if (!success) // It would have logged the exact problem, but we still want to clearly say what happened, high-level:
2015 {
2016 FLOW_LOG_WARNING("Config_manager [" << *this << "]: Request to apply config file [" << cfg_path << "] as both "
2017 "static config and *baseline* dynamic config: Will not parse file, because stringent check "
2018 "of defaults detected at least 1 individually-invalid default value. Either correct "
2019 "the default or use apply_static_and_dynamic(allow_invalid_defaults_tag_t) overload.");
2020 }
2021 } // if ((!allow_invalid_defaults) && (!m_multi_src_update_in_progress))
2022
2023 // First collect all valid static *and* dynamic option names as required by apply_impl().
2024 unordered_set<string> all_opt_names;
2025 unordered_set<string> this_opt_names;
2026 value_set_idx = 0;
2027 if (success) // Skip all this if failed above.
2028 {
2029 /* Flag for the skipping of parsing and validation. Becomes true and stays true once one of the
2030 * final_validator_func()s yields S_SKIP. */
2031 bool skip_parsing = false;
2032
2033 (
2034 ...,
2035 (
2036 this_opt_names = opt_set<S_d_value_set>(value_set_idx)->option_names(), // Param pack expansion kernel here.
2037 all_opt_names.insert(this_opt_names.begin(), this_opt_names.end()),
2038 ++value_set_idx
2039 )
2040 );
2041
2042 // Next do the actual parsing of each static *and* dynamic Option_set.
2043 value_set_idx = 0;
2044 [[maybe_unused]] const auto dummy = // Defeats unused-value warning due to trailing `success`.
2045 (
2046 ...
2047 &&
2048 (
2049 success = apply_impl(opt_set<S_d_value_set>(value_set_idx), // Param pack expansion kernel here.
2050 // Initial (baseline) parse: no need to apply baseline state.
2051 static_cast<const S_d_value_set*>(nullptr), // (And here.)
2052 cfg_path, all_opt_names,
2053 final_validator_func, // (And here.)
2054 &skip_parsing),
2055 ++value_set_idx,
2056 success // Stop apply_impl()ing on first failure.
2057 )
2058 );
2059 } // if (success) (but it may have become false inside)
2060
2061 if ((!commit) && success)
2062 {
2063 m_multi_src_update_in_progress = Update_type::S_STATIC_AND_DYNAMIC; // (Was either NONE or already this.)
2064 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update has successfully begun or continued. "
2065 "Expecting more sources before we can canonicalize candidate(s).");
2066 return true;
2067 }
2068 // else if (commit || (!success))
2069
2070 /* !success => reject, regardless of commit (a failure aborts a multi-source update too).
2071 * commit => accept or reject depending on `success`.
2072 *
2073 * So next either canonicalize or reject each parse attempt depending on overall success (static *and* dynamic). */
2074 value_set_idx = 0;
2075 (
2076 ...,
2077 (
2078 /* Note: If parsing stopped before `value_set_idx` due to failure, rejecting Option_set value_set_idx is a
2079 * harmless no-op by Option_set docs. */
2080 option_set_canonicalize_or_reject
2081 (opt_set<S_d_value_set>(value_set_idx), // Param pack expansion kernel here.
2082 success, nullptr),
2083 ++value_set_idx
2084 )
2085 );
2086
2087 if (m_multi_src_update_in_progress != Update_type::S_NONE)
2088 {
2089 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update is now finished.");
2090 m_multi_src_update_in_progress = Update_type::S_NONE;
2091 }
2092 // else { It was NONE and remains so, either due to failure or being a vanilla (single-source) update or both. }
2093
2094 if (!success)
2095 {
2096 return false;
2097 }
2098 // else if (success):
2099 assert(commit && "Maintenance bug? We should have returned above if `!commit` but success==true.");
2100
2101 FLOW_LOG_INFO("Config_manager [" << *this << "]: State that was just made canonical follows.");
2102 log_state();
2103
2104 /* For dynamic sets only -- we must memorize the current Value_set state into
2105 * m_d_baseline_value_sets[]. It shall be set as the baseline state before actually parsing dynamic config file
2106 * contents in apply_dynamic(), each time it is called subsequently. */
2107 bool dyn_else_st = false;
2108 value_set_idx = 0;
2109 size_t d_value_set_idx = 0;
2110 (
2111 ...,
2112 (
2113 /* As noted above, fill an m_d_baseline_value_sets[] but for dynamic sets only. Note that this will copy
2114 * a Value_set onto a Value_set (in its entirety). We could also replace the shared_ptr, but why bother?
2115 * The code would be longer, and it would be somewhat slower too (still a copy involved).
2116 *
2117 * Also skip any null() dynamic set.
2118 * (This is `if (dyn_else_st) { ... }` in expression form.) */
2119 static_cast<void> // Defeats possible unused-value warning.
2120 (dyn_else_st
2121 // (This is `if (!(...).null()) { ... }` in expression form.)
2122 && (opt_set<S_d_value_set>(value_set_idx)->null() // Param pack expansion kernel here.
2123 || (*(d_baseline_value_set<S_d_value_set>(d_value_set_idx)) // (And here.)
2124 = opt_set<S_d_value_set>(value_set_idx)->values(), // (And here.)
2125 true),
2126 ++d_value_set_idx,
2127 true)),
2128
2129 ++value_set_idx,
2130 dyn_else_st = !dyn_else_st
2131 )
2132 );
2133
2134 // Next: Eureka! Set the dynamic-values pointers for the first time.
2135 {
2136 Lock_guard<decltype(m_d_value_sets_mutex)> lock{m_d_value_sets_mutex};
2137 value_set_idx = 0;
2138 dyn_else_st = false;
2139 (
2140 ...,
2141 (
2142 // Just skip static ones. (This is `if (dyn_else_st) { ... }` in expression form.)
2143 static_cast<void> // Defeats possible unused-value warning.
2144 (dyn_else_st
2145 && (save_dynamic_value_set_locked<S_d_value_set> // Param pack expansion kernel here.
2146 (opt_set<S_d_value_set>(value_set_idx), value_set_idx / 2),
2147 true)),
2148 ++value_set_idx,
2149 dyn_else_st = !dyn_else_st
2150 )
2151 );
2152 } // Lock_guard lock{m_d_value_sets_mutex};
2153
2154 // They shouldn't do apply_static_and_dynamic() except as the first apply*_dynamic() thing.
2155 assert((!m_dynamic_values_set)
2156 && "User apparently attempted apply_static_and_dynamic(), but dynamic config was already initialized OK.");
2157 m_dynamic_values_set = true;
2158
2159 // Finally invoke dynamic "change" listeners for the first time. (.null() => no listeners registered.)
2160 for (d_value_set_idx = 0; d_value_set_idx != S_N_D_VALUE_SETS; ++d_value_set_idx)
2161 {
2162 invoke_dynamic_change_listeners(d_value_set_idx, true); // true => initial.
2163 }
2164
2165 return true;
2166} // Config_manager::apply_static_and_dynamic_impl()
2167
2168template<typename... S_d_value_set>
2169template<typename... Value_set>
2171 (const fs::path& dynamic_cfg_path,
2172 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
2173 bool commit)
2174{
2175 return apply_dynamic_impl<Value_set...>(false, dynamic_cfg_path, final_validator_func..., commit);
2176}
2177
2178template<typename... S_d_value_set>
2179template<typename... Value_set>
2182 const fs::path& dynamic_cfg_path,
2183 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
2184 bool commit)
2185{
2186 return apply_dynamic_impl<Value_set...>(true, dynamic_cfg_path, final_validator_func..., commit);
2187}
2188
2189template<typename... S_d_value_set>
2190template<typename... Value_set>
2192 (bool allow_invalid_defaults,
2193 const fs::path& dynamic_cfg_path,
2194 const typename Final_validator_func<Value_set>::Type&... final_validator_func,
2195 bool commit)
2196{
2197 using util::Lock_guard;
2199 using boost::array;
2200 using std::flush;
2201
2202 if (m_dynamic_values_set)
2203 {
2204 FLOW_LOG_INFO("Config_manager [" << *this << "]: "
2205 "Request to apply dynamic config file [" << dynamic_cfg_path << "]. "
2206 "Initializing dynamic config? = [false]. "
2207 "This application (if successful) shall end with canonicalizing values? = [" << commit << "]; "
2208 "multi-source update already in progress "
2209 "(0=none) = [" << int(m_multi_src_update_in_progress) << "].");
2210 }
2211 else
2212 {
2213 FLOW_LOG_INFO("Config_manager [" << *this << "]: "
2214 "Request to apply dynamic config file [" << dynamic_cfg_path << "]. "
2215 "Initializing dynamic config? = [true]. "
2216 "Invalid defaults allowed if explicitly set in file? = [" << allow_invalid_defaults << "]. "
2217 "This application (if successful) shall end with canonicalizing values? = [" << commit << "]; "
2218 "multi-source update already in progress "
2219 "(0=none) = [" << int(m_multi_src_update_in_progress) << "].");
2220 }
2221
2222 reject_candidates_if_update_type_changed(Update_type::S_DYNAMIC);
2223
2224 /* (See class doc header Implementation section for explanation of fold-expression (..., ) trick.)
2225 *
2226 * Note, though, that (... && expr) (of, say, length 4) evaluates to (((expr1 && expr2) && expr3) && expr4);
2227 * which means it'll run through the `expr...i...`s until one evaluates to false; then it stops and evaluates
2228 * no more past that. */
2229
2230 size_t value_set_idx;
2231 bool success = true;
2232
2233 /* Optionally scan the defaults themselves for individual-option-validator validity if so requested and applicable.
2234 * However no need to repeat this, if a multi-source update was already in progress. */
2235 if ((!m_dynamic_values_set) && (!allow_invalid_defaults) && (m_multi_src_update_in_progress == Update_type::S_NONE))
2236 {
2237 value_set_idx = 1; // 1, 3, 5, ....
2238 [[maybe_unused]] const auto dummy = // Defeats unused-value warning due to trailing `success`.
2239 (
2240 ...
2241 &&
2242 (
2243 opt_set<Value_set>(value_set_idx) // Param pack expansion kernel here.
2244 ->validate_values(&success), // Set `success`...
2245 value_set_idx += 2, // (Skip static ones.)
2246 success // ...and if it's false, the subsequent option sets shall be skipped.
2247 )
2248 );
2249
2250 if (!success) // It would have logged the exact problem, but we still want to clearly say what happened, high-level:
2251 {
2252 FLOW_LOG_WARNING("Config_manager [" << *this << "]: "
2253 "Request to initially-apply dynamic config file [" << dynamic_cfg_path << "]: "
2254 "Will not parse file, because stringent check "
2255 "of defaults detected at least 1 individually-invalid default value. Either correct "
2256 "the default or use apply_dynamic(allow_invalid_defaults_tag_t) overload.");
2257 }
2258 } // if ((!m_dynamic_values_set) && (!allow_invalid_defaults) && (m_multi_src_update_in_progress == NONE))
2259 /* else if (m_multi_src_update_in_progress != NONE) { It has been checked already; don't repeat. }
2260 * else if ((!m_dynamic_values_set) && allow_invalid_defaults) { They don't want default check: don't check it. }
2261 * else if (m_dynamic_values_set) { As advertised do not check defaults except possibly before first load. } */
2262
2263 /* Do the actual parsing of each dynamic Option_set. Recall that due to forward/backward-compatibility concerns
2264 * we allow any unknown option names, hence the empty set for all_opt_names. */
2265 success = success
2266 && apply_static_or_dynamic_impl<Value_set...>(true,
2267 dynamic_cfg_path, {}, final_validator_func...);
2268
2269 if ((!commit) && success)
2270 {
2271 m_multi_src_update_in_progress = Update_type::S_DYNAMIC; // (Was either NONE or already this.)
2272 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update has successfully begun or continued. "
2273 "Expecting more sources before we can canonicalize candidate(s).");
2274 return true;
2275 }
2276 // else if (commit || (!success))
2277
2278 /* !success => reject, regardless of commit (a failure aborts a multi-source update too).
2279 * commit => accept or reject depending on `success`.
2280 *
2281 * So next either canonicalize or reject each parse attempt depending on overall success (dynamic only). */
2282 size_t d_value_set_idx = 0;
2283
2284 /* Zero it (`{}`) to avoid warnings from undefined behavior sanitizer; it's not a perf-critical path.
2285 * (In reality the zeroing is not necessary, but we've run into warnings by some tools; might as well avoid.) */
2286 array<bool, S_N_D_VALUE_SETS> changed{};
2287 bool some_changed = false;
2288 (
2289 ...,
2290 (
2291 value_set_idx = (d_value_set_idx * 2) + 1, // 1, 3, 5, ....
2292 /* Note: If parsing stopped before `value_set_idx` due to failure, rejecting Option_set value_set_idx is a
2293 * harmless no-op by Option_set docs. */
2294 option_set_canonicalize_or_reject(opt_set<Value_set>(value_set_idx), // Param pack expansion kernel here.
2295 success,
2296 // If initial dynamic parse, then `changed[] = true` by definition.
2297 m_dynamic_values_set ? &changed[d_value_set_idx] : nullptr),
2298 // If initial dynamic parse, then `changed[] = true` by definition.
2299 changed[d_value_set_idx] = (!m_dynamic_values_set) || changed[d_value_set_idx],
2300 // some_changed = true iff: changed[x] == true for at least one x.
2301 some_changed = some_changed || changed[d_value_set_idx],
2302 ++d_value_set_idx
2303 )
2304 );
2305
2306 if (m_multi_src_update_in_progress != Update_type::S_NONE)
2307 {
2308 FLOW_LOG_INFO("Config_manager [" << *this << "]: Multi-source update is now finished.");
2309 m_multi_src_update_in_progress = Update_type::S_NONE;
2310 }
2311 // else { It was NONE and remains so, either due to failure or being a vanilla (single-source) update or both. }
2312
2313 if (!success)
2314 {
2315 return false;
2316 }
2317 // else
2318
2319 if (!some_changed) // Note, again, that if initial dynamic parse then some_changed==true.
2320 {
2321 return true; // Meaning, no changes -- but success.
2322 }
2323 // else
2324
2325 // The following is almost exactly log_state() but for dynamic sets only.
2326 String_ostream os;
2327 os.os() << "Config_manager [" << *this << "]: (Dynamic) state that was just made canonical follows.\n";
2328 value_set_idx = 1;
2329 (
2330 ...,
2331 (
2332 // 1, 3, 5, ....
2333 state_to_ostream_impl<Value_set>(value_set_idx, os.os()), // Param pack expansion kernel here.
2334 value_set_idx += 2
2335 )
2336 );
2337 os.os() << flush;
2338 FLOW_LOG_INFO(os.str());
2339
2340 /* Next: Eureka! Set the dynamic-values pointer for each option set that did change.
2341 *
2342 * There are some funky-looking logic-op/comma-expr constructions in there. I (ygoldfel) feel they're understandable
2343 * enough, and the conciseness is worth it, but arguably it could instead be done with regular `if ()`s instead
2344 * in a helper function -- though less concise (possible @todo). BTW generic lambdas could help there, but it would
2345 * require C++20 (I haven't looked into it thoroughly though). */
2346 {
2347 Lock_guard<decltype(m_d_value_sets_mutex)> lock{m_d_value_sets_mutex};
2348 d_value_set_idx = 0;
2349 (
2350 ...,
2351 (
2352 value_set_idx = (d_value_set_idx * 2) + 1, // 1, 3, 5, ....
2353 // Just skip unchanged ones. (This is `if (x) { f(...); }` in expression form.)
2354 static_cast<void> // Defeats possible unused-value warning.
2355 (changed[d_value_set_idx]
2356 && (save_dynamic_value_set_locked<Value_set> // Param pack expansion kernel here.
2357 (opt_set<Value_set>(value_set_idx), // (And here.)
2358 d_value_set_idx),
2359 true)),
2360 ++d_value_set_idx
2361 )
2362 );
2363 } // Lock_guard lock{m_d_value_sets_mutex};
2364
2365 const bool was_dynamic_values_set = m_dynamic_values_set;
2366 m_dynamic_values_set = true; // Might already be true (if not initial parse).
2367
2368 /* Finally invoke dynamic change (or "change," if initial parse) listeners (possibly for the first time).
2369 * (.null() => no listeners registered.) */
2370 for (d_value_set_idx = 0; d_value_set_idx != S_N_D_VALUE_SETS; ++d_value_set_idx)
2371 {
2372 if (changed[d_value_set_idx])
2373 {
2374 invoke_dynamic_change_listeners(d_value_set_idx, !was_dynamic_values_set);
2375 }
2376 }
2377
2378 return true;
2379} // Config_manager::apply_dynamic()
2380
2381template<typename... S_d_value_set>
2383{
2384 if (m_multi_src_update_in_progress == Update_type::S_NONE)
2385 {
2386 FLOW_LOG_INFO("Config_manager [" << *this << "]: Request to abandon multi-source update in-progress; but none "
2387 "is in progress. Doing nothing.");
2388 return; // Nothing to cancel.
2389 }
2390 // else
2391
2392 FLOW_LOG_INFO("Config_manager [" << *this << "]: Request to abandon multi-source update in-progress. Doing so.");
2393
2394 // (See class doc header Implementation section for explanation of fold-expression (..., ) trick.)
2395 size_t value_set_idx = 0;
2396 (
2397 ...,
2398 (
2399 /* This will be silent if it is a no-op for a given Value_set; namely if it's a Null_value_set, and/or
2400 * it pertains to a static Value_set after an apply_dynamic() or dynamic after an apply_static(). */
2401 option_set_canonicalize_or_reject
2402 (opt_set<S_d_value_set>(value_set_idx), // Param pack expansion kernel here.
2403 false, nullptr), // false <= reject.
2404 ++value_set_idx
2405 )
2406 );
2407
2408 m_multi_src_update_in_progress = Update_type::S_NONE;
2409} // Config_manager::reject_candidates()
2410
2411template<typename... S_d_value_set>
2413{
2414 assert(this_update_type != Update_type::S_NONE);
2415 if ((m_multi_src_update_in_progress == Update_type::S_NONE) // Nothing to cancel; all is cool.
2416 || (m_multi_src_update_in_progress == this_update_type)) // It's a multi-source update; all is cool.
2417 {
2418 return; // Nothing to cancel.
2419 }
2420 // else if (m_multi_src_update_in_progress is truthy but != this_update_type)
2421
2422 FLOW_LOG_INFO("Config_manager [" << *this << "]: An update of type [" << int(this_update_type) << "] "
2423 "is interrupting (canceling) an in-progress multi-source update of type "
2424 "[" << int(m_multi_src_update_in_progress) << "]. Reverting any uncommitted values "
2425 "from the latter. Suggest invoking reject_candidates() explicitly if intentional; this "
2426 "message will then go away, while the code will be more deliberate.");
2427
2428 reject_candidates();
2429 assert(m_multi_src_update_in_progress == Update_type::S_NONE);
2430} // Config_manager::reject_candidates_if_update_type_changed()
2431
2432template<typename... S_d_value_set>
2433template<typename Value_set>
2435 (Option_set<Value_set>* opt_set_ptr, size_t d_value_set_idx)
2436{
2437 assert(opt_set_ptr);
2438 auto& opt_set = *opt_set_ptr;
2439
2440 /* Make a copy of the canonical dynamic Value_set, wrapped in ptr-to-mutable; upgrade to ptr-to-immutable.
2441 * @todo It's not-great this is inside the locked section. There's no great alternative -- maybe make all these
2442 * copies before the locked section, which can be done; it's just rather hairy due to the param-pack expanding. */
2443 *(static_cast<typename Value_set::Const_ptr*>(m_d_value_sets[d_value_set_idx].get()))
2444 // Attn: --^ void* -> T* cast; no RTTI to check our type safety.
2445 = Value_set::const_ptr_cast(opt_set.mutable_values_copy());
2446}
2447
2448template<typename... S_d_value_set>
2450{
2451 FLOW_LOG_INFO("Config_manager [" << *this << "]: "
2452 "Dynamic update for dynamic option set [" << d_value_set_idx << "] (0-based) of "
2453 "[" << S_N_D_VALUE_SETS << "] (1-based); trigger was "
2454 "[" << (init ? "initial-update" : "change-detected") << "].");
2455
2456 const auto& on_dynamic_change_funcs = m_on_dynamic_change_funcs[d_value_set_idx];
2457
2458 size_t idx = 0;
2459 for (const auto& on_dynamic_change_func : on_dynamic_change_funcs)
2460 {
2461 FLOW_LOG_INFO("Invoking listener [" << idx << "] (0-based) of [" << on_dynamic_change_funcs.size() << "] "
2462 "(1-based).");
2463 on_dynamic_change_func();
2464 ++idx;
2465 }
2466 FLOW_LOG_INFO("Done invoking change listeners for dynamic option set.");
2467} // Config_manager::invoke_dynamic_change_listeners()
2468
2469template<typename... S_d_value_set>
2470template<typename... Value_set>
2471void Config_manager<S_d_value_set...>::all_static_values(const Value_set**... value_set_or_null) const
2472{
2473 static_assert(sizeof...(Value_set) == S_N_S_VALUE_SETS,
2474 "You must supply N/2 `value_set_or_null`s, where N is # of S_d_value_set params. "
2475 "Use nullptr for any Null_value_set and/or Value_set of no interest.");
2476
2477 size_t s_value_set_idx = 0;
2478 size_t value_set_idx;
2479 (
2480 ...,
2481 (
2482 value_set_idx = s_value_set_idx * 2,
2483 // I.e., if (x && y) { *x = ... }.
2484 static_cast<void> // Defeats possible unused-value warning.
2485 ((value_set_or_null && (!opt_set<Value_set> // Param pack expansion kernel here (x2).
2486 (value_set_idx)->null()))
2487 && (*value_set_or_null = &(opt_set<Value_set>(value_set_idx)->values()), // (And here, x2.)
2488 true)),
2489 ++s_value_set_idx
2490 )
2491 );
2492} // Config_manager::all_static_values()
2493
2494template<typename... S_d_value_set>
2495template<typename... Value_set>
2496void Config_manager<S_d_value_set...>::all_static_values_candidates(const Value_set**... value_set_or_null) const
2497{
2498 static_assert(sizeof...(Value_set) == S_N_S_VALUE_SETS,
2499 "You must supply N/2 `value_set_or_null`s, where N is # of S_d_value_set params. "
2500 "Use nullptr for any Null_value_set and/or Value_set of no interest.");
2501
2502 size_t s_value_set_idx = 0;
2503 size_t value_set_idx;
2504 (
2505 ...,
2506 (
2507 value_set_idx = s_value_set_idx * 2,
2508 static_cast<void> // Defeats possible unused-value warning.
2509 ((value_set_or_null && (!opt_set<Value_set> // Param pack expansion kernel here (x2).
2510 (value_set_idx)->null()))
2511 /* Emitted pointer will be equivalent to what is provided by all_static_values() unless a
2512 * parsed-but-not-canonicalized value set is available (i.e. this is being called from a validator function
2513 * being executed during parsing). This is achieved here because Option_set<>::values_candidate() will
2514 * return the candidate when in PARSING state, but nullptr when in CANONICAL state (in which case the
2515 * canonical values provided by Option_set<>::values() is then used, here, instead). */
2516 && (*value_set_or_null = opt_set<Value_set>(value_set_idx)->values_candidate() // (And here x2.)
2517 // (?: with omitted middle operand is gcc extension).
2518 ?: &(opt_set<Value_set>(value_set_idx)->values()), // (And here.)
2519 true)),
2520 ++s_value_set_idx
2521 )
2522 );
2523} // Config_manager::all_static_values_candidates()
2524
2525template<typename... S_d_value_set>
2526template<typename Value_set>
2527const Value_set& Config_manager<S_d_value_set...>::static_values(size_t s_value_set_idx) const
2528{
2529 assert((s_value_set_idx < S_N_S_VALUE_SETS) && "Invalid static option set index.");
2530
2531 return opt_set<Value_set>(s_value_set_idx * 2)->values();
2532} // Config_manager::static_values()
2533
2534template<typename... S_d_value_set>
2535template<typename Value_set>
2536const Value_set& Config_manager<S_d_value_set...>::static_values_candidate(size_t s_value_set_idx) const
2537{
2538 assert((s_value_set_idx < S_N_S_VALUE_SETS) && "Invalid static option set index.");
2539
2540 const auto opt = opt_set<Value_set>(s_value_set_idx * 2);
2541
2542 /* Return value will be equivalent to what is provided by static_values() unless a parsed-but-not-canonicalized value
2543 * set is available (i.e. this is being called from a validator function being executed during parsing). This is
2544 * achieved here because ->values_candidate() will return the candidate when in PARSING state, but nullptr when in
2545 * CANONICAL state (in which case the canonical values provided by ->values() is used, instead). */
2546 const Value_set* values = opt->values_candidate();
2547 if (!values)
2548 {
2549 values = &(opt->values());
2550 }
2551
2552 return *values;
2553} // Config_manager::static_values_candidate()
2554
2555template<typename... S_d_value_set>
2556template<typename... Value_set>
2558 (typename Value_set::Const_ptr*... value_set_or_null) const
2559{
2560 using util::Lock_guard;
2561
2562 static_assert(sizeof...(Value_set) == S_N_D_VALUE_SETS,
2563 "You must supply N/2 `value_set_or_null`s, where N is # of S_d_value_set params. "
2564 "Use nullptr for any Null_value_set and/or Value_set of no interest.");
2565
2566 // As promised just copy out the values atomically and return them. Next time it might return different ones.
2567 Lock_guard<decltype(m_d_value_sets_mutex)> lock{m_d_value_sets_mutex};
2568
2569 size_t d_value_set_idx = 0;
2570 size_t value_set_idx;
2571 (
2572 ...,
2573 (
2574 value_set_idx = (d_value_set_idx * 2) + 1,
2575 // I.e., if (x && y) { *x = ... }.
2576 static_cast<void> // Defeats possible unused-value warning.
2577 ((value_set_or_null && (!opt_set<Value_set> // Param pack expansion kernel here (x2).
2578 (value_set_idx)->null()))
2579 && (*value_set_or_null // (And here.)
2580 = *(static_cast<typename Value_set::Const_ptr*>(m_d_value_sets[d_value_set_idx].get())), // (And here.)
2581 // Attn: --^ void* -> T* cast; no RTTI to check our type safety.
2582 true)),
2583 ++d_value_set_idx
2584 )
2585 );
2586} // Config_manager::all_dynamic_values()
2587
2588template<typename... S_d_value_set>
2589template<typename Value_set>
2590typename Value_set::Const_ptr
2592{
2593 using util::Lock_guard;
2594
2595 assert((d_value_set_idx < S_N_D_VALUE_SETS) && "Invalid dynamic option set index.");
2596
2597 // As promised just copy out the value atomically and return it. Next time it might return different pointer.
2598 Lock_guard<decltype(m_d_value_sets_mutex)> lock{m_d_value_sets_mutex};
2599 return *(static_cast<typename Value_set::Const_ptr*>(m_d_value_sets[d_value_set_idx].get()));
2600 // Attn: --^ void* -> T* cast; no RTTI to check our type safety.
2601}
2602
2603template<typename... S_d_value_set>
2605{
2606 os << "Config_manager [" << *this << "]: Current state + config documentation:\n";
2607
2608 size_t value_set_idx = 0;
2609 (
2610 ...,
2611 state_to_ostream_impl<S_d_value_set>(value_set_idx++, os) // Param pack expansion kernel here.
2612 );
2613}
2614
2615template<typename... S_d_value_set>
2616template<typename Value_set>
2617void Config_manager<S_d_value_set...>::state_to_ostream_impl(size_t value_set_idx, std::ostream& os) const
2618{
2619 const auto& opts = *(opt_set<Value_set>(value_set_idx));
2620 if (opts.null())
2621 {
2622 return; // Print nothing at all.
2623 }
2624 // else
2625
2626 const size_t s_d_value_set_idx = value_set_idx / 2;
2627 const bool dyn_else_st = (value_set_idx % 2) == 1;
2628
2629 os << "-- [" << (dyn_else_st ? "DYNAMIC" : "STATIC") << "] [" << s_d_value_set_idx << "] --\n";
2630
2631 /* Helper that prints any pending commit=false data that hasn't been upgraded to canonical via
2632 * apply_*(commit = true). */
2633 const auto output_uncanonicalized = [&]()
2634 {
2635 if (m_multi_src_update_in_progress != Update_type::S_NONE)
2636 {
2637 /* The apply_*() sequence in-progress may be apply_dynamic(), while we're static, or vice versa.
2638 * In that case `Option_set opts` is in PARSING, not CANONICAL state, so there is nothing to print. */
2639 const auto candidate_or_none = opts.values_candidate();
2640 if (candidate_or_none)
2641 {
2642 os << " <incomplete multi-source update type [" << int(m_multi_src_update_in_progress) << "] in-progress / "
2643 "current candidate values follow>\n";
2644 opts.values_to_ostream(os, candidate_or_none);
2645 }
2646 }
2647 }; // output_uncanonicalized =
2648
2649 if (!dyn_else_st)
2650 {
2651 opts.values_to_ostream(os);
2652 output_uncanonicalized();
2653 return;
2654 }
2655 // else if (dyn_else_st)
2656
2657 if (m_dynamic_values_set)
2658 {
2659 opts.values_to_ostream(os);
2660 output_uncanonicalized();
2661 return;
2662 }
2663 // else if (no dynamic values yet loaded)
2664
2665 /* Print just help (no current values: we have none -- only defaults).
2666 * Granted the same could be said of static sets too, before apply_static*(), but keeping track of
2667 * a hypothetical m_static_values_set just to be able to do this same thing here for static options, for
2668 * something with such a simple usage lifecycle (apply_static*() is done exactly once, probably near the top
2669 * of the module/application), seems like overkill. */
2670 os << "<no dynamic config init payload / option docs follow instead>\n";
2671 opts.help_to_ostream(os);
2672
2673 output_uncanonicalized();
2674} // Config_manager::state_to_ostream_impl()
2675
2676template<typename... S_d_value_set>
2678{
2680 using std::flush;
2681
2682 String_ostream os;
2683 state_to_ostream(os.os());
2684 os.os() << flush;
2685 FLOW_LOG_WITH_CHECKING(sev, os.str());
2686} // Config_manager::log_state()
2687
2688template<typename... S_d_value_set>
2690{
2691 os << "Config_manager [" << *this << "]: Config help:\n";
2692
2693 size_t value_set_idx = 0;
2694 (
2695 ...,
2696 help_to_ostream_impl<S_d_value_set>(value_set_idx++, os) // Param pack expansion kernel here.
2697 );
2698}
2699
2700template<typename... S_d_value_set>
2701template<typename Value_set>
2702void Config_manager<S_d_value_set...>::help_to_ostream_impl(size_t value_set_idx, std::ostream& os) const
2703{
2704 const auto opts = opt_set<Value_set>(value_set_idx);
2705 if (opts->null())
2706 {
2707 return; // Print nothing at all.
2708 }
2709 // else
2710
2711 const size_t s_d_value_set_idx = value_set_idx / 2;
2712 const bool dyn_else_st = (value_set_idx % 2) == 1;
2713
2714 os << "-- [" << (dyn_else_st ? "DYNAMIC" : "STATIC") << "] [" << s_d_value_set_idx << "] --\n";
2715 opts->help_to_ostream(os);
2716} // Config_manager::help_to_ostream_impl()
2717
2718template<typename... S_d_value_set>
2720{
2722 using std::flush;
2723
2724 String_ostream os;
2725 help_to_ostream(os.os());
2726 os.os() << flush;
2727 FLOW_LOG_WITH_CHECKING(sev, os.str());
2728} // Config_manager::log_help()
2729
2730template<typename Value_set>
2732{
2733 return [](const Value_set&) -> Final_validator_outcome { return Final_validator_outcome::S_ACCEPT; };
2734}
2735
2736template<typename... S_d_value_set>
2737std::ostream& operator<<(std::ostream& os, const Config_manager<S_d_value_set...>& val)
2738{
2739 return os << '[' << val.m_nickname << "]@" << &val;
2740}
2741
2742} // namespace flow::cfg
Manages a config setup, intended for a single daemon process, by maintaining 1 or more set(s) of stat...
void log_help(log::Sev sev=log::Sev::S_INFO) const
Logs what help_to_ostream() would print.
boost::array< std::list< On_dynamic_change_func >, S_N_D_VALUE_SETS > m_on_dynamic_change_funcs
List of callbacks to execute after m_d_value_sets members (the pointers) are next assigned: one per e...
void state_to_ostream(std::ostream &os) const
Prints a human-targeted long-form summary of our contents, doubling as a usage message and a dump of ...
void log_state(log::Sev sev=log::Sev::S_INFO) const
Logs what state_to_ostream() would print.
bool apply_static(const fs::path &static_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit=true)
Invoke this after construction to load the permanent set of static config from config sources includi...
bool apply_dynamic(allow_invalid_defaults_tag_t, const fs::path &dynamic_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit=true)
Identical to apply_dynamic() overload without allow_invalid_defaults_tag_t tag; except that – applica...
bool apply_dynamic(const fs::path &dynamic_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit=true)
Load the first or subsequent set of dynamic config from config source including a dynamic config file...
void option_set_canonicalize_or_reject(Option_set< Value_set > *opt_set, bool canonicalize_else_reject, bool *changed_or_null)
Helper that executes opt_set->canonicalize_candidate() or opt_set->reject_candidate().
Option_set< Value_set > * opt_set(size_t value_set_idx)
Helper that obtains the Option_set in the slot m_s_d_opt_sets[value_set_idx], which stores an Option_...
boost::array< Void_ptr, S_N_D_VALUE_SETS > m_d_value_sets
The dynamic config ref-counted handles returned by all_dynamic_values().
boost::array< Void_ptr, S_N_D_VALUE_SETS > m_d_baseline_value_sets
The baseline dynamic value sets, in the same order as S_N_D_VALUE_SETS dynamic S_d_value_set template...
void unregister_dynamic_change_listener(const On_dynamic_change_func_handle &handle)
Remove a previously registered dynamic change callback.
boost::array< Void_ptr, S_N_VALUE_SETS > m_s_d_opt_sets
The static and dynamic value sets, in the same order as the S_N_VALUE_SETS S_d_value_set template arg...
void invoke_dynamic_change_listeners(size_t d_value_set_idx, bool init) const
Invokes the registered listeners for the given dynamic config slot (synchronously).
bool apply_static_and_dynamic(allow_invalid_defaults_tag_t, const fs::path &cfg_path, const typename Final_validator_func< S_d_value_set >::Type &... final_validator_func, bool commit=true)
Identical to apply_static_and_dynamic() overload without allow_invalid_defaults_tag_t tag; but skips ...
void all_static_values_candidates(const Value_set **... value_set_or_null) const
Similar to all_static_values(), but if called from within a validator function passed to apply_static...
bool apply_static_and_dynamic_impl(bool allow_invalid_defaults, const fs::path &cfg_path, const typename Final_validator_func< S_d_value_set >::Type &... final_validator_func, bool commit)
Implements all apply_static_and_dynamic() overloads.
allow_invalid_defaults_tag_t
Tag type: indicates an apply_*() method must allow invalid defaults and only complain if the config s...
@ S_ALLOW_INVALID_DEFAULTS
Sole value for tag type allow_invalid_defaults_tag_t.
const std::string m_nickname
See nickname ctor arg.
void all_dynamic_values(typename Value_set::Const_ptr *... value_set_or_null) const
Obtain ref-counted pointers to each currently-canonical set of dynamic config; each pointed-at struct...
boost::shared_ptr< void > Void_ptr
Short-hand for shared_ptr-to-void type used to store variable-type values in internal containers.
void all_static_values(const Value_set **... value_set_or_null) const
Emit a pointer to each permanently set static config value set; the same pointers are emitted through...
const Value_set & static_values(size_t s_value_set_idx) const
Similar to all_static_values(), but obtains the static config in one specified slot as opposed to all...
void save_dynamic_value_set_locked(Option_set< Value_set > *opt_set, size_t d_value_set_idx)
Little helper that, having assumed m_d_value_sets_mutex is locked, makes a newly allocated copy of th...
bool apply_dynamic_impl(bool allow_invalid_defaults, const fs::path &dynamic_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit)
Implements all apply_dynamic() overloads.
void help_to_ostream_impl(size_t value_set_idx, std::ostream &os) const
Helper of help_to_ostream() for m_s_d_opt_sets slot value_set_idx.
On_dynamic_change_func_handle register_dynamic_change_listener(size_t d_value_set_idx, On_dynamic_change_func &&on_dynamic_change_func_moved)
Saves the given callback; next time apply_dynamic(commit = true) or apply_static_and_dynamic(commit =...
static constexpr size_t S_N_S_VALUE_SETS
The number of static value sets (including any Null_value_sets).
bool apply_static_and_dynamic(const fs::path &cfg_path, const typename Final_validator_func< S_d_value_set >::Type &... final_validator_func, bool commit=true)
If you use dynamic config, and you allow for initial values for dynamic options to be read from the s...
Update_type
Useful at least in the context of multi-source (commit == false) apply_*() methods,...
bool m_dynamic_values_set
Starts false; set to true permanently on successful apply_static_and_dynamic() or apply_dynamic().
bool apply_static_or_dynamic_impl(bool dyn_else_st, const fs::path &cfg_path, const boost::unordered_set< std::string > &all_opt_names_or_empty, const typename Final_validator_func< Value_set >::Type &... final_validator_func)
Work-horse helper that parses either all static value sets or all dynamic value sets from the specifi...
util::Mutex_non_recursive m_d_value_sets_mutex
Mutex protecting m_d_value_sets.
Value_set * d_baseline_value_set(size_t d_value_set_idx)
Helper that obtains the baseline dynamic Value_set in the slot m_d_baseline_value_sets[value_set_idx]...
void reject_candidates_if_update_type_changed(Update_type this_update_type)
Helper for the top of apply_*() that guards against a call to apply_Y() following apply_X(commit == f...
void reject_candidates()
Cancel a not-yet-canonicalized (incomplete) multi-source update, if one is in progress.
Value_set::Const_ptr dynamic_values(size_t d_value_set_idx) const
Similar to all_dynamic_values() but obtains the dynamic config in one specified slot as opposed to al...
static constexpr size_t S_N_D_VALUE_SETS
The number of dynamic value sets (including any Null_value_sets).
bool apply_impl(Option_set< Value_set > *opt_set, const Value_set *baseline_value_set_or_null, const fs::path &cfg_path, const boost::unordered_set< std::string > &all_opt_names_or_empty, const typename Final_validator_func< Value_set >::Type &final_validator_func, bool *skip_parsing)
Work-horse helper that parses into one given Option_set in m_s_d_opt_sets (from opt_set()) from the s...
Update_type m_multi_src_update_in_progress
In short, truthy if and only if a commit == false update is currently in progress,...
bool apply_static_impl(bool allow_invalid_defaults, const fs::path &static_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit)
Implements all apply_static() overloads.
static constexpr size_t S_N_VALUE_SETS
The number of template params in this Config_manager instantiation. It must be even and positive.
Config_manager(log::Logger *logger_ptr, util::String_view nickname, typename Option_set< S_d_value_set >::Declare_options_func &&... declare_opts_func_moved)
Constructs a Config_manager ready to read initial config via apply_*() and other setup methods; and f...
void help_to_ostream(std::ostream &os) const
Prints a human-targeted long-form usage message that includes all options with their descriptions and...
const Value_set & static_values_candidate(size_t s_value_set_idx) const
Similar to static_values(), but if called from within a validator function passed to apply_static() o...
bool apply_static(allow_invalid_defaults_tag_t, const fs::path &static_cfg_path, const typename Final_validator_func< Value_set >::Type &... final_validator_func, bool commit=true)
Identical to apply_static() overload without allow_invalid_defaults_tag_t tag; but skips the stringen...
const Option_set< Value_set > * opt_set(size_t value_set_idx) const
const overload of the other opt_set() helper.
void state_to_ostream_impl(size_t value_set_idx, std::ostream &os) const
Helper of state_to_ostream() for m_s_d_opt_sets slot value_set_idx.
The core config-parsing facility, which builds parsing/comparison/output capabilities on top of a giv...
Definition: option_set.hpp:422
const Values & values() const
Externally immutable internally stored canonical (current) config values as last constructed or parse...
void reject_candidate()
In PARSING state, returns to CANONICAL state, as if no parse attempts have occurred.
bool null() const
Return true if and only if the option-declaring function passed to the constructor declared no option...
void canonicalize_candidate(bool *change_detected=nullptr)
In PARSING state enters CANONICAL state, finalizing values() from values_candidate().
const Values * values_candidate() const
Returns null in CANONICAL state; or in PARSING state a pointer to the not-yet-canonical values after ...
void parse_direct_values(const Values &src_values)
Enters into (from CANONICAL state) or continues in PARSING state by simply setting *values_candidate(...
Convenience class that simply stores a Logger and/or Component passed into a constructor; and returns...
Definition: log.hpp:1786
Logger * get_logger() const
Returns the stored Logger pointer, particularly as many FLOW_LOG_*() macros expect.
Definition: log.cpp:260
Interface that the user should implement, passing the implementing Logger into logging classes (Flow'...
Definition: log.hpp:1392
Convenience class template that endows the given subclass T with nested aliases Ptr and Const_ptr ali...
Similar to ostringstream but allows fast read-only access directly into the std::string being written...
#define FLOW_LOG_INFO(ARG_stream_fragment)
Logs an INFO message into flow::log::Logger *get_logger() with flow::log::Component get_log_component...
Definition: log.hpp:200
#define FLOW_LOG_WARNING(ARG_stream_fragment)
Logs a WARNING message into flow::log::Logger *get_logger() with flow::log::Component get_log_compone...
Definition: log.hpp:155
#define FLOW_LOG_WITH_CHECKING(ARG_sev, ARG_stream_fragment)
Logs a message of the specified severity into flow::log::Logger *get_logger() with flow::log::Compone...
Definition: log.hpp:574
#define FLOW_LOG_TRACE(ARG_stream_fragment)
Logs a TRACE message into flow::log::Logger *get_logger() with flow::log::Component get_log_component...
Definition: log.hpp:230
Flow module that facilitates configuring modules, such as applications and APIs, via statically and/o...
Definition: cfg_fwd.hpp:112
Final_validator_outcome
Result enumeration for a Final_validator_func::Type function which is used by a Config_manager user w...
@ S_ACCEPT
The holistically-checked cumulative Value_set has no problems and shall be accepted into the candidat...
@ S_SKIP
The holistically-checked cumulative Value_set has contents such that the validator function decided t...
@ S_FAIL
The holistically-checked cumulative Value_set has invalid contents; the candidate shall be rejected,...
Option_set< Null_value_set >::Declare_options_func null_declare_opts_func()
Returns a value usable as declare_opts_func_moved Config_manager ctor arg for a Null_value_set value ...
Definition: cfg_manager.cpp:26
Final_validator_func< Null_value_set >::Type null_final_validator_func()
Returns a value usable as final_validator_func arg to Config_manager::apply_static() and others – for...
Definition: cfg_manager.cpp:31
std::ostream & operator<<(std::ostream &os, const Option_set< Value_set > &val)
Serializes (briefly) an Option_set to a standard output stream.
Sev
Enumeration containing one of several message severity levels, ordered from highest to lowest.
Definition: log_fwd.hpp:248
@ S_INFO
Message indicates a not-"bad" condition that is not frequent enough to be of severity Sev::S_TRACE.
boost::unique_lock< Mutex > Lock_guard
Short-hand for advanced-capability RAII lock guard for any mutex, ensuring exclusive ownership of tha...
Definition: util_fwd.hpp:298
std::string ostream_op_string(T &&... ostream_args)
Equivalent to ostream_op_to_string() but returns a new string by value instead of writing to the call...
Definition: util.hpp:575
boost::mutex Mutex_non_recursive
Short-hand for non-reentrant, exclusive mutex. ("Reentrant" = one can lock an already-locked-in-that-...
Definition: util_fwd.hpp:248
Basic_string_view< char > String_view
Commonly used char-based Basic_string_view. See its doc header.
Flow_log_component
The flow::log::Component payload enumeration comprising various log components used by Flow's own int...
Definition: common.hpp:627
Opaque handle for managing a dynamic config change callback.
std::list< On_dynamic_change_func >::const_iterator m_pos
Opaque handle detail.
Utility/traits type to concisely work with final-validation functions when calling methods like Confi...
Definition: cfg_manager.hpp:42
static Type null()
Returns a final-validator function that simply always returns Final_validator_outcome::S_ACCEPT.
Empty struct suitable as a *_value_set template arg for Config_manager, when a slot requires a Value_...
Definition: cfg_manager.hpp:74