Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/grpc-web-telemetry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
default: minor
---

# zingod-grpc: gRPC-web traffic by protocol and origin

`zingod_grpc_requests_total` gains a `protocol` label (`grpc`, `grpc_web`). Once a minute, an
`Origin requests` log line names each of the 10 busiest browser origins with its request count
and verdict; one with `origin="(other)"` sums the rest.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion book/src/operators/dos-protection.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ server. Policies take effect within a second and survive restarts; the most spec
| `zingod origin reset <domain>` | remove its policy |
| `zingod origin` | list the policies |

An allowed origin still gets the same limits as everyone else.
An allowed origin still gets the same limits as everyone else. Once a minute, an `Origin requests`
log line names the 10 busiest origins; `origin="(other)"` sums the rest.

## Overload

Expand Down
1 change: 1 addition & 0 deletions packages/zingod-grpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ zingod-header-chain = { workspace = true, features = ["testing"] }
zingod-nfs = { workspace = true, features = ["testing"] }
zingod-grpc-snapshot = { workspace = true, features = ["testing"] }
h2 = "0.4"
metrics-util = { version = "0.20", default-features = false, features = ["debugging"] }

[lints.rust]
unreachable_pub = "warn"
31 changes: 30 additions & 1 deletion packages/zingod-grpc/src/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,31 @@ impl<Inner> Guard<Inner> {
}
}

/// Wire protocol a request arrived in (request extension; absent = native gRPC)
#[derive(Clone, Copy, Debug)]
pub(crate) enum Protocol {
Grpc,
GrpcWeb,
}

impl Protocol {
pub(crate) const fn label(self) -> &'static str {
match self {
Self::Grpc => "grpc",
Self::GrpcWeb => "grpc_web",
}
}

/// Tags a gRPC-web request (before `tonic_web` rewrites its content-type to native gRPC)
pub(crate) fn tag<B>(mut request: Request<B>) -> Request<B> {
let content_type = request.headers().get(http::header::CONTENT_TYPE);
if content_type.is_some_and(|value| value.as_bytes().starts_with(b"application/grpc-web")) {
request.extensions_mut().insert(Self::GrpcWeb);
}
request
}
}

/// Request `Origin` → host (scheme / port stripped, lowercased); absent = native client (default)
fn origin_host(headers: &HeaderMap) -> Option<String> {
let origin = headers.get(http::header::ORIGIN)?.to_str().ok()?;
Expand Down Expand Up @@ -94,6 +119,7 @@ where
let method = Method::of_request(&request);
let mut close = CloseOut {
method,
protocol: request.extensions().get().copied().unwrap_or(Protocol::Grpc),
started: Instant::now(),
answered: false,
sent: 0,
Expand All @@ -108,6 +134,7 @@ where
Some(host) => {
let verdict = self.gate.verdict(&host);
metrics::origin_request(verdict);
summary::origin(&host, verdict);
verdict
}
None => OriginVerdict::Default,
Expand Down Expand Up @@ -178,6 +205,7 @@ pub(crate) struct Guarded<B> {
#[derive(Debug)]
struct CloseOut {
method: Option<Method>,
protocol: Protocol,
started: Instant,
answered: bool,
sent: u64,
Expand Down Expand Up @@ -247,7 +275,8 @@ impl Drop for CloseOut {
true => Code::Ok,
false => Code::Cancelled,
});
metrics::stream_finished(self.method, code, self.started.elapsed(), self.sent);
let elapsed = self.started.elapsed();
metrics::stream_finished(self.method, self.protocol, code, elapsed, self.sent);
summary::finished(self.method, code, self.message.as_deref().unwrap_or_default());
}
}
Expand Down
27 changes: 15 additions & 12 deletions packages/zingod-grpc/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use tonic::Code;
use zingod_primitives::metric::Metric;

use crate::admission::Refusal;
use crate::guard::Protocol;
use crate::lifetime::RetireReason;
use crate::origin::OriginVerdict;
use crate::service::{Method, Reply};
Expand Down Expand Up @@ -77,7 +78,10 @@ fn reply(method: Option<Method>) -> Reply {
}

pub const METRICS: &[Metric] = &[
Metric::counter(REQUESTS_TOTAL, "Finished requests, by method and gRPC status code"),
Metric::counter(
REQUESTS_TOTAL,
"Finished requests, by method, gRPC status code and protocol (grpc, grpc_web)",
),
Metric::histogram(
DURATION_SECONDS,
"One-reply RPC latency: admission through trailers, OK answers only, by method",
Expand Down Expand Up @@ -241,17 +245,9 @@ pub(crate) fn stream_rejected(refusal: Refusal) {
metrics::counter!(ADMISSION_REJECTED_TOTAL, "reason" => refusal.label()).increment(1);
}

fn verdict_label(verdict: OriginVerdict) -> &'static str {
match verdict {
OriginVerdict::Blocked => "blocked",
OriginVerdict::Allowed => "allowed",
OriginVerdict::Default => "default",
}
}

/// One `Origin`-bearing (gRPC-web) request, by gate verdict (native requests never counted here)
pub(crate) fn origin_request(verdict: OriginVerdict) {
metrics::counter!(ORIGIN_REQUESTS_TOTAL, "verdict" => verdict_label(verdict)).increment(1);
metrics::counter!(ORIGIN_REQUESTS_TOTAL, "verdict" => verdict.label()).increment(1);
}

/// One overload window: wallets hurt by cause, over `open` connections (the latch = readiness)
Expand All @@ -269,9 +265,16 @@ pub(crate) fn first_message(method: Option<Method>, elapsed: Duration) {
}

/// One stream's close-out (recorded where the body drops)
pub(crate) fn stream_finished(method: Option<Method>, code: Code, elapsed: Duration, sent: u64) {
pub(crate) fn stream_finished(
method: Option<Method>,
protocol: Protocol,
code: Code,
elapsed: Duration,
sent: u64,
) {
let name = method_label(method);
metrics::counter!(REQUESTS_TOTAL, "method" => name, "code" => code_label(code)).increment(1);
let labels = [("method", name), ("code", code_label(code)), ("protocol", protocol.label())];
metrics::counter!(REQUESTS_TOTAL, &labels).increment(1);
// answers only (refusal = µs of no work)
if reply(method) == Reply::One && code == Code::Ok {
metrics::histogram!(DURATION_SECONDS, "method" => name).record(elapsed);
Expand Down
10 changes: 10 additions & 0 deletions packages/zingod-grpc/src/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ pub enum OriginVerdict {
Blocked,
}

impl OriginVerdict {
pub(crate) const fn label(self) -> &'static str {
match self {
Self::Default => "default",
Self::Allowed => "allowed",
Self::Blocked => "blocked",
}
}
}

/// Blocked + allowed FQDN keys, disjoint (one marker per domain)
#[derive(Debug, Default, PartialEq, Eq)]
struct OriginSets {
Expand Down
67 changes: 67 additions & 0 deletions packages/zingod-grpc/src/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@
//!
//! - WARN once any request was refused or failed or a connection evicted, else INFO; silent idle
//! - first server fault of a window logged as it happens (ERROR `Request failed`), the rest counted
//! - then one `Origin requests` line per top origin (gRPC-web, `Origin`-bearing), the rest pooled

use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;

use tonic::Code;
use tracing::{error, info, warn};

use crate::metrics::{code_label, method_label};
use crate::origin::OriginVerdict;
use crate::service::Method;

pub(crate) const INTERVAL: Duration = Duration::from_secs(60);

/// Per window: origins logged by name, hosts tallied by name (`Origin` = client-set), longest host
const TOP_ORIGINS: usize = 10;
const MAX_ORIGINS: usize = 1024;
const MAX_HOST: usize = 253;

static ORIGINS: Mutex<Origins> = Mutex::new(Origins { hosts: BTreeMap::new(), pooled: 0 });

static REQUESTS: AtomicU64 = AtomicU64::new(0);
static REFUSED: AtomicU64 = AtomicU64::new(0);
static FAILED: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -45,6 +56,45 @@ pub(crate) fn evicted() {
EVICTED.fetch_add(1, Ordering::Relaxed);
}

/// One `Origin`-bearing request, under its host (verdict = the latest it got)
pub(crate) fn origin(host: &str, verdict: OriginVerdict) {
ORIGINS.lock().expect("origins mutex poisoned").count(host, verdict);
}

/// One window's origins: host → (requests, latest verdict); `pooled` = requests past the bounds
#[derive(Debug, Default)]
struct Origins {
hosts: BTreeMap<String, (u64, OriginVerdict)>,
pooled: u64,
}

impl Origins {
fn count(&mut self, host: &str, verdict: OriginVerdict) {
let full = self.hosts.len() >= MAX_ORIGINS || host.len() > MAX_HOST;
match self.hosts.get_mut(host) {
Some(seen) => *seen = (seen.0 + 1, verdict),
None if full => self.pooled += 1,
None => _ = self.hosts.insert(host.to_owned(), (1, verdict)),
}
}
}

/// The window's [`TOP_ORIGINS`] busiest by name, the rest as `(other)`
fn log_origins() {
let Origins { hosts, mut pooled } = std::mem::take(&mut *ORIGINS.lock().expect("origins"));
let mut hosts: Vec<_> = hosts.into_iter().collect();
hosts.sort_by_key(|(_, (requests, _))| std::cmp::Reverse(*requests));
for (rank, (origin, (requests, verdict))) in hosts.into_iter().enumerate() {
match rank < TOP_ORIGINS {
true => info!(origin, requests, verdict = verdict.label(), "Origin requests"),
false => pooled += requests,
}
}
if pooled > 0 {
info!(origin = "(other)", requests = pooled, "Origin requests");
}
}

/// (requests, refused, failed, evicted) since the last call, zeroed
fn take() -> (u64, u64, u64, u64) {
let take = |counter: &AtomicU64| counter.swap(0, Ordering::Relaxed);
Expand All @@ -65,6 +115,7 @@ pub(crate) fn summarise(elapsed: Duration, connections: usize) {
0 => info!(rps, conns = connections, "Serving"),
_ => warn!(rps, conns = connections, refused, failed, evicted, "Serving"),
}
log_origins();
}

#[cfg(test)]
Expand All @@ -84,4 +135,20 @@ mod tests {
assert_eq!(take(), (5, 1, 1, 1), "(requests, refused, failed, evicted)");
assert_eq!(take(), (0, 0, 0, 0), "taken = zeroed");
}

/// 1030 sites + an oversized host: 1024 held by name (counting on, latest verdict), the rest
/// pooled
#[test]
fn origins_hold_1024_hosts_by_name_and_pool_the_rest() {
let mut origins = Origins::default();
for site in 0..1030 {
origins.count(&format!("site{site}.example"), OriginVerdict::Default);
}
origins.count("site0.example", OriginVerdict::Blocked);
origins.count(&"a".repeat(254), OriginVerdict::Default);

assert_eq!(origins.hosts.len(), MAX_ORIGINS, "held by name up to the bound");
assert_eq!(origins.hosts["site0.example"], (2, OriginVerdict::Blocked), "held counts on");
assert_eq!(origins.pooled, 6 + 1, "6 sites past the bound + the oversized host");
}
}
47 changes: 41 additions & 6 deletions packages/zingod-grpc/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use zingod_source::ChainDataSource;

use crate::admission::AdmissionState;
use crate::connections::{ConnectionCaps, Reserved};
use crate::guard::Guard;
use crate::guard::{Guard, Protocol};
use crate::health::{Health, HealthRoute};
use crate::lifetime::{Activity, Retire, RetireReason, Retirement};
use crate::overload;
Expand Down Expand Up @@ -488,8 +488,9 @@ impl<S: ChainDataSource, V: PinnedView> Shared<S, V> {
activity.clone(),
Arc::clone(&self.origin_gate),
);
// CORS outermost (answers browser preflight), then gRPC-web framing, native gRPC through
let gated = cors(self.grpc_web).layer(tonic_web::GrpcWebLayer::new().layer(guard));
// CORS outermost (answers browser preflight), protocol tagged, gRPC-web framing, guard
let web = tonic_web::GrpcWebLayer::new().layer(guard);
let gated = cors(self.grpc_web).layer(tower::util::MapRequest::new(web, Protocol::tag));
let service =
TowerToHyperService::new(HealthRoute::new(gated, self.health.clone(), self.grpc_web));
let serving = self.http.serve_connection(TokioIo::new(io), service);
Expand Down Expand Up @@ -1076,10 +1077,13 @@ mod tests {
String::from_utf8_lossy(&response).to_ascii_lowercase()
}

/// gRPC-web on: a browser preflight gets a permissive CORS grant, and native gRPC over the
/// same listener is untouched by the layer
/// gRPC-web on: a browser preflight gets a permissive CORS grant, a browser call and a native
/// one both reach the service, and each is counted under its own `protocol`
#[tokio::test]
async fn grpc_web_answers_a_preflight_and_still_serves_native_grpc() {
async fn grpc_web_answers_a_preflight_and_serves_both_protocols_counted_apart() {
let recorder = metrics_util::debugging::DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let _recording = metrics::set_default_local_recorder(&recorder);
let server = GrpcService::new(ANY_PORT, GrpcLimits::default(), CAPACITY)
.expect("read threads start")
.with_grpc_web(true)
Expand All @@ -1105,8 +1109,39 @@ mod tests {
"native gRPC decodes over h2, unaffected by the CORS / gRPC-web layer",
);

let browser = "POST /cash.z.wallet.sdk.rpc.CompactTxStreamer/GetLightdInfo HTTP/1.1\r\n\
Host: zec.global\r\n\
Origin: https://wallet.example\r\n\
Content-Type: application/grpc-web+proto\r\n\
X-Grpc-Web: 1\r\n\
Content-Length: 5\r\n\
Connection: close\r\n\r\n\0\0\0\0\0";
let mut stream = tokio::net::TcpStream::connect(bind).await.expect("connects");
stream.write_all(browser.as_bytes()).await.expect("writes the call");
let mut response = Vec::new();
tokio::time::timeout(SCHEDULING, stream.read_to_end(&mut response))
.await
.expect("server answered and closed")
.expect("read");
let response = String::from_utf8_lossy(&response).to_ascii_lowercase();
assert!(response.contains("grpc-status: 14"), "gRPC-web answered UNAVAILABLE:\n{response}");

cancel.cancel();
serving.await.expect("the serve task ran");
// method, code, protocol → value
let mut counted: Vec<String> = (snapshotter.snapshot().into_vec().into_iter())
.filter(|(key, ..)| key.key().name() == "zingod.grpc.requests_total")
.map(|(key, .., value)| {
let labels: Vec<_> = key.key().labels().map(|label| label.value()).collect();
format!("{} {value:?}", labels.join(" "))
})
.collect();
counted.sort();
let want = [
"GetLightdInfo Unavailable grpc Counter(1)",
"GetLightdInfo Unavailable grpc_web Counter(1)",
];
assert_eq!(counted, want, "one request each, counted by its wire protocol");
}

/// gRPC-web off (the default): the same preflight gets no CORS grant, so a browser is refused
Expand Down
Loading