tonin-core 0.3.4

Core types for tonin: Service builder, Config, Context, Error, runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! `Instrumented<T>` — the single decorator that gives every capability
//! call a span, metric, and slow-op WARN log.
//!
//! Service authors never see this directly. Phase 5 will wrap each
//! capability returned from `Service` accessors in `Instrumented`, so
//! `svc.cache().get("k")` automatically gets:
//!
//! - a `cache.get` span as a child of the current request span,
//! - a `cache_op_duration_ms` histogram observation,
//! - a `cache_op_total` counter increment,
//! - a WARN log if the call exceeds `SlowThresholds::cache_op` or fails.
//!
//! New backend impls (`tonin-redis`, future `tonin-postgres`) get
//! all of this for free — they only implement the trait methods.

use std::{
    collections::HashMap,
    hash::{Hash, Hasher},
    pin::Pin,
    sync::Arc,
    task::{Context as TaskContext, Poll},
    time::{Duration, Instant},
};

use async_trait::async_trait;
use futures_core::Stream;
use tracing::Span;
use tracing_opentelemetry::OpenTelemetrySpanExt;

use crate::telemetry::capability_metrics::{
    SlowThresholds, record_cache_op, record_messaging_publish,
};
use crate::telemetry::propagate::{extract_context_from_map, inject_current_context_map};

use crate::Error;
use crate::traits::{
    Cache, Config, Database, DeliveredMessage, EventBus, MessageId, SecretStore, SubscribeOptions,
    Subscription,
};

/// Decorator that wraps any capability impl with telemetry. Cheap to
/// clone — internal state is an `Arc` to the inner impl plus a small
/// `SlowThresholds`.
///
/// ```
/// # use std::sync::Arc;
/// # use std::time::Duration;
/// # use async_trait::async_trait;
/// # use tonin_core::{instrumented::Instrumented, traits::Cache, Error};
/// struct MockCache;
/// #[async_trait]
/// impl Cache for MockCache {
///     fn system(&self) -> &'static str { "mock" }
///     async fn get(&self, _k: &str) -> Result<Option<Vec<u8>>, Error> {
///         Ok(Some(b"hi".to_vec()))
///     }
///     async fn set(&self, _k: &str, _v: &[u8], _t: Option<Duration>) -> Result<(), Error> { Ok(()) }
///     async fn del(&self, _k: &str) -> Result<(), Error> { Ok(()) }
///     async fn set_nx(&self, _k: &str, _v: &[u8], _t: Option<Duration>) -> Result<bool, Error> { Ok(true) }
/// }
///
/// # tokio_test::block_on(async {
/// let cache = Instrumented::with_defaults(Arc::new(MockCache));
/// let v = Cache::get(&cache, "hello").await.unwrap();
/// assert_eq!(v, Some(b"hi".to_vec()));
/// # });
/// ```
pub struct Instrumented<T: ?Sized> {
    inner: Arc<T>,
    slow: SlowThresholds,
}

impl<T: ?Sized> Clone for Instrumented<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            slow: self.slow.clone(),
        }
    }
}

impl<T: ?Sized> Instrumented<T> {
    pub fn new(inner: Arc<T>, slow: SlowThresholds) -> Self {
        Self { inner, slow }
    }

    /// Use the framework's default thresholds — handy for tests and the
    /// Phase 5 wiring path when no `[telemetry.slow]` was provided.
    pub fn with_defaults(inner: Arc<T>) -> Self {
        Self::new(inner, SlowThresholds::default())
    }
}

// ---------- Cache impl ----------

#[async_trait]
impl<T: Cache + ?Sized> Cache for Instrumented<T> {
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
        let span = tracing::info_span!(
            "cache.get",
            cache.system = self.inner.system(),
            cache.op = "get",
            cache.key.hash = key_hash(key),
            cache.hit = tracing::field::Empty,
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.get(key).await;
        let elapsed = start.elapsed();
        let outcome = match &result {
            Ok(Some(_)) => "hit",
            Ok(None) => "miss",
            Err(_) => "error",
        };
        if let Ok(opt) = &result {
            Span::current().record("cache.hit", opt.is_some());
        }
        record_cache_op(self.inner.system(), "get", outcome, elapsed);
        slow_or_error_log(elapsed, self.slow.cache_op, &result, "cache.get", key);
        result
    }

    async fn set(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<(), Error> {
        let span = tracing::info_span!(
            "cache.set",
            cache.system = self.inner.system(),
            cache.op = "set",
            cache.key.hash = key_hash(key),
            ttl_ms = ttl.map(|d| d.as_millis() as u64),
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.set(key, value, ttl).await;
        let elapsed = start.elapsed();
        let outcome = if result.is_ok() { "ok" } else { "error" };
        record_cache_op(self.inner.system(), "set", outcome, elapsed);
        slow_or_error_log(elapsed, self.slow.cache_op, &result, "cache.set", key);
        result
    }

    async fn del(&self, key: &str) -> Result<(), Error> {
        let span = tracing::info_span!(
            "cache.del",
            cache.system = self.inner.system(),
            cache.op = "del",
            cache.key.hash = key_hash(key),
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.del(key).await;
        let elapsed = start.elapsed();
        let outcome = if result.is_ok() { "ok" } else { "error" };
        record_cache_op(self.inner.system(), "del", outcome, elapsed);
        slow_or_error_log(elapsed, self.slow.cache_op, &result, "cache.del", key);
        result
    }

    async fn set_nx(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<bool, Error> {
        let span = tracing::info_span!(
            "cache.set_nx",
            cache.system = self.inner.system(),
            cache.op = "setnx",
            cache.key.hash = key_hash(key),
            ttl_ms = ttl.map(|d| d.as_millis() as u64),
            cache.created = tracing::field::Empty,
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.set_nx(key, value, ttl).await;
        let elapsed = start.elapsed();
        let outcome = match &result {
            Ok(true) => "ok",
            Ok(false) => "exists",
            Err(_) => "error",
        };
        if let Ok(created) = &result {
            Span::current().record("cache.created", *created);
        }
        record_cache_op(self.inner.system(), "setnx", outcome, elapsed);
        slow_or_error_log(elapsed, self.slow.cache_op, &result, "cache.set_nx", key);
        result
    }

    fn system(&self) -> &'static str {
        self.inner.system()
    }
}

// ---------- Database impl ----------
//
// Pass-through. The trait has no methods worth wrapping (url() is sync
// and infallible; pool() is a borrow). Query spans come from the user's
// chosen DB client (sqlx, sea-orm), which emits OTel spans via the
// global tracer that `crate::telemetry::init` installs.

#[async_trait]
impl<T: Database + ?Sized> Database for Instrumented<T> {
    fn url(&self) -> &str {
        self.inner.url()
    }
    fn system(&self) -> &'static str {
        self.inner.system()
    }
}

// ---------- SecretStore impl ----------

#[async_trait]
impl<T: SecretStore + ?Sized> SecretStore for Instrumented<T> {
    async fn get(&self, key: &str) -> Result<String, Error> {
        // The key name is intentionally NOT a span attribute — secret
        // names can be sensitive. Only the provider is recorded.
        let span = tracing::info_span!("secret.get", secret.provider = self.inner.provider(),);
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.get(key).await;
        let elapsed = start.elapsed();
        // No metric for SecretStore in Phase 3 — it's hot-path-cached
        // and uninteresting volumetrically. Add later if a backend
        // makes per-call network hops.
        if result.is_err() {
            tracing::warn!(
                elapsed_ms = elapsed.as_millis() as u64,
                provider = self.inner.provider(),
                "secret.get failed",
            );
        }
        result
    }

    fn provider(&self) -> &'static str {
        self.inner.provider()
    }
}

// ---------- Config impl ----------

#[async_trait]
impl<T: Config + ?Sized> Config for Instrumented<T> {
    async fn get(&self, path: &str) -> Result<Option<Vec<u8>>, Error> {
        // Path IS recorded as a span attribute — unlike SecretStore::get
        // where the key name can be sensitive, config paths are application
        // structure (db.pool.max, feature.flag) and are safe to record.
        let span = tracing::info_span!(
            "config.get",
            config.source = self.inner.source(),
            config.path = path,
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self.inner.get(path).await;
        let elapsed = start.elapsed();
        if result.is_err() {
            tracing::warn!(
                elapsed_ms = elapsed.as_millis() as u64,
                source = self.inner.source(),
                path,
                "config.get failed",
            );
        }
        result
    }

    fn watch(
        &self,
        path: &str,
        interval: std::time::Duration,
    ) -> tokio::sync::watch::Receiver<Option<Vec<u8>>> {
        // No span around watch() — the channel lives much longer than
        // any single span and emits a stream of values; instrumenting
        // each emission lives in the consumer's processing loop.
        self.inner.watch(path, interval)
    }

    fn source(&self) -> &'static str {
        self.inner.source()
    }
}

// ---------- EventBus impl ----------

#[async_trait]
impl<T: EventBus + ?Sized> EventBus for Instrumented<T> {
    async fn publish(&self, subject: &str, payload: &[u8]) -> Result<MessageId, Error> {
        let mut headers = HashMap::new();
        inject_current_context_map(&mut headers);
        self.publish_inner(subject, payload, headers).await
    }

    async fn publish_with_headers(
        &self,
        subject: &str,
        payload: &[u8],
        mut headers: HashMap<String, String>,
    ) -> Result<MessageId, Error> {
        // Only inject if the caller didn't already provide one — caller-
        // supplied `traceparent` wins (rare, but matters for testing).
        if !headers.contains_key("traceparent") {
            inject_current_context_map(&mut headers);
        }
        self.publish_inner(subject, payload, headers).await
    }

    async fn subscribe(
        &self,
        subject_pattern: &str,
        group: &str,
        opts: SubscribeOptions,
    ) -> Result<Subscription, Error> {
        let inner_sub = self.inner.subscribe(subject_pattern, group, opts).await?;
        let system: &'static str = self.inner.system();
        let group_owned = group.to_string();
        let subject_owned = subject_pattern.to_string();
        Ok(Subscription::new(InstrumentedSubscription {
            inner: inner_sub,
            system,
            group: group_owned,
            subject: subject_owned,
        }))
    }

    fn system(&self) -> &'static str {
        self.inner.system()
    }
}

impl<T: EventBus + ?Sized> Instrumented<T> {
    async fn publish_inner(
        &self,
        subject: &str,
        payload: &[u8],
        headers: HashMap<String, String>,
    ) -> Result<MessageId, Error> {
        let span = tracing::info_span!(
            "messaging.publish",
            messaging.system = self.inner.system(),
            messaging.destination.name = subject,
            messaging.destination.kind = "topic",
            messaging.message.body.size = payload.len(),
        );
        let _enter = span.enter();
        let start = Instant::now();
        let result = self
            .inner
            .publish_with_headers(subject, payload, headers)
            .await;
        let elapsed = start.elapsed();
        let outcome = if result.is_ok() { "ok" } else { "error" };
        record_messaging_publish(self.inner.system(), subject, outcome, elapsed);
        if elapsed > self.slow.messaging_publish || result.is_err() {
            tracing::warn!(
                elapsed_ms = elapsed.as_millis() as u64,
                subject,
                error = result.as_ref().err().map(|e| e.to_string()),
                "slow or failing messaging.publish",
            );
        }
        result
    }
}

/// Wraps the backend `Subscription` and creates a `messaging.process`
/// span per yielded message. The span's parent is the publisher's
/// context, extracted from `msg.headers`. If the header is missing or
/// malformed, the span becomes a new root — never grafted onto
/// `Span::current()`, which would lie about causality.
struct InstrumentedSubscription {
    inner: Subscription,
    system: &'static str,
    group: String,
    subject: String,
}

impl Stream for InstrumentedSubscription {
    type Item = DeliveredMessage;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
        let this = self.as_mut().get_mut();
        match Pin::new(&mut this.inner).poll_next(cx) {
            Poll::Ready(Some(msg)) => {
                // Emit messaging.process parented to the publisher's
                // context. Consumer handlers create their own spans;
                // those are linked to this trace via the propagator if
                // the handler enters this span. We don't enter it here
                // — the consumer owns processing-time accounting.
                let span = tracing::info_span!(
                    "messaging.process",
                    messaging.system = this.system,
                    messaging.destination.name = %msg.subject,
                    messaging.consumer.id = %this.group,
                    messaging.message.id = %msg.id,
                    messaging.delivery_attempt = msg.delivery_attempt,
                    subscription.subject_pattern = %this.subject,
                );
                let parent_cx = extract_context_from_map(&msg.headers);
                span.set_parent(parent_cx);
                drop(span);
                Poll::Ready(Some(msg))
            }
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

// ---------- helpers ----------

fn slow_or_error_log<T>(
    elapsed: Duration,
    threshold: Duration,
    result: &Result<T, Error>,
    op: &'static str,
    key_for_hash: &str,
) {
    if elapsed > threshold || result.is_err() {
        tracing::warn!(
            elapsed_ms = elapsed.as_millis() as u64,
            key.hash = key_hash(key_for_hash),
            error = result.as_ref().err().map(|e| e.to_string()),
            "slow or failing {op}",
            op = op,
        );
    }
}

/// Stable, low-cardinality hash. Not cryptographic — bounded label
/// cardinality, that's all.
fn key_hash(key: &str) -> u64 {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    key.hash(&mut h);
    h.finish()
}