spike(relay): prove zero-service core event path

Signed-off-by: npub13n66s06epmqf2kc3v373ez8hj65cuzyvxzjf93vwpervxqn2u7jq2qd9je <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz>
This commit is contained in:
npub13n66s06epmqf2kc3v373ez8hj65cuzyvxzjf93vwpervxqn2u7jq2qd9je
2026-08-01 07:40:53 -04:00
committed by Brother Darryl
parent 43573d114b
commit 777ab859e4
4 changed files with 284 additions and 0 deletions

View File

@@ -0,0 +1,64 @@
# Phase 0 local-mode breakage catalogue
Base: `origin/main` c104eecfb38620de2c35c7e20a716f8658b5a6b1. Spike branch: `spike/local-mode-relay`.
## Result
`BUZZ_LOCAL_MODE=1 BUZZ_BIND_ADDR=127.0.0.1:4317 BUZZ_RELAY_URL=ws://127.0.0.1:4317 target/debug/buzz-relay` boots without Postgres, Redis, or S3. The real `buzz-test-client` proves NIP-42, event insertion, historical REQ filtering, and two-client live fan-out. This is a deliberately separate tracer-bullet path, not the production `AppState` and not mergeable architecture.
## Worked as-is
| Module | Evidence | Result |
|---|---|---|
| NIP-01 frame parsing/formatting | `crates/buzz-relay/src/protocol.rs:15-175,177-217` reused by `local_mode.rs:22,99-143` | EVENT, REQ, CLOSE, COUNT and AUTH wire shapes required no changes. |
| Nostr signature/filter implementation | `local_mode.rs:113-127,159-176` | Signature verification, dedupe by event ID, and `Filter::match_event` work in memory. |
| Axum/WebSocket runtime | `local_mode.rs:64-76` | Same binary serves WebSocket plus liveness/readiness on loopback. |
| Existing client | `crates/buzz-test-client/src/bin/local_mode_smoke.rs` | Real NIP-42 client exercised auth/store/history/fan-out. |
## Worked with shim
| Module | Evidence | Fidelity / breakage |
|---|---|---|
| Event store + REQ | `local_mode.rs:50-55,113-140` | `RwLock<Vec<Event>>`; correct basic filters/dedupe, volatile, O(n), no replacement/deletion/tenant/channel visibility semantics. This is in-memory rather than SQLite: it proves the storage boundary, not SQL portability. |
| Pubsub | `local_mode.rs:53,58-63,93-94,126,146-154` | `tokio::broadcast`; fan-out works in one process. Redis topic scoping, reconnect, cross-pod invalidation and connection control absent. Existing Redis-only shape is explicit at `crates/buzz-pubsub/src/lib.rs:99-139`. |
| NIP-42 | `local_mode.rs:79-111,159-170` | Crypto challenge/relay/signature verification works. Moderation, allowlist, relay membership, and NIP-OA backfill are bypassed; production coupling starts at `handlers/auth.rs:94-260`. |
| Health | `local_mode.rs:64-70` | Static OK; does not inspect backend health. |
## Stubbed / bypassed
| Module | Evidence | Spike behavior |
|---|---|---|
| Presence + typing | Redis modules enumerated at `crates/buzz-pubsub/src/lib.rs:30-43` | No-op / absent. |
| Rate limiting + NIP-98 replay | Production fields at `state.rs:576-584`; Redis construction `state.rs:711-713` | Permissive no-op / absent. |
| Media | S3-only concrete `MediaStorage` at `crates/buzz-media/src/storage.rs:18-70`; startup at `main.rs:448-454` | HTTP media routes absent. No fs shim attempted because bypassing `AppState` removed the route surface. |
| Search | PG pool constructed at `main.rs:403-419` | Route/service absent; expected unsupported. |
| Audit/workflows/git | PG/S3 construction at `main.rs:355-367,422-423`; `state.rs:692-713` | Absent. |
| Channel/membership/moderation | Production auth DB calls begin `handlers/auth.rs:94`; Db has 50 channel and 23 relay-members query call sites | Open-relay behavior: any valid NIP-42 identity can publish/read; channel tags are filter data only. |
| Replica fence, partition, usage, push, mesh | DB boot invokes partitions/fence `main.rs:200-222`; excluded by brief | Skipped entirely. |
## Hard boundary found
The production router cannot be retained while swapping only the core store. `AppState` is a concrete service aggregate, not a seam: concrete `Db`, Redis pool/manager, `SearchService`, and `MediaStorage` are mandatory fields (`state.rs:488-502,554-584`) and constructor parameters (`state.rs:637-648`). Constructor body also creates S3-backed git storage plus Redis replay/rate-limit services (`state.rs:692-713`). Startup eagerly connects Postgres (`main.rs:172-192`), Redis (`main.rs:369-399`), search Postgres (`main.rs:403-419`), and S3 (`main.rs:448-454`) before router construction.
Therefore a SQLite port of `event.rs` alone cannot boot the existing handler/router path. Phase 1 must first separate a local profile/router service aggregate or add backend traits/configurable optional services. The tracer bullet confirms protocol/client compatibility but **does not yet meet the desktop+agent/channel success criterion**.
## Phase 2 estimate refinement
Core SQL count is not the main blocker. `event.rs` has 39 `sqlx::query` call sites; unavoidable auth/chat widening immediately adds approximately channel (50), relay_members (23), moderation (15), user (11), reaction (8), thread (19), DM (12), and feed (2), before shared `lib.rs` queries. A useful real-client slice is thus roughly 179 module-level query sites, not 39, plus creating the AppState/service seam. Recommended next tracer bullet: land the service aggregate/profile seam first, then port event + tenant/community + auth moderation/membership + channel as one vertical slice.
## Commands and observed output
```text
cargo check -p buzz-relay
# PASS
cargo test -p buzz-relay --lib
# 792 passed; 10 failed; 35 ignored
# Failures require external DB/media/mesh and are present in untouched production tests.
BUZZ_LOCAL_MODE=1 ... target/debug/buzz-relay
# BUZZ_LOCAL_MODE active: in-memory store and fan-out; external services bypassed
target/debug/local_mode_smoke ws://127.0.0.1:4317
# PASS nip42,event_insert,req_history,live_fanout
```

View File

@@ -0,0 +1,177 @@
//! Throwaway Phase 0 zero-service relay tracer bullet.
//!
//! Enabled only by `BUZZ_LOCAL_MODE=1`. This deliberately bypasses the production
//! AppState so the spike can measure the coupling before a durable storage seam exists.
use std::net::SocketAddr;
use std::sync::Arc;
use anyhow::Context;
use axum::extract::ws::{Message, WebSocket};
use axum::extract::{State, WebSocketUpgrade};
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use futures_util::{SinkExt, StreamExt};
use nostr::filter::MatchEventOptions;
use nostr::{Event, Filter, Kind};
use tokio::sync::{broadcast, RwLock};
use tracing::{info, warn};
use uuid::Uuid;
use buzz_relay::protocol::{ClientMessage, RelayMessage};
pub(crate) struct Config {
bind_addr: SocketAddr,
relay_url: String,
}
impl Config {
pub(crate) fn from_env() -> anyhow::Result<Option<Self>> {
let enabled = std::env::var("BUZZ_LOCAL_MODE")
.ok()
.is_some_and(|value| matches!(value.trim(), "1" | "true" | "on"));
if !enabled {
return Ok(None);
}
let bind_addr = std::env::var("BUZZ_BIND_ADDR")
.unwrap_or_else(|_| "127.0.0.1:4000".into())
.parse()
.context("invalid BUZZ_BIND_ADDR")?;
let relay_url =
std::env::var("BUZZ_RELAY_URL").unwrap_or_else(|_| format!("ws://{bind_addr}"));
Ok(Some(Self {
bind_addr,
relay_url,
}))
}
}
#[derive(Clone)]
struct LocalState {
events: Arc<RwLock<Vec<Event>>>,
fanout: broadcast::Sender<Event>,
relay_url: Arc<str>,
}
pub(crate) async fn run(config: Config) -> anyhow::Result<()> {
let (fanout, _) = broadcast::channel(1024);
let state = LocalState {
events: Arc::new(RwLock::new(Vec::new())),
fanout,
relay_url: config.relay_url.into(),
};
let app = Router::new()
.route("/", get(ws_upgrade))
.route("/_liveness", get(|| async { "ok" }))
.route("/_readiness", get(|| async { "ok" }))
.with_state(state);
let listener = tokio::net::TcpListener::bind(config.bind_addr).await?;
info!(bind_addr = %config.bind_addr, "BUZZ_LOCAL_MODE active: in-memory store and fan-out; external services bypassed");
axum::serve(listener, app).await?;
Ok(())
}
async fn ws_upgrade(ws: WebSocketUpgrade, State(state): State<LocalState>) -> impl IntoResponse {
ws.on_upgrade(move |socket| serve_socket(socket, state))
}
async fn serve_socket(socket: WebSocket, state: LocalState) {
let challenge = Uuid::new_v4().to_string();
let (mut tx, mut rx) = socket.split();
if tx
.send(Message::Text(
RelayMessage::auth_challenge(&challenge).into(),
))
.await
.is_err()
{
return;
}
let mut authenticated = false;
let mut live = state.fanout.subscribe();
let mut subscriptions: Vec<(String, Vec<Filter>)> = Vec::new();
loop {
tokio::select! {
frame = rx.next() => {
let Some(Ok(Message::Text(raw))) = frame else { break };
let message = match ClientMessage::parse(&raw) {
Ok(message) => message,
Err(error) => {
let _ = tx.send(Message::Text(RelayMessage::notice(&error.to_string()).into())).await;
continue;
}
};
match message {
ClientMessage::Auth(event) => {
let accepted = verify_auth(&event, &challenge, &state.relay_url);
authenticated = accepted;
let reason = if accepted { "" } else { "auth-required: verification failed" };
let _ = tx.send(Message::Text(RelayMessage::ok(&event.id.to_hex(), accepted, reason).into())).await;
}
ClientMessage::Event(event) if authenticated => {
let id = event.id.to_hex();
if event.verify().is_err() {
let _ = tx.send(Message::Text(RelayMessage::ok(&id, false, "invalid: bad signature").into())).await;
continue;
}
let inserted = {
let mut events = state.events.write().await;
if events.iter().any(|stored| stored.id == event.id) { false } else {
events.push(event.clone());
true
}
};
if inserted { let _ = state.fanout.send(event); }
let _ = tx.send(Message::Text(RelayMessage::ok(&id, true, if inserted { "" } else { "duplicate" }).into())).await;
}
ClientMessage::Req { sub_id, filters } if authenticated => {
let events = state.events.read().await.clone();
for event in events.iter().filter(|event| matches_any(&filters, event)) {
if tx.send(Message::Text(RelayMessage::event(&sub_id, event).into())).await.is_err() { return; }
}
if tx.send(Message::Text(RelayMessage::eose(&sub_id).into())).await.is_err() { return; }
subscriptions.retain(|(existing, _)| existing != &sub_id);
subscriptions.push((sub_id, filters));
}
ClientMessage::Count { sub_id, filters } if authenticated => {
let count = state.events.read().await.iter().filter(|event| matches_any(&filters, event)).count() as u64;
let _ = tx.send(Message::Text(RelayMessage::count(&sub_id, count).into())).await;
}
ClientMessage::Close(sub_id) => subscriptions.retain(|(existing, _)| existing != &sub_id),
_ => { let _ = tx.send(Message::Text(RelayMessage::notice("auth-required: authenticate first").into())).await; }
}
}
event = live.recv(), if authenticated => match event {
Ok(event) => {
for (sub_id, _) in subscriptions.iter().filter(|(_, filters)| matches_any(filters, &event)) {
if tx.send(Message::Text(RelayMessage::event(sub_id, &event).into())).await.is_err() { return; }
}
}
Err(broadcast::error::RecvError::Lagged(skipped)) => warn!(skipped, "local fan-out receiver lagged"),
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
fn verify_auth(event: &Event, challenge: &str, relay_url: &str) -> bool {
event.kind == Kind::Authentication
&& event.verify().is_ok()
&& event
.tags
.iter()
.any(|tag| tag.as_slice() == ["challenge", challenge])
&& event
.tags
.iter()
.any(|tag| tag.as_slice() == ["relay", relay_url])
}
fn matches_any(filters: &[Filter], event: &Event) -> bool {
filters.is_empty()
|| filters
.iter()
.any(|filter| filter.match_event(event, MatchEventOptions::default()))
}

View File

@@ -1,3 +1,5 @@
mod local_mode;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::Ordering;
use std::sync::Arc;
@@ -139,6 +141,10 @@ async fn main() -> anyhow::Result<()> {
info!("Starting buzz-relay");
if let Some(config) = local_mode::Config::from_env()? {
return local_mode::run(config).await;
}
let config = Config::from_env().map_err(|e| {
error!("Invalid configuration: {e}");
anyhow::anyhow!("Configuration error: {e}")

View File

@@ -0,0 +1,37 @@
//! Phase 0 local-mode smoke: two authenticated clients, live fan-out, history and COUNT.
use buzz_test_client::{BuzzTestClient, RelayMessage};
use nostr::{Filter, Keys};
use std::time::Duration;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let url = std::env::args()
.nth(1)
.unwrap_or_else(|| "ws://127.0.0.1:4317".into());
let keys = Keys::parse("0000000000000000000000000000000000000000000000000000000000000001")?;
let mut subscriber = BuzzTestClient::connect(&url, &keys).await?;
subscriber.subscribe("live", vec![Filter::new()]).await?;
let _ = subscriber.recv_event(Duration::from_secs(1)).await?; // EOSE
let mut publisher = BuzzTestClient::connect(&url, &keys).await?;
let ok = publisher
.send_text_message(
&keys,
"00000000-0000-0000-0000-000000000042",
"phase0 live",
9,
)
.await?;
anyhow::ensure!(ok.accepted, "publish rejected: {}", ok.message);
match subscriber.recv_event(Duration::from_secs(2)).await? {
RelayMessage::Event { event, .. } => anyhow::ensure!(event.content == "phase0 live"),
other => anyhow::bail!("expected live EVENT, got {other:?}"),
}
let mut history = BuzzTestClient::connect(&url, &keys).await?;
history.subscribe("history", vec![Filter::new()]).await?;
match history.recv_event(Duration::from_secs(2)).await? {
RelayMessage::Event { event, .. } => anyhow::ensure!(event.content == "phase0 live"),
other => anyhow::bail!("expected historical EVENT, got {other:?}"),
}
println!("PASS nip42,event_insert,req_history,live_fanout");
Ok(())
}