diff --git a/.github/actions/run-dotnet-tests/action.yml b/.github/actions/run-dotnet-tests/action.yml index 7081760c90..3d4d195a7b 100644 --- a/.github/actions/run-dotnet-tests/action.yml +++ b/.github/actions/run-dotnet-tests/action.yml @@ -53,15 +53,10 @@ inputs: runs: using: composite steps: - - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - dotnet-version: ${{ inputs.dotnet }} - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: - global-json-file: global.json + dotnet-version: ${{ inputs.dotnet }} - name: Set cloud version shell: pwsh diff --git a/.github/actions/setup-repository-dotnet/action.yml b/.github/actions/setup-repository-dotnet/action.yml new file mode 100644 index 0000000000..c8be326ff6 --- /dev/null +++ b/.github/actions/setup-repository-dotnet/action.yml @@ -0,0 +1,55 @@ +name: Setup repository .NET SDK +description: >- + Installs the exact .NET SDK pinned in global.json, plus any additional SDKs + the job needs, into a job-private directory and verifies that the build + resolves the pinned version. global.json rolls forward to newer SDK feature + bands for contributors; runner images preinstall newer SDKs into the default + directory, which that policy would otherwise select on CI. See + .github/scripts/select-repository-sdk.ps1. + +inputs: + dotnet-version: + description: >- + Newline-separated additional .NET SDK versions, for example the 8.0.x, + 9.0.x and 10.0.x SDKs whose runtimes older target frameworks execute on. + The global.json SDK is always installed and always selected. + required: false + default: '' + +outputs: + sdk: + description: The exact .NET SDK version the job builds with. + value: ${{ steps.select.outputs.sdk }} + +runs: + using: composite + steps: + - name: Select the repository .NET SDK + id: select + shell: pwsh + env: + ADDITIONAL_SDKS: ${{ inputs.dotnet-version }} + run: ./.github/scripts/select-repository-sdk.ps1 -AdditionalSdks $env:ADDITIONAL_SDKS + + - name: Install .NET SDKs + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ steps.select.outputs.versions }} + + - name: Verify the repository .NET SDK + shell: pwsh + env: + EXPECTED_SDK: ${{ steps.select.outputs.sdk }} + run: | + $dotnet = (Get-Command dotnet).Source + dotnet --list-sdks + $actual = (dotnet --version | Out-String).Trim() + if ($actual -cne $env:EXPECTED_SDK) { + Write-Host "::error::'$dotnet' selected .NET SDK '$actual' instead of the global.json SDK '$($env:EXPECTED_SDK)'." + exit 1 + } + if (-not $dotnet.StartsWith($env:DOTNET_INSTALL_DIR, [StringComparison]::OrdinalIgnoreCase)) { + Write-Host "::error::'$dotnet' is not the job-private installation in '$($env:DOTNET_INSTALL_DIR)'." + exit 1 + } + Write-Host "Using .NET SDK $actual from '$dotnet'." diff --git a/.github/scripts/install-aspire-bundle.ps1 b/.github/scripts/install-aspire-bundle.ps1 new file mode 100644 index 0000000000..c79d43fcad --- /dev/null +++ b/.github/scripts/install-aspire-bundle.ps1 @@ -0,0 +1,81 @@ +<# + .SYNOPSIS + Installs the Aspire CLI bundle before a solution build that contains an Aspire AppHost. + + .DESCRIPTION + tools/Opc.Ua.Lens.AppHost builds with AspireUseCliBundle. When Aspire home + holds no bundle, the AppHost build downloads it (about 350 MB) by running + 'aspire setup' itself under a two-minute timeout. On cold CI runners that + in-build setup intermittently fails, and the build then fails with + ASPIRE009. Installing the bundle up front, without that timeout and with + retries, lets the AppHost build resolve the existing layout instead. + + The bundle version is the Aspire.Hosting.AppHost version that + Directory.Packages.props pins. + + .PARAMETER PackagesPropsPath + Path to Directory.Packages.props. + + .PARAMETER AspireHome + Aspire home that receives the bundle. Defaults to ASPIRE_HOME or, when that + is not set, to the .aspire directory in the user profile, which is where the + AppHost build looks. + + .PARAMETER Attempts + Number of install attempts before the script fails. +#> +param( + [string] $PackagesPropsPath = 'Directory.Packages.props', + [string] $AspireHome = '', + [int] $Attempts = 3 +) + +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path -LiteralPath $PackagesPropsPath -PathType Leaf)) +{ + Write-Host "::error::'$PackagesPropsPath' does not exist; check out the repository first." + exit 1 +} + +[xml] $props = Get-Content -LiteralPath $PackagesPropsPath -Raw +$version = @($props.Project.ItemGroup.PackageVersion | + Where-Object { $_.Include -ceq 'Aspire.Hosting.AppHost' } | + ForEach-Object { $_.Version }) +if ($version.Count -ne 1 -or $version[0] -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') +{ + Write-Host "::error::'$PackagesPropsPath' must pin exactly one Aspire.Hosting.AppHost version." + exit 1 +} +$version = $version[0] + +if ([string]::IsNullOrWhiteSpace($AspireHome)) +{ + $AspireHome = if ([string]::IsNullOrWhiteSpace($env:ASPIRE_HOME)) + { + Join-Path ([Environment]::GetFolderPath('UserProfile')) '.aspire' + } + else + { + $env:ASPIRE_HOME + } +} + +$bundle = Join-Path $AspireHome 'bundle' +for ($attempt = 1; $attempt -le $Attempts; $attempt++) +{ + Write-Host "Installing the Aspire $version CLI bundle into '$AspireHome' (attempt $attempt of $Attempts)." + dotnet dnx --yes "aspire.cli@$version" -- setup --install-path $AspireHome + $exitCode = $LASTEXITCODE + if ($exitCode -eq 0 -and + (Test-Path -LiteralPath (Join-Path $bundle 'dcp') -PathType Container) -and + (Test-Path -LiteralPath (Join-Path $bundle 'dashboard') -PathType Container)) + { + Write-Host "Installed the Aspire $version CLI bundle into '$bundle'." + exit 0 + } + Write-Host "::warning::Aspire bundle setup attempt $attempt exited with $exitCode or left no complete bundle." +} + +Write-Host "::error::Could not install the Aspire $version CLI bundle into '$AspireHome' after $Attempts attempts." +exit 1 diff --git a/.github/scripts/select-repository-sdk.ps1 b/.github/scripts/select-repository-sdk.ps1 new file mode 100644 index 0000000000..c120fee2fb --- /dev/null +++ b/.github/scripts/select-repository-sdk.ps1 @@ -0,0 +1,98 @@ +<# + .SYNOPSIS + Selects the exact repository .NET SDK and a job-private install directory. + + .DESCRIPTION + global.json pins the minimum SDK version with rollForward 'latestFeature' so + that contributors can build with any newer feature band or patch of that + major version they have installed. The dotnet host applies that policy to + every SDK in its own installation directory, and GitHub-hosted runner images + preinstall newer SDKs into the default directory. A job that installs the + repository SDK there therefore builds with whatever newer SDK the image + happens to carry, and that SDK's new analyzers can break the build. + + This script points actions/setup-dotnet at a directory under RUNNER_TEMP + that contains only the SDKs the job installs, so the host can resolve + nothing newer than the global.json version. It writes: + + DOTNET_INSTALL_DIR (GITHUB_ENV) The job-private install directory. + sdk (GITHUB_OUTPUT) The exact global.json SDK version. + versions (GITHUB_OUTPUT) The SDKs to install, the global.json + version last. + + .PARAMETER AdditionalSdks + Newline-separated SDK versions the job needs besides the global.json SDK, + for example the 8.0.x and 9.0.x SDKs whose runtimes the older target + frameworks' tests execute on. + + .PARAMETER GlobalJsonPath + Path to the repository global.json. + + .PARAMETER InstallDirectory + Directory that receives the SDKs. Defaults to RUNNER_TEMP/dotnet, which is + empty at the start of every job. +#> +param( + [string] $AdditionalSdks = '', + [string] $GlobalJsonPath = 'global.json', + [string] $InstallDirectory = '' +) + +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path -LiteralPath $GlobalJsonPath -PathType Leaf)) +{ + Write-Host "::error::'$GlobalJsonPath' does not exist; check out the repository first." + exit 1 +} + +$sdk = (Get-Content -LiteralPath $GlobalJsonPath -Raw | ConvertFrom-Json).sdk.version +if ([string]::IsNullOrWhiteSpace($sdk) -or $sdk -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') +{ + Write-Host "::error::'$GlobalJsonPath' must pin an exact sdk.version; found '$sdk'." + exit 1 +} + +if ([string]::IsNullOrWhiteSpace($InstallDirectory)) +{ + if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) + { + Write-Host '::error::RUNNER_TEMP is not set; pass -InstallDirectory explicitly.' + exit 1 + } + $InstallDirectory = Join-Path $env:RUNNER_TEMP 'dotnet' +} + +$versions = [System.Collections.Generic.List[string]]::new() +foreach ($line in $AdditionalSdks -split '\r?\n') +{ + $version = $line.Trim() + if ($version.Length -eq 0 -or $version -ceq $sdk -or $versions.Contains($version)) + { + continue + } + if ($version -notmatch '^\d+(\.(\d+|x)){1,2}(-[0-9A-Za-z.-]+)?$') + { + Write-Host "::error::'$version' is not a .NET SDK version that actions/setup-dotnet accepts." + exit 1 + } + $versions.Add($version) +} +$versions.Add($sdk) + +if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_ENV)) +{ + "DOTNET_INSTALL_DIR=$InstallDirectory" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 +} +if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_OUTPUT)) +{ + $delimiter = "versions_$([guid]::NewGuid().ToString('N'))" + @( + "sdk=$sdk" + "versions<<$delimiter" + $versions + $delimiter + ) | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 +} + +Write-Host "Installing .NET SDK(s) $($versions -join ', ') into '$InstallDirectory'; the build uses $sdk." diff --git a/.github/workflows/buildandtest.yml b/.github/workflows/buildandtest.yml index 9dad71de79..5a43f0227f 100644 --- a/.github/workflows/buildandtest.yml +++ b/.github/workflows/buildandtest.yml @@ -324,9 +324,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download test results uses: actions/download-artifact@v8 @@ -498,9 +496,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh @@ -568,20 +564,25 @@ jobs: # a shallow clone. fetch-depth: 0 - - name: Setup .NET SDKs for build matrix - uses: actions/setup-dotnet@v6 - with: - dotnet-version: ${{ matrix.entry.dotnet }} - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: - global-json-file: global.json + dotnet-version: ${{ matrix.entry.dotnet }} - name: Set cloud version shell: pwsh run: ./.azurepipelines/set-version.ps1 + # Only UA.slnx contains the Aspire AppHost, which imports the Aspire SDK + # when CustomTestTarget is empty, net10.0 or net11.0. + - name: Install the Aspire CLI bundle + if: >- + ${{ matrix.entry.solution == 'UA.slnx' && + (matrix.entry.customTestTarget == 'net10.0' || matrix.entry.customTestTarget == 'net11.0' || + matrix.entry.customTestTarget == '') }} + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 + - name: Build ${{ matrix.entry.solution }} (${{ matrix.entry.customTestTarget }}) shell: pwsh env: @@ -610,10 +611,9 @@ jobs: # Full history: Nerdbank.GitVersioning refuses to compute a version from # a shallow clone, which fails the build before any test runs. fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Validate manifest and negative controls shell: pwsh run: ./fuzzing/Scripts/validate-fuzz-manifest.ps1 -SelfTest @@ -664,17 +664,13 @@ jobs: # Full history: Nerdbank.GitVersioning refuses to compute a version from # a shallow clone, which fails the build before any test runs. fetch-depth: 0 - - name: Setup .NET 8, 9 and 10 runtimes - uses: actions/setup-dotnet@v6 + - name: Setup repository .NET SDK with .NET 8, 9 and 10 runtimes + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: | 8.0.x 9.0.x 10.0.x - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json - name: Run fuzz regressions shell: pwsh run: ./fuzzing/Scripts/test-fuzzing.ps1 -Framework '${{ matrix.framework }}' -ResultsDirectory '${{ runner.temp }}/fuzz-results' diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 1f85d928c0..191b615f51 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -52,9 +52,11 @@ jobs: # queries: ./path/to/local/query, your-org/your-repo/queries@main - name: Set up .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet + # UA.slnx contains the Aspire AppHost, which needs the Aspire CLI bundle. + - name: Install the Aspire CLI bundle + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 # https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#c-compiler-flags-injected-by-codeql-for-manual-builds # # CustomTestTarget pins the build to a single target framework (see diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 503b2c78f6..ecd921e777 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -147,9 +147,7 @@ jobs: fetch-depth: 0 - name: Set up .NET 10 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Version shell: pwsh @@ -217,9 +215,7 @@ jobs: fetch-depth: 0 - name: Set up .NET 10 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Version shell: pwsh diff --git a/.github/workflows/interop-foreign.yml b/.github/workflows/interop-foreign.yml index 29069413fb..234728584b 100644 --- a/.github/workflows/interop-foreign.yml +++ b/.github/workflows/interop-foreign.yml @@ -58,10 +58,9 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json # ---------------------------------------------------------------- node-opcua - name: Setup Node.js diff --git a/.github/workflows/mcpgrade.yml b/.github/workflows/mcpgrade.yml index 63c86fa7ee..fa79b70bbd 100644 --- a/.github/workflows/mcpgrade.yml +++ b/.github/workflows/mcpgrade.yml @@ -36,9 +36,9 @@ jobs: fetch-depth: 0 - name: Setup .NET 10 - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: - global-json-file: global.json + dotnet-version: 10.0.x - name: Setup Node.js uses: actions/setup-node@v7 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 47f1a4a93b..f812211810 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -115,8 +115,8 @@ jobs: with: fetch-depth: 0 - - name: Setup .NET - uses: actions/setup-dotnet@v6 + - name: Setup repository .NET SDK + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: ${{ matrix.entry.dotnet }} @@ -124,6 +124,16 @@ jobs: shell: pwsh run: ./.azurepipelines/set-version.ps1 + # Only UA.slnx contains the Aspire AppHost, which imports the Aspire SDK + # when CustomTestTarget is empty, net10.0 or net11.0. + - name: Install the Aspire CLI bundle + if: >- + ${{ matrix.entry.solution == 'UA.slnx' && + (matrix.entry.customTestTarget == 'net10.0' || matrix.entry.customTestTarget == 'net11.0' || + matrix.entry.customTestTarget == '') }} + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 + - name: Build ${{ matrix.entry.solution }} (${{ matrix.entry.customTestTarget }}) shell: pwsh env: @@ -186,9 +196,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set cloud version shell: pwsh @@ -282,9 +290,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download test results uses: actions/download-artifact@v8 diff --git a/.github/workflows/nuget-publish.yml b/.github/workflows/nuget-publish.yml index 775e2f0eb4..3841111aa3 100644 --- a/.github/workflows/nuget-publish.yml +++ b/.github/workflows/nuget-publish.yml @@ -126,9 +126,7 @@ jobs: fetch-depth: 0 - name: Setup .NET 10.0 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Decode strong-name key shell: pwsh @@ -477,9 +475,7 @@ jobs: uses: actions/checkout@v6 - name: Setup .NET 10.0 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download signed package sets uses: actions/download-artifact@v8 diff --git a/.github/workflows/sample-ha-longhaul.yml b/.github/workflows/sample-ha-longhaul.yml index c9020cd73b..e4f76296e9 100644 --- a/.github/workflows/sample-ha-longhaul.yml +++ b/.github/workflows/sample-ha-longhaul.yml @@ -66,10 +66,9 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/stability-test.yml b/.github/workflows/stability-test.yml index 2817216924..bb7aa7d0a1 100644 --- a/.github/workflows/stability-test.yml +++ b/.github/workflows/stability-test.yml @@ -55,10 +55,9 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/stress-test.yml b/.github/workflows/stress-test.yml index e1112e99e9..a55c5370cc 100644 --- a/.github/workflows/stress-test.yml +++ b/.github/workflows/stress-test.yml @@ -57,10 +57,9 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Set Cloud Version shell: pwsh @@ -126,10 +125,9 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/ualens-artifacts.yml b/.github/workflows/ualens-artifacts.yml index 056c1529ef..0f7797fb3f 100644 --- a/.github/workflows/ualens-artifacts.yml +++ b/.github/workflows/ualens-artifacts.yml @@ -61,10 +61,9 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Run artifact validation unit tests with NUnit if: matrix.tfm == 'net10.0' shell: pwsh @@ -92,10 +91,9 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Build the desktop regression harness shell: pwsh run: | @@ -145,10 +143,9 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Linux native compiler and desktop prerequisites if: runner.os == 'Linux' run: | @@ -193,10 +190,9 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - name: Restore and pack managed tool (never reuse native output) shell: pwsh run: | @@ -235,10 +231,9 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 + - uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: 10.0.x - global-json-file: global.json - uses: actions/download-artifact@v8 with: name: ualens-managed-packages diff --git a/docs/DeveloperGuide.md b/docs/DeveloperGuide.md index 620adf9156..1ff4149a3a 100644 --- a/docs/DeveloperGuide.md +++ b/docs/DeveloperGuide.md @@ -34,7 +34,7 @@ If you are new here, read the sections in order: [Prerequisites](#prerequisites) ## Prerequisites -- **.NET SDK 11.0.100 or later (11.0 feature bands)** — `global.json` sets this minimum and selects the highest installed stable 11.0 SDK through `rollForward: latestFeature`; prerelease SDKs are excluded. (`actions/setup-dotnet` reads `latestMajor` as "the current LTS", which would install a .NET 10 SDK in CI.) CI selects its SDK version explicitly. The class libraries still *target* older frameworks (see [Packages, platform support, and versioning](#packages-platform-support-and-versioning)); those target frameworks do not determine the SDK used to build the repository. +- **.NET SDK 11.0.100 or later (11.0 feature bands)** — `global.json` sets this minimum and selects the highest installed stable 11.0 SDK through `rollForward: latestFeature`; prerelease SDKs are excluded. (`actions/setup-dotnet` reads `latestMajor` as "the current LTS", which would install a .NET 10 SDK in CI.) CI installs the exact `global.json` SDK into a job-private directory through `.github/actions/setup-repository-dotnet`, so newer SDKs preinstalled on the runner image are not selected. The class libraries still *target* older frameworks (see [Packages, platform support, and versioning](#packages-platform-support-and-versioning)); those target frameworks do not determine the SDK used to build the repository. - **An IDE (optional but recommended)** — Visual Studio 2026, Visual Studio Code with the C# Dev Kit, or JetBrains Rider. Everything can also be done from the command line with `dotnet`. - **git** — to clone and to create feature branches. - **Docker Desktop (optional)** — only needed to run the containerized reference server; see [ContainerReferenceServer.md](ContainerReferenceServer.md). diff --git a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs index 779e0356c8..ddb17e0dc1 100644 --- a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs +++ b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs @@ -789,12 +789,11 @@ private NodeId GetTrustListId(NodeId certificateGroupId) return null; } - private ICertificateGroup? GetGroupForCertificate(ByteString certificate) + private ICertificateGroup? GetGroupForCertificate(ByteString certificate, NodeId certificateType) { if (certificate.Length > 0) { using var x509 = Certificate.FromRawData(certificate); - NodeId certificateType = CertificateIdentifier.GetCertificateType(x509); foreach (ICertificateGroup certificateGroup in m_certificateGroups.Values) { KeyValuePair matchingCert = certificateGroup @@ -818,12 +817,13 @@ private NodeId GetTrustListId(NodeId certificateGroupId) private async Task RevokeCertificateAsync( ByteString certificate, + NodeId certificateType, CancellationToken cancellationToken = default) { bool revoked = false; if (certificate.Length > 0) { - ICertificateGroup? certificateGroup = GetGroupForCertificate(certificate); + ICertificateGroup? certificateGroup = GetGroupForCertificate(certificate, certificateType); if (certificateGroup != null) { @@ -836,6 +836,22 @@ private async Task RevokeCertificateAsync( if (crl != null) { revoked = true; + + // The new CRL is in the server's issuer store. Notify the + // certificate manager so that it revalidates the open + // SecureChannels and closes those that use the revoked + // certificate. + try + { + m_configuration.CertificateManager?.NotifyTrustListChanged( + TrustListIdentifier.Peers, + trustChanged: false, + crlChanged: true); + } + catch (Exception ex) + { + m_logger.RevocationNotificationFailed(ex, certificateGroup.Id); + } } } catch (Exception e) @@ -1325,7 +1341,7 @@ private async ValueTask out ByteString certificate) && !certificate.IsEmpty) { - await RevokeCertificateAsync(certificate, cancellationToken) + await RevokeCertificateAsync(certificate, certType.Key, cancellationToken) .ConfigureAwait(false); } } @@ -1407,6 +1423,7 @@ private async ValueTask OnRevokeCertificateA revoked = await RevokeCertificateAsync( certificate, + certType.Key, cancellationToken).ConfigureAwait(false); if (revoked) { @@ -3699,5 +3716,12 @@ public static partial void FinishRequestIssueFailed( Exception exception, NodeId requestId, [ApplicationIdentity] string? applicationUri); + + [LoggerMessage(EventId = GdsServerCommonEventIds.ApplicationsNodeManager + 22, Level = LogLevel.Error, + Message = "Failed to notify the server of the revocation in certificate group {CertificateGroupId}.")] + public static partial void RevocationNotificationFailed( + this ILogger logger, + Exception exception, + NodeId certificateGroupId); } } diff --git a/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs b/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs index 3b0dec01dd..ee4e9ebcfa 100644 --- a/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs +++ b/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs @@ -145,27 +145,10 @@ private async ValueTask RefreshPreparedUnitsAsync( WotRefreshResult result; try { - for (int attempt = 0; ; attempt++) - { - bool decisionStarted = false; - try - { - result = await RefreshPreparedUnitAsync( - unitCapture, snapshot, start, unit, includeSkipped, - publication, registryPublication, preview, cancellationToken, mutation, - () => decisionStarted = true) - .ConfigureAwait(false); - break; - } - catch (InvalidOperationException failure) when ( - !decisionStarted && attempt < 2 && - failure.Message is - "Serving references changed during batch preparation." or - "Serving references changed during preparation.") - { - await Task.Yield(); - } - } + result = await RefreshPreparedUnitWithRetryAsync( + unitCapture, snapshot, start, unit, includeSkipped, + publication, registryPublication, preview, mutation, cancellationToken) + .ConfigureAwait(false); } catch (WotRegistryCommitNotCommittedException failure) when ( rows.Any(row => row.Outcome is WoTOutcomeEnum.Success or WoTOutcomeEnum.Warning)) @@ -198,9 +181,9 @@ failure.Message is } if (plan.Units.IsEmpty) { - WotRefreshResult empty = await RefreshPreparedUnitAsync( - refresh, snapshot, start, [], true, publication, registryPublication, preview, cancellationToken, - mutation) + WotRefreshResult empty = await RefreshPreparedUnitWithRetryAsync( + refresh, snapshot, start, [], true, publication, registryPublication, preview, mutation, + cancellationToken) .ConfigureAwait(false); rows.AddRange(empty.Results); retired = empty.Summary.Retired; @@ -281,6 +264,52 @@ .. rows.GroupBy(row => (row.GroupId, row.ResourceId)).Select(group => return completed; } + /// + /// Publishes one prepared unit and rebuilds it when a concurrent serving-reference write + /// invalidates the prepared candidate before the durable decision starts. + /// + /// + /// Other server components, such as the registry projection, can write references of a node + /// that the publication prepared. The server then rejects the reservation before the decision, + /// so nothing was published and the unit is rebuilt from the live serving state. Unload and + /// retire-only publications without activation units use the same budget as activations. + /// + private async ValueTask RefreshPreparedUnitWithRetryAsync( + WotRefreshCapture refresh, + WotRegistrySnapshot snapshot, + DateTime start, + ArrayOf unit, + bool includeSkipped, + IWotProjectionPublication? publication, + IWotRegistryPublication? registryPublication, + PublicationCapture? preview, + WotRegistryMutationImage? mutation, + CancellationToken cancellationToken) + { + for (int attempt = 1; ; attempt++) + { + bool decisionStarted = false; + try + { + return await RefreshPreparedUnitAsync( + refresh, snapshot, start, unit, includeSkipped, + publication, registryPublication, preview, cancellationToken, mutation, + () => decisionStarted = true) + .ConfigureAwait(false); + } + catch (InvalidOperationException failure) when ( + !decisionStarted && attempt < kMaxPreparedPublicationAttempts && + failure.Message is + "Serving references changed during batch preparation." or + "Serving references changed during preparation.") + { + // Let the concurrent writer finish before the unit is prepared again. + await Task.Delay(TimeSpan.FromMilliseconds(10 * attempt), cancellationToken) + .ConfigureAwait(false); + } + } + } + private async ValueTask RefreshPreparedUnitAsync( WotRefreshCapture refresh, WotRegistrySnapshot snapshot, @@ -1526,6 +1555,7 @@ public ValueTask DeactivateAsync(WotBindingPlan plan, CancellationToken cancella } } + private const int kMaxPreparedPublicationAttempts = 3; private readonly IWotProjectionHost m_sourceHost; private readonly IWotViewProjectionHost m_sourceViewHost; private readonly IWotBinderRegistry m_sourceBinders; diff --git a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs index 524ee6df77..c7973e3874 100644 --- a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs +++ b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs @@ -104,8 +104,7 @@ public async Task ReverseConnectServiceLevelDropFailsOverOverMemberConnectionAsy await using UaManagedSession session = await set.ConnectAsync(options, null, timeout.Token) .ConfigureAwait(false); Assert.That(ServerUriOf(session), Is.EqualTo(set.Primary.ApplicationUri)); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); set.Primary.SetServiceLevel(150); await WaitUntilAsync( @@ -203,8 +202,7 @@ public async Task ReverseConnectMemberWithoutConnectionIsNeverSelectedAsync() }; await using UaManagedSession session = await set.ConnectAsync(options, null, timeout.Token) .ConfigureAwait(false); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); ServerRedundancyInfo info = await WaitForMemberAsync( session, set.Backup, server => server.ResolutionError != null, timeout.Token).ConfigureAwait(false); diff --git a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs index 68c2230113..b8ce9922e8 100644 --- a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs +++ b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs @@ -391,8 +391,7 @@ public async Task FailoverAsyncSwitchesToExplicitTargetAsync(bool useChannelMana await using UaManagedSession session = await set.ConnectAsync( new ServerRedundancyOptions(), timeout.Token, channelManager: channels).ConfigureAwait(false); Assert.That(set.Primary.SessionCount, Is.EqualTo(1)); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); await session.FailoverAsync(set.Backup.Endpoint, timeout.Token).ConfigureAwait(false); await WaitUntilAsync(() => states.Contains(ConnectionState.Connected), timeout.Token).ConfigureAwait(false); @@ -456,6 +455,24 @@ await Assert.ThatAsync( return session.ConfiguredEndpoint.Description.Server?.ApplicationUri; } + /// + /// Records the connection states the session enters from now on. The connect + /// call can return before the notification of the initial Connecting to Connected + /// transition is delivered, so that late notification is not recorded. + /// + private static ConcurrentQueue RecordStatesAfterConnect(UaManagedSession session) + { + var states = new ConcurrentQueue(); + session.ConnectionStateChanged += (_, e) => + { + if (e.PreviousState != ConnectionState.Connecting) + { + states.Enqueue(e.NewState); + } + }; + return states; + } + private static async Task WaitUntilAsync(Func condition, CancellationToken ct) { while (!condition()) diff --git a/tests/Opc.Ua.Gds.Tests/ClientTest.cs b/tests/Opc.Ua.Gds.Tests/ClientTest.cs index b9ca2c2867..cd99f83115 100644 --- a/tests/Opc.Ua.Gds.Tests/ClientTest.cs +++ b/tests/Opc.Ua.Gds.Tests/ClientTest.cs @@ -35,6 +35,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Moq; using NUnit.Framework; using Opc.Ua.Gds.Server; using Opc.Ua.Security.Certificates; @@ -1745,12 +1746,26 @@ public async Task RevokeGoodCertificatesAsync() AssertIgnoreTestWithoutInvalidRegistration(); AssertIgnoreTestWithoutGoodNewKeyPairRequest(); await ConnectGDSAsync(true).ConfigureAwait(false); + + // A revocation must reach the server's certificate manager so + // that already open channels and sessions using the revoked + // certificate are revalidated, not only new connections. + var crlUpdates = new Mock>(); + using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges + .Subscribe(crlUpdates.Object); + int revocations = 0; foreach (ApplicationTestData application in m_goodApplicationTestSet) { await m_gdsClient.GDSClient.RevokeCertificateAsync( application.ApplicationRecord.ApplicationId, application.Certificate.ToByteString()).ConfigureAwait(false); + revocations++; } + crlUpdates.Verify( + observer => observer.OnNext(It.Is(change => + change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Peers)), + Times.AtLeast(revocations)); foreach (ApplicationTestData application in m_invalidApplicationTestSet) { await Assert.ThatAsync( diff --git a/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs b/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs new file mode 100644 index 0000000000..d14112dd13 --- /dev/null +++ b/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs @@ -0,0 +1,148 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Threading.Tasks; +using NUnit.Framework; +using Opc.Ua.Gds.Client; +using Opc.Ua.Tests; + +namespace Opc.Ua.Gds.Tests +{ + /// + /// End-to-end test verifying that revoking an application certificate through the + /// GDS cuts off a session that is already open with that certificate. + /// + [TestFixture] + [Category("GDS")] + [NonParallelizable] + public class RevokeCertificateSessionTest + { + private static readonly TimeSpan s_enforcementTimeout = TimeSpan.FromSeconds(30); + + private GlobalDiscoveryTestServer m_server = null!; + private GlobalDiscoveryTestClient m_gdsClient = null!; + + [OneTimeSetUp] + public async Task OneTimeSetUpAsync() + { + m_server = await TestUtils.StartGDSAsync(clean: true).ConfigureAwait(false); + m_gdsClient = new GlobalDiscoveryTestClient(true, NUnitTelemetryContext.Create()); + await m_gdsClient.LoadClientConfigurationAsync(m_server.BasePort).ConfigureAwait(false); + } + + [OneTimeTearDown] + public async Task OneTimeTearDownAsync() + { + if (m_gdsClient != null) + { + await m_gdsClient.DisconnectClientAsync().ConfigureAwait(false); + m_gdsClient.Dispose(); + m_gdsClient = null!; + } + if (m_server != null) + { + await m_server.DisposeAsync().ConfigureAwait(false); + m_server = null!; + } + } + + [Test] + public async Task RevokeCertificateCutsOffOpenSessionOfRevokedCertificateAsync() + { + ApplicationConfiguration configuration = m_gdsClient.Configuration; + CertificateIdentifier adminCertificate = + configuration.SecurityConfiguration.ApplicationCertificate!; + + // Issue a GDS certificate to the test client. This replaces the + // application certificate the next session is created with. + Assert.That(await m_gdsClient.RegisterTestClientAtGdsAsync().ConfigureAwait(false), Is.True); + ApplicationTestData application = m_gdsClient.OwnApplicationTestData; + + var victim = new GlobalDiscoveryServerClient(configuration, m_gdsClient.Anonymous) + { + Endpoint = new ConfiguredEndpoint( + null, + m_gdsClient.GDSClient.Endpoint!.Description, + EndpointConfiguration.Create(configuration)) + }; + try + { + // The certificate grants the session ApplicationSelfAdmin rights. + NodeId applicationId = application.ApplicationRecord.ApplicationId; + await victim.ConnectAsync().ConfigureAwait(false); + ApplicationRecordDataType record = + await victim.GetApplicationAsync(applicationId).ConfigureAwait(false); + Assert.That(record.ApplicationId, Is.EqualTo(applicationId)); + + // Revoke from an admin session which uses the original certificate, + // so that only the victim session holds the revoked certificate. + configuration.SecurityConfiguration.ApplicationCertificate = adminCertificate; + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + try + { + await m_gdsClient.GDSClient.RevokeCertificateAsync( + applicationId, + application.Certificate.ToByteString()).ConfigureAwait(false); + } + finally + { + await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); + } + + // The server revalidates the open SecureChannels asynchronously + // after the CRL update and closes the one using the revoked + // certificate, so the session can no longer be used. + ServiceResultException? failure = null; + DateTime deadline = DateTime.UtcNow + s_enforcementTimeout; + while (failure == null && DateTime.UtcNow < deadline) + { + try + { + await victim.GetApplicationAsync(applicationId).ConfigureAwait(false); + await Task.Delay(100).ConfigureAwait(false); + } + catch (ServiceResultException ex) + { + failure = ex; + } + } + Assert.That( + failure, + Is.Not.Null, + "The session using the revoked certificate can still be used."); + } + finally + { + await victim.DisposeAsync().ConfigureAwait(false); + } + } + } +} diff --git a/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs b/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs index 524c50d738..77e17a8d85 100644 --- a/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs +++ b/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs @@ -44,7 +44,8 @@ namespace Opc.Ua.Tools.Tests public sealed class TestMatrixScriptTests { /// - /// Artifact qualification installs the exact repository SDK instead of a floating patch. + /// Artifact qualification installs the exact repository SDK through the shared action, + /// plus only the .NET 10 runtime that the net10.0 artifact jobs execute on. /// [Test] public async Task ArtifactJobsInstallTheRepositorySdkAsync() @@ -53,22 +54,104 @@ public async Task ArtifactJobsInstallTheRepositorySdkAsync() string source = await File.ReadAllTextAsync(path).ConfigureAwait(false); string[] steps = [.. source.ReplaceLineEndings("\n") .Split("\n - ", StringSplitOptions.None) - .Where(step => step.StartsWith("uses: actions/setup-dotnet@", StringComparison.Ordinal))]; + .Where(step => step.StartsWith(RepositorySdkAction, StringComparison.Ordinal))]; Assert.That(steps, Is.Not.Empty); foreach (string step in steps) { string[] lines = step.Split('\n'); - Assert.That(lines, Does.Contain(" global-json-file: global.json")); - // The SDK comes from global.json. The only extra install allowed is the - // net10.0 runtime the net10.0 artifact jobs need, which the newer SDK - // does not carry; it never selects the SDK because global.json pins it. + // The shared action always builds with the global.json SDK. The only extra + // install allowed is the 10.0 SDK whose runtime the net10.0 artifact jobs need; + // it never selects the SDK because global.json pins it. Assert.That( lines.Where(line => line.Contains("dotnet-version:", StringComparison.Ordinal)), Is.All.EqualTo(" dotnet-version: 10.0.x")); } } + /// + /// Runner images preinstall newer SDKs that the global.json roll-forward policy would + /// select, so every workflow installs .NET through the action that isolates the SDK. + /// + [Test] + public async Task WorkflowsInstallDotnetOnlyThroughTheRepositorySdkActionAsync() + { + string github = Path.Combine(FindRepositoryRoot(), ".github"); + string sharedAction = Path.Combine(github, "actions", "setup-repository-dotnet", "action.yml"); + // The release job checks out the candidate commit, which can predate the shared + // action, and only pushes packages that were already built. + string release = Path.Combine(github, "workflows", "release.yml"); + string[] files = [.. Directory.GetFiles(Path.Combine(github, "workflows"), "*.yml") + .Concat(Directory.GetFiles(Path.Combine(github, "actions"), "action.yml", SearchOption.AllDirectories)) + .Where(file => file != sharedAction && file != release)]; + + int uses = 0; + foreach (string file in files) + { + string source = await File.ReadAllTextAsync(file).ConfigureAwait(false); + Assert.That(source, Does.Not.Contain("actions/setup-dotnet@"), file); + uses += source.Split(RepositorySdkAction, StringSplitOptions.None).Length - 1; + } + Assert.That(uses, Is.GreaterThan(0)); + } + + /// + /// The SDK selection installs extra SDKs first, the global.json SDK last, into the + /// job-private directory. + /// + [Test] + public async Task RepositorySdkSelectionPinsTheGlobalJsonSdkLastAsync() + { + string directory = CreateSdkSelectionDirectory(); + try + { + string install = Path.Combine(directory, "dotnet"); + ScriptResult result = await RunSdkSelectionAsync( + directory, "8.0.x\n10.0.403\n 9.0.x \n8.0.x\n", install).ConfigureAwait(false); + + Assert.That(result.ExitCode, Is.Zero, result.Output); + string[] environment = await File.ReadAllLinesAsync( + Path.Combine(directory, "env")).ConfigureAwait(false); + Assert.That(environment, Is.EqualTo(new[] { "DOTNET_INSTALL_DIR=" + install })); + string[] output = await File.ReadAllLinesAsync( + Path.Combine(directory, "output")).ConfigureAwait(false); + Assert.That(output, Has.Length.EqualTo(6)); + Assert.That(output[0], Is.EqualTo("sdk=10.0.403")); + Assert.That(output[1], Does.StartWith("versions<<")); + Assert.That(string.Join(',', output[2..5]), Is.EqualTo("8.0.x,9.0.x,10.0.403")); + Assert.That(output[5], Is.EqualTo(output[1]["versions<<".Length..])); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + /// + /// The SDK selection rejects a malformed extra version before anything is installed. + /// + [TestCase("latest")] + [TestCase("10")] + [TestCase("8.0.x; rm -rf /")] + public async Task RepositorySdkSelectionRejectsInvalidVersionsAsync(string version) + { + string directory = CreateSdkSelectionDirectory(); + try + { + ScriptResult result = await RunSdkSelectionAsync( + directory, version, Path.Combine(directory, "dotnet")).ConfigureAwait(false); + + Assert.That(result.ExitCode, Is.EqualTo(1), result.Output); + Assert.That(result.Output, Does.Contain("::error::")); + Assert.That(File.Exists(Path.Combine(directory, "env")), Is.False); + Assert.That(File.Exists(Path.Combine(directory, "output")), Is.False); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + /// /// Every artifact job that builds a project has the history needed by Git versioning. /// @@ -265,6 +348,35 @@ public async Task GitHubBatchScopesNativePathsToTheLinuxTestProcessAsync( Assert.That(document.RootElement.GetProperty("parent").GetString(), Is.EqualTo(inherited)); } + private static string CreateSdkSelectionDirectory() + { + string directory = Path.Combine(Path.GetTempPath(), "sdk-selection-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + File.WriteAllText( + Path.Combine(directory, "global.json"), + """{"sdk":{"version":"10.0.403","rollForward":"latestMajor"}}"""); + return directory; + } + + private static Task RunSdkSelectionAsync( + string directory, + string additionalSdks, + string installDirectory) + { + string root = FindRepositoryRoot(); + string script = Path.Combine(root, ".github", "scripts", "select-repository-sdk.ps1"); + string command = $$""" + $env:GITHUB_ENV = {{QuotePowerShell(Path.Combine(directory, "env"))}} + $env:GITHUB_OUTPUT = {{QuotePowerShell(Path.Combine(directory, "output"))}} + & {{QuotePowerShell(script)}} ` + -AdditionalSdks {{QuotePowerShell(additionalSdks)}} ` + -GlobalJsonPath {{QuotePowerShell(Path.Combine(directory, "global.json"))}} ` + -InstallDirectory {{QuotePowerShell(installDirectory)}} + exit $LASTEXITCODE + """; + return RunPowerShellAsync(root, command); + } + private static Task RunGitHubFunctionAsync( string discovery, string invocation, @@ -350,6 +462,8 @@ private static string QuotePowerShell(string value) private const string LensProjectFile = "tests/Opc.Ua.Lens.Workflow.Tests/Opc.Ua.Lens.Workflow.Tests.csproj"; + private const string RepositorySdkAction = "uses: ./.github/actions/setup-repository-dotnet"; + private sealed record ScriptResult(int ExitCode, string Output); } } diff --git a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs index 1e1d528e13..fe5f2c2daf 100644 --- a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs +++ b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs @@ -233,6 +233,64 @@ await Assert.ThatAsync(async () => await coordinator.RefreshAsync(HandoffRequest Assert.That(host.DisposedPublications, Is.EqualTo(attempts)); } + /// + /// Verifies that an unload without activation units rebuilds its publication after a + /// predecision reference conflict and stops at the publication budget. + /// + /// The number of predecision conflicts injected before success. + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + public async Task UnloadPublicationRetriesPredecisionReferenceConflictsWithinThePublicationBudget( + int conflicts) + { + m_coordinator.Dispose(); + var host = new PausableWotProjectionHost(new LifecycleWotProjectionHost(m_server.NodeManagerLifecycle)); + m_coordinator = new WotMaterializationCoordinator(m_registry, host, documentConverter: m_converter) + { + ServerNamespaceUris = m_server.CurrentInstance.NamespaceUris, + DeletePolicy = WoTDeletePolicyEnum.Force + }; + WotResource resource = await AddAsync("unload-conflict").ConfigureAwait(false); + WotRefreshResult loaded = await m_coordinator.RefreshAsync(HandoffRequest("unload-conflict-load")) + .ConfigureAwait(false); + Assert.That(loaded.NewGeneration, Is.EqualTo(1u)); + WotRegistrySnapshot before = m_registry.Current; + int disposedBefore = host.DisposedPublications; + int attempts = 0; + host.BeforeCommit = () => + { + if (++attempts <= conflicts) + { + throw new InvalidOperationException("Serving references changed during preparation."); + } + }; + + if (conflicts < 3) + { + WotRegistryMutationResult result = await m_coordinator.SetEnabledAsync( + resource.GroupId, resource.ResourceId, false).ConfigureAwait(false); + + Assert.That(result.Outcome, Is.EqualTo(WoTOutcomeEnum.Success), result.Message); + Assert.That(m_registry.Current.FindResourceByXid(resource.Xid)!.Enabled, Is.False); + Assert.That((await ReadNodeClassAsync(Root(resource)).ConfigureAwait(false)).StatusCode, + Is.EqualTo(StatusCodes.BadNodeIdUnknown)); + } + else + { + await Assert.ThatAsync(async () => await m_coordinator.SetEnabledAsync( + resource.GroupId, resource.ResourceId, false).ConfigureAwait(false), + Throws.TypeOf() + .With.Message.EqualTo("Serving references changed during preparation.")).ConfigureAwait(false); + + Assert.That(m_registry.Current, Is.SameAs(before)); + Assert.That((await ReadNodeClassAsync(Root(resource)).ConfigureAwait(false)).StatusCode, + Is.EqualTo(StatusCodes.Good)); + } + Assert.That(attempts, Is.EqualTo(Math.Min(conflicts + 1, 3))); + Assert.That(host.DisposedPublications - disposedBefore, Is.EqualTo(attempts)); + } + /// /// Verifies that an unrelated publication error is propagated immediately without retry. ///