# `TraceGuard.EventCollector`
[🔗](https://github.com/HataluliRandima/trace_guard/blob/v0.1.0/lib/trace_guard/event_collector.ex#L1)

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

Appends diagnostic events to the calling process's `TraceGuard.Context`.

Every event has the same internal shape:

    %{
      seq: 3,                       # order of observation within the process
      process: "request",           # "request", or "task-N" for propagated work
      name: "ecto.query",
      type: "db",
      at: -576460748160,            # System.monotonic_time(), see "Timestamps"
      duration: 1234 | nil,         # native time units, when the source reports one
      outcome: "ok" | "error" | nil,
      metadata: %{...}              # already filtered by the caller
    }

## Timestamps

An event is timestamped when its telemetry handler runs, except the end
of a span. Other handlers attached to the same event may run before
TraceGuard's and do slow work of their own: error reporters such as
ErrorTracker write to the database from their exception handler. Their
queries are recorded first, but happened after the exception. So an event
recorded with `span: {:stop, key}` is timestamped at the time of the
matching `span: {:start, key}` event plus its own `:duration`, the time
the span actually ended. Spans of the same key nest, as in a Phoenix
router forwarding to another router.

## Bounding

At most `:max_events` ordinary events are retained per trace. Further
ordinary events are counted in `dropped` and discarded. *Lifecycle* events
(request start/stop, exceptions, error rendering) are always retained; a
request emits only a handful of them, so the total stays bounded.

In a process running wrapped work (`role: :task`, see
`TraceGuard.Propagation`), events are not stored locally but sent to the
trace's task collector, within a budget of `:max_events` shared by all
task processes of the trace. Task lifecycle events count against it.

# `event_opts`

```elixir
@type event_opts() :: [
  duration: integer() | nil,
  outcome: String.t() | nil,
  lifecycle: boolean(),
  span: {:start | :stop, atom()}
]
```

# `accepting?`

```elixir
@spec accepting?() :: boolean()
```

Returns true if the calling process has an active trace whose buffer can
still take an ordinary event. Lets handlers skip building metadata for
events that would be dropped.

# `finish`

```elixir
@spec finish(integer() | nil) ::
  {:reported, String.t()} | {:dropped, String.t(), term()} | :ok | :no_context
```

Completes the calling process's trace.

The context is always removed. A report is built and stored only when the
request failed: an exception was captured, or `status` is at least
`:failure_status`. Successful requests leave nothing behind.

If the request propagated its trace to tasks, the task collector is
drained into the report (failed requests, waiting at most
`:task_drain_timeout` ms) or discarded without waiting (successful ones).
Only the process that owns the trace can complete it.

Returns `{:reported, trace_id}` when the storage adapter accepted the
report, `{:dropped, trace_id, reason}` when it did not (for example
`:overloaded`), `:ok` (no failure) or `:no_context`. The trace context is
removed *before* the report is stored, so storage can never add events to
any trace.

# `put_failure`

```elixir
@spec put_failure(map()) :: :ok | :no_context
```

Records failure details on the active context.

The first failure wins: a later, less specific signal (for example the
endpoint's error rendering after the router already reported the
exception) never overwrites it.

# `put_request_fields`

```elixir
@spec put_request_fields(map()) :: :ok | :no_context
```

Merges `fields` into the active context's request metadata.

# `record`

```elixir
@spec record(String.t(), String.t(), map(), event_opts()) ::
  :ok | :dropped | :no_context
```

Records an event if the calling process has an active context.

Returns `:ok` when recorded, `:dropped` when the event cap was reached and
`:no_context` when the calling process is not handling a traced request.

# `record_dropped`

```elixir
@spec record_dropped() :: :dropped | :no_context
```

Counts an ordinary event that was not recorded because the buffer is full.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
