1 unstable release

0.0.9 Apr 23, 2024

#1082 in Rust patterns

Download history 112/week @ 2024-06-01 86/week @ 2024-06-08 94/week @ 2024-06-15 43/week @ 2024-06-22 156/week @ 2024-06-29 72/week @ 2024-07-06 153/week @ 2024-07-13 99/week @ 2024-07-20 118/week @ 2024-07-27 219/week @ 2024-08-03 157/week @ 2024-08-10 173/week @ 2024-08-17 241/week @ 2024-08-24 45/week @ 2024-08-31 147/week @ 2024-09-07 134/week @ 2024-09-14

572 downloads per month

MIT license

16KB
143 lines

tyco - crate for creating scoped TYped COntexts.

Crates.io docs.rs CI

This crate allows you to define and store typed information in current execution context (sync or async) and pass it down call stack without explicitely speicfying it in function arguments. This is helpful for implementing some additional functionality without main business logic messing up your main business logic code.

It is inspired by and similar to opentelemetry::Context, how loggers stored id log/slog/tracing, using TLS for storing and accessing values. Unlike opentelemetry::Context, which is basically HashMap<TypeId, Any>, current crate allows to work any type, which may (or may not) result in more efficient and clean code.

Example

Basic example of how to define context, which will contain some tracing identifier, which can be used for things like distinguishing HTTP requests.

use tyco::{context, FutureExt, TypedContext};

mod trace_id {
    use super::*;

    #[derive(Clone, Default, Debug, PartialEq)]
    pub struct TraceId(String);

    tyco::context!(TraceId);
}

let t = trace_id::TraceId::default();

let spawned_fut = tokio::spawn(
    async { println!("{:?}", trace_id::TraceId::current()) }
    // 2 ways to pass context to spawned future
    .with_current::<trace_id::TraceId>()
    .with(t.clone()),
);

Also check more complex examples (on how to use it with HTTP server/client for example).

Dependencies

~290–760KB
~18K SLoC