diff --git a/doc/webapp-guide.md b/doc/webapp-guide.md index 57c4a69e..d3e8b9e2 100644 --- a/doc/webapp-guide.md +++ b/doc/webapp-guide.md @@ -40,6 +40,7 @@ 17. [安全](#17-安全) 18. [已知限制](#18-已知限制) 19. [横向扩展:多循环(`set_loops`)](#19-横向扩展多循环set_loops) +20. [可观测性:`/health` / `/ready` / `/metrics`](#20-可观测性health--ready--metrics) --- @@ -1534,6 +1535,39 @@ join() 已等 N ms,仍有 M 条循环没退出(停机扇出或某条循环 --- +## 20. 可观测性:`/health` / `/ready` / `/metrics` + +`uvcpp_metrics_registry`(核心层,不依赖 webapp)+ `uvcpp_web_metrics`(端点): + +```cpp +// doc-snippet: fragment — 装配摘录,不是完整翻译单元。 +uvcpp::uvcpp_metrics_registry reg; +uvcpp::uvcpp_web_metrics metrics(reg); + +uvcpp::uvcpp_web_app app; +metrics.install(app); // /health /ready /metrics + 请求计数/耗时 +metrics.set_ready_check([](std::string& why) { + return db_pool_healthy(why); // false 时 why 里写一句人读原因 +}); + +// 数值本来在别处维护 → 回调 Gauge,render 那一刻取值 +reg.register_gauge("db_pool_in_use", "Borrowed connections", + [&pool] { return static_cast(pool.in_use()); }); +``` + +- `/health`:恒 200(liveness 不查依赖 —— 数据库挂了该摘流量,不该重启进程)。 +- `/ready`:`set_ready_check()` 返回 false 时 **503**,body 带原因;每个请求现问一次。 +- `/metrics`:Prometheus 文本(`text/plain; version=0.0.4`)。 +- 请求指标(默认开,注册成**最外层**中间件):`http_requests_total{method,status}`、 + `http_request_duration_ms{method}`(默认桶 1..10000 ms)、`http_requests_in_flight`; + 另有 `uvcpp_web_app_connections` 回调 Gauge。 +- **标签里不放 URL 原串**(高基数);要按路由看,在路由里自己 `reg.inc(..., + {{"route", "/user/:id"}})`。 +- 不 `install()` 就零成本:没有后台线程、没有定时器、没有全局单例。 + 用例:`web_app_metrics_func.cpp`。 + +--- + ## 可运行示例 `examples/webapp_demo.cpp` —— 默认**自校验**:起一个 app(路由 + 中间件 + 静态 + diff --git a/src/uvcpp/uvcpp_metrics_registry.cpp b/src/uvcpp/uvcpp_metrics_registry.cpp new file mode 100644 index 00000000..1367b88d --- /dev/null +++ b/src/uvcpp/uvcpp_metrics_registry.cpp @@ -0,0 +1,348 @@ +/** + * @file src/uvcpp/uvcpp_metrics_registry.cpp + * @brief 指标注册表的实现。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "uvcpp/uvcpp_metrics_registry.h" + +#include +#include +#include +#include +#include + +namespace uvcpp { + +namespace { + +void escape_label_value(const std::string& in, std::string& out) { + out.reserve(out.size() + in.size()); + for (size_t i = 0; i < in.size(); ++i) { + const char c = in[i]; + switch (c) { + case '\\': out += "\\\\"; break; + case '"': out += "\\\""; break; + case '\n': out += "\\n"; break; + default: out += c; break; + } + } +} + +/// 标签序列化:**先按名字排序**,再拼 `name="value",...`。同组标签的字节稳定 +/// 是 Prometheus 把两行认成"同一个时间序列"的前提。 +std::string label_key(const uvcpp_metric_labels& labels) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + std::string out; + for (size_t i = 0; i < sorted.size(); ++i) { + if (i != 0) out += ','; + out += sorted[i].name; + out += '='; + out += sorted[i].value; // 键里不需要转义,只要不歧义 + } + return out; +} + +std::string render_labels(const uvcpp_metric_labels& labels) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + std::string out = "{"; + for (size_t i = 0; i < sorted.size(); ++i) { + if (i != 0) out += ','; + out += sorted[i].name; + out += "=\""; + escape_label_value(sorted[i].value, out); + out += '"'; + } + out += '}'; + return out; +} + +/// 数值输出:整数不带小数点(好看且省字节),其余用 10 位有效数字。 +std::string fmt_double(double v) { + char buf[64]; + if (std::isfinite(v) && v == std::floor(v) && std::fabs(v) < 1e15) { + std::snprintf(buf, sizeof(buf), "%lld", + static_cast(v)); + } else if (std::isnan(v)) { + return "NaN"; + } else if (std::isinf(v)) { + return v > 0 ? "+Inf" : "-Inf"; + } else { + std::snprintf(buf, sizeof(buf), "%.10g", v); + } + return std::string(buf); +} + +} // namespace + +std::string uvcpp_metric_label_string(const uvcpp_metric_labels& labels) { + if (labels.empty()) return std::string(); + return render_labels(labels); +} + +std::vector uvcpp_metrics_registry::default_buckets() { + const double b[] = {1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, + 10000}; + return std::vector(b, b + sizeof(b) / sizeof(b[0])); +} + +uvcpp_metrics_registry::uvcpp_metrics_registry() {} +uvcpp_metrics_registry::~uvcpp_metrics_registry() {} + +uvcpp_metrics_registry::family& uvcpp_metrics_registry::family_for( + const std::string& name, family::kind_t kind) { + std::map::iterator it = families_.find(name); + if (it == families_.end()) { + family f; + f.kind = kind; + if (kind == family::K_HISTOGRAM) f.buckets = default_buckets(); + it = families_.insert(std::make_pair(name, std::move(f))).first; + } + return it->second; +} + +void uvcpp_metrics_registry::inc(const std::string& name, + const uvcpp_metric_labels& labels, + uint64_t delta) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_COUNTER); + if (f.kind != family::K_COUNTER) return; // 同名不同类型:忽略(不静默改类型) + const std::string key = label_key(labels); + f.values[key] += static_cast(delta); + if (f.labels.find(key) == f.labels.end()) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + f.labels[key] = sorted; + } +} + +void uvcpp_metrics_registry::set_gauge(const std::string& name, double value, + const uvcpp_metric_labels& labels) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_GAUGE); + if (f.kind != family::K_GAUGE) return; + const std::string key = label_key(labels); + f.values[key] = value; + if (f.labels.find(key) == f.labels.end()) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + f.labels[key] = sorted; + } +} + +void uvcpp_metrics_registry::add_gauge(const std::string& name, double delta, + const uvcpp_metric_labels& labels) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_GAUGE); + if (f.kind != family::K_GAUGE) return; + const std::string key = label_key(labels); + f.values[key] += delta; + if (f.labels.find(key) == f.labels.end()) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + f.labels[key] = sorted; + } +} + +void uvcpp_metrics_registry::register_gauge(const std::string& name, + const std::string& help, + std::function fn) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_GAUGE); + if (f.kind != family::K_GAUGE) return; + if (!help.empty()) f.help = help; + if (fn) f.gauges.push_back(std::make_pair(name, std::move(fn))); +} + +void uvcpp_metrics_registry::observe(const std::string& name, double value, + const uvcpp_metric_labels& labels) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_HISTOGRAM); + if (f.kind != family::K_HISTOGRAM) return; + const std::string key = label_key(labels); + histogram& h = f.hists[key]; + if (h.counts.size() != f.buckets.size()) h.counts.assign(f.buckets.size(), 0); + for (size_t i = 0; i < f.buckets.size(); ++i) { + if (value <= f.buckets[i]) ++h.counts[i]; + } + ++h.count; + h.sum += value; + if (f.labels.find(key) == f.labels.end()) { + uvcpp_metric_labels sorted = labels; + std::sort(sorted.begin(), sorted.end(), + [](const uvcpp_metric_label& a, const uvcpp_metric_label& b) { + return a.name < b.name; + }); + f.labels[key] = sorted; + } +} + +void uvcpp_metrics_registry::configure_histogram( + const std::string& name, const std::string& help, + const std::vector& buckets) { + std::lock_guard lk(mu_); + family& f = family_for(name, family::K_HISTOGRAM); + if (f.kind != family::K_HISTOGRAM) return; + if (!help.empty()) f.help = help; + std::vector b = buckets; + std::sort(b.begin(), b.end()); + b.erase(std::unique(b.begin(), b.end()), b.end()); + if (b.empty()) return; + // 换桶之前已经记过的观测按新桶**重放不了**(只存了累计数)—— 调用方应在 + // 第一次 observe 之前配置。这里把旧计数清零,避免"新桶 + 旧计数"的错配。 + f.buckets = b; + f.hists.clear(); +} + +void uvcpp_metrics_registry::set_help(const std::string& name, + const std::string& help) { + std::lock_guard lk(mu_); + std::map::iterator it = families_.find(name); + if (it == families_.end()) { + family f; + f.help = help; + families_.insert(std::make_pair(name, std::move(f))); + return; + } + it->second.help = help; +} + +void uvcpp_metrics_registry::clear() { + std::lock_guard lk(mu_); + families_.clear(); +} + +std::string uvcpp_metrics_registry::render() const { + // 先在锁里拷一份快照,锁外跑回调与格式化:`register_gauge()` 的回调通常读 + // 别的对象(连接池、线程池),在锁里跑会把它们的锁与本注册表的锁叠起来。 + std::map snapshot; + { + std::lock_guard lk(mu_); + snapshot = families_; + } + + std::string out; + for (std::map::iterator it = snapshot.begin(); + it != snapshot.end(); ++it) { + const std::string& name = it->first; + family& f = it->second; + if (!f.help.empty()) { + out += "# HELP "; + out += name; + out += ' '; + out += f.help; + out += '\n'; + } + switch (f.kind) { + case family::K_COUNTER: + out += "# TYPE " + name + " counter\n"; + break; + case family::K_GAUGE: + out += "# TYPE " + name + " gauge\n"; + break; + case family::K_HISTOGRAM: + out += "# TYPE " + name + " histogram\n"; + break; + } + + for (std::map::iterator v = f.values.begin(); + v != f.values.end(); ++v) { + out += name; + const std::map::iterator l = + f.labels.find(v->first); + if (l != f.labels.end() && !l->second.empty()) { + out += render_labels(l->second); + } + out += ' '; + out += fmt_double(v->second); + out += '\n'; + } + + for (size_t i = 0; i < f.gauges.size(); ++i) { + const double val = f.gauges[i].second ? f.gauges[i].second() : 0.0; + out += f.gauges[i].first; + out += ' '; + out += fmt_double(val); + out += '\n'; + } + + if (f.kind == family::K_HISTOGRAM) { + for (std::map::iterator h = f.hists.begin(); + h != f.hists.end(); ++h) { + const uvcpp_metric_labels* labels = nullptr; + const std::map::iterator l = + f.labels.find(h->first); + if (l != f.labels.end()) labels = &l->second; + for (size_t i = 0; i < f.buckets.size(); ++i) { + out += name; + out += "_bucket"; + uvcpp_metric_labels with_le; + if (labels != nullptr) with_le = *labels; + uvcpp_metric_label le; + le.name = "le"; + le.value = fmt_double(f.buckets[i]); + with_le.push_back(le); + out += render_labels(with_le); + out += ' '; + out += fmt_double(static_cast(h->second.counts[i])); + out += '\n'; + } + { + out += name; + out += "_bucket"; + uvcpp_metric_labels with_le; + if (labels != nullptr) with_le = *labels; + uvcpp_metric_label le; + le.name = "le"; + le.value = "+Inf"; + with_le.push_back(le); + out += render_labels(with_le); + out += ' '; + out += fmt_double(static_cast(h->second.count)); + out += '\n'; + } + { + out += name; + out += "_sum"; + if (labels != nullptr && !labels->empty()) { + out += render_labels(*labels); + } + out += ' '; + out += fmt_double(h->second.sum); + out += '\n'; + } + { + out += name; + out += "_count"; + if (labels != nullptr && !labels->empty()) { + out += render_labels(*labels); + } + out += ' '; + out += fmt_double(static_cast(h->second.count)); + out += '\n'; + } + } + } + } + return out; +} + +} // namespace uvcpp diff --git a/src/uvcpp/uvcpp_metrics_registry.h b/src/uvcpp/uvcpp_metrics_registry.h new file mode 100644 index 00000000..e4d34b45 --- /dev/null +++ b/src/uvcpp/uvcpp_metrics_registry.h @@ -0,0 +1,162 @@ +/** + * @file src/uvcpp/uvcpp_metrics_registry.h + * @brief 进程内的指标注册表:Counter / Gauge / Histogram + Prometheus 文本。 + * @author zhuweiye + * @version 1.0.0 + * + * 这是**可观测性那一层的核心**,不依赖 webapp、不依赖任何外部库: + * + * ```cpp + * uvcpp::uvcpp_metrics_registry reg; + * reg.inc("http_requests_total", {{"method", "GET"}, {"status", "200"}}); + * reg.observe("request_duration_ms", 12.5); + * reg.register_gauge("db_pool_in_use", "Connections currently borrowed", + * [&pool] { return static_cast(pool.in_use()); }); + * + * std::string text = reg.render(); // Prometheus/OpenMetrics 文本格式 + * ``` + * + * ## 三条规矩 + * + * 1. **线程安全**:所有更新方法内部一把互斥量;`render()` 也是。指标更新出现在 + * 每个请求上,而 `render()` 是运维路径(每秒一次都算密),这把锁不是瓶颈。 + * 2. **标签基数由调用方负责**:本类不阻止你把 URL 原串、用户 ID 塞进标签 —— 那会 + * 让时间序列数爆炸。约定见 `doc/webapp-guide.md`(只用方法、状态码、路由模式 + * 这类有限集合)。 + * 3. **关闭即零成本**:没装指标模块、也没人调这些方法时,本类只是一块空内存; + * 没有后台线程、没有定时器、没有全局单例。 + * + * ## 名字与标签 + * + * 名字原样输出(不做前缀);标签按名字排序后输出,保证同一组标签的字节稳定 + * (Prometheus 按 `名字{标签}` 识别时间序列)。值里的 `\`、`"`、换行按文本格式 + * 转义。直方图的桶用**绝对上界**(毫秒、字节这类),`_bucket{le="..."}` 是 + * 累计的。 + */ + +#pragma once +#ifndef SRC_UVCPP_UVCPP_METRICS_REGISTRY_H +#define SRC_UVCPP_UVCPP_METRICS_REGISTRY_H + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace uvcpp { + +/** + * @brief 一条标签。`name` 必须是合法的 Prometheus 标签名(调用方保证,本类不校验)。 + */ +struct UVCPP_API uvcpp_metric_label { + std::string name; + std::string value; +}; + +using uvcpp_metric_labels = std::vector; + +/** + * @brief 指标注册表。见文件头。 + */ +class UVCPP_API uvcpp_metrics_registry { + public: + /// 直方图默认桶(毫秒):1、5、10、25、50、100、250、500、1000、2500、5000、10000。 + static std::vector default_buckets(); + + uvcpp_metrics_registry(); + ~uvcpp_metrics_registry(); + + uvcpp_metrics_registry(const uvcpp_metrics_registry&) = delete; + uvcpp_metrics_registry& operator=(const uvcpp_metrics_registry&) = delete; + + // ---- 写 ---- + + /// Counter 加 @p delta(默认 1)。Counter 只增不减。 + void inc(const std::string& name, const uvcpp_metric_labels& labels = {}, + uint64_t delta = 1); + + /// Gauge 设成 @p value。 + void set_gauge(const std::string& name, double value, + const uvcpp_metric_labels& labels = {}); + + /// Gauge 加减 @p delta。 + void add_gauge(const std::string& name, double delta, + const uvcpp_metric_labels& labels = {}); + + /** + * @brief 注册一棵"渲染时才取值"的 Gauge(没有标签)。 + * + * 给"数值本来就在别处维护"的场合用(连接池的 `in_use()`、线程池深度)—— + * 不需要每请求同步一次,`render()` 那一刻读到什么就报什么。 + * + * 回调在 `render()` 里、**锁外**调用;回调不得再调本注册表的写方法 + * (那会自我死锁),读方法也请避免。 + */ + void register_gauge(const std::string& name, const std::string& help, + std::function fn); + + /** + * @brief 记一次观测(Histogram)。桶可用 `configure_histogram()` 换。 + * + * 未配置过的指标用 `default_buckets()`(毫秒)。 + */ + void observe(const std::string& name, double value, + const uvcpp_metric_labels& labels = {}); + + /// 配置一个 Histogram 的名字 / 帮助文本 / 绝对上界(升序;内部会排序去重)。 + void configure_histogram(const std::string& name, const std::string& help, + const std::vector& buckets); + + /// 配一条 HELP 文本(可选的;没配就只有样例行)。 + void set_help(const std::string& name, const std::string& help); + + /// 清空所有指标(测试与重启用;不是线程安全的"热重置",别在跑服务时调)。 + void clear(); + + // ---- 读 ---- + + /// 渲染成 Prometheus 文本格式(`# HELP` / `# TYPE` / 样例行)。 + std::string render() const; + + private: + struct histogram { + std::vector counts; ///< 与 buckets 等长:**小于等于**该上界的累计数 + uint64_t count = 0; + double sum = 0; + }; + + struct family { + enum kind_t { K_COUNTER, K_GAUGE, K_HISTOGRAM } kind = K_COUNTER; + std::string help; + + /// 样例键(标签序列化后的串)→ 值。Counter / Gauge。 + std::map values; + /// 样例键 → 标签(render 时输出用)。 + std::map labels; + + /// Histogram 专用(按样例键)。 + std::vector buckets; + std::map hists; + + /// 回调 Gauge(无标签)。 + std::vector>> gauges; + }; + + family& family_for(const std::string& name, family::kind_t kind); + + mutable std::mutex mu_; + std::map families_; +}; + +/// 把一组标签转成 `{a="b",c="d"}`;空标签返回空串。值按文本格式转义。 +UVCPP_API std::string uvcpp_metric_label_string( + const uvcpp_metric_labels& labels); + +} // namespace uvcpp + +#endif // SRC_UVCPP_UVCPP_METRICS_REGISTRY_H diff --git a/src/webapp/uvcpp_web_metrics.cpp b/src/webapp/uvcpp_web_metrics.cpp new file mode 100644 index 00000000..98ddbbc4 --- /dev/null +++ b/src/webapp/uvcpp_web_metrics.cpp @@ -0,0 +1,143 @@ +/** + * @file src/webapp/uvcpp_web_metrics.cpp + * @brief 运维端点与请求指标中间件的实现。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "webapp/uvcpp_web_metrics.h" + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include + +#include +#include +#include +#include + +namespace uvcpp { + +uvcpp_web_metrics_options::uvcpp_web_metrics_options() + : health_path("/health"), + ready_path("/ready"), + metrics_path("/metrics"), + instrument_requests(true), + register_connection_gauge(true) {} + +uvcpp_web_metrics::uvcpp_web_metrics(uvcpp_metrics_registry& registry) + : registry_(registry) {} + +uvcpp_web_metrics::~uvcpp_web_metrics() = default; + +void uvcpp_web_metrics::install(uvcpp_web_app& app, + const uvcpp_web_metrics_options& opts) { + app_ = &app; + + // liveness:不查任何依赖。数据库挂了不该让编排器重启进程。 + app.get(opts.health_path, + [](uvcpp_web_request&, uvcpp_web_response& resp, uvcpp_web_next) { + resp.set_header("content-type", "text/plain; charset=utf-8"); + resp.text(std::string("ok\n")); + resp.end(); + }); + + // readiness:**不缓存**结果 —— 每个请求现问一次。检查通常是一次原子读 / + // 连接池计数,代价可以忽略;缓存反而会让"刚恢复但还没到 TTL"变成一次误判。 + app.get(opts.ready_path, + [this](uvcpp_web_request&, uvcpp_web_response& resp, + uvcpp_web_next) { + std::string why; + bool ready = true; + if (ready_check_) ready = ready_check_(why); + resp.set_header("content-type", "text/plain; charset=utf-8"); + if (ready) { + resp.text(std::string("ready\n")); + } else { + resp.status(http_status::SERVICE_UNAVAILABLE); + std::string body = "not ready"; + if (!why.empty()) { + body += ": "; + body += why; + } + body += '\n'; + resp.text(body); + } + resp.end(); + }); + + app.get(opts.metrics_path, + [this](uvcpp_web_request&, uvcpp_web_response& resp, + uvcpp_web_next) { + // Prometheus 文本格式的 content-type 带版本号;运维端按它挑解析器。 + resp.set_header("content-type", + "text/plain; version=0.0.4; charset=utf-8"); + resp.text(registry_.render()); + resp.end(); + }); + + // 请求计数 / 耗时 / 在途。注册在最外层(`install()` 必须早于其它中间件), + // 这样覆盖整条链(含错误兜底转出来的 500)。 + if (opts.instrument_requests) { + app.use([this](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next next) { + const std::string method = + http_method_str(req.method()); + const std::chrono::steady_clock::time_point t0 = + std::chrono::steady_clock::now(); + registry_.add_gauge("http_requests_in_flight", 1); + + // `on_sent` 在响应真正发出去时触发(整包与 deferred 两条路都有), + // 是"这条请求结束了"的唯一统一时刻;流式响应也是它先回调一次。 + resp.on_sent([this, method, t0](const uvcpp_web_sent_info& si) { + registry_.add_gauge("http_requests_in_flight", -1); + const std::string status = std::to_string(si.status_code); + uvcpp_metric_labels labels; + uvcpp_metric_label m; + m.name = "method"; + m.value = method; + labels.push_back(m); + uvcpp_metric_label s; + s.name = "status"; + s.value = status; + labels.push_back(s); + registry_.inc("http_requests_total", labels, 1); + + const double ms = static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count()) / + 1000.0; + uvcpp_metric_labels dl; + uvcpp_metric_label dm; + dm.name = "method"; + dm.value = method; + dl.push_back(dm); + registry_.observe("http_request_duration_ms", ms, dl); + }); + + next(); + }); + } + + if (opts.register_connection_gauge) { + // 回调在 `render()` 里、锁外调用;`app` 必须活得比本对象久(install 的契约)。 + uvcpp_web_app* const a = &app; + registry_.register_gauge("uvcpp_web_app_connections", + "Connections currently registered by the app", + [a]() { + return static_cast(a->connection_count()); + }); + } +} + +void uvcpp_web_metrics::set_ready_check( + std::function check) { + ready_check_ = std::move(check); +} + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE diff --git a/src/webapp/uvcpp_web_metrics.h b/src/webapp/uvcpp_web_metrics.h new file mode 100644 index 00000000..a507c431 --- /dev/null +++ b/src/webapp/uvcpp_web_metrics.h @@ -0,0 +1,115 @@ +/** + * @file src/webapp/uvcpp_web_metrics.h + * @brief webapp 的运维端点:`/health`、`/ready`、`/metrics`。 + * @author zhuweiye + * @version 1.0.0 + * + * ```cpp + * uvcpp::uvcpp_metrics_registry reg; + * uvcpp::uvcpp_web_metrics metrics(reg); + * + * uvcpp::uvcpp_web_app app; + * metrics.install(app); // 注册三个端点 + 请求计数/耗时 + * metrics.set_ready_check([](std::string& why) { + * return db_pool_ready(why); // false 时 why 里写一句原因 + * }); + * ``` + * + * ## 三个端点各回答什么 + * + * | 端点 | 语义 | 不健康时 | + * |---|---|---| + * | `GET /health` | **进程活着**(liveness) | 永远 200;进程死了自然没响应 | + * | `GET /ready` | **能接业务**(readiness) | `set_ready_check()` 返回 false 时 503 | + * | `GET /metrics`| Prometheus 文本(OpenMetrics 0.0.4 格式) | 永远 200 | + * + * `/health` 故意不查依赖:数据库挂了不该让编排器**重启**进程(重启解决不了 + * 数据库),那正是 `/ready` 的活(把它摘出负载均衡即可)。 + * + * ## 请求指标 + * + * `instrument_requests`(默认开)装一个**最外层**中间件,记: + * + * - `http_requests_total{method="GET",status="200"}` —— Counter; + * - `http_request_duration_ms{method="GET"}` —— Histogram(默认桶见注册表); + * - `http_requests_in_flight` —— Gauge(响应 `on_sent` 时减回去)。 + * + * **标签里不放 URL 原串**:那是高基数,一个爬虫就能造出几十万个时间序列。 + * 要按路由看,用 `app.get()` 时自己 `reg.inc("route_requests_total", + * {{"route", "/user/:id"}})` —— 路由模式是有限集合。 + * + * ## 关闭时零成本 + * + * 不构造本对象、不 `install()`:注册表是空内存,框架里没有任何钩子。 + */ + +#pragma once +#ifndef SRC_WEBAPP_UVCPP_WEB_METRICS_H +#define SRC_WEBAPP_UVCPP_WEB_METRICS_H + +#include +#include + +#if UVCPP_WEBAPP_ENABLE + +#include +#include + +#include + +namespace uvcpp { + +class uvcpp_web_app; + +/// `install()` 的旋钮。显式构造函数(C++11 聚合初始化资格,见本仓约定)。 +struct UVCPP_API uvcpp_web_metrics_options { + uvcpp_web_metrics_options(); + + std::string health_path; ///< 默认 `/health` + std::string ready_path; ///< 默认 `/ready` + std::string metrics_path; ///< 默认 `/metrics` + /// 是否装请求计数 / 耗时 / 在途中间件。默认 true。 + bool instrument_requests; + /// 是否注册 `uvcpp_web_app_connections`(当前登记表里的连接数)。默认 true。 + bool register_connection_gauge; +}; + +/** + * @brief 把注册表接到 `uvcpp_web_app` 上。见文件头。 + */ +class UVCPP_API uvcpp_web_metrics { + public: + explicit uvcpp_web_metrics(uvcpp_metrics_registry& registry); + ~uvcpp_web_metrics(); + + uvcpp_web_metrics(const uvcpp_web_metrics&) = delete; + uvcpp_web_metrics& operator=(const uvcpp_web_metrics&) = delete; + + /** + * @brief 注册端点与(可选)请求中间件。**在 `app.start()` 之前调。** + * + * @param app 必须活得比本对象久(连接数 gauge 捕的是它的地址)。 + */ + void install(uvcpp_web_app& app, + const uvcpp_web_metrics_options& opts = uvcpp_web_metrics_options()); + + /** + * @brief 设置 readiness 检查。回调在**循环线程**上、每个 `/ready` 请求一次。 + * + * @param check 返回 false 表示未就绪;可通过出参写一句人读原因。 + * 传空函数 = 永远就绪。 + */ + void set_ready_check(std::function check); + + uvcpp_metrics_registry& registry() { return registry_; } + + private: + uvcpp_metrics_registry& registry_; + uvcpp_web_app* app_ = nullptr; + std::function ready_check_; +}; + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE +#endif // SRC_WEBAPP_UVCPP_WEB_METRICS_H diff --git a/tests/functional/web_app_metrics_func.cpp b/tests/functional/web_app_metrics_func.cpp new file mode 100644 index 00000000..b50db1b5 --- /dev/null +++ b/tests/functional/web_app_metrics_func.cpp @@ -0,0 +1,279 @@ +/** + * @file tests/functional/web_app_metrics_func.cpp + * @brief 指标注册表 + webapp 运维端点(`/health` `/ready` `/metrics`)。 + * + * 两层判据: + * + * 1. **注册表本身**(不碰网络):Counter / Gauge / Histogram 的文本格式、 + * 标签排序与转义、`le` 累计桶、`+Inf`、`_sum` / `_count`、回调 Gauge; + * 2. **端点**:真 `uvcpp_web_app` + 真 TCP 客户端: + * - `/health` 恒 200(liveness 不查依赖); + * - `/ready` 随 `set_ready_check()` 的返回在 200 / 503 之间切换,并带上原因; + * - `/metrics` 里能看到请求计数(含 404 那条)、耗时直方图、在途 Gauge 归零、 + * 连接数回调 Gauge。 + * + * 文件名带 `web_app_` 是**必须的**(webapp 是可选模块、默认关;见 + * `tests/functional/CMakeLists.txt` 的命名约定)。 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include +#include +#include +#include + +using namespace uvcpp; + +namespace { + +int g_fail = 0; + +void check(bool ok, const std::string& what) { + if (ok) { + std::cout << " [ ok ] " << what << std::endl; + } else { + ++g_fail; + std::cerr << " [FAIL] " << what << std::endl; + } +} + +bool contains(const std::string& hay, const std::string& needle) { + return hay.find(needle) != std::string::npos; +} + +// --------------------------------------------------------------------------- +// 1. 注册表 +// --------------------------------------------------------------------------- +void test_registry_text() { + std::cout << "-- 注册表:文本格式 --" << std::endl; + uvcpp_metrics_registry reg; + + uvcpp_metric_labels l; + uvcpp_metric_label a; + a.name = "status"; + a.value = "200"; + l.push_back(a); + uvcpp_metric_label b; + b.name = "method"; + b.value = "GET"; + l.push_back(b); // 故意倒序给,渲染应按名字排好 + + reg.inc("requests_total", l); + reg.inc("requests_total", l); + reg.set_gauge("in_flight", 3); + reg.add_gauge("in_flight", -1); + reg.register_gauge("pool_size", "Pool size", [] { return 7.0; }); + reg.configure_histogram("latency_ms", "Latency", {10, 100}); + reg.observe("latency_ms", 5); + reg.observe("latency_ms", 50); + reg.observe("latency_ms", 500); + + const std::string t = reg.render(); + std::cout << t; + + check(contains(t, "# TYPE requests_total counter"), + "Counter 的 TYPE 行"); + check(contains(t, + "requests_total{method=\"GET\",status=\"200\"} 2"), + "标签按名字排序、值正确"); + check(contains(t, "# TYPE in_flight gauge"), "Gauge 的 TYPE 行"); + check(contains(t, "in_flight 2"), "Gauge 加减小计正确"); + check(contains(t, "pool_size 7"), "回调 Gauge 在 render 时取值"); + check(contains(t, "# TYPE latency_ms histogram"), "Histogram 的 TYPE 行"); + check(contains(t, "latency_ms_bucket{le=\"10\"} 1"), + "le=10 的累计桶(5 落在这里)"); + check(contains(t, "latency_ms_bucket{le=\"100\"} 2"), + "le=100 的累计桶(5、50)"); + check(contains(t, "latency_ms_bucket{le=\"+Inf\"} 3"), "+Inf 桶"); + check(contains(t, "latency_ms_sum 555"), "sum = 5+50+500"); + check(contains(t, "latency_ms_count 3"), "count = 3"); + + // 标签值转义 + uvcpp_metrics_registry esc; + uvcpp_metric_labels el; + uvcpp_metric_label e; + e.name = "v"; + e.value = "a\"b\nc"; + el.push_back(e); + esc.inc("esc_total", el); + check(contains(esc.render(), "esc_total{v=\"a\\\"b\\nc\"} 1"), + "标签值里的引号与换行被转义"); +} + +void test_registry_threads() { + std::cout << "-- 注册表:并发更新 --" << std::endl; + uvcpp_metrics_registry reg; + const int kThreads = 4; + const int kPerThread = 5000; + std::vector threads; + for (int i = 0; i < kThreads; ++i) { + threads.push_back(std::thread([®, kPerThread] { + for (int k = 0; k < kPerThread; ++k) reg.inc("conc_total"); + })); + } + // 与更新并发地渲染几轮 + std::thread renderer([®] { + for (int i = 0; i < 50; ++i) { + std::string s = reg.render(); + (void)s; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + }); + for (size_t i = 0; i < threads.size(); ++i) threads[i].join(); + renderer.join(); + check(contains(reg.render(), "conc_total " + + std::to_string(kThreads * kPerThread)), + "并发自增无丢失(" + std::to_string(kThreads * kPerThread) + ")"); +} + +// --------------------------------------------------------------------------- +// 2. 端点 +// --------------------------------------------------------------------------- +struct TestApp { + uvcpp_web_app app; + uvcpp_metrics_registry reg; + uvcpp_web_metrics metrics{reg}; + std::atomic ready{true}; + + void build() { + app.set_host("127.0.0.1") + .set_port(0) + .set_access_log(false) + .set_log_level(log_level::WARN); + + metrics.install(app); + metrics.set_ready_check([this](std::string& why) { + if (ready.load()) return true; + why = "db down"; + return false; + }); + + app.get("/hello", + [](uvcpp_web_request&, uvcpp_web_response& resp, uvcpp_web_next) { + resp.text(std::string("hello")); + resp.end(); + }); + } + + int start() { + if (app.start_background() != 0) return -1; + return app.bound_port(); + } + void shutdown() { + app.stop(); + app.join(); + } +}; + +struct reply { + int status = 0; + std::string body; +}; + +reply get(int port, const std::string& path) { + uvcpp_http_client c; + reply out; + if (c.connect_wait("127.0.0.1", port, 3000) != 0) return out; + uvcpp_http_response resp; + if (c.send_wait(uvcpp_http_request::make_get(path), resp, 3000) != 0) { + return out; + } + out.status = static_cast(resp.status_code); + out.body = resp.body.to_string(); + return out; +} + +void test_endpoints() { + std::cout << "-- 端点:health / ready / metrics --" << std::endl; + TestApp t; + t.build(); + const int port = t.start(); + check(port > 0, "app 起来了"); + if (port <= 0) { + t.shutdown(); + return; + } + + { + const reply r = get(port, "/health"); + check(r.status == 200, "liveness:200"); + check(r.body == "ok\n", "liveness:body 是 ok"); + } + + { + const reply r = get(port, "/ready"); + check(r.status == 200, "readiness(就绪):200"); + check(r.body == "ready\n", "readiness(就绪):body 是 ready"); + t.ready.store(false); + const reply nr = get(port, "/ready"); + check(nr.status == 503, "readiness(未就绪):503"); + check(contains(nr.body, "not ready: db down"), + "readiness(未就绪):带原因(实际 \"" + nr.body + "\")"); + t.ready.store(true); + } + + // 先打几条业务请求(含一条 404),再看 /metrics + check(get(port, "/hello").status == 200, "业务请求 200"); + check(get(port, "/missing").status == 404, "未命中路由 404"); + + // 先直接渲染一次注册表:此刻没有在途请求(前面的响应都已发完),在途 Gauge + // 必须是 0。`/metrics` 那个 HTTP 请求自己在飞的时候会是 1 —— 那是自计数, + // 不是泄漏,下面那条断言照实写 1。 + check(contains(t.reg.render(), "http_requests_in_flight 0"), + "metrics(直接读):在途 Gauge 为 0"); + + const reply m = get(port, "/metrics"); + check(m.status == 200, "metrics:200"); + std::cout << m.body; + check(contains(m.body, "http_requests_total{method=\"GET\",status=\"200\"}"), + "metrics:有 200 的请求计数"); + check(contains(m.body, "http_requests_total{method=\"GET\",status=\"404\"}"), + "metrics:404 也被计数"); + check(contains(m.body, "# TYPE http_request_duration_ms histogram"), + "metrics:耗时直方图在"); + check(contains(m.body, "http_requests_in_flight 1"), + "metrics:在途 Gauge = 1(渲染它的这条请求自己)"); + check(contains(m.body, "uvcpp_web_app_connections"), "metrics:连接数回调 Gauge"); + + t.shutdown(); +} + +} // namespace + +int main() { + std::cout << "[web_app_metrics] start" << std::endl; + test_registry_text(); + test_registry_threads(); + test_endpoints(); + if (g_fail == 0) { + std::cout << "[web_app_metrics] ALL PASS" << std::endl; + return 0; + } + std::cerr << "[web_app_metrics] " << g_fail << " check(s) failed" << std::endl; + return 1; +} + +#else // !WEBAPP + +int main() { + std::cout << "SKIP: webapp disabled" << std::endl; + return 0; +} + +#endif