Skip to content
Open
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
7 changes: 3 additions & 4 deletions src/statichost/StaticHost/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

namespace Microsoft.Extensions.Hosting;

public static class Extensions
Expand All @@ -10,6 +6,9 @@ public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where
{
builder.ConfigureOpenTelemetry();

// Register 1DS analytics for downloads...
builder.Services.AddSingleton<OneDSTelemetryService>();

return builder;
}

Expand Down
9 changes: 9 additions & 0 deletions src/statichost/StaticHost/GlobalUsings.cs
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;
138 changes: 138 additions & 0 deletions src/statichost/StaticHost/OneDSTelemetryService.cs
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);
}
16 changes: 8 additions & 8 deletions src/statichost/StaticHost/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Microsoft.AspNetCore.StaticFiles;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
Expand Down Expand Up @@ -49,16 +47,18 @@

app.MapGet("/healthz", () => Results.Ok());

app.MapGet("/install.ps1", async context =>
app.MapGet("/install.ps1", (HttpContext context, OneDSTelemetryService telemetry) =>
{
await Task.CompletedTask;
context.Response.Redirect("https://aka.ms/aspire/get/install.ps1");
telemetry.TrackDownload(context, "install.ps1");

return Results.Redirect("https://aka.ms/aspire/get/install.ps1");
});

app.MapGet("/install.sh", async context =>
app.MapGet("/install.sh", (HttpContext context, OneDSTelemetryService telemetry) =>
{
await Task.CompletedTask;
context.Response.Redirect("https://aka.ms/aspire/get/install.sh");
telemetry.TrackDownload(context, "install.sh");

return Results.Redirect("https://aka.ms/aspire/get/install.sh");
});

app.MapStaticAssets();
Expand Down
1 change: 1 addition & 0 deletions src/statichost/StaticHost/StaticHost.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.23.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.14.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.14.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.14.0" />
Expand Down
Loading