Skip to content

feat: Add server-side request context support#198

Open
dustinbyrne wants to merge 35 commits into
mainfrom
feat/request-context
Open

feat: Add server-side request context support#198
dustinbyrne wants to merge 35 commits into
mainfrom
feat/request-context

Conversation

@dustinbyrne
Copy link
Copy Markdown
Contributor

@dustinbyrne dustinbyrne commented May 6, 2026

💡 Motivation and Context

Add ASP.NET Core request-scoped PostHog context so server-side captures and exception events during a request can inherit useful request metadata and, when enabled, PostHog tracing headers (X-PostHog-Distinct-Id, X-PostHog-Session-Id).

This aligns .NET behavior with the server-side request context guidelines while keeping the context implementation internal to avoid expanding the public .NET API surface.

Middleware behavior:

  • UsePostHogRequestContext now always wraps ASP.NET Core requests and applies request metadata ($current_url, $request_method, $request_path, $user_agent, $ip) to captures made during the request.
  • PostHog tracing header identity/session usage is controlled separately via options.UseTracingHeaders.
  • Exception capture only adds exception-specific metadata; request context identity/session/properties are applied by the core capture path. ASP.NET Core HttpContext.User is not treated as a PostHog distinct ID automatically.

💚 How did you test it?

  • dotnet build PostHog.sln --no-restore
  • dotnet test tests/UnitTests.AspNetCore/UnitTests.AspNetCore.csproj --no-restore
  • dotnet test tests/UnitTests/UnitTests.csproj --no-restore --framework net8.0 --filter "FullyQualifiedName~PostHogContextTests|FullyQualifiedName~FeatureFlagEvaluationsTests"

Note: full UnitTests net8 currently has two unrelated exception stack-frame assertion failures in this environment.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran pnpm changeset to generate a changeset file

@dustinbyrne dustinbyrne force-pushed the feat/request-context branch from 85697e0 to 118ff9c Compare May 6, 2026 19:12
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 6, 2026

posthog-dotnet Compliance Report

Date: 2026-05-18 18:06:40 UTC
Duration: 530ms

⚠️ Some Tests Failed

2/16 tests passed, 14 failed


Feature_Flags Tests

⚠️ 2/16 tests passed, 14 failed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 44ms
Request Payload.Flags Request Uses V2 Query Param 22ms
Request Payload.Flags Request Hits Flags Path Not Decide 5ms
Request Payload.Flags Request Omits Authorization Header 4ms
Request Payload.Token In Flags Body Matches Init 5ms
Request Payload.Groups Round Trip 4ms
Request Payload.Groups Default To Empty Object 5ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 4ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 5ms
Request Payload.Disable Geoip Omitted Defaults To False 4ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 5ms
Request Lifecycle.No Flags Request On Init Alone 3ms
Request Lifecycle.No Flags Request On Normal Capture 180ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 6ms
Request Lifecycle.Mock Response Value Is Returned To Caller 5ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 4ms

Failures

request_payload.request_with_person_properties_device_id

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_uses_v2_query_param

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_hits_flags_path_not_decide

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flags_request_omits_authorization_header

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.token_in_flags_body_matches_init

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.groups_round_trip

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.groups_default_to_empty_object

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.person_properties_distinct_id_auto_populated_when_caller_omits_it

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.disable_geoip_false_propagates_as_geoip_disable_false

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.disable_geoip_omitted_defaults_to_false

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_payload.flag_keys_to_evaluate_contains_only_requested_key

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_lifecycle.two_flag_calls_produce_two_remote_requests

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

request_lifecycle.mock_response_value_is_returned_to_caller

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

side_effect_events.get_feature_flag_captures_feature_flag_called_event

404, message='Not Found', url='http://sdk-adapter:8080/get_feature_flag'

Comment thread src/PostHog/Capture/CaptureExtensions.cs Outdated
@dustinbyrne dustinbyrne marked this pull request as ready for review May 6, 2026 20:08
@dustinbyrne dustinbyrne requested review from a team and haacked as code owners May 6, 2026 20:08
@dustinbyrne dustinbyrne changed the title Add server-side request context support feat: Add server-side request context support May 6, 2026
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented May 6, 2026

Prompt To Fix All With AI
Fix the following 4 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 4
src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs:115-120
`$current_url` omits the query string. PostHog's other SDKs set `$current_url` to the full URL including query parameters (UTM tags, pagination state, etc.), so omitting it will cause analytics discrepancies. `request.QueryString.ToUriComponent()` returns an empty string when there is no query string, so appending it is always safe.

```suggestion
        return string.Concat(
            request.Scheme,
            "://",
            request.Host.ToUriComponent(),
            request.PathBase.ToUriComponent(),
            request.Path.ToUriComponent(),
            request.QueryString.ToUriComponent());
```

### Issue 2 of 4
src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs:77-78
`StringValues.IsNullOrEmpty` returns `true` whenever `Count == 0` (or the single value is empty), so after it returns `false`, `Count` is always ≥ 1. The `values.ToString()` branch is therefore unreachable dead code.

```suggestion
        return SanitizeValue(values[0]);
```

### Issue 3 of 4
src/PostHog.AspNetCore/Tracing/PostHogRequestContextMiddlewareExtensions.cs:20-23
When `app` is null, `return app!` uses the null-forgiving operator to push a `null` through a non-nullable return type. Any subsequent chained call on the result would throw a `NullReferenceException`. `ArgumentNullException.ThrowIfNull` is the idiomatic guard here and gives a better error message.

```suggestion
        ArgumentNullException.ThrowIfNull(app);
```

### Issue 4 of 4
tests/UnitTests/PostHogContextTests.cs:103-123
`MissingDistinctIdCreatesPersonlessContext` and `ExplicitProcessPersonProfileOverridesPersonlessDefault` exercise the same method with different `properties` inputs and assert on the same output key — a good fit for a `[Theory]` per the project's preference for parameterised tests.

```suggestion
    [Theory]
    [InlineData(null, false)]
    [InlineData(true, true)]
    public void PersonlessContextSetsProcessPersonProfile(bool? explicitOverride, bool expectedValue)
    {
        var properties = explicitOverride.HasValue
            ? new Dictionary<string, object> { ["$process_person_profile"] = explicitOverride.Value }
            : null;

        var context = PostHogContextHelper.ResolveCaptureContext(distinctId: null, properties: properties);

        Assert.True(Guid.TryParse(context.DistinctId, out _));
        Assert.True(context.IsPersonless);
        Assert.NotNull(context.Properties);
        Assert.Equal(expectedValue, (bool)context.Properties["$process_person_profile"]);
    }
```

Reviews (1): Last reviewed commit: "Move request context overloads to ASP.NE..." | Re-trigger Greptile

Comment thread src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs
Comment thread src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs Outdated
Comment thread src/PostHog.AspNetCore/Tracing/PostHogRequestContextMiddlewareExtensions.cs Outdated
Comment thread tests/UnitTests/PostHogContextTests.cs Outdated
@dustinbyrne dustinbyrne force-pushed the feat/request-context branch from 73cb36d to df0ca2f Compare May 6, 2026 20:34
Comment on lines +16 to +20
public static IApplicationBuilder UsePostHogRequestContext(
this IApplicationBuilder app,
Action<PostHogRequestContextOptions>? configure = null)
{
ArgumentNullException.ThrowIfNull(app);
Copy link
Copy Markdown
Contributor Author

@dustinbyrne dustinbyrne May 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We typically avoid throwing, but this one seems unavoidable. If app is null, there's no easy way to recover.

Considering this would be called on initialization, avoiding an exception here could mask some serious issues.

Copy link
Copy Markdown
Contributor

@haacked haacked left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solid PR overall. A handful of non-blocking suggestions inline; the highest-leverage ones are the duplicate $session_id constant, the empty-string divergence across the three flag entrypoints, and the query-string secrets surface in $current_url.

Comment thread src/PostHog.AspNetCore/Tracing/PostHogRequestPropertyNames.cs Outdated
Comment thread src/PostHog/PostHogClient.cs
Comment thread src/PostHog/PostHogContext.cs Outdated
Comment thread src/PostHog/PostHogContext.cs Outdated
Comment thread src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs
Comment thread tests/UnitTests.AspNetCore/PostHogRequestContextMiddlewareTests.cs Outdated
Comment thread tests/UnitTests/PostHogContextTests.cs
Comment thread tests/UnitTests.AspNetCore/PostHogRequestContextMiddlewareTests.cs
Comment thread src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs
Comment thread src/PostHog.AspNetCore/Tracing/PostHogTracingHeaders.cs Outdated
@marandaneto
Copy link
Copy Markdown
Member

@haacked did the review already so skipping until its good to go, happy to do a final review if needed otherwise his approval should be enough!

@github-actions
Copy link
Copy Markdown
Contributor

This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, post a comment or remove the stale label – otherwise this will be closed in another week.

@github-actions github-actions Bot added the stale label May 15, 2026
@github-actions github-actions Bot removed the stale label May 19, 2026
@marandaneto marandaneto requested a review from haacked May 22, 2026 14:08
this IPostHogClient client,
string eventName)
{
var checkedClient = NotNull(client);
Copy link
Copy Markdown
Member

@marandaneto marandaneto May 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this will crash the app, better to just return false instead, check the other callsites

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants