readpolicy: CLOSED + retryMs backpressure on drained read budgets
The read throttles (read_bandwidth, max_events_per_conn) admitted every subscription at reqOpen and silently withheld events on `req` once the budget was spent. A client just saw a short EOSE with no signal — and for a bounded `limit:N` query that is lossy: a silent partial delivery + EOSE is indistinguishable from "that's all N there were", so the client stops and never retries. Reject an over-budget IP/conn outright at reqOpen instead, so strfry emits a NIP-01 CLOSED with our message and a retry hint (real backpressure that preserves eventual completeness — the client knows to come back): - read_bandwidth: refill-then-peek the per-IP byte bucket at reqOpen; if it can't afford a nominal event (512 B, clamped to capacity so a fresh full bucket always passes), reject with retry_ms = time to refill one nominal event at bytes_per_minute. The next event's real size is unknown at open, so retry_ms is an estimate (documented on NOMINAL_EVENT_SIZE). The refill logic is extracted to ByteBucket::refill and shared with filter_event. - max_events_per_conn: if the connId is at its lifetime cap, reject with a message and NO retry_ms — the cap has no refill on the same connId, so a same-conn retry is futile; a reconnect gets a fresh connId (its own retry). The per-event withhold-rest-of-batch `Stop` is kept, re-scoped as overshoot protection only (bound one in-flight batch to <= budget) — without it a single limit:500 batch delivers the whole payload and the bucket goes deeply negative. reqOpen reject is the primary path (covers reconnect/churn/new- query abuse); a mid-stream drain or long-lived live sub still has only the silent-withhold lever (no admission hook on post-EOSE `req` batches). Verified E2E against strfry (reqWorker=1 reqMonitor=1): an IP that drained a 2000 B/min budget on its first REQ got, on the next fresh REQ, `CLOSED s2: ERROR: read bandwidth budget exhausted (2000 bytes/min per IP) (retry in 15360ms)`; a conn at a max=3 cap got `CLOSED s2: ERROR: per-connection event cap reached (3 events); reconnect for a fresh budget` (no retry hint). Unit tests cover reject-at-reqOpen for both filters plus the still-accept and whitelist-passthrough paths. Changelog-Added: CLOSED/retryMs backpressure for read throttles (read_bandwidth, max_events_per_conn) — an over-budget subscription is now rejected at reqOpen with a NIP-01 CLOSED + retry hint instead of a silent truncated feed Headway: headway:noteguard/bridge-live-frame Agentium: agentium:student-legend-hospital 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
d6c69fed9d
commit
6651dde5a4
@@ -16,6 +16,31 @@ struct ByteBucket {
|
||||
last_refill: Instant,
|
||||
}
|
||||
|
||||
impl ByteBucket {
|
||||
/// Refill toward `cap` by the elapsed fraction of a minute (same shape as
|
||||
/// `ratelimit.rs`), clamped to one minute's worth and capped at `cap`.
|
||||
fn refill(&mut self, cap: f64) {
|
||||
let now = Instant::now();
|
||||
let mut elapsed = now.duration_since(self.last_refill);
|
||||
let min = Duration::from_secs(60);
|
||||
if elapsed > min {
|
||||
elapsed = min;
|
||||
}
|
||||
let refill = (elapsed.as_secs_f64() / 60.0) * cap;
|
||||
self.tokens = (self.tokens + refill).min(cap);
|
||||
self.last_refill = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// Nominal event size (bytes) assumed at `reqOpen`, where the next event's real
|
||||
/// wire size is unknown. Used both to decide whether the IP's bucket can afford
|
||||
/// "roughly one event" (and so whether to reject the subscription outright) and
|
||||
/// to estimate the retry hint. A middling nostr event is a few hundred bytes;
|
||||
/// the real per-event charge on `req` still meters each event's exact size. The
|
||||
/// threshold is clamped to the bucket capacity below, so a fresh (full) bucket
|
||||
/// always affords it and only a drained IP trips the reject.
|
||||
const NOMINAL_EVENT_SIZE: u64 = 512;
|
||||
|
||||
/// 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
|
||||
@@ -92,18 +117,46 @@ impl ReadFilter for ReadBandwidth {
|
||||
// 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);
|
||||
let cap = self.bytes_per_minute as f64;
|
||||
|
||||
// Peek the IP's (refilled) bucket to decide admission before serving a
|
||||
// single event. An already-drained IP is rejected outright so the client
|
||||
// gets a NIP-01 CLOSED + retry hint (real backpressure) instead of a
|
||||
// silent empty/truncated feed — the reconnect/churn abuse case. While
|
||||
// there is still budget we admit and meter per-event on `req` as before.
|
||||
let mut reject_retry_ms: Option<u64> = None;
|
||||
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 {
|
||||
let bucket = self.buckets.entry(key.clone()).or_insert(ByteBucket {
|
||||
tokens: cap,
|
||||
last_refill: Instant::now(),
|
||||
});
|
||||
bucket.refill(cap);
|
||||
// Nominal event size clamped to capacity: a fresh (full) bucket
|
||||
// always affords it, so only a drained IP trips the reject.
|
||||
let nominal = (NOMINAL_EVENT_SIZE as f64).min(cap);
|
||||
if bucket.tokens < nominal {
|
||||
// retry_ms: time to refill one nominal event at
|
||||
// bytes_per_minute. An estimate — the next event's real size is
|
||||
// unknown at reqOpen (documented on NOMINAL_EVENT_SIZE).
|
||||
reject_retry_ms = Some(((nominal / cap) * 60_000.0).ceil() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
let exempt = key.is_none();
|
||||
self.conn_keys.insert(ctx.conn_id, key);
|
||||
|
||||
if let Some(retry_ms) = reject_retry_ms {
|
||||
return OpenDecision::reject(
|
||||
Some(format!(
|
||||
"read bandwidth budget exhausted ({} bytes/min per IP)",
|
||||
self.bytes_per_minute
|
||||
)),
|
||||
Some(retry_ms),
|
||||
);
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -132,17 +185,9 @@ impl ReadFilter for ReadBandwidth {
|
||||
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;
|
||||
// Refill (elapsed/60 of a minute's bytes, capped at capacity) then test
|
||||
// affordability. Same refill used at reqOpen to peek for backpressure.
|
||||
bucket.refill(cap);
|
||||
|
||||
if bucket.tokens < ev.size() as f64 {
|
||||
EventVerdict::Stop
|
||||
|
||||
@@ -29,11 +29,30 @@ impl ReadFilter for MaxEventsPerConn {
|
||||
|
||||
fn req_open(
|
||||
&mut self,
|
||||
_ctx: &ConnContext,
|
||||
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.
|
||||
// If this connection has already been delivered its lifetime cap, reject
|
||||
// the new subscription outright so the client gets a NIP-01 CLOSED
|
||||
// instead of an admitted sub that would silently deliver nothing.
|
||||
//
|
||||
// No retry_ms: the cap is a per-connId LIFETIME limit with no refill, so
|
||||
// retrying on the SAME connId is futile — a reconnect gets a fresh connId
|
||||
// (and a fresh counter), so the client's own reconnect *is* the retry. A
|
||||
// millisecond hint would be a lie here.
|
||||
let already = *self.delivered.get(&ctx.conn_id).unwrap_or(&0);
|
||||
if already >= self.max {
|
||||
return OpenDecision::reject(
|
||||
Some(format!(
|
||||
"per-connection event cap reached ({} events); reconnect for a fresh budget",
|
||||
self.max
|
||||
)),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
// Otherwise a configured cap always needs to see events, so strfry must
|
||||
// keep sending `req` batches for the counter to bound delivery.
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
|
||||
|
||||
@@ -634,6 +634,85 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bandwidth_rejects_at_open_when_drained() {
|
||||
// Budget for exactly one event. The first sub drains the IP's bucket; a
|
||||
// fresh REQ from the SAME IP is then rejected OUTRIGHT at reqOpen with a
|
||||
// CLOSED (msg + retryMs) — real backpressure — rather than a silent
|
||||
// empty feed. The not-yet-drained accept case is covered by
|
||||
// `bandwidth_disables_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 = {}
|
||||
"#,
|
||||
size + 1
|
||||
));
|
||||
|
||||
// Fresh IP: admitted (a full bucket affords the nominal event).
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["action"], "accept");
|
||||
|
||||
// Spend the whole budget on the one affordable event.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
|
||||
// Reconnect from the SAME IP (bucket keyed by IP, never evicted): now
|
||||
// drained, so reqOpen is rejected with a CLOSED + retry hint.
|
||||
engine.handle(r#"{"type":"connClose","connId":1}"#);
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":9,"connId":2,"subId":"s2","ip":"1.2.3.4"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["reqId"], 9);
|
||||
assert_eq!(v["action"], "reject");
|
||||
assert!(v["msg"].as_str().unwrap().contains("bandwidth"));
|
||||
assert!(v["retryMs"].as_u64().unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_rejects_at_open_when_cap_reached() {
|
||||
// Once a connection has been delivered its lifetime cap, a new sub on the
|
||||
// same connId is rejected at reqOpen (CLOSED, no retryMs — the cap has no
|
||||
// refill on this connId, so a same-connId retry is futile). The
|
||||
// not-yet-capped accept case is covered by
|
||||
// `count_throttle_disables_passthrough`.
|
||||
let mut engine = engine(
|
||||
r#"
|
||||
pipeline = ["max_events_per_conn"]
|
||||
[filters.max_events_per_conn]
|
||||
max = 1
|
||||
"#,
|
||||
);
|
||||
// Fresh conn: admitted.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":0,"connId":1,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":0,"action":"accept"}"#);
|
||||
|
||||
// Deliver the one allowed event to reach the cap.
|
||||
assert_eq!(engine.filter_batch(1, "s", &events(&["a"])), vec!["a"]);
|
||||
|
||||
// A new sub on the SAME connId is now rejected — message, NO retryMs.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":3,"connId":1,"subId":"s2"}"#)
|
||||
.unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&open).unwrap();
|
||||
assert_eq!(v["action"], "reject");
|
||||
assert!(v["msg"].as_str().unwrap().contains("cap reached"));
|
||||
assert!(v["retryMs"].is_null());
|
||||
|
||||
// A reconnect (fresh connId) resets the counter and is admitted again.
|
||||
let open = engine
|
||||
.handle(r#"{"type":"reqOpen","reqId":4,"connId":2,"subId":"s"}"#)
|
||||
.unwrap();
|
||||
assert_eq!(open, r#"{"reqId":4,"action":"accept"}"#);
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
Reference in New Issue
Block a user