| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | use topcoat::{ |
| 19 | Result, |
| 20 | context::{Cx, app_context}, |
| 21 | router::{ |
| 22 | Body, Response, StatusCode, |
| 23 | error::not_found, |
| 24 | header::{CACHE_CONTROL, CONTENT_TYPE}, |
| 25 | route, |
| 26 | }, |
| 27 | }; |
| 28 | |
| 29 | use std::sync::Arc; |
| 30 | |
| 31 | use crate::infrastructure::{ |
| 32 | cat_file::CatFilePool, |
| 33 | merge_cache::MergeCache, |
| 34 | metrics::{Gauges, Metrics}, |
| 35 | }; |
| 36 | |
| 37 | use super::{ |
| 38 | context::{highlights, server_error}, |
| 39 | import::ImportQueue, |
| 40 | operator::operator_authorized, |
| 41 | rate_limit::metrics_throttled, |
| 42 | }; |
| 43 | |
| 44 | |
| 45 | |
| 46 | const EXPOSITION: &str = "text/plain; version=0.0.4; charset=utf-8"; |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | #[route(GET "/metrics")] |
| 55 | async fn expose(cx: &Cx) -> Result<Response<Body>> { |
| 56 | if !operator_authorized(cx) { |
| 57 | if let Some(throttled) = metrics_throttled(cx) { |
| 58 | return Ok(throttled); |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | return Err(not_found().into()); |
| 64 | } |
| 65 | |
| 66 | let body = app_context::<Arc<Metrics>>(cx).render(&gauges(cx)); |
| 67 | |
| 68 | Response::builder() |
| 69 | .status(StatusCode::OK) |
| 70 | .header(CONTENT_TYPE, EXPOSITION) |
| 71 | |
| 72 | |
| 73 | .header(CACHE_CONTROL, "no-store") |
| 74 | .body(Body::from(body)) |
| 75 | .map_err(server_error) |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | fn gauges(cx: &Cx) -> Gauges { |
| 83 | let (_, highlight_cache_bytes) = highlights(cx).stats(); |
| 84 | let (_, merge_cache_bytes) = app_context::<Arc<MergeCache>>(cx).stats(); |
| 85 | |
| 86 | Gauges { |
| 87 | cat_file_pool: app_context::<Arc<CatFilePool>>(cx).live_repositories() as u64, |
| 88 | highlight_cache_bytes: highlight_cache_bytes as u64, |
| 89 | merge_cache_bytes: merge_cache_bytes as u64, |
| 90 | active_imports: app_context::<ImportQueue>(cx).active() as u64, |
| 91 | } |
| 92 | } |