TraceGuard.Propagation (trace_guard v0.1.0)

Copy Markdown View Source

Internal module. Not part of TraceGuard's public API: it may change in any release. Use the functions in TraceGuard instead.

Explicit, opt-in propagation of a request's trace into selected processes.

Telemetry handlers run in the process that emits an event, and TraceGuard.Context lives in the request process's dictionary, so work done in a Task is invisible by default. TraceGuard.wrap/1 (implemented here) binds a function to the current trace so that events emitted while it runs, in whichever process, are added to that trace:

Task.async(TraceGuard.wrap(fn -> Repo.all(Product) end))

What is propagated

Only a TraceGuard.Propagation.Token: the trace ID, the pid of the trace's task collector and an :atomics counter. No request data, headers, credentials or other process-dictionary entries are copied.

How events travel

The first wrap/1 call in a request starts a TraceGuard.TaskCollector (one per trace, under a bounded DynamicSupervisor). A process running wrapped work holds a task context for exactly the duration of the function; its events are sent to the collector as messages. All processes of one trace share the atomics counter, so at most :max_events task events are ever sent, regardless of the number of tasks. When the request completes, the collector is drained (failed request, bounded by :task_drain_timeout) or discarded (successful request).

Semantics

  • Opt-in. Unwrapped tasks inherit nothing.
  • Same trace ID. Wrapped work never starts a new trace.
  • Nesting. Wrapping inside wrapped work reuses the same token, so grandchildren report into the same trace. Calling a wrapped function in the process that owns the trace just calls the function.
  • Completion. Events that reach the collector after the request completed are dropped. Await tasks before responding if their events matter.
  • Errors. The wrapper never rescues: results, raises, throws and exits pass through unchanged (re-raised with the original stacktrace). A failure is recorded as a task.exception event first.
  • No blocking. Children never wait for TraceGuard. The request process waits at most :task_drain_timeout ms, only for failed requests.

Summary

Functions

Binds fun (arity 0 or 1) to the calling process's trace.

Functions

wrap(fun)

@spec wrap(fun) :: fun when fun: (-> any()) | (any() -> any())

Binds fun (arity 0 or 1) to the calling process's trace.

Returns fun unchanged when there is no active trace, when TraceGuard is disabled, or when the collector limit is reached.