diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 633b74626ab..f522dd9a57d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,8 +132,8 @@ jobs: # 2. Runs the subset of Aspire.Cli.Tests classes that exercise version/channel/template # version pinning logic against the stably-built CLI assemblies. These are the code # paths most likely to behave differently when the CLI's own version label is stable. - # 3. Runs a small `aspire new aspire-empty` + `aspire restore` smoke script that - # exercises the user-visible CLI flow against the locally-built stable feed, + # 3. Runs C#, Go, and Java template scaffolding + `aspire restore` smoke checks that + # exercise the user-visible CLI flow against the locally-built stable feed, # which is the scenario that has historically broken on stabilization branches. # # The job is gated to enabled PRs only. Push CI (including push to release branches with @@ -150,8 +150,8 @@ jobs: - name: Build + pack with StabilizePackageVersion=true # SkipNativeBuild=true keeps this job fast (~5min): pack-time NU5104 detection - # doesn't need NativeAOT CLI binaries, and the moderate smoke below invokes the - # CLI via `dotnet run --project src/Aspire.Cli/Aspire.Cli.csproj`. + # doesn't need NativeAOT CLI binaries. The consumer smoke separately publishes + # a Release bundled driver so guest restores cannot substitute source projects. run: | ./build.sh -restore -build -ci -pack \ -p:StabilizePackageVersion=true \ diff --git a/.github/workflows/cli-starter-validation.yml b/.github/workflows/cli-starter-validation.yml index 1027ca349c9..2a906eeeea9 100644 --- a/.github/workflows/cli-starter-validation.yml +++ b/.github/workflows/cli-starter-validation.yml @@ -35,10 +35,10 @@ jobs: if: ${{ github.repository == 'microsoft/aspire' }} runs-on: ${{ inputs.runner }} # Shared budget for every caller of this reusable workflow. The validation script can spend - # up to four startup waits (run + start for two templates) and three resource waits, which is - # 27 minutes on the current Windows ARM64 input set before template creation, package add, log + # up to six startup waits (run + start for three templates) and five resource waits, which is + # 42 minutes on the current Windows ARM64 input set before template creation, package add, log # collection, and artifact upload. Keep the job timeout above that aggregate budget. - timeout-minutes: 45 + timeout-minutes: 60 env: GH_TOKEN: ${{ github.token }} steps: @@ -63,6 +63,44 @@ jobs: with: node-version: '22' + - name: Setup Go + shell: pwsh + # Download the official toolchain directly so this lane needs no additional action pin. + # Verify the archive using the checksum published by https://go.dev/dl/?mode=json. + run: | + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $true + $os = switch ('${{ runner.os }}') { + 'Windows' { 'windows' } + 'macOS' { 'darwin' } + 'Linux' { 'linux' } + default { throw 'Unsupported runner OS' } + } + $arch = switch ('${{ runner.arch }}') { + 'X64' { 'amd64' } + 'ARM64' { 'arm64' } + default { throw 'Unsupported runner architecture' } + } + $releases = Invoke-RestMethod 'https://go.dev/dl/?mode=json&include=all' + $release = $releases | Where-Object version -EQ 'go1.26.10' + $archive = @($release.files | Where-Object { $_.os -eq $os -and $_.arch -eq $arch -and $_.kind -eq 'archive' }) + if ($archive.Count -ne 1) { throw "Expected one Go archive for $os/$arch" } + $download = Join-Path $env:RUNNER_TEMP $archive[0].filename + Invoke-WebRequest "https://go.dev/dl/$($archive[0].filename)" -OutFile $download + if ((Get-FileHash $download -Algorithm SHA256).Hash -ne $archive[0].sha256) { + throw 'Go archive checksum mismatch' + } + $destination = Join-Path $env:RUNNER_TEMP 'starter-go' + New-Item -ItemType Directory -Path $destination -Force | Out-Null + if ($os -eq 'windows') { + Expand-Archive $download -DestinationPath $destination + } else { + tar -xzf $download -C $destination + } + $goBin = Join-Path $destination 'go/bin' + $goBin >> $env:GITHUB_PATH + & (Join-Path $goBin 'go') version + - name: Install Aspire CLI from PR dogfood script shell: pwsh env: @@ -79,7 +117,7 @@ jobs: - name: Create starter app and validate startup # Leave headroom above the script's aggregate wait budget so slower runs can still finish # template creation, aspire add, and cleanup instead of being cancelled mid-validation. - timeout-minutes: 40 + timeout-minutes: 55 shell: pwsh env: PR_NUMBER: ${{ inputs.prNumber }} diff --git a/.github/workflows/polyglot-validation/test-go-playground.sh b/.github/workflows/polyglot-validation/test-go-playground.sh index 63ee330aafd..60f9d22b44a 100755 --- a/.github/workflows/polyglot-validation/test-go-playground.sh +++ b/.github/workflows/polyglot-validation/test-go-playground.sh @@ -2,7 +2,7 @@ # Polyglot SDK Validation - Go validation AppHosts # Iterates all Go validation AppHosts under tests/PolyglotAppHosts/*/Go, # runs 'aspire restore --apphost' to regenerate the per-integration .aspire/modules/ SDK, and -# compile-checks each AppHost with 'go build ./...' to verify the generated API surface. +# builds and vets each AppHost against its own generated API surface. set -euo pipefail echo "=== Go Validation AppHost Codegen Validation ===" @@ -85,6 +85,14 @@ for app_dir in "${APP_DIRS[@]}"; do continue fi + echo " → go vet ./..." + if ! go vet ./... 2>&1; then + echo " ❌ go vet failed for $integration_name" + FAILED+=("$integration_name (go vet)") + echo "" + continue + fi + echo " ✅ $integration_name passed" PASSED+=("$integration_name") echo "" diff --git a/.github/workflows/polyglot-validation/test-go.sh b/.github/workflows/polyglot-validation/test-go.sh index f4596ea894e..f86dde2b75f 100755 --- a/.github/workflows/polyglot-validation/test-go.sh +++ b/.github/workflows/polyglot-validation/test-go.sh @@ -67,6 +67,23 @@ if grep -q "builder.Build()" apphost.go; then print "\tif missingValue != nil {" print "\t\tlog.Fatalf(\"Expected missing configuration key to return nil, got %q\", *missingValue)" print "\t}" + print "\tchildren, err := builder.GetConfiguration().GetChildren()" + print "\tif err != nil {" + print "\t\tlog.Fatalf(\"Failed to decode configuration children: %v\", err)" + print "\t}" + print "\tfoundSection := false" + print "\tfor _, child := range children {" + print "\t\tkey, err := child.Key()" + print "\t\tif err != nil {" + print "\t\t\tlog.Fatalf(\"Failed to read configuration child key: %v\", err)" + print "\t\t}" + print "\t\tif key == \"PolyglotTest\" {" + print "\t\t\tfoundSection = true" + print "\t\t}" + print "\t}" + print "\tif !foundSection {" + print "\t\tlog.Fatal(\"Configuration children did not include PolyglotTest\")" + print "\t}" print "" print "\t// Add Redis cache resource" print "\tredis := builder.AddRedis(\"cache\", &aspire.AddRedisOptions{Port: aspire.Float64Ptr(0)}).WithImageRegistry(\"netaspireci.azurecr.io\")" diff --git a/docs/ci/test-trigger-map.md b/docs/ci/test-trigger-map.md index b9d642150f7..1673cfd87aa 100644 --- a/docs/ci/test-trigger-map.md +++ b/docs/ci/test-trigger-map.md @@ -105,6 +105,15 @@ still select their normal validation. | `ALL` | every selector target; PR CI runs the full PR test matrix and all PR-gated jobs, while independently scheduled, dispatched, or outerloop targets remain advisory | | `` | a named group (see `groups:`) expanding **recursively** to its `test:`/`job:` members | +Starter validation runs C#, TypeScript, and Go starters on all six native runner +platforms. The Go scenario waits for the API on every platform and Redis on Linux. +Containerless macOS/Windows runners use `--use-redis-cache false`; the default +Redis-enabled starter remains covered by Linux runners and Docker CLI E2E tests. +Changes to their hosting/code-generation packages select this lane through runtime consumer rules. +The stabilization smoke separately scaffolds and restores Go and Java starters +against the isolated local stable feed; it runs only when the stabilization gate +is enabled, not through the test selector. + Unconditional baseline builds are not selector targets. Gated reusable workflows are routed to the target they implement or serve. diff --git a/eng/github-ci/test-trigger-map.yml b/eng/github-ci/test-trigger-map.yml index bdd48f47a42..6935c670ead 100644 --- a/eng/github-ci/test-trigger-map.yml +++ b/eng/github-ci/test-trigger-map.yml @@ -632,8 +632,11 @@ affected_project_rules: - Aspire.Hosting.Dotnet - Aspire.Hosting.CodeGeneration.TypeScript - Aspire.Hosting.JavaScript + - Aspire.Hosting.CodeGeneration.Go + - Aspire.Hosting.Go + - Aspire.Hosting.Redis targets: [job:cli-starter-validation] - reason: direct executables, SDK, and hosting/code-generation packages used by the C# and TypeScript starter scenarios + reason: direct executables, SDK, and hosting/code-generation packages used by the C#, TypeScript, and Go starter scenarios - projects: [Aspire.Hosting.Dotnet] targets: [test:Aspire.Cli.EndToEnd.Tests, test:Aspire.Templates.Tests] reason: generated C# AppHosts use AddDotnetProject through a runtime-only package reference diff --git a/eng/scripts/cli-starter-validation.ps1 b/eng/scripts/cli-starter-validation.ps1 index 4e27c7763ae..077f87494b4 100644 --- a/eng/scripts/cli-starter-validation.ps1 +++ b/eng/scripts/cli-starter-validation.ps1 @@ -251,6 +251,13 @@ $templates = @( TemplateId = 'aspire-starter' ProjectName = 'AspireCliCsStarterSmoke' ExpectedResources = @('apiservice') + }, + @{ + TemplateId = 'aspire-go-starter' + ProjectName = 'AspireCliGoStarterSmoke' + # Hosted macOS/Windows runners have no Linux container runtime. Keep full Redis + # readiness on Linux; the other runners exercise the supported cache-free starter. + ExpectedResources = $(if ($IsLinux) { @('api', 'cache') } else { @('api') }) } ) @@ -279,7 +286,12 @@ foreach ($template in $templates) { $newStartedAt = Get-Date Write-DiagnosticMessage "${templateId}: invoking aspire new." - aspire new $templateId --name $projectName --output $projectRoot --channel "pr-$PRNumber" --non-interactive --nologo --suppress-agent-init + $templateArguments = @() + if ($templateId -eq 'aspire-go-starter' -and -not $IsLinux) + { + $templateArguments = @('--use-redis-cache', 'false') + } + aspire new $templateId --name $projectName --output $projectRoot --channel "pr-$PRNumber" --non-interactive --nologo --suppress-agent-init @templateArguments Write-DiagnosticMessage "${templateId}: aspire new returned after $([math]::Round(((Get-Date) - $newStartedAt).TotalSeconds, 1)) seconds." Push-Location $projectRoot diff --git a/eng/scripts/stabilization-smoke-init-restore.sh b/eng/scripts/stabilization-smoke-init-restore.sh index b19e019fe6d..42c14cbb891 100755 --- a/eng/scripts/stabilization-smoke-init-restore.sh +++ b/eng/scripts/stabilization-smoke-init-restore.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Stabilization smoke test: aspire new aspire-empty + aspire restore against the locally-built +# Stabilization smoke test: C#, Go, and Java starters + aspire restore against the locally-built # stable Aspire feed. # # Purpose @@ -24,22 +24,19 @@ # This script (the smoke) handles the end-to-end consumer flow specifically. It exercises: # * Template integrity — that `aspire new aspire-empty` produces a buildable project shape # using the stably-built Aspire.ProjectTemplates package. -# * Template version-pinning — that the SDK reference (Aspire.AppHost.Sdk) and any -# PackageReferences emitted by the template resolve against the stable feed for -# Aspire.* packages. +# * Template version-pinning — that the hosting package references emitted by the +# templates resolve against the stable feed for Aspire.* packages. # * Restore wiring — that `aspire restore` succeeds end-to-end for the generated project tree. # -# Coverage NOTE: today `aspire new aspire-empty` resolves to a single-file `apphost.cs` shape -# whose only NuGet dependency is `Aspire.AppHost.Sdk` (which transitively pulls -# Aspire.Hosting.AppHost / Aspire.Hosting). So this smoke validates that the SDK reference path -# is wired correctly through to the local stable feed — NOT that every Aspire integration -# package restores. Per-integration NU5104 (stable depends on preview) detection comes from the +# Coverage NOTE: `aspire new aspire-empty` resolves to a single-file `apphost.cs` with +# Aspire.Hosting.AppHost and Aspire.Hosting.Dotnet package directives. Go and Java starters +# additionally validate their hosting package versions, not every integration. +# Per-integration NU5104 (stable depends on preview) detection comes from the # previous step in the stabilization_check job (the stabilized pack). The two are complementary. # -# Aspire.* packages MUST come from the local stable feed (so missing/preview-only Aspire packages -# fail restore here, exactly as they would on a real stabilization branch). Non-Aspire deps -# pulled in by the template (Microsoft.Extensions.*, OpenTelemetry.*, etc.) are routed to the -# normal public dotnet feeds via packageSourceMapping — they're not the surface we're validating. +# Aspire.* packages MUST come from the local stable feed, selected by ASPIRE_CLI_PACKAGES +# (so missing/preview-only Aspire packages fail restore here). Non-Aspire dependencies +# (Microsoft.Extensions.*, OpenTelemetry.*, etc.) use nuget.org. # # The pack-time NU5104 check (the primary detector for the Foo.Lib scenario above) is the # previous step in the stabilization_check job in ci.yml — this script complements it by @@ -62,6 +59,10 @@ # STABILIZATION_SMOKE_CONFIGURATION Build configuration the pack step used (default: Debug) # STABILIZATION_SMOKE_FEED Absolute path to the local NuGet feed # (default: $REPO_ROOT/artifacts/packages/$CONFIG/Shipping) +# +# The driver is always a Release bundled CLI published outside the checkout, regardless of +# the pack configuration. Java is enabled only for its subprocess. Its preview-only hosting +# package is deliberately not substituted for the stable version emitted by the starter. set -euo pipefail @@ -72,7 +73,7 @@ LOCAL_FEED="${STABILIZATION_SMOKE_FEED:-$REPO_ROOT/artifacts/packages/$CONFIGURA ASPIRE_CLI_PROJECT="$REPO_ROOT/src/Aspire.Cli/Aspire.Cli.csproj" # Use the repo-local SDK that restore.sh / build.sh install under .dotnet/. The wrapper script # also sets DOTNET_SKIP_FIRST_TIME_EXPERIENCE and resolves the SDK version from global.json, -# which is what we need on CI runners that don't have a system-wide .NET 10 SDK. +# which is what we need on CI runners without the repository's pinned SDK. DOTNET="$REPO_ROOT/dotnet.sh" echo "=== Stabilization smoke: aspire new aspire-empty + restore ===" @@ -122,52 +123,87 @@ WORK_DIR="$(mktemp -d -t aspire-stab-smoke-XXXXXXXX)" trap 'rm -rf "$WORK_DIR"' EXIT echo "Work dir: $WORK_DIR" -# Build the CLI project up-front (under stabilization) so subsequent `dotnet run` invocations -# from inside the temp dir don't trigger a build in the test working directory (which would -# pull in the temp dir's NuGet.config and try to restore the CLI's own dependencies against -# our local-only feed). +# Pin the driver and generated projects to the SDK that the stabilized pack produced. +APPHOST_SDK_NUPKG=$(ls "$LOCAL_FEED"/Aspire.AppHost.Sdk.*.nupkg 2>/dev/null \ + | grep -E '/Aspire\.AppHost\.Sdk\.[0-9]+\.[0-9]+\.[0-9]+\.nupkg$' \ + | head -1 || true) +if [ -z "$APPHOST_SDK_NUPKG" ]; then + echo "❌ No stable Aspire.AppHost.Sdk.MAJOR.MINOR.PATCH.nupkg in $LOCAL_FEED — can't pin the template SDK version." + exit 1 +fi +# For example, Aspire.AppHost.Sdk.17.0.0.nupkg becomes 17.0.0. +APPHOST_SDK_VERSION=$(basename "$APPHOST_SDK_NUPKG" .nupkg) +APPHOST_SDK_VERSION="${APPHOST_SDK_VERSION#Aspire.AppHost.Sdk.}" +echo " ✓ Pinned Aspire.AppHost.Sdk version: $APPHOST_SDK_VERSION (from $(basename "$APPHOST_SDK_NUPKG"))" + +# dotnet --info prints a line such as " RID: linux-x64". Use the SDK's host RID +# rather than assuming x64 when the smoke is run locally on another architecture. +RUNTIME_IDENTIFIER=$(DOTNET_CLI_UI_LANGUAGE=en-US "$DOTNET" --info | awk '/^[[:space:]]*RID:/ { print $2; exit }') +if [ -z "$RUNTIME_IDENTIFIER" ]; then + echo "❌ Could not determine the .NET runtime identifier." + exit 1 +fi + +# Debug checkout drivers select the development server and replace package references +# with source projects. A Release driver with its real bundled server must instead +# resolve the guest template's pins from LOCAL_FEED. echo "" -echo "→ Building Aspire.Cli (stabilized) for use as the smoke driver" +echo "→ Building a stabilized Release CLI bundle for use as the smoke driver" ( cd "$REPO_ROOT" - "$DOTNET" build "$ASPIRE_CLI_PROJECT" \ - -c "$CONFIGURATION" \ + # Bundle.proj invokes child dotnet processes, so the stabilization setting must + # also be inherited by those processes, not only passed to the outer MSBuild. + export StabilizePackageVersion=true + "$DOTNET" build "$REPO_ROOT/eng/Bundle.proj" \ + -c Release \ + -p:StabilizePackageVersion=true \ + "-p:BundleVersion=$APPHOST_SDK_VERSION" \ + "-p:TargetRid=$RUNTIME_IDENTIFIER" \ + -p:SkipNativeBuild=true \ + --nologo -v quiet + "$DOTNET" publish "$ASPIRE_CLI_PROJECT" \ + -c Release -r "$RUNTIME_IDENTIFIER" --self-contained \ + -p:PublishAot=false -p:PublishSingleFile=true \ -p:StabilizePackageVersion=true \ + "-p:VersionPrefix=$APPHOST_SDK_VERSION" \ + "-p:BundlePayloadPath=$REPO_ROOT/artifacts/bundle/aspire-$APPHOST_SDK_VERSION-$RUNTIME_IDENTIFIER.tar.gz" \ + --output "$WORK_DIR/cli" \ --nologo -v quiet ) -# Helper: invoke the CLI via the repo-local SDK. Intentionally does NOT change directory — +# Keep consumer restores cold, independently of the packages needed to build the driver. +# The package override also reaches the server's temporary integration project, which +# cannot discover the consumer workspace's NuGet.config. +export NUGET_PACKAGES="$WORK_DIR/.nuget/packages" +export ASPIRE_CLI_PACKAGES="$LOCAL_FEED" +# The standalone driver no longer inherits dotnet.sh's SDK environment. +export DOTNET_ROOT="$REPO_ROOT/.dotnet" +export PATH="$DOTNET_ROOT:$PATH" + +# Helper: invoke the bundled CLI outside the checkout. Intentionally does NOT change directory — # the caller's CWD is what propagates to the spawned aspire process. That matters because: # * aspire's --output (and other path-based) flags resolve relative paths against # Environment.CurrentDirectory. -# * NuGet config-walk starts from CWD, so we want the temp-dir NuGet.config (with the -# Aspire* -> local-stable source mapping) to be the one found, not the repo's own +# * NuGet config-walk starts from CWD, so we want the temp-dir NuGet.config +# to be the one found, not the repo's own # NuGet.config which points at dnceng-internal feeds. -# (`./dotnet.sh` resolves the local SDK via $scriptroot — independent of CWD — so we don't -# need to be in $REPO_ROOT for the SDK lookup.) -# --no-build because we just built above; --no-launch-profile keeps src/Aspire.Cli/Properties/ -# launchSettings.json from interfering with our explicit args. --non-interactive (a recursive +# --non-interactive (a recursive # root-level option, see Aspire.Cli/Commands/RootCommand.cs: NonInteractiveOption with # Recursive = true) is the canonical "I'm in CI, never prompt" flag. The explicit suppression # flags below (--language, --suppress-agent-init, --localhost-tld) supply the actual *values* # we want for the known prompts; --non-interactive guards against any future prompt being # added without a matching suppression flag, and against ambient prompts like the certificate # trust check. -run_aspire() { - "$DOTNET" run --project "$ASPIRE_CLI_PROJECT" \ - -c "$CONFIGURATION" \ - --no-build \ - --no-launch-profile \ - -p:StabilizePackageVersion=true \ - -- --non-interactive "$@" -} +run_aspire() ( + # Release normally avoids repository discovery, but an inherited explicit + # developer override would still select source references. + unset ASPIRE_REPO_ROOT + "$WORK_DIR/cli/aspire" --non-interactive "$@" +) -# Stage a NuGet.config in the work dir BEFORE running `aspire new`. The CLI itself fetches -# the templates package via NuGet, and the subsequent restore needs both Aspire.* (from local -# stable) and any non-Aspire transitives. packageSourceMapping pins Aspire.* to our feed so -# a missing/preview Aspire dep fails fast rather than silently falling back to nuget.org for -# an older stable release. Everything else flows from nuget.org — matches what an end user -# running `aspire new` would have configured by default. +# Isolate ambient feeds without pre-owning the CLI's channel mapping. ASPIRE_CLI_PACKAGES +# supplies the authoritative Aspire* policy; Go and C# scaffold their project-local mappings. +# An inherited user-owned mapping for that same feed cannot safely be rewritten by scaffolding. cat > "$WORK_DIR/NuGet.config" < @@ -176,13 +212,9 @@ cat > "$WORK_DIR/NuGet.config" < - - - - @@ -192,28 +224,57 @@ cat > "$WORK_DIR/NuGet.config" < EOF -echo " ✓ Source-mapped NuGet.config written (Aspire* -> local-stable; everything else -> nuget.org)" +echo " ✓ Isolated NuGet.config written (Aspire* uses the CLI's local stable-feed override)" PROJECT_NAME="MyAspireApp" # Absolute path so `--output` is unambiguous regardless of CWD. PROJECT_DIR="$WORK_DIR/$PROJECT_NAME" -# Derive the exact Aspire.AppHost.Sdk version from the local feed. We pass this via -# `aspire new --version` AND assert later that the generated apphost.cs references this -# exact version (rather than whatever the CLI's own template-version resolution would -# pick). This makes the smoke test the precise contract — "the AppHost SDK this stable -# build packed is what the generated app restores from $LOCAL_FEED" — instead of -# leaving room for the CLI to silently pick a different version that then fails restore -# with a confusing "not found in local feed" message. -APPHOST_SDK_NUPKG=$(ls "$LOCAL_FEED"/Aspire.AppHost.Sdk.[0-9]*.[0-9]*.[0-9]*.nupkg 2>/dev/null | head -1) -if [ -z "$APPHOST_SDK_NUPKG" ]; then - echo "❌ No Aspire.AppHost.Sdk.*.nupkg in $LOCAL_FEED — can't pin the template SDK version." - exit 1 -fi -# Strip the leading 'Aspire.AppHost.Sdk.' prefix and trailing '.nupkg' to get the version. -APPHOST_SDK_VERSION=$(basename "$APPHOST_SDK_NUPKG" .nupkg) -APPHOST_SDK_VERSION="${APPHOST_SDK_VERSION#Aspire.AppHost.Sdk.}" -echo " ✓ Pinned Aspire.AppHost.Sdk version: $APPHOST_SDK_VERSION (from $(basename "$APPHOST_SDK_NUPKG"))" +# Exercise both guest starters even if one fails, so a preview-only hosting package does not +# hide the other language's result. Keep the template's actual pins: rewriting them to whatever +# exists in the feed would mask the stabilization regression this smoke is intended to catch. +GUEST_FAILURES=() +for language in go java; do + guest_dir="$WORK_DIR/${language}-starter" + echo "" + echo "→ Scaffolding and restoring $language starter against the stable feed" + if ! ( + if [ "$language" = java ]; then + # Java is opt-in. Enable it only in this smoke subprocess so template + # filtering cannot hide the stable-package restore being tested. + export features__experimentalPolyglotJava=true + fi + cd "$WORK_DIR" || exit $? + run_aspire new "aspire-${language}-starter" \ + --name "Stable${language}Starter" \ + --output "$guest_dir" \ + --source "$LOCAL_FEED" \ + --version "$APPHOST_SDK_VERSION" \ + --suppress-agent-init \ + --localhost-tld false < /dev/null || exit $? + cd "$guest_dir" || exit $? + run_aspire restore < /dev/null || exit $? + # A development server can succeed with source references instead. Require cold + # NuGet extraction of the pinned hosting packages and retain their provenance in CI. + packages=("aspire.hosting.$language") + if [ "$language" = go ]; then + packages+=(aspire.hosting.redis) + fi + for package in "${packages[@]}"; do + metadata="$NUGET_PACKAGES/$package/$APPHOST_SDK_VERSION/.nupkg.metadata" + if [ ! -f "$metadata" ]; then + echo "❌ Restore did not extract $package/$APPHOST_SDK_VERSION from NuGet." + exit 1 + fi + echo " ✓ Restored $package/$APPHOST_SDK_VERSION; NuGet provenance:" + cat "$metadata" || exit $? + echo "" + done + ); then + GUEST_FAILURES+=("$language") + echo "❌ $language starter could not restore its emitted package pins from the stable feed." + fi +done echo "" echo "→ aspire new aspire-empty --name $PROJECT_NAME --output $PROJECT_DIR --version $APPHOST_SDK_VERSION --language csharp --suppress-agent-init --localhost-tld false" @@ -224,11 +285,10 @@ echo "→ aspire new aspire-empty --name $PROJECT_NAME --output $PROJECT_DIR --v # --localhost-tld false suppresses the localhost-tld prompt # --source pins the templates-package fetch to our local-stable feed, so we test the templates # we just packed (not whatever's on nuget.org). -# --version pins the Aspire.AppHost.Sdk version emitted into the generated AppHost; without +# --version pins the hosting package versions emitted into the generated AppHost; without # it, the CLI's own template-version resolution decides. We want this smoke to test the exact -# version we just packed. -# CWD is $WORK_DIR so the temp NuGet.config (with Aspire* source-mapped to local-stable) is -# the one NuGet finds via its config walk. +# product version we just packed. +# CWD is $WORK_DIR so NuGet discovers the isolated consumer configuration. ( cd "$WORK_DIR" run_aspire new aspire-empty \ @@ -250,17 +310,18 @@ if [ ! -d "$PROJECT_DIR" ]; then echo "❌ aspire new did not create the project directory $PROJECT_DIR" exit 1 fi -APPHOST_SDK_REF_FILE="" +APPHOST_REF_FILE="" if [ -f "$PROJECT_DIR/apphost.cs" ] && [ -f "$PROJECT_DIR/aspire.config.json" ]; then echo " ✓ Single-file AppHost detected (apphost.cs + aspire.config.json)" - # Single-file AppHosts reference the SDK as `#:sdk Aspire.AppHost.Sdk@`. - APPHOST_SDK_REF_FILE="$PROJECT_DIR/apphost.cs" - EXPECTED_SDK_REF="#:sdk Aspire.AppHost.Sdk@$APPHOST_SDK_VERSION" + # File-based AppHosts use "#:package Aspire.Hosting.AppHost@17.0.0", not #:sdk. + APPHOST_REF_FILE="$PROJECT_DIR/apphost.cs" + EXPECTED_APPHOST_REF="#:package Aspire.Hosting.AppHost@$APPHOST_SDK_VERSION" + REFERENCE_MATCH=(-qxF) elif [ -f "$PROJECT_DIR/$PROJECT_NAME.AppHost/$PROJECT_NAME.AppHost.csproj" ]; then echo " ✓ Project-based AppHost detected ($PROJECT_NAME.AppHost.csproj)" - # Project-based AppHosts reference the SDK as `Sdk="Aspire.AppHost.Sdk/"`. - APPHOST_SDK_REF_FILE="$PROJECT_DIR/$PROJECT_NAME.AppHost/$PROJECT_NAME.AppHost.csproj" - EXPECTED_SDK_REF="Aspire.AppHost.Sdk/$APPHOST_SDK_VERSION" + APPHOST_REF_FILE="$PROJECT_DIR/$PROJECT_NAME.AppHost/$PROJECT_NAME.AppHost.csproj" + EXPECTED_APPHOST_REF="Include=\"Aspire.Hosting.AppHost\" Version=\"$APPHOST_SDK_VERSION\"" + REFERENCE_MATCH=(-qF) else echo "❌ aspire new produced an unrecognized layout in $PROJECT_DIR" echo " Contents (depth 3):" @@ -268,24 +329,29 @@ else exit 1 fi -# Assert the AppHost references the exact SDK version we pinned. Catches the failure mode +# Assert the AppHost references the exact hosting version we pinned. Catches the failure mode # where `--version` is ignored / overridden by CLI template-version resolution. Without # this assertion, a mismatch would later surface as a confusing "package not found in -# local-stable feed" restore error instead of a clear "wrong SDK version emitted." -if ! grep -qF "$EXPECTED_SDK_REF" "$APPHOST_SDK_REF_FILE"; then - echo "❌ Expected AppHost SDK reference not found in $APPHOST_SDK_REF_FILE:" - echo " Expected: $EXPECTED_SDK_REF" - echo " Actual SDK references in file:" - grep -E '(#:sdk|Sdk=)' "$APPHOST_SDK_REF_FILE" || true +# local stable feed" restore error instead of a clear "wrong hosting version emitted." +if ! grep "${REFERENCE_MATCH[@]}" "$EXPECTED_APPHOST_REF" "$APPHOST_REF_FILE"; then + echo "❌ Expected AppHost package reference not found in $APPHOST_REF_FILE:" + echo " Expected: $EXPECTED_APPHOST_REF" + echo " Actual package references in file:" + grep -E '(#:package|PackageReference)' "$APPHOST_REF_FILE" || true exit 1 fi -echo " ✓ AppHost references the pinned SDK ($EXPECTED_SDK_REF)" +echo " ✓ AppHost references the pinned hosting package ($EXPECTED_APPHOST_REF)" echo "" echo "→ aspire restore (against local stable feed for Aspire packages, nuget.org for everything else)" # Run from $PROJECT_DIR so aspire restore discovers aspire.config.json there AND so the -# nearest NuGet.config (the one we wrote at $WORK_DIR) is the one used. +# NuGet discovers both the CLI's project-local source policy and our isolated parent defaults. (cd "$PROJECT_DIR" && run_aspire restore < /dev/null) +if [ ${#GUEST_FAILURES[@]} -gt 0 ]; then + echo "❌ Guest starter stabilization failures: ${GUEST_FAILURES[*]}" + exit 1 +fi + echo "" -echo "✅ Stabilization smoke passed: aspire new aspire-empty + restore both succeeded against stable packages, with Aspire.AppHost.Sdk pinned to $APPHOST_SDK_VERSION." +echo "✅ Stabilization smoke passed: C#, Go, and Java scaffolding and restore succeeded against stable packages pinned to $APPHOST_SDK_VERSION." diff --git a/src/Aspire.Cli/Templating/CliTemplateFactory.GoStarterTemplate.cs b/src/Aspire.Cli/Templating/CliTemplateFactory.GoStarterTemplate.cs index 3d4aca1ec33..2a1c40330e1 100644 --- a/src/Aspire.Cli/Templating/CliTemplateFactory.GoStarterTemplate.cs +++ b/src/Aspire.Cli/Templating/CliTemplateFactory.GoStarterTemplate.cs @@ -36,6 +36,8 @@ private async Task ApplyGoStarterTemplateAsync(CallbackTemplate _logger.LogDebug("Applying Go starter template. ProjectName: {ProjectName}, OutputPath: {OutputPath}, AspireVersion: {AspireVersion}.", projectName, outputPath, aspireVersion); var useLocalhostTld = await ResolveUseLocalhostTldAsync(parseResult, cancellationToken); + // Keep the existing Redis-enabled default, including non-interactive scaffolding. + var useRedisCache = parseResult.GetValue(_useRedisCacheOption) ?? true; TemplateResult templateResult; try @@ -52,11 +54,19 @@ private async Task ApplyGoStarterTemplateAsync(CallbackTemplate var projectNameLower = projectName.ToLowerInvariant(); var ports = GenerateRandomPorts(); var hostName = useLocalhostTld ? $"{projectNameLower}.dev.localhost" : "localhost"; - string ApplyAllTokens(string content) => ApplyTokens(content, projectName, projectNameLower, aspireVersion, ports, hostName); + var conditions = new Dictionary { ["redis"] = useRedisCache }; + string ApplyAllTokens(string content) => ConditionalBlockProcessor.Process( + ApplyTokens(content, projectName, projectNameLower, aspireVersion, ports, hostName), + conditions); _logger.LogDebug("Copying embedded Go starter template files to '{OutputPath}'.", outputPath); await CopyTemplateTreeToDiskAsync("go-starter", outputPath, ApplyAllTokens, cancellationToken); + if (useRedisCache) + { + AddRedisPackageToConfig(outputPath, aspireVersion); + } + // Persist the resolved channel into the scaffolded project's aspire.config.json // when NewCommand resolved an Explicit channel (pr-, daily, staging, local). // Without this pin, `aspire update` skips the local-config step in its diff --git a/src/Aspire.Cli/Templating/CliTemplateFactory.cs b/src/Aspire.Cli/Templating/CliTemplateFactory.cs index 7e23407193a..484f7f053e4 100644 --- a/src/Aspire.Cli/Templating/CliTemplateFactory.cs +++ b/src/Aspire.Cli/Templating/CliTemplateFactory.cs @@ -218,7 +218,11 @@ private IEnumerable GetTemplateDefinitions() KnownTemplateId.GoStarter, "Starter App (Go API + Redis, Go AppHost)", (ctx, projectName) => OutputPathHelper.GetUniqueDefaultOutputPath(projectName, ctx.WorkingDirectory.FullName), - cmd => AddOptionIfMissing(cmd, _localhostTldOption), + cmd => + { + AddOptionIfMissing(cmd, _localhostTldOption); + AddOptionIfMissing(cmd, _useRedisCacheOption); + }, ApplyGoStarterTemplateAsync, runtime: TemplateRuntime.Cli, languageId: KnownLanguageId.Go), diff --git a/src/Aspire.Cli/Templating/Templates/go-starter/api/go.mod b/src/Aspire.Cli/Templating/Templates/go-starter/api/go.mod index b1294da4da9..5c0ed973c55 100644 --- a/src/Aspire.Cli/Templating/Templates/go-starter/api/go.mod +++ b/src/Aspire.Cli/Templating/Templates/go-starter/api/go.mod @@ -4,20 +4,17 @@ go 1.26 require ( github.com/redis/go-redis/v9 v9.19.0 - go.opentelemetry.io/auto/sdk v1.2.1 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0 go.opentelemetry.io/otel v1.43.0 go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.19.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 go.opentelemetry.io/otel/log v0.19.0 go.opentelemetry.io/otel/metric v1.43.0 go.opentelemetry.io/otel/sdk v1.43.0 go.opentelemetry.io/otel/sdk/log v0.19.0 go.opentelemetry.io/otel/sdk/metric v1.43.0 - go.opentelemetry.io/otel/trace v1.43.0 ) require ( @@ -28,6 +25,9 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect go.opentelemetry.io/proto/otlp v1.10.0 // indirect go.uber.org/atomic v1.11.0 // indirect golang.org/x/net v0.52.0 // indirect diff --git a/src/Aspire.Cli/Templating/Templates/go-starter/api/go.sum b/src/Aspire.Cli/Templating/Templates/go-starter/api/go.sum new file mode 100644 index 00000000000..caf8e353f23 --- /dev/null +++ b/src/Aspire.Cli/Templating/Templates/go-starter/api/go.sum @@ -0,0 +1,89 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k= +github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= +go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0 h1:jhVIQEprwUTV+KfzzliLidclhoTOoHTgdz96kAyR8mU= +go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0/go.mod h1:4HsdbLUbernaTnA8CNaNE+1g026SciXb3juRYe3l8EY= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.19.0 h1:Dn8rkudDzY6KV9dr/D/bTUuWgqDf9xe0rr4G2elrn0Y= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.19.0/go.mod h1:gMk9F0xDgyN9M/3Ed5Y1wKcx/9mlU91NXY2SNq7RQuU= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 h1:8UQVDcZxOJLtX6gxtDt3vY2WTgvZqMQRzjsqiIHQdkc= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0/go.mod h1:2lmweYCiHYpEjQ/lSJBYhj9jP1zvCvQW4BqL9dnT7FQ= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 h1:RAE+JPfvEmvy+0LzyUA25/SGawPwIUbZ6u0Wug54sLc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod h1:AGmbycVGEsRx9mXMZ75CsOyhSP6MFIcj/6dnG+vhVjk= +go.opentelemetry.io/otel/log v0.19.0 h1:KUZs/GOsw79TBBMfDWsXS+KZ4g2Ckzksd1ymzsIEbo4= +go.opentelemetry.io/otel/log v0.19.0/go.mod h1:5DQYeGmxVIr4n0/BcJvF4upsraHjg6vudJJpnkL6Ipk= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk/log v0.19.0 h1:scYVLqT22D2gqXItnWiocLUKGH9yvkkeql5dBDiXyko= +go.opentelemetry.io/otel/sdk/log v0.19.0/go.mod h1:vFBowwXGLlW9AvpuF7bMgnNI95LiW10szrOdvzBHlAg= +go.opentelemetry.io/otel/sdk/log/logtest v0.19.0 h1:BEbF7ZBB6qQloV/Ub1+3NQoOUnVtcGkU3XX4Ws3GQfk= +go.opentelemetry.io/otel/sdk/log/logtest v0.19.0/go.mod h1:Lua81/3yM0wOmoHTokLj9y9ADeA02v1naRrVrkAZuKk= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g= +go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= +google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/src/Aspire.Cli/Templating/Templates/go-starter/apphost.go b/src/Aspire.Cli/Templating/Templates/go-starter/apphost.go index a60e95b1216..2f0aded6fc7 100644 --- a/src/Aspire.Cli/Templating/Templates/go-starter/apphost.go +++ b/src/Aspire.Cli/Templating/Templates/go-starter/apphost.go @@ -12,24 +12,26 @@ func main() { log.Fatal(aspire.FormatError(err)) } - // A Redis cache the API will use for read-through caching. - cache := builder.AddRedis("cache") - // The Go HTTP API. WithModTidy runs "go mod tidy" before launching so that // go.sum is always up to date. Aspire injects: - // - "ConnectionStrings__cache" so the API can dial Redis. // - "OTEL_EXPORTER_OTLP_*" env vars (via WithOtlpExporter) so traces, // metrics, and logs flow to the Aspire dashboard. api := builder.AddGoApp("api", "./api"). WithModTidy(). - WithReference(cache). - WaitFor(cache). WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). WithExternalHttpEndpoints(). WithOtlpExporter() + resources := []aspire.Resource{api} + // {{#redis}} + + // WithReference injects ConnectionStrings__cache for read-through caching. + cache := builder.AddRedis("cache") + api.WithReference(cache).WaitFor(cache) + resources = append(resources, cache) + // {{/redis}} // Each call records its failure on the handle that it returns, so check every resource. - for _, resource := range []aspire.Resource{cache, api} { + for _, resource := range resources { if err := resource.Err(); err != nil { log.Fatal(aspire.FormatError(err)) } diff --git a/src/Aspire.Cli/Templating/Templates/go-starter/aspire.config.json b/src/Aspire.Cli/Templating/Templates/go-starter/aspire.config.json index be29d78565c..b52075dbdd0 100644 --- a/src/Aspire.Cli/Templating/Templates/go-starter/aspire.config.json +++ b/src/Aspire.Cli/Templating/Templates/go-starter/aspire.config.json @@ -4,8 +4,7 @@ "language": "go" }, "packages": { - "Aspire.Hosting.Go": "{{aspireVersion}}", - "Aspire.Hosting.Redis": "{{aspireVersion}}" + "Aspire.Hosting.Go": "{{aspireVersion}}" }, "profiles": { "https": { diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs index 31c306ede4b..a1b8b41f687 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs @@ -75,6 +75,7 @@ private static async Task RestoreBuildAndRunAsync( var projectRoot = Path.Combine(workspace.WorkspaceRoot.FullName, projectName); Assert.True(File.Exists(Path.Combine(projectRoot, "apphost.go")), $"Expected apphost.go in {projectRoot}"); Assert.True(File.Exists(Path.Combine(projectRoot, "go.mod")), $"Expected go.mod in {projectRoot}"); + GitIgnoreAssertions.AssertContainsEntry(projectRoot, ".aspire/"); await auto.RunCommandAsync($"cd {projectName}", counter); await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs index 54ddfcf8962..c596f60fb0b 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs @@ -24,7 +24,7 @@ public async Task DeployGoAppToKubernetes() using var workspace = TemporaryWorkspace.Create(output); var clusterName = KubernetesDeployTestHelpers.GenerateUniqueClusterName(); - const string k8sNamespace = "default"; + var k8sNamespace = $"test-{clusterName[..16]}"; output.WriteLine($"Cluster name: {clusterName}"); output.WriteLine($"Namespace: {k8sNamespace}"); @@ -64,11 +64,6 @@ public async Task DeployGoAppToKubernetes() // Regenerate the Go SDK with Kubernetes types await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); - // The starter ships api/go.mod without a go.sum, and its "go mod tidy" resource only runs - // under "aspire run". The generated Dockerfile builds from go.mod and go.sum alone, so - // the container build needs the go.sum that "go mod tidy" writes. - await auto.RunCommandAsync("(cd api && go mod tidy)", counter, TimeSpan.FromMinutes(3)); - // ===================================================================== // Phase 3: Modify apphost.go to add Kubernetes environment // ===================================================================== @@ -77,9 +72,6 @@ public async Task DeployGoAppToKubernetes() output.WriteLine($"Looking for apphost.go at: {appHostFilePath}"); - // The AppHost passes no WithHelm callback: a Configure func inside the generated Go options - // struct panics the options merge (https://github.com/microsoft/aspire/issues/18080), so the - // Helm defaults apply (namespace "default", chart version 0.1.0). GoAppHostTestHelpers.InsertBeforeBuild( appHostFilePath, """ @@ -87,8 +79,14 @@ public async Task DeployGoAppToKubernetes() registryEndpoint := builder.AddParameter("registryendpoint") builder.AddContainerRegistry("registry", registryEndpoint) - // Add Kubernetes environment (Helm is the default deployment engine) - builder.AddKubernetesEnvironment("env") + namespace := builder.AddParameter("namespace") + chartVersion := builder.AddParameter("chartversion") + builder.AddKubernetesEnvironment("env").WithHelm(&aspire.WithHelmOptions{ + Configure: func(helm aspire.HelmChartOptions) { + helm.WithNamespace(namespace) + helm.WithChartVersion(chartVersion) + }, + }) """); output.WriteLine("Modified apphost.go with Kubernetes environment configuration"); @@ -101,6 +99,8 @@ await auto.AspireDeployInteractiveAsync( parameterResponses: [ ("registryendpoint", "localhost:5001"), + ("namespace", k8sNamespace), + ("chartversion", "0.1.0"), ]); // ===================================================================== diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoStarterReadinessTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoStarterReadinessTests.cs new file mode 100644 index 00000000000..e188e66a84b --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoStarterReadinessTests.cs @@ -0,0 +1,69 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Cli.EndToEnd.Tests.Helpers; +using Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +public sealed class GoStarterReadinessTests(ITestOutputHelper output) +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + [CaptureWorkspaceOnFailure] + public async Task StarterShipsTidyApiAndServesRequests(bool useRedisCache) + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + // DCP publishes Redis on the Docker host. The API must reach that host's loopback ports. + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal( + repoRoot, strategy, output, + variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, + mountDockerSocket: useRedisCache, workspace: workspace, network: "host"); + var counter = new SequenceCounter(); + var auto = new Hex1bTerminalAutomator(terminal, defaultTimeout: TimeSpan.FromSeconds(500)); + await using var terminalRun = CliE2ETestHelpers.StartRun(terminal, workspace, auto, counter, output, TestContext.Current.CancellationToken); + + await auto.PrepareDockerEnvironmentAsync(counter, workspace); + await auto.InstallAspireCliAsync(strategy, counter); + if (useRedisCache) + { + await auto.AspireNewAsync("GoReady", counter, template: AspireTemplate.GoStarter); + } + else + { + await auto.RunCommandAsync( + "aspire new aspire-go-starter --name GoReady --output GoReady --use-redis-cache false --localhost-tld false --non-interactive --suppress-agent-init", + counter, + TimeSpan.FromMinutes(3)); + } + + var projectRoot = Path.Combine(workspace.WorkspaceRoot.FullName, "GoReady"); + GitIgnoreAssertions.AssertContainsEntry(projectRoot, ".aspire/"); + Assert.True(File.Exists(Path.Combine(projectRoot, "api", "go.sum"))); + + await auto.RunCommandAsync("cd GoReady", counter); + // Build before any run/start can repair the template through WithModTidy. + await auto.RunCommandAsync("(cd api && go build -mod=readonly -o /tmp/go-ready-api . && go mod tidy -diff)", counter, TimeSpan.FromMinutes(3)); + try + { + await auto.AspireStartAsync(counter, startTimeout: TimeSpan.FromMinutes(4)); + await auto.RunCommandAsync("aspire wait api --status up --timeout 120", counter, TimeSpan.FromMinutes(3)); + await auto.RunCommandAsync("aspire describe api --format json > api.json", counter); + // Describe emits { resources: [{ urls: [{ url: \"http://...\" }] }] }. Use Node, + // already provided by the polyglot image, rather than assuming jq is installed. + await auto.RunCommandAsync( + """API_URL=$(node -e 'const fs = require("node:fs"); const data = JSON.parse(fs.readFileSync("api.json", "utf8")); const url = data.resources[0].urls.find(u => u.url.startsWith("http://")); if (!url) throw new Error("Missing HTTP API URL"); process.stdout.write(url.url.replace(/\/$/, ""));') && curl -fsS --retry 10 --retry-all-errors --retry-delay 1 "$API_URL/health" && curl -fsS "$API_URL/api/weatherforecast" > weather.json && node -e 'const assert = require("node:assert/strict"); const weather = require("./weather.json"); assert.equal(weather.length, 5); for (const forecast of weather) { assert.equal(typeof forecast.temperatureC, "number"); assert.equal(typeof forecast.summary, "string"); }'""", + counter, + TimeSpan.FromMinutes(2)); + } + finally + { + await auto.AspireStopAsync(counter); + } + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs index adfded84d69..4d7e099fb8b 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs @@ -278,7 +278,6 @@ await auto.WaitForAspireNewEmptyAppHostCompletionAsync( projectName, "C#", counter, - AppHostLanguagePromptSelection.DefaultCSharp, effectiveTimeout); } @@ -308,7 +307,6 @@ await auto.WaitForAspireNewEmptyAppHostCompletionAsync( projectName, "TypeScript", counter, - AppHostLanguagePromptSelection.TypeScript, effectiveTimeout); } @@ -338,7 +336,6 @@ await auto.WaitForAspireNewEmptyAppHostCompletionAsync( projectName, "Go", counter, - AppHostLanguagePromptSelection.Go, effectiveTimeout); } @@ -367,7 +364,6 @@ private static async Task WaitForAspireNewEmptyAppHostCompletionAsync( string projectName, string languageDisplayName, SequenceCounter counter, - AppHostLanguagePromptSelection languagePromptSelection, TimeSpan effectiveTimeout) { var languagePrompt = new CellPatternSearcher() @@ -414,7 +410,7 @@ await auto.WaitUntilAsync(snapshot => switch (result) { case AspireNewEmptyAppHostResult.LanguagePrompt: - await auto.SelectAppHostLanguageAsync(languagePromptSelection); + await auto.SelectAppHostLanguageAsync(languageDisplayName); await auto.DeclineAgentInitPromptAsync(counter, effectiveTimeout); return; @@ -434,38 +430,16 @@ await auto.WaitUntilAsync(snapshot => } } - private static async Task SelectAppHostLanguageAsync( + internal static async Task SelectAppHostLanguageAsync( this Hex1bTerminalAutomator auto, - AppHostLanguagePromptSelection languagePromptSelection) + string languageDisplayName) { - switch (languagePromptSelection) - { - case AppHostLanguagePromptSelection.DefaultCSharp: - await auto.EnterAsync(); - return; - - case AppHostLanguagePromptSelection.TypeScript: - await auto.DownAsync(); - await auto.WaitUntilAsync( - s => new CellPatternSearcher().Find("> TypeScript (Node.js)").Search(s).Count > 0, - timeout: TimeSpan.FromSeconds(5), - description: "TypeScript AppHost language selected"); - await auto.EnterAsync(); - return; - - case AppHostLanguagePromptSelection.Go: - // Search by text so the selection does not depend on which other languages the picker lists. - await auto.TypeAsync("Go"); - await auto.WaitUntilAsync( - s => new CellPatternSearcher().Find("> Go").Search(s).Count > 0, - timeout: TimeSpan.FromSeconds(5), - description: "Go AppHost language selected"); - await auto.EnterAsync(); - return; - - default: - throw new InvalidOperationException($"Unexpected AppHost language prompt selection: {languagePromptSelection}."); - } + await auto.TypeAsync(languageDisplayName); + await auto.WaitUntilAsync( + snapshot => new CellPatternSearcher().Find($"> {languageDisplayName}").Search(snapshot).Count > 0, + timeout: TimeSpan.FromSeconds(5), + description: $"{languageDisplayName} AppHost language selected"); + await auto.EnterAsync(); } /// @@ -848,7 +822,7 @@ internal static async Task AspireInitGoAppHostAsync( await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - await auto.SelectAppHostLanguageAsync(AppHostLanguagePromptSelection.Go); + await auto.SelectAppHostLanguageAsync("Go"); await auto.WaitUntilTextAsync("Created apphost.go", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); } @@ -1341,10 +1315,4 @@ private enum AspireNewEmptyAppHostResult ErrorPrompt } - private enum AppHostLanguagePromptSelection - { - DefaultCSharp, - TypeScript, - Go - } } diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/KubernetesDeployTestHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/KubernetesDeployTestHelpers.cs index e9422e23577..8a6a701813c 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/KubernetesDeployTestHelpers.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/KubernetesDeployTestHelpers.cs @@ -25,7 +25,7 @@ internal static string GenerateUniqueClusterName() => /// /// Installs KinD, Helm, and kubectl binaries to ~/.local/bin and adds to PATH. - /// Skips downloads for tools already on PATH (e.g., pre-installed in Dockerfile.e2e). + /// Skips downloads for tools already on PATH. /// Retries downloads up to 3 times to handle transient GitHub CDN failures. /// internal static async Task InstallKindAndHelmAsync( diff --git a/tests/Aspire.Cli.EndToEnd.Tests/JavaCodegenValidationTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/JavaCodegenValidationTests.cs index 29b021a5870..43ab263ab86 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/JavaCodegenValidationTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/JavaCodegenValidationTests.cs @@ -32,12 +32,7 @@ public async Task RestoreGeneratesSdkFiles() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - // Picker order is C#, TypeScript, Go, Java (Python and Rust stay hidden without their flags), so Java is 3 down. - await auto.DownAsync(); - await auto.DownAsync(); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> Java", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("Java"); await auto.WaitUntilTextAsync("Created AppHost.java", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); @@ -57,11 +52,6 @@ public async Task RestoreGeneratesSdkFiles() throw new InvalidOperationException($".aspire/modules directory was not created at {modulesDir}"); } - // The second integration is added only after `.aspire/modules` is already populated. A - // restore that treats a non-empty modules directory as up to date would leave the stale - // SDK in place and still report success, so the SqlServer assertions below are what - // actually prove the refresh. Adding both integrations before the first restore would - // generate everything in one pass and never exercise that path. var codegenHashPath = Path.Combine(modulesDir, ".codegen-hash"); var initialCodegenHash = File.Exists(codegenHashPath) ? File.ReadAllText(codegenHashPath) : null; @@ -71,11 +61,18 @@ public async Task RestoreGeneratesSdkFiles() throw new InvalidOperationException("Baseline SDK already exposes addSqlServer; test cannot verify refresh behavior after adding Aspire.Hosting.SqlServer."); } + // Add regenerates the SDK too. Restore the entire baseline in the container so only + // aspire restore can produce the new exports, source list, and codegen hash. + await auto.RunCommandAsync("cp -a .aspire/modules ~/java-sdk-baseline", counter); await auto.TypeAsync("aspire add Aspire.Hosting.SqlServer"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("The package Aspire.Hosting.", timeout: TimeSpan.FromMinutes(2)); await auto.WaitForSuccessPromptAsync(counter); + await auto.RunCommandAsync("rm -rf .aspire/modules && cp -a ~/java-sdk-baseline .aspire/modules", counter); + Assert.Equal(initialCodegenHash, File.ReadAllText(codegenHashPath)); + Assert.False(File.ReadAllText(builderPath).Contains("addSqlServer", StringComparison.Ordinal)); + await auto.TypeAsync("aspire restore"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("SDK code restored successfully", timeout: TimeSpan.FromMinutes(3)); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotApphostDirectoryTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotApphostDirectoryTests.cs index 954047c99dd..4f79d498e18 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotApphostDirectoryTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotApphostDirectoryTests.cs @@ -50,12 +50,7 @@ public async Task StopJavaPolyglotAppHostUsingApphostDirectory() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - // Picker order is C#, TypeScript, Go, Java (Python and Rust stay hidden without their flags), so Java is 3 down. - await auto.DownAsync(); - await auto.DownAsync(); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> Java", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("Java"); await auto.WaitUntilTextAsync("Created AppHost.java", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotTests.cs index d1736fb71be..284c817c0f1 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/JavaPolyglotTests.cs @@ -32,12 +32,7 @@ public async Task CreateJavaAppHostWithViteApp() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - // Picker order is C#, TypeScript, Go, Java (Python and Rust stay hidden without their flags), so Java is 3 down. - await auto.DownAsync(); - await auto.DownAsync(); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> Java", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("Java"); await auto.WaitUntilTextAsync("Created AppHost.java", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/JavaScriptPublishTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/JavaScriptPublishTests.cs index 18af4fb6ac3..9d4ec92b23e 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/JavaScriptPublishTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/JavaScriptPublishTests.cs @@ -41,9 +41,7 @@ public async Task AllPublishMethodsBuildDockerImages() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/KubernetesDeployTypeScriptTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/KubernetesDeployTypeScriptTests.cs index 8134a1696ec..dcdf5086e80 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/KubernetesDeployTypeScriptTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/KubernetesDeployTypeScriptTests.cs @@ -124,10 +124,12 @@ await auto.AspireDeployInteractiveAsync( // Phase 5: Verify the deployment // ===================================================================== - // Verify pods are running in the namespace - await auto.TypeAsync($"kubectl get pods -n {k8sNamespace} --no-headers"); - await auto.EnterAsync(); - await auto.WaitForSuccessPromptAsync(counter, timeout: TimeSpan.FromSeconds(30)); + // The frontend is bundled into app's image, not deployed as a separate workload. + // Waiting by app's label also fails if the chart omitted its only workload. + await auto.RunCommandAsync( + $"kubectl wait --for=condition=Ready pod -n {k8sNamespace} -l app.kubernetes.io/component=app --timeout=180s", + counter, + TimeSpan.FromMinutes(4)); // ===================================================================== // Phase 6: Cleanup diff --git a/tests/Aspire.Cli.EndToEnd.Tests/LocalConfigMigrationTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/LocalConfigMigrationTests.cs index 47e8320ebe3..54f9d6ccccc 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/LocalConfigMigrationTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/LocalConfigMigrationTests.cs @@ -58,9 +58,7 @@ public async Task LegacySettingsMigration_AdjustsRelativeAppHostPath() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/SecretTypeScriptAppHostTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/SecretTypeScriptAppHostTests.cs index cbb26ba7e7e..81a07a2526b 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/SecretTypeScriptAppHostTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/SecretTypeScriptAppHostTests.cs @@ -31,9 +31,7 @@ public async Task SecretInputSourcesOnTypeScriptAppHost() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("> C#", timeout: TimeSpan.FromSeconds(30)); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); @@ -60,9 +58,7 @@ public async Task SecretCrudOnTypeScriptAppHost() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("> C#", timeout: TimeSpan.FromSeconds(30)); - await auto.DownAsync(); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptCodegenValidationTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptCodegenValidationTests.cs index 8f7cd254642..fd558d39c7b 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptCodegenValidationTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptCodegenValidationTests.cs @@ -61,6 +61,15 @@ public async Task RestoreGeneratesSdkFiles_WithConfiguredToolchain(string toolch CliE2ETestHelpers.WriteLocalChannelSettings(workspace.WorkspaceRoot.FullName, localChannel.SdkVersion); } + // Init supplies SDK sources without the restore cache metadata. Establish a restored + // baseline before saving it so the stale-cache assertions exercise an actual prior restore. + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + await auto.RunCommandAsync("cp -a .aspire/modules ~/typescript-sdk-baseline", counter); + var baselineSdkPath = Path.Combine(workspace.WorkspaceRoot.FullName, ".aspire", "modules", "aspire.mts"); + var baselineSdk = File.ReadAllText(baselineSdkPath); + var baselineHashPath = Path.Combine(workspace.WorkspaceRoot.FullName, ".aspire", "modules", ".codegen-hash"); + var baselineHash = File.ReadAllText(baselineHashPath); + // Step 2: Add two integrations. await auto.TypeAsync("aspire add Aspire.Hosting.Redis"); await auto.EnterAsync(); @@ -70,12 +79,19 @@ public async Task RestoreGeneratesSdkFiles_WithConfiguredToolchain(string toolch await auto.EnterAsync(); await auto.WaitForAspireAddSuccessAsync(counter, TimeSpan.FromMinutes(2)); + // Add already regenerated the SDK; put back the stale files before exercising restore. + await auto.RunCommandAsync("rm -rf .aspire/modules && cp -a ~/typescript-sdk-baseline .aspire/modules", counter); + Assert.Equal(baselineSdk, File.ReadAllText(baselineSdkPath)); + Assert.Equal(baselineHash, File.ReadAllText(baselineHashPath)); + // Step 3: Run aspire restore and verify success. await auto.TypeAsync("aspire restore"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("SDK code restored successfully", timeout: TimeSpan.FromMinutes(3)); await auto.WaitForSuccessPromptAsync(counter); + Assert.NotEqual(baselineHash, File.ReadAllText(baselineHashPath)); + var lockFilePath = Path.Combine( workspace.WorkspaceRoot.FullName, TypeScriptAppHostToolchainTestHelpers.GetLockFileName(toolchain)); @@ -213,12 +229,18 @@ public async Task RestoreRefreshesGeneratedSdkAfterAddingIntegration() var codegenHashPath = Path.Combine(modulesDir, ".codegen-hash"); var initialCodegenHash = File.Exists(codegenHashPath) ? File.ReadAllText(codegenHashPath) : null; + await auto.RunCommandAsync("cp -a .aspire/modules ~/typescript-sdk-baseline", counter); + // Step 2: Add a new integration that is not present in the initial generated SDK. await auto.TypeAsync("aspire add Aspire.Hosting.Redis"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("The package Aspire.Hosting.", timeout: TimeSpan.FromMinutes(2)); await auto.WaitForSuccessPromptAsync(counter); + await auto.RunCommandAsync("rm -rf .aspire/modules && cp -a ~/typescript-sdk-baseline .aspire/modules", counter); + Assert.Equal(initialAspireTs, File.ReadAllText(aspireModulePath)); + Assert.Equal(initialCodegenHash, File.ReadAllText(codegenHashPath)); + // Step 3: Run aspire restore and verify the generated SDK picks up the new exports. await auto.TypeAsync("aspire restore"); await auto.EnterAsync(); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptPublishTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptPublishTests.cs index 93b1dcc7427..b2f3d3ab913 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptPublishTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/TypeScriptPublishTests.cs @@ -3,7 +3,6 @@ using Aspire.Cli.EndToEnd.Tests.Helpers; using Hex1b.Automation; -using Hex1b.Input; using Xunit; namespace Aspire.Cli.EndToEnd.Tests; @@ -162,9 +161,7 @@ public async Task PublishWithDockerComposeServiceCallbackSucceeds() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - await auto.KeyAsync(Hex1bKey.DownArrow); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); @@ -338,9 +335,7 @@ public async Task PublishWithoutOutputPathUsesAppHostDirectoryDefault() await auto.TypeAsync("aspire init"); await auto.EnterAsync(); await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); - await auto.KeyAsync(Hex1bKey.DownArrow); - await auto.WaitUntilTextAsync("> TypeScript (Node.js)", timeout: TimeSpan.FromSeconds(5)); - await auto.EnterAsync(); + await auto.SelectAppHostLanguageAsync("TypeScript"); await auto.WaitUntilTextAsync("Created apphost.mts", timeout: TimeSpan.FromMinutes(2)); await auto.DeclineAgentInitPromptAsync(counter); diff --git a/tests/Aspire.Cli.Tests/Commands/NewCommandTemplateConfigPersistenceTests.cs b/tests/Aspire.Cli.Tests/Commands/NewCommandTemplateConfigPersistenceTests.cs index b334f5fcd5a..337df1e2fab 100644 --- a/tests/Aspire.Cli.Tests/Commands/NewCommandTemplateConfigPersistenceTests.cs +++ b/tests/Aspire.Cli.Tests/Commands/NewCommandTemplateConfigPersistenceTests.cs @@ -233,6 +233,7 @@ public async Task Template_WritesAspireConfigWithOsLineBreaksAndSingleFinalNewli identityChannel: PackageChannelNames.Daily, registerIdentityChannel: false, explicitChannelArg: null, + extraArguments: "", outputDirectory => File.ReadAllText(Path.Combine(outputDirectory, AspireConfigFile.FileName))); LineEndingAssert.UsesOsLineBreaksAndSingleFinalNewline(content); @@ -369,6 +370,34 @@ public async Task NewTemplate_PrDogfoodInstallHiveDiscovered_UsesPrChannel(PrDog } } + [Theory] + [InlineData("default", true)] + [InlineData("true", true)] + [InlineData("false", false)] + public async Task GoStarterHonorsRedisChoice(string choice, bool usesRedis) + { + var (appHost, packages) = await ScaffoldAndReadAsync( + KnownTemplateId.GoStarter, + identityChannel: PackageChannelNames.Daily, + registerIdentityChannel: false, + explicitChannelArg: null, + extraArguments: choice == "default" ? "" : $" --use-redis-cache {choice}", + outputDirectory => + { + var config = AspireConfigFile.Load(outputDirectory); + Assert.NotNull(config); + Assert.NotNull(config.Packages); + return ( + File.ReadAllText(Path.Combine(outputDirectory, "apphost.go")), + config.Packages.Keys.Order(StringComparer.Ordinal).ToArray()); + }); + + Assert.Equal( + usesRedis ? ["Aspire.Hosting.Go", "Aspire.Hosting.Redis"] : ["Aspire.Hosting.Go"], + packages); + await Verify(appHost, "go").UseParameters(choice); + } + /// /// Drives aspire new <templateId> and reads the channel value persisted to /// aspire.config.json in the scaffolded output directory. @@ -388,6 +417,7 @@ public async Task NewTemplate_PrDogfoodInstallHiveDiscovered_UsesPrChannel(PrDog identityChannel, registerIdentityChannel, explicitChannelArg, + extraArguments: "", outputDirectory => AspireConfigFile.Load(outputDirectory)?.Channel); } @@ -402,6 +432,7 @@ private async Task ScaffoldAndReadAsync( string identityChannel, bool registerIdentityChannel, string? explicitChannelArg, + string extraArguments, Func readOutput) { using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); @@ -442,7 +473,7 @@ private async Task ScaffoldAndReadAsync( // `--localhost-tld false` short-circuits the bool? confirmation prompt so the // test is non-interactive. The value doesn't affect channel persistence. var parseResult = newCommand.Parse( - $"new {templateId} --name TemplateOut --output ./{outputDirectoryName} --localhost-tld false{channelArg}"); + $"new {templateId} --name TemplateOut --output ./{outputDirectoryName} --localhost-tld false{channelArg}{extraArguments}"); var exitCode = await parseResult.InvokeAsync().DefaultTimeout(); Assert.Equal((int)CliExitCodes.Success, exitCode); diff --git a/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=default.verified.go b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=default.verified.go new file mode 100644 index 00000000000..d662d666d33 --- /dev/null +++ b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=default.verified.go @@ -0,0 +1,45 @@ +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + // The Go HTTP API. WithModTidy runs "go mod tidy" before launching so that + // go.sum is always up to date. Aspire injects: + // - "OTEL_EXPORTER_OTLP_*" env vars (via WithOtlpExporter) so traces, + // metrics, and logs flow to the Aspire dashboard. + api := builder.AddGoApp("api", "./api"). + WithModTidy(). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints(). + WithOtlpExporter() + resources := []aspire.Resource{api} + + // WithReference injects ConnectionStrings__cache for read-through caching. + cache := builder.AddRedis("cache") + api.WithReference(cache).WaitFor(cache) + resources = append(resources, cache) + + // Each call records its failure on the handle that it returns, so check every resource. + for _, resource := range resources { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} diff --git a/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=false.verified.go b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=false.verified.go new file mode 100644 index 00000000000..e06ad1991ed --- /dev/null +++ b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=false.verified.go @@ -0,0 +1,40 @@ +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + // The Go HTTP API. WithModTidy runs "go mod tidy" before launching so that + // go.sum is always up to date. Aspire injects: + // - "OTEL_EXPORTER_OTLP_*" env vars (via WithOtlpExporter) so traces, + // metrics, and logs flow to the Aspire dashboard. + api := builder.AddGoApp("api", "./api"). + WithModTidy(). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints(). + WithOtlpExporter() + resources := []aspire.Resource{api} + + // Each call records its failure on the handle that it returns, so check every resource. + for _, resource := range resources { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} diff --git a/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=true.verified.go b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=true.verified.go new file mode 100644 index 00000000000..d662d666d33 --- /dev/null +++ b/tests/Aspire.Cli.Tests/Snapshots/NewCommandTemplateConfigPersistenceTests.GoStarterHonorsRedisChoice_choice=true.verified.go @@ -0,0 +1,45 @@ +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + // The Go HTTP API. WithModTidy runs "go mod tidy" before launching so that + // go.sum is always up to date. Aspire injects: + // - "OTEL_EXPORTER_OTLP_*" env vars (via WithOtlpExporter) so traces, + // metrics, and logs flow to the Aspire dashboard. + api := builder.AddGoApp("api", "./api"). + WithModTidy(). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints(). + WithOtlpExporter() + resources := []aspire.Resource{api} + + // WithReference injects ConnectionStrings__cache for read-through caching. + cache := builder.AddRedis("cache") + api.WithReference(cache).WaitFor(cache) + resources = append(resources, cache) + + // Each call records its failure on the handle that it returns, so check every resource. + for _, resource := range resources { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} diff --git a/tests/Infrastructure.Tests/TestTriggerMap/TestTriggerMapTests.cs b/tests/Infrastructure.Tests/TestTriggerMap/TestTriggerMapTests.cs index e7086360292..2a66ce45959 100644 --- a/tests/Infrastructure.Tests/TestTriggerMap/TestTriggerMapTests.cs +++ b/tests/Infrastructure.Tests/TestTriggerMap/TestTriggerMapTests.cs @@ -15,6 +15,19 @@ namespace Infrastructure.Tests.TestTriggerMap; [Collection("GraphAffectedProjects")] // MSBuildLocator registers process-wide; keep graph use serialized. public sealed class TestTriggerMapTests { + [Theory] + [InlineData("Aspire.Hosting.CodeGeneration.Go")] + [InlineData("Aspire.Hosting.Go")] + [InlineData("Aspire.Hosting.Redis")] + public void GoStarterRuntimePackagesSelectRealRunnerValidation(string project) + { + var result = SelectWithRealMap($"src/{project}/{project}.csproj", project); + + Assert.False(result.SelectsAll); + Assert.Empty(result.UnmatchedFiles); + Assert.Contains("job:cli-starter-validation", result.Jobs); + } + [Fact] public void IndependentNativeWorkflowSelectsInfrastructureWithoutExtraJobs() { @@ -813,15 +826,15 @@ public void DotnetProjectResourceChangesRunGeneratedAppHostConsumersWithoutProje public void CliStarterValidationDoesNotRunForUnrelatedHostingIntegrationChange() { var result = SelectWithRealMap( - "src/Aspire.Hosting.Redis/RedisBuilderExtensions.cs", - "Aspire.Hosting.Redis", - "Aspire.Hosting.Redis.Tests", + "src/Aspire.Hosting.RabbitMQ/RabbitMQBuilderExtensions.cs", + "Aspire.Hosting.RabbitMQ", + "Aspire.Hosting.RabbitMQ.Tests", "Aspire.Hosting.Tests"); Assert.False(result.SelectsAll); Assert.False( result.Jobs.Contains("job:cli-starter-validation", StringComparer.Ordinal), - "Aggregate tests selected by Redis changes must not pull in all six starter-validation jobs."); + "Aggregate tests selected by RabbitMQ changes must not pull in all six starter-validation jobs."); } [Fact] diff --git a/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/apphost.go b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/apphost.go new file mode 100644 index 00000000000..232bba6efbb --- /dev/null +++ b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/apphost.go @@ -0,0 +1,54 @@ +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + api := builder.AddProject("api", "./src/Api") + dotnetAPI := builder.AddDotnetProject("dotnet-api", "./src/Api/Api.csproj") + apiMigrations := builder.AddProject("api-migrations-project", "./src/Api.Migrations") + + dotnetAPI.AddEFMigrations("dotnet-api-migrations") + api.AddEFMigrations("api-migrations"). + WithMigrationsProject(&aspire.WithMigrationsProjectOptions{ + MigrationsProject: "./src/Api.Migrations", + }) + api.AddEFMigrations("api-dbcontext-migrations", &aspire.AddEFMigrationsOptions{ + DbContextTypeName: aspire.StringPtr("Api.Data.AppDbContext"), + }).WithMigrationsProject(&aspire.WithMigrationsProjectOptions{ + MigrationsProject: apiMigrations, + }). + WithMigrationNamespace("Api.Data.Migrations") + api.AddEFMigrations("api-script-migrations"). + PublishAsMigrationScript() + api.AddEFMigrations("api-script-options-migrations"). + PublishAsMigrationScript(&aspire.PublishAsMigrationScriptOptions{ + Idempotent: aspire.BoolPtr(false), + NoTransactions: aspire.BoolPtr(true), + }) + api.AddEFMigrations("api-bundle-migrations"). + PublishAsMigrationBundle() + api.AddEFMigrations("api-bundle-options-migrations"). + PublishAsMigrationBundle(&aspire.PublishAsMigrationBundleOptions{ + TargetRuntime: aspire.StringPtr("linux-x64"), + SelfContained: aspire.BoolPtr(true), + PublishContainer: aspire.BoolPtr(true), + BaseImage: aspire.StringPtr("mcr.microsoft.com/dotnet/runtime:10.0"), + }) + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} diff --git a/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/aspire.config.json b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/aspire.config.json new file mode 100644 index 00000000000..23ed59d9c16 --- /dev/null +++ b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/aspire.config.json @@ -0,0 +1,10 @@ +{ + "appHost": { + "path": "apphost.go", + "language": "go" + }, + "packages": { + "Aspire.Hosting.EntityFrameworkCore": "", + "Aspire.Hosting.Dotnet": "" + } +} diff --git a/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/go.mod b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/go.mod new file mode 100644 index 00000000000..b152cea7778 --- /dev/null +++ b/tests/PolyglotAppHosts/Aspire.Hosting.EntityFrameworkCore/Go/go.mod @@ -0,0 +1,7 @@ +module apphost + +go 1.26 + +require apphost/modules/aspire v0.0.0 + +replace apphost/modules/aspire => ./.aspire/modules diff --git a/tests/PolyglotAppHosts/Aspire.Hosting.Foundry/Go/apphost.go b/tests/PolyglotAppHosts/Aspire.Hosting.Foundry/Go/apphost.go index 26888d2c48e..8e765e8e06a 100644 --- a/tests/PolyglotAppHosts/Aspire.Hosting.Foundry/Go/apphost.go +++ b/tests/PolyglotAppHosts/Aspire.Hosting.Foundry/Go/apphost.go @@ -63,11 +63,11 @@ func main() { project.AddConnection(keyVault) project.AddSearchConnection(search) - _ = project.AddCodeInterpreterTool("code-interpreter") - _ = project.AddFileSearchTool("file-search", []string{"vs_placeholder"}) - _ = project.AddWebSearchTool("web-search") - _ = project.AddImageGenerationTool("image-gen") - _ = project.AddComputerUseTool("computer-use") + codeInterpreter := project.AddCodeInterpreterTool("code-interpreter") + fileSearch := project.AddFileSearchTool("file-search", []string{"vs_placeholder"}) + webSearch := project.AddWebSearchTool("web-search") + imageGen := project.AddImageGenerationTool("image-gen") + computerUse := project.AddComputerUseTool("computer-use") aiSearchTool := project.AddAISearchTool("ai-search-tool") aiSearchTool.WithReference(search) @@ -81,11 +81,22 @@ func main() { bingTool3 := project.AddBingGroundingTool("bing-tool-3") bingTool3.WithReference(bingParam) - _ = project.AddSharePointTool("sharepoint-tool", []string{"https://contoso.sharepoint.com", "MySite"}) - _ = project.AddFabricTool("fabric-tool", []string{"workspace-id"}) - _ = project.AddAzureFunctionTool("az-func-tool", "myFunction", "Does something", "{}", "https://queue.core.windows.net", "input-q", "https://queue.core.windows.net", "output-q") - _ = project.AddFunctionTool("func-tool", "myFunc", "{}") - _ = project.AddPromptAgent("prompt-agent", chat) + sharepoint := project.AddSharePointTool("sharepoint-tool", []string{"https://contoso.sharepoint.com", "MySite"}) + fabric := project.AddFabricTool("fabric-tool", []string{"workspace-id"}) + azFunc := project.AddAzureFunctionTool("az-func-tool", "myFunction", "Does something", "{}", "https://queue.core.windows.net", "input-q", "https://queue.core.windows.net", "output-q") + funcTool := project.AddFunctionTool("func-tool", "myFunc", "{}") + promptAgent := project.AddPromptAgent("prompt-agent", chat) + promptAgent.WithTool(codeInterpreter). + WithTool(fileSearch). + WithTool(webSearch). + WithTool(imageGen). + WithTool(computerUse). + WithTool(aiSearchTool). + WithTool(bingTool). + WithTool(sharepoint). + WithTool(fabric). + WithTool(azFunc). + WithTool(funcTool) builderProjectFoundry := builder.AddFoundry("builder-project-foundry") builderProject := builderProjectFoundry.AddProject("builder-project") diff --git a/tests/PolyglotAppHosts/Aspire.Hosting/Go/apphost.go b/tests/PolyglotAppHosts/Aspire.Hosting/Go/apphost.go index 6fd3c0c55c9..07c2d9b6dde 100644 --- a/tests/PolyglotAppHosts/Aspire.Hosting/Go/apphost.go +++ b/tests/PolyglotAppHosts/Aspire.Hosting/Go/apphost.go @@ -27,6 +27,14 @@ func main() { log.Fatal(aspire.FormatError(err)) } }) + aks.WithSystemNodePool(func(pool *aspire.AksNodePoolConfig) { + pool.OsSku = aspire.StringPtr("AzureLinux") + }) + aks.AddNodePool("workers", func(pool *aspire.AksNodePoolConfig) { + pool.VmSize = aspire.AksNodeVmSizes.StandardDSv5.StandardD2sV5 + pool.OsSku = aspire.StringPtr("AzureLinux") + }) + aks.AddPersistentVolume("aks-data").WithCapacity("20Gi") if aks.Err() != nil { log.Fatal(aspire.FormatError(aks.Err())) }