105 route tests, matrix crawl, spec and README updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
696 lines
22 KiB
C++
696 lines
22 KiB
C++
#include "Platform.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
|
|
namespace molo::example::fw {
|
|
|
|
namespace {
|
|
|
|
std::string lower(std::string s) {
|
|
for (char& c : s) c = (char)std::tolower((unsigned char)c);
|
|
return s;
|
|
}
|
|
|
|
std::string trim(const std::string& s) {
|
|
std::size_t a = s.find_first_not_of(" \t");
|
|
if (a == std::string::npos) return "";
|
|
return s.substr(a, s.find_last_not_of(" \t") - a + 1);
|
|
}
|
|
|
|
std::vector<std::string> split(const std::string& s, char sep) {
|
|
std::vector<std::string> out;
|
|
std::size_t start = 0;
|
|
while (true) {
|
|
std::size_t at = s.find(sep, start);
|
|
out.push_back(trim(s.substr(start, at == std::string::npos ? at : at - start)));
|
|
if (at == std::string::npos) break;
|
|
start = at + 1;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// "gzip;q=0.5" -> token "gzip", q 0.5. Missing q is 1.
|
|
void token_q(const std::string& part, std::string& token, double& q) {
|
|
std::size_t semi = part.find(';');
|
|
token = lower(trim(part.substr(0, semi)));
|
|
q = 1.0;
|
|
if (semi == std::string::npos) return;
|
|
std::string rest = lower(trim(part.substr(semi + 1)));
|
|
if (rest.rfind("q=", 0) == 0) q = std::atof(rest.c_str() + 2);
|
|
}
|
|
|
|
bool parse_size(const std::string& s, std::size_t& out) {
|
|
if (s.empty() || s.size() > 15) return false;
|
|
std::size_t v = 0;
|
|
for (char c : s) {
|
|
if (c < '0' || c > '9') return false;
|
|
v = v * 10 + (std::size_t)(c - '0');
|
|
}
|
|
out = v;
|
|
return true;
|
|
}
|
|
|
|
std::string hex_pad(unsigned long long v, std::size_t digits) {
|
|
char buf[40];
|
|
std::snprintf(buf, sizeof(buf), "%0*llx", (int)digits, v);
|
|
std::string s = buf;
|
|
return s.substr(s.size() - digits);
|
|
}
|
|
|
|
|
|
} // namespace
|
|
|
|
// ---- i18n -----------------------------------------------------------------
|
|
|
|
int PluralRule::forms(const std::string& locale) {
|
|
if (locale == "ru") return 3;
|
|
if (locale == "ja") return 1;
|
|
return 2;
|
|
}
|
|
|
|
int PluralRule::index(const std::string& locale, long n) {
|
|
if (n < 0) n = -n;
|
|
if (locale == "ja") return 0;
|
|
if (locale == "fr") return n < 2 ? 0 : 1;
|
|
if (locale == "ru") {
|
|
if (n % 10 == 1 && n % 100 != 11) return 0;
|
|
if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) return 1;
|
|
return 2;
|
|
}
|
|
return n == 1 ? 0 : 1;
|
|
}
|
|
|
|
bool MessageCatalog::add(const std::string& locale, const std::string& msgid,
|
|
std::vector<std::string> forms) {
|
|
if (!data_.count(locale) && data_.size() >= platform_caps::kMaxLocales)
|
|
return false;
|
|
auto& msgs = data_[locale];
|
|
if (!msgs.count(msgid) && msgs.size() >= platform_caps::kMaxMessages)
|
|
return false;
|
|
msgs[msgid] = std::move(forms);
|
|
return true;
|
|
}
|
|
|
|
std::string MessageCatalog::translate(const std::string& locale,
|
|
const std::string& msgid, long n) const {
|
|
for (const std::string& loc : {locale, default_}) {
|
|
auto l = data_.find(loc);
|
|
if (l == data_.end()) continue;
|
|
auto m = l->second.find(msgid);
|
|
if (m == l->second.end() || m->second.empty()) continue;
|
|
std::size_t idx = (std::size_t)PluralRule::index(loc, n);
|
|
const std::string& form = m->second[std::min(idx, m->second.size() - 1)];
|
|
std::string out = form;
|
|
std::size_t at = out.find("%d");
|
|
if (at != std::string::npos) out.replace(at, 2, std::to_string(n));
|
|
return out;
|
|
}
|
|
return msgid;
|
|
}
|
|
|
|
std::vector<std::string> MessageCatalog::locales() const {
|
|
std::vector<std::string> out;
|
|
for (const auto& [k, v] : data_) out.push_back(k);
|
|
return out;
|
|
}
|
|
|
|
bool MessageCatalog::has_locale(const std::string& locale) const {
|
|
return data_.count(locale) > 0;
|
|
}
|
|
|
|
std::string MessageCatalog::to_po(const std::string& locale) const {
|
|
auto l = data_.find(locale);
|
|
std::string out = "msgid \"\"\nmsgstr \"\"\n\"Language: " + locale +
|
|
"\\n\"\n\"Plural-Forms: nplurals=" +
|
|
std::to_string(PluralRule::forms(locale)) + ";\\n\"\n";
|
|
if (l == data_.end()) return out;
|
|
for (const auto& [id, forms] : l->second) {
|
|
out += "\nmsgid \"" + id + "\"\n";
|
|
if (forms.size() == 1) {
|
|
out += "msgstr \"" + forms[0] + "\"\n";
|
|
} else {
|
|
out += "msgid_plural \"" + id + "\"\n";
|
|
for (std::size_t i = 0; i < forms.size(); ++i)
|
|
out += "msgstr[" + std::to_string(i) + "] \"" + forms[i] + "\"\n";
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
void MessageCatalog::set_default(std::string locale) {
|
|
default_ = std::move(locale);
|
|
}
|
|
const std::string& MessageCatalog::default_locale() const { return default_; }
|
|
|
|
std::string negotiate_locale(const std::string& lang_param,
|
|
const std::string& accept_language,
|
|
const MessageCatalog& catalog) {
|
|
std::string forced = lower(lang_param);
|
|
if (catalog.has_locale(forced)) return forced;
|
|
std::string best = catalog.default_locale();
|
|
double best_q = 0;
|
|
for (const std::string& part : split(accept_language, ',')) {
|
|
if (part.empty()) continue;
|
|
std::string tag;
|
|
double q;
|
|
token_q(part, tag, q);
|
|
std::string primary = tag.substr(0, tag.find('-'));
|
|
std::string pick = catalog.has_locale(tag) ? tag
|
|
: catalog.has_locale(primary) ? primary
|
|
: "";
|
|
if (!pick.empty() && q > best_q) {
|
|
best = pick;
|
|
best_q = q;
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
|
|
// ---- compression ----------------------------------------------------------
|
|
|
|
std::uint32_t crc32(const std::string& data) {
|
|
std::uint32_t crc = 0xFFFFFFFFu;
|
|
for (unsigned char c : data) {
|
|
crc ^= c;
|
|
for (int k = 0; k < 8; ++k) crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
|
|
}
|
|
return ~crc;
|
|
}
|
|
|
|
namespace {
|
|
void put_le32(std::string& out, std::uint32_t v) {
|
|
for (int i = 0; i < 4; ++i) out.push_back((char)((v >> (8 * i)) & 0xFF));
|
|
}
|
|
} // namespace
|
|
|
|
std::string gzip_stored(const std::string& data) {
|
|
std::string out("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff", 10);
|
|
std::size_t pos = 0;
|
|
do {
|
|
std::size_t n = std::min<std::size_t>(65535, data.size() - pos);
|
|
bool last = pos + n >= data.size();
|
|
out.push_back(last ? 1 : 0);
|
|
out.push_back((char)(n & 0xFF));
|
|
out.push_back((char)(n >> 8));
|
|
out.push_back((char)(~n & 0xFF));
|
|
out.push_back((char)((~n >> 8) & 0xFF));
|
|
out.append(data, pos, n);
|
|
pos += n;
|
|
} while (pos < data.size());
|
|
put_le32(out, crc32(data));
|
|
put_le32(out, (std::uint32_t)data.size());
|
|
return out;
|
|
}
|
|
|
|
bool accepts_encoding(const std::string& accept_encoding,
|
|
const std::string& coding) {
|
|
bool star = false;
|
|
for (const std::string& part : split(accept_encoding, ',')) {
|
|
std::string tag;
|
|
double q;
|
|
token_q(part, tag, q);
|
|
if (tag == coding) return q > 0;
|
|
if (tag == "*" && q > 0) star = true;
|
|
}
|
|
return star;
|
|
}
|
|
|
|
// ---- conditional GET and ranges -------------------------------------------
|
|
|
|
std::string make_etag(const std::string& body) {
|
|
std::uint64_t h = 1469598103934665603ull;
|
|
for (unsigned char c : body) {
|
|
h ^= c;
|
|
h *= 1099511628211ull;
|
|
}
|
|
return "\"" + hex_pad(h, 16) + "-" + std::to_string(body.size()) + "\"";
|
|
}
|
|
|
|
bool etag_matches(const std::string& header, const std::string& etag) {
|
|
if (trim(header) == "*") return true;
|
|
for (std::string tag : split(header, ',')) {
|
|
if (tag.rfind("W/", 0) == 0) tag = tag.substr(2);
|
|
if (!tag.empty() && tag == etag) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
ByteRange parse_range(const std::string& header, std::size_t size) {
|
|
ByteRange r;
|
|
if (header.rfind("bytes=", 0) != 0) return r;
|
|
std::string spec = trim(header.substr(6));
|
|
if (spec.find(',') != std::string::npos) return r;
|
|
std::size_t dash = spec.find('-');
|
|
if (dash == std::string::npos) return r;
|
|
std::string a = spec.substr(0, dash), b = spec.substr(dash + 1);
|
|
std::size_t first = 0, last = 0;
|
|
if (a.empty()) {
|
|
std::size_t n;
|
|
if (!parse_size(b, n)) return r;
|
|
r.kind = (n == 0 || size == 0) ? ByteRange::Kind::Unsatisfiable
|
|
: ByteRange::Kind::Ok;
|
|
if (r.kind == ByteRange::Kind::Ok) {
|
|
r.first = n >= size ? 0 : size - n;
|
|
r.last = size - 1;
|
|
}
|
|
return r;
|
|
}
|
|
if (!parse_size(a, first)) return r;
|
|
if (b.empty()) {
|
|
last = size ? size - 1 : 0;
|
|
} else if (!parse_size(b, last)) {
|
|
return r;
|
|
}
|
|
if (first >= size || first > last) {
|
|
r.kind = ByteRange::Kind::Unsatisfiable;
|
|
return r;
|
|
}
|
|
r.kind = ByteRange::Kind::Ok;
|
|
r.first = first;
|
|
r.last = std::min(last, size - 1);
|
|
return r;
|
|
}
|
|
|
|
// ---- health probes --------------------------------------------------------
|
|
|
|
bool HealthRegistry::add_check(const std::string& name, bool up) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
if (!checks_.count(name) && checks_.size() >= platform_caps::kMaxChecks)
|
|
return false;
|
|
checks_[name] = up;
|
|
return true;
|
|
}
|
|
|
|
bool HealthRegistry::set_check(const std::string& name, bool up) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
auto it = checks_.find(name);
|
|
if (it == checks_.end()) return false;
|
|
it->second = up;
|
|
return true;
|
|
}
|
|
|
|
bool HealthRegistry::add_startup_task(const std::string& name, bool done) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
if (!tasks_.count(name) && tasks_.size() >= platform_caps::kMaxChecks)
|
|
return false;
|
|
tasks_[name] = done;
|
|
return true;
|
|
}
|
|
|
|
bool HealthRegistry::set_startup_task(const std::string& name, bool done) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
auto it = tasks_.find(name);
|
|
if (it == tasks_.end()) return false;
|
|
it->second = done;
|
|
return true;
|
|
}
|
|
|
|
bool HealthRegistry::startup_complete() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
for (const auto& [k, v] : tasks_)
|
|
if (!v) return false;
|
|
return true;
|
|
}
|
|
|
|
bool HealthRegistry::ready() const {
|
|
if (!startup_complete()) return false;
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
for (const auto& [k, v] : checks_)
|
|
if (!v) return false;
|
|
return true;
|
|
}
|
|
|
|
namespace {
|
|
std::string bool_map_json(const std::map<std::string, bool>& m,
|
|
const char* up, const char* down) {
|
|
std::string out = "{";
|
|
bool first = true;
|
|
for (const auto& [k, v] : m) {
|
|
out += std::string(first ? "" : ",") + "\"" + json_escape(k) + "\":\"" +
|
|
(v ? up : down) + "\"";
|
|
first = false;
|
|
}
|
|
return out + "}";
|
|
}
|
|
} // namespace
|
|
|
|
std::string HealthRegistry::liveness_json() const {
|
|
long up = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::steady_clock::now() - started_)
|
|
.count();
|
|
return "{\"status\":\"alive\",\"uptime_seconds\":" + std::to_string(up) + "}";
|
|
}
|
|
|
|
std::string HealthRegistry::readiness_json() const {
|
|
bool ok = ready();
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
return std::string("{\"status\":\"") + (ok ? "ready" : "not_ready") +
|
|
"\",\"checks\":" + bool_map_json(checks_, "up", "down") + "}";
|
|
}
|
|
|
|
std::string HealthRegistry::startup_json() const {
|
|
bool ok = startup_complete();
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
return std::string("{\"status\":\"") + (ok ? "started" : "starting") +
|
|
"\",\"tasks\":" + bool_map_json(tasks_, "done", "pending") + "}";
|
|
}
|
|
|
|
// ---- Prometheus -----------------------------------------------------------
|
|
|
|
PrometheusExporter::PrometheusExporter(const Metrics* metrics,
|
|
const Stats* stats)
|
|
: metrics_(metrics), stats_(stats) {}
|
|
|
|
std::string PrometheusExporter::sanitize(const std::string& name) {
|
|
std::string out;
|
|
for (char c : name) {
|
|
bool ok = std::isalnum((unsigned char)c) || c == '_' || c == ':';
|
|
out.push_back(ok ? c : '_');
|
|
}
|
|
if (out.empty() || std::isdigit((unsigned char)out[0])) out.insert(0, "_");
|
|
return out;
|
|
}
|
|
|
|
std::string PrometheusExporter::render() const {
|
|
std::string out;
|
|
auto sample = [&out](const std::string& name, const char* type,
|
|
const std::string& help, const std::string& value) {
|
|
out += "# HELP " + name + " " + help + "\n# TYPE " + name + " " + type +
|
|
"\n" + name + " " + value + "\n";
|
|
};
|
|
sample("molo_http_requests_total", "counter", "Requests served.",
|
|
std::to_string(stats_->total_requests()));
|
|
sample("molo_http_connections_total", "counter", "Connections accepted.",
|
|
std::to_string(stats_->total_connections()));
|
|
sample("molo_http_connections_active", "gauge", "Open connections.",
|
|
std::to_string(stats_->active_connections()));
|
|
for (const auto& [k, v] : metrics_->snapshot()) {
|
|
char buf[64];
|
|
std::snprintf(buf, sizeof(buf), "%g", v);
|
|
sample("molo_example_" + sanitize(k), "gauge",
|
|
"Example metric " + k + ".", buf);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ---- structured logging ---------------------------------------------------
|
|
|
|
bool parse_level(const std::string& name, LogLevel& out) {
|
|
std::string n = lower(name);
|
|
if (n == "debug") out = LogLevel::Debug;
|
|
else if (n == "info") out = LogLevel::Info;
|
|
else if (n == "warn") out = LogLevel::Warn;
|
|
else if (n == "error") out = LogLevel::Error;
|
|
else return false;
|
|
return true;
|
|
}
|
|
|
|
std::string level_name(LogLevel level) {
|
|
switch (level) {
|
|
case LogLevel::Debug: return "debug";
|
|
case LogLevel::Info: return "info";
|
|
case LogLevel::Warn: return "warn";
|
|
case LogLevel::Error: return "error";
|
|
}
|
|
return "info";
|
|
}
|
|
|
|
std::string LogRing::redact(const std::string& message) {
|
|
static const char* keys[] = {"password", "passwd", "token", "secret",
|
|
"authorization", "api_key", "apikey"};
|
|
std::string out = message;
|
|
std::string low = lower(out);
|
|
for (const char* key : keys) {
|
|
std::string k = key;
|
|
std::size_t from = 0;
|
|
while ((from = low.find(k, from)) != std::string::npos) {
|
|
std::size_t p = from + k.size();
|
|
from = p;
|
|
if (p >= out.size() || (out[p] != '=' && out[p] != ':')) continue;
|
|
++p;
|
|
while (p < out.size() && out[p] == ' ') ++p;
|
|
std::size_t e = p;
|
|
while (e < out.size() && !std::isspace((unsigned char)out[e]) &&
|
|
out[e] != ',' && out[e] != ';' && out[e] != '&')
|
|
++e;
|
|
out.replace(p, e - p, "***");
|
|
low = lower(out);
|
|
from = p;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
void LogRing::log(LogLevel level, std::string message,
|
|
std::string correlation_id) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
if (level < min_) {
|
|
++filtered_;
|
|
return;
|
|
}
|
|
LogRecord r;
|
|
r.seq = next_seq_++;
|
|
r.ts = (long)std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::system_clock::now().time_since_epoch())
|
|
.count();
|
|
r.level = level;
|
|
if (message.size() > platform_caps::kLogMessage)
|
|
message.resize(platform_caps::kLogMessage);
|
|
r.message = redact(message);
|
|
r.correlation_id = std::move(correlation_id);
|
|
ring_.push_back(std::move(r));
|
|
while (ring_.size() > platform_caps::kLogRing) ring_.pop_front();
|
|
}
|
|
|
|
std::vector<LogRecord> LogRing::last(std::size_t n, LogLevel min) const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
std::vector<LogRecord> out;
|
|
for (auto it = ring_.rbegin(); it != ring_.rend() && out.size() < n; ++it)
|
|
if (it->level >= min) out.push_back(*it);
|
|
return out;
|
|
}
|
|
|
|
void LogRing::set_min_level(LogLevel level) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
min_ = level;
|
|
}
|
|
LogLevel LogRing::min_level() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
return min_;
|
|
}
|
|
std::size_t LogRing::size() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
return ring_.size();
|
|
}
|
|
unsigned long LogRing::dropped_below_min() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
return filtered_;
|
|
}
|
|
|
|
std::string LogRing::to_json(const LogRecord& r) {
|
|
return "{\"seq\":" + std::to_string(r.seq) + ",\"ts\":" +
|
|
std::to_string(r.ts) + ",\"level\":\"" + level_name(r.level) +
|
|
"\",\"msg\":\"" + json_escape(r.message) + "\",\"correlation_id\":\"" +
|
|
json_escape(r.correlation_id) + "\"}";
|
|
}
|
|
|
|
// ---- trace context --------------------------------------------------------
|
|
|
|
std::string TraceContext::traceparent() const {
|
|
return "00-" + trace_id + "-" + span_id + "-" + flags;
|
|
}
|
|
|
|
std::string TraceContextFactory::next_hex(std::size_t digits) {
|
|
unsigned long long v = ++counter_;
|
|
v *= 0x9E3779B97F4A7C15ull;
|
|
std::string out = hex_pad(v, 16);
|
|
while (out.size() < digits) out += hex_pad(v * (out.size() + 7), 16);
|
|
return out.substr(0, digits);
|
|
}
|
|
|
|
TraceContext TraceContextFactory::from_header(const std::string& header) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
TraceContext ctx;
|
|
ctx.had_parent = !header.empty();
|
|
auto parts = split(header, '-');
|
|
auto is_hex = [](const std::string& s) {
|
|
return !s.empty() && std::all_of(s.begin(), s.end(), [](char c) {
|
|
return std::isxdigit((unsigned char)c) && !std::isupper((unsigned char)c);
|
|
});
|
|
};
|
|
bool ok = parts.size() == 4 && parts[0].size() == 2 && is_hex(parts[0]) &&
|
|
parts[0] != "ff" && parts[1].size() == 32 && is_hex(parts[1]) &&
|
|
parts[1] != std::string(32, '0') && parts[2].size() == 16 &&
|
|
is_hex(parts[2]) && parts[2] != std::string(16, '0') &&
|
|
parts[3].size() == 2 && is_hex(parts[3]);
|
|
if (ok) {
|
|
ctx.trace_id = parts[1];
|
|
ctx.parent_span_id = parts[2];
|
|
ctx.flags = parts[3];
|
|
} else {
|
|
ctx.parent_valid = !ctx.had_parent;
|
|
ctx.trace_id = next_hex(32);
|
|
}
|
|
ctx.span_id = next_hex(16);
|
|
return ctx;
|
|
}
|
|
|
|
// ---- DI registry ----------------------------------------------------------
|
|
|
|
std::string lifetime_name(Lifetime l) {
|
|
switch (l) {
|
|
case Lifetime::Singleton: return "singleton";
|
|
case Lifetime::Scoped: return "scoped";
|
|
case Lifetime::Transient: return "transient";
|
|
}
|
|
return "singleton";
|
|
}
|
|
|
|
bool ServiceRegistry::add(const std::string& name, Lifetime lifetime,
|
|
std::function<std::string()> factory) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
if (!slots_.count(name) && slots_.size() >= platform_caps::kMaxServices)
|
|
return false;
|
|
Slot s;
|
|
s.lifetime = lifetime;
|
|
s.factory = std::move(factory);
|
|
slots_[name] = std::move(s);
|
|
return true;
|
|
}
|
|
|
|
bool ServiceRegistry::resolve(const std::string& name, const std::string& scope,
|
|
std::string& out) {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
auto it = slots_.find(name);
|
|
if (it == slots_.end()) return false;
|
|
Slot& s = it->second;
|
|
++s.resolved;
|
|
if (s.lifetime == Lifetime::Singleton) {
|
|
if (!s.built) {
|
|
s.instance = s.factory();
|
|
s.built = true;
|
|
++s.created;
|
|
}
|
|
out = s.instance;
|
|
} else if (s.lifetime == Lifetime::Scoped) {
|
|
auto sc = s.scoped.find(scope);
|
|
if (sc == s.scoped.end()) {
|
|
if (s.scoped.size() >= 16) s.scoped.clear();
|
|
sc = s.scoped.emplace(scope, s.factory()).first;
|
|
++s.created;
|
|
}
|
|
out = sc->second;
|
|
} else {
|
|
out = s.factory();
|
|
++s.created;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::vector<ServiceRegistry::Entry> ServiceRegistry::list() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
std::vector<Entry> out;
|
|
for (const auto& [k, s] : slots_)
|
|
out.push_back({k, s.lifetime, s.created, s.resolved});
|
|
return out;
|
|
}
|
|
|
|
// ---- flash messages -------------------------------------------------------
|
|
|
|
std::string FlashCodec::encode(const std::string& message) {
|
|
std::string m = message.substr(0, platform_caps::kFlashBytes);
|
|
std::string out;
|
|
for (unsigned char c : m) out += hex_pad(c, 2);
|
|
return out;
|
|
}
|
|
|
|
bool FlashCodec::decode(const std::string& cookie, std::string& message) {
|
|
if (cookie.empty() || cookie.size() % 2 || cookie.size() > platform_caps::kFlashBytes * 2)
|
|
return false;
|
|
std::string out;
|
|
for (std::size_t i = 0; i < cookie.size(); i += 2) {
|
|
if (!std::isxdigit((unsigned char)cookie[i]) ||
|
|
!std::isxdigit((unsigned char)cookie[i + 1]))
|
|
return false;
|
|
out.push_back((char)std::stoi(cookie.substr(i, 2), nullptr, 16));
|
|
}
|
|
message = out;
|
|
return true;
|
|
}
|
|
|
|
// ---- expose stats ---------------------------------------------------------
|
|
|
|
namespace {
|
|
constexpr std::size_t kBuckets =
|
|
(std::size_t)(platform_caps::kExposeWindowSec / platform_caps::kExposeBucketSec);
|
|
}
|
|
|
|
ExposeStats::ExposeStats(long (*now_sec)()) : clock_(now_sec) {}
|
|
|
|
void ExposeStats::set_clock(long (*now_sec)()) { clock_ = now_sec; }
|
|
|
|
long ExposeStats::now() const {
|
|
if (clock_) return clock_();
|
|
return (long)std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::system_clock::now().time_since_epoch())
|
|
.count();
|
|
}
|
|
|
|
bool ExposeStats::known_method(const std::string& m) {
|
|
static const char* names[] = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};
|
|
for (const char* n : names)
|
|
if (m == n) return true;
|
|
return false;
|
|
}
|
|
|
|
bool ExposeStats::record(const std::string& method, unsigned long up,
|
|
unsigned long down, unsigned long micros) {
|
|
if (!known_method(method)) return false;
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
ExposeRow& row = rows_[method];
|
|
++row.count;
|
|
row.bytes_up += up;
|
|
row.bytes_down += down;
|
|
row.micros += micros;
|
|
auto& win = windows_[method];
|
|
if (win.empty()) win.resize(kBuckets);
|
|
long slot = now() / platform_caps::kExposeBucketSec;
|
|
Bucket& b = win[(std::size_t)slot % kBuckets];
|
|
if (b.slot != slot) b = Bucket{slot, 0, 0};
|
|
b.up += up;
|
|
b.down += down;
|
|
return true;
|
|
}
|
|
|
|
std::map<std::string, ExposeRow> ExposeStats::snapshot() const {
|
|
std::lock_guard<std::mutex> lock(mu_);
|
|
std::map<std::string, ExposeRow> out;
|
|
ExposeRow total;
|
|
long cur = now() / platform_caps::kExposeBucketSec;
|
|
for (const auto& [m, row] : rows_) {
|
|
ExposeRow r = row;
|
|
unsigned long up = 0, down = 0;
|
|
for (const Bucket& b : windows_.at(m))
|
|
if (b.slot > cur - (long)kBuckets && b.slot <= cur) {
|
|
up += b.up;
|
|
down += b.down;
|
|
}
|
|
r.kb_s_up = up / 1024.0 / platform_caps::kExposeWindowSec;
|
|
r.kb_s_down = down / 1024.0 / platform_caps::kExposeWindowSec;
|
|
total.count += r.count;
|
|
total.bytes_up += r.bytes_up;
|
|
total.bytes_down += r.bytes_down;
|
|
total.micros += r.micros;
|
|
total.kb_s_up += r.kb_s_up;
|
|
total.kb_s_down += r.kb_s_down;
|
|
out[m] = r;
|
|
}
|
|
out["_total"] = total;
|
|
return out;
|
|
}
|
|
|
|
} // namespace molo::example::fw
|