chadtmiller.com/monolith
An atproto PDS
0
0
The admin reads the log and stats over HTTP, the CLI and MCP
crates/pds-cli/src/lib.rs+235−61
| @@ -1,5 +1,7 @@ | ||
//! The CLI: each method the server serves as a command, `pds <group> <command> | ||
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`). | ||
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`); | ||
//! and the admin's reads, `pds admin logs` and `pds admin stats`, which no | ||
//! lexicon makes, calling `/xrpc/_logs` and `/xrpc/_stats` (`READS`). | ||
//! | ||
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for | ||
//! a usage error (no call made), 3 for a server that cannot be reached. | ||
| @@ -68,6 +70,14 @@ fn command(args: &[String]) -> Result<u8, Stop> { | ||
print!("{}", group_help(group)); | ||
return Ok(0); | ||
} | ||
if let Some(r) = READS.iter().find(|r| group == ADMIN && r.command == name) { | ||
let flags: Vec<&Arg> = r.args.iter().collect(); | ||
let Some(args) = parse_flags(ADMIN, r.command, &flags, &args[2..])? else { | ||
print!("{}", help(ADMIN, r.command, Some(r.description), &flags)); | ||
return Ok(0); | ||
}; | ||
return call_read(r, args); | ||
} | ||
let Some(m) = pds_lexicon::by_command(group, name) else { | ||
return usage(format!( | ||
"pds {group} has no command {name}; `pds {group} --help` lists them" | ||
| @@ -80,6 +90,72 @@ fn command(args: &[String]) -> Result<u8, Stop> { | ||
call(m, args) | ||
} | ||
| ||
/// The group of the admin's reads, after the commands of | ||
/// `com.atproto.admin`'s methods. | ||
const ADMIN: &str = "admin"; | ||
| ||
/// One of the admin's reads (`spec/COMMANDS.md`, "The admin's reads"): a | ||
/// command of no lexicon's, its route, its description and its flags. | ||
struct AdminRead { | ||
command: &'static str, | ||
route: &'static str, | ||
description: &'static str, | ||
args: Vec<Arg>, | ||
} | ||
| ||
static READS: LazyLock<[AdminRead; 2]> = LazyLock::new(|| { | ||
let arg = |name: &str, ty: Type, description: &str, schema: Json| Arg { | ||
name: name.into(), | ||
ty, | ||
required: false, | ||
description: Some(description.into()), | ||
def: schema.clone(), | ||
schema, | ||
}; | ||
let string = || json!({ "type": "string" }); | ||
[ | ||
AdminRead { | ||
command: "logs", | ||
route: "_logs", | ||
description: "As the admin, the lines the server logged and kept in PDS_LOG_DIR, oldest first: the last of those of a trace, a message, a route, a level and above, or a time. Needs the admin's Basic auth.", | ||
args: vec![ | ||
arg("trace", Type::String, "Lines of this trace id.", string()), | ||
arg("msg", Type::String, "Lines of this msg.", string()), | ||
arg( | ||
"method", | ||
Type::String, | ||
"Lines of this route, as com.atproto.repo.createRecord or /oauth/token.", | ||
string(), | ||
), | ||
arg( | ||
"level", | ||
Type::String, | ||
"Lines at this level or above: debug, info, warn or error.", | ||
json!({ "type": "string", "enum": ["debug", "info", "warn", "error"] }), | ||
), | ||
arg( | ||
"minMs", | ||
Type::Integer, | ||
"Lines with an ms of this many milliseconds or more.", | ||
json!({ "type": "integer", "minimum": 0 }), | ||
), | ||
arg( | ||
"limit", | ||
Type::Integer, | ||
"How many, the last of those matched: 1 to 500, 100 if not given.", | ||
json!({ "type": "integer", "minimum": 1, "maximum": 500 }), | ||
), | ||
], | ||
}, | ||
AdminRead { | ||
command: "stats", | ||
route: "_stats", | ||
description: "As the admin, what the server counted since it started: its requests by route and status with their mean times, the requests it made, its syncs, its accounts and its firehose. Needs the admin's Basic auth.", | ||
args: vec![], | ||
}, | ||
] | ||
}); | ||
| ||
fn top_help() -> String { | ||
let mut out = String::from( | ||
"pds: an atproto PDS, and a command for each of its methods.\n\n\ | ||
| @@ -92,31 +168,31 @@ fn top_help() -> String { | ||
); | ||
for g in pds_lexicon::groups() { | ||
out.push_str(&format!(" {g}\n")); | ||
for (name, m) in commands(g) { | ||
out.push_str(&format!( | ||
" {name:<20} {}\n", | ||
m.description.as_deref().unwrap_or("") | ||
)); | ||
for (name, description) in listed(g) { | ||
out.push_str(&format!(" {name:<20} {description}\n")); | ||
} | ||
} | ||
out | ||
} | ||
| ||
fn commands(group: &str) -> Vec<(String, &'static Method)> { | ||
pds_lexicon::methods() | ||
/// A group's commands, each with its description: its methods', then, in | ||
/// `admin`, the admin's reads. | ||
fn listed(group: &str) -> Vec<(String, &'static str)> { | ||
let methods = pds_lexicon::methods() | ||
.iter() | ||
.filter(|m| m.group == group) | ||
.filter_map(|m| Some((m.command()?, m))) | ||
.collect() | ||
.filter_map(|m| Some((m.command()?, m.description.as_deref().unwrap_or("")))); | ||
let reads = READS | ||
.iter() | ||
.filter(|_| group == ADMIN) | ||
.map(|r| (r.command.to_string(), r.description)); | ||
methods.chain(reads).collect() | ||
} | ||
| ||
fn group_help(group: &str) -> String { | ||
let mut out = format!("Usage: pds {group} <command> [flags]\n\nCommands:\n"); | ||
for (name, m) in commands(group) { | ||
out.push_str(&format!( | ||
" {name:<20} {}\n", | ||
m.description.as_deref().unwrap_or("") | ||
)); | ||
for (name, description) in listed(group) { | ||
out.push_str(&format!(" {name:<20} {description}\n")); | ||
} | ||
out | ||
} | ||
| @@ -148,20 +224,27 @@ fn flags_of(m: &Method) -> impl Iterator<Item = &Arg> { | ||
} | ||
| ||
fn command_help(m: &Method) -> String { | ||
let mut out = format!( | ||
"Usage: pds {} {} [flags]\n", | ||
m.group, | ||
m.command().unwrap_or_default() | ||
); | ||
if let Some(d) = &m.description { | ||
let flags: Vec<&Arg> = flags_of(m).collect(); | ||
help( | ||
&m.group, | ||
&m.command().unwrap_or_default(), | ||
m.description.as_deref(), | ||
&flags, | ||
) | ||
} | ||
| ||
/// A command's help: its usage, its description, and its flags. | ||
fn help(group: &str, command: &str, description: Option<&str>, flags: &[&Arg]) -> String { | ||
let mut out = format!("Usage: pds {group} {command} [flags]\n"); | ||
if let Some(d) = description { | ||
out.push_str(&format!("\n{d}\n")); | ||
} | ||
if flags_of(m).next().is_none() { | ||
if flags.is_empty() { | ||
out.push_str("\nIt takes no flags.\n"); | ||
return out; | ||
} | ||
out.push_str("\nFlags:\n"); | ||
for a in flags_of(m) { | ||
for a in flags { | ||
let flag = format!("--{} {}", a.flag(), a.ty.placeholder()); | ||
let mut about = String::new(); | ||
if a.needed() { | ||
| @@ -184,6 +267,18 @@ fn command_help(m: &Method) -> String { | ||
| ||
/// A command's flags as its method's arguments, or None if they ask for help. | ||
fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop> { | ||
let args: Vec<&Arg> = flags_of(m).collect(); | ||
parse_flags(&m.group, &m.command().unwrap_or_default(), &args, flags) | ||
} | ||
| ||
/// The flags `pds <group> <command>` was given, as the arguments `args` | ||
/// names, or None if they ask for help. | ||
fn parse_flags( | ||
group: &str, | ||
command: &str, | ||
args: &[&Arg], | ||
flags: &[String], | ||
) -> Result<Option<Map<String, Json>>, Stop> { | ||
let mut values = Map::new(); | ||
let mut stdin_read = false; | ||
let mut i = 0; | ||
| @@ -200,12 +295,8 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop | ||
Some((n, v)) => (n, Some(v.to_string())), | ||
None => (flag, None), | ||
}; | ||
let Some(arg) = flags_of(m).find(|x| x.flag() == name) else { | ||
return usage(format!( | ||
"pds {} {} takes no flag --{name}", | ||
m.group, | ||
m.command().unwrap_or_default() | ||
)); | ||
let Some(arg) = args.iter().find(|x| x.flag() == name) else { | ||
return usage(format!("pds {group} {command} takes no flag --{name}")); | ||
}; | ||
if values.contains_key(&arg.name) { | ||
return usage(format!("--{name} is given twice")); | ||
| @@ -230,15 +321,14 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop | ||
let value = value(arg, text, &mut stdin_read)?; | ||
values.insert(arg.name.clone(), value); | ||
} | ||
let missing: Vec<String> = flags_of(m) | ||
let missing: Vec<String> = args | ||
.iter() | ||
.filter(|a| a.needed() && !values.contains_key(&a.name)) | ||
.map(|a| format!("--{}", a.flag())) | ||
.collect(); | ||
if !missing.is_empty() { | ||
return usage(format!( | ||
"pds {} {} needs {}", | ||
m.group, | ||
m.command().unwrap_or_default(), | ||
"pds {group} {command} needs {}", | ||
missing.join(", ") | ||
)); | ||
} | ||
| @@ -309,6 +399,26 @@ struct Server { | ||
} | ||
| ||
impl Server { | ||
/// The server `PDS_URL` names, called with `PDS_TOKEN` if set, else | ||
/// with the admin's password if `PDS_ADMIN_PASSWORD` is set. | ||
fn from_env() -> Result<Server, Stop> { | ||
let Ok(url) = std::env::var("PDS_URL") else { | ||
return Err(Stop::Unreachable( | ||
"PDS_URL is not set: it is the server's URL".into(), | ||
)); | ||
}; | ||
let http = reqwest::blocking::Client::builder() | ||
.no_proxy() | ||
.build() | ||
.map_err(|e| Stop::Unreachable(e.to_string()))?; | ||
Ok(Server { | ||
url: url.trim_end_matches('/').to_string(), | ||
token: std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty()), | ||
admin: std::env::var("PDS_ADMIN_PASSWORD").ok(), | ||
http, | ||
}) | ||
} | ||
| ||
/// Call a method: a query with `args` as its parameters, a procedure with | ||
/// them as its JSON input, or with `raw`, a type and bytes, as its body. | ||
fn send( | ||
| @@ -318,7 +428,7 @@ impl Server { | ||
raw: Option<(String, Vec<u8>)>, | ||
) -> Result<reqwest::blocking::Response, Stop> { | ||
let url = format!("{}/xrpc/{}", self.url, m.nsid); | ||
let mut req = match (m.kind, raw) { | ||
let req = match (m.kind, raw) { | ||
(Kind::Procedure, Some((encoding, body))) => self | ||
.http | ||
.post(&url) | ||
| @@ -331,19 +441,34 @@ impl Server { | ||
.post(&url) | ||
.header("content-type", JSON) | ||
.body(Json::Object(args.clone()).to_string()), | ||
_ => { | ||
let mut params = Vec::new(); | ||
for (k, v) in args { | ||
match v { | ||
Json::Array(items) => { | ||
params.extend(items.iter().map(|i| (k.as_str(), param_text(i)))) | ||
} | ||
v => params.push((k.as_str(), param_text(v))), | ||
} | ||
_ => return self.get(&url, args), | ||
}; | ||
self.with_auth(req) | ||
} | ||
| ||
/// `GET` of `url`, with `args` as its query's parameters. | ||
fn get( | ||
&self, | ||
url: &str, | ||
args: &Map<String, Json>, | ||
) -> Result<reqwest::blocking::Response, Stop> { | ||
let mut params = Vec::new(); | ||
for (k, v) in args { | ||
match v { | ||
Json::Array(items) => { | ||
params.extend(items.iter().map(|i| (k.as_str(), param_text(i)))) | ||
} | ||
self.http.get(&url).query(¶ms) | ||
v => params.push((k.as_str(), param_text(v))), | ||
} | ||
}; | ||
} | ||
self.with_auth(self.http.get(url).query(¶ms)) | ||
} | ||
| ||
/// Send `req` with the token, or else the admin's `Basic` auth. | ||
fn with_auth( | ||
&self, | ||
mut req: reqwest::blocking::RequestBuilder, | ||
) -> Result<reqwest::blocking::Response, Stop> { | ||
if let Some(t) = &self.token { | ||
req = req.bearer_auth(t); | ||
} else if let Some(password) = &self.admin { | ||
| @@ -418,22 +543,7 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
missing.join(", ") | ||
)); | ||
} | ||
let Ok(url) = std::env::var("PDS_URL") else { | ||
return Err(Stop::Unreachable( | ||
"PDS_URL is not set: it is the server's URL".into(), | ||
)); | ||
}; | ||
let http = reqwest::blocking::Client::builder() | ||
.no_proxy() | ||
.build() | ||
.map_err(|e| Stop::Unreachable(e.to_string()))?; | ||
let admin = std::env::var("PDS_ADMIN_PASSWORD").ok(); | ||
let server = Server { | ||
url: url.trim_end_matches('/').to_string(), | ||
token, | ||
admin, | ||
http, | ||
}; | ||
let server = Server::from_env()?; | ||
// A token getSession does not answer for leaves them out, for the method to answer it. | ||
if server.token.is_some() | ||
&& !left_out.is_empty() | ||
| @@ -486,6 +596,27 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
Ok(0) | ||
} | ||
| ||
/// Call one of the admin's reads: its JSON answer, printed as the server | ||
/// sent it, one line (`_logs`' lines each as the server wrote it); or its | ||
/// error, printed as a method's. | ||
fn call_read(r: &AdminRead, args: Map<String, Json>) -> Result<u8, Stop> { | ||
let server = Server::from_env()?; | ||
let res = server.get(&format!("{}/xrpc/{}", server.url, r.route), &args)?; | ||
let status = res.status().as_u16(); | ||
let text = res | ||
.text() | ||
.map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?; | ||
match serde_json::from_str::<Json>(&text) { | ||
Ok(_) if (200..300).contains(&status) => { | ||
let mut out = std::io::stdout().lock(); | ||
let _ = writeln!(out, "{}", text.trim()); | ||
Ok(0) | ||
} | ||
Ok(body) => Ok(print_error(status, &body)), | ||
Err(_) => Ok(print_error(status, &Json::String(text))), | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| @@ -651,4 +782,47 @@ mod tests { | ||
assert!(flags("com.atproto.repo.importRepo", &["--encoding", "a/b"]).is_err()); | ||
assert!(command_help(import).contains("It takes no flags.")); | ||
} | ||
| ||
/// The admin's reads are commands of `admin`, after its methods', with | ||
/// the spec's descriptions and `logs`'s flags. | ||
#[test] | ||
fn admin_reads() { | ||
let names: Vec<String> = listed(ADMIN).into_iter().map(|(n, _)| n).collect(); | ||
assert_eq!(&names[names.len() - 2..], ["logs", "stats"]); | ||
assert!(names.len() > 2); | ||
let help = group_help(ADMIN); | ||
assert!(help.contains("As the admin, what the server counted since it started")); | ||
let logs = &READS[0]; | ||
let flags: Vec<&Arg> = logs.args.iter().collect(); | ||
let text = help_of(logs); | ||
for f in [ | ||
"--trace", "--msg", "--method", "--level", "--min-ms", "--limit", | ||
] { | ||
assert!(text.contains(f), "{f}"); | ||
} | ||
let parse = |argv: &[&str]| { | ||
let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect(); | ||
parse_flags(ADMIN, "logs", &flags, &argv) | ||
}; | ||
assert_eq!( | ||
parse(&["--level", "info", "--min-ms", "5", "--limit=3"]) | ||
.ok() | ||
.flatten() | ||
.map(Json::Object), | ||
Some(json!({ "level": "info", "minMs": 5, "limit": 3 })) | ||
); | ||
for bad in [ | ||
&["--limit", "x"][..], | ||
&["--no-such-flag", "x"], | ||
&["--level"], | ||
] { | ||
assert!(matches!(parse(bad), Err(Stop::Usage(_))), "{bad:?}"); | ||
} | ||
assert!(help_of(&READS[1]).contains("It takes no flags.")); | ||
} | ||
| ||
fn help_of(r: &AdminRead) -> String { | ||
let flags: Vec<&Arg> = r.args.iter().collect(); | ||
help(ADMIN, r.command, Some(r.description), &flags) | ||
} | ||
} | ||
crates/pds-server/src/ops/admin.rsnew+459−0
459 lines changed: not loaded until asked for.
crates/pds-server/src/ops/kept.rsnew+377−0
| @@ -0,0 +1,377 @@ | ||
//! The log kept in `PDS_LOG_DIR`, for the admin to read back | ||
//! (`spec/OPERATIONS.md`, "Kept"). Each line written to standard output is | ||
//! appended to `pds.log` too, by one `write` under the log's lock. Before a | ||
//! line would take `pds.log` past half of `PDS_LOG_KEEP_BYTES`, it is renamed | ||
//! over `pds.log.1` and a new one started: so neither file is ever past half, | ||
//! the two together never past the whole, and the newest lines of half of it | ||
//! are always in them. A line longer than half is not kept. | ||
//! | ||
//! `_logs` reads them (`Snapshot`) from handles and lengths taken under the | ||
//! lock, with no lock held as it reads, newest line first: a rotation since | ||
//! leaves the handles on the files they were, so the read sees the lines kept | ||
//! when it began. | ||
| ||
use std::fs::{File, OpenOptions}; | ||
use std::io::{self, Write}; | ||
use std::os::unix::fs::FileExt; | ||
use std::path::{Path, PathBuf}; | ||
| ||
/// The file lines are appended to. | ||
const CURRENT: &str = "pds.log"; | ||
/// The one before, renamed over by `CURRENT` once it is full. | ||
const PREVIOUS: &str = "pds.log.1"; | ||
/// `PDS_LOG_KEEP_BYTES`: its least, and its default. | ||
const LEAST: u64 = 65_536; | ||
const DEFAULT: u64 = 64 << 20; | ||
/// How much of a file a read takes at once, from its end. | ||
const CHUNK: u64 = 64 << 10; | ||
| ||
/// What the environment says of where the log is kept: the directory made, | ||
/// and `CURRENT` opened, so that one that cannot be is found before the start. | ||
pub(super) struct Settings { | ||
dir: PathBuf, | ||
keep: u64, | ||
current: File, | ||
} | ||
| ||
impl Settings { | ||
/// `PDS_LOG_DIR` and `PDS_LOG_KEEP_BYTES`; None with no directory. | ||
pub fn from_env() -> Result<Option<Settings>, String> { | ||
let keep = match super::var("PDS_LOG_KEEP_BYTES") { | ||
None => DEFAULT, | ||
Some(v) => v | ||
.trim() | ||
.parse::<u64>() | ||
.ok() | ||
.filter(|n| *n >= LEAST) | ||
.ok_or_else(|| { | ||
format!("PDS_LOG_KEEP_BYTES is {v:?}, not a number of bytes of {LEAST} or more") | ||
})?, | ||
}; | ||
let Some(dir) = super::var("PDS_LOG_DIR") else { | ||
return Ok(None); | ||
}; | ||
let dir = PathBuf::from(dir); | ||
let cannot = |e: &dyn std::fmt::Display| { | ||
format!( | ||
"PDS_LOG_DIR {} cannot be made or written to: {e}", | ||
dir.display() | ||
) | ||
}; | ||
pds_store::make_dirs(&dir).map_err(|e| cannot(&e))?; | ||
rustix::fs::access(&dir, rustix::fs::Access::WRITE_OK).map_err(|e| cannot(&e))?; | ||
let current = open_current(&dir.join(CURRENT)).map_err(|e| cannot(&e))?; | ||
Ok(Some(Settings { dir, keep, current })) | ||
} | ||
} | ||
| ||
/// `CURRENT`, made if missing, open to append to and read. | ||
fn open_current(path: &Path) -> io::Result<File> { | ||
pds_store::open_private( | ||
path, | ||
OpenOptions::new().create(true).append(true).read(true), | ||
) | ||
} | ||
| ||
/// The kept files, as the writer has them. | ||
pub(super) struct Kept { | ||
dir: PathBuf, | ||
/// Half of `PDS_LOG_KEEP_BYTES`: the most each file holds. | ||
half: u64, | ||
/// None once starting a new one failed, until one is made. | ||
current: Option<File>, | ||
current_len: u64, | ||
previous: Option<File>, | ||
previous_len: u64, | ||
/// `current` ends in no `\n`, as a write cut short, or a power lost | ||
/// mid-line, leaves it: the next line is written after one. | ||
torn: bool, | ||
} | ||
| ||
impl Kept { | ||
/// Carry on after the lines the directory holds, as the last start left | ||
/// them; with more than this start's half in either file, as when | ||
/// `PDS_LOG_KEEP_BYTES` was lowered, only the newest lines of half. | ||
pub fn open(s: Settings) -> Kept { | ||
let previous = File::open(s.dir.join(PREVIOUS)).ok(); | ||
let len = |f: &File| f.metadata().map_or(0, |m| m.len()); | ||
let mut k = Kept { | ||
half: s.keep / 2, | ||
current_len: len(&s.current), | ||
previous_len: previous.as_ref().map_or(0, len), | ||
current: Some(s.current), | ||
previous, | ||
dir: s.dir, | ||
torn: false, | ||
}; | ||
if k.current_len > k.half || k.previous_len > k.half { | ||
k.trim(); | ||
} else if k.current_len > 0 { | ||
let mut last = [0u8]; | ||
let read = k | ||
.current | ||
.as_ref() | ||
.map(|f| f.read_exact_at(&mut last, k.current_len - 1)); | ||
k.torn = matches!(read, Some(Ok(()))) && last[0] != b'\n'; | ||
} | ||
k | ||
} | ||
| ||
/// Keep only the newest whole lines of at most half, in `PREVIOUS`, | ||
/// and start `CURRENT` again: what is let go is let go first. | ||
fn trim(&mut self) { | ||
let mut tail = self.snapshot().newest_bytes(self.half); | ||
// A line cut short at the end is no line. | ||
let whole = tail.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1); | ||
tail.truncate(whole); | ||
let previous = self.dir.join(PREVIOUS); | ||
self.previous = None; | ||
self.previous_len = 0; | ||
let _ = std::fs::remove_file(&previous); | ||
if let Some(f) = &self.current { | ||
let _ = f.set_len(0); | ||
} | ||
self.current_len = 0; | ||
let written = pds_store::open_private( | ||
&previous, | ||
OpenOptions::new() | ||
.create(true) | ||
.truncate(true) | ||
.write(true) | ||
.read(true), | ||
) | ||
.and_then(|mut f| f.write_all(&tail).map(|()| f)); | ||
if let Ok(f) = written { | ||
self.previous = Some(f); | ||
self.previous_len = tail.len() as u64; | ||
} | ||
} | ||
| ||
/// Keep a line, `\n` and all, failures ignored. | ||
pub fn write(&mut self, line: &[u8]) { | ||
let len = line.len() as u64; | ||
if len > self.half { | ||
return; | ||
} | ||
if (self.current.is_none() || self.current_len + len + u64::from(self.torn) > self.half) | ||
&& self.rotate().is_err() | ||
{ | ||
return; | ||
} | ||
let Some(f) = &self.current else { return }; | ||
let mut f = f; | ||
let wrote = if self.torn { | ||
let mut b = Vec::with_capacity(line.len() + 1); | ||
b.push(b'\n'); | ||
b.extend_from_slice(line); | ||
f.write(&b).map(|n| (n, b.len())) | ||
} else { | ||
f.write(line).map(|n| (n, line.len())) | ||
}; | ||
if let Ok((n, of)) = wrote { | ||
self.current_len += n as u64; | ||
self.torn = n < of; | ||
} | ||
} | ||
| ||
/// `CURRENT` becomes `PREVIOUS`, and a new one is started; with none | ||
/// (starting one failed), only the new one. | ||
fn rotate(&mut self) -> io::Result<()> { | ||
let current = self.dir.join(CURRENT); | ||
if let Some(f) = self.current.take() { | ||
if let Err(e) = std::fs::rename(¤t, self.dir.join(PREVIOUS)) { | ||
self.current = Some(f); | ||
return Err(e); | ||
} | ||
self.previous = Some(f); | ||
self.previous_len = self.current_len; | ||
} | ||
self.current_len = 0; | ||
self.torn = false; | ||
let f = open_current(¤t)?; | ||
f.set_len(0)?; | ||
self.current = Some(f); | ||
Ok(()) | ||
} | ||
| ||
/// The files as they are now, to read with no lock held. | ||
pub fn snapshot(&self) -> Snapshot { | ||
let mut files = Vec::with_capacity(2); | ||
for (f, len) in [ | ||
(&self.current, self.current_len), | ||
(&self.previous, self.previous_len), | ||
] { | ||
if let Some(f) = f.as_ref().and_then(|f| f.try_clone().ok()) { | ||
files.push((f, len)); | ||
} | ||
} | ||
Snapshot { files } | ||
} | ||
} | ||
| ||
/// The kept files as they were when it was taken, newest first, each to | ||
/// the length it had then. | ||
pub(crate) struct Snapshot { | ||
files: Vec<(File, u64)>, | ||
} | ||
| ||
impl Snapshot { | ||
/// Each line, newest first, until `each` answers false. Lines do not run | ||
/// from one file into the other; empty ones are passed over. | ||
pub fn lines_back(&self, mut each: impl FnMut(&[u8]) -> bool) -> io::Result<()> { | ||
let mut buf: Vec<u8> = Vec::new(); | ||
for (f, len) in &self.files { | ||
// `buf` holds, past what is read next, a line's start not yet found. | ||
buf.clear(); | ||
let mut pos = *len; | ||
loop { | ||
let start = pos.saturating_sub(CHUNK); | ||
let n = (pos - start) as usize; | ||
buf.splice(0..0, std::iter::repeat_n(0, n)); | ||
f.read_exact_at(&mut buf[..n], start)?; | ||
let mut end = buf.len(); | ||
while let Some(i) = buf[..end].iter().rposition(|b| *b == b'\n') { | ||
if end > i + 1 && !each(&buf[i + 1..end]) { | ||
return Ok(()); | ||
} | ||
end = i; | ||
} | ||
buf.truncate(end); | ||
pos = start; | ||
if pos == 0 { | ||
break; | ||
} | ||
} | ||
if !buf.is_empty() && !each(&buf) { | ||
return Ok(()); | ||
} | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// The last `n` bytes of the files, oldest first, starting at a line's | ||
/// start: the whole lines that fit. | ||
fn newest_bytes(&self, n: u64) -> Vec<u8> { | ||
let mut lines: Vec<Vec<u8>> = Vec::new(); | ||
let mut total = 0u64; | ||
let _ = self.lines_back(|line| { | ||
total += line.len() as u64 + 1; | ||
if total > n { | ||
return false; | ||
} | ||
lines.push(line.to_vec()); | ||
true | ||
}); | ||
let mut out = Vec::with_capacity(total.min(n) as usize); | ||
for line in lines.iter().rev() { | ||
out.extend_from_slice(line); | ||
out.push(b'\n'); | ||
} | ||
out | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
fn scratch(name: &str) -> PathBuf { | ||
let d = std::env::temp_dir().join(format!("pds-kept-{name}-{}", std::process::id())); | ||
let _ = std::fs::remove_dir_all(&d); | ||
std::fs::create_dir_all(&d).unwrap(); | ||
d | ||
} | ||
| ||
fn open(dir: &Path, keep: u64) -> Kept { | ||
Kept::open(Settings { | ||
dir: dir.to_path_buf(), | ||
keep, | ||
current: open_current(&dir.join(CURRENT)).unwrap(), | ||
}) | ||
} | ||
| ||
fn back(k: &Kept) -> Vec<String> { | ||
let mut out = Vec::new(); | ||
k.snapshot() | ||
.lines_back(|l| { | ||
out.push(String::from_utf8(l.to_vec()).unwrap()); | ||
true | ||
}) | ||
.unwrap(); | ||
out | ||
} | ||
| ||
fn size(dir: &Path) -> u64 { | ||
std::fs::read_dir(dir) | ||
.unwrap() | ||
.map(|e| e.unwrap().metadata().unwrap().len()) | ||
.sum() | ||
} | ||
| ||
/// The files never hold more than the whole, the newest lines of half | ||
/// are always there, and a line longer than half is not kept. | ||
#[test] | ||
fn rotates_within_bounds() { | ||
let dir = scratch("rotate"); | ||
let mut k = open(&dir, 1000); | ||
let mut all = Vec::new(); | ||
for i in 0..400 { | ||
let line = format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(i % 37)); | ||
k.write(format!("{line}\n").as_bytes()); | ||
all.push(line); | ||
assert!(size(&dir) <= 1000); | ||
let kept = back(&k); | ||
let mut want = 0; | ||
let mut sum = 0; | ||
for l in all.iter().rev() { | ||
sum += l.len() + 1; | ||
if sum > 500 { | ||
break; | ||
} | ||
want += 1; | ||
} | ||
assert!(kept.len() >= want, "{i}: {} < {want}", kept.len()); | ||
assert_eq!( | ||
kept, | ||
all.iter() | ||
.rev() | ||
.take(kept.len()) | ||
.cloned() | ||
.collect::<Vec<_>>() | ||
); | ||
} | ||
k.write(format!("{}\n", "y".repeat(500)).as_bytes()); | ||
assert_eq!(back(&k)[0], all[399]); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A start carries on after the lines there; a torn line is not glued to | ||
/// the next; a lower `PDS_LOG_KEEP_BYTES` keeps only the newest of half. | ||
#[test] | ||
fn starts_again() { | ||
let dir = scratch("again"); | ||
let mut k = open(&dir, 1000); | ||
k.write(b"{\"a\":1}\n"); | ||
drop(k); | ||
std::fs::OpenOptions::new() | ||
.append(true) | ||
.open(dir.join(CURRENT)) | ||
.unwrap() | ||
.write_all(b"{\"cut") | ||
.unwrap(); | ||
let mut k = open(&dir, 1000); | ||
k.write(b"{\"b\":2}\n"); | ||
assert_eq!(back(&k), ["{\"b\":2}", "{\"cut", "{\"a\":1}"]); | ||
for i in 0..100 { | ||
k.write(format!("{{\"c\":{i:03}}}\n").as_bytes()); | ||
} | ||
drop(k); | ||
let k = open(&dir, 200); | ||
assert!(size(&dir) <= 200); | ||
let kept = back(&k); | ||
assert_eq!(kept.len(), 10); | ||
assert_eq!(kept[0], "{\"c\":099}"); | ||
assert_eq!(kept[9], "{\"c\":090}"); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
} | ||
crates/pds-server/src/ops/metrics.rs+102−27
| @@ -1,11 +1,13 @@ | ||
//! The server's metrics, in Prometheus' text format, version 0.0.4, on | ||
//! `127.0.0.1:PDS_METRICS_PORT` (`spec/OPERATIONS.md`). Every label's | ||
//! values are bounded: the routes served, statuses, and the outbound targets. | ||
//! `127.0.0.1:PDS_METRICS_PORT` (`spec/OPERATIONS.md`), and as `_stats` | ||
//! answers them (`stats`). Every label's values are bounded: the routes | ||
//! served, statuses, and the outbound targets. | ||
| ||
use super::trace::Target; | ||
use crate::{Shared, read}; | ||
use axum::body::Body; | ||
use axum::http::{Method, Response, StatusCode, header}; | ||
use serde_json::{Map, Value as Json, json}; | ||
use std::collections::BTreeMap; | ||
use std::fmt::Write; | ||
use std::sync::{Mutex, PoisonError}; | ||
| @@ -128,27 +130,7 @@ impl Metrics { | ||
| ||
/// The exposition, with the gauges read from `svc` now. | ||
fn render(&self, svc: &Shared) -> String { | ||
// As `listRepos` lists them: the count the directory keeps. The | ||
// accounts' files are found by DID, of an account loaded or not. | ||
let (accounts, dids) = { | ||
let d = read(&svc.directory); | ||
(d.count(), d.dids()) | ||
}; | ||
// Every generation's log not yet folded away, and the checkpoints: | ||
// of an account or a store not loaded, as its files' sizes are, | ||
// which loads none. | ||
let log_bytes = svc.log.log_bytes() | ||
+ svc.log.checkpoint_bytes() | ||
+ dids | ||
.iter() | ||
.map(|did| { | ||
let loaded = read(&svc.directory).by_did.get(did).cloned(); | ||
match loaded { | ||
Some(a) => a.store.log_bytes(), | ||
None => crate::directory::files_bytes(&svc.dir, did), | ||
} | ||
}) | ||
.sum::<u64>(); | ||
let g = Gauges::of(svc); | ||
let mut out = String::with_capacity(8192); | ||
let family = |out: &mut String, name: &str, ty: &str, help: &str| { | ||
let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {ty}"); | ||
| @@ -199,28 +181,28 @@ impl Metrics { | ||
"gauge", | ||
"The seq of the firehose's last event.", | ||
); | ||
let _ = writeln!(out, "pds_firehose_seq {}", svc.events.published()); | ||
let _ = writeln!(out, "pds_firehose_seq {}", g.seq); | ||
family( | ||
&mut out, | ||
"pds_firehose_subscribers", | ||
"gauge", | ||
"subscribeRepos connections open.", | ||
); | ||
let _ = writeln!(out, "pds_firehose_subscribers {}", svc.events.subscribers()); | ||
let _ = writeln!(out, "pds_firehose_subscribers {}", g.subscribers); | ||
family( | ||
&mut out, | ||
"pds_accounts", | ||
"gauge", | ||
"The accounts the server holds.", | ||
); | ||
let _ = writeln!(out, "pds_accounts {accounts}"); | ||
let _ = writeln!(out, "pds_accounts {}", g.accounts); | ||
family( | ||
&mut out, | ||
"pds_log_bytes", | ||
"gauge", | ||
"The bytes of the logs the server keeps its state in.", | ||
); | ||
let _ = writeln!(out, "pds_log_bytes {log_bytes}"); | ||
let _ = writeln!(out, "pds_log_bytes {}", g.log_bytes); | ||
family( | ||
&mut out, | ||
"pds_fsync_duration_seconds", | ||
| @@ -255,6 +237,99 @@ impl Metrics { | ||
} | ||
out | ||
} | ||
| ||
/// What `_stats` answers (`spec/OPERATIONS.md`, "_stats"): the same | ||
/// counters, the gauges read from `svc` now, `started` the time of | ||
/// this start's `start` line. | ||
pub fn stats(&self, svc: &Shared, started: &str) -> Json { | ||
let g = Gauges::of(svc); | ||
let m = self.lock(); | ||
let ms = |h: &Histogram| { | ||
if h.count == 0 { | ||
0.0 | ||
} else { | ||
h.sum / h.count as f64 * 1000.0 | ||
} | ||
}; | ||
let mut routes: Vec<(&str, &Histogram)> = | ||
m.durations.iter().map(|(r, h)| (*r, h)).collect(); | ||
routes.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(b.0))); | ||
let routes: Vec<Json> = routes | ||
.into_iter() | ||
.map(|(route, h)| { | ||
let statuses: Map<String, Json> = m | ||
.requests | ||
.range((route, 0)..=(route, u16::MAX)) | ||
.map(|((_, status), n)| (status.to_string(), json!(n))) | ||
.collect(); | ||
json!({ | ||
"method": route, | ||
"count": h.count, | ||
"statuses": statuses, | ||
"rateLimited": m.limited.get(route).copied().unwrap_or(0), | ||
"meanMs": ms(h), | ||
}) | ||
}) | ||
.collect(); | ||
let outbound: Vec<Json> = m | ||
.outbound_durations | ||
.iter() | ||
.map(|(target, h)| { | ||
let n = |outcome| m.outbound.get(&(*target, outcome)).copied().unwrap_or(0); | ||
json!({ "target": target, "ok": n("ok"), "error": n("error"), "meanMs": ms(h) }) | ||
}) | ||
.collect(); | ||
json!({ | ||
"version": super::VERSION, | ||
"started": started, | ||
"accounts": g.accounts, | ||
"logBytes": g.log_bytes, | ||
"firehose": { "seq": g.seq, "subscribers": g.subscribers }, | ||
"routes": routes, | ||
"outbound": outbound, | ||
"fsync": { "count": m.fsync.count, "meanMs": ms(&m.fsync) }, | ||
}) | ||
} | ||
} | ||
| ||
/// The gauges, as they are now. | ||
struct Gauges { | ||
accounts: u64, | ||
log_bytes: u64, | ||
seq: u64, | ||
subscribers: u64, | ||
} | ||
| ||
impl Gauges { | ||
fn of(svc: &Shared) -> Gauges { | ||
// As `listRepos` lists them: the count the directory keeps. The | ||
// accounts' files are found by DID, of an account loaded or not. | ||
let (accounts, dids) = { | ||
let d = read(&svc.directory); | ||
(d.count(), d.dids()) | ||
}; | ||
// Every generation's log not yet folded away, and the checkpoints: | ||
// of an account or a store not loaded, as its files' sizes are, | ||
// which loads none. | ||
let log_bytes = svc.log.log_bytes() | ||
+ svc.log.checkpoint_bytes() | ||
+ dids | ||
.iter() | ||
.map(|did| { | ||
let loaded = read(&svc.directory).by_did.get(did).cloned(); | ||
match loaded { | ||
Some(a) => a.store.log_bytes(), | ||
None => crate::directory::files_bytes(&svc.dir, did), | ||
} | ||
}) | ||
.sum::<u64>(); | ||
Gauges { | ||
accounts, | ||
log_bytes, | ||
seq: svc.events.published(), | ||
subscribers: svc.events.subscribers() as u64, | ||
} | ||
} | ||
} | ||
| ||
fn escape(v: &str) -> String { | ||
crates/pds-server/src/lib.rs+4−1
| @@ -31,7 +31,8 @@ | ||
//! found by DID, handle, email or reset token and loaded on first use, | ||
//! `directory`, what it holds of each account's store in memory, loaded on | ||
//! first use and let go, `cache`, and what it tells whoever runs it, its | ||
//! log, health, metrics, traces and shutdown, `ops`. | ||
//! log, kept lines, health, metrics, traces and shutdown, and the admin's | ||
//! reads of them, `ops`. | ||
| ||
#![forbid(unsafe_code)] | ||
| ||
| @@ -794,6 +795,8 @@ fn router(svc: Shared) -> Router { | ||
) | ||
.route("/", any(ops::root)) | ||
.route("/xrpc/_health", any(ops::health)) | ||
.route("/xrpc/_logs", any(ops::logs)) | ||
.route("/xrpc/_stats", any(ops::stats)) | ||
.route("/xrpc/com.atproto.repo.uploadBlob", any(blobs::upload)) | ||
.route("/xrpc/{*method}", any(handle)) | ||
.route("/mcp", any(mcp::endpoint)) | ||
crates/pds-server/src/mcp.rs+56−19
| @@ -5,11 +5,12 @@ | ||
//! requests after it that name a legacy version in `MCP-Protocol-Version`, | ||
//! as 2025-11-25 or 2025-06-18, statelessly too, with no session. Each | ||
//! method with a JSON answer, or none, is a tool, called through the same | ||
//! handling as XRPC. | ||
//! handling as XRPC; after them, the admin's reads, `admin_logs` and | ||
//! `admin_stats`, answered as `/xrpc/_logs` and `/xrpc/_stats` (`ops::read`). | ||
| ||
use crate::oauth::mcp::Token as McpToken; | ||
use crate::sessions::Bearer; | ||
use crate::{Auth, Call, Resp, Shared, XrpcError, answer, authorization, limits, scopes}; | ||
use crate::{Auth, Call, Resp, Shared, XrpcError, answer, authorization, limits, ops, scopes}; | ||
use axum::body::Body; | ||
use axum::extract::{Extension, State}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; | ||
| @@ -571,7 +572,7 @@ fn discover() -> Json { | ||
}) | ||
} | ||
| ||
/// Every tool, the same in either era. | ||
/// Every tool, the same in either era: each method's, then the admin's reads'. | ||
fn tools() -> Vec<Json> { | ||
pds_lexicon::methods() | ||
.iter() | ||
| @@ -586,6 +587,7 @@ fn tools() -> Vec<Json> { | ||
} | ||
Some(tool) | ||
}) | ||
.chain(ops::Read::tools()) | ||
.collect() | ||
} | ||
| ||
| @@ -601,6 +603,20 @@ fn param_text(v: &Json) -> String { | ||
} | ||
} | ||
| ||
/// A query's parameters, from a tool's arguments: an array as the parameter | ||
/// repeated, a null left out. | ||
fn query_params(args: &Map<String, Json>) -> Vec<(String, String)> { | ||
let mut params = Vec::new(); | ||
for (k, v) in args { | ||
match v { | ||
Json::Null => {} | ||
Json::Array(items) => params.extend(items.iter().map(|i| (k.clone(), param_text(i)))), | ||
v => params.push((k.clone(), param_text(v))), | ||
} | ||
} | ||
params | ||
} | ||
| ||
/// Call a tool's method, with its arguments as the query's parameters or the | ||
/// procedure's input, and the request's `Authorization` header, from `client`: | ||
/// its answer, and whether it is an error the method answered. An MCP | ||
| @@ -616,13 +632,19 @@ async fn call_tool( | ||
client: String, | ||
) -> Result<(Json, bool), RpcError> { | ||
let bearer = Bearer::of(authorization.as_deref()); | ||
let Some(m): Option<&'static Lexicon> = pds_lexicon::by_tool(name) else { | ||
return Err(rpc_err( | ||
StatusCode::OK, | ||
INVALID_PARAMS, | ||
format!("Unknown tool: {name}"), | ||
)); | ||
}; | ||
// A method's tool, or one of the admin's reads'. | ||
let tool: Result<&'static Lexicon, ops::Read> = | ||
match (pds_lexicon::by_tool(name), ops::Read::of_tool(name)) { | ||
(Some(m), _) => Ok(m), | ||
(None, Some(read)) => Err(read), | ||
(None, None) => { | ||
return Err(rpc_err( | ||
StatusCode::OK, | ||
INVALID_PARAMS, | ||
format!("Unknown tool: {name}"), | ||
)); | ||
} | ||
}; | ||
let mut args = match arguments { | ||
None | Some(Json::Null) => Map::new(), | ||
Some(Json::Object(a)) => a.clone(), | ||
| @@ -648,6 +670,29 @@ async fn call_tool( | ||
}, | ||
_ => None, | ||
}; | ||
// The admin's reads, as XRPC answers them; a token, of an MCP session or | ||
// not, is no admin. | ||
let m = match tool { | ||
Ok(m) => m, | ||
Err(read) => { | ||
let params = query_params(&args); | ||
let call = Call { | ||
nsid: read.route(), | ||
method: &Method::GET, | ||
params: ¶ms, | ||
body: &[], | ||
bearer, | ||
headers: &HeaderMap::new(), | ||
client, | ||
charged: OnceLock::new(), | ||
http: None, | ||
}; | ||
return Ok(match ops::read(st, read, &call).await { | ||
Ok(a) => (a.json(), false), | ||
Err(e) => (json!({ "error": e.name, "message": e.message }), true), | ||
}); | ||
} | ||
}; | ||
// The token's scope, for a step-up if the call is refused for it. | ||
let granted = mcp.as_ref().map(|(_, a)| a.scope.clone()); | ||
// A `repo` or `did` left out is the token's account's; with no token, or | ||
| @@ -679,15 +724,7 @@ async fn call_tool( | ||
String::new(), | ||
); | ||
if m.kind == Kind::Query { | ||
for (k, v) in &args { | ||
match v { | ||
Json::Null => {} | ||
Json::Array(items) => { | ||
params.extend(items.iter().map(|i| (k.clone(), param_text(i)))) | ||
} | ||
v => params.push((k.clone(), param_text(v))), | ||
} | ||
} | ||
params = query_params(&args); | ||
} else if m.input.is_some() || !args.is_empty() { | ||
// A procedure that takes no input is sent none, unless given arguments, which it refuses. | ||
body = Json::Object(args).to_string(); | ||
crates/pds-server/src/ops.rs+66−16
| @@ -1,16 +1,22 @@ | ||
//! What the server tells whoever runs it, as `spec/OPERATIONS.md` says: its | ||
//! log, JSON lines on standard output; `/xrpc/_health`; its metrics | ||
//! (`metrics`); its traces (`trace`); and how it shuts down, and says on its | ||
//! next start whether the last one did. | ||
//! log, JSON lines on standard output, and kept in `PDS_LOG_DIR` too | ||
//! (`kept`); `/xrpc/_health`; its metrics (`metrics`); its traces | ||
//! (`trace`); the admin's reads of the kept lines and of the metrics, | ||
//! `/xrpc/_logs` and `/xrpc/_stats` (`admin`); and how it shuts down, and | ||
//! says on its next start whether the last one did. | ||
//! | ||
//! Every request goes through `Seen`, in the one place connections are | ||
//! served (`limits::serve`): its route, its trace, and once its answer is | ||
//! whole, before the last byte of it is sent, its log line, its metrics and | ||
//! its span. | ||
| ||
mod admin; | ||
mod kept; | ||
mod metrics; | ||
mod trace; | ||
| ||
pub(crate) use admin::{Read, logs, read, stats}; | ||
| ||
pub(crate) use trace::{Target, execute, send}; | ||
| ||
use crate::Shared; | ||
| @@ -68,6 +74,7 @@ pub(crate) struct Settings { | ||
level: Level, | ||
metrics_port: Option<u16>, | ||
trace: trace::Settings, | ||
kept: Option<kept::Settings>, | ||
} | ||
| ||
impl Settings { | ||
| @@ -102,18 +109,28 @@ impl Settings { | ||
level, | ||
metrics_port, | ||
trace: trace::Settings::from_env()?, | ||
kept: kept::Settings::from_env()?, | ||
}) | ||
} | ||
} | ||
| ||
/// Where lines go: standard output, and the files they are kept in, if any. | ||
struct Out { | ||
/// Written to with one `write` a line. | ||
stdout: Option<File>, | ||
kept: Option<kept::Kept>, | ||
} | ||
| ||
/// What every request and every line shares. | ||
struct Ops { | ||
level: Level, | ||
/// Standard output, written to with one `write` a line. | ||
out: Option<Mutex<File>>, | ||
/// Held while a line is written, to both. | ||
out: Mutex<Out>, | ||
metrics: metrics::Metrics, | ||
/// Where spans go, if they are exported. | ||
exporter: Option<trace::Exporter>, | ||
/// The `time` of this start's `start` line. | ||
started: String, | ||
} | ||
| ||
static OPS: OnceLock<Ops> = OnceLock::new(); | ||
| @@ -122,9 +139,13 @@ static OPS: OnceLock<Ops> = OnceLock::new(); | ||
fn ops() -> &'static Ops { | ||
OPS.get_or_init(|| Ops { | ||
level: Level::Off, | ||
out: None, | ||
out: Mutex::new(Out { | ||
stdout: None, | ||
kept: None, | ||
}), | ||
metrics: metrics::Metrics::default(), | ||
exporter: None, | ||
started: crate::events::timestamp(), | ||
}) | ||
} | ||
| ||
| @@ -139,14 +160,20 @@ fn stdout() -> Option<File> { | ||
} | ||
| ||
/// Take the settings, and write the `start` line: the environment is read, | ||
/// and the data not yet. | ||
/// and the data not yet. The lines kept in `PDS_LOG_DIR` go on after those | ||
/// there. | ||
pub(crate) fn start(s: Settings, port: u16) { | ||
let exporter = s.trace.exporter(); | ||
let started = crate::events::timestamp(); | ||
let _ = OPS.set(Ops { | ||
level: s.level, | ||
out: stdout().map(Mutex::new), | ||
out: Mutex::new(Out { | ||
stdout: stdout(), | ||
kept: s.kept.map(kept::Kept::open), | ||
}), | ||
metrics: metrics::Metrics::default(), | ||
exporter, | ||
started: started.clone(), | ||
}); | ||
pds_store::on_sync(|d| ops().metrics.fsync(d)); | ||
pds_store::on_error(|why| failed("compacting a log failed", why)); | ||
| @@ -158,7 +185,9 @@ pub(crate) fn start(s: Settings, port: u16) { | ||
.map(|l| format!("{}:{}", l.file(), l.line())); | ||
error("panic", &[("at", json!(at))]); | ||
})); | ||
info( | ||
line_at( | ||
&started, | ||
Level::Info, | ||
"start", | ||
&[ | ||
("version", json!(VERSION)), | ||
| @@ -176,14 +205,19 @@ static METRICS_PORT: OnceLock<u16> = OnceLock::new(); | ||
/// Write a line at `level`, with `fields` after `time`, `level` and `msg`; | ||
/// a field that is null is left out. | ||
pub(crate) fn line(level: Level, msg: &str, fields: &[(&str, Json)]) { | ||
line_at(&crate::events::timestamp(), level, msg, fields); | ||
} | ||
| ||
/// Write a line whose `time` is `time`: to standard output, then, the same | ||
/// bytes, to the files it is kept in, before the next line goes to either. | ||
fn line_at(time: &str, level: Level, msg: &str, fields: &[(&str, Json)]) { | ||
let o = ops(); | ||
if o.level == Level::Off || level < o.level { | ||
return; | ||
} | ||
let Some(out) = &o.out else { return }; | ||
let mut s = String::with_capacity(192); | ||
s.push_str("{\"time\":\""); | ||
s.push_str(&crate::events::timestamp()); | ||
s.push_str(time); | ||
s.push_str("\",\"level\":\""); | ||
s.push_str(level.name()); | ||
s.push_str("\",\"msg\":"); | ||
| @@ -198,8 +232,20 @@ pub(crate) fn line(level: Level, msg: &str, fields: &[(&str, Json)]) { | ||
s.push_str(&v.to_string()); | ||
} | ||
s.push_str("}\n"); | ||
let f = out.lock().unwrap_or_else(PoisonError::into_inner); | ||
let _ = (&*f).write_all(s.as_bytes()); | ||
let mut out = o.out.lock().unwrap_or_else(PoisonError::into_inner); | ||
if let Some(mut f) = out.stdout.as_ref() { | ||
let _ = f.write_all(s.as_bytes()); | ||
} | ||
if let Some(k) = &mut out.kept { | ||
k.write(s.as_bytes()); | ||
} | ||
} | ||
| ||
/// The lines kept in `PDS_LOG_DIR`, as they are now, to read with no lock | ||
/// held; None with no `PDS_LOG_DIR`. | ||
fn kept_now() -> Option<kept::Snapshot> { | ||
let out = ops().out.lock().unwrap_or_else(PoisonError::into_inner); | ||
out.kept.as_ref().map(kept::Kept::snapshot) | ||
} | ||
| ||
pub(crate) fn info(msg: &str, fields: &[(&str, Json)]) { | ||
| @@ -416,10 +462,14 @@ const ROUTES: &[&str] = &[ | ||
const ASSETS: &str = "/oauth/assets/{name}"; | ||
| ||
/// A request's route, as its log line and metrics label it: the NSID of a | ||
/// method served, `_health`, a path served outside `/xrpc/`, or `_unknown`. | ||
/// method served, `_health`, `_logs` or `_stats`, a path served outside | ||
/// `/xrpc/`, or `_unknown`. | ||
fn route_of(path: &str) -> &'static str { | ||
if path == "/xrpc/_health" { | ||
return "_health"; | ||
if let Some(own) = ["_health", "_logs", "_stats"] | ||
.into_iter() | ||
.find(|r| path.strip_prefix("/xrpc/") == Some(*r)) | ||
{ | ||
return own; | ||
} | ||
if let Some(nsid) = path.strip_prefix("/xrpc/") { | ||
return pds_lexicon::method(nsid).map_or("_unknown", |m| m.nsid.as_str()); | ||
docs/guide/calling.md+5−1
| @@ -45,7 +45,11 @@ pds repo list-records --collection com.example.note --limit 5 | ||
``` | ||
| ||
`pds --help` lists the groups and commands, and `pds <group> --help` a | ||
group's, each with its lexicon's description. | ||
group's, each with its lexicon's description. `pds admin logs` and `pds | ||
admin stats`, and the MCP tools `admin_logs` and `admin_stats`, are the | ||
admin's reads of the log and the metrics, which have no lexicon | ||
([COMMANDS.md](../../spec/COMMANDS.md#the-admins-reads), | ||
[Operating](operating.md#reading-the-log-and-stats)). | ||
| ||
A few commands send or write bytes rather than JSON | ||
([COMMANDS.md](../../spec/COMMANDS.md#answers)): `sync get-repo` and | ||
docs/guide/comparing.md+1−0
| @@ -36,6 +36,7 @@ calls a set's session may make are compared with the reference. | ||
Every run ends with the server's operations | ||
([OPERATIONS.md](../../spec/OPERATIONS.md)): its `/xrpc/_health` against | ||
the reference's; its metrics against its log and what the harness sent; | ||
the admin's `_logs` and `_stats` against what it wrote and counted; | ||
every span against the request it is of, at a stub OTLP receiver that the | ||
run takes away for a while; a shutdown, and starts at another log level, | ||
with a PLC directory that fails, after a kill, and with variables that do | ||
docs/guide/deploying.md+2−1
| @@ -49,7 +49,8 @@ says the rest. | ||
| `PDS_PLC_ROTATION_KEY_HEX` | a new secp256k1 key (`openssl rand -hex 32`), in a secret store: whoever holds it controls every account's DID | | ||
| `PDS_RECOVERY_DID_KEY` | a `did:key` whose private key is kept offline, so the DIDs outlive a lost or stolen rotation key | | ||
| `PDS_EMAIL_SMTP_URL`, `PDS_EMAIL_FROM` | the mail server, and the address mail is from | | ||
| `PDS_ADMIN_PASSWORD`, `PDS_INVITE_REQUIRED` | the admin's password; `true` unless anyone may sign up | | ||
| `PDS_ADMIN_PASSWORD`, `PDS_INVITE_REQUIRED` | the admin's password, which also reads the log and stats ([Operating](operating.md#reading-the-log-and-stats)); `true` unless anyone may sign up | | ||
| `PDS_LOG_DIR`, `PDS_LOG_KEEP_BYTES` | a directory, on a volume of its own apart from `/data`, the log is kept in too, so that the admin reads it back across deploys; and the most it takes, 64 MiB unless set | | ||
| `PDS_CRAWLERS` | the relays told of it, as `https://bsky.network` | | ||
| `PDS_BSKY_APP_VIEW_URL`, `PDS_BSKY_APP_VIEW_DID`, `PDS_BSKY_APP_VIEW_CDN_URL_PATTERN` | `https://api.bsky.app`, `did:web:api.bsky.app` and `https://cdn.bsky.app/img/%s/plain/%s/%s@jpeg`, for the Bluesky app | | ||
| `PDS_MAX_REPO_IMPORT_SIZE` | the largest repository an account may bring when it moves here ([MIGRATION.md](../../spec/MIGRATION.md)), 300 MiB unless set | | ||
docs/guide/operating.md+31−0
| @@ -17,6 +17,37 @@ variable does not parse. | ||
default), `warn` or `error`, or `off` for none | ||
([OPERATIONS.md](../../spec/OPERATIONS.md#the-log)). | ||
| ||
Set `PDS_LOG_DIR` to keep each line in that directory too, so that it can | ||
be read back without reaching the machine, and outlives a container made | ||
again. Its files take at most `PDS_LOG_KEEP_BYTES` (64 MiB by default), | ||
the oldest lines let go first. Keep it apart from `PDS_DATA_DIR`, on a | ||
volume of its own: no backup needs it | ||
([OPERATIONS.md](../../spec/OPERATIONS.md#kept)). | ||
| ||
## Reading the log and stats | ||
| ||
With `PDS_ADMIN_PASSWORD` set, the admin reads what the server logged and | ||
counted over its own port: `GET /xrpc/_logs` and `GET /xrpc/_stats`, with | ||
`Authorization: Basic` and the user `admin`, or as the CLI's `pds admin | ||
logs` and `pds admin stats`, or the MCP tools `admin_logs` and | ||
`admin_stats` ([OPERATIONS.md](../../spec/OPERATIONS.md#the-admins-reads)): | ||
| ||
```sh | ||
export PDS_URL=https://pds.example.com PDS_ADMIN_PASSWORD=… | ||
pds admin logs # the last 100 lines kept | ||
pds admin logs --level warn --limit 20 # the last warnings and errors | ||
pds admin logs --trace 4bf92f3577b34da6a3ce929d0e0e4736 # one request | ||
pds admin logs --method com.atproto.repo.createRecord --min-ms 500 | ||
pds admin stats # requests by route, since the start | ||
``` | ||
| ||
`_logs` answers the last `limit` (100 by default, at most 500) of the lines | ||
kept in `PDS_LOG_DIR` that match every filter given, oldest first; with no | ||
`PDS_LOG_DIR` it is `404 LogNotKept`. `_stats` answers what the metrics | ||
have counted since the server started, as JSON: requests by route and | ||
status with their mean times, the requests it made, its syncs, its | ||
accounts and its firehose; it needs no `PDS_METRICS_PORT`. | ||
| ||
## Health | ||
| ||
`GET /xrpc/_health` answers `200` with `{"version": "..."}` while the | ||