Skip to content

Adds targeting middleware and targeting initializer #350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions Microsoft.FeatureManagement.sln
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FeatureManagement
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EvaluationDataToApplicationInsights", "examples\EvaluationDataToApplicationInsights\EvaluationDataToApplicationInsights.csproj", "{1502529E-47E9-4306-98C4-BF6CF7C7C275}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FeatureManagement.Telemetry.ApplicationInsights.AspNetCore", "src\Microsoft.FeatureManagement.Telemetry.ApplicationInsights.AspNetCore\Microsoft.FeatureManagement.Telemetry.ApplicationInsights.AspNetCore.csproj", "{C647611B-A8E5-4AD7-9DBA-60DDE276644B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -73,6 +75,10 @@ Global
{1502529E-47E9-4306-98C4-BF6CF7C7C275}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1502529E-47E9-4306-98C4-BF6CF7C7C275}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1502529E-47E9-4306-98C4-BF6CF7C7C275}.Release|Any CPU.Build.0 = Release|Any CPU
{C647611B-A8E5-4AD7-9DBA-60DDE276644B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C647611B-A8E5-4AD7-9DBA-60DDE276644B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C647611B-A8E5-4AD7-9DBA-60DDE276644B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C647611B-A8E5-4AD7-9DBA-60DDE276644B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.FeatureManagement.FeatureFilters;
using System;
using System.Threading.Tasks;

namespace Microsoft.FeatureManagement
{
/// <summary>
/// Used to add targeting information to HTTP context.
/// </summary>
public class TargetingHttpContextMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

private const string TargetingIdKey = $"Microsoft.FeatureManagement.TargetingId";

/// <summary>
/// Creates an instance of the TargetingHttpContextMiddleware
/// </summary>
public TargetingHttpContextMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) {
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<TargetingHttpContextMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
}

/// <summary>
/// Adds targeting information to the HTTP context.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> to add the targeting information to.</param>
/// <param name="targetingContextAccessor">The <see cref="ITargetingContextAccessor"/> to retrieve the targeting information from.</param>
/// <exception cref="ArgumentNullException">Thrown if the provided context or targetingContextAccessor is null.</exception>
public async Task InvokeAsync(HttpContext context, ITargetingContextAccessor targetingContextAccessor)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}

if (targetingContextAccessor == null)
{
throw new ArgumentNullException(nameof(targetingContextAccessor));
}

TargetingContext targetingContext = await targetingContextAccessor.GetContextAsync().ConfigureAwait(false);

if (targetingContext != null)
{
context.Items[TargetingIdKey] = targetingContext.UserId;
}
else
{
_logger.LogDebug("The targeting context accessor returned a null TargetingContext");
}

await _next(context);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\NugetProperties.props" />

<!-- Official Version -->
<PropertyGroup>
<MajorVersion>4</MajorVersion>
<MinorVersion>0</MinorVersion>
<PatchVersion>0</PatchVersion>
<PreviewVersion>-preview</PreviewVersion>
</PropertyGroup>

<Import Project="..\..\build\Versioning.props" />

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<SignAssembly>true</SignAssembly>
<DelaySign>false</DelaySign>
<AssemblyOriginatorKeyFile>..\..\build\Microsoft.FeatureManagement.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>

<PropertyGroup>
<Description>Microsoft.FeatureManagement.Telemetry.ApplicationInsights.AspNetCore provides a solution for tagging Application Insights telemetry with Microsoft.FeatureManagement targeting information.</Description>
<Authors>Microsoft</Authors>
<Company>Microsoft</Company>
<PackageLicenseUrl>https://licenses.nuget.org/MIT</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/Azure/AppConfiguration</PackageProjectUrl>
<PackageReleaseNotes>Release notes can be found at https://aka.ms/MicrosoftFeatureManagementReleaseNotes</PackageReleaseNotes>
<PackageTags>Microsoft FeatureManagement FeatureFlags ApplicationInsights</PackageTags>
<PackageIconUrl>https://aka.ms/AzureAppConfigurationPackageIcon</PackageIconUrl>
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.22.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Microsoft.FeatureManagement\Microsoft.FeatureManagement.csproj" />
</ItemGroup>

<PropertyGroup>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\XMLComments\$(MSBuildProjectName).xml</DocumentationFile>
</PropertyGroup>

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
<Copy SourceFiles="$(DocumentationFile)" DestinationFolder="$(OutDir)\XMLComments" SkipUnchangedFiles="false" />
</Target>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//

using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;

namespace Microsoft.FeatureManagement.Telemetry.ApplicationInsights.AspNetCore
{
/// <summary>
/// Used to add targeting information to outgoing Application Insights telemetry.
/// </summary>
public class TargetingTelemetryInitializer : TelemetryInitializerBase
{
private const string TargetingIdKey = $"Microsoft.FeatureManagement.TargetingId";

/// <summary>
/// Creates an instance of the TargetingTelemetryInitializer
/// </summary>
public TargetingTelemetryInitializer(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
}

/// <summary>
/// When telemetry is initialized, adds targeting information to all relevant telemetry.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> to get the targeting information from.</param>
/// <param name="requestTelemetry">The <see cref="RequestTelemetry"/> relevant to the telemetry.</param>
/// <param name="telemetry">The <see cref="ITelemetry"/> to be initialized.</param>
/// <exception cref="ArgumentNullException">Thrown if the any param is null.</exception>
protected override void OnInitializeTelemetry(HttpContext httpContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
{
if (telemetry == null)
{
throw new ArgumentNullException("telemetry");
}

if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}

// Extract the targeting id from the http context
string targetingId = null;

if (httpContext.Items.TryGetValue(TargetingIdKey, out object value))
{
targetingId = value?.ToString();
}

if (!string.IsNullOrEmpty(targetingId))
{
// Telemetry.Properties is deprecated in favor of ISupportProperties
if (telemetry is ISupportProperties telemetryWithSupportProperties)
{
telemetryWithSupportProperties.Properties["TargetingId"] = targetingId;
Copy link
Member

Choose a reason for hiding this comment

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

This would set in two places. is that necessary?

Copy link
Contributor Author

@rossgrambo rossgrambo Jan 17, 2024

Choose a reason for hiding this comment

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

So it was my understanding that this Interface was called differently, as it is given both a RequestTelemetry and a Telemetry. I didn't think it would be called at any point with those two items being the same, but I just did some testing, and I was incorrect!

So good callout, I removed the requestTelemetry TargetingId setting, as it was redundant. I also removed the null check on requestTelemetry, since it being null no longer matters to this function.

}
}
}
}
}