Skip to content
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
5 changes: 4 additions & 1 deletion .github/workflows/Build-Test-And-Deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ jobs:
context: .
secret-files: |
"nuget_config=${{ runner.temp }}/nuget/NuGet.Config"
build-args: SOURCE_REVISION=${{ github.sha }}
outputs: type=docker,dest=${{ github.workspace }}/essentialcsharpwebimage.tar
cache-from: type=gha,scope=essentialcsharpweb-main
cache-to: type=gha,mode=max,scope=essentialcsharpweb-main
Expand Down Expand Up @@ -270,7 +271,9 @@ jobs:
type=gha,scope=essentialcsharpweb-main
type=gha,scope=essentialcsharpweb-pr
cache-to: type=gha,mode=min,scope=essentialcsharpweb-pr
build-args: ACCESS_TO_NUGET_FEED=false
build-args: |
ACCESS_TO_NUGET_FEED=false
SOURCE_REVISION=${{ github.sha }}

deploy-development:
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
Expand Down
86 changes: 86 additions & 0 deletions EssentialCSharp.Web.Tests/VersionEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using System.Net;
using System.Reflection;
using System.Text.Json;
using EssentialCSharp.Web.Services;

namespace EssentialCSharp.Web.Tests;

public class VersionEndpointTests : IntegrationTestBase
{
[Test]
public async Task GetVersion_ReturnsRunningAssemblyBuildInfo_WithoutCaching()
{
using HttpClient client = CreateClientWithoutAutoRedirect();

using HttpResponseMessage response = await client.GetAsync("/version");

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
await Assert.That(response.Headers.CacheControl?.NoStore).IsTrue();
await Assert.That(response).HasJsonContent();

string body = await response.Content.ReadAsStringAsync();
await Assert.That(body).IsValidJsonObject();

// Deep equality pins the whole contract that deployment checks rely on: no renamed or extra fields.
string? expectedVersion = typeof(Program).Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
using JsonDocument expected = JsonDocument.Parse(JsonSerializer.Serialize(new
{
version = expectedVersion,
commit = BuildInfo.FromInformationalVersion(expectedVersion).Commit,
}));
using JsonDocument actual = JsonDocument.Parse(body);
await Assert.That(actual.RootElement).IsDeepEqualTo(expected.RootElement);
}

[Test]
public async Task HeadVersion_ReturnsOk()
{
using HttpClient client = CreateClientWithoutAutoRedirect();
using var request = new HttpRequestMessage(HttpMethod.Head, "/version");

using HttpResponseMessage response = await client.SendAsync(request);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
}

[Test]
public async Task BuildInfo_InGitHubActions_IsStampedWithCheckedOutCommit()
{
// Locally the stamp depends on the developer's checkout, so only enforce it in CI, where the
// checked-out commit is GITHUB_SHA and the SDK's SourceLink stamps it into the informational version.
if (!string.Equals(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"), "true", StringComparison.OrdinalIgnoreCase))
{
return;
}

await Assert.That(BuildInfo.Current.Commit).IsEqualTo(Environment.GetEnvironmentVariable("GITHUB_SHA"));
}

[Test]
public async Task GetVersion_IsNotRateLimited()
{
// Deployment checks poll /version until the new revision answers; the global limiter must not reject them.
using HttpClient client = CreateClientWithoutAutoRedirect();

for (int i = 0; i < 40; i++)
{
using HttpResponseMessage response = await client.GetAsync("/version");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
}
}

[Test]
[Arguments("1.0.0+0123456789abcdef0123456789abcdef01234567", "1.0.0+0123456789abcdef0123456789abcdef01234567", "0123456789abcdef0123456789abcdef01234567")]
[Arguments("1.0.0", "1.0.0", null)]
[Arguments("1.0.0+", "1.0.0+", null)]
[Arguments(null, null, null)]
[Arguments("", null, null)]
public async Task FromInformationalVersion_ExtractsCommitAfterPlus(string? informationalVersion, string? expectedVersion, string? expectedCommit)
{
BuildInfo info = BuildInfo.FromInformationalVersion(informationalVersion);

await Assert.That(info.Version).IsEqualTo(expectedVersion);
await Assert.That(info.Commit).IsEqualTo(expectedCommit);
}
}
8 changes: 7 additions & 1 deletion EssentialCSharp.Web/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,16 @@ RUN --mount=type=secret,id=nuget_config,required=false,target=/root/.nuget/NuGet
dotnet restore "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED
COPY . .
COPY --from=frontend-build /frontend/EssentialCSharp.Web/wwwroot/dist ./EssentialCSharp.Web/wwwroot/dist
# Commit SHA the image is built from. .git is excluded from the build context, so CI passes it in;
# it becomes the "+<sha>" suffix of AssemblyInformationalVersion and is reported by GET /version.
# Declared here (after COPY . .) so a new value does not invalidate the cached restore layer.
ARG SOURCE_REVISION=
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
dotnet build "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release --no-restore -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:ReleaseDateAttribute=True -p:SkipFrontendBuild=true
dotnet build "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release --no-restore -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:ReleaseDateAttribute=True -p:SkipFrontendBuild=true -p:SourceRevisionId=$SOURCE_REVISION
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
dotnet publish "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release -p:PublishDir=/app/publish -p:UseAppHost=false -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:SkipFrontendBuild=true --no-build
# The bundle step rebuilds without SourceRevisionId; that's fine because /app/publish already holds the
# stamped web assembly and the bundle only writes efbundle. Keep publish before this step.
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
dotnet tool restore && \
ASPNETCORE_ENVIRONMENT=Development SkipFrontendBuild=true dotnet ef migrations bundle \
Expand Down
10 changes: 9 additions & 1 deletion EssentialCSharp.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ private static void Main(string[] args)
{
options.Filter = ctx =>
!ctx.Request.Path.StartsWithSegments("/health")
&& !ctx.Request.Path.StartsWithSegments("/alive");
&& !ctx.Request.Path.StartsWithSegments("/alive")
&& !ctx.Request.Path.StartsWithSegments("/version");
// EnrichWithHttpResponse fires after the authentication middleware has run,
// so HttpContext.User is populated and IsAuthenticated is reliable.
options.EnrichWithHttpResponse = (activity, response) =>
Expand Down Expand Up @@ -558,6 +559,13 @@ await McpJsonRpcResponseWriter.WriteErrorAsync(
Predicate = r => r.Tags.Contains("live")
}).DisableRateLimiting();

// Machine-readable build identity for deployment checks (not linked from or shown in the UI).
app.MapMethods("/version", [HttpMethods.Get, HttpMethods.Head], (HttpResponse response) =>
{
response.Headers.CacheControl = "no-store";
return Results.Ok(BuildInfo.Current);
}).DisableRateLimiting();

if (!app.Environment.IsDevelopment())
{
app.UseHttpsRedirection();
Expand Down
36 changes: 36 additions & 0 deletions EssentialCSharp.Web/Services/BuildInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;

namespace EssentialCSharp.Web.Services;

/// <summary>
/// Identifies the build that is running, for <c>GET /version</c>. Deployment checks poll it to confirm
/// a new revision is serving traffic before smoke testing it. Nothing here is shown in the site UI.
/// </summary>
/// <param name="Version">The assembly's informational version, e.g. <c>1.0.0+&lt;sha&gt;</c>.</param>
/// <param name="Commit">The source revision (git SHA) the build came from, or <see langword="null"/> when the build was not stamped.</param>
public sealed record BuildInfo(string? Version, string? Commit)
{
public static BuildInfo Current { get; } = FromAssembly(typeof(BuildInfo).Assembly);

public static BuildInfo FromAssembly(Assembly assembly) =>
FromInformationalVersion(assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);

/// <summary>
/// The SDK appends <c>+$(SourceRevisionId)</c> to the informational version when a source revision is known
/// (from SourceLink locally, or the <c>SOURCE_REVISION</c> Docker build argument in CI).
/// </summary>
public static BuildInfo FromInformationalVersion(string? informationalVersion)
{
if (string.IsNullOrWhiteSpace(informationalVersion))
{
return new BuildInfo(null, null);
}

int plus = informationalVersion.IndexOf('+', StringComparison.Ordinal);
string? commit = plus >= 0 && plus < informationalVersion.Length - 1
? informationalVersion[(plus + 1)..]
: null;

return new BuildInfo(informationalVersion, commit);
}
}
Loading