Skip to main content

Dial9HandleTokioExt

Trait Dial9HandleTokioExt 

pub trait Dial9HandleTokioExt: Sealed {
    // Required methods
    fn attach_tokio_runtime(
        &self,
        builder: Builder,
        options: TokioAttachOptions,
    ) -> Result<Runtime, Error>;
    fn attach_tokio_local_runtime(
        &self,
        builder: Builder,
        options: TokioAttachOptions,
    ) -> Result<LocalRuntime, Error>;
    fn detach_tokio_runtime_on_drop(&self, runtime: &Handle) -> TokioDetachGuard;
    fn detach_tokio_runtime(&self, runtime: &Handle) -> TokioDetachOutcome;
}
Available on crate features dial9 and tokio only.
Expand description

Tokio instrumentation for Dial9Handle.

Required Methods§

fn attach_tokio_runtime( &self, builder: Builder, options: TokioAttachOptions, ) -> Result<Runtime, Error>

Instrument a builder you configured, build it, and return the runtime.

Get a handle from Recorder::handle, or clone one per thread. Each call attaches another runtime (it does not replace earlier ones) and every runtime attached to the same recorder records into the same trace.

  • builder: yours to configure. dial9 does not seed it, so call enable_all (or the drivers you need) yourself, and pick the flavor. Taken by value: the hooks installed on it belong to this one runtime.
  • options: dial9 tracing behavior for this runtime (runtime name, task tracking, task-dump config, composed hooks).

On a disabled recorder this still returns a working, untraced runtime, as does tokio_instrumentation_enabled(false), which skips instrumentation for this runtime only. Hooks passed via TokioHooks are installed in both cases.

Do not set builder thread/task callbacks directly (on_thread_start and friends) because dial9 installs its own and would overwrite yours. Pass TokioHooks in the options to compose them instead.

Drop the runtime before calling Recorder::graceful_shutdown on the recorder this handle came from, so the runtime’s workers flush.

Attach claims the calling thread: the handle is installed thread-locally, so Dial9Handle::current and dial9::spawn work there before the first poll, replacing any handle a previous attach installed. Attach a current_thread runtime on the thread that will drive it.

The runtime stays registered, even after it drops, until detach_tokio_runtime, a TokioDetachGuard drop, or recorder teardown.

§Errors

Fails if Tokio cannot build the runtime, or if the recorder has already shut down.

Drive the root future with block_on, not Runtime::block_on: to ensure polls and wakes are captured.

use dial9_core::buffer::MemoryBuffer;
use dial9_core::recorder::recorder;
use dial9_tokio_telemetry::telemetry::{Dial9HandleTokioExt, TokioAttachOptions};

let recorder = recorder(MemoryBuffer::new(1 << 20)?).build();

let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.enable_all().worker_threads(4);
let runtime = recorder
    .handle()
    .attach_tokio_runtime(builder, TokioAttachOptions::default())?;

The handle is cheap to clone, so several threads can each attach their own runtime off the same recorder:

use dial9_core::buffer::MemoryBuffer;
use dial9_core::recorder::recorder;
use dial9_tokio_telemetry::telemetry::{Dial9HandleTokioExt, TokioAttachOptions};

let recorder = recorder(MemoryBuffer::new(1 << 20)?).build();
let handle = recorder.handle().clone();

let threads: Vec<_> = (0..2)
    .map(|_| {
        let handle = handle.clone();
        std::thread::spawn(move || {
            let mut builder = tokio::runtime::Builder::new_current_thread();
            builder.enable_all();
            let runtime = handle
                .attach_tokio_runtime(builder, TokioAttachOptions::default())
                .expect("build runtime");
            dial9_tokio_telemetry::block_on(&runtime, async { /* ... */ });
        })
    })
    .collect();

fn attach_tokio_local_runtime( &self, builder: Builder, options: TokioAttachOptions, ) -> Result<LocalRuntime, Error>

Like attach_tokio_runtime, but builds a [tokio::runtime::LocalRuntime], which can spawn !Send futures.

Drive it with block_on_local and spawn_local so !Send tasks are traced without --cfg tokio_unstable.

§Errors

Fails if the builder is multi-thread, if Tokio cannot build the runtime, or if the recorder has already shut down.

use dial9_core::buffer::MemoryBuffer;
use dial9_core::recorder::recorder;
use dial9_tokio_telemetry::telemetry::{Dial9HandleTokioExt, TokioAttachOptions};

let recorder = recorder(MemoryBuffer::new(1 << 20)?).build();

let mut builder = tokio::runtime::Builder::new_current_thread();
builder.enable_all();
let runtime = recorder
    .handle()
    .attach_tokio_local_runtime(builder, TokioAttachOptions::default())?;

dial9_tokio_telemetry::block_on_local(&runtime, async {
    let cell = std::rc::Rc::new(1);
    dial9_tokio_telemetry::spawn_local(async move { *cell }).await.unwrap();
});

fn detach_tokio_runtime_on_drop(&self, runtime: &Handle) -> TokioDetachGuard

Detach runtime when the returned guard leaves scope or unwinds.

Declare the guard after the runtime so it detaches before the runtime drops on normal return, early return through ?, and panic unwinding. It also supports dropping the runtime first: the guard’s owned Tokio handle retains its drivers until the guard drops.

Create the guard on the thread that drives a current_thread runtime or LocalRuntime. The guard cannot move to another thread, but it does not establish which thread drives a runtime.

This schedules cleanup without attaching a runtime or checking whether it is tracked. A paused recorder still detaches; an untracked runtime, disabled handle, stopped recorder, or earlier explicit detach is harmless. Detach has the same recording behavior and limitations as detach_tokio_runtime.

use dial9_core::buffer::MemoryBuffer;
use dial9_core::recorder::recorder;
use dial9_tokio_telemetry::telemetry::{
    Dial9HandleTokioExt, TokioAttachOptions, TokioDetachGuard,
};

let recorder = recorder(MemoryBuffer::new(1 << 20)?).build();
let d9 = recorder.handle();
{
    let mut builder = tokio::runtime::Builder::new_current_thread();
    builder.enable_all();
    let rt = d9.attach_tokio_runtime(builder, TokioAttachOptions::default())?;
    let _guard: TokioDetachGuard = d9.detach_tokio_runtime_on_drop(rt.handle());
    dial9_tokio_telemetry::block_on(&rt, async { /* serve */ });
}
recorder.graceful_shutdown(std::time::Duration::from_secs(1));

fn detach_tokio_runtime(&self, runtime: &Handle) -> TokioDetachOutcome

Stop tracking runtime and release dial9’s references to it.

Returns TokioDetachOutcome::Detached when tracking state is removed. Returns TokioDetachOutcome::NotTracked if nothing is removed: the runtime was never attached here, was attached with tokio_instrumentation_enabled(false), is already detached, the handle is Dial9Handle::disabled, or the recorder has shut down. A paused recorder still detaches. Idempotent.

Without this, an attached runtime stays registered for the recorder’s life: its metrics keep a runtime Handle, which holds the runtime’s drivers (and their file descriptors) open after the runtime drops. Detach before dropping a runtime the recorder outlives, e.g. on hot reload.

Works for a Runtime and a LocalRuntime alike, via .handle(). Detaching after the drop through a saved Handle clone also works, but that clone keeps the drivers open until it drops too.

With --cfg tokio_unstable, detach a current_thread runtime or LocalRuntime on the thread that drives it. A detach from another thread leaves the runtime’s metrics cached on the driving thread, keeping its drivers open until that thread drives another traced runtime or exits.

Tokio hooks cannot be removed from a built runtime. If it keeps running after detach, dial9 stops recording its poll, park, spawn and terminate events and its runtime-metrics samples, but until it drops these can continue: wakes of dial9::spawn tasks, task dumps, CPU samples on its threads and sched samples on its already-enrolled worker threads, and events recorded through a Dial9Handle (custom events, the tracing layer). Hooks passed via TokioHooks keep firing.

use dial9_core::buffer::MemoryBuffer;
use dial9_core::recorder::recorder;
use dial9_tokio_telemetry::telemetry::{
    Dial9HandleTokioExt, TokioAttachOptions, TokioDetachOutcome,
};

let recorder = recorder(MemoryBuffer::new(1 << 20)?).build();
let d9 = recorder.handle();

let mut builder = tokio::runtime::Builder::new_multi_thread();
builder.enable_all();
let rt = d9.attach_tokio_runtime(builder, TokioAttachOptions::default())?;
// ... serve until reload ...
match d9.detach_tokio_runtime(rt.handle()) {
    TokioDetachOutcome::Detached => {}
    TokioDetachOutcome::NotTracked => {}
}
drop(rt);

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§