From 9cf64270fdb95ad6305152291b87d73574478a9b Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 2 Nov 2026 16:34:53 +0100 Subject: [PATCH 1/2] refactor(telemetry): one SendTraced for auth and the SDK Moves SendTraced into piquel-common behind a client-spans feature, so the Rust SDK sends its requests through it instead of a copy of its span. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + apps/auth-service/src/lib.rs | 5 +- crates/auth-sdk/Cargo.toml | 6 +- crates/auth-sdk/src/http.rs | 69 ++++++------------- crates/auth-sdk/src/lib.rs | 2 +- crates/common/Cargo.toml | 4 ++ .../client.rs => common/src/client_span.rs} | 23 ++++--- crates/common/src/lib.rs | 6 ++ crates/telemetry/Cargo.toml | 2 +- crates/telemetry/src/lib.rs | 10 ++- docs/architecture/telemetry.md | 6 +- 11 files changed, 61 insertions(+), 74 deletions(-) rename crates/{telemetry/src/client.rs => common/src/client_span.rs} (61%) diff --git a/Cargo.lock b/Cargo.lock index 9f9fd32ed..7ee22bb71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2025,10 +2025,12 @@ dependencies = [ "chrono", "openssl", "piquel-crypto", + "reqwest", "serde", "serde_json", "sqlx", "thiserror 2.0.18", + "tracing", "unicode-normalization", "url", "uuid", diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index bc3f8d6af..9d6902a31 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -90,9 +90,8 @@ use thiserror::Error; /// The default `service.name` of exported telemetry. pub const SERVICE_NAME: &str = "auth-service"; /// What is traced, and logged unless `RUST_LOG` says otherwise: auth's own -/// operations, its database queries and committed events, and the SDK's requests, -/// such as Google's signing-key fetches. -pub const TELEMETRY_FILTER: &str = "auth_service=info,piquel_repository=info,piquel_auth=info"; +/// operations, and its database queries and committed events. +pub const TELEMETRY_FILTER: &str = "auth_service=info,piquel_repository=info"; /// Bound on browser ceremony and API JSON bodies. const MAX_REQUEST_BODY_BYTES: usize = 64 * 1024; diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml index b99926b24..397a690b6 100644 --- a/crates/auth-sdk/Cargo.toml +++ b/crates/auth-sdk/Cargo.toml @@ -8,12 +8,12 @@ repository.workspace = true [features] # Extractors, layers and login routes for axum. -axum = ["dep:axum", "dep:tower"] +axum = ["dep:axum", "dep:tower", "dep:tracing"] # `axum::check_backend`, to test an application's session backend. test-util = ["axum"] [dependencies] -piquel-common.workspace = true +piquel-common = { workspace = true, features = ["client-spans"] } axum = { workspace = true, optional = true } base64.workspace = true @@ -28,7 +28,7 @@ sha2.workspace = true thiserror.workspace = true tokio.workspace = true tower = { workspace = true, optional = true } -tracing.workspace = true +tracing = { workspace = true, optional = true } url.workspace = true [dev-dependencies] diff --git a/crates/auth-sdk/src/http.rs b/crates/auth-sdk/src/http.rs index dd9438d2a..5274a8cd1 100644 --- a/crates/auth-sdk/src/http.rs +++ b/crates/auth-sdk/src/http.rs @@ -2,10 +2,10 @@ //! around each request. use base64::{Engine, engine::general_purpose::STANDARD}; +use piquel_common::SendTraced; use reqwest::{RequestBuilder, StatusCode, header}; use std::time::Duration; use thiserror::Error; -use tracing::{Instrument, field::Empty}; use url::Url; /// Most bytes read from any response. Metadata, key sets and token responses are a @@ -140,10 +140,8 @@ impl Http { self.send(url, request, authorization).await } - /// Authenticates, sends and reads a request in an `http.client` span. Like auth's - /// own client spans, it records only the method, host and status: never the path, - /// query, headers or body, which carry codes and tokens. A failure or 4xx/5xx - /// status marks it failed. + /// Authenticates, sends and reads a request. It is sent in the `http.client` span + /// of [`SendTraced`], which records only the method, host and status. async fn send( &self, url: &Url, @@ -166,49 +164,26 @@ impl Http { url: url.clone(), source, }; - let request = request.build().map_err(failed)?; - let method = request.method().as_str(); - let span = tracing::info_span!( - "http.client", - otel.name = method, - otel.kind = "client", - otel.status_code = Empty, - http.request.method = method, - server.address = url.host_str(), - http.response.status_code = Empty, - ); - let exchange = async { - let mut response = self.0.execute(request).await.map_err(failed)?; - let status = response.status(); - // tracing-opentelemetry exports unsigned integers as strings. - span.record("http.response.status_code", i64::from(status.as_u16())); - if status.is_client_error() || status.is_server_error() { - span.record("otel.status_code", "ERROR"); + let mut response = request.send_traced().await.map_err(failed)?; + let status = response.status(); + let max_age = response + .headers() + .get_all(header::CACHE_CONTROL) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .find_map(|directive| directive.trim().strip_prefix("max-age=")?.parse().ok()); + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(failed)? { + if body.len() + chunk.len() > MAX_BODY_BYTES { + return Err(NetworkError::TooLarge { url: url.clone() }); } - let max_age = response - .headers() - .get_all(header::CACHE_CONTROL) - .iter() - .filter_map(|value| value.to_str().ok()) - .flat_map(|value| value.split(',')) - .find_map(|directive| directive.trim().strip_prefix("max-age=")?.parse().ok()); - let mut body = Vec::new(); - while let Some(chunk) = response.chunk().await.map_err(failed)? { - if body.len() + chunk.len() > MAX_BODY_BYTES { - return Err(NetworkError::TooLarge { url: url.clone() }); - } - body.extend_from_slice(&chunk); - } - Ok(Reply { - status, - max_age, - body, - }) - }; - let reply = exchange.instrument(span.clone()).await; - if reply.is_err() { - span.record("otel.status_code", "ERROR"); + body.extend_from_slice(&chunk); } - reply + Ok(Reply { + status, + max_age, + body, + }) } } diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index 99f924f02..e397784d9 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -84,7 +84,7 @@ //! or extra trusted roots. //! //! Each request runs in an `http.client` `tracing` span, at `info` under the -//! `piquel_auth` target, with its method, host and status only, as OpenTelemetry's +//! `piquel_common` target, with its method, host and status only, as OpenTelemetry's //! HTTP client conventions name them. //! //! The behavior follows `docs/architecture/sdk.md` in the piquel-fr repository, and is diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index d7ab816e6..2f4a5dd8f 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -9,6 +9,8 @@ repository.workspace = true [features] # The views of administration, for auth and its dashboard. admin = ["dep:serde_json"] +# `SendTraced`: client spans around `reqwest` requests, for auth and the SDK. +client-spans = ["dep:reqwest", "dep:tracing"] # Environment variables, validated origins and secret references, for servers. config = [] # Email address normalization, for servers that store or compare addresses. @@ -20,10 +22,12 @@ sqlx = ["dep:sqlx"] [dependencies] chrono.workspace = true +reqwest = { workspace = true, optional = true } serde.workspace = true serde_json = { workspace = true, optional = true } sqlx = { workspace = true, optional = true } thiserror.workspace = true +tracing = { workspace = true, optional = true } unicode-normalization = { workspace = true, optional = true } url.workspace = true uuid.workspace = true diff --git a/crates/telemetry/src/client.rs b/crates/common/src/client_span.rs similarity index 61% rename from crates/telemetry/src/client.rs rename to crates/common/src/client_span.rs index 5534df80d..356e3a763 100644 --- a/crates/telemetry/src/client.rs +++ b/crates/common/src/client_span.rs @@ -2,13 +2,16 @@ use reqwest::{RequestBuilder, Response}; use tracing::{Instrument, field::Empty}; -use tracing_opentelemetry::OpenTelemetrySpanExt; /// Sends a `reqwest` request in a client span, e.g. `client.get(url).send_traced()`. +/// Auth's provider and delivery calls use it, and so does the Rust SDK, so every +/// request either sends looks the same in a trace. pub trait SendTraced { - /// Sends the request in a span recording only its method, host and response - /// status: never its path, query, headers or body, which carry codes and tokens. - /// A failure or 4xx/5xx status marks the span failed. + /// Sends the request in an `http.client` span, at `info` under the + /// `piquel_common` target, recording only its method, host and response status + /// as OpenTelemetry's HTTP client conventions name them: never its path, query, + /// headers or body, which carry codes and tokens. A failure or 4xx/5xx status + /// marks the span failed. fn send_traced(self) -> impl Future> + Send; } @@ -16,21 +19,21 @@ impl SendTraced for RequestBuilder { async fn send_traced(self) -> reqwest::Result { let (client, request) = self.build_split(); let request = request?; - let method = request.method().as_str().to_owned(); + let method = request.method().as_str(); let span = tracing::info_span!( "http.client", otel.name = method, otel.kind = "client", otel.status_code = Empty, + http.request.method = method, + server.address = request.url().host_str(), + http.response.status_code = Empty, ); - span.set_attribute("http.request.method", method); - if let Some(host) = request.url().host_str() { - span.set_attribute("server.address", host.to_owned()); - } let response = client.execute(request).instrument(span.clone()).await; match &response { Ok(response) => { - span.set_attribute( + // tracing-opentelemetry exports unsigned integers as strings. + span.record( "http.response.status_code", i64::from(response.status().as_u16()), ); diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 9d590ba6f..a484c403c 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -6,6 +6,7 @@ //! the vocabulary macros. Servers add: //! //! - `admin`: the views of administration. +//! - `client-spans`: `SendTraced`, a client span around each `reqwest` request. //! - `config`: environment variables, validated origins and secret references. //! - `email`: email address normalization. //! - `events`: the domain events auth records. @@ -14,6 +15,9 @@ /// The views of administration: what the admin dashboard shows and the CLI prints. #[cfg(feature = "admin")] pub mod admin; +/// Client spans around outbound `reqwest` requests. +#[cfg(feature = "client-spans")] +mod client_span; /// OAuth client registrations, each field validated by its type. pub mod clients; /// Environment variables, validated origins and secret references. @@ -35,6 +39,8 @@ use std::{error::Error as StdError, fmt, str::FromStr}; use thiserror::Error; use uuid::Uuid; +#[cfg(feature = "client-spans")] +pub use client_span::SendTraced; pub use clients::ClientId; pub use handle::{Handle, HandleError}; diff --git a/crates/telemetry/Cargo.toml b/crates/telemetry/Cargo.toml index 9d8df8c6c..f74197e02 100644 --- a/crates/telemetry/Cargo.toml +++ b/crates/telemetry/Cargo.toml @@ -10,7 +10,7 @@ repository.workspace = true test-util = ["opentelemetry_sdk/testing"] [dependencies] -piquel-common = { workspace = true, features = ["config"] } +piquel-common = { workspace = true, features = ["client-spans", "config"] } async-trait.workspace = true axum.workspace = true diff --git a/crates/telemetry/src/lib.rs b/crates/telemetry/src/lib.rs index b30c71b3f..111938d9f 100644 --- a/crates/telemetry/src/lib.rs +++ b/crates/telemetry/src/lib.rs @@ -17,8 +17,6 @@ //! Everything a span, log line or label holds may be exported. Never record a //! secret, a query string or a request header. -/// Client spans for outbound `reqwest` requests. -mod client; /// OTLP export through the workspace's `reqwest`. mod export; /// Server spans, access logs and request durations for axum routers. @@ -32,9 +30,9 @@ mod capture; #[cfg(any(test, feature = "test-util"))] pub use capture::Capture; -pub use client::SendTraced; pub use http::HttpTelemetry; pub use metrics::{Counter, Gauge, Histogram, Label, Labels}; +pub use piquel_common::SendTraced; use export::Exporters; use opentelemetry::{KeyValue, trace::TraceContextExt}; @@ -64,9 +62,9 @@ use uuid::Uuid; /// Instrumentation scope of every tracer and meter. const SCOPE: &str = "piquel"; -/// Added to every filter: this crate's spans and access logs, and the SDK's own -/// warnings, such as failed exports. -const OWN_DIRECTIVES: &str = "piquel_telemetry=info,opentelemetry=warn"; +/// Added to every filter: this crate's spans and access logs, the client spans of +/// [`SendTraced`], and the SDK's own warnings, such as failed exports. +const OWN_DIRECTIVES: &str = "piquel_telemetry=info,piquel_common=info,opentelemetry=warn"; /// Targets never exported as logs: the SDK, which logs its own failures, and the /// HTTP stack export requests run on, outside the SDK's suppression of its own /// telemetry. Exporting either would feed the exporter its own traffic. They still diff --git a/docs/architecture/telemetry.md b/docs/architecture/telemetry.md index 79bb85017..f320acdf4 100644 --- a/docs/architecture/telemetry.md +++ b/docs/architecture/telemetry.md @@ -79,9 +79,9 @@ where one exists, and `piquel.auth.*` otherwise. Units follow UCUM: `s`, or `{thing}` for counts. **An outbound HTTP call:** `request.send_traced()` instead of `send()`. It -records the method, host and status only. Requests the Rust SDK sends, such as -Google's signing-key fetches through `KeyCache`, get the same span from the SDK -itself. +records the method, host and status only. `SendTraced` lives in `piquel-common` +so the Rust SDK sends its requests, such as Google's signing-key fetches through +`KeyCache`, the same way. ## What never goes in telemetry From 4ecd09ca24b6f871c1a2ad9d745c509bdd3875eb Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 2 Nov 2026 16:57:46 +0100 Subject: [PATCH 2/2] docs(monorepo): list piquel-common's client-spans and email features Co-Authored-By: Claude Opus 5.5 --- docs/architecture/monorepo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/monorepo.md b/docs/architecture/monorepo.md index 13ec9cea0..44b990511 100644 --- a/docs/architecture/monorepo.md +++ b/docs/architecture/monorepo.md @@ -8,7 +8,7 @@ is authentication, with its account settings, and the admin dashboard. | `apps/auth-service` | Rust auth authority, browser ceremonies, social adapters, OIDC, server-rendered pages, the settings API, the admin dashboard at admin.piquel.fr, CLI; `assets/passkey.js`, the one script its pages load: the WebAuthn passkey ceremonies and the form hooks that run them | | `crates/database` | `piquel-repository`: PostgreSQL connections, migrations and typed persistence operations | | `crates/auth-sdk` | `piquel-auth`, the public Rust SDK: token validation, typed scopes, login and the JWKS cache auth also uses for Google; `axum` feature: extractors, bearer layer, login routes over an application's own session backend | -| `crates/common` | `piquel-common`, the one home for shared types: IDs, string enums, `Personal`, and the wire types shared by auth and the SDKs (token claims, discovery metadata, JWK sets, OAuth/OIDC vocabulary and errors, bearer challenges, SDK error codes, and the bodies auth's settings API and the admin views share); `admin` feature: the views of administration, which the admin dashboard shows, the CLI prints as JSON and the database crate decodes into; `config` feature: environment variables, validated origins, secret references; `events` feature: domain events | +| `crates/common` | `piquel-common`, the one home for shared types: IDs, string enums, `Personal`, and the wire types shared by auth and the SDKs (token claims, discovery metadata, JWK sets, OAuth/OIDC vocabulary and errors, bearer challenges, SDK error codes, and the bodies auth's settings API and the admin views share); `admin` feature: the views of administration, which the admin dashboard shows, the CLI prints as JSON and the database crate decodes into; `client-spans` feature: `SendTraced`, client spans around `reqwest` requests, for auth and the SDK; `config` feature: environment variables, validated origins, secret references; `email` feature: email address normalization; `events` feature: domain events | | `crates/crypto` | Random secrets, SHA-256, HMAC, PKCE and RS256 signing | | `crates/ui` | `piquel-ui`: the Topcoat components and layouts of auth's server-rendered pages, rendering plain data and taking URLs as props, the admin dashboard's included, and the shared stylesheet, `assets/style.css` | | `crates/telemetry` | `piquel-telemetry`: stderr logs, and OpenTelemetry traces, metrics and logs over OTLP; request spans and access logs for axum routers, client spans, and typed metric instruments; see [telemetry.md](telemetry.md) |