Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,44 @@ internal static bool TryExtractBaggage(string? baggageString, out IEnumerable<Ke
// value = 0*255(chr) nblk-chr
// nblk-chr = %x21-2B / %x2D-3C / %x3E-7E
// chr = %x20 / nblk-chr
// A single incoming request commonly fans out to several outgoing calls that
// all inject the same (unmodified) Activity.TraceStateString (see InjectTraceState),
// typically all from the same thread for a given request. Cache the last
// (input, output) pair per thread to skip re-parsing and rebuilding it every time.
[ThreadStatic]
private static string? t_lastRawTraceState;
[ThreadStatic]
private static string? t_lastValidatedTraceState;
Comment thread
martincostello marked this conversation as resolved.

internal static string? ValidateTraceState(string? traceState)
{
if (string.IsNullOrEmpty(traceState))
{
return null;
}

// ValidateTraceState also runs on the raw carrier value from an incoming (untrusted)
// request, via ExtractTraceIdAndState. Don't let an arbitrarily large or malformed
// value get rooted in per-thread state for the thread's lifetime just because it was
// seen once - only cache inputs already within a valid tracestate's own size limit.
if (traceState.Length > MaxTraceStateEncodedLength)
{
return ValidateTraceStateCore(traceState);
}

if (ReferenceEquals(traceState, t_lastRawTraceState))
{
return t_lastValidatedTraceState;
}

string? validated = ValidateTraceStateCore(traceState);
t_lastRawTraceState = traceState;
t_lastValidatedTraceState = validated;
return validated;
}

private static string? ValidateTraceStateCore(string traceState)
{
int entries = 0;
using ValueStringBuilder vsb = new ValueStringBuilder(stackalloc char[Math.Min(traceState.Length, MaxTraceStateEncodedLength)]);

Expand Down
Loading