Repository navigation
feat(mcp): add the relay_status tool over a published status document #1209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
c71d0da
feat(relay): count every live socket in ConnectionCap::live_total
chappie-daemon f51dddf
feat(relay): build the NIP-11 document from settings
chappie-daemon 215a63a
feat(admin): assemble the relay status document and read it back
chappie-daemon c9efd97
feat(daemon): publish the relay status document every five seconds
chappie-daemon 0382661
style: apply rustfmt to the new modules and cases
chappie-daemon af40773
feat(mcp): add the relay_status tool over the published document and …
chappie-daemon fcd6ed3
test(mcp): audit the relay_status dispatch in call order
chappie-daemon 53c9c59
docs(adr): record the relay status document and the NIP-11 field set
chappie-daemon f6a09d2
docs(adr): cite ADR 0014's single-writer decision without a cross-rec…
chappie-daemon 3bdba83
fix(admin): create the status document's directory and prove the repl…
chappie-daemon b9dba7a
fix(relay): advertise the difficulty the event handler enforces
chappie-daemon a6f8eb7
fix(nostreamd): name relay_status in the stdio help
chappie-daemon 460c751
fix(daemon): publish one status document at start, not two
chappie-daemon bae2d0d
style: apply rustfmt to the status cases
chappie-daemon f1b9cd6
docs(adr): the audit vocabulary gains one mcp.* name per tool, not four
chappie-daemon 3885d38
test(relay): prove the advertised difficulty and the enforced one are…
chappie-daemon d6747d8
feat(admin): carry the relay's own key in the published document
chappie-daemon 91366c6
fix(admin): name the field when generatedAt cannot be read
chappie-daemon 87598db
docs(adr): restore D1's file-over-route cost and name the record it c…
chappie-daemon 50f49e3
fix(relay): take nip11 self from the published key alone
chappie-daemon f6f3201
docs(adr): record self's single source
chappie-daemon 22bc16e
docs: NIP-11 self is the relay's published key, not info.self
chappie-daemon 9425f25
docs(adr): D1 names the document's fifth key
chappie-daemon 263c3cb
test(mcp): a stale document names no identity either
chappie-daemon 1c90022
docs(cli): NIP-11 self is the derived key, not info.self
chappie-daemon ab0a8cc
docs: an unset info.self skips the invite check rather than failing it
chappie-daemon 0aeab52
docs: the status document has five keys, and info.self no longer clai…
chappie-daemon db8ff8c
docs(settings): the self rule differs by implementation, so say both
chappie-daemon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| --- | ||
| --- | ||
|
|
||
| feat(mcp): `relay_status`, slice 2 — the published status document and the NIP-11 builder | ||
|
|
||
| A fifth MCP tool answers the relay's status: the software version, the relay process's uptime, | ||
| its live connection count, its worker rows and the NIP-11 document it advertises. The facts only | ||
| the relay process can know are not invented by the answering process — `nostreamd` publishes | ||
| `<config>/relay-status.json` every 5 s (a 30 s freshness bound, written through a sibling `.tmp` | ||
| and a rename so no reader sees a half-written document) and the tool reads it per call. When the | ||
| document is absent, unreadable or older than the bound those values are `null` with a reason | ||
| naming the file, never `0`: a zero would read as "nothing is connected". `ConnectionCap` gains | ||
| `live_total()`, the socket count the document carries. The document also carries `relayPubkey`, | ||
| the key the daemon signs with, so the tool's NIP-11 `self` is the relay's identity rather than one | ||
| the answering process derived from its own environment. | ||
|
|
||
| The NIP-11 document is built by `nostream_relay::nip11` from the settings, and every key's | ||
| presence is decided there: `supported_nip_extensions`, `supported_mips`, `payments_url`, | ||
| `peering`, `limitation.min_prefix`, `limitation.max_event_tags` and `fees.subscription` are | ||
| dropped with their reasons, `supported_nips` loses 43/50 when their switches are off and 77 | ||
| always, and `restricted_writes` folds the arms the event handler enforces. Nothing serves it | ||
| over HTTP and `nostream-cli info` is unchanged. The decisions are ADR 0016 D1–D7, which closes | ||
| `docs/rewrite/nip-parity.md` item 11. | ||
|
|
||
| Rust only: no published package changes, so this entry carries no version bump. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| //! The relay status document: the daemon publishes it, the MCP door reads it (ADR 0016 D1). | ||
| //! | ||
| //! It is the one artifact carrying the relay process's own facts — its uptime, its live | ||
| //! connection count, its worker rows and the key it signs with — to a process that hosts no | ||
| //! relay: heartbeats are process memory and `AdminState` holds no `Relay` handle, so a tool | ||
| //! answering from its own process would report a running relay as idle, and one deriving the | ||
| //! identity from its own environment would report a key the relay never signs with. The daemon | ||
| //! is its only writer and the MCP door its only reader, which is not ADR 0014 D18's | ||
| //! second-writer hazard — that is about `admin-audit.jsonl` and the settings write, and neither | ||
| //! is this file. | ||
|
|
||
| use std::path::{Path, PathBuf}; | ||
| use std::time::Duration; | ||
|
|
||
| use nostream_config::SettingsPaths; | ||
| use nostream_core::Pubkey; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| use crate::error::AdminError; | ||
| use crate::state::{AdminState, iso8601}; | ||
| use crate::utils::workers::{self, WorkerRow}; | ||
|
|
||
| /// The document's name under the config base directory. | ||
| pub const STATUS_FILE: &str = "relay-status.json"; | ||
|
|
||
| /// How often the daemon rewrites the document: six writes inside the freshness bound, so one | ||
| /// missed write is still fresh, and 5 s is the coarsest cadence that makes a connection count | ||
| /// worth reading. | ||
| pub const STATUS_INTERVAL: Duration = Duration::from_millis(5_000); | ||
|
|
||
| /// How old a document may be and still be reported: 30 s is fresh, 31 s is not. | ||
| pub const STATUS_TTL_SECONDS: u64 = 30; | ||
|
|
||
| /// The document's keys, camelCase like the console's own `uptimeSeconds`. | ||
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct StatusDocument { | ||
| pub generated_at: String, | ||
| pub uptime_seconds: u64, | ||
| pub active_connections: u64, | ||
| /// The key the relay signs with, resolved by the daemon where the environment is read, so | ||
| /// the MCP door reads the relay's identity here instead of deriving one of its own. Omitted | ||
| /// when the daemon has no key source. | ||
| #[serde(skip_serializing_if = "Option::is_none")] | ||
| pub relay_pubkey: Option<Pubkey>, | ||
| pub workers: Vec<WorkerRow>, | ||
| } | ||
|
|
||
| /// A document fresh enough to report, and how old it was. | ||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub struct Published { | ||
| pub document: StatusDocument, | ||
| pub age_seconds: u64, | ||
| } | ||
|
|
||
| /// Why there is no document to report. The reason is the caller's whole message: every one of | ||
| /// them names the file, so a reader can tell what to look at. | ||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub struct StatusError { | ||
| pub reason: String, | ||
| } | ||
|
|
||
| /// The file's path: `<config_base_dir>/relay-status.json`, beside `admin-audit.jsonl`. | ||
| pub fn path(paths: &SettingsPaths) -> PathBuf { | ||
| paths.config_base_dir.join(STATUS_FILE) | ||
| } | ||
|
|
||
| /// Assembles the document from the implementations that already exist and nothing else: the | ||
| /// state's own uptime, its clock, the console's worker rows and the identity the caller resolved. | ||
| pub fn collect( | ||
| state: &AdminState, | ||
| relay_pubkey: Option<Pubkey>, | ||
| active_connections: u64, | ||
| ) -> Result<StatusDocument, AdminError> { | ||
| let settings = state.settings()?; | ||
|
|
||
| Ok(StatusDocument { | ||
| generated_at: iso8601(state.clock().now_ms()), | ||
| uptime_seconds: state.uptime_seconds(), | ||
| active_connections, | ||
| relay_pubkey, | ||
| workers: workers::rows(state, &settings), | ||
| }) | ||
| } | ||
|
|
||
| /// Replaces the file atomically: a sibling `.tmp` write then a rename, so a reader never sees | ||
| /// a half-written document and no `.tmp` survives a successful write. | ||
| /// | ||
| /// The parent directory is created first: the settings loader deliberately does not create it | ||
| /// (only the mutating callers do), so a daemon started against an absent config directory would | ||
| /// otherwise warn on every write and serve no document at all. The rule is the audit log's. | ||
| pub fn write(path: &Path, document: &StatusDocument) -> std::io::Result<()> { | ||
| let body = serde_json::to_vec(document).map_err(std::io::Error::other)?; | ||
|
|
||
| if let Some(parent) = path.parent() { | ||
| std::fs::create_dir_all(parent)?; | ||
| } | ||
|
|
||
| let staging = staging_path(path); | ||
|
|
||
| std::fs::write(&staging, body)?; | ||
| std::fs::rename(&staging, path) | ||
| } | ||
|
|
||
| /// Reads the document, at most [`STATUS_TTL_SECONDS`] old. Nothing caches it: the read happens | ||
| /// per call, so a rewrite or a deletion is in force by the next one. | ||
| pub fn read(paths: &SettingsPaths, now_ms: u64) -> Result<Published, StatusError> { | ||
| let path = path(paths); | ||
| let unreadable = |error: &dyn std::fmt::Display| StatusError { | ||
| reason: format!( | ||
| "the relay status document at {} could not be read: {error}", | ||
| path.display() | ||
| ), | ||
| }; | ||
|
|
||
| let raw = std::fs::read_to_string(&path).map_err(|error| { | ||
| if error.kind() == std::io::ErrorKind::NotFound { | ||
| StatusError { | ||
| reason: format!("no relay status document at {}", path.display()), | ||
| } | ||
| } else { | ||
| unreadable(&error) | ||
| } | ||
| })?; | ||
|
|
||
| let document: StatusDocument = | ||
| serde_json::from_str(&raw).map_err(|error| unreadable(&error))?; | ||
| // The stamp is the reader's clock source, so its failure names the field and the value: a | ||
| // complete document with a bad stamp reported as `premature end of input` reads like a | ||
| // truncated file and sends an operator looking for the wrong thing. | ||
| let generated = chrono::DateTime::parse_from_rfc3339(&document.generated_at).map_err(|_| { | ||
| unreadable(&format_args!( | ||
| "generatedAt {:?} is not a timestamp", | ||
| document.generated_at | ||
| )) | ||
| })?; | ||
| let generated_ms = u64::try_from(generated.timestamp_millis()).unwrap_or(0); | ||
| let age_seconds = now_ms.saturating_sub(generated_ms) / 1000; | ||
|
|
||
| if age_seconds > STATUS_TTL_SECONDS { | ||
| return Err(StatusError { | ||
| reason: format!( | ||
| "the relay status document at {} is {age_seconds} seconds old; the bound is \ | ||
| {STATUS_TTL_SECONDS}", | ||
| path.display() | ||
| ), | ||
| }); | ||
| } | ||
|
|
||
| Ok(Published { | ||
| document, | ||
| age_seconds, | ||
| }) | ||
| } | ||
|
|
||
| /// The staging file beside `path`: `<file>.tmp`. | ||
| fn staging_path(path: &Path) -> PathBuf { | ||
| let mut name = path.as_os_str().to_owned(); | ||
|
|
||
| name.push(".tmp"); | ||
|
|
||
| PathBuf::from(name) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.