-
Notifications
You must be signed in to change notification settings - Fork 40
feat: implement OneDSTelemetryService for download tracking and add t… #261
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
Open
IEvangelist
wants to merge
4
commits into
main
Choose a base branch
from
add-dwnlds
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+159
−12
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9251e4e
feat: implement OneDSTelemetryService for download tracking and add t…
IEvangelist c781fa6
fix: ensure early return in TrackEvent method for non-production envi…
IEvangelist 4c6c788
refactor: update OneDSTelemetryService to implement IAsyncDisposable …
IEvangelist 1d2d9d5
fix: format spacing in TrackDownload method call for consistency
IEvangelist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| global using StaticHost; | ||
|
|
||
| global using OpenTelemetry; | ||
| global using OpenTelemetry.Metrics; | ||
| global using OpenTelemetry.Trace; | ||
|
|
||
| global using Microsoft.ApplicationInsights; | ||
| global using Microsoft.ApplicationInsights.DataContracts; | ||
| global using Microsoft.ApplicationInsights.Extensibility; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| namespace StaticHost; | ||
|
|
||
| /// <summary> | ||
| /// Service for tracking events to 1DS/Application Insights. | ||
| /// Uses the same instrumentation key as the client-side 1ds.js. | ||
| /// </summary> | ||
| internal sealed class OneDSTelemetryService : IAsyncDisposable | ||
| { | ||
| private readonly TelemetryClient _telemetryClient; | ||
| private readonly TelemetryConfiguration _configuration; | ||
| private readonly ILogger<OneDSTelemetryService> _logger; | ||
| private readonly string _environment; | ||
|
|
||
| // This key is intended to be public, same as in 1ds.js | ||
| private const string InstrumentationKey = "1c6ad99c3e274af7881b9c3c78eed459-573e6b44-ab25-4e60-97ad-7b7f38f0243a-6923"; | ||
|
|
||
| private const string AspireDotDev = "https://aspire.dev"; | ||
|
|
||
| public OneDSTelemetryService( | ||
| ILogger<OneDSTelemetryService> logger, | ||
| IWebHostEnvironment hostEnvironment) | ||
| { | ||
| _logger = logger; | ||
| _environment = hostEnvironment.IsProduction() ? "PROD" : "PPE"; | ||
|
|
||
| _configuration = new TelemetryConfiguration | ||
| { | ||
| ConnectionString = $"InstrumentationKey={InstrumentationKey}" | ||
| }; | ||
|
|
||
| _telemetryClient = new TelemetryClient(_configuration); | ||
| _telemetryClient.Context.GlobalProperties["env"] = _environment; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Tracks a download event for the specified script. | ||
| /// </summary> | ||
| /// <param name="context">The HTTP context for extracting request metadata.</param> | ||
| /// <param name="scriptName">The name of the script being downloaded.</param> | ||
| public void TrackDownload(HttpContext context, string scriptName) | ||
| { | ||
| TrackEvent("Download", context, new Dictionary<string, string> | ||
| { | ||
| ["behavior"] = "DOWNLOAD", | ||
| // ["actionType"] = "CL", - dot.net has this, but I think it implies user click, which is not the case for aspire.dev | ||
| ["scriptName"] = scriptName | ||
| }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Tracks a custom event with the specified name and properties. | ||
| /// </summary> | ||
| /// <param name="eventName">The name of the event to track.</param> | ||
| /// <param name="context">The HTTP context for extracting request metadata.</param> | ||
| /// <param name="additionalProperties">Optional additional properties to include with the event.</param> | ||
| public void TrackEvent( | ||
| string eventName, | ||
| HttpContext context, | ||
| IDictionary<string, string>? additionalProperties = null) | ||
| { | ||
| var origin = $"{context.Request.Scheme}://{context.Request.Host}"; | ||
|
|
||
| // Skip tracking for non-production origins (matching 1ds.js behavior) | ||
| if (_environment is not "PROD" || | ||
| !origin.Equals(AspireDotDev, StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| _logger.LogSkippingTracking(origin); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var eventTelemetry = new EventTelemetry(eventName) | ||
| { | ||
| Properties = | ||
| { | ||
| ["env"] = _environment, | ||
| ["userAgent"] = context.Request.Headers.UserAgent.ToString(), | ||
| ["referer"] = context.Request.Headers.Referer.ToString(), | ||
| ["origin"] = origin | ||
| } | ||
| }; | ||
|
|
||
| // Add client IP if available (for geographic insights) | ||
| var clientIp = context.Connection.RemoteIpAddress?.ToString(); | ||
| if (!string.IsNullOrEmpty(clientIp)) | ||
| { | ||
| eventTelemetry.Properties["clientIp"] = clientIp; | ||
| } | ||
|
|
||
| // Add any additional properties | ||
| if (additionalProperties is not null) | ||
| { | ||
| foreach (var (key, value) in additionalProperties) | ||
| { | ||
| eventTelemetry.Properties[key] = value; | ||
| } | ||
| } | ||
|
|
||
| _telemetryClient.TrackEvent(eventTelemetry); | ||
|
|
||
| _logger.LogTrackedEvent(eventName); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogTrackingFailed(eventName, ex); | ||
| } | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| await _telemetryClient.FlushAsync(CancellationToken.None); | ||
|
|
||
| _configuration.Dispose(); | ||
| } | ||
| } | ||
|
|
||
| internal static partial class Log | ||
| { | ||
| [LoggerMessage( | ||
| Level = LogLevel.Debug, | ||
| Message = "[1ds] Skipping tracking for origin: {Origin}")] | ||
| internal static partial void LogSkippingTracking( | ||
| this ILogger logger, string origin); | ||
|
|
||
| [LoggerMessage( | ||
| Level = LogLevel.Information, | ||
| Message = "Tracked event: {EventName}")] | ||
| internal static partial void LogTrackedEvent( | ||
| this ILogger logger, string eventName); | ||
|
|
||
| [LoggerMessage( | ||
| Level = LogLevel.Warning, | ||
| Message = "Failed to track event: {EventName}")] | ||
| internal static partial void LogTrackingFailed( | ||
| this ILogger logger, string eventName, Exception exception); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.