From 47b917ef25ffc30795ded0da1bfebb17ce99a909 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Fri, 6 Nov 2026 04:56:19 -0800 Subject: [PATCH] Align JavaScript Dockerfile run-script validator with Go and Python pipeline registration (#21461) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description Part of #21205. Aligns the JavaScript existing-Dockerfile run-script validator (`validate-javascript-dockerfile-run-script-{name}`) with the Go and Python validators fixed in #21186. ### Bugs on `main`, each reproduced by a new test 1. **Excluded resources still fail publish.** A JavaScript app with an existing Dockerfile and an explicit run script that is marked `ExcludeFromManifest()` still runs the validator and throws `JavaScript app resource 'js' is configured to run script 'migrate', but publish is using the existing Dockerfile ...`. The resource isn't published at all, so this failure is spurious. 2. **`PublishAsDockerFile(c => c.WithDockerfile(...))` crashes in publish mode.** The validator was a second `PipelineStepAnnotation` on the container. `WithDockerfile` calls `EnsureBuildAndPushPipelineAnnotations`, which adds its annotation with `ResourceAnnotationMutationBehavior.Replace` and then fails with `InvalidOperationException: Sequence contains more than one element`. 3. **Deploy graphs skip the validator.** It was only `RequiredBySteps = [Build, Publish]`. Azure Container Apps and App Service select a resource's `BuildCompute` steps directly, so `build-{name}` never depended on the validator. ### Fix This is the same shape #21186 merged for Go and Python: - Register the step through `builder.Pipeline.AddStep`, so it's no longer a container annotation that `WithDockerfile` can replace. - Skip validation when `containerBuilder.Resource.IsExcludedFromPublish()`. - Make the container's `BuildCompute` steps depend on the validation step through `WithPipelineConfiguration`. The existing test `PublishPipelineWithExistingDockerfileThrowsFromValidationStepWhenRunScriptNameIsExplicit` built a bare `new DistributedApplicationPipeline()`, which doesn't contain steps added through `builder.Pipeline`. It now resolves the app's `IDistributedApplicationPipeline`, as the Go and Python tests in #21186 do. Its assertions are unchanged. Not in this PR (remaining #21205 items): the Next.js standalone check's `BuildCompute` dependency and a shared helper across Go, Python and JavaScript. ### Before/after (local) | Test | Before (`main` source) | After | |---|---|---| | `PublishPipelineValidationStepIsNoOpForResourceExcludedFromManifest` | ❌ `DistributedApplicationException: JavaScript app resource 'js' is configured to run script 'migrate' ...` | ✅ | | `PublishPipelineValidationStepSurvivesLaterWithDockerfile` | ❌ `InvalidOperationException: Sequence contains more than one element` (from `WithDockerfile`) | ✅ | | `PublishPipelineRunsValidationStepBeforeImageBuildStep` | ❌ `Assert.Contains() Failure: Filter not matched` (validator not in the `build-js` closure) | ✅ | - The four `*PublishPipeline*` tests pass in 20/20 repeated runs. - Full `Aspire.Hosting.JavaScript.Tests`: 408/427 pass locally. The 19 failures are environmental and unrelated: - Bun and Deno functional tests fail in 0ms because those tools aren't installed. - Verify snapshot tests fail because the sandbox HOME is `/root`, which the scrubber rewrites inside `/root/.cache`. With a different HOME, all 101 snapshot tests pass. ## Checklist - Is this feature complete? - [ ] Yes. Ready to ship. - [x] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - [ ] No - Did you add public API? - [ ] Yes - If yes, did you have an API Review for it? - [ ] Yes - [ ] No - Did you add `` and `` elements on your triple slash comments? - [ ] Yes - [ ] No - [x] No - Does the change make any security assumptions or guarantees? - [ ] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [ ] No - [x] No **🤖 Posted by AspireAgent (AI Agent)** --------- Co-authored-by: davidfowl <95136+davidfowl@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: David Pine Co-authored-by: IEvangelist <7679720+IEvangelist@users.noreply.github.com> (cherry picked from commit 059be63c471dda28c4c9066429b0bbbbaf273bb3) --- .../Aspire.Hosting.Go.csproj | 1 + src/Aspire.Hosting.Go/GoHostingExtensions.cs | 37 ++------ .../Aspire.Hosting.JavaScript.csproj | 1 + .../JavaScriptHostingExtensions.cs | 51 ++++------- .../Aspire.Hosting.Python.csproj | 1 + .../PythonAppResourceBuilderExtensions.cs | 36 ++------ src/Shared/PublishValidationExtensions.cs | 46 ++++++++++ .../JavaScriptPublishValidationTests.cs | 73 ++++++++++++++++ .../AddJavaScriptAppTests.cs | 87 +++++++++++++++++-- .../AddViteAppTests.cs | 76 +++++++++++----- 10 files changed, 283 insertions(+), 126 deletions(-) create mode 100644 src/Shared/PublishValidationExtensions.cs create mode 100644 tests/Aspire.Hosting.Azure.Tests/JavaScriptPublishValidationTests.cs diff --git a/src/Aspire.Hosting.Go/Aspire.Hosting.Go.csproj b/src/Aspire.Hosting.Go/Aspire.Hosting.Go.csproj index 25035778ab9..6b9778ffb4d 100644 --- a/src/Aspire.Hosting.Go/Aspire.Hosting.Go.csproj +++ b/src/Aspire.Hosting.Go/Aspire.Hosting.Go.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Aspire.Hosting.Go/GoHostingExtensions.cs b/src/Aspire.Hosting.Go/GoHostingExtensions.cs index 8275c817951..3fb42350d89 100644 --- a/src/Aspire.Hosting.Go/GoHostingExtensions.cs +++ b/src/Aspire.Hosting.Go/GoHostingExtensions.cs @@ -332,38 +332,11 @@ public static IResourceBuilder AddGoApp( if (builder.ExecutionContext.IsPublishMode && builder.TryCreateResourceBuilder(resource.Name, out var containerBuilder)) { - var validationStepName = $"validate-go-dockerfile-package-path-{resource.Name}"; - - // The step is added to the pipeline instead of as a PipelineStepAnnotation on the container because - // WithDockerfile replaces the container's step annotation, which would drop this step (or throw when - // more than one exists) if the Dockerfile is configured again after this point. - builder.Pipeline.AddStep(new PipelineStep - { - Name = validationStepName, - Description = $"Warns when Go app '{resource.Name}' publishes an existing Dockerfile that ignores its package path.", - RequiredBySteps = [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], - Resource = containerBuilder.Resource, - Action = context => - { - // A resource excluded from the manifest is never published, so there is nothing to warn about. - if (!containerBuilder.Resource.IsExcludedFromPublish()) - { - WarnIfExistingDockerfileIgnoresPackagePath(resource, containerBuilder.Resource, context.Logger); - } - - return Task.CompletedTask; - } - }); - - // Deploy environments such as Azure Container Apps run the image build step without the aggregate - // Build step, so the image build must wait for this step itself to surface the warning before a - // potentially long build instead of after it. - containerBuilder.WithPipelineConfiguration(context => - { - var validationStep = context.GetSteps(containerBuilder.Resource).FirstOrDefault(step => step.Name == validationStepName); - - context.GetSteps(containerBuilder.Resource, WellKnownPipelineTags.BuildCompute).DependsOn(validationStep); - }); + containerBuilder.AddPublishValidation( + $"validate-go-dockerfile-package-path-{resource.Name}", + $"Warns when Go app '{resource.Name}' publishes an existing Dockerfile that ignores its package path.", + [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], + context => WarnIfExistingDockerfileIgnoresPackagePath(resource, containerBuilder.Resource, context.Logger)); } // Ensure source resources (that provide container files) build before this Go image. diff --git a/src/Aspire.Hosting.JavaScript/Aspire.Hosting.JavaScript.csproj b/src/Aspire.Hosting.JavaScript/Aspire.Hosting.JavaScript.csproj index d7d4d0b56fb..e954577199e 100644 --- a/src/Aspire.Hosting.JavaScript/Aspire.Hosting.JavaScript.csproj +++ b/src/Aspire.Hosting.JavaScript/Aspire.Hosting.JavaScript.csproj @@ -18,6 +18,7 @@ + diff --git a/src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs b/src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs index df4dad6bdc1..fb33f8d6e2b 100644 --- a/src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs +++ b/src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs @@ -1901,8 +1901,6 @@ private static IResourceBuilder CreateDefaultJavaScriptAppBuilder(resource.Name, out var containerBuilder)) { - var validationStepName = $"validate-javascript-dockerfile-run-script-{resource.Name}"; - Task WriteValidatedContainerAsync(ManifestPublishingContext context) { ValidateExistingDockerfileRunScript(resource, containerBuilder.Resource); @@ -1911,18 +1909,11 @@ Task WriteValidatedContainerAsync(ManifestPublishingContext context) resourceBuilder.WithManifestPublishingCallback(WriteValidatedContainerAsync); containerBuilder.WithManifestPublishingCallback(WriteValidatedContainerAsync); - containerBuilder.WithAnnotation(new PipelineStepAnnotation(_ => new PipelineStep - { - Name = validationStepName, - Description = $"Validates that JavaScript app '{resource.Name}' does not publish an ignored run script with an existing Dockerfile.", - RequiredBySteps = [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], - Resource = containerBuilder.Resource, - Action = _ => - { - ValidateExistingDockerfileRunScript(resource, containerBuilder.Resource); - return Task.CompletedTask; - } - })); + containerBuilder.AddPublishValidation( + $"validate-javascript-dockerfile-run-script-{resource.Name}", + $"Validates that JavaScript app '{resource.Name}' does not publish an ignored run script with an existing Dockerfile.", + [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], + _ => ValidateExistingDockerfileRunScript(resource, containerBuilder.Resource)); } resourceBuilder.WithVSCodeDebugging(); @@ -2192,6 +2183,9 @@ public static IResourceBuilder AddViteApp(this IDistributedAppl /// /// The Next.js application must have output: "standalone" configured in next.config.ts /// and a public/ directory (even if empty) for the published container to build correctly. + /// The standalone output check runs before the container image build during publish and deployment, + /// including Azure Container Apps and App Service. Resources excluded from publishing are not validated. + /// Use when the configuration cannot be statically inspected. /// /// /// The following example creates a Next.js app. @@ -2253,29 +2247,22 @@ public static IResourceBuilder AddNextJsApp(this IDistributed } } - // Add a publish prereq step that validates the Next.js config has standalone output enabled. - // This runs at deploy time (not resource creation time) so it doesn't block `aspire start`. - // Can be disabled with .DisableBuildValidation(). - resourceBuilder.WithAnnotation(new PipelineStepAnnotation(factoryCtx => - [ - new PipelineStep - { - Name = $"nextjs-standalone-check-{name}", - Description = $"Validates that the Next.js app '{name}' has output: \"standalone\" configured.", - DependsOnSteps = [WellKnownPipelineSteps.BuildPrereq], - RequiredBySteps = [WellKnownPipelineSteps.Build], - Resource = resourceBuilder.Resource, - Action = _ => + if (builder.ExecutionContext.IsPublishMode && + builder.TryCreateResourceBuilder(name, out var containerBuilder)) + { + var validationStep = containerBuilder.AddPublishValidation( + $"nextjs-standalone-check-{name}", + $"Validates that the Next.js app '{name}' has output: \"standalone\" configured.", + [WellKnownPipelineSteps.Build], + _ => { if (!resourceBuilder.Resource.TryGetLastAnnotation(out var suppress)) { ValidateNextJsStandaloneOutput(appDirectory); } - - return Task.CompletedTask; - } - } - ])); + }); + validationStep.DependsOn(WellKnownPipelineSteps.BuildPrereq); + } return resourceBuilder; } diff --git a/src/Aspire.Hosting.Python/Aspire.Hosting.Python.csproj b/src/Aspire.Hosting.Python/Aspire.Hosting.Python.csproj index 8eb7619a563..f612160bb78 100644 --- a/src/Aspire.Hosting.Python/Aspire.Hosting.Python.csproj +++ b/src/Aspire.Hosting.Python/Aspire.Hosting.Python.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Aspire.Hosting.Python/PythonAppResourceBuilderExtensions.cs b/src/Aspire.Hosting.Python/PythonAppResourceBuilderExtensions.cs index b4230534b0e..1f4fa519a44 100644 --- a/src/Aspire.Hosting.Python/PythonAppResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting.Python/PythonAppResourceBuilderExtensions.cs @@ -485,39 +485,13 @@ Task WriteValidatedContainerAsync(ManifestPublishingContext context) return context.WriteContainerAsync(containerBuilder.Resource); } - var validationStepName = $"validate-python-dockerfile-entrypoint-{resource.Name}"; - resourceBuilder.WithManifestPublishingCallback(WriteValidatedContainerAsync); containerBuilder.WithManifestPublishingCallback(WriteValidatedContainerAsync); - // The step is added to the pipeline instead of as a PipelineStepAnnotation on the container because - // WithDockerfile replaces the container's step annotation, which would drop this step (or throw when - // more than one exists) if the Dockerfile is configured again after this point. - builder.Pipeline.AddStep(new PipelineStep - { - Name = validationStepName, - Description = $"Validates that Python app '{resource.Name}' does not publish an ignored entrypoint with an existing Dockerfile.", - RequiredBySteps = [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], - Resource = containerBuilder.Resource, - Action = _ => - { - // A resource excluded from the manifest is never published, so it must not fail the pipeline. - if (!containerBuilder.Resource.IsExcludedFromPublish()) - { - ValidateExistingDockerfileEntrypoint(resource, containerBuilder.Resource, entrypointType, entrypoint); - } - - return Task.CompletedTask; - } - }); - - // Deploy environments such as Azure Container Apps run the image build step without the aggregate - // Build step, so the image build must wait for the validation itself. - containerBuilder.WithPipelineConfiguration(context => - { - var validationStep = context.GetSteps(containerBuilder.Resource).FirstOrDefault(step => step.Name == validationStepName); - - context.GetSteps(containerBuilder.Resource, WellKnownPipelineTags.BuildCompute).DependsOn(validationStep); - }); + containerBuilder.AddPublishValidation( + $"validate-python-dockerfile-entrypoint-{resource.Name}", + $"Validates that Python app '{resource.Name}' does not publish an ignored entrypoint with an existing Dockerfile.", + [WellKnownPipelineSteps.Build, WellKnownPipelineSteps.Publish], + _ => ValidateExistingDockerfileEntrypoint(resource, containerBuilder.Resource, entrypointType, entrypoint)); } resourceBuilder.WithPipelineConfiguration(context => diff --git a/src/Shared/PublishValidationExtensions.cs b/src/Shared/PublishValidationExtensions.cs new file mode 100644 index 00000000000..c6cd122274d --- /dev/null +++ b/src/Shared/PublishValidationExtensions.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Hosting.ApplicationModel; +using Aspire.Hosting.Pipelines; + +namespace Aspire.Hosting; + +internal static class PublishValidationExtensions +{ + internal static PipelineStep AddPublishValidation( + this IResourceBuilder builder, + string stepName, + string description, + string[] requiredBySteps, + Action validate) + { + var step = new PipelineStep + { + Name = stepName, + Description = description, + RequiredBySteps = [.. requiredBySteps], + Resource = builder.Resource, + Action = context => + { + // Exclusion can be configured after registration. An unpublished resource must not fail validation. + if (!builder.Resource.IsExcludedFromPublish()) + { + validate(context); + } + + return Task.CompletedTask; + } + }; + + // WithDockerfile replaces container step annotations, so keep validation in the application pipeline. + builder.ApplicationBuilder.Pipeline.AddStep(step); + builder.WithPipelineConfiguration(context => + { + // Azure deploy graphs select BuildCompute directly, without the aggregate Build or Publish steps. + context.GetSteps(builder.Resource, WellKnownPipelineTags.BuildCompute).DependsOn(stepName); + }); + + return step; + } +} diff --git a/tests/Aspire.Hosting.Azure.Tests/JavaScriptPublishValidationTests.cs b/tests/Aspire.Hosting.Azure.Tests/JavaScriptPublishValidationTests.cs new file mode 100644 index 00000000000..a117c5589b0 --- /dev/null +++ b/tests/Aspire.Hosting.Azure.Tests/JavaScriptPublishValidationTests.cs @@ -0,0 +1,73 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#pragma warning disable ASPIREJAVASCRIPT001 // Type is for evaluation purposes only +#pragma warning disable ASPIRECOMPUTE003 // Type is for evaluation purposes only + +using Aspire.Hosting.ApplicationModel; +using Aspire.Hosting.Pipelines; +using Aspire.Hosting.Utils; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Aspire.Hosting.Azure.Tests; + +public class JavaScriptPublishValidationTests(ITestOutputHelper outputHelper) +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DeployGraphRequiresJavaScriptAndNextJsValidationBeforeImageBuilds(bool appService) + { + using var workspace = TemporaryWorkspace.Create(outputHelper); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish, step: "inspect"); + if (appService) + { + builder.AddAzureAppServiceEnvironment("env"); + } + else + { + builder.AddAzureContainerAppEnvironment("env"); + } + + builder.AddJavaScriptApp("js", workspace.Path) + .PublishAsPackageScript("start") + .WithHttpEndpoint(port: 3001) + .WithExternalHttpEndpoints(); + builder.AddNextJsApp("nextjs", workspace.Path).WithExternalHttpEndpoints(); + + IReadOnlyList graph = []; + builder.Pipeline.AddStep("inspect", _ => Task.CompletedTask); + builder.Pipeline.AddPipelineConfiguration(context => + { + graph = context.Steps.ToArray(); + return Task.CompletedTask; + }); + + using var app = builder.Build(); + await AzureManifestUtils.ExecuteBeforeStartHooksAsync(app, TestContext.Current.CancellationToken); + await app.Services.GetRequiredService().ExecuteAsync( + new PipelineContext( + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services, + NullLogger.Instance, + TestContext.Current.CancellationToken)); + + Assert.True(Reaches(WellKnownPipelineSteps.Deploy, "build-js")); + Assert.True(Reaches(WellKnownPipelineSteps.Deploy, "build-nextjs")); + Assert.True(Reaches("build-js", "validate-javascript-dockerfile-run-script-js")); + Assert.True(Reaches("build-nextjs", "nextjs-standalone-check-nextjs")); + Assert.True(Reaches(WellKnownPipelineSteps.Deploy, "validate-javascript-dockerfile-run-script-js")); + Assert.True(Reaches(WellKnownPipelineSteps.Deploy, "nextjs-standalone-check-nextjs")); + + bool Reaches(string from, string target) + { + var visited = new HashSet(StringComparer.Ordinal); + bool Visit(string name) => name == target || (visited.Add(name) && + graph.Single(step => step.Name == name).DependsOnSteps.Any(Visit)); + + return Visit(from); + } + } +} diff --git a/tests/Aspire.Hosting.JavaScript.Tests/AddJavaScriptAppTests.cs b/tests/Aspire.Hosting.JavaScript.Tests/AddJavaScriptAppTests.cs index 4ff0876b6c4..580fc33ad64 100644 --- a/tests/Aspire.Hosting.JavaScript.Tests/AddJavaScriptAppTests.cs +++ b/tests/Aspire.Hosting.JavaScript.Tests/AddJavaScriptAppTests.cs @@ -255,21 +255,85 @@ public async Task PublishPipelineWithExistingDockerfileThrowsFromValidationStepW .WithBun(); using var app = builder.Build(); - var pipeline = new DistributedApplicationPipeline(); - var context = new PipelineContext( - app.Services.GetRequiredService(), - app.Services.GetRequiredService(), - app.Services, - app.Services.GetRequiredService>(), - CancellationToken.None); + var pipeline = app.Services.GetRequiredService(); - var exception = await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(context)); + var exception = await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(CreatePipelineContext(app))); Assert.Contains("runScriptName", exception.Message); Assert.Contains("WithRunScript", exception.Message); Assert.Contains("Dockerfile", exception.Message); } + [Fact] + public async Task PublishPipelineValidationStepIsNoOpForResourceExcludedFromManifest() + { + using var workspace = TemporaryWorkspace.Create(outputHelper); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithResourceCleanUp(true); + builder.Services.AddSingleton(); + + var appDir = CreateJavaScriptAppWithDockerfile(workspace.Path); + builder.AddJavaScriptApp("js", appDir, "migrate") + .WithBun() + .ExcludeFromManifest(); + + using var app = builder.Build(); + var pipeline = (DistributedApplicationPipeline)app.Services.GetRequiredService(); + var context = CreatePipelineContext(app); + + var stepNames = (await pipeline.ResolveStepsAsync(context)).Select(step => step.Name).ToList(); + Assert.Contains("validate-javascript-dockerfile-run-script-js", stepNames); + + await pipeline.ExecuteStepSequentiallyAsync("validate-javascript-dockerfile-run-script-js", context); + } + + [Fact] + public async Task PublishPipelineValidationStepSurvivesLaterWithDockerfile() + { + using var workspace = TemporaryWorkspace.Create(outputHelper); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithResourceCleanUp(true); + builder.Services.AddSingleton(); + + var appDir = CreateJavaScriptAppWithDockerfile(workspace.Path); + builder.AddJavaScriptApp("js", appDir, "migrate") + .WithBun() + .PublishAsDockerFile(container => container.WithDockerfile(appDir)); + + using var app = builder.Build(); + var pipeline = (DistributedApplicationPipeline)app.Services.GetRequiredService(); + var context = CreatePipelineContext(app); + + var stepNames = (await pipeline.ResolveStepsAsync(context)).Select(step => step.Name).ToList(); + Assert.Contains("validate-javascript-dockerfile-run-script-js", stepNames); + + var exception = await Assert.ThrowsAsync( + () => pipeline.ExecuteStepSequentiallyAsync("validate-javascript-dockerfile-run-script-js", context)); + + Assert.Contains("runScriptName", exception.Message); + } + + [Fact] + public async Task PublishPipelineRunsValidationStepBeforeImageBuildStep() + { + using var workspace = TemporaryWorkspace.Create(outputHelper); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithResourceCleanUp(true); + builder.Services.AddSingleton(); + + var appDir = CreateJavaScriptAppWithDockerfile(workspace.Path); + builder.AddJavaScriptApp("js", appDir) + .WithBun(); + + using var app = builder.Build(); + var pipeline = (DistributedApplicationPipeline)app.Services.GetRequiredService(); + + var steps = (await pipeline.ResolveStepsAsync(CreatePipelineContext(app))) + .ToDictionary(step => step.Name, StringComparer.Ordinal); + + // Compute environments such as Azure Container Apps depend on the image build step without the aggregate Build step. + var buildStepClosure = DistributedApplicationPipeline.ComputeTransitiveDependencies(steps["build-js"], steps); + + Assert.Contains(buildStepClosure, step => step.Name == "validate-javascript-dockerfile-run-script-js"); + } + [Fact] public async Task PublishWithExistingDockerfileAllowsImplicitDefaultRunScript() { @@ -709,6 +773,13 @@ public async Task VerifyPnpmDockerfileWhenPublishedAsPackageScriptRunsWithoutNet return (process.ExitCode, await stdoutTask, await stderrTask); } + private static PipelineContext CreatePipelineContext(DistributedApplication app) => new( + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services, + app.Services.GetRequiredService>(), + CancellationToken.None); + private static string CreateJavaScriptAppWithDockerfile(string rootDirectory) { var appDir = Path.Combine(rootDirectory, "js"); diff --git a/tests/Aspire.Hosting.JavaScript.Tests/AddViteAppTests.cs b/tests/Aspire.Hosting.JavaScript.Tests/AddViteAppTests.cs index 1f3e74f7f8b..00a1d848957 100644 --- a/tests/Aspire.Hosting.JavaScript.Tests/AddViteAppTests.cs +++ b/tests/Aspire.Hosting.JavaScript.Tests/AddViteAppTests.cs @@ -1040,19 +1040,27 @@ public async Task AddViteApp_ServerAuthCertConfig_DetectsAllDefaultConfigFileFor } [Fact] - public void NextJsAppHasBuildValidationStep() + public async Task NextJsAppHasBuildValidationStep() { using var workspace = TemporaryWorkspace.Create(outputHelper); - using var builder = TestDistributedApplicationBuilder.Create().WithResourceCleanUp(true); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithResourceCleanUp(true); + builder.Services.AddSingleton(); var nextDir = Path.Combine(workspace.Path, "nextjs"); Directory.CreateDirectory(nextDir); File.WriteAllText(Path.Combine(nextDir, "package-lock.json"), "empty"); - var nodeApp = builder.AddNextJsApp("nextjs", nextDir); + builder.AddNextJsApp("nextjs", nextDir); + + using var app = builder.Build(); + var pipeline = (DistributedApplicationPipeline)app.Services.GetRequiredService(); + var steps = (await pipeline.ResolveStepsAsync(CreatePipelineContext(app))) + .ToDictionary(step => step.Name, StringComparer.Ordinal); + + var buildStepClosure = DistributedApplicationPipeline.ComputeTransitiveDependencies(steps["build-nextjs"], steps); - var stepAnnotations = nodeApp.Resource.Annotations.OfType().ToList(); - Assert.NotEmpty(stepAnnotations); + Assert.Contains(buildStepClosure, step => step.Name == "nextjs-standalone-check-nextjs"); + Assert.Contains(WellKnownPipelineSteps.BuildPrereq, steps["nextjs-standalone-check-nextjs"].DependsOnSteps); } [Fact] @@ -1071,35 +1079,57 @@ public void DisableBuildValidationAddsSuppressAnnotation() Assert.True(nodeApp.Resource.TryGetLastAnnotation(out _)); } - [Fact] - public async Task NextJsStandaloneCheckFailsInPipelineWhenMissing() + [Theory] + [InlineData(false, false, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, true)] + public async Task NextJsStandaloneCheckRespectsConfigurationSuppressionAndExclusion(bool standalone, bool suppress, bool excluded) { using var workspace = TemporaryWorkspace.Create(outputHelper); - using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish, step: null).WithResourceCleanUp(true); + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish, step: "nextjs-standalone-check-nextjs").WithResourceCleanUp(true); builder.Services.AddSingleton(); var nextDir = Path.Combine(workspace.Path, "nextjs"); Directory.CreateDirectory(nextDir); File.WriteAllText(Path.Combine(nextDir, "package-lock.json"), "empty"); - File.WriteAllText(Path.Combine(nextDir, "next.config.ts"), "const nextConfig = {}; export default nextConfig;"); + File.WriteAllText(Path.Combine(nextDir, "next.config.ts"), standalone + ? "export default { output: 'standalone' };" + : "export default {};"); - builder.AddNextJsApp("nextjs", nextDir); + var next = builder.AddNextJsApp("nextjs", nextDir); + if (suppress) + { + next.DisableBuildValidation(); + } - var app = builder.Build(); - var pipeline = new DistributedApplicationPipeline(); - var context = new PipelineContext( - app.Services.GetRequiredService(), - app.Services.GetRequiredService(), - app.Services, - app.Services.GetRequiredService>(), - CancellationToken.None); - - // Pipeline throws AggregateException when multiple steps fail - var ex = await Assert.ThrowsAnyAsync(() => pipeline.ExecuteAsync(context)); - // Verify our standalone check step fired with the right message - Assert.Contains("output: \"standalone\"", ex.ToString()); + if (excluded) + { + next.ExcludeFromManifest(); + } + + using var app = builder.Build(); + var pipeline = app.Services.GetRequiredService(); + var context = CreatePipelineContext(app); + + if (standalone || suppress || excluded) + { + await pipeline.ExecuteAsync(context); + } + else + { + var exception = await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(context)); + Assert.Contains("output: \"standalone\"", exception.Message); + } } + private static PipelineContext CreatePipelineContext(DistributedApplication app) => new( + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services, + app.Services.GetRequiredService>(), + TestContext.Current.CancellationToken); + private static async Task GenerateViteWrapperAsync(DistributedApplication app) { var appModel = app.Services.GetRequiredService();