readpolicy: strfry read-side plugin with a ReadFilter pipeline
Add a read-side counterpart to noteguard's writePolicy plugin, consuming
strfry's per-subscription REQ deliverability protocol (reqOpen / req / reqClose
/ connClose) to make per-subscriber, per-event deliver/withhold decisions.
Withholding an event never touches storage and never affects another subscriber.
Wire protocol lives in src/readmsg.rs (line-delimited JSON, monotonic reqId),
reachable via a new `noteguard read` subcommand (strfry invokes it as
`./noteguard read`). Events arrive as UnparsedNote(Box<RawValue>), kept in their
original wire form: size() is the exact streamed byte length with no
re-serialization, and parse()/id() defer any real parse to the paths that need
fields. Because RawValue only captures source bytes at the top-level
deserializer, ReadInput uses a manual Deserialize over a flat RawInput struct
rather than a derived internally-tagged enum (which buffers into a serde Content
and breaks capture).
The read path is a composable pipeline, the analogue of the write-side
NoteFilter design. The new ReadFilter trait (src/read_filter.rs) carries the
richer semantics reads need: lifecycle hooks (req_open admission + passthrough
opt-out, req_close, conn_close), a per-event verdict {Deliver, Skip, Stop}
(Stop withholds the rest of a batch), a check/commit split (filter_event checks,
on_delivered commits budget only for events delivered by the WHOLE pipeline — so
an event a later filter withholds never charges an earlier filter's counter),
shared per-connection context (the engine caches ip/authed at reqOpen since req
batches carry no IP), and a per-filter fail-open contract.
ReadPolicy (src/readpolicy.rs) is the engine: a name-keyed registry +
register_filter + a config-driven [readpolicy].pipeline, mirroring
Noteguard/register_filter/pipeline and sharing the same noteguard.toml (both
subcommands now honour $NOTEGUARD_CONFIG via noteguard::config_path).
Unknown/misconfigured pipeline entries are logged and skipped (fail open) rather
than panicking like the write side — a misconfigured read filter must not take
down a subscriber's feed.
Subscriptions that do no per-event work answer reqOpen with
{"action":"accept","passthrough":true}: strfry then skips all per-event
marshaling and delivers via its zero-copy fast path, never sending `req`
batches (it still sends reqClose/connClose so we can free state). Passthrough is
the AND of !needs_events across filters, evaluated per subscription. Reject still
wins; passthrough only rides on an accept. Emitting the field is
forward-compatible: a strfry without passthrough support ignores the extra key.
Ships one filter, max_events_per_conn (a per-connection delivery cap), which is
enough to exercise the counter/Stop/commit path; read_bandwidth and the
experimental nscript guest filter follow in their own commits.
Changelog-Added: Add strfry read-side (readPolicy) REQ plugin mode (`noteguard read`) with a composable ReadFilter pipeline
Headway: headway:noteguard/hotel-limit-bounce
Agentium: agentium:twenty-trouble-until
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
6ac89a1626
commit
cad9b83241
+1
-1
@@ -8,7 +8,7 @@ forwarder = ["tokio-tungstenite", "tokio", "futures-util"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["raw_value"] }
|
||||
toml = "0.5"
|
||||
ipnetwork = "0.20.0"
|
||||
|
||||
|
||||
@@ -166,6 +166,68 @@ be queued if the connection goes down (up to the `queue_size` buffer limit)
|
||||
|
||||
- `queue_size` *optional* - size of the note queue, this is used to buffer notes if the connection goes down. Default is 1000.
|
||||
|
||||
## Read-policy (readPolicy) mode
|
||||
|
||||
Everything above is the **write-side** plugin: it decides what gets *stored* (a
|
||||
reject deletes the event for everyone). strfry also has a **read-side**
|
||||
(`readPolicy`) plugin hook that decides, *per subscription*, which already-stored
|
||||
events are *delivered* to that particular subscriber — the right hook for
|
||||
personal/inbox feed filtering and per-connection read throttling. Withholding an
|
||||
event never touches storage and never affects any other subscriber.
|
||||
|
||||
Run noteguard in read mode with the `read` subcommand and point strfry's
|
||||
`relay.readPolicy.plugin` at it:
|
||||
|
||||
```
|
||||
readPolicy {
|
||||
plugin = "./noteguard read"
|
||||
}
|
||||
```
|
||||
|
||||
The subscription's subscriber (the NIP-42 `authed` pubkey) and client IP are
|
||||
cached at `reqOpen` and handed to every filter, so a filter can scope its
|
||||
decisions to whoever is reading. Like strfry itself, the read loop **fails
|
||||
open**: a filter that errors, an unparseable message, or a misconfigured
|
||||
pipeline entry delivers rather than withholds.
|
||||
|
||||
Like the write side, the read side is a **composable filter pipeline**: it reads
|
||||
a `[readpolicy]` table from the same config file as the write side
|
||||
(`noteguard.toml`, or the file named by `$NOTEGUARD_CONFIG`) with an ordered
|
||||
`pipeline` of read-filter names plus a per-filter `[readpolicy.filters.X]`
|
||||
config table — the read-side analogue of the write-side `pipeline` /
|
||||
`[filters.X]`. An empty (or absent) pipeline delivers everything (every
|
||||
subscription is passthrough). Filters run in order per event.
|
||||
|
||||
```toml
|
||||
[readpolicy]
|
||||
# compose the read filters, in order. Empty/absent => deliver all.
|
||||
pipeline = ["max_events_per_conn"]
|
||||
|
||||
# connection-level throttle: max events delivered per connection.
|
||||
[readpolicy.filters.max_events_per_conn]
|
||||
max = 5000
|
||||
```
|
||||
|
||||
Each filter is a [`ReadFilter`](src/read_filter.rs) — a lifecycle-aware,
|
||||
stateful analogue of the write-side [`NoteFilter`](src/note_filter.rs). It can
|
||||
allocate per-subscription / per-connection state at `reqOpen` and free it at
|
||||
`reqClose`/`connClose`, and returns one of **deliver**, **skip** (withhold this
|
||||
event), or **stop** (withhold this event and the rest of the batch) per event —
|
||||
so the throttles can bound a batch once a budget runs out. Adding a new read
|
||||
behavior is now a matter of implementing the trait and registering it, exactly
|
||||
like the write side.
|
||||
|
||||
**Passthrough fast path:** a subscription for which *no* filter needs per-event
|
||||
work answers `reqOpen` with `{"action":"accept","passthrough":true}`. strfry then
|
||||
skips all per-event marshaling for that subscription and delivers it via its
|
||||
zero-copy fast path, never sending `req` batches (it still sends
|
||||
`reqClose`/`connClose`). Each filter declares whether it needs events for a given
|
||||
subscription, and the engine ANDs those: an empty pipeline is always
|
||||
passthrough, while a configured throttle keeps the subscription non-passthrough
|
||||
(strfry must keep sending events for the counter to bound delivery). Emitting
|
||||
the field is forward-compatible: a strfry without passthrough support simply
|
||||
ignores it.
|
||||
|
||||
## Testing
|
||||
|
||||
You can test your filters like so:
|
||||
|
||||
+12
@@ -1,6 +1,18 @@
|
||||
pub mod filters;
|
||||
mod messages;
|
||||
mod note_filter;
|
||||
mod read_filter;
|
||||
pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
|
||||
pub use messages::{Action, InputMessage, OutputMessage};
|
||||
pub use note_filter::{Note, NoteFilter};
|
||||
pub use read_filter::{Admission, ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
|
||||
/// Path to the config file, from `$NOTEGUARD_CONFIG` or defaulting to
|
||||
/// `noteguard.toml`. Shared by the write loop and the read loop so both halves
|
||||
/// of the same deployment always read the same file.
|
||||
pub fn config_path() -> String {
|
||||
std::env::var("NOTEGUARD_CONFIG").unwrap_or_else(|_| "noteguard.toml".to_string())
|
||||
}
|
||||
|
||||
+17
-9
@@ -8,7 +8,7 @@ use noteguard::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Read};
|
||||
use std::io;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Config {
|
||||
@@ -107,12 +107,24 @@ impl Noteguard {
|
||||
#[cfg(feature = "forwarder")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
noteguard();
|
||||
dispatch();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "forwarder"))]
|
||||
fn main() {
|
||||
noteguard();
|
||||
dispatch();
|
||||
}
|
||||
|
||||
/// Route to the write-policy loop (default) or the read-policy loop
|
||||
/// (`noteguard read`). strfry invokes the read plugin as a plain shell command,
|
||||
/// e.g. `relay.readPolicy.plugin = "./noteguard read"`.
|
||||
fn dispatch() {
|
||||
env_logger::init();
|
||||
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("read") => noteguard::readpolicy::run(),
|
||||
_ => noteguard(),
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_output_message(msg: &OutputMessage) -> String {
|
||||
@@ -120,17 +132,13 @@ fn serialize_output_message(msg: &OutputMessage) -> String {
|
||||
}
|
||||
|
||||
fn noteguard() {
|
||||
env_logger::init();
|
||||
info!("running noteguard");
|
||||
|
||||
let config_path = "noteguard.toml";
|
||||
let config_path = noteguard::config_path();
|
||||
let mut noteguard = Noteguard::new();
|
||||
|
||||
let config: Config = {
|
||||
let mut file = std::fs::File::open(config_path).expect("Failed to open config file");
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)
|
||||
.expect("Failed to read config file");
|
||||
let contents = std::fs::read_to_string(&config_path).expect("Failed to read config file");
|
||||
toml::from_str(&contents).expect("Failed to parse config file")
|
||||
};
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
use crate::{InputMessage, OutputMessage};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone)]
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
pub struct Note {
|
||||
pub id: String,
|
||||
pub pubkey: String,
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Read-side (readPolicy) filter trait — the deliverability-path analogue of
|
||||
//! [`NoteFilter`](crate::NoteFilter).
|
||||
//!
|
||||
//! Where a [`NoteFilter`] decides whether an incoming event is *stored*, a
|
||||
//! [`ReadFilter`] decides, per subscription, which already-stored events are
|
||||
//! *delivered* to a particular subscriber. The read path needs richer semantics
|
||||
//! than the pure `fn(event) -> action` write path, so the trait carries:
|
||||
//!
|
||||
//! * **Lifecycle hooks** — [`req_open`](ReadFilter::req_open) (admission +
|
||||
//! passthrough opt-out), [`req_close`](ReadFilter::req_close),
|
||||
//! [`conn_close`](ReadFilter::conn_close) — so a filter can allocate per-sub /
|
||||
//! per-conn state and free it deterministically.
|
||||
//! * **Stateful, order-dependent batch filtering** — filters keep cross-event
|
||||
//! state (a per-conn delivery counter) and use
|
||||
//! [`EventVerdict::Stop`] to withhold the *rest* of a batch once a budget is
|
||||
//! exhausted, not just an independent per-event boolean.
|
||||
//! * **A check / commit split** — [`filter_event`](ReadFilter::filter_event) is
|
||||
//! a *check* that must not consume budget; the engine calls
|
||||
//! [`on_delivered`](ReadFilter::on_delivered) exactly once, and only when
|
||||
//! *every* filter delivered the event, so counters advance only for
|
||||
//! events that actually reach the client (see the module docs on
|
||||
//! [`crate::readpolicy`]).
|
||||
//! * **Shared per-connection context** — the engine caches the client IP +
|
||||
//! authed pubkey at `reqOpen` (a `req` batch carries no IP) and hands every
|
||||
//! hook a [`ConnContext`], so a per-client filter can key its own state by
|
||||
//! identity.
|
||||
//!
|
||||
//! **Fail-open** is a per-filter contract: a filter that errors or whose guest
|
||||
//! traps must return [`EventVerdict::Deliver`] rather than withhold a
|
||||
//! subscriber's own authorized feed. This matches strfry's stance and the engine
|
||||
//! (which no-responds on unparseable input so strfry times out and delivers).
|
||||
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Per-`(connId, subId)` context handed to every [`ReadFilter`] hook.
|
||||
///
|
||||
/// The IP and authed pubkey are cached by the engine at `reqOpen` (a `req` batch
|
||||
/// carries no IP), so a per-IP filter can meter on `req` without re-deriving
|
||||
/// them. Borrowed, never owned — a filter that needs to retain identity keys its
|
||||
/// own state by them.
|
||||
pub struct ConnContext<'a> {
|
||||
pub conn_id: u64,
|
||||
pub sub_id: &'a str,
|
||||
/// The rendered client IP, if strfry sent one (newer builds). `None` against
|
||||
/// older strfry, which sends no IP on `reqOpen`.
|
||||
pub ip: Option<&'a str>,
|
||||
/// The NIP-42 authed pubkey hex, if the connection did AUTH.
|
||||
pub authed: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// A read filter's per-event decision.
|
||||
///
|
||||
/// The three variants map onto the batch loop's control flow: `Deliver`
|
||||
/// continues to the next filter, `Skip` withholds just this event, and `Stop`
|
||||
/// withholds this event *and the entire remainder of the batch* (the "budget
|
||||
/// exhausted, `break`" semantics the throttles rely on).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EventVerdict {
|
||||
/// Deliver this event as far as this filter is concerned; continue the
|
||||
/// pipeline.
|
||||
Deliver,
|
||||
/// Withhold this event but keep processing the rest of the batch (e.g. a
|
||||
/// guest reject).
|
||||
Skip,
|
||||
/// Withhold this event and every subsequent event in the batch (e.g. a
|
||||
/// delivery budget just ran out).
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// A filter's `reqOpen` admission decision.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
/// Admit the subscription.
|
||||
Accept,
|
||||
/// Refuse the whole subscription, with an optional client message and retry
|
||||
/// hint (milliseconds).
|
||||
Reject {
|
||||
msg: Option<String>,
|
||||
retry_ms: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a filter reports at `reqOpen`: whether to admit the subscription and
|
||||
/// whether it needs to see per-event `req` batches for it.
|
||||
///
|
||||
/// The engine ANDs `!needs_events` across all filters to decide passthrough: a
|
||||
/// subscription is passthrough (strfry skips per-event marshaling) only if *no*
|
||||
/// filter needs per-event work. `needs_events` is evaluated per subscription, so
|
||||
/// it may depend on per-sub state established in `req_open` (e.g. whether this
|
||||
/// connection is exempt from the filter entirely).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OpenDecision {
|
||||
pub admission: Admission,
|
||||
pub needs_events: bool,
|
||||
}
|
||||
|
||||
impl OpenDecision {
|
||||
/// Admit and declare no per-event work (passthrough-friendly). The default.
|
||||
pub fn passthrough() -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Accept,
|
||||
needs_events: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit but declare this filter needs to see `req` batches (disables
|
||||
/// passthrough for the subscription).
|
||||
pub fn needs_events() -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Accept,
|
||||
needs_events: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse the whole subscription.
|
||||
pub fn reject(msg: Option<String>, retry_ms: Option<u64>) -> Self {
|
||||
OpenDecision {
|
||||
admission: Admission::Reject { msg, retry_ms },
|
||||
needs_events: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A composable read-policy filter. See the [module docs](self) for the
|
||||
/// semantics (lifecycle, check/commit, fail-open).
|
||||
pub trait ReadFilter {
|
||||
/// The `[readpolicy].pipeline` key this filter is registered under.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// A subscription started serving. Allocate any per-sub state, and report
|
||||
/// admission + whether this filter needs per-event batches (passthrough).
|
||||
/// `filter` is the subscription's cached filter JSON, present only here.
|
||||
///
|
||||
/// Defaults to admit + passthrough-friendly.
|
||||
fn req_open(&mut self, _ctx: &ConnContext, _filter: Option<&Value>) -> OpenDecision {
|
||||
OpenDecision::passthrough()
|
||||
}
|
||||
|
||||
/// Decide one event. This is a **check only**: it must not consume budget —
|
||||
/// commit that in [`on_delivered`](Self::on_delivered), which the engine
|
||||
/// calls iff every filter delivered the event. This keeps a partial pipeline
|
||||
/// run (a later filter's `Stop`) from corrupting this filter's budget.
|
||||
///
|
||||
/// Only called for non-passthrough subscriptions. To honour the fail-open
|
||||
/// contract, return [`EventVerdict::Deliver`] on internal error.
|
||||
///
|
||||
/// Defaults to [`EventVerdict::Deliver`].
|
||||
fn filter_event(&mut self, _ctx: &ConnContext, _ev: &UnparsedNote) -> EventVerdict {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
|
||||
/// Called, in pipeline order, after an event was delivered by *every*
|
||||
/// filter. The place to consume budget / bump counters exactly once. Defaults to a
|
||||
/// no-op (stateless filters need nothing here).
|
||||
fn on_delivered(&mut self, _ctx: &ConnContext, _ev: &UnparsedNote) {}
|
||||
|
||||
/// A subscription went away — free its per-sub state.
|
||||
fn req_close(&mut self, _conn_id: u64, _sub_id: &str) {}
|
||||
|
||||
/// A connection went away — free its per-conn state. (Note: per-IP state that
|
||||
/// must survive a reconnect is deliberately *not* freed here.)
|
||||
fn conn_close(&mut self, _conn_id: u64) {}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Per-connection delivery cap: withhold once a connection has been delivered
|
||||
/// `max` events across the life of the connection (across all its
|
||||
/// subscriptions).
|
||||
///
|
||||
/// The counter is keyed by `connId`, so it is shared by every subscription on a
|
||||
/// connection and reset only when the connection closes. Once the cap is hit the
|
||||
/// rest of the batch — and every future batch — is withheld
|
||||
/// ([`EventVerdict::Stop`]).
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct MaxEventsPerConn {
|
||||
/// Max events delivered per `connId` over the connection's life.
|
||||
pub max: u64,
|
||||
|
||||
/// `connId` -> events delivered so far. Committed in `on_delivered`, so it
|
||||
/// only counts events delivered by the *whole* pipeline.
|
||||
#[serde(skip)]
|
||||
pub delivered: HashMap<u64, u64>,
|
||||
}
|
||||
|
||||
impl ReadFilter for MaxEventsPerConn {
|
||||
fn name(&self) -> &'static str {
|
||||
"max_events_per_conn"
|
||||
}
|
||||
|
||||
fn req_open(
|
||||
&mut self,
|
||||
_ctx: &ConnContext,
|
||||
_filter: Option<&serde_json::Value>,
|
||||
) -> OpenDecision {
|
||||
// A configured cap always needs to see events, so strfry must keep
|
||||
// sending `req` batches for the counter to bound delivery.
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, _ev: &UnparsedNote) -> EventVerdict {
|
||||
// Check only: once the connection is at its cap, withhold this event and
|
||||
// the rest of the batch. The counter advances in `on_delivered`.
|
||||
let already = *self.delivered.get(&ctx.conn_id).unwrap_or(&0);
|
||||
if already >= self.max {
|
||||
EventVerdict::Stop
|
||||
} else {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
|
||||
fn on_delivered(&mut self, ctx: &ConnContext, _ev: &UnparsedNote) {
|
||||
*self.delivered.entry(ctx.conn_id).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
self.delivered.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Built-in [`ReadFilter`](crate::ReadFilter) implementations, composed by the
|
||||
//! `[readpolicy].pipeline` config. The read-side counterpart to
|
||||
//! [`crate::filters`].
|
||||
|
||||
mod max_events;
|
||||
|
||||
pub use max_events::MaxEventsPerConn;
|
||||
+395
@@ -0,0 +1,395 @@
|
||||
//! Read-side (readPolicy) plugin wire protocol.
|
||||
//!
|
||||
//! strfry's read plugin is the REQ-path analogue of the writePolicy plugin
|
||||
//! implemented in [`crate::messages`]. Whereas the write plugin decides whether
|
||||
//! an incoming event is *stored* (a reject deletes it for everyone), the read
|
||||
//! plugin decides, per subscription, which already-stored events are *delivered*
|
||||
//! to that particular subscriber. See `strfry/docs/plugins.md` ("Read-policy
|
||||
//! plugins") and `strfry/src/PluginReadPolicy.h` for the authoritative protocol.
|
||||
//!
|
||||
//! Every message is one minified JSON object followed by a newline. All requests
|
||||
//! carry a monotonic `reqId`; responses to `reqOpen`/`req` must echo it.
|
||||
//! `reqClose`/`connClose` are fire-and-forget — the plugin must NOT respond to
|
||||
//! them (a stray response desyncs the pipe).
|
||||
|
||||
use crate::Note;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
use serde_json::Value;
|
||||
|
||||
/// An event object from a `req` batch, kept in its original unparsed wire form.
|
||||
///
|
||||
/// Wrapping the raw JSON (rather than a fully-parsed [`Note`]) lets us measure
|
||||
/// the exact number of bytes strfry streamed — [`size`](Self::size) is the wire
|
||||
/// length with no re-serialization — while deferring the cost of a full parse to
|
||||
/// the paths that actually need field access. A filter that only meters volume
|
||||
/// never parses a `Note` at all; it only ever calls `size()` and, for the
|
||||
/// accept-list, the cheap id-only [`id`](Self::id).
|
||||
///
|
||||
/// `RawValue` only captures the original source bytes when it is deserialized
|
||||
/// straight from the top-level `serde_json` deserializer. That is why
|
||||
/// [`ReadInput`] uses a manual `Deserialize` over a flat struct instead of the
|
||||
/// derived `#[serde(tag = "type")]` enum: an internally-tagged enum buffers the
|
||||
/// object into a serde `Content` value first, which strips `RawValue`'s capture.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UnparsedNote(Box<RawValue>);
|
||||
|
||||
impl UnparsedNote {
|
||||
/// Exact byte length of the event object as strfry streamed it — the wire
|
||||
/// cost of delivering it. No re-serialization.
|
||||
pub fn size(&self) -> usize {
|
||||
self.0.get().len()
|
||||
}
|
||||
|
||||
/// Fully parse the event into a [`Note`]. Only used by a filter that
|
||||
/// actually needs the event's fields.
|
||||
pub fn parse(&self) -> serde_json::Result<Note> {
|
||||
serde_json::from_str(self.0.get())
|
||||
}
|
||||
|
||||
/// Cheaply parse just the event `id` for the accept-list, avoiding a full
|
||||
/// [`Note`] parse for filters that never look at an event's fields.
|
||||
pub fn id(&self) -> serde_json::Result<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct IdOnly {
|
||||
id: String,
|
||||
}
|
||||
let IdOnly { id } = serde_json::from_str(self.0.get())?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Construct one directly from a JSON string (test helper / for callers that
|
||||
/// already hold the wire bytes).
|
||||
#[cfg(test)]
|
||||
pub fn from_json(json: &str) -> serde_json::Result<Self> {
|
||||
Ok(UnparsedNote(RawValue::from_string(json.to_string())?))
|
||||
}
|
||||
}
|
||||
|
||||
/// A message sent from strfry to the read plugin, discriminated by `type`.
|
||||
///
|
||||
/// Deserialized via a manual `impl Deserialize` (below) rather than the derived
|
||||
/// internally-tagged enum, so the nested `Vec<UnparsedNote>` in [`Req`] captures
|
||||
/// true wire bytes for byte metering. See [`UnparsedNote`].
|
||||
#[derive(Debug)]
|
||||
pub enum ReadInput {
|
||||
/// A subscription started serving on a read thread. The admission/throttle
|
||||
/// hook and the authoritative place the subscription's `filter` arrives.
|
||||
ReqOpen {
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
/// The authenticated pubkey (hex), present only if the connection did
|
||||
/// NIP-42 AUTH. This is the subscriber / script owner.
|
||||
authed: Option<String>,
|
||||
/// The subscription's filters, as a JSON array. Sent authoritatively
|
||||
/// here; omitted on `req`. Cache it per `(connId, subId)` if needed.
|
||||
filter: Option<Value>,
|
||||
/// The rendered client IP string, present when strfry knows it (newer
|
||||
/// strfry builds only; absent → `None` against older strfry). Cached
|
||||
/// per `connId` so the per-IP bandwidth throttle can meter on `req`,
|
||||
/// which carries no IP.
|
||||
ip: Option<String>,
|
||||
},
|
||||
|
||||
/// A batch of already-matched events to make deliverability decisions about.
|
||||
/// `filter` is NOT resent here — use the one cached from `reqOpen`.
|
||||
Req {
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
authed: Option<String>,
|
||||
events: Vec<UnparsedNote>,
|
||||
},
|
||||
|
||||
/// A subscription went away. Free per-subscription state. No response.
|
||||
ReqClose { conn_id: u64, sub_id: String },
|
||||
|
||||
/// A connection went away. Free all per-connection state. No response.
|
||||
ConnClose { conn_id: u64 },
|
||||
}
|
||||
|
||||
/// Flat wire shape of every read-plugin message. Deserialized straight from the
|
||||
/// top-level `serde_json` deserializer (no tag/flatten/untagged buffering) so
|
||||
/// the nested `Vec<UnparsedNote>` keeps its raw bytes; [`ReadInput`]'s manual
|
||||
/// `Deserialize` dispatches on `msg_type` to build the typed enum.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawInput {
|
||||
#[serde(rename = "type")]
|
||||
msg_type: String,
|
||||
#[serde(default)]
|
||||
req_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
conn_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
sub_id: Option<String>,
|
||||
#[serde(default)]
|
||||
authed: Option<String>,
|
||||
#[serde(default)]
|
||||
filter: Option<Value>,
|
||||
#[serde(default)]
|
||||
ip: Option<String>,
|
||||
#[serde(default)]
|
||||
events: Vec<UnparsedNote>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ReadInput {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::de::Error;
|
||||
let RawInput {
|
||||
msg_type,
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
events,
|
||||
} = RawInput::deserialize(deserializer)?;
|
||||
|
||||
match msg_type.as_str() {
|
||||
"reqOpen" => Ok(ReadInput::ReqOpen {
|
||||
req_id: req_id.ok_or_else(|| D::Error::missing_field("reqId"))?,
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
}),
|
||||
"req" => Ok(ReadInput::Req {
|
||||
req_id: req_id.ok_or_else(|| D::Error::missing_field("reqId"))?,
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
authed,
|
||||
events,
|
||||
}),
|
||||
"reqClose" => Ok(ReadInput::ReqClose {
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
sub_id: sub_id.ok_or_else(|| D::Error::missing_field("subId"))?,
|
||||
}),
|
||||
"connClose" => Ok(ReadInput::ConnClose {
|
||||
conn_id: conn_id.ok_or_else(|| D::Error::missing_field("connId"))?,
|
||||
}),
|
||||
other => Err(D::Error::unknown_variant(
|
||||
other,
|
||||
&["reqOpen", "req", "reqClose", "connClose"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admission action returned to a `reqOpen`.
|
||||
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ReadAction {
|
||||
/// Admit the subscription.
|
||||
Accept,
|
||||
/// Refuse / throttle the whole subscription.
|
||||
Reject,
|
||||
}
|
||||
|
||||
/// Response to a `reqOpen`: admit or refuse the subscription.
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReqOpenResponse {
|
||||
pub req_id: u64,
|
||||
pub action: ReadAction,
|
||||
/// Reason surfaced to the client on reject (optional).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub msg: Option<String>,
|
||||
/// Retry hint in milliseconds, appended to the reject message (optional).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub retry_ms: Option<u64>,
|
||||
/// Opt out of per-event filtering for this subscription. When `true` (only
|
||||
/// meaningful on an `accept`), the plugin declares it needs no `req`
|
||||
/// batches: strfry skips all per-event marshaling and delivers this
|
||||
/// subscription via its zero-copy fast path, while still sending
|
||||
/// `reqClose`/`connClose` so the plugin can free state. Omitted from the
|
||||
/// wire when `false`.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub passthrough: bool,
|
||||
}
|
||||
|
||||
impl ReqOpenResponse {
|
||||
/// Admit the subscription. With `passthrough`, opt out of per-event
|
||||
/// filtering: strfry never sends `req` for it and delivers via the
|
||||
/// zero-copy fast path.
|
||||
pub fn accept(req_id: u64, passthrough: bool) -> Self {
|
||||
ReqOpenResponse {
|
||||
req_id,
|
||||
action: ReadAction::Accept,
|
||||
msg: None,
|
||||
retry_ms: None,
|
||||
passthrough,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse the subscription with an optional message and retry hint.
|
||||
pub fn reject(req_id: u64, msg: Option<String>, retry_ms: Option<u64>) -> Self {
|
||||
ReqOpenResponse {
|
||||
req_id,
|
||||
action: ReadAction::Reject,
|
||||
msg,
|
||||
retry_ms,
|
||||
passthrough: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Response to a `req`: the accept-list is authoritative. Every event in the
|
||||
/// batch whose id is NOT listed is withheld from this subscriber. (Delivering
|
||||
/// all = echo every id; withholding all = empty array.)
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReqResponse {
|
||||
pub req_id: u64,
|
||||
pub accept: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_with_filter_and_auth() {
|
||||
let line = r#"{"type":"reqOpen","reqId":7,"connId":3,"subId":"sub0","authed":"aa","filter":[{"kinds":[1]}]}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(req_id, 7);
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(sub_id, "sub0");
|
||||
assert_eq!(authed.as_deref(), Some("aa"));
|
||||
assert!(filter.is_some());
|
||||
}
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_unauthed_no_filter() {
|
||||
let line = r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen {
|
||||
authed, filter, ip, ..
|
||||
} => {
|
||||
assert!(authed.is_none());
|
||||
assert!(filter.is_none());
|
||||
// Absent `ip` field (older strfry) => None, still parses.
|
||||
assert!(ip.is_none());
|
||||
}
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_open_with_ip() {
|
||||
let line = r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"127.0.0.1"}"#;
|
||||
match serde_json::from_str::<ReadInput>(line).unwrap() {
|
||||
ReadInput::ReqOpen { ip, .. } => assert_eq!(ip.as_deref(), Some("127.0.0.1")),
|
||||
other => panic!("expected reqOpen, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_req_with_events() {
|
||||
let event = r#"{"id":"ab","pubkey":"cd","content":"hi","created_at":1,"kind":1,"tags":[],"sig":"ef"}"#;
|
||||
let line =
|
||||
format!(r#"{{"type":"req","reqId":9,"connId":3,"subId":"sub0","events":[{event}]}}"#);
|
||||
match serde_json::from_str::<ReadInput>(&line).unwrap() {
|
||||
ReadInput::Req {
|
||||
req_id,
|
||||
conn_id,
|
||||
events,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(req_id, 9);
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(events.len(), 1);
|
||||
// The raw wire bytes are captured verbatim...
|
||||
assert_eq!(events[0].size(), event.len());
|
||||
// ...and both the cheap id-only and full parse agree.
|
||||
assert_eq!(events[0].id().unwrap(), "ab");
|
||||
assert_eq!(events[0].parse().unwrap().id, "ab");
|
||||
}
|
||||
other => panic!("expected req, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparsed_note_size_is_raw_wire_length() {
|
||||
// Deliberately include whitespace: size() must reflect the exact bytes
|
||||
// as delivered, not a re-minified form.
|
||||
let raw = r#"{"id": "ab", "kind": 1}"#;
|
||||
let note = UnparsedNote::from_json(raw).unwrap();
|
||||
assert_eq!(note.size(), raw.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unparsed_note_parse_round_trips() {
|
||||
let raw = r#"{"id":"ab","pubkey":"cd","content":"hi","created_at":1,"kind":1,"tags":[],"sig":"ef"}"#;
|
||||
let note = UnparsedNote::from_json(raw).unwrap();
|
||||
let parsed = note.parse().unwrap();
|
||||
assert_eq!(parsed.id, "ab");
|
||||
assert_eq!(parsed.pubkey, "cd");
|
||||
assert_eq!(parsed.kind, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_lifecycle_messages() {
|
||||
match serde_json::from_str::<ReadInput>(r#"{"type":"reqClose","connId":3,"subId":"sub0"}"#)
|
||||
.unwrap()
|
||||
{
|
||||
ReadInput::ReqClose { conn_id, sub_id } => {
|
||||
assert_eq!(conn_id, 3);
|
||||
assert_eq!(sub_id, "sub0");
|
||||
}
|
||||
other => panic!("expected reqClose, got {:?}", other),
|
||||
}
|
||||
|
||||
match serde_json::from_str::<ReadInput>(r#"{"type":"connClose","connId":3}"#).unwrap() {
|
||||
ReadInput::ConnClose { conn_id } => assert_eq!(conn_id, 3),
|
||||
other => panic!("expected connClose, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_responses_minified() {
|
||||
let accept = ReqOpenResponse::accept(2, false);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&accept).unwrap(),
|
||||
r#"{"reqId":2,"action":"accept"}"#
|
||||
);
|
||||
|
||||
let passthrough = ReqOpenResponse::accept(2, true);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&passthrough).unwrap(),
|
||||
r#"{"reqId":2,"action":"accept","passthrough":true}"#
|
||||
);
|
||||
|
||||
let reject = ReqOpenResponse::reject(2, Some("slow down".into()), Some(1000));
|
||||
assert_eq!(
|
||||
serde_json::to_string(&reject).unwrap(),
|
||||
r#"{"reqId":2,"action":"reject","msg":"slow down","retryMs":1000}"#
|
||||
);
|
||||
|
||||
let batch = ReqResponse {
|
||||
req_id: 5,
|
||||
accept: vec!["deadbeef".into()],
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_string(&batch).unwrap(),
|
||||
r#"{"reqId":5,"accept":["deadbeef"]}"#
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
//! Read-side (readPolicy) plugin engine.
|
||||
//!
|
||||
//! Speaks strfry's per-subscription REQ deliverability protocol
|
||||
//! ([`crate::readmsg`]) and drives a config-composed pipeline of
|
||||
//! [`ReadFilter`]s to make per-subscriber, per-event deliver/withhold decisions.
|
||||
//! It is the read-path counterpart to the write-side [`Noteguard`] engine in
|
||||
//! `main.rs`: a name-keyed `registered_filters` registry, a
|
||||
//! [`register_filter`](ReadPolicy::register_filter) hook, and a config-driven
|
||||
//! `pipeline: Vec<String>` composed in [`load_config`](ReadPolicy::load_config).
|
||||
//!
|
||||
//! ## Batch semantics (the check / commit split)
|
||||
//!
|
||||
//! Unlike the write side's pure `fn(event) -> action`, read filters carry
|
||||
//! cross-event state (a per-conn delivery counter) and can withhold
|
||||
//! the *rest* of a batch once a budget is exhausted. To compose these correctly
|
||||
//! the engine runs a **two-phase** batch loop per event:
|
||||
//!
|
||||
//! 1. [`filter_event`](ReadFilter::filter_event) — a *check* over the pipeline in
|
||||
//! order. First [`Skip`](EventVerdict::Skip) withholds just this event; first
|
||||
//! [`Stop`](EventVerdict::Stop) withholds this event and breaks the batch. A
|
||||
//! filter must not consume budget here.
|
||||
//! 2. [`on_delivered`](ReadFilter::on_delivered) — called on every filter, in
|
||||
//! order, *only if* every filter delivered the event, so counters/buckets
|
||||
//! advance exactly once and only for events that actually reach the client.
|
||||
//!
|
||||
//! This reproduces the old inline `continue`/`break` semantics faithfully: an
|
||||
//! event a later filter withholds never charges an earlier filter's budget.
|
||||
//!
|
||||
//! ## Fail-open
|
||||
//!
|
||||
//! Like strfry, this loop FAILS OPEN. Filters honour that internally (a guest
|
||||
//! trap delivers); the engine no-responds on unparseable input so strfry times
|
||||
//! out and delivers, and a bad/unknown pipeline entry is logged and skipped
|
||||
//! rather than aborting the loop.
|
||||
//!
|
||||
//! As an optimization, a subscription whose filters all report `!needs_events`
|
||||
//! answers `reqOpen` with `passthrough: true`, telling strfry to skip per-event
|
||||
//! marshaling and deliver via the zero-copy fast path (no `req` batches).
|
||||
|
||||
use crate::read_filter::{Admission, ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readfilters::MaxEventsPerConn;
|
||||
use crate::readmsg::{ReadInput, ReqOpenResponse, ReqResponse, UnparsedNote};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
/// The `[readpolicy]` config table (read from `noteguard.toml`, or the file
|
||||
/// named by `$NOTEGUARD_CONFIG`). Mirrors the write-side `Config`: an ordered
|
||||
/// `pipeline` of filter names plus a `filters` map of each filter's own config.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct ReadPolicyConfig {
|
||||
/// Ordered list of read-filter names to compose. Empty => deliver all
|
||||
/// (every subscription is passthrough).
|
||||
pub pipeline: Vec<String>,
|
||||
|
||||
/// Per-filter config tables, keyed by filter name (`[readpolicy.filters.X]`).
|
||||
pub filters: HashMap<String, toml::Value>,
|
||||
}
|
||||
|
||||
/// Wrapper matching the surrounding `noteguard.toml` shape so the read loop can
|
||||
/// share the same config file as the write loop (the write-side `pipeline` and
|
||||
/// `filters` keys are ignored by serde here).
|
||||
#[derive(Deserialize, Default)]
|
||||
struct FileConfig {
|
||||
readpolicy: Option<ReadPolicyConfig>,
|
||||
}
|
||||
|
||||
/// Per-connection identity captured at `reqOpen` and freed at `connClose`.
|
||||
/// Cached because `req` batches carry no client IP, but a per-IP filter must
|
||||
/// meter on `req` — so the engine caches the IP (and `authed`, for whitelists)
|
||||
/// under `connId` and hands it to filters via [`ConnContext`].
|
||||
struct ConnInfo {
|
||||
ip: Option<String>,
|
||||
authed: Option<String>,
|
||||
}
|
||||
|
||||
/// Constructs a boxed [`ReadFilter`] from its TOML config. Mirrors the
|
||||
/// write-side `ConstructFilter`.
|
||||
type ConstructReadFilter = Box<fn(toml::Value) -> Result<Box<dyn ReadFilter>, toml::de::Error>>;
|
||||
|
||||
/// The read-policy engine: a name-keyed filter registry, the loaded pipeline,
|
||||
/// and the engine-owned shared per-connection context.
|
||||
#[derive(Default)]
|
||||
pub struct ReadPolicy {
|
||||
registered_filters: HashMap<String, ConstructReadFilter>,
|
||||
pipeline: Vec<Box<dyn ReadFilter>>,
|
||||
/// `connId` -> its IP/authed identity, cached at `reqOpen`. Freed at
|
||||
/// `connClose`.
|
||||
conn_info: HashMap<u64, ConnInfo>,
|
||||
}
|
||||
|
||||
impl ReadPolicy {
|
||||
/// A new engine with all built-in filters registered but an empty pipeline
|
||||
/// (call [`load_config`](Self::load_config) to compose it).
|
||||
pub fn new() -> Self {
|
||||
let mut rp = ReadPolicy::default();
|
||||
rp.register_builtin_filters();
|
||||
rp
|
||||
}
|
||||
|
||||
/// Register a read filter, keyed by its [`name`](ReadFilter::name). Mirrors
|
||||
/// the write-side `register_filter`.
|
||||
pub fn register_filter<F: ReadFilter + 'static + Default + DeserializeOwned>(&mut self) {
|
||||
self.registered_filters.insert(
|
||||
F::name(&F::default()).to_string(),
|
||||
Box::new(|filter_config| {
|
||||
filter_config
|
||||
.try_into()
|
||||
.map(|filter: F| Box::new(filter) as Box<dyn ReadFilter>)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// All built-in read filters, available on every new [`ReadPolicy`].
|
||||
fn register_builtin_filters(&mut self) {
|
||||
self.register_filter::<MaxEventsPerConn>();
|
||||
}
|
||||
|
||||
/// Compose the pipeline from config. Unlike the write side (which panics on a
|
||||
/// bad/unknown pipeline entry), the read side fails open: a bad or unknown
|
||||
/// entry is logged and skipped, since a misconfigured read filter must not
|
||||
/// take down a subscriber's feed.
|
||||
pub fn load_config(&mut self, config: &ReadPolicyConfig) {
|
||||
self.pipeline.clear();
|
||||
|
||||
for name in &config.pipeline {
|
||||
let cfg = config
|
||||
.filters
|
||||
.get(name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| toml::Value::Table(Default::default()));
|
||||
|
||||
match self.registered_filters.get(name.as_str()) {
|
||||
Some(constructor) => match constructor(cfg) {
|
||||
Ok(filter) => self.pipeline.push(filter),
|
||||
Err(e) => log::error!(
|
||||
"readpolicy: bad config for filter '{}' ({}); skipping (fail open)",
|
||||
name,
|
||||
e
|
||||
),
|
||||
},
|
||||
None => log::error!(
|
||||
"readpolicy: unknown read filter '{}'; skipping (fail open)",
|
||||
name
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one input line. Returns `Some(json)` to write back for
|
||||
/// `reqOpen`/`req`, or `None` for the fire-and-forget lifecycle messages
|
||||
/// (`reqClose`/`connClose`) and unparseable input (strfry fails open on no
|
||||
/// response).
|
||||
pub fn handle(&mut self, line: &str) -> Option<String> {
|
||||
let input: ReadInput = match serde_json::from_str(line) {
|
||||
Ok(input) => input,
|
||||
Err(e) => {
|
||||
// Can't recover a reqId, so we can't respond; strfry will time
|
||||
// out and deliver (fail open).
|
||||
log::error!("readpolicy: unparseable input ({}): {}", e, line);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match input {
|
||||
ReadInput::ReqOpen {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
filter,
|
||||
ip,
|
||||
} => {
|
||||
log::info!(
|
||||
"reqOpen conn={} sub={} authed={:?} ip={:?} filter={}",
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed,
|
||||
ip,
|
||||
filter.as_ref().map(|f| f.to_string()).unwrap_or_default()
|
||||
);
|
||||
Some(json(
|
||||
&self.req_open(req_id, conn_id, sub_id, authed, ip, filter),
|
||||
))
|
||||
}
|
||||
|
||||
ReadInput::Req {
|
||||
req_id,
|
||||
conn_id,
|
||||
sub_id,
|
||||
authed: _,
|
||||
events,
|
||||
} => {
|
||||
let accept = self.filter_batch(conn_id, &sub_id, &events);
|
||||
log::info!(
|
||||
"req conn={} sub={} events={} delivered={}",
|
||||
conn_id,
|
||||
sub_id,
|
||||
events.len(),
|
||||
accept.len()
|
||||
);
|
||||
Some(json(&ReqResponse { req_id, accept }))
|
||||
}
|
||||
|
||||
ReadInput::ReqClose { conn_id, sub_id } => {
|
||||
log::info!("reqClose conn={} sub={}", conn_id, sub_id);
|
||||
for filter in &mut self.pipeline {
|
||||
filter.req_close(conn_id, &sub_id);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
ReadInput::ConnClose { conn_id } => {
|
||||
log::info!("connClose conn={}", conn_id);
|
||||
for filter in &mut self.pipeline {
|
||||
filter.conn_close(conn_id);
|
||||
}
|
||||
self.conn_info.remove(&conn_id);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit (or refuse) a subscription. Caches the connection identity, runs
|
||||
/// every filter's `req_open`, and composes the result: reject if any filter
|
||||
/// rejects (first message wins), else accept — with `passthrough` iff NO
|
||||
/// filter needs per-event batches.
|
||||
fn req_open(
|
||||
&mut self,
|
||||
req_id: u64,
|
||||
conn_id: u64,
|
||||
sub_id: String,
|
||||
authed: Option<String>,
|
||||
ip: Option<String>,
|
||||
filter: Option<serde_json::Value>,
|
||||
) -> ReqOpenResponse {
|
||||
// Cache the connection's identity so per-IP filters can meter on `req`,
|
||||
// which carries no IP. Refreshed on each reqOpen (a connection's IP is
|
||||
// stable, but a later AUTH can add an authed pubkey).
|
||||
self.conn_info.insert(
|
||||
conn_id,
|
||||
ConnInfo {
|
||||
ip: ip.clone(),
|
||||
authed: authed.clone(),
|
||||
},
|
||||
);
|
||||
|
||||
let ctx = ConnContext {
|
||||
conn_id,
|
||||
sub_id: &sub_id,
|
||||
ip: ip.as_deref(),
|
||||
authed: authed.as_deref(),
|
||||
};
|
||||
|
||||
// Run req_open on EVERY filter (so each allocates its per-sub state and
|
||||
// gets symmetric reqClose/connClose cleanup even under reject), while
|
||||
// collecting the composed decision.
|
||||
let mut needs_events = false;
|
||||
let mut reject: Option<(Option<String>, Option<u64>)> = None;
|
||||
for f in &mut self.pipeline {
|
||||
let decision = f.req_open(&ctx, filter.as_ref());
|
||||
let OpenDecision {
|
||||
admission,
|
||||
needs_events: filter_needs,
|
||||
} = decision;
|
||||
needs_events |= filter_needs;
|
||||
if reject.is_none() {
|
||||
if let Admission::Reject { msg, retry_ms } = admission {
|
||||
reject = Some((msg, retry_ms));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((msg, retry_ms)) = reject {
|
||||
return ReqOpenResponse::reject(req_id, msg, retry_ms);
|
||||
}
|
||||
|
||||
// Passthrough iff no filter needs per-event work: strfry skips per-event
|
||||
// marshaling and delivers via its zero-copy fast path.
|
||||
ReqOpenResponse::accept(req_id, !needs_events)
|
||||
}
|
||||
|
||||
/// Decide which events in a batch to deliver by running the two-phase
|
||||
/// pipeline (see the module docs). Returns the accept-list of event ids.
|
||||
fn filter_batch(&mut self, conn_id: u64, sub_id: &str, events: &[UnparsedNote]) -> Vec<String> {
|
||||
// Resolve the connection's cached identity (req carries no IP).
|
||||
// Destructured so the conn_info borrow is disjoint from the pipeline's.
|
||||
let ReadPolicy {
|
||||
pipeline,
|
||||
conn_info,
|
||||
..
|
||||
} = self;
|
||||
let conn = conn_info.get(&conn_id);
|
||||
let ctx = ConnContext {
|
||||
conn_id,
|
||||
sub_id,
|
||||
ip: conn.and_then(|c| c.ip.as_deref()),
|
||||
authed: conn.and_then(|c| c.authed.as_deref()),
|
||||
};
|
||||
|
||||
// The accept-list can never exceed the batch.
|
||||
let mut accept = Vec::with_capacity(events.len());
|
||||
'batch: for ev in events {
|
||||
// Phase 1: check the pipeline in order. First Skip withholds this
|
||||
// event; first Stop withholds this event and the rest of the batch.
|
||||
let mut deliver = true;
|
||||
for filter in pipeline.iter_mut() {
|
||||
match filter.filter_event(&ctx, ev) {
|
||||
EventVerdict::Deliver => {}
|
||||
EventVerdict::Skip => {
|
||||
deliver = false;
|
||||
break;
|
||||
}
|
||||
EventVerdict::Stop => break 'batch,
|
||||
}
|
||||
}
|
||||
if !deliver {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Phase 2: the event is delivered by ALL filters — commit budget.
|
||||
for filter in pipeline.iter_mut() {
|
||||
filter.on_delivered(&ctx, ev);
|
||||
}
|
||||
|
||||
// Accept-list needs the id. A cheap id-only parse — the bandwidth-
|
||||
// only path still never full-parses. A malformed id (should not
|
||||
// happen post-delivery) just drops the event from the accept-list.
|
||||
match ev.id() {
|
||||
Ok(id) => accept.push(id),
|
||||
Err(e) => log::error!("readpolicy: unparseable event id (withholding): {}", e),
|
||||
}
|
||||
}
|
||||
accept
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a response to minified JSON (never fails for our types).
|
||||
fn json<T: serde::Serialize>(msg: &T) -> String {
|
||||
serde_json::to_string(msg).expect("read policy response should always serialize")
|
||||
}
|
||||
|
||||
/// Load the `[readpolicy]` table from the shared config file
|
||||
/// ([`crate::config_path`]). A missing file or absent `[readpolicy]` table
|
||||
/// yields the default (empty pipeline => deliver-all) config.
|
||||
///
|
||||
/// (Named apart from [`ReadPolicy::load_config`], which composes the pipeline
|
||||
/// from an already-parsed config.)
|
||||
fn read_config_file() -> ReadPolicyConfig {
|
||||
let path = crate::config_path();
|
||||
|
||||
let contents = match std::fs::read_to_string(&path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("readpolicy: no config at {} ({}); delivering all", path, e);
|
||||
return ReadPolicyConfig::default();
|
||||
}
|
||||
};
|
||||
|
||||
match toml::from_str::<FileConfig>(&contents) {
|
||||
Ok(cfg) => cfg.readpolicy.unwrap_or_default(),
|
||||
Err(e) => {
|
||||
log::error!("readpolicy: bad config {} ({}); delivering all", path, e);
|
||||
ReadPolicyConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `noteguard read` entrypoint: read line-delimited JSON requests from
|
||||
/// stdin, write line-delimited JSON responses to stdout (line-buffered).
|
||||
pub fn run() {
|
||||
log::info!("running noteguard read policy");
|
||||
let config = read_config_file();
|
||||
log::info!(
|
||||
"readpolicy pipeline: {:?} ({} filter configs)",
|
||||
config.pipeline,
|
||||
config.filters.len()
|
||||
);
|
||||
|
||||
let mut engine = ReadPolicy::new();
|
||||
engine.load_config(&config);
|
||||
|
||||
let stdin = io::stdin();
|
||||
let stdout = io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
|
||||
for line in stdin.lock().lines() {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(e) => {
|
||||
eprintln!("readpolicy: failed to read line: {}", e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(response) = engine.handle(&line) {
|
||||
if writeln!(out, "{}", response).is_err() {
|
||||
break;
|
||||
}
|
||||
// strfry reads a response per request; keep the pipe line-buffered.
|
||||
let _ = out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Build an engine from a `[readpolicy]`-inner TOML fragment (pipeline +
|
||||
/// filter tables), exercising the real registry + config path.
|
||||
fn engine(config: &str) -> ReadPolicy {
|
||||
let config: ReadPolicyConfig = toml::from_str(config).expect("test config parses");
|
||||
let mut engine = ReadPolicy::new();
|
||||
engine.load_config(&config);
|
||||
engine
|
||||
}
|
||||
|
||||
/// An [`UnparsedNote`] built from real wire JSON.
|
||||
fn unparsed_note(id: &str, kind: i64, content: &str) -> UnparsedNote {
|
||||
let json = format!(
|
||||
r#"{{"id":"{}","pubkey":"00","content":"{}","created_at":0,"kind":{},"tags":[],"sig":"00"}}"#,
|
||||
id, content, kind
|
||||
);
|
||||
UnparsedNote::from_json(&json).unwrap()
|
||||
}
|
||||
|
||||
fn events(ids: &[&str]) -> Vec<UnparsedNote> {
|
||||
ids.iter().map(|id| unparsed_note(id, 1, "")).collect()
|
||||
}
|
||||
|
||||
fn parse_accept(json: &str) -> Vec<String> {
|
||||
let v: serde_json::Value = serde_json::from_str(json).unwrap();
|
||||
v["accept"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|x| x.as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_pipeline_delivers_all_via_passthrough() {
|
||||
// No filters => no per-event work => passthrough (strfry fast path).
|
||||
let mut engine = engine("pipeline = []");
|
||||
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","authed":"aa"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept","passthrough":true}"#);
|
||||
|
||||
// Belt-and-suspenders: if an older strfry still sends `req` for a
|
||||
// passthrough sub, we deliver everything anyway.
|
||||
let resp = engine
|
||||
.handle(
|
||||
r#"{"type":"req","reqId":1,"connId":1,"subId":"s","events":[{"id":"a","pubkey":"0","content":"","created_at":0,"kind":1,"tags":[],"sig":"0"},{"id":"b","pubkey":"0","content":"","created_at":0,"kind":1,"tags":[],"sig":"0"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(parse_accept(&resp), vec!["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_throttle_disables_passthrough() {
|
||||
// A configured throttle means strfry must keep sending `req` batches so
|
||||
// the connId counter can shrink delivery — so NOT passthrough.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 10
|
||||
"#,
|
||||
);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_throttle_caps_delivery_per_connection() {
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 3
|
||||
"#,
|
||||
);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":7,"subId":"s"}"#);
|
||||
|
||||
// Two batches of 2 events; only the first 3 (across batches) deliver.
|
||||
let first = engine.filter_batch(7, "s", &events(&["a", "b"]));
|
||||
assert_eq!(first, vec!["a", "b"]);
|
||||
|
||||
let second = engine.filter_batch(7, "s", &events(&["c", "d"]));
|
||||
assert_eq!(second, vec!["c"]); // 3rd delivered, 4th withheld by cap
|
||||
|
||||
let third = engine.filter_batch(7, "s", &events(&["e"]));
|
||||
assert!(third.is_empty()); // cap already reached
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conn_close_frees_state_and_lifecycle_is_silent() {
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 1
|
||||
"#,
|
||||
);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
|
||||
// Deliver the one allowed event, then the cap is hit.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
assert!(engine.filter_batch(1, "s", &events(&["b"])).is_empty());
|
||||
|
||||
// Lifecycle messages produce no response.
|
||||
assert!(engine
|
||||
.handle(r#"{"type":"reqClose","connId":1,"subId":"s"}"#)
|
||||
.is_none());
|
||||
assert!(engine
|
||||
.handle(r#"{"type":"connClose","connId":1}"#)
|
||||
.is_none());
|
||||
assert!(!engine.conn_info.contains_key(&1));
|
||||
|
||||
// After connClose the per-conn counter is freed: reopening the same
|
||||
// connId delivers again.
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["c"])), vec!["c"]);
|
||||
}
|
||||
|
||||
/// A test-only filter that withholds (`Skip`) any event whose id starts with
|
||||
/// `x`, and otherwise delivers. Used to exercise cross-filter composition
|
||||
/// (an earlier stateful filter must not charge an event a later filter
|
||||
/// withholds).
|
||||
#[derive(Default)]
|
||||
struct SkipX;
|
||||
impl ReadFilter for SkipX {
|
||||
fn name(&self) -> &'static str {
|
||||
"skip_x"
|
||||
}
|
||||
fn req_open(
|
||||
&mut self,
|
||||
_ctx: &ConnContext,
|
||||
_filter: Option<&serde_json::Value>,
|
||||
) -> OpenDecision {
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
fn filter_event(&mut self, _ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
if ev.id().unwrap().starts_with('x') {
|
||||
EventVerdict::Skip
|
||||
} else {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadPolicy {
|
||||
/// Build an engine from pre-constructed filters (test-only, so a pipeline
|
||||
/// can include a filter that isn't in the registry).
|
||||
fn from_pipeline(pipeline: Vec<Box<dyn ReadFilter>>) -> Self {
|
||||
ReadPolicy {
|
||||
registered_filters: HashMap::new(),
|
||||
pipeline,
|
||||
conn_info: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skip_does_not_charge_an_earlier_stateful_filter() {
|
||||
// The crux of the check/commit split. Pipeline [count(max=2), skip_x].
|
||||
// count's counter must advance only for events delivered by the WHOLE
|
||||
// pipeline — a skipped event must NOT consume the count budget.
|
||||
let mut engine = ReadPolicy::from_pipeline(vec![
|
||||
Box::new(MaxEventsPerConn {
|
||||
max: 2,
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(SkipX),
|
||||
]);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#);
|
||||
|
||||
// "x0" is skipped and must not charge count; then a, b deliver (using the
|
||||
// whole cap of 2); c is stopped by the cap. If count had charged the
|
||||
// skipped "x0", only "a" would survive.
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["x0", "a", "b", "c"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user