Repository navigation
Expand file tree
/
Copy pathConfig.cpp
More file actions
633 lines (522 loc) · 14.8 KB
/
Copy pathConfig.cpp
File metadata and controls
633 lines (522 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/**
*
* @file Config.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license that can be found in the License file.
*
* Vix.cpp
*
*/
#include <vix/config/Config.hpp>
#include <vix/json/json.hpp>
#include <vix/env/EnvFileOptions.hpp>
#include <vix/env/Get.hpp>
#include <vix/env/GetBool.hpp>
#include <vix/env/GetInt.hpp>
#include <vix/env/LoadIntoProcess.hpp>
#include <algorithm>
#include <cctype>
#include <stdexcept>
#include <string>
#include <utility>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
namespace vix::config
{
struct Config::RawConfigState
{
RawConfigState() : value(vix::json::Json::object()) {}
vix::json::Json value;
};
namespace
{
[[nodiscard]] std::string trim_copy(std::string value)
{
auto not_space = [](unsigned char ch)
{ return !std::isspace(ch); };
value.erase(
value.begin(),
std::find_if(value.begin(), value.end(), not_space));
value.erase(
std::find_if(value.rbegin(), value.rend(), not_space).base(),
value.end());
return value;
}
[[nodiscard]] std::string to_upper_ascii(std::string value)
{
std::transform(
value.begin(),
value.end(),
value.begin(),
[](unsigned char c)
{ return static_cast<char>(std::toupper(c)); });
return value;
}
[[nodiscard]] std::string normalize_env_name(std::string value)
{
value = trim_copy(std::move(value));
if (value.empty() || value == ".env")
{
return {};
}
if (value.rfind(".env.", 0) == 0)
{
value.erase(0, 5);
}
return value;
}
[[nodiscard]] std::string dotted_to_env_key(const std::string &dottedKey)
{
std::string out;
out.reserve(dottedKey.size());
for (const char c : dottedKey)
{
if (c == '.')
{
out.push_back('_');
}
else
{
out.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
}
}
return out;
}
[[nodiscard]] std::string get_env_string(
const std::string &envKey,
const std::string &defaultValue)
{
auto value = vix::env::get(envKey);
if (!value)
{
return defaultValue;
}
return value.value();
}
[[nodiscard]] int get_env_int(
const std::string &envKey,
int defaultValue)
{
auto value = vix::env::get_int(envKey);
if (!value)
{
return defaultValue;
}
return value.value();
}
[[nodiscard]] bool get_env_bool(
const std::string &envKey,
bool defaultValue)
{
auto value = vix::env::get_bool(envKey);
if (!value)
{
return defaultValue;
}
return value.value();
}
} // namespace
Config::Config(const std::filesystem::path &configPath)
: configPath_(configPath),
configPathExplicit_(!configPath.empty()),
db_host(DEFAULT_DB_HOST),
db_user(DEFAULT_DB_USER),
db_pass(DEFAULT_DB_PASS),
db_name(DEFAULT_DB_NAME),
db_port(DEFAULT_DB_PORT),
server_port(DEFAULT_SERVER_PORT),
request_timeout(DEFAULT_REQUEST_TIMEOUT),
rawConfig_(std::make_shared<RawConfigState>()),
io_threads_(DEFAULT_IO_THREADS),
log_async_(DEFAULT_LOG_ASYNC),
log_queue_max_(DEFAULT_LOG_QUEUE_MAX),
log_drop_on_overflow_(DEFAULT_LOG_DROP_ON_OVERFLOW),
waf_mode_(DEFAULT_WAF_MODE),
waf_max_target_len_(DEFAULT_WAF_MAX_TARGET_LEN),
waf_max_body_bytes_(DEFAULT_WAF_MAX_BODY_BYTES),
session_timeout_sec_(DEFAULT_SESSION_TIMEOUT_SEC),
bench_mode_(DEFAULT_BENCH_MODE),
tls_enabled_(DEFAULT_TLS_ENABLED),
tls_cert_file_(DEFAULT_TLS_CERT_FILE),
tls_key_file_(DEFAULT_TLS_KEY_FILE)
{
if (configPath_.empty())
{
configPath_ = ".env";
}
loadConfig();
}
void Config::loadConfig()
{
rawConfig_ = std::make_shared<RawConfigState>();
vix::env::EnvFileOptions env_options{};
env_options.base_dir = configPath_.has_parent_path()
? configPath_.parent_path().string()
: ".";
env_options.filename = ".env";
env_options.mode = vix::env::EnvFileMode::Layered;
env_options.load_base_file = true;
env_options.load_local_file = true;
env_options.ignore_missing_files = true;
env_options.env.overwrite_existing = configPathExplicit_;
const std::string config_filename = configPath_.filename().string();
const std::string environment_name = normalize_env_name(config_filename);
if (!environment_name.empty())
{
env_options.environment_name = environment_name;
env_options.load_environment_file = true;
env_options.load_environment_local_file = true;
}
if (auto err = vix::env::load_layered_into_process(env_options); err)
{
throw std::runtime_error(
"Failed to load environment configuration: " +
std::string(err.message()));
}
db_host = get_env_string("DATABASE_DEFAULT_HOST", DEFAULT_DB_HOST);
db_user = get_env_string("DATABASE_DEFAULT_USER", DEFAULT_DB_USER);
db_name = get_env_string("DATABASE_DEFAULT_NAME", DEFAULT_DB_NAME);
db_port = get_env_int("DATABASE_DEFAULT_PORT", DEFAULT_DB_PORT);
db_pass = getDbPasswordFromEnv();
server_port = get_env_int("SERVER_PORT", DEFAULT_SERVER_PORT);
request_timeout = get_env_int("SERVER_REQUEST_TIMEOUT", DEFAULT_REQUEST_TIMEOUT);
io_threads_ = get_env_int("SERVER_IO_THREADS", DEFAULT_IO_THREADS);
session_timeout_sec_ =
get_env_int("SERVER_SESSION_TIMEOUT_SEC", DEFAULT_SESSION_TIMEOUT_SEC);
bench_mode_ = get_env_bool("SERVER_BENCH_MODE", DEFAULT_BENCH_MODE);
tls_enabled_ = get_env_bool("SERVER_TLS_ENABLED", DEFAULT_TLS_ENABLED);
tls_cert_file_ = get_env_string("SERVER_TLS_CERT_FILE", DEFAULT_TLS_CERT_FILE);
tls_key_file_ = get_env_string("SERVER_TLS_KEY_FILE", DEFAULT_TLS_KEY_FILE);
log_async_ = get_env_bool("LOGGING_ASYNC", DEFAULT_LOG_ASYNC);
log_queue_max_ = get_env_int("LOGGING_QUEUE_MAX", DEFAULT_LOG_QUEUE_MAX);
log_drop_on_overflow_ =
get_env_bool("LOGGING_DROP_ON_OVERFLOW", DEFAULT_LOG_DROP_ON_OVERFLOW);
waf_mode_ = get_env_string("WAF_MODE", DEFAULT_WAF_MODE);
waf_max_target_len_ =
get_env_int("WAF_MAX_TARGET_LEN", DEFAULT_WAF_MAX_TARGET_LEN);
waf_max_body_bytes_ =
get_env_int("WAF_MAX_BODY_BYTES", DEFAULT_WAF_MAX_BODY_BYTES);
}
#if VIX_CORE_WITH_MYSQL
std::shared_ptr<sql::Connection> Config::getDbConnection()
{
return {};
}
#endif
std::string Config::getDbPasswordFromEnv() const
{
if (auto value = vix::env::get("VIX_DB_PASSWORD"); value && !value.value().empty())
{
return value.value();
}
if (auto value = vix::env::get("DATABASE_DEFAULT_PASSWORD"); value && !value.value().empty())
{
return value.value();
}
if (auto value = vix::env::get("DB_PASSWORD"); value && !value.value().empty())
{
return value.value();
}
if (auto value = vix::env::get("MYSQL_PASSWORD"); value && !value.value().empty())
{
return value.value();
}
return DEFAULT_DB_PASS;
}
void Config::set(const std::string &dottedKey, const vix::json::Json &value)
{
if (dottedKey.empty())
{
return;
}
if (rawConfig_.use_count() > 1)
{
rawConfig_ = std::make_shared<RawConfigState>(*rawConfig_);
}
vix::json::Json *node = &rawConfig_->value;
std::size_t start = 0;
while (start < dottedKey.size())
{
const std::size_t dot = dottedKey.find('.', start);
const std::string key =
dottedKey.substr(start, dot == std::string::npos ? std::string::npos : dot - start);
if (dot == std::string::npos)
{
(*node)[key] = value;
return;
}
node = &((*node)[key]);
start = dot + 1;
}
}
void Config::set(const std::string &dottedKey, std::string_view value)
{
set(dottedKey, vix::json::Json(value));
}
void Config::set(const std::string &dottedKey, const char *value)
{
if (value == nullptr)
{
set(dottedKey, vix::json::Json(nullptr));
return;
}
set(dottedKey, std::string_view(value));
}
void Config::set(const std::string &dottedKey, bool value)
{
set(dottedKey, vix::json::Json(value));
}
void Config::setInteger(const std::string &dottedKey, std::int64_t value)
{
set(dottedKey, vix::json::Json(value));
}
void Config::setNumber(const std::string &dottedKey, double value)
{
set(dottedKey, vix::json::Json(value));
}
const std::string &Config::getDbHost() const noexcept
{
return db_host;
}
const std::string &Config::getDbUser() const noexcept
{
return db_user;
}
const std::string &Config::getDbName() const noexcept
{
return db_name;
}
int Config::getDbPort() const noexcept
{
return db_port;
}
int Config::getServerPort() const noexcept
{
return server_port;
}
int Config::getRequestTimeout() const noexcept
{
return request_timeout;
}
void Config::setServerPort(int port)
{
server_port = port;
set("server.port", port);
}
const vix::json::Json *Config::findNode(const std::string &dottedKey) const noexcept
{
if (dottedKey.empty())
{
return nullptr;
}
const vix::json::Json *node = &rawConfig_->value;
std::size_t start = 0;
while (start < dottedKey.size())
{
const std::size_t dot = dottedKey.find('.', start);
const std::string key =
dottedKey.substr(start, dot == std::string::npos ? std::string::npos : dot - start);
if (!node->is_object())
{
return nullptr;
}
auto it = node->find(key);
if (it == node->end())
{
return nullptr;
}
node = &(*it);
if (dot == std::string::npos)
{
break;
}
start = dot + 1;
}
return node;
}
bool Config::has(const std::string &dottedKey) const noexcept
{
if (findNode(dottedKey) != nullptr)
{
return true;
}
auto env_value = vix::env::get(dotted_to_env_key(dottedKey));
return static_cast<bool>(env_value);
}
int Config::getInt(const std::string &dottedKey, int defaultValue) const noexcept
{
const vix::json::Json *node = findNode(dottedKey);
if (node)
{
if (node->is_number_integer())
{
return node->get<int>();
}
if (node->is_number_unsigned())
{
return static_cast<int>(node->get<unsigned int>());
}
if (node->is_number_float())
{
return static_cast<int>(node->get<double>());
}
if (node->is_boolean())
{
return node->get<bool>() ? 1 : 0;
}
if (node->is_string())
{
try
{
const std::string &value = node->get_ref<const std::string &>();
std::size_t pos = 0;
const int parsed = std::stoi(value, &pos);
if (pos == value.size())
{
return parsed;
}
}
catch (...)
{
}
}
// A raw value is authoritative. If it cannot be converted, use the
// caller's fallback instead of silently falling through to the process
// environment.
return defaultValue;
}
return get_env_int(dotted_to_env_key(dottedKey), defaultValue);
}
bool Config::getBool(const std::string &dottedKey, bool defaultValue) const noexcept
{
const vix::json::Json *node = findNode(dottedKey);
if (node)
{
if (node->is_boolean())
{
return node->get<bool>();
}
if (node->is_number_integer())
{
return node->get<int>() != 0;
}
if (node->is_number_unsigned())
{
return node->get<unsigned int>() != 0U;
}
if (node->is_string())
{
const std::string value = to_upper_ascii(node->get<std::string>());
if (value == "1" || value == "TRUE" || value == "YES" || value == "ON")
{
return true;
}
if (value == "0" || value == "FALSE" || value == "NO" || value == "OFF")
{
return false;
}
}
// Do not let an invalid raw value be overridden by an environment
// value; the raw configuration still owns this key.
return defaultValue;
}
return get_env_bool(dotted_to_env_key(dottedKey), defaultValue);
}
std::string Config::getString(
const std::string &dottedKey,
const std::string &defaultValue) const noexcept
{
const vix::json::Json *node = findNode(dottedKey);
if (node)
{
if (node->is_string())
{
return node->get<std::string>();
}
if (node->is_boolean())
{
return node->get<bool>() ? "true" : "false";
}
if (node->is_number_integer())
{
return std::to_string(node->get<int>());
}
if (node->is_number_unsigned())
{
return std::to_string(node->get<unsigned int>());
}
if (node->is_number_float())
{
return std::to_string(node->get<double>());
}
// null, arrays and objects are present but not string-convertible.
// Their presence must prevent an environment fallback.
return defaultValue;
}
return get_env_string(dotted_to_env_key(dottedKey), defaultValue);
}
int Config::getIOThreads() const noexcept
{
return io_threads_;
}
bool Config::isBenchMode() const noexcept
{
#ifdef VIX_BENCH_MODE
return true;
#else
return bench_mode_;
#endif
}
bool Config::getLogAsync() const noexcept
{
return log_async_;
}
int Config::getLogQueueMax() const noexcept
{
return log_queue_max_;
}
bool Config::getLogDropOnOverflow() const noexcept
{
return log_drop_on_overflow_;
}
const std::string &Config::getWafMode() const noexcept
{
return waf_mode_;
}
int Config::getWafMaxTargetLen() const noexcept
{
return waf_max_target_len_;
}
int Config::getWafMaxBodyBytes() const noexcept
{
return waf_max_body_bytes_;
}
int Config::getSessionTimeoutSec() const noexcept
{
return session_timeout_sec_;
}
bool Config::isTlsEnabled() const noexcept
{
return tls_enabled_;
}
const std::string &Config::getTlsCertFile() const noexcept
{
return tls_cert_file_;
}
const std::string &Config::getTlsKeyFile() const noexcept
{
return tls_key_file_;
}
vix::server::TlsConfig Config::getTlsConfig() const
{
vix::server::TlsConfig cfg{};
cfg.enabled = tls_enabled_;
cfg.cert_file = tls_cert_file_;
cfg.key_file = tls_key_file_;
return cfg;
}
} // namespace vix::config