Skip to content

Integration ProxyTap Extension

aryehcitron@gmail.com edited this page Nov 3, 2026 · 16 revisions

The Kronikol.Extensions.ProxyTap package is Kronikol's first out-of-process capture component. A ProxyTap is a transparent HTTP tee: it listens on a port, forwards every request byte-for-byte to the real service, and records a copy of each exchange as a Kronikol request/response pair attributed to the running test. Nothing inside the services needs to change.

Use it when the system under test is polyglot, third-party or legacy — services you cannot add TestTrackingMessageHandler / TestTrackingContextMiddleware to — and you still want per-test sequence diagrams of every hop.

Three capture topologies. Kronikol's classic model (topology A) instruments the system under test: handlers and middleware inside the backend record the calls. The proxy-tap model (topology B) leaves the backend untouched: a browser or test fixture stamps identity headers, they ride the real request through the services, and a tap on each hop is the sink. The span model (topology C, Integration Otlp Extension) tees the OTLP traces the services already export and maps their client spans. All three produce the same RequestResponseLog entries and the same reports.

Tapping a database hop? ProxyTap speaks HTTP. For the Redis and MongoDB hops of the same stack use Integration TcpTap Extension — the same tee shape and the same options, over a byte-for-byte TCP tee with RESP and OP_MSG decoders, producing arrows identical to the in-process Integration Redis Extension / Integration MongoDB Extension.

When a hop cannot be proxied — a binary or compressed protocol, an in-process driver, a cloud SDK — use Integration Otlp Extension instead, or as well: it attributes by W3C trace id rather than by header, and kronikol ingest --merge-duplicates folds the two views of a call that both taps saw into one arrow (see Ingesting External Captures).


Install

dotnet add package Kronikol.Extensions.ProxyTap

No ASP.NET Core host is required — the tap is built on HttpListener and binds localhost without URL ACLs.


How It Works

browser/test ──► tap :8082 ──► graphql :8081 ──► tap :9192 ──► myDotnetService :9091 ──► ...
                  │ records                        │ records
                  ▼                                ▼
            RequestResponseLogger  /  NDJSON file  (IRequestResponseSink)

For every exchange the tap:

  1. Resolves the test identity from the inbound request — test-tracking-current-test-name / test-tracking-current-test-id (the same headers TestTrackingContextMiddleware reads), then any configured fallback headers, then (by default) the W3C traceparent trace id. The traceparent fallback is what makes browser-driven suites work: the test mints the trace, every browser request carries it, and downstream hops that drop the custom headers still carry traceparent.
  2. Re-injects the four correlation headers (test-tracking-current-test-name, -current-test-id, -caller-name, -trace-id) on the forwarded request when missing, so attribution survives a hop that would otherwise drop them. A name or id that is not plain ASCII is read and written in the UTF-8'' form (HTTP Tracking Setup › Header values); until 4.12.1 the tap read it raw and re-injected ? for each such character.
  3. Forwards the original bytes (hop-by-hop headers handled; Host rewritten to the target). When an ActivityListener is attached to the Kronikol.ProxyTap source it emits a server span (parented on the inbound traceparent) and a client span, and re-parents the forwarded traceparent on the client span — the downstream service then nests under the tap in your distributed trace. Without a listener it is fully transparent. The forwarded traceparent keeps the caller's sampled flag when the tap's client span is not recorded (Kronikol's own internal-flow listener samples with AllData, so in a test process it is not), and says sampled for a trace the tap starts; when a listener drops the server span, the client span is parented on the caller's traceparent itself. Both are from 4.18.3: before, a tap in a test process forwarded -00, so a service with a parent-based sampler recorded nothing, and a sampler that dropped the server span replaced the caller's trace. From 4.19.4 the forward runs none of the HttpClient instrumentation in the tap's process: OpenTelemetry's instrumentation put a span of its own in place of the forwarded traceparent, which started a new trace with nothing listening to the tap and went out -00 beside Kronikol's listener; listen to Kronikol.ProxyTap for the forward's span. A tap started under an activity no longer forwards that activity's trace and baggage either: each request starts with no current activity.
  4. Responds first, records second — capture decodes (gzip/deflate/br) and caps a copy of both bodies after the response has been written back, so it never sits on the request path.
  5. Redacts secrets at capture — authorization, proxy-authorization, cookie, set-cookie, x-api-key, … are replaced with [REDACTED] (or dropped) before the entry reaches any sink. This is the security boundary: the secret never enters the in-memory store, TestRunReport.json, or an NDJSON file. (ExcludedHeaders only hides headers in the diagram — see Capture-Time-Redaction.)
  6. Logs a Request and a Response entry (shared TraceId/RequestResponseId, ServiceName/CallerName from the options, status, timestamps, ActivityTraceId/ActivitySpanId) to the configured sink.

Requests with no resolvable identity (health probes, warm-ups) are forwarded but not captured unless CaptureUnattributedRequests is set.


Quick Start

using Kronikol.Extensions.ProxyTap;

await using var tap = new ProxyTap(new ProxyTapOptions
{
    ListenPort = 8082,
    ForwardBaseUri = new Uri("http://localhost:8081"),
    CallerName = "web",        // the participant that dials the tap
    ServiceName = "graphql",   // the participant the tap forwards to
});
await tap.StartAsync();

// Point the caller at :8082 instead of :8081 — it sees identical traffic.

Then generate reports exactly as you would for in-process tracking (ReportGenerator.CreateStandardReportsWithDiagrams(features, start, end, options)); every tapped call renders as an arrow between web and graphql in the scenario whose Id equals the resolved test id.

With dependency injection

services.AddProxyTapTestTracking(o =>
{
    o.ListenPort = 8082;
    o.ForwardBaseUri = new Uri("http://localhost:8081");
    o.CallerName = "web";
    o.ServiceName = "graphql";
});

One IHostedService per tap starts it with the host and stops it on shutdown. Call it once per hop (a ProxyTap per listen → forward pair); the taps are resolvable as IEnumerable<ProxyTap>.

Stopping a tap

await tap.DisposeAsync() settles the exchanges in flight, stops listening, gives the port back and releases the upstream client. Since 4.22.2 it settles each exchange before the listener closes, so every caller hears what became of its request: one whose body is still arriving is answered 503 Service Unavailable at once (on Windows its connection is reset, as http.sys writes nothing for an aborted request), a forward still waiting on the real service is cut short and answered the 502 its record names, an answer already in hand has up to 2 s to finish so its capture lands, and a request that arrives meanwhile, or that the stop reaches before its forward begins (behind a slow IdentityResolver, say), is answered 503 and neither forwarded nor recorded. An answer written while the tap stops closes its connection, and DisposeAsync returns within about 2 s. Before 4.22.2 the listener closed first: on Linux and macOS that answered a caller still sending its body 200 OK, for a request the real service never saw, after waiting a second for each such caller, and an answer still being written was cut short. It is safe to await more than once, safe on a tap that never started or whose StartAsync failed, and — since v3.20.1 — it will not throw because something else claimed the port the moment it was freed. Before that, disposal released the listener with Stop() then Close(), and off Windows the second call re-bound the port it had just given up: a parallel test or an outbound connection taking that port in between failed the disposal with HttpListenerException: Address already in use, in a test that had already passed (#74).

A tap starts once. Since 4.26.3 a second StartAsync throws InvalidOperationException, one after DisposeAsync throws ObjectDisposedException, and a start and a dispose that race leave nothing listening. The token StartAsync takes aborts a start that has not begun and nothing after it; before 4.26.3 it was linked into the tap's lifetime, so cancelling it once the tap had started left the tap listening and answering every request 503. A wait for a request that fails while the tap runs is logged and tried again, with pauses of up to 1 s; before 4.26.3 it ended the tap's accept loop, and the tap went on listening with nothing to take a request. A request the tap has taken but not yet handed on when a stop begins is settled like any other, never left to the listener's close, which answered it 200 OK on Linux and macOS.

A caller that hangs up

Since 4.19.2 a caller that goes away is let go at once. On Linux and macOS the HttpListener behind the tap holds a connection until its response is closed or aborted, and before 4.19.2 a caller that hung up while its answer was being written, in the middle of its body, or before a failed forward was answered kept its connection open until the tap was disposed (#172). Windows (http.sys) drops such a request itself.

  • A request that never arrives whole, because its caller hung up mid-body, is not forwarded, not recorded and not counted. A caller still listening is answered 400 Bad Request, on Windows too (since 5.28.2: an abort there writes nothing, so a failed body read reset the caller). One that stops sending without hanging up is cut after CallerStallTimeout (4.23.0; see A caller that stalls).
  • A caller that hangs up while its answer is being written: the exchange is still recorded and counted as handled.
  • A forward that fails is answered 502 Bad Gateway and counted in ForwardFailures, whether or not its caller is still there, and ProxyTap.Diagnostics() reports the count (see Diagnostics and Debugging).

A caller that stalls

Since 4.23.0 a caller that stops moving bytes without hanging up is cut after CallerStallTimeout, 100 s by default. Before 4.23.0 a caller that stopped sending in the middle of its body was held on Linux and macOS until the tap was disposed (on Windows http.sys resets it after about two minutes), and one that stopped reading a large answer was held on both platforms, its request still published as in flight.

  • The limit times silence, not the whole transfer: every read of the request body and every write of the answer that moves bytes starts the wait again, so a slow caller that keeps moving is never cut. The tap reads the body and writes the answer in pieces of 16 KiB (an answer's last piece up to 32 KiB), so a caller has to move one piece per limit, about 164 bytes a second at the default.
  • A caller cut while it sends its body is answered 408 Request Timeout and its connection closed (on Windows, where http.sys writes nothing on an abort, the connection is reset). The request is neither forwarded nor recorded.
  • A caller cut while it reads its answer has its connection closed. The exchange is recorded, as one whose caller hangs up mid-answer, and its in-flight identity is released.
  • Each cut is counted in CallerTimeouts, logged (proxy-tap caller stalled 00:01:40 sending its request body; not forwarded, answered 408 and closed, which on Windows ends not forwarded, connection reset) and reported by Diagnostics() on a CaptureDegraded line that says how many callers were cut in each phase.
  • The forward is ForwardTimeout's, and a connection idle between requests is the listener's: neither is a stall.
  • No limit fires while a debugger is attached to the tap's process. A service paused in a debugger in a process of its own (a container, or a host the run starts) is cut after the limit, so set CallerStallTimeout to null for such a session. null or Timeout.InfiniteTimeSpan turns the limit off, and zero or a negative value fails at start.

Stamping identity from the test

  • .NET + Playwright — use Integration Playwright (browser.NewTrackedContextAsync(identity)): the four headers plus a traceparent land on every browser request.
  • Any other client — send the headers named in Kronikol.Constants.TestTrackingHttpHeaders, or just a W3C traceparent whose trace id you use as the scenario id.
  • In-process HttpClient — TestTrackingMessageHandler already stamps them.

ProxyTapOptions (the topology schema)

Option Default Meaning
ListenPort / ListenHost — / localhost Where the tap listens.
ForwardBaseUri — The real service, http or https (scheme + host + port). Every request goes to its scheme and authority with the request's own path and query, whatever host the request target names; a path in the URI is not used. Since 4.19.1 any other scheme fails at start.
CallerName / ServiceName — The two participants this hop joins.
DependencyCategory / CallerDependencyCategory null A DependencyCategories value for shape/colour (e.g. BigQuery, AI).
CaptureBodies / BodyCapBytes true / 65536 Capture bodies; truncate decoded text beyond the cap (…truncated (N chars total)). A negative cap fails at start (4.22.2).
HeaderPolicy AllExceptSecrets All, AllExceptSecrets, Whitelist (+ HeaderWhitelist), None.
SecretDenylist / DropSecretHeaders / RedactedValue CaptureRedaction.DefaultSecretHeaders / false / [REDACTED] Capture-time secret handling.
ReinjectCorrelation true Re-stamp missing test-tracking-* headers on the forwarded request.
IdentityFromTraceparent true Use the inbound traceparent trace id as the test id when no id header is present.
TestNameHeaderFallbacks / TestIdHeaderFallbacks empty Extra headers to read name/id from (legacy header names).
IdentityResolver null Custom (headers, traceparent) → (name, id)? override.
TraceIdFromIdentity false From 4.19.0. Forward a request that brings no traceparent under a trace whose id is the test id, when the tap resolves the identity and the id is a W3C trace id as written; see A caller that cannot send a trace.
FallbackTestName Unknown Name when only an id is known (the tests file / kronikol ingest normalises it).
CaptureUnattributedRequests false Capture requests with no identity (under FallbackTestName).
FallbackTestId null With CaptureUnattributedRequests, use this fixed id for all unattributed traffic (one "outside any test" scenario) instead of a fresh id per request.
Sink RequestResponseLoggerSink.Instance Where entries go; combine with NdjsonInteractionWriter (or an OtlpExportSink, 3.0.60+) via CompositeRequestResponseSink.
Phase Unknown TestPhase stamped on entries.
EmitActivities / SynthesizeTraceparent true / true Spans on ProxyTap.ActivitySource; mint a traceparent when the caller sent none (its trace is random, or the test id with TraceIdFromIdentity).
ForwardTimeout / ConnectTimeout 200 s / 5 s Upstream deadlines. From 4.19.5 a forward that misses one is recorded as a failed call naming it; see When the upstream fails. Timeout.InfiniteTimeSpan, or int.MaxValue milliseconds (24.8 days) or more, means no deadline; zero and other negative values fail at start (4.22.2). Before 4.22.2 an infinite ForwardTimeout cut every forward at 10 s and blamed ConnectTimeout.
CallerStallTimeout 100 s From 4.23.0. How long a caller may move no bytes while it sends its body or reads its answer before the tap cuts it; null or Timeout.InfiniteTimeSpan for none. See A caller that stalls.
InFlightRegistry null Publish the identity of every request in flight to ServiceName, so a capturer that cannot read headers can attribute what it sees — see In-flight identity.
Log / Name null Diagnostics callback and display name. Whatever the callback throws is ignored (4.22.2), so one bound to a test's output that has ended changes nothing the tap does.

A caller that cannot send a trace

A browser test mints the trace its requests carry with the test id as the trace id, so every hop behind the tap, and every capturer that attributes by trace id (another tap's IdentityFromTraceparent, the OTLP tap's AttributeByTraceId), files the work under the test. A caller that cannot send a traceparent or the test-tracking-* headers, such as a mobile app, has no trace to carry. The host knows whose call it is, so it names the test through IdentityResolver, and from 4.19.0 TraceIdFromIdentity makes the tap forward the call under the test's trace:

(string Name, string Id)? runningTest = null; // your suite sets it as each test starts, with Id = Guid.NewGuid().ToString("N")

await using var tap = new ProxyTap(new ProxyTapOptions
{
    ListenPort = 5100,
    ForwardBaseUri = new Uri("http://localhost:5000"),
    CallerName = "App",
    ServiceName = "Api",
    IdentityResolver = (_, _) => runningTest,
    TraceIdFromIdentity = true,
});
  • The test id must be a W3C trace id as written: 32 lower-case hex digits, not all zero, such as Guid.NewGuid().ToString("N"). The readers behind the tap turn a trace id back into a test id by its text, so an id written any other way (a hyphenated GUID, upper case, xUnit v3's or NUnit's ids) keeps a random trace. The tap counts those requests in Diagnostics() as OptionNotApplied and logs the first.
  • A request that brings its own traceparent keeps it. An unattributed request (CaptureUnattributedRequests) and an ignored one (test-tracking-ignore) keep a random trace.
  • With a listener on Kronikol.ProxyTap, each call's server span is a root of the test's trace. Without one, the forwarded traceparent names the test's trace and a parent span of its own, as a browser test's does. With SynthesizeTraceparent off nothing is sent, and the tap's records still carry the test's trace.
  • The trace goes out sampled, so a parent-based sampler records it whatever its ratio, as it records a browser test's.
  • Every call of the test then shares one trace. A call's internal-flow popup still shows only its own spans when the calls overlap in time (from 4.18.3).

In-flight identity: lending a database tap an identity

Added in v3.0.45

A tap on an HTTP hop reads the test identity straight off the request headers. A tap on a database connection cannot: the Redis and MongoDB wire protocols have nowhere to put a test-tracking-current-test-id, and the connection is pooled besides. The only honest source left is which test was the service handling when the query left it — and the HTTP tap in front of that service knows.

InFlightIdentityRegistry is that channel. Point one or more taps at it and each registers every request it forwards, for as long as it is in flight:

var inFlight = new InFlightIdentityRegistry();          // or InFlightIdentityRegistry.Shared

services.AddProxyTap(o =>
{
    o.CallerName = "graphql";
    o.ServiceName = "myDotnetService";
    o.InFlightRegistry = inFlight;                      // publish who myDotnetService is working for
    // …
});

// The database capturer asks, per captured command:
var identity = inFlight.MostRecentFor("myDotnetService");
var testId = identity?.Id ?? fallbackTestId;
Member
Register(serviceName, testName, testId) Returns a handle; dispose it when the request completes. The tap does this in a using covering every exit, so a failed forward cannot leave a stale identity behind.
MostRecentFor(serviceName) The identity of the most recently started request still in flight, or null when the service is idle. A caller that stops reading its answer keeps its request in flight until CallerStallTimeout cuts it (before 4.23.0, until the tap was disposed). Most recent, not first: a call a service makes belongs to the request it is currently handling, and nested work always starts after its cause.
CountFor(serviceName) / ActiveServices Diagnostics.
Clear() Forget everything (tests, restarts).
Shared A process-wide instance for hosts that would rather not thread one through.

Service names match case-insensitively, and the whole thing is thread-safe.

Prefer ingest-time window attribution. With one worker MostRecentFor is exact; with several it is a best guess, and it couples the database tap to an HTTP tap in the same process. kronikol ingest --attribute-by-window reconstructs the same answer deterministically from the tests NDJSON's timeline, works for any capturer in any process, and is documented in Ingesting External Captures. The registry is the live option for suites that genuinely run tests in parallel; nothing is published unless InFlightRegistry is set.


When the upstream fails

From 4.19.5, a forward that fails is drawn as a failed call, where before it was missing from the diagram.

  • What the caller gets. 502 Bad Gateway with {"error":{"code":502,"message":"proxy-tap: …"}}. The message is the cause: the exception's message chain (… Caused by: …), or for a timeout proxy-tap: no answer from {host} within ForwardTimeout ({t}) or proxy-tap: could not connect to {host} within ConnectTimeout ({t}), then the chain.
  • What is recorded. When the request names a test (or CaptureUnattributedRequests is on), both halves are recorded, as the in-process handler records a failed send: the request as it was sent, and a response whose status is the exception's type (!HttpRequestException, !TaskCanceledException), whose content is the 502 body and whose Error holds the cause. The diagram labels the return arrow with that status and shows the body in its note; the data files and kronikol query http carry Error. A forward cut short by the tap's own disposal is recorded as proxy-tap: the tap stopped before {ServiceName} answered.
  • Spans. The client span ends with an error status, the cause as its description and error.type in .NET's own words (connection_error, name_resolution_error, response_ended, or the exception's type name). The server span ends with an error status and http.response.status_code 502.
  • Counters and diagnostics. ForwardFailures counts the upstream's failures, not the tap stopping, a caller hanging up or a caller cut for stalling (CallerTimeouts, on a CaptureDegraded line of its own). Diagnostics() reports them on one CaptureDegraded line, which ends by saying which were recorded (each is recorded as a failed call, they carried no test identity and were not recorded, or a count of each). By the time the caller has its 502, the failure is recorded, counted and logged (proxy-tap error:).
  • Capture faults. An IdentityResolver, sink, body decoder or ActivityListener that throws never changes what the caller gets. A throwing resolver leaves the built-in rules to decide; every such fault is counted on a CaptureDegraded line of its own (N capture fault(s): … (the first: Type, message)).

Same process or different process?

RequestResponseLogger is a process-wide static store, so a tap running in the same process as report generation (a test host, an orchestrator) can log directly — the default sink. A tap running in another process (a sidecar, a polyglot harness) cannot reach that store: give it an NdjsonInteractionWriter sink and replay the file with kronikol ingest (see Ingesting External Captures). Use both at once to get the live in-process report and a replayable artifact:

using var file = new NdjsonInteractionWriter(".logs/taps/web-graphql.ndjson");
o.Sink = new CompositeRequestResponseSink(RequestResponseLoggerSink.Instance, file);

A third destination (3.0.60+): compose an OtlpExportSink into the same CompositeRequestResponseSink and every tapped call also streams live to an OTLP collector as an OpenTelemetry span; see Exporting to OpenTelemetry.


Legible diagrams for chatty hops

Polling and retry traffic produces long runs of identical arrows. Enable collapsing on the report: ReportConfigurationOptions.CollapseConsecutiveIdenticalCalls = true (+ CollapseThreshold, MaxArrowsPerDiagram) — see Report Configuration. A scenario whose id matched no tapped call shows an explicit No interactions captured marker rather than an empty section.


Limitations

  • HTTP/1.1 only (the HttpListener front end); HTTP/2 or gRPC-over-h2c hops need a different tee.
  • The tap is a participant in the trace: latencies you see include the tap's own (small) overhead.
  • A caller that stalls inside its request head is out of CallerStallTimeout's reach: the listener reads the head before the tap sees the request, and the managed listener (Linux, macOS) times only the wait for a head's first bytes (90 s on a new connection, 15 s on a kept-alive one), so a caller that sends part of a head and stops is held until the tap is disposed. On Windows http.sys resets it after about two minutes.
  • http.sys keeps its own timers on Windows. It resets a stalled head, body or idle connection at about two minutes and a stalled piece of an answer at about 115 s, so a CallerStallTimeout longer than that does not hold such a caller longer there, and that reset is not counted in CallerTimeouts.
  • A service paused in a debugger in another process (a container, or a host the run starts) is cut after CallerStallTimeout like any stalled caller: the tap sees only a debugger attached to its own process. Set the option to null for such a session.
  • On Linux and macOS a chunked request whose caller hangs up (sends its FIN) before the last chunk reaches the service as if whole: the managed HttpListener ends the read without an error, and nothing on the request tells such a body from a whole one (dotnet/runtime#135680). On Windows http.sys answers it 400 and nothing is forwarded.
  • The tap cannot repair a downstream service that resets trace context on its own (e.g. a Java agent starting a fresh root for an outbound call); such legs need the service to forward the id — see the generic alternative (header re-injection) before patching anything.

Home · 🔍 Search this wiki Full-text search across every page. The “Pages” list above matches page and heading names, not page content.


Demo


Getting Started

Common Tasks

Integration Guides

Uninstrumentable / polyglot backends

Extensions

Configuration

Features

Reference

Clone this wiki locally