readpolicy: read-bandwidth-per-minute throttle (per-IP byte bucket)
Add a read-side analogue of the write-side `ratelimit` filter: meter the bytes of events delivered per minute, keyed per client IP so a client cannot reconnect (new connId) to reset its budget. Byte size comes from UnparsedNote::size() — the exact streamed wire length, no re-serialization and no Note parse, so this filter never deserializes an event. filter_batch charges each delivered event's size against an Instant token bucket keyed by IP (same refill shape as ratelimit.rs), withholding the rest of a batch once the budget is spent. Because the charge lands in on_delivered, an event a later filter withholds spends no budget. The byte buckets are never evicted on connClose — surviving reconnect is the point. Whitelist status and the bucket key are resolved once per connection at reqOpen (a connection's IP, authed pubkey and whitelist status are fixed for its life), so the per-event path is a single connId lookup with no allocation and no whitelist rescan, and an old strfry that sends no `ip` warns once per connection rather than per event. A bandwidth-limited sub is excluded from the passthrough fast path so strfry keeps sending `req` to meter; a whitelisted one is passthrough, since it does no per-event work. Config: [readpolicy.filters.read_bandwidth] bytes_per_minute (per IP) and whitelist (an entry matches the conn's IP or authed pubkey). E2E-verified against a rebuilt strfry carrying the reqOpen `ip` field: below budget delivers all, the byte cap withholds the rest, and with a single reqWorker thread the per-IP budget survives a reconnect. Note: strfry runs one plugin process per read-serving thread, so the budget is scoped per-process (effective limit up to numThreads x configured) — same per-thread scoping as the write-side ratelimit; documented in the README. Changelog-Added: Read-bandwidth-per-minute throttle for the readPolicy plugin, metering bytes of delivered events per client IP. Headway: headway:noteguard/muffin-column-enough Agentium: agentium:coast-awesome-relax
This commit is contained in:
@@ -201,11 +201,24 @@ 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"]
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth"]
|
||||
|
||||
# connection-level throttle: max events delivered per connection.
|
||||
[readpolicy.filters.max_events_per_conn]
|
||||
max = 5000
|
||||
|
||||
# read-bandwidth throttle: max BYTES of events delivered per minute, keyed per
|
||||
# client IP. Reconnecting with a fresh connId from the same IP does NOT reset the
|
||||
# budget — the read-side analogue of the write-side `ratelimit` filter, metering
|
||||
# the exact wire size of each delivered event via an Instant token bucket
|
||||
# (tokens = bytes). Once an IP's per-minute byte budget is spent, further events
|
||||
# in the batch are withheld.
|
||||
[readpolicy.filters.read_bandwidth]
|
||||
bytes_per_minute = 5000000
|
||||
# exempt entries: an entry matches a connection's client IP OR its authed pubkey
|
||||
# hex (optional). A whitelisted connection is never metered and takes the
|
||||
# passthrough fast path.
|
||||
whitelist = ["127.0.0.1", "0000…0000"]
|
||||
```
|
||||
|
||||
Each filter is a [`ReadFilter`](src/read_filter.rs) — a lifecycle-aware,
|
||||
@@ -223,10 +236,30 @@ 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.
|
||||
passthrough; a configured throttle keeps the subscription non-passthrough
|
||||
(strfry must keep sending events for the counter/byte-meter to bound delivery);
|
||||
and a bandwidth-whitelisted connection is passthrough (it is never metered).
|
||||
Emitting the field is forward-compatible: a strfry without passthrough support
|
||||
simply ignores it.
|
||||
|
||||
**Per-IP bandwidth keying needs the client IP:** `read_bandwidth` meters per
|
||||
client IP so a reconnect can't reset the budget. `req` batches carry
|
||||
no IP, so noteguard caches the IP from the `reqOpen` message (added by newer
|
||||
strfry builds, alongside `connId`/`authed`) under its `connId`. Against an older
|
||||
strfry that doesn't send `ip`, metering degrades gracefully to per-connection
|
||||
(logged once per connection as a warning) — a reconnect then gets a fresh budget.
|
||||
|
||||
**Per-thread scoping (important):** strfry runs *one plugin process per
|
||||
read-serving thread* (`relay.numThreads.reqWorker` / `reqMonitor`), each with its
|
||||
own in-memory byte buckets. A given connection is served by one thread, so the
|
||||
per-IP budget only survives a reconnect that lands on the *same* thread; the
|
||||
effective per-IP budget is therefore up to `numThreads ×
|
||||
read_bandwidth.bytes_per_minute`. This is the same per-process scoping the write-side
|
||||
`ratelimit` filter has (its buckets live in the per-ingester-thread process).
|
||||
For exact per-IP enforcement, set `relay.numThreads.reqWorker = 1` and
|
||||
`relay.numThreads.reqMonitor = 1`; otherwise treat the limit as approximate.
|
||||
(True cross-thread enforcement would require sharing bucket state across plugin
|
||||
processes, which this phase does not do.)
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
+7
-8
@@ -11,19 +11,18 @@
|
||||
//! [`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
|
||||
//! state (a per-IP byte bucket, a per-conn 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
|
||||
//! *every* filter delivered the event, so counters/buckets 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.
|
||||
//! hook a [`ConnContext`].
|
||||
//!
|
||||
//! **Fail-open** is a per-filter contract: a filter that errors or whose guest
|
||||
//! traps must return [`EventVerdict::Deliver`] rather than withhold a
|
||||
@@ -64,7 +63,7 @@ pub enum EventVerdict {
|
||||
/// guest reject).
|
||||
Skip,
|
||||
/// Withhold this event and every subsequent event in the batch (e.g. a
|
||||
/// delivery budget just ran out).
|
||||
/// count/bandwidth budget just ran out).
|
||||
Stop,
|
||||
}
|
||||
|
||||
@@ -88,7 +87,7 @@ pub enum Admission {
|
||||
/// 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).
|
||||
/// connection is bandwidth-whitelisted).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OpenDecision {
|
||||
pub admission: Admission,
|
||||
@@ -150,8 +149,8 @@ pub trait ReadFilter {
|
||||
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
|
||||
/// 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) {}
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// An `Instant` token bucket of *bytes*, keyed per client IP. Mirrors the
|
||||
/// write-side `ratelimit.rs` mechanism (there tokens are posts; here they are
|
||||
/// bytes). Refills at `bytes_per_minute` bytes per minute up to that capacity,
|
||||
/// and — like `ratelimit.rs`'s `sources` map — is **never evicted**: surviving a
|
||||
/// reconnect is the entire point of keying on IP.
|
||||
struct ByteBucket {
|
||||
/// Bytes of budget currently available. Starts full (capacity).
|
||||
tokens: f64,
|
||||
/// When `tokens` was last refilled.
|
||||
last_refill: Instant,
|
||||
}
|
||||
|
||||
/// Read-bandwidth throttle: cap the *bytes* of events delivered per minute,
|
||||
/// keyed per client IP so reconnecting with a fresh `connId` from the same IP
|
||||
/// does not reset the budget. The read-side analogue of the write-side
|
||||
/// `ratelimit` filter, metering the exact wire byte size of each delivered event
|
||||
/// via a per-IP byte bucket.
|
||||
///
|
||||
/// Once an IP's bucket can't cover the next event, the rest of the batch is
|
||||
/// withheld ([`EventVerdict::Stop`]). A whitelisted connection is exempt
|
||||
/// entirely — and, since it then does no per-event work, is reported as
|
||||
/// passthrough at `reqOpen`.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct ReadBandwidth {
|
||||
/// Max bytes of events delivered per minute, per IP (bucket capacity).
|
||||
pub bytes_per_minute: u64,
|
||||
|
||||
/// Entries exempt from the throttle: an entry matches a connection's client
|
||||
/// IP **or** its authed pubkey hex.
|
||||
#[serde(default)]
|
||||
pub whitelist: Vec<String>,
|
||||
|
||||
/// Client IP (or `conn:<id>` fallback) -> its byte bucket. Never evicted, so
|
||||
/// a reconnect from the same IP shares the same budget.
|
||||
#[serde(skip)]
|
||||
buckets: HashMap<String, ByteBucket>,
|
||||
|
||||
/// `connId` -> the bucket key to charge, resolved once at `reqOpen` (a
|
||||
/// connection's IP, whitelist status and authed pubkey are fixed for its
|
||||
/// life). `None` means exempt — whitelisted, so never metered. Freed at
|
||||
/// `connClose`; the buckets themselves are not.
|
||||
#[serde(skip)]
|
||||
conn_keys: HashMap<u64, Option<String>>,
|
||||
}
|
||||
|
||||
impl ReadBandwidth {
|
||||
/// Whether this connection is exempt: a whitelist entry matching its client
|
||||
/// IP or authed pubkey.
|
||||
fn whitelisted(&self, ctx: &ConnContext) -> bool {
|
||||
if self.whitelist.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let hit = |v: Option<&str>| v.is_some_and(|v| self.whitelist.iter().any(|e| e == v));
|
||||
hit(ctx.ip) || hit(ctx.authed)
|
||||
}
|
||||
|
||||
/// The bucket key to charge this connection against: `None` if it is
|
||||
/// whitelisted, else its client IP, or a per-connection fallback when strfry
|
||||
/// sent no IP (old strfry — metering then degrades to per-connection and
|
||||
/// resets on reconnect).
|
||||
fn resolve_key(&self, ctx: &ConnContext) -> Option<String> {
|
||||
if self.whitelisted(ctx) {
|
||||
return None;
|
||||
}
|
||||
Some(match ctx.ip {
|
||||
Some(ip) => ip.to_string(),
|
||||
None => {
|
||||
log::warn!(
|
||||
"readpolicy: no client IP for conn={} (old strfry?); metering \
|
||||
bandwidth per-connection (resets on reconnect)",
|
||||
ctx.conn_id
|
||||
);
|
||||
format!("conn:{}", ctx.conn_id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadFilter for ReadBandwidth {
|
||||
fn name(&self) -> &'static str {
|
||||
"read_bandwidth"
|
||||
}
|
||||
|
||||
fn req_open(&mut self, ctx: &ConnContext, _filter: Option<&serde_json::Value>) -> OpenDecision {
|
||||
// Resolve identity once per connection, so the per-event path is a
|
||||
// single `connId` lookup with no allocation, no whitelist rescan, and
|
||||
// (against an old strfry) one missing-IP warning rather than a flood.
|
||||
let key = self.resolve_key(ctx);
|
||||
if let Some(key) = &key {
|
||||
// Create the bucket full on first sight of this IP — but never
|
||||
// reset an existing one, which must survive a reconnect.
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
self.buckets.entry(key.clone()).or_insert(ByteBucket {
|
||||
tokens: cap,
|
||||
last_refill: Instant::now(),
|
||||
});
|
||||
}
|
||||
let exempt = key.is_none();
|
||||
self.conn_keys.insert(ctx.conn_id, key);
|
||||
|
||||
// A whitelisted connection is never metered, so it does no per-event
|
||||
// work and can take the passthrough fast path. Everyone else needs `req`
|
||||
// batches so we can meter bytes.
|
||||
if exempt {
|
||||
OpenDecision::passthrough()
|
||||
} else {
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
// Check only: refill and test affordability, but DON'T spend — the
|
||||
// event isn't delivered until every later filter also delivers, so the
|
||||
// byte is charged in `on_delivered`.
|
||||
//
|
||||
// A missing entry means whitelisted, or a `req` for a subscription we
|
||||
// never saw open: deliver either way (fail open).
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
let Self {
|
||||
buckets, conn_keys, ..
|
||||
} = self;
|
||||
let Some(Some(key)) = conn_keys.get(&ctx.conn_id) else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
let Some(bucket) = buckets.get_mut(key) else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
|
||||
// Refill: elapsed/60 of a full minute's worth of bytes, clamped to a
|
||||
// minute and capped at capacity (same shape as ratelimit.rs).
|
||||
let now = Instant::now();
|
||||
let mut elapsed = now.duration_since(bucket.last_refill);
|
||||
let min = Duration::from_secs(60);
|
||||
if elapsed > min {
|
||||
elapsed = min;
|
||||
}
|
||||
let refill = (elapsed.as_secs_f64() / 60.0) * cap;
|
||||
bucket.tokens = (bucket.tokens + refill).min(cap);
|
||||
bucket.last_refill = now;
|
||||
|
||||
if bucket.tokens < ev.size() as f64 {
|
||||
EventVerdict::Stop
|
||||
} else {
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
|
||||
fn on_delivered(&mut self, ctx: &ConnContext, ev: &UnparsedNote) {
|
||||
// The bucket was resolved (and refilled) in `filter_event` for this same
|
||||
// event, so it exists; charge the delivered event's exact wire size.
|
||||
let Self {
|
||||
buckets, conn_keys, ..
|
||||
} = self;
|
||||
if let Some(Some(key)) = conn_keys.get(&ctx.conn_id) {
|
||||
if let Some(bucket) = buckets.get_mut(key) {
|
||||
bucket.tokens -= ev.size() as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
// Only the resolved key is per-connection. NB: no bucket eviction —
|
||||
// buckets are keyed by IP and must survive a reconnect, else the per-IP
|
||||
// budget resets.
|
||||
self.conn_keys.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
//! `[readpolicy].pipeline` config. The read-side counterpart to
|
||||
//! [`crate::filters`].
|
||||
|
||||
mod bandwidth;
|
||||
mod max_events;
|
||||
|
||||
pub use bandwidth::ReadBandwidth;
|
||||
pub use max_events::MaxEventsPerConn;
|
||||
|
||||
+4
-4
@@ -22,7 +22,7 @@ use serde_json::Value;
|
||||
/// 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
|
||||
/// the paths that actually need field access. The bandwidth-only metering path
|
||||
/// never parses a `Note` at all; it only ever calls `size()` and, for the
|
||||
/// accept-list, the cheap id-only [`id`](Self::id).
|
||||
///
|
||||
@@ -35,8 +35,8 @@ use serde_json::Value;
|
||||
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.
|
||||
/// Exact byte length of the event object as strfry streamed it (the token
|
||||
/// cost charged by the bandwidth throttle). No re-serialization.
|
||||
pub fn size(&self) -> usize {
|
||||
self.0.get().len()
|
||||
}
|
||||
@@ -48,7 +48,7 @@ impl UnparsedNote {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// [`Note`] parse on the bandwidth-only path.
|
||||
pub fn id(&self) -> serde_json::Result<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct IdOnly {
|
||||
|
||||
+124
-3
@@ -11,7 +11,7 @@
|
||||
//! ## 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
|
||||
//! cross-event state (a per-IP byte bucket, a per-conn 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:
|
||||
//!
|
||||
@@ -38,7 +38,7 @@
|
||||
//! 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::readfilters::{MaxEventsPerConn, ReadBandwidth};
|
||||
use crate::readmsg::{ReadInput, ReqOpenResponse, ReqResponse, UnparsedNote};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Deserialize;
|
||||
@@ -116,6 +116,7 @@ impl ReadPolicy {
|
||||
/// All built-in read filters, available on every new [`ReadPolicy`].
|
||||
fn register_builtin_filters(&mut self) {
|
||||
self.register_filter::<MaxEventsPerConn>();
|
||||
self.register_filter::<ReadBandwidth>();
|
||||
}
|
||||
|
||||
/// Compose the pipeline from config. Unlike the write side (which panics on a
|
||||
@@ -421,7 +422,7 @@ mod tests {
|
||||
engine
|
||||
}
|
||||
|
||||
/// An [`UnparsedNote`] built from real wire JSON.
|
||||
/// An [`UnparsedNote`] built from wire JSON so `size()` is realistic.
|
||||
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"}}"#,
|
||||
@@ -533,6 +534,99 @@ mod tests {
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["c"])), vec!["c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_disables_passthrough() {
|
||||
// A bandwidth budget means strfry must keep sending `req` so we can meter
|
||||
// bytes — so NOT passthrough, even with no guest and no count cap.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = 1000
|
||||
"#,
|
||||
);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_caps_delivery_by_bytes() {
|
||||
// Budget for exactly two events' worth of bytes (single-char ids => all
|
||||
// events are the same wire size). Refill over the sub-ms test window
|
||||
// floors to ~0, so the byte cap is deterministic.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
"#,
|
||||
size * 2 + 1
|
||||
));
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"9.9.9.9"}"#);
|
||||
|
||||
// First two fit the budget; the rest are withheld once bytes run out.
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c", "d"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_keyed_per_ip_survives_reconnect() {
|
||||
// Budget for exactly one event.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
"#,
|
||||
size + 1
|
||||
));
|
||||
|
||||
// connId=1 from ip X spends the whole budget on its first event.
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#);
|
||||
let first = engine.filter_batch(1, "s", &events(&["a", "b"]));
|
||||
assert_eq!(first, vec!["a"]); // 2nd withheld; bucket now ~empty
|
||||
|
||||
// Reconnect: brand-new connId, SAME ip. Because the bucket is keyed by IP
|
||||
// (and not evicted on connClose), the budget is still empty.
|
||||
engine.handle(r#"{"type":"connClose","connId":1}"#);
|
||||
engine.handle(r#"{"type":"reqOpen","reqId":0,"connId":2,"subId":"s","ip":"1.2.3.4"}"#);
|
||||
let second = engine.filter_batch(2, "s", &events(&["c"]));
|
||||
assert!(second.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_whitelist_exempts_and_passes_through() {
|
||||
// Whitelisted IP: the bandwidth gate is skipped entirely, so delivery
|
||||
// continues past a budget that would otherwise cap it — and, doing no
|
||||
// per-event work, the subscription is reported passthrough.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["read_bandwidth"]
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
whitelist = ["5.5.5.5"]
|
||||
"#,
|
||||
size
|
||||
));
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"5.5.5.5"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept","passthrough":true}"#);
|
||||
|
||||
// And even if strfry sends `req`, all events deliver (no metering).
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c"])),
|
||||
vec!["a", "b", "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
|
||||
@@ -593,4 +687,31 @@ mod tests {
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_and_bandwidth_compose() {
|
||||
// count cap 5, bandwidth budget for 2 events, pipeline [count, bandwidth]:
|
||||
// bandwidth is the binding constraint here and caps the batch at 2.
|
||||
let size = unparsed_note("a", 1, "").size() as u64;
|
||||
let mut engine = engine(&format!(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 5
|
||||
[filters.read_bandwidth]
|
||||
bytes_per_minute = {}
|
||||
"#,
|
||||
size * 2 + 1
|
||||
));
|
||||
// Both throttles need events, so the sub is non-passthrough.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"7.7.7.7"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
|
||||
assert_eq!(
|
||||
engine.filter_batch(1, "s", &events(&["a", "b", "c"])),
|
||||
vec!["a", "b"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user