chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
Logs as JSON lines in traces, kept for HUD's operators
crates/hud/src/main.rs+95−15
| @@ -1,9 +1,12 @@ | ||
//! `hud`, the server's binary: `hud serve` reads its configuration from the | ||
//! environment (`HUD_*`, as `--help` lists), listens, sweeps sign-ins past | ||
//! their time hourly when sign-in is on, and stops gracefully on SIGINT or | ||
//! SIGTERM, letting requests in flight finish and ending the workspace's | ||
//! event streams (`hud_server::serve`). `hud resolve` gives a recorded | ||
//! answer its `_meta.ui`, for the harnesses that draw one with no server. | ||
//! environment (`HUD_*`, as `--help` lists), logs as JSON lines on stderr | ||
//! (`hud_core::telemetry`), kept for its operators with `HUD_LOGS`, | ||
//! listens, answers `/metrics` and `PUT /log` on `HUD_METRICS` if set, | ||
//! sweeps sign-ins past their time hourly when sign-in is on, and stops | ||
//! gracefully on SIGINT or SIGTERM, letting requests in flight finish and | ||
//! ending the workspace's event streams (`hud_server::serve`). `hud | ||
//! resolve` gives a recorded answer its `_meta.ui`, for the harnesses that | ||
//! draw one with no server. | ||
| ||
#![forbid(unsafe_code)] | ||
| ||
| @@ -11,8 +14,13 @@ use hud_core::backlinks::Backlinks; | ||
use hud_core::{Config, Hud}; | ||
use std::net::{IpAddr, SocketAddr}; | ||
use std::path::PathBuf; | ||
use std::time::Duration; | ||
use url::Url; | ||
| ||
/// The commit this was built from, where `git archive` wrote it | ||
/// (`hud_core::telemetry::commit`). | ||
const COMMIT: &str = include_str!("../commit.txt"); | ||
| ||
const HELP: &str = "\ | ||
hud: an MCP server that shows atproto records, and the answers of | ||
services' XRPC queries, as MCP Apps views; signed in, it writes records | ||
| @@ -42,8 +50,9 @@ Configuration, from the environment: | ||
about the most bytes the in-memory caches (identities, | ||
lexicons, joins' records, counts) hold (67108864, 64 MiB) | ||
HUD_DATA_DIR where sign-in's key, sessions and registered clients | ||
(under oauth/) and the workspace's canvases (under | ||
canvas/) are kept, files mode 0600 (HUD_CACHE_DIR) | ||
(under oauth/), the workspace's canvases (under | ||
canvas/) and, with HUD_LOGS, the lines logged | ||
(logs.db) are kept, files mode 0600 (HUD_CACHE_DIR) | ||
HUD_OAUTH on or off: sign-in, the write and canvas tools, the | ||
workspace, and queries through the account's PDS (on | ||
when HUD_PUBLIC_URL is https, which on requires) | ||
| @@ -80,7 +89,21 @@ Configuration, from the environment: | ||
only an account's (https://bsky.network) | ||
HUD_SIGN_UP_PDS the PDS \"Create one\" makes a new account at, an | ||
origin (https://selfhosted.social) | ||
RUST_LOG log filter (info) | ||
RUST_LOG what is logged, JSON lines on stderr: a level, or | ||
directives such as info,hud::outgoing=debug (info) | ||
HUD_SLOW_MS how many milliseconds a request, an outbound call or a | ||
tool call takes before it is logged at warn (1000) | ||
HUD_METRICS a loopback address and port answering GET /metrics | ||
(Prometheus) and PUT /log (a RUST_LOG directive, to | ||
change what is logged until a restart), as | ||
127.0.0.1:9464 (unset: off) | ||
HUD_LOGS on or off: keep every line logged in | ||
HUD_DATA_DIR/logs.db too, for HUD_OPERATOR_DIDS to read | ||
with place.hud.getLogs and admin_logs (off) | ||
HUD_LOGS_KEEP how many lines at info and below are kept there; every | ||
line goes after 30 days (500000) | ||
HUD_OPERATOR_DIDS the DIDs of the accounts that run this server, by | ||
commas or spaces: they alone read the kept lines (none) | ||
"; | ||
| ||
/// An environment variable, if set to something. | ||
| @@ -256,6 +279,27 @@ fn config() -> Result<Config, String> { | ||
Some(u) => origin("HUD_SIGN_UP_PDS", &u)?, | ||
None => hud_core::config::SIGN_UP_PDS.to_string(), | ||
}; | ||
// DIDs, by commas or spaces. | ||
let operators = var("HUD_OPERATOR_DIDS")?.unwrap_or_default(); | ||
let operators = operators | ||
.split(|c: char| c == ',' || c.is_whitespace()) | ||
.filter(|d| !d.is_empty()) | ||
.map(|d| match atproto::syntax::is_did(d) { | ||
true => Ok(d.to_string()), | ||
false => Err(format!("HUD_OPERATOR_DIDS: {d:?} is not a DID")), | ||
}) | ||
.collect::<Result<Vec<_>, _>>()?; | ||
let logs = match var("HUD_LOGS")?.as_deref() { | ||
None | Some("off") => false, | ||
Some("on") => true, | ||
Some(v) => return Err(format!("HUD_LOGS: {v:?} is not on or off")), | ||
}; | ||
let logs_keep = match var("HUD_LOGS_KEEP")? { | ||
Some(n) => n | ||
.parse::<u64>() | ||
.map_err(|_| format!("HUD_LOGS_KEEP: {n:?} is not a number of lines"))?, | ||
None => hud_core::logs::KEEP, | ||
}; | ||
Ok(Config { | ||
port, | ||
bind, | ||
| @@ -275,6 +319,18 @@ fn config() -> Result<Config, String> { | ||
image_cdn, | ||
relay, | ||
sign_up_pds, | ||
operators, | ||
logs, | ||
logs_keep, | ||
}) | ||
} | ||
| ||
/// `HUD_METRICS`'s address: one on loopback, so nothing outside the | ||
/// machine (or the container) reaches what it answers. | ||
fn loopback(value: &str) -> Result<SocketAddr, String> { | ||
let addr = value.parse::<SocketAddr>().ok(); | ||
addr.filter(|a| a.ip().is_loopback()).ok_or_else(|| { | ||
format!("HUD_METRICS: {value:?} is not a loopback address and port, as 127.0.0.1:9464") | ||
}) | ||
} | ||
| ||
| @@ -302,12 +358,36 @@ async fn shutdown() { | ||
| ||
async fn serve() -> Result<(), String> { | ||
let config = config()?; | ||
let slow = match var("HUD_SLOW_MS")? { | ||
Some(ms) => ms | ||
.parse::<u64>() | ||
.map_err(|_| format!("HUD_SLOW_MS: {ms:?} is not a number of milliseconds"))?, | ||
None => 1000, | ||
}; | ||
hud_core::telemetry::set_slow(slow); | ||
let metrics = var("HUD_METRICS")?.map(|m| loopback(&m)).transpose()?; | ||
if config.allow_private { | ||
tracing::warn!("HUD_ALLOW_PRIVATE is set: outbound requests may reach private addresses"); | ||
} | ||
let addr = SocketAddr::new(config.bind, config.port); | ||
let public = config.public_origin.clone(); | ||
let hud = Hud::new(config)?; | ||
if let Some(logs) = hud.logs.clone() { | ||
let kept = logs.clone(); | ||
hud_core::telemetry::keep_lines(move |line| kept.keep(line)); | ||
tokio::spawn(hud_core::logs::flushing(logs, hud_core::logs::FLUSH)); | ||
let path = hud.config.data_dir.join("logs.db"); | ||
tracing::info!(path = %path.display(), "keeping the lines logged"); | ||
} | ||
if let Some(at) = metrics { | ||
let listener = tokio::net::TcpListener::bind(at) | ||
.await | ||
.map_err(failed(format!("listening on {at}")))?; | ||
tracing::info!(%at, "metrics at http://{at}/metrics"); | ||
tokio::spawn(hud_server::telemetry::serve_admin(listener, hud.clone())); | ||
} | ||
let every = Duration::from_secs(60); | ||
tokio::spawn(hud_server::telemetry::summaries(hud.clone(), every)); | ||
if hud.config.spaces { | ||
tracing::info!(scope = %hud.config.oauth_scope, "canvases go in people's own spaces where their PDS and sign-in allow"); | ||
} | ||
| @@ -316,7 +396,7 @@ async fn serve() -> Result<(), String> { | ||
let sweeper = hud.clone(); | ||
tokio::spawn(async move { | ||
let auth = sweeper.oauth.as_ref().expect("sign-in is on"); | ||
let mut every = tokio::time::interval(std::time::Duration::from_secs(3600)); | ||
let mut every = tokio::time::interval(Duration::from_secs(3600)); | ||
loop { | ||
every.tick().await; | ||
auth.sweep().await; | ||
| @@ -333,6 +413,10 @@ async fn serve() -> Result<(), String> { | ||
// The canvases' changes still waiting to be written, written. | ||
hud.canvases.flush().await; | ||
tracing::info!(caches = %hud.caches(), "caches at shutdown"); | ||
// The lines logged since the last write, this one's with them. | ||
if let Some(logs) = &hud.logs { | ||
logs.write_held(); | ||
} | ||
served | ||
} | ||
| ||
| @@ -357,12 +441,8 @@ fn resolve(tool: Option<&str>, arguments: Option<&str>) -> Result<(), String> { | ||
/// cannot be made is said before the logs are set up: on stderr alone. | ||
fn run() -> Result<(), String> { | ||
let runtime = tokio::runtime::Runtime::new().map_err(failed("a runtime".into()))?; | ||
tracing_subscriber::fmt() | ||
.with_env_filter( | ||
tracing_subscriber::EnvFilter::try_from_default_env() | ||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), | ||
) | ||
.init(); | ||
let commit = hud_core::telemetry::commit(COMMIT); | ||
hud_core::telemetry::init(env!("CARGO_PKG_VERSION"), commit); | ||
runtime.block_on(serve()) | ||
} | ||
| ||
crates/hud/tests/cli.rs+177−11
| @@ -104,13 +104,30 @@ fn run(mut cmd: Command, stdin: &str) -> Ran { | ||
} | ||
} | ||
| ||
/// `hud serve` with `env`, which it refuses: what it said on stderr. | ||
/// What a person reads on stderr: its lines but the log's JSON ones. | ||
fn said(stderr: &str) -> String { | ||
let plain = stderr.lines().filter(|l| !l.starts_with('{')); | ||
plain.collect::<Vec<_>>().join("\n") | ||
} | ||
| ||
/// `hud serve` with `env`, which it refuses: what it said on stderr, | ||
/// besides its log. | ||
fn refused(env: &[(&str, &str)]) -> String { | ||
let dir = temp_dir("refused"); | ||
let env: Vec<(&str, &OsStr)> = env.iter().map(|(k, v)| (*k, OsStr::new(v))).collect(); | ||
let ran = run(hud(&["serve"], &dir, &env), ""); | ||
assert_eq!(ran.status.code(), Some(1), "{env:?}: {}", ran.stderr); | ||
ran.stderr | ||
// Its log says it too, as an error. | ||
let logged = ran | ||
.stderr | ||
.lines() | ||
.filter_map(|l| serde_json::from_str::<Value>(l).ok()); | ||
assert!( | ||
logged.clone().any(|l| l["level"] == "ERROR"), | ||
"{}", | ||
ran.stderr | ||
); | ||
said(&ran.stderr) | ||
} | ||
| ||
/// A port nothing listens on now. | ||
| @@ -122,12 +139,14 @@ fn free_port() -> u16 { | ||
.port() | ||
} | ||
| ||
/// `GET path` of the server on `port`: its status and body. | ||
fn get(port: u16, path: &str) -> (u16, String) { | ||
/// `method path` of the server on `port`, with `headers` and `body`: its | ||
/// status, head and body. | ||
fn ask(port: u16, method: &str, path: &str, headers: &str, body: &str) -> (u16, String, String) { | ||
let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap(); | ||
let length = body.len(); | ||
write!( | ||
s, | ||
"GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n" | ||
"{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{headers}Content-Length: {length}\r\nConnection: close\r\n\r\n{body}" | ||
) | ||
.unwrap(); | ||
let mut answer = String::new(); | ||
| @@ -142,6 +161,12 @@ fn get(port: u16, path: &str) -> (u16, String) { | ||
true => body.split("\r\n").nth(1).unwrap_or_default().to_string(), | ||
false => body.to_string(), | ||
}; | ||
(status, head.to_string(), body) | ||
} | ||
| ||
/// `GET path` of the server on `port`: its status and body. | ||
fn get(port: u16, path: &str) -> (u16, String) { | ||
let (status, _, body) = ask(port, "GET", path, "", ""); | ||
(status, body) | ||
} | ||
| ||
| @@ -153,18 +178,19 @@ struct Server { | ||
} | ||
| ||
impl Server { | ||
/// `hud serve` in `cwd` with `env`, once it says it is serving. | ||
/// `hud serve` in `cwd` with `env`, once it says it is serving: its | ||
/// log, the JSON lines on stderr, read as it writes them. | ||
fn start(cwd: &std::path::Path, env: &[(&str, &str)]) -> Server { | ||
let env: Vec<(&str, &OsStr)> = env.iter().map(|(k, v)| (*k, OsStr::new(v))).collect(); | ||
let mut child = hud(&["serve"], cwd, &env) | ||
.stdout(Stdio::piped()) | ||
.stderr(Stdio::inherit()) | ||
.stdout(Stdio::inherit()) | ||
.stderr(Stdio::piped()) | ||
.spawn() | ||
.unwrap(); | ||
let (tx, lines) = mpsc::channel(); | ||
let stdout = child.stdout.take().unwrap(); | ||
let stderr = child.stderr.take().unwrap(); | ||
std::thread::spawn(move || { | ||
for line in BufReader::new(stdout).lines() { | ||
for line in BufReader::new(stderr).lines() { | ||
let _ = tx.send(line.unwrap()); | ||
} | ||
}); | ||
| @@ -408,6 +434,30 @@ fn refuses_configuration_it_cannot_use() { | ||
&[("HUD_SIGN_UP_PDS", "https://pds.example/signup")], | ||
r#"HUD_SIGN_UP_PDS: "https://pds.example/signup" is not an http or https origin"#, | ||
), | ||
( | ||
&[("HUD_OPERATOR_DIDS", "did:plc:operator, alice.test")], | ||
r#"HUD_OPERATOR_DIDS: "alice.test" is not a DID"#, | ||
), | ||
( | ||
&[("HUD_LOGS", "yes")], | ||
r#"HUD_LOGS: "yes" is not on or off"#, | ||
), | ||
( | ||
&[("HUD_LOGS_KEEP", "lots")], | ||
r#"HUD_LOGS_KEEP: "lots" is not a number of lines"#, | ||
), | ||
( | ||
&[("HUD_SLOW_MS", "soon")], | ||
r#"HUD_SLOW_MS: "soon" is not a number of milliseconds"#, | ||
), | ||
( | ||
&[("HUD_METRICS", "0.0.0.0:9464")], | ||
r#"HUD_METRICS: "0.0.0.0:9464" is not a loopback address and port, as 127.0.0.1:9464"#, | ||
), | ||
( | ||
&[("HUD_METRICS", "9464")], | ||
r#"HUD_METRICS: "9464" is not a loopback address and port"#, | ||
), | ||
]; | ||
for (env, message) in cases { | ||
let said = refused(env); | ||
| @@ -428,10 +478,126 @@ fn refuses_variables_that_are_not_text() { | ||
] { | ||
let ran = run(hud(&["serve"], &dir, &[(name, bytes)]), ""); | ||
assert_eq!(ran.status.code(), Some(1), "{name}: {}", ran.stderr); | ||
assert_eq!(ran.stderr.trim_end(), format!("hud: {message}")); | ||
assert_eq!(said(&ran.stderr), format!("hud: {message}")); | ||
} | ||
} | ||
| ||
/// Where its lines can't be kept, or its metrics' port is taken: said, and | ||
/// not served. | ||
#[test] | ||
fn refuses_where_it_cannot_keep_logs_or_listen() { | ||
let dir = temp_dir("unkept"); | ||
std::fs::write(dir.join("file"), "").unwrap(); | ||
let file = dir.join("file"); | ||
let said = refused(&[ | ||
("HUD_LOGS", "on"), | ||
("HUD_DATA_DIR", file.to_str().unwrap()), | ||
("HUD_CACHE_DIR", dir.to_str().unwrap()), | ||
]); | ||
assert!(said.starts_with("hud: the logs at "), "{said}"); | ||
let taken = TcpListener::bind("127.0.0.1:0").unwrap(); | ||
let at = taken.local_addr().unwrap().to_string(); | ||
let said = refused(&[ | ||
("HUD_METRICS", &at), | ||
("HUD_CACHE_DIR", dir.to_str().unwrap()), | ||
]); | ||
assert!( | ||
said.starts_with(&format!("hud: listening on {at}: ")), | ||
"{said}" | ||
); | ||
} | ||
| ||
/// Its log is JSON lines on stderr: a request in the trace its | ||
/// `traceparent` names, which the answer gives back as `x-trace-id`, its | ||
/// query's secrets masked. `/metrics` and `PUT /log` answer on loopback, | ||
/// the latter changing what is logged. With `HUD_LOGS`, each line is kept | ||
/// in `logs.db` too, mode 0600, and written as it stops. | ||
#[test] | ||
fn logs_kept_and_metrics_on_loopback() { | ||
let dir = temp_dir("logs"); | ||
let port = free_port().to_string(); | ||
let metrics = free_port(); | ||
let at = format!("127.0.0.1:{metrics}"); | ||
let data = dir.join("data"); | ||
let server = Server::start( | ||
&dir, | ||
&[ | ||
("HUD_PORT", &port), | ||
("HUD_BIND", "127.0.0.1"), | ||
("HUD_ALLOW_PRIVATE", "1"), | ||
("HUD_BACKLINKS", "none"), | ||
("HUD_FAVICONS", ""), | ||
("HUD_CACHE_DIR", dir.join("cache").to_str().unwrap()), | ||
("HUD_DATA_DIR", data.to_str().unwrap()), | ||
("HUD_LOGS", "on"), | ||
("HUD_LOGS_KEEP", "1000"), | ||
("HUD_METRICS", &at), | ||
("HUD_SLOW_MS", "60000"), | ||
("HUD_OPERATOR_DIDS", "did:plc:operator, did:web:hud.example"), | ||
], | ||
); | ||
let lines = |log: &[String]| -> Vec<Value> { | ||
log.iter() | ||
.map(|l| serde_json::from_str(l).unwrap_or_else(|_| panic!("not JSON: {l}"))) | ||
.collect() | ||
}; | ||
let started = lines(&server.log); | ||
let starting = started | ||
.iter() | ||
.find(|l| l["message"] == "hud starting") | ||
.unwrap(); | ||
assert_eq!(starting["version"], env!("CARGO_PKG_VERSION")); | ||
assert_eq!(starting["level"], "INFO"); | ||
assert!(server.said("keeping the lines logged")); | ||
// The level, changed: a health check is logged at debug. | ||
let (status, _, body) = ask(metrics, "PUT", "/log", "", "debug"); | ||
assert_eq!((status, body.as_str()), (200, "logging debug\n")); | ||
let (status, _, _) = ask(metrics, "PUT", "/log", "", "[[["); | ||
assert_eq!(status, 400); | ||
let port: u16 = port.parse().unwrap(); | ||
let id = "4bf92f3577b34da6a3ce929d0e0e4736"; | ||
let parent = format!("traceparent: 00-{id}-00f067aa0ba902b7-01\r\n"); | ||
let (status, head, body) = ask(port, "GET", "/_health?token=secret", &parent, ""); | ||
assert_eq!((status, body.as_str()), (200, "ok")); | ||
assert!(head.contains(&format!("x-trace-id: {id}")), "{head}"); | ||
let (status, _, text) = ask(metrics, "GET", "/metrics", "", ""); | ||
assert_eq!(status, 200); | ||
assert!(text.contains("http_route=\"/_health\""), "{text}"); | ||
assert!(text.contains("hud_build_info{version="), "{text}"); | ||
// Nothing but its metrics and level there. | ||
assert_eq!(ask(metrics, "GET", "/mcp", "", "").0, 404); | ||
let (status, log) = server.stop("TERM"); | ||
assert!(status.success(), "{log:#?}"); | ||
let log = lines(&log); | ||
let request = log | ||
.iter() | ||
.find(|l| l["message"] == "request" && l["trace_id"] == id) | ||
.unwrap_or_else(|| panic!("{log:#?}")); | ||
assert_eq!(request["level"], "DEBUG"); | ||
assert_eq!(request["http.route"], "/_health"); | ||
assert_eq!(request["url.path"], "/_health"); | ||
assert_eq!(request["url.query"], "token=_"); | ||
assert_eq!(request["http.response.status_code"], 200); | ||
assert!(!log.iter().any(|l| l.to_string().contains("secret"))); | ||
// Kept, every line from when it began keeping them. | ||
let kept = data.join("logs.db"); | ||
let mode = | ||
std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(&kept).unwrap().permissions()); | ||
assert_eq!(mode & 0o777, 0o600); | ||
let db = rusqlite::Connection::open(&kept).unwrap(); | ||
let count = |sql: &str| -> i64 { db.query_row(sql, [], |r| r.get(0)).unwrap() }; | ||
assert_eq!( | ||
count(&format!("SELECT count(*) FROM line WHERE trace = '{id}'")), | ||
1 | ||
); | ||
let keeping = "SELECT count(*) FROM line WHERE message = 'keeping the lines logged'"; | ||
assert_eq!(count(keeping), 1); | ||
assert_eq!( | ||
count("SELECT count(*) FROM line WHERE message = 'caches at shutdown'"), | ||
1 | ||
); | ||
} | ||
| ||
/// `hud <args>` given `stdin`, in a directory of its own. | ||
fn resolve(args: &[&str], stdin: &str) -> Ran { | ||
run(hud(args, &temp_dir("resolve"), &[]), stdin) | ||
crates/hud/Cargo.toml+5−1
| @@ -8,10 +8,14 @@ rust-version.workspace = true | ||
publish.workspace = true | ||
| ||
[dependencies] | ||
atproto.workspace = true | ||
hud-core.workspace = true | ||
hud-server.workspace = true | ||
tokio.workspace = true | ||
serde_json.workspace = true | ||
tracing.workspace = true | ||
tracing-subscriber.workspace = true | ||
url.workspace = true | ||
| ||
[dev-dependencies] | ||
# The kept lines, read back in the binary's tests. | ||
rusqlite.workspace = true | ||
crates/hud/commit.txtnew+1−0
| @@ -0,0 +1 @@ | ||
$Format:%H$ | ||
crates/hud-core/src/canvas/canonical.rs+3−0
| @@ -149,6 +149,9 @@ mod tests { | ||
oauth: false, | ||
oauth_scope: crate::scope::asked(false), | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
operators: Vec::new(), | ||
logs: false, | ||
logs_keep: crate::logs::KEEP, | ||
spaces: false, | ||
plc_url: "http://127.0.0.1:9".into(), | ||
handle_resolver: None, | ||
crates/hud-core/src/canvas/space.rs+4−1
| @@ -590,7 +590,7 @@ impl Inner { | ||
} | ||
Entry::Vacant(e) => { | ||
e.insert(Some(due)); | ||
tokio::spawn(self.clone().settle_tile(key)); | ||
crate::telemetry::spawn(self.clone().settle_tile(key)); | ||
} | ||
} | ||
true | ||
| @@ -1324,6 +1324,9 @@ mod tests { | ||
oauth: false, | ||
oauth_scope: crate::scope::asked(false), | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
operators: Vec::new(), | ||
logs: false, | ||
logs_keep: crate::logs::KEEP, | ||
spaces: false, | ||
plc_url: "http://127.0.0.1:9".into(), | ||
handle_resolver: None, | ||
crates/hud-core/src/canvas/tools.rs+3−0
| @@ -496,6 +496,9 @@ mod tests { | ||
image_cdn: None, | ||
relay: None, | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
operators: Vec::new(), | ||
logs: false, | ||
logs_keep: crate::logs::KEEP, | ||
}) | ||
.unwrap() | ||
} | ||
crates/hud-core/src/oauth/tests.rs+3−0
| @@ -62,6 +62,9 @@ fn config(plc: &str) -> crate::Config { | ||
image_cdn: None, | ||
relay: None, | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
operators: Vec::new(), | ||
logs: false, | ||
logs_keep: crate::logs::KEEP, | ||
} | ||
} | ||
| ||
crates/hud-core/src/blobcache.rs+1−1
| @@ -252,7 +252,7 @@ impl BlobCache { | ||
scratch, | ||
filling: filling.clone(), | ||
}; | ||
tokio::spawn(download.run(writer, body, max)); | ||
crate::telemetry::spawn(download.run(writer, body, max)); | ||
Ok(filling) | ||
} | ||
| ||
crates/hud-core/src/cache.rs+23−1
| @@ -3,12 +3,14 @@ | ||
//! about `bytes` bytes, each entry weighed as it is put (`Weigh`); past | ||
//! either, the expired go, then those nearest their end, until it is three | ||
//! quarters full, which costs only lookups made again. A value weighing | ||
//! more than a quarter of `bytes` is not kept at all. | ||
//! more than a quarter of `bytes` is not kept at all. Each lookup is | ||
//! counted, a hit or a miss, for `/metrics` and the summary each minute. | ||
| ||
use serde_json::Value; | ||
use std::collections::{BTreeMap, HashMap}; | ||
use std::hash::Hash; | ||
use std::mem::size_of; | ||
use std::sync::atomic::{AtomicU64, Ordering}; | ||
use std::sync::{Arc, Mutex}; | ||
use std::time::{Duration, Instant}; | ||
| ||
| @@ -122,6 +124,8 @@ pub struct Ttl<K, V> { | ||
inner: Mutex<Inner<K, V>>, | ||
cap: usize, | ||
bytes: usize, | ||
hits: AtomicU64, | ||
misses: AtomicU64, | ||
} | ||
| ||
impl<K: Eq + Hash + Clone + Weigh, V: Clone + Weigh> Ttl<K, V> { | ||
| @@ -134,6 +138,8 @@ impl<K: Eq + Hash + Clone + Weigh, V: Clone + Weigh> Ttl<K, V> { | ||
}), | ||
cap, | ||
bytes, | ||
hits: AtomicU64::new(0), | ||
misses: AtomicU64::new(0), | ||
} | ||
} | ||
| ||
| @@ -145,6 +151,16 @@ impl<K: Eq + Hash + Clone + Weigh, V: Clone + Weigh> Ttl<K, V> { | ||
| ||
/// The value kept for `key`, if it has not expired. | ||
pub fn get(&self, key: &K) -> Option<V> { | ||
let found = self.found(key); | ||
let counted = match found { | ||
Some(_) => &self.hits, | ||
None => &self.misses, | ||
}; | ||
counted.fetch_add(1, Ordering::Relaxed); | ||
found | ||
} | ||
| ||
fn found(&self, key: &K) -> Option<V> { | ||
let mut inner = self.lock(); | ||
match inner.entries.get(key) { | ||
Some((until, _, v)) if *until > Instant::now() => Some(v.clone()), | ||
| @@ -156,6 +172,12 @@ impl<K: Eq + Hash + Clone + Weigh, V: Clone + Weigh> Ttl<K, V> { | ||
} | ||
} | ||
| ||
/// Its hits and misses since it was made. | ||
pub fn lookups(&self) -> (u64, u64) { | ||
let hits = self.hits.load(Ordering::Relaxed); | ||
(hits, self.misses.load(Ordering::Relaxed)) | ||
} | ||
| ||
/// Keep `value` for `key` for `ttl`, unless it weighs too much to. | ||
pub fn put(&self, key: K, value: V, ttl: Duration) { | ||
let weight = ENTRY + key.weigh() + value.weigh(); | ||
crates/hud-core/src/config.rs+11−1
crates/hud-core/src/identity.rs+6−0
crates/hud-core/src/join.rs+3−0
crates/hud-core/src/lib.rs+57−15
crates/hud-core/src/logs.rsnew+681−0
681 lines changed: not loaded until asked for.
crates/hud-core/src/net.rs+126−2
crates/hud-core/src/telemetry.rsnew+1137−0
1137 lines changed: not loaded until asked for.