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

Diagnostic reports for failed Phoenix requests.

When a request fails, TraceGuard reconstructs the timeline of telemetry
events it could observe for that request (endpoint, router, Ecto queries,
the exception), redacts sensitive values, and keeps a JSON-ready report.

## Setup

    # lib/my_app_web/endpoint.ex
    plug Plug.RequestId
    plug TraceGuard.Plug
    plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]

    # config/config.exs
    config :trace_guard, ecto_telemetry_prefixes: [[:my_app, :repo]]

## Usage

    {:ok, report} = TraceGuard.get_report(trace_id)
    {:ok, json} = TraceGuard.export_json(trace_id, pretty: true)

The trace ID of a failed request is returned in the `x-traceguard-id`
response header and added to `Logger` metadata as `trace_guard_id`.

## Report structure (`traceguard.report/v1`)

    %{
      "schema" => "traceguard.report/v1",
      "trace_id" => "32 lowercase hex chars",
      "generated_at" => "ISO 8601 UTC timestamp",
      "outcome" => "exception" | "error_status",
      "request" => %{"method", "route", "path", "started_at", "request_id",
                     "incoming_id", "headers"},
      "response" => %{"status" => integer | nil},
      "duration_us" => integer,
      "events" => [%{"seq", "process", "name", "type", "offset_us",
                     "duration_us", "outcome", "metadata"}],
      "events_dropped" => integer,
      "failure" => nil | %{"kind", "exception", "message", "plug_status",
                           "stacktrace", "captured_by"},
      "tasks" => nil | %{"status", "processes", "events"},
      "redaction" => %{"applied", "placeholder", "sensitive_keys",
                       "redacted_values", "scrubbed_message_values"},
      "limitations" => [String.t()]
    }

# `report`

```elixir
@type report() :: %{optional(String.t()) =&gt; term()}
```

# `await_report`

```elixir
@spec await_report(String.t(), timeout()) ::
  {:ok, report()}
  | {:error,
     :invalid_trace_id
     | :timeout
     | :not_found
     | :unavailable
     | :corrupt
     | {:dropped, term()}}
```

Waits until the report for `trace_id` is retained, then returns it.

Reports are stored asynchronously after the response is sent. Instead of
polling, this subscribes to TraceGuard's report events, then checks the
store, so a report retained at any point is never missed:

  * `{:ok, report}` once it is retained;
  * `{:error, {:dropped, reason}}` if it was refused or lost, either
    while waiting or **before the call** when its drop record is still
    retained (see `report_status/1`);
  * `{:error, :corrupt}` if the adapter holds the report but can't read it;
  * `{:error, :timeout}` if none of this is observed within `timeout` ms,
    for example a report that was evicted, or whose drop record expired.

# `call`

```elixir
@spec call(GenServer.server(), term(), timeout()) :: term()
```

Like `GenServer.call/3`, carrying the caller's trace into a server that
uses `TraceGuard.Server`. See `TraceGuard.Server` for the contract.

# `clear_reports`

```elixir
@spec clear_reports() :: :ok | {:error, :unavailable}
```

Deletes all stored reports.

# `current_trace_id`

```elixir
@spec current_trace_id() :: String.t() | nil
```

Returns the trace ID of the request being handled by the calling process,
or nil outside a traced request.

# `delete_report`

```elixir
@spec delete_report(String.t()) :: :ok | {:error, :invalid_trace_id | :unavailable}
```

Deletes one stored report.

# `export_json`

```elixir
@spec export_json(String.t(), keyword()) ::
  {:ok, String.t()}
  | {:error, :invalid_trace_id | :not_found | :unavailable | Exception.t()}
```

Returns the report for `trace_id` encoded as JSON.

Accepts the same options as `TraceGuard.Exporter.JSON.encode/2`.

# `get_report`

```elixir
@spec get_report(String.t()) ::
  {:ok, report()}
  | {:error, :invalid_trace_id | :not_found | :unavailable | :corrupt}
```

Fetches the stored report for a failed request.

Only well-formed trace IDs are looked up; anything else is rejected
without touching the store. Returns `{:error, :unavailable}` (never exits)
if the storage adapter cannot answer.

# `list_reports`

```elixir
@spec list_reports(keyword()) :: [map()]
```

Lists stored reports, newest first, as summaries.

Every summary has `"trace_id"`, `"generated_at"`, `"outcome"`,
`"method"`, `"route"`, `"status"`, `"kind"`, `"exception"`,
`"captured_by"`, `"request_id"` and `"incoming_id"`.

Filters narrow the list by exact match, for discovering reports whose
response carried no `x-traceguard-id` header (exits, throws, failures
outside the router):

    TraceGuard.list_reports(incoming_id: "checkout-7f3a")   # caller's correlation ID
    TraceGuard.list_reports(request_id: "F5zX...")         # Plug.RequestId, from logs
    TraceGuard.list_reports(route: "/api/orders/:id", kind: "exit")

Supported filters: `:exception`, `:incoming_id`, `:kind`, `:method`, `:outcome`, `:request_id`, `:route`, `:status`, `:trace_id`.
Unknown filters raise `ArgumentError`. Returns `[]` if the storage adapter
is unavailable (see `report_stats/0`).

# `report_stats`

```elixir
@spec report_stats() :: map()
```

Report submission and storage statistics.

Counters since the application started: `:submitted`, `:accepted`,
`:stored`, `:dropped_overloaded`, `:dropped_other` and `:lost` (accepted,
then lost in a store restart). They are merged with the adapter's own
figures, which for the default `TraceGuard.ReportStore` are `:retained`,
`:max_reports`, `:pending`, `:max_pending_reports`, `:evicted` and
`:available`.

# `report_status`

```elixir
@spec report_status(String.t()) ::
  :stored
  | {:dropped, term()}
  | :pending
  | :unknown
  | {:error, :invalid_trace_id | :unavailable | :corrupt}
```

What TraceGuard knows about the report of `trace_id`:

  * `:stored`: the storage adapter has it now;
  * `{:dropped, reason}`: a retained drop record says it was not kept
    (`:overloaded`, `:unavailable`, `:lost` in a store restart,
    `{:adapter_failed, kind}`, ...);
  * `:pending`: accepted by a queueing adapter, outcome not yet observed;
  * `:unknown`: none of the above. The trace may not have failed, may
    not have finished, or its report may have been evicted, or its drop
    record expired (`:drop_record_ttl`) or been evicted
    (`:max_drop_records`). `:unknown` is never evidence that a report
    was or was not dropped;
  * `{:error, :invalid_trace_id}`, or `{:error, :unavailable}` /
    `{:error, :corrupt}` when the store cannot answer and nothing else is
    known.

Nothing is inferred from timing or from a report's absence: `:dropped`
is only returned from an explicit record.

# `wrap`

```elixir
@spec wrap(fun) :: fun when fun: (-&gt; any()) | (any() -&gt; any())
```

Binds `fun` to the calling process's trace, so that events emitted while
it runs in another process (typically a `Task`) join that trace.

    Task.async(TraceGuard.wrap(fn -> Repo.all(Product) end))
    Task.async_stream(ids, TraceGuard.wrap(fn id -> Repo.get(Product, id) end))

Accepts functions of arity 0 or 1. Returns `fun` unchanged when the
calling process has no active trace, so it is safe to use anywhere.

The wrapper preserves `fun`'s result and failures exactly (it re-raises
with the original stacktrace). Only the trace ID and an internal collector
reference are propagated; nothing else from the calling process is copied.
See `TraceGuard.Propagation` for the full contract.

---

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