From 68143dff25da3a0e7700f268ef98e7b82b38d8f6 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 30 Nov 2026 21:20:42 +0200 Subject: [PATCH 1/2] Adds per-platform release artifacts and release image validation --- .github/workflows/publish-release.yml | 23 +- build/RuntimeIdentifiers.props | 51 +++ build/build.proj | 372 ++++++++++++++++-- docs/manual/installation/index.md | 21 +- docs/technical/RELEASING.md | 38 +- plugins/Directory.Build.props | 3 +- .../Nemera.Plugins.Pdf.csproj | 5 +- src/Nemera.Presentation.Api/Dockerfile | 5 +- .../Dockerfile.release | 6 +- .../Nemera.Presentation.Api.csproj | 2 + src/Nemera.Presentation.Api/Program.cs | 9 + src/Nemera.Presentation.Web/Dockerfile | 5 +- .../Dockerfile.release | 6 +- .../Nemera.Presentation.Web.csproj | 2 + src/Nemera.Presentation.Web/Program.cs | 15 +- src/Nemera.slnx | 1 + .../Setup/PublishedAssemblyResourceReader.cs | 54 +++ .../PublishedAssemblyResourceReaderTests.cs | 43 ++ .../BundledPluginManifestReaderTests.cs | 57 ++- 19 files changed, 603 insertions(+), 115 deletions(-) create mode 100644 build/RuntimeIdentifiers.props create mode 100644 tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReader.cs create mode 100644 tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReaderTests.cs diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 08a39e04..1caca81f 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -45,7 +45,16 @@ jobs: env: SixLaborsLicenseKey: ${{ secrets.SIXLABORS_LICENSE_KEY }} RELEASE_BRANCH: ${{ github.ref_name }} - run: dotnet msbuild build/build.proj -t:RecordBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true -p:AllowBundledPluginsRecording=true -p:ReleaseBranch="$RELEASE_BRANCH" + run: | + release_version="${RELEASE_BRANCH#release/}" + dotnet msbuild build/build.proj -t:RecordBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true -p:AllowBundledPluginsRecording=true -p:ReleaseBranch="$RELEASE_BRANCH" -p:Version="$release_version" + # Upload the verified archives before the image step, so a Docker failure does not discard successfully built archives. + - name: Upload release archives + uses: actions/upload-artifact@v4 + with: + name: release-archives + path: bin/release/* + if-no-files-found: error # Reuse the verified publish output, so the images contain exactly the plugin binaries whose hashes were recorded. - name: Build release images env: @@ -53,18 +62,6 @@ jobs: run: | release_version="${RELEASE_BRANCH#release/}" dotnet msbuild build/build.proj -t:Docker -p:Configuration=Release -p:OfficialReleaseBuild=true -p:ReusePublishedBundledPlugins=true -p:Version="$release_version" - - name: Upload release server files - uses: actions/upload-artifact@v4 - with: - name: release-api - path: bin/api/publish - if-no-files-found: error - - name: Upload release web files - uses: actions/upload-artifact@v4 - with: - name: release-web - path: bin/web/publish - if-no-files-found: error - name: Upload bundled plugin manifest uses: actions/upload-artifact@v4 with: diff --git a/build/RuntimeIdentifiers.props b/build/RuntimeIdentifiers.props new file mode 100644 index 00000000..389f764a --- /dev/null +++ b/build/RuntimeIdentifiers.props @@ -0,0 +1,51 @@ + + + + + windows-x64 + .zip + + + windows-x86 + .zip + + + windows-arm64 + .zip + + + linux-x64 + .tar.gz + + + linux-arm64 + .tar.gz + + + linux-musl-x64 + .tar.gz + + + macos-x64 + .tar.gz + + + macos-arm64 + .tar.gz + + + + + + + + + + + + + + + + + diff --git a/build/build.proj b/build/build.proj index 0643f1ed..d5bc6d5d 100644 --- a/build/build.proj +++ b/build/build.proj @@ -1,5 +1,6 @@ + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..')) @@ -7,14 +8,41 @@ Debug $(RepoRoot)/bin/api/publish $(RepoRoot)/bin/web/publish + + $(RepoRoot)/bin/release + + $(RepoRoot)/bin/release-verify + $(Version) + 0.0.0-dev + + <_ReleaseVersionPattern>^([0-9]+\.[0-9]+\.[0-9]+|0\.0\.0-dev)$ + + <_ImageVersion Condition="'$(Version)' != ''">$(Version) + <_ImageVersion Condition="'$(Version)' == ''">latest + + $(RepoRoot)/bin/api/bundled-plugins + + linux-x64 + + <_DockerPlatform Condition="'$(ApiReleaseRuntimeIdentifier)' == 'linux-x64'">linux/amd64 + <_DockerPlatform Condition="'$(ApiReleaseRuntimeIdentifier)' == 'linux-arm64'">linux/arm64 $(RepoRoot)/bin/api/BundledPlugins.current.manifest $(MSBuildThisFileDirectory)obj/BundledPlugins.slnx <_OfficialReleaseBuild Condition="'$(OfficialReleaseBuild)' == ''">false <_OfficialReleaseBuild Condition="'$(OfficialReleaseBuild)' != ''">$(OfficialReleaseBuild) <_DockerDependsOn>Build <_DockerDependsOn Condition="'$(_OfficialReleaseBuild)' == 'true'">ValidateDockerRelease;VerifyPublishedBundledPlugins + + <_DockerDependsOn Condition="'$(_OfficialReleaseBuild)' == 'true' And '$(ReusePublishedBundledPlugins)' == 'true'">ValidateDockerRelease + + <_DockerPlatformOption Condition="'$(_OfficialReleaseBuild)' == 'true'">--platform "$(_DockerPlatform)" + + + <_ReleaseRuntime Include="@(BundledPluginRuntime)" /> + + @@ -50,7 +78,7 @@ - + @@ -93,61 +121,347 @@ - - - - - + + + + <_StagingNativeRuntimeDirectory Include="$([System.IO.Directory]::GetDirectories('$(BundledPluginsPublishDirectory)/runtimes'))" Condition="Exists('$(BundledPluginsPublishDirectory)/runtimes')" /> + <_DeclaredStagingNativeRuntimeDirectory Include="@(BundledPluginRuntimeDirectory->'$(BundledPluginsPublishDirectory)/runtimes/%(Identity)')" /> + + + + + + + <_MissingStagingNativeRuntimeDirectory Include="@(_ExpectedStagingNativeRuntimeDirectory)" Condition="!Exists('%(FullPath)')" /> + <_UnexpectedStagingNativeRuntimeDirectory Include="@(_StagingNativeRuntimeDirectory)" Exclude="@(_ExpectedStagingNativeRuntimeDirectory)" /> + + + + + + + + + <_ApiReleaseDirectory>$(ApiPublishDirectory)/$(ApiReleaseRuntimeIdentifier) + + + + + <_WindowsReleaseRuntime Include="@(_ReleaseRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('win-'))" /> + <_UnixReleaseRuntime Include="@(_ReleaseRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('win-')) == false" /> + <_ReleaseApiPath Include="@(_ReleaseRuntime->'$(ApiPublishDirectory)/%(Identity)/Nemera.Presentation.Api.dll')" /> + <_ReleaseWebPath Include="@(_ReleaseRuntime->'$(WebPublishDirectory)/%(Identity)/Nemera.Presentation.Web.dll')" /> + <_ReleaseApiAppHostPath Include="@(_WindowsReleaseRuntime->'$(ApiPublishDirectory)/%(Identity)/Nemera.Presentation.Api.exe')" /> + <_ReleaseApiAppHostPath Include="@(_UnixReleaseRuntime->'$(ApiPublishDirectory)/%(Identity)/Nemera.Presentation.Api')" /> + <_ReleaseWebAppHostPath Include="@(_WindowsReleaseRuntime->'$(WebPublishDirectory)/%(Identity)/Nemera.Presentation.Web.exe')" /> + <_ReleaseWebAppHostPath Include="@(_UnixReleaseRuntime->'$(WebPublishDirectory)/%(Identity)/Nemera.Presentation.Web')" /> + <_MissingReleaseApi Include="@(_ReleaseApiPath)" Condition="!Exists('%(FullPath)')" /> + <_MissingReleaseWeb Include="@(_ReleaseWebPath)" Condition="!Exists('%(FullPath)')" /> + <_MissingReleaseApiAppHost Include="@(_ReleaseApiAppHostPath)" Condition="!Exists('%(FullPath)')" /> + <_MissingReleaseWebAppHost Include="@(_ReleaseWebAppHostPath)" Condition="!Exists('%(FullPath)')" /> + <_ReleaseNativeRuntimeMapping Include="@(BundledPluginRuntimeDirectory)" /> + <_ReleasePdb Include="$(ApiPublishDirectory)/**/*.pdb;$(WebPublishDirectory)/**/*.pdb" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ReleaseApiArchive Include="@(_ReleaseRuntime->'$(ReleaseArchivesDirectory)/Nemera-$(ReleaseVersion)-%(ReleaseArchiveStem)-api%(ReleaseArchiveExtension)')" /> + <_ReleaseWebArchive Include="@(_ReleaseRuntime->'$(ReleaseArchivesDirectory)/Nemera-$(ReleaseVersion)-%(ReleaseArchiveStem)-web%(ReleaseArchiveExtension)')" /> + <_MissingReleaseApiArchive Include="@(_ReleaseApiArchive)" Condition="!Exists('%(FullPath)')" /> + <_MissingReleaseWebArchive Include="@(_ReleaseWebArchive)" Condition="!Exists('%(FullPath)')" /> + + + + + + + + + + + + <_ReleaseRuntimeDirectoryPath>$(ApiPublishDirectory)/$(BundledPluginReleaseRuntimeIdentifier)/plugins/runtimes + + + + <_DeclaredRuntimeDirectory Include="@(BundledPluginRuntimeDirectory)" Condition="'%(BundledPluginRuntimeDirectory.RuntimeIdentifier)' == '$(BundledPluginReleaseRuntimeIdentifier)'" /> + <_ExpectedRuntimeDirectory Include="@(_DeclaredRuntimeDirectory->'$(_ReleaseRuntimeDirectoryPath)/%(Identity)')" /> + <_ActualRuntimeDirectory Include="$([System.IO.Directory]::GetDirectories('$(_ReleaseRuntimeDirectoryPath)'))" /> + <_MissingRuntimeDirectory Include="@(_ExpectedRuntimeDirectory)" Condition="!Exists('%(FullPath)')" /> + <_UnexpectedRuntimeDirectory Include="@(_ActualRuntimeDirectory)" Exclude="@(_ExpectedRuntimeDirectory)" /> + + + + + + + + + + <_NativeSourceDirectory>$(BundledPluginsPublishDirectory)/runtimes/$(BundledPluginRuntimeDirectoryName) + <_NativeReleaseDirectory>$(ApiPublishDirectory)/$(BundledPluginReleaseRuntimeIdentifier)/plugins/runtimes/$(BundledPluginRuntimeDirectoryName) + + + + <_NativeSourceFile Include="$(_NativeSourceDirectory)/**/*" /> + <_NativeReleaseFile Include="@(_NativeSourceFile->'$(_NativeReleaseDirectory)/%(RecursiveDir)%(Filename)%(Extension)')" /> + <_ActualNativeReleaseFile Include="$(_NativeReleaseDirectory)/**/*" /> + <_MissingNativeReleaseFile Include="@(_NativeReleaseFile)" Condition="!Exists('%(FullPath)')" /> + + + + + + + + + + <_NativeSourceHashList>@(_NativeSourceFileHash->'%(FileHash)') + <_NativeReleaseHashList>@(_NativeReleaseFileHash->'%(FileHash)') + <_NativeSourceFileCount>@(_NativeSourceFile->Count()) + <_ActualNativeFileCount>@(_ActualNativeReleaseFile->Count()) + + + + + + + + + <_ExpectedBundledPluginAssembly Include="@(BundledPluginProject->'$(ApiPublishDirectory)/$(BundledPluginReleaseRuntimeIdentifier)/plugins/%(Filename).dll')" /> + <_MissingBundledPluginAssembly Include="@(_ExpectedBundledPluginAssembly)" Condition="!Exists('%(FullPath)')" /> + + + + + + + + + <_ReferencePluginAssembly Include="$(ReferencePluginsDirectory)/Nemera.Plugins.*.dll" /> + <_ReleasePluginAssembly Include="@(_ReferencePluginAssembly->'$(ReleasePluginsDirectory)/%(Filename)%(Extension)')" /> + <_ActualReleasePluginAssembly Include="$(ReleasePluginsDirectory)/Nemera.Plugins.*.dll" /> + <_MissingReleasePluginAssembly Include="@(_ReleasePluginAssembly)" Condition="!Exists('%(FullPath)')" /> + <_UnexpectedReleasePluginAssembly Include="@(_ActualReleasePluginAssembly)" Exclude="@(_ReleasePluginAssembly)" /> + + + + + + + + + + + + <_ReferencePluginAssemblyCount>@(_ReferencePluginAssembly->Count()) + <_ActualReleasePluginAssemblyCount>@(_ActualReleasePluginAssembly->Count()) + <_ReferencePluginAssemblyHashList>@(_ReferencePluginAssemblyHash->'%(FileHash)') + <_ReleasePluginAssemblyHashList>@(_ReleasePluginAssemblyHash->'%(FileHash)') + + + + + + + + + + + + + + + + + + <_ExecutableTarReleaseArchiveEntry Include="@(_TarReleaseArchiveEntry)" Condition="'$(ReleaseArchiveExtension)' == '.tar.gz' And $([System.Text.RegularExpressions.Regex]::IsMatch('%(Identity)', '^-..x.*[ ./]$(ReleaseArchiveAppHostFileName)\s*$'))" /> + + + + + <_ArchiveSourceFile Include="$(ReleaseArchiveSourceDirectory)/**/*" /> + <_ArchiveExpectedFile Include="@(_ArchiveSourceFile->'$(ReleaseArchiveVerificationDirectory)/%(RecursiveDir)%(Filename)%(Extension)')" /> + <_ArchiveExtractedFile Include="$(ReleaseArchiveVerificationDirectory)/**/*" /> + <_MissingArchiveFile Include="@(_ArchiveExpectedFile)" Condition="!Exists('%(FullPath)')" /> + + + + + + + + + + <_ArchiveSourceHashList>@(_ArchiveSourceFileHash->'%(FileHash)') + <_ArchiveExtractedHashList>@(_ArchiveVerificationFileHash->'%(FileHash)') + <_ArchiveSourceFileCount>@(_ArchiveSourceFile->Count()) + <_ArchiveExtractedFileCount>@(_ArchiveExtractedFile->Count()) + + + + + + + + + + <_UnknownReleaseRuntime Include="$(ApiReleaseRuntimeIdentifier)" Exclude="@(BundledPluginRuntime)" /> + + - + - + + + + - - + + - <_PublishedBundledPluginAssembly Include="$(ApiPublishDirectory)/plugins/Nemera.Plugins.*.dll" /> + <_PublishedBundledPluginAssembly Include="$(BundledPluginsPublishDirectory)/Nemera.Plugins.*.dll" /> - + - - + + + + + + + + + + + + <_PublishedPdb Include="$(ApiPublishDirectory)/**/*.pdb;$(WebPublishDirectory)/**/*.pdb" /> + + <_PublishedBundledPlugins>true - - - + + + + + <_RuntimeBundledPluginSharedFile Include="$(BundledPluginsPublishDirectory)/**/*" Exclude="$(BundledPluginsPublishDirectory)/runtimes/**" /> + + <_ReleaseNativeRuntimeDirectory Include="@(BundledPluginRuntimeDirectory)" Condition="'%(BundledPluginRuntimeDirectory.RuntimeIdentifier)' == '$(BundledPluginReleaseRuntimeIdentifier)'" /> + + + - - + + + + <_RuntimeBundledPluginNativeFile Include="$(BundledPluginsPublishDirectory)/runtimes/$(BundledPluginRuntimeDirectoryName)/**/*" /> + + + + + + + + <_ReleaseVersionIsValid>false + <_ReleaseVersionIsValid Condition="$([System.Text.RegularExpressions.Regex]::IsMatch('$(ReleaseVersion)', '$(_ReleaseVersionPattern)'))">true + + + + + + + + <_ArchiveRuntime Include="@(BundledPluginRuntime)" /> + <_ArchivePublishOutput Include="@(_ArchiveRuntime->'$(ApiPublishDirectory)/%(Identity)/Nemera.Presentation.Api.dll')" /> + <_ArchivePublishOutput Include="@(_ArchiveRuntime->'$(WebPublishDirectory)/%(Identity)/Nemera.Presentation.Web.dll')" /> + <_MissingArchivePublishOutput Include="@(_ArchivePublishOutput)" Condition="!Exists('%(FullPath)')" /> + + + + + + + + + + + + + + + + + + <_DockerReleaseRuntime Include="linux-x64;linux-arm64" /> + <_NonGlibcDockerReleaseRuntime Include="$(ApiReleaseRuntimeIdentifier)" Exclude="@(_DockerReleaseRuntime)" /> + + + + + + + + + + + + <_DockerImageVersionIsValid>false + <_DockerImageVersionIsValid Condition="'$(_ImageVersion)' == 'latest'">true + <_DockerImageVersionIsValid Condition="$([System.Text.RegularExpressions.Regex]::IsMatch('$(_ImageVersion)', '$(_ReleaseVersionPattern)'))">true + + + + + + - <_ImageVersion Condition="'$(Version)' != ''">$(Version) - <_ImageVersion Condition="'$(Version)' == ''">latest <_DockerApiDockerfile Condition="'$(_OfficialReleaseBuild)' == 'true'">$(RepoRoot)/src/Nemera.Presentation.Api/Dockerfile.release <_DockerApiDockerfile Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot)/src/Nemera.Presentation.Api/Dockerfile - <_DockerApiContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(ApiPublishDirectory) + <_DockerApiContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(ApiPublishDirectory)/$(ApiReleaseRuntimeIdentifier) <_DockerApiContext Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot) <_DockerWebDockerfile Condition="'$(_OfficialReleaseBuild)' == 'true'">$(RepoRoot)/src/Nemera.Presentation.Web/Dockerfile.release <_DockerWebDockerfile Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot)/src/Nemera.Presentation.Web/Dockerfile - <_DockerWebContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(WebPublishDirectory) + <_DockerWebContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(WebPublishDirectory)/$(ApiReleaseRuntimeIdentifier) <_DockerWebContext Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot) - - + + @@ -172,17 +486,17 @@ - + - + - <_BundledPluginPublishedAssembly Include="$(ApiPublishDirectory)/plugins/Nemera.Plugins.*.dll" /> + <_BundledPluginPublishedAssembly Include="$(ApiPublishDirectory)/$(ApiReleaseRuntimeIdentifier)/plugins/Nemera.Plugins.*.dll" /> - + diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index c56eda0b..76823a89 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -30,7 +30,7 @@ Everything from Configuration onward applies to whichever route you chose. ## Before you start -- **Docker**, if you want the container route. For a non-container install, you need the Nemera application files, from a release package or installer, or from your own build, plus the **.NET 10 runtime** unless that package is self-contained. The **.NET 10 SDK** is only needed if you build from source. +- **Docker**, if you want the container route. For a non-container install, you need the Nemera application files, from a release package or installer, or from your own build, plus the **ASP.NET Core Runtime 10** unless that package is self-contained. The **.NET 10 SDK** is only needed if you build from source. - **ffmpeg**, for any non-container install, however you obtained the application files. The API server uses it to remux or transcode audio that the browser cannot play as stored. The Docker API container image already includes it. - By default the **web client listens on port `5012`** and the **API on port `5214`**. You can change either, as long as the two agree on where the API is (see [Configuration](#configuration)). - For anything reachable beyond your own machine, put a **reverse proxy** in front to terminate TLS and forward to the web client. @@ -86,12 +86,25 @@ Use a release package or installer when one is available, or, with the .NET 10 S dotnet build Nemera.slnx ``` -The official release artifacts include the PDF plugin's native libraries for Linux x64 and ARM64 (including Alpine x64), macOS Intel and Apple Silicon, and Windows x64 and ARM64. The single release download works on those platforms; the plugin loads the native libraries that match the host at runtime. +The official release is split into one API archive and one web archive per platform and architecture. Download both archives for your platform: -Run the API and the web client from the installed release package or from the published build. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: +| Platform | API archive | Web archive | +| --- | --- | --- | +| Linux x64 | `Nemera--linux-x64-api.tar.gz` | `Nemera--linux-x64-web.tar.gz` | +| Linux ARM64 | `Nemera--linux-arm64-api.tar.gz` | `Nemera--linux-arm64-web.tar.gz` | +| Linux x64 with musl, including Alpine | `Nemera--linux-musl-x64-api.tar.gz` | `Nemera--linux-musl-x64-web.tar.gz` | +| macOS Intel | `Nemera--macos-x64-api.tar.gz` | `Nemera--macos-x64-web.tar.gz` | +| macOS Apple Silicon | `Nemera--macos-arm64-api.tar.gz` | `Nemera--macos-arm64-web.tar.gz` | +| Windows x64 | `Nemera--windows-x64-api.zip` | `Nemera--windows-x64-web.zip` | +| Windows x86 | `Nemera--windows-x86-api.zip` | `Nemera--windows-x86-web.zip` | +| Windows ARM64 | `Nemera--windows-arm64-api.zip` | `Nemera--windows-arm64-web.zip` | + +Each archive contains only the files for its platform and architecture. The API archive includes the bundled plugins and the PDF plugin's native libraries for that platform. Extract both archives into separate folders. + +When using the release package, run the API and the web client from the folders you extracted. On Windows, start `Nemera.Presentation.Api.exe` and `Nemera.Presentation.Web.exe`. On Linux and macOS, start `./Nemera.Presentation.Api` and `./Nemera.Presentation.Web`. The API listens on `http://localhost:5214` and the web client on `http://localhost:5012` by default. Set `ASPNETCORE_URLS`, `ASPNETCORE_HTTP_PORTS` or `ASPNETCORE_HTTPS_PORTS` only when you need different addresses: ```bash -ASPNETCORE_HTTP_PORTS=5012 dotnet Nemera.Presentation.Web.dll +ASPNETCORE_URLS=http://0.0.0.0:5012 ./Nemera.Presentation.Web ``` The API creates its SQLite database (`Nemera.db`) next to its own binary and applies any pending migrations at startup, so the first launch sets up the schema on its own. diff --git a/docs/technical/RELEASING.md b/docs/technical/RELEASING.md index 1b069105..555232a0 100644 --- a/docs/technical/RELEASING.md +++ b/docs/technical/RELEASING.md @@ -19,15 +19,17 @@ Releases are cut only by the repository owner. There is one official build, and 1. The owner creates a `release/x.y.z` branch from `master`. 2. The `Publish Release` workflow builds and publishes the official artifacts with `OfficialReleaseBuild=true`. -3. The same workflow verifies the published API assembly against the published plugin binaries, records the release's plugin hashes in the append-only trust list, builds the release images from the verified publish output, and opens a pull request to `master`. -4. The owner downloads the official artifacts and creates the GitHub release and tag. +3. The same workflow verifies the embedded plugin manifest against every published API folder, records the release's plugin hashes in the append-only trust list, builds the release images from the verified publish output, and opens a pull request to `master`. +4. The owner downloads the release archives and creates the GitHub release and tag. 5. The owner merges the trust-list pull request. The current release already embeds its own official plugin manifest, so this pull request keeps the release's plugin binaries Official in future releases. -The full test suite runs on normal pull requests to `master`. The release build does not rerun the full suite. It runs the manifest verification tests for the official build, publishes, verifies the published API assembly against the published plugin binaries, records the hashes and builds the release images from the verified publish output. +The full test suite runs on normal pull requests to `master`. The release build does not rerun the full suite. It runs the manifest verification tests for the official build, publishes, verifies the embedded plugin manifest against every published API folder, checks the native folders and files of every runtime, verifies every archive against its publish folder, records the hashes and builds the release images from the verified publish output. The repository pins the .NET SDK in `global.json`. The workflows install that exact SDK, and the Docker build stage uses the matching `10.0.100` SDK image, so root-level and container builds use the same toolchain. -The `release-api` artifact is a single framework-dependent publish built on `ubuntu-latest`. The bundled plugin deployment keeps the PDF plugin's native libraries for the supported runtime identifiers: `win-x64`, `win-arm64`, `linux-x64`, `linux-arm64`, `linux-musl-x64`, `osx-x64` and `osx-arm64`. The macOS packages also keep their shared SkiaSharp library in the `osx` fallback folder, which the build retains automatically even though no device reports that identifier. The list is defined by `BundledPluginRuntimeIdentifiers` in `plugins/Directory.Build.props`, and the PDF plugin validates its required native libraries for every identifier in it, accepting a library from either the identifier's own folder or its OS family fallback. The plugin resolves the matching native library at runtime from its dependency manifest. The release Docker images copy that same publish output. +The `Publish` target produces two archives for each supported runtime identifier: an API archive and a web archive. The names are `Nemera----api.` and `Nemera----web.`, for example `Nemera-1.2.3-linux-x64-web.tar.gz` and `Nemera-1.2.3-windows-x64-api.zip`. Windows archives are `.zip` files; Linux and macOS archives are `.tar.gz` files, so the executable permission survives the download. Each archive contains the application files, the native apphost and the native libraries for that runtime identifier only. The supported runtime identifiers are `linux-x64`, `linux-arm64`, `linux-musl-x64`, `osx-x64`, `osx-arm64`, `win-x64`, `win-x86` and `win-arm64`, and the workflow builds them all on `ubuntu-latest`. The API archive also contains the bundled plugins, so the API can run directly from the extracted folder. The plugin deployment copies only the native runtime folders the catalog declares for that runtime: the identifier's own folder and the shared `osx` folder for the macOS archives, so the PDF plugin's native libraries for the other operating systems are not shipped. The macOS archives keep their shared SkiaSharp library in the `osx` fallback folder, which the build retains automatically even though no device reports that identifier. The runtime list is defined by the `BundledPluginRuntime` items and the native folder mapping by `BundledPluginRuntimeDirectory` in `build/RuntimeIdentifiers.props`. The catalog must list exactly the folders the bundled plugins deploy: verification fails when the staging folder is missing a declared folder or contains an undeclared one, and each release must contain exactly the folders declared for its runtime identifier. The PDF plugin validates its required native libraries for every identifier in it, accepting a library from either the identifier's own folder or its OS family fallback. The plugin resolves the matching native library at runtime from its dependency manifest. Verification runs the embedded manifest test against every published API folder, requires exactly the declared native runtime folders and their files, and extracts every archive to compare its contents and hashes with the publish folder it was built from. The trust list records the published plugin hashes from the verified `linux-x64` folder; every other runtime folder is verified against the same embedded manifest and its plugin binaries are compared with that reference folder, so the recorded hashes describe every shipped platform. The publish output excludes `.pdb` files. The API listens on `http://localhost:5214` and the web client on `http://localhost:5012` by default. The `Publish Release` workflow builds the release images from the `linux-x64` publish folders to validate the image definitions, and does not upload them. The images you ship are built manually from the extracted `Nemera--linux-x64-api` and `Nemera--linux-x64-web` archives with `--platform linux/amd64`, or from the `linux-arm64` archives with `--platform linux/arm64`; the `linux-musl-x64` archives cannot be used with these images, because their base image is a glibc distribution. The Linux and macOS archives must be created on Linux or macOS, because Windows cannot store the executable bit in a tar archive: `Publish` on Windows creates only the Windows archives and warns that the others were skipped. + +`Publish` restores the API and web projects once for all supported runtimes and publishes each runtime with `--no-restore`, so the projects keep a multi-RID assets file. The restore reads the runtime list from an environment variable set only for that command, so normal builds are unaffected. The presentation host does not compile against the concrete plugin projects, and it does not own the bundled plugin catalog. The plugin projects are part of the solution and copy their outputs to the API plugin folder. `build.proj` owns the release catalog: it builds and hashes the plugin binaries, writes the current manifest, passes that manifest to the API publish, and copies the binaries into the published plugin folder. Adding or removing a bundled plugin changes the release catalog and the solution, not the host project. @@ -93,12 +95,12 @@ The token is used only by the `record-manifest` job. It is not available to the ## Workflows - `Publish Release` runs when the owner creates a `release/x.y.z` branch. It has two jobs: - - `publish`: builds and publishes the official artifacts with `OfficialReleaseBuild=true`, runs the manifest verification tests, verifies the published API assembly against the published plugin binaries, records the released plugin hashes, builds the release images from the verified publish output, and uploads the `release-api`, `release-web` and `bundled-plugins-manifest` artifacts. It has the license secret and a read-only token. + - `publish`: builds and publishes the official artifacts with `OfficialReleaseBuild=true`, runs the manifest verification tests, verifies the embedded plugin manifest against every published API folder, checks every runtime's native folders and files, verifies every archive against its publish folder, records the released plugin hashes, builds the release images from the verified publish output, and uploads the `release-archives` and `bundled-plugins-manifest` artifacts. The `release-archives` artifact contains the API and web archives for every supported runtime. It has the license secret and a read-only token. - `record-manifest`: downloads the manifest artifact, appends only the release entries that are missing from master's current trust list, and opens the `other/record-release-x.y.z` pull request to `master` with the `RELEASE_PR_TOKEN`. It does not have the license secret. - `Run All Tests` runs on pull requests to `master` and uses the repository `SIXLABORS_LICENSE_KEY` secret. - `Branch Push Naming Convention Check` and `Pull Request Source Branch Validation Check` allow `feature/`, `bugfix/`, `hotfix/`, `documentation/`, `refactor/`, `other/`, and `release/x.y.z`. -The release branch is built from `master` after the normal pull request checks have passed. The release build does not rerun the full test suite. It runs the manifest verification tests, because that is the only part of the build that changes when the official plugin manifest and the official release marker are embedded. It then verifies the published API assembly against the published plugin binaries before recording hashes or building images. The trust-list pull request runs the full suite before it can be merged. +The release branch is built from `master` after the normal pull request checks have passed. The release build does not rerun the full test suite. It runs the manifest verification tests, because that is the only part of the build that changes when the official plugin manifest and the official release marker are embedded. It then verifies the embedded plugin manifest against every published API folder, the native folders and files of every runtime, and the contents of every archive before recording hashes or building images. The trust-list pull request runs the full suite before it can be merged. Recording is CI-only. The publish job checks that the worktree is clean and that `HEAD` matches `origin/master` before it appends to the trust list. A local `RecordBundledPlugins` run is rejected by the guard. @@ -111,26 +113,29 @@ The trust list `build/BundledPlugins.manifest` is append-only. Never remove exis 3. Create the `release/x.y.z` branch from the current `master` as the owner. The publish job requires the branch to point at the current `origin/master`. The check is exact: if anything merges to `master` before the job runs, the job fails and the branch must be recreated from the new `master`. 4. Approve the `release` environment for the `publish` and `record-manifest` jobs. 5. Wait for `Publish Release` to publish and verify the official artifacts, record the trust list and build the release images. -6. Download the `release-api` and `release-web` artifacts. -7. Create the GitHub release and tag manually from those artifacts. The workflow does not create the release. +6. Download the `release-archives` artifact. It contains one API archive and one web archive for each supported runtime identifier. +7. Create the GitHub release and tag manually from those archives. The workflow does not create the release. 8. Wait for `Run All Tests` and both branch validators on the `other/record-release-1.2.3` pull request. Review the trust-list diff and merge it. -9. The workflow builds the release images from the verified publish output to validate the image definitions, but it does not upload them. Build the images you ship from the downloaded artifacts, so they contain exactly the plugin binaries whose hashes were recorded: +9. The workflow builds the release images from the verified publish output to validate the image definitions, but it does not upload them. Build the images you ship from the extracted archives, so they contain exactly the plugin binaries whose hashes were recorded: ```bash - docker build -t nemera-api:1.2.3 -f src/Nemera.Presentation.Api/Dockerfile.release - docker build -t nemera-web:1.2.3 -f src/Nemera.Presentation.Web/Dockerfile.release + docker build --platform linux/amd64 -t nemera-api:1.2.3 -f src/Nemera.Presentation.Api/Dockerfile.release + docker build --platform linux/amd64 -t nemera-web:1.2.3 -f src/Nemera.Presentation.Web/Dockerfile.release ``` + Extract `Nemera-1.2.3-linux-x64-api.tar.gz` and `Nemera-1.2.3-linux-x64-web.tar.gz` first. Each archive contains its publish files at the root, so the extracted folder is the Docker context. Use `--platform linux/arm64` with the `linux-arm64` archives. The `linux-musl-x64` archives cannot be used with these images, because their base image is a glibc distribution. To publish, verify and build in one local step instead, run: ```bash dotnet msbuild build/build.proj -t:Docker -p:Configuration=Release -p:OfficialReleaseBuild=true -p:Version=1.2.3 ``` - That target publishes from source, verifies the publish output and builds the images from it. Those images are not the exact released artifacts unless the build is byte-identical, so prefer the downloaded artifacts for the images you ship. + That target publishes from source, verifies the publish output and builds the images from the `linux-x64` publish folder with the `linux/amd64` platform derived from `ApiReleaseRuntimeIdentifier`. Pass `-p:ApiReleaseRuntimeIdentifier=linux-arm64` to build from the arm64 publish folder instead. Those images are not the exact released artifacts unless the build is byte-identical, so prefer the downloaded archives for the images you ship. The local equivalent of the official build is verification only. Recording is CI-only. The release workflow checks that the checkout is clean and that `HEAD` matches `origin/master` exactly before it appends to the trust list. ```bash -dotnet msbuild build/build.proj -t:VerifyPublishedBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true +dotnet msbuild build/build.proj -t:VerifyPublishedBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true -p:Version=1.2.3 ``` +`VerifyPublishedBundledPlugins` checks the publish folders and does not require `bin/release`. `CreateReleaseArchives` can run on its own after a publish, and `VerifyReleaseArchives` creates the archives if needed and verifies every archive against its publish folder; both must run on Linux or macOS, because Windows cannot create `.tar.gz` archives with the executable bit. The Docker target only needs the publish folders, so `-t:Docker -p:ReusePublishedBundledPlugins=true` works even when `bin/release` is absent. `ReusePublishedBundledPlugins=true` skips both the publish and its verification, so pass it only after the publish folders were just verified, as the release workflow does. The release Docker target derives `--platform` from `ApiReleaseRuntimeIdentifier`, which must be `linux-x64` (`linux/amd64`) or `linux-arm64` (`linux/arm64`); `linux-musl-x64` has no matching glibc image base. + For a local Release build, set `SixLaborsLicenseKey` to the content of `src/Nemera.Domain/sixlabors.lic` first. The file alone is only discovered by `Nemera.Domain`, and projects that reference ImageSharp through it fail license validation otherwise. ## Revoking a bundled plugin hash @@ -184,5 +189,8 @@ If the token is compromised, also review recent branches, pull requests and work | `RecordBundledPlugins` fails because `master` moved | The release branch no longer matches the current `origin/master`. | Recreate the `release/x.y.z` branch from the new `master` and approve the new run. | | The record-list pull request removes trust-list lines | The merge step was skipped, or master's current manifest was replaced with an older artifact. | The record job only appends missing entries and fails if the staged diff removes a line. Rerun the workflow. | | A known good plugin is not Official | A deny-list entry matches its hash. | Remove the matching line from `build/BundledPlugins.deny.manifest`. | -| `VerifyPublishedBundledPlugins` fails | The manifest embedded in the published API assembly does not match the published plugin binaries. | Re-run the release build from the same commit. Do not mix artifacts from different builds. | -| The release image build fails with an official configuration error | `Docker` was called with `OfficialReleaseBuild=true` and a configuration other than `Release`. | Pass `-p:Configuration=Release`. | +| `VerifyPublishedBundledPlugins` fails | The bundled plugin staging folder is missing a native folder the catalog declares or contains an undeclared one, a published runtime folder is missing its assembly, apphost, plugin binary or native file, still contains a PDB or an undeclared native runtime folder or an unexpected number of plugin binaries, its embedded plugin manifest does not match its plugin binaries, or its plugin binaries differ from the reference `linux-x64` folder. | Re-run the release build from the same commit. Do not mix artifacts from different builds. If the staging folder and the catalog disagree, align `build/RuntimeIdentifiers.props` with the native folders the bundled plugins deploy. | +| `VerifyReleaseArchives` fails | A platform archive is missing, or its files or hashes differ from the publish folder it was built from, or the Linux or macOS app host is not executable inside the archive. | Re-run the release build from the same commit, so the archives and the publish folders come from the same build. Build Linux and macOS archives on Linux or macOS. | +| The Linux or macOS archives are missing after `Publish` | `Publish` ran on Windows, which cannot store the executable bit in a tar archive, so those archives are skipped with a warning. | Run `Publish` on Linux or macOS. The `Publish Release` workflow builds the released archives on `ubuntu-latest`. | +| The release build rejects the version | `Version` or `ReleaseVersion` is not three numeric parts. | Pass a version such as `-p:Version=1.2.3`. | +| The release image build fails with an official configuration error | `Docker` was called with `OfficialReleaseBuild=true` and a configuration other than `Release`, or with an `ApiReleaseRuntimeIdentifier` that is not a glibc runtime (`linux-x64` or `linux-arm64`; the musl runtime has no matching image base). | Pass `-p:Configuration=Release` and a glibc runtime identifier such as `linux-x64`. | diff --git a/plugins/Directory.Build.props b/plugins/Directory.Build.props index ea80d1ac..210fa3b2 100644 --- a/plugins/Directory.Build.props +++ b/plugins/Directory.Build.props @@ -1,11 +1,10 @@ + $(RepoRoot)bin/plugins/ - - win-x64;win-arm64;linux-x64;linux-arm64;linux-musl-x64;osx-x64;osx-arm64 true true $(WarningsAsErrors);CS1591 diff --git a/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj b/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj index de5827da..854f1369 100644 --- a/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj +++ b/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj @@ -11,10 +11,11 @@ - + + - <_SupportedPdfRuntime Include="$(BundledPluginRuntimeIdentifiers)" /> + <_SupportedPdfRuntime Include="@(BundledPluginRuntime)" /> <_WindowsPdfRuntime Include="@(_SupportedPdfRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('win-'))"> win diff --git a/src/Nemera.Presentation.Api/Dockerfile b/src/Nemera.Presentation.Api/Dockerfile index 0ba7d002..b107f65b 100644 --- a/src/Nemera.Presentation.Api/Dockerfile +++ b/src/Nemera.Presentation.Api/Dockerfile @@ -62,9 +62,8 @@ WORKDIR /app # The app user must own the published files, because the plugin installer writes into /app/plugins. COPY --from=publish --chown=app:app /app/publish . -# The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for -# Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set. -ENV ASPNETCORE_HTTP_PORTS=5214 +# The container branch in Program.cs binds the API to this port. Direct published runs default to the documented address +# and can override it with ASPNETCORE_URLS, ASPNETCORE_HTTP_PORTS or ASPNETCORE_HTTPS_PORTS. EXPOSE 5214 ENTRYPOINT ["dotnet", "Nemera.Presentation.Api.dll"] diff --git a/src/Nemera.Presentation.Api/Dockerfile.release b/src/Nemera.Presentation.Api/Dockerfile.release index 4f759867..b616f62d 100644 --- a/src/Nemera.Presentation.Api/Dockerfile.release +++ b/src/Nemera.Presentation.Api/Dockerfile.release @@ -1,6 +1,6 @@ # This image ships the published release artifacts, so the recorded plugin hashes and the image contents are the same files. -# Build it with the published API directory as the context: -# docker build -t nemera-api -f src/Nemera.Presentation.Api/Dockerfile.release bin/api/publish +# Build it with the extracted Linux x64 API archive as the context. +# docker build -t nemera-api -f src/Nemera.Presentation.Api/Dockerfile.release FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final # Curl is used by the container healthcheck to probe the /health endpoints. @@ -16,6 +16,6 @@ WORKDIR /app # The app user must own the published files, because the plugin installer writes into /app/plugins. COPY --chown=app:app . . -ENV ASPNETCORE_HTTP_PORTS=5214 +# The container branch in Program.cs binds the API to this port. EXPOSE 5214 ENTRYPOINT ["dotnet", "Nemera.Presentation.Api.dll"] diff --git a/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj b/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj index 32017ce3..14653f67 100644 --- a/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj +++ b/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj @@ -9,6 +9,8 @@ nemera-api nemera-api ..\docker-compose.dcproj + + $(NEMERA_RELEASE_RUNTIME_IDENTIFIERS) $(DefineConstants);OFFICIAL_RELEASE_BUILD diff --git a/src/Nemera.Presentation.Api/Program.cs b/src/Nemera.Presentation.Api/Program.cs index e1fc3b1b..db6068f8 100644 --- a/src/Nemera.Presentation.Api/Program.cs +++ b/src/Nemera.Presentation.Api/Program.cs @@ -74,7 +74,16 @@ public class Program }); } else + { logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // Use local binary path. + // A published build used to fall back to the framework's port 5000. Keep the documented default only when the host + // did not provide an address or a port through configuration, including ASPNETCORE_URLS, ASPNETCORE_HTTP_PORTS + // and ASPNETCORE_HTTPS_PORTS. + if (string.IsNullOrWhiteSpace(builder.Configuration["Urls"]) + && string.IsNullOrWhiteSpace(builder.Configuration["HTTP_PORTS"]) + && string.IsNullOrWhiteSpace(builder.Configuration["HTTPS_PORTS"])) + builder.WebHost.UseUrls("http://localhost:5214"); + } Directory.CreateDirectory(logPath); if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString())) logPath = logPath += Path.DirectorySeparatorChar; diff --git a/src/Nemera.Presentation.Web/Dockerfile b/src/Nemera.Presentation.Web/Dockerfile index 8af6040c..3603df87 100644 --- a/src/Nemera.Presentation.Web/Dockerfile +++ b/src/Nemera.Presentation.Web/Dockerfile @@ -47,9 +47,8 @@ FROM base AS final WORKDIR /app COPY --from=publish --chown=app:app /app/publish . -# The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for -# Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set. -ENV ASPNETCORE_HTTP_PORTS=5012 +# The container branch in Program.cs binds the web client to this port. Direct published runs default to the documented +# address and can override it with ASPNETCORE_URLS, ASPNETCORE_HTTP_PORTS or ASPNETCORE_HTTPS_PORTS. EXPOSE 5012 ENTRYPOINT ["dotnet", "Nemera.Presentation.Web.dll"] diff --git a/src/Nemera.Presentation.Web/Dockerfile.release b/src/Nemera.Presentation.Web/Dockerfile.release index 17e1350b..80333ea3 100644 --- a/src/Nemera.Presentation.Web/Dockerfile.release +++ b/src/Nemera.Presentation.Web/Dockerfile.release @@ -1,6 +1,6 @@ # This image ships the published release artifacts, so the image contents are the same files the release workflow exported. -# Build it with the published Web directory as the context: -# docker build -t nemera-web -f src/Nemera.Presentation.Web/Dockerfile.release bin/web/publish +# Build it with the extracted Linux x64 Web archive as the context. +# docker build -t nemera-web -f src/Nemera.Presentation.Web/Dockerfile.release FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final # Curl is used by the container healthcheck to probe the /health endpoints. @@ -14,6 +14,6 @@ WORKDIR /app COPY --chown=app:app . . -ENV ASPNETCORE_HTTP_PORTS=5012 +# The container branch in Program.cs binds the web client to this port. EXPOSE 5012 ENTRYPOINT ["dotnet", "Nemera.Presentation.Web.dll"] diff --git a/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj b/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj index 663123fe..369dcfde 100644 --- a/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj +++ b/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj @@ -11,6 +11,8 @@ nemera-web nemera-web ..\docker-compose.dcproj + + $(NEMERA_RELEASE_RUNTIME_IDENTIFIERS) diff --git a/src/Nemera.Presentation.Web/Program.cs b/src/Nemera.Presentation.Web/Program.cs index 8cd3cd31..8ed655b6 100644 --- a/src/Nemera.Presentation.Web/Program.cs +++ b/src/Nemera.Presentation.Web/Program.cs @@ -1,8 +1,5 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Nemera.Presentation.Web.Common.DependencyInjection; -using Nemera.Presentation.Web.Common.HealthChecks; -using Nemera.Presentation.Web.Common.Utilities; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; @@ -11,6 +8,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Primitives; +using Nemera.Presentation.Web.Common.DependencyInjection; +using Nemera.Presentation.Web.Common.HealthChecks; +using Nemera.Presentation.Web.Common.Utilities; using Scalar.AspNetCore; using Serilog; using System; @@ -50,7 +50,16 @@ public class Program builder.WebHost.ConfigureKestrel(options => options.ListenAnyIP(5012)); // HTTP only. } else + { logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // Use local binary path. + // A published build used to fall back to the framework's port 5000. Keep the documented default only when the host + // did not provide an address or a port through configuration, including ASPNETCORE_URLS, ASPNETCORE_HTTP_PORTS + // and ASPNETCORE_HTTPS_PORTS. + if (string.IsNullOrWhiteSpace(builder.Configuration["Urls"]) + && string.IsNullOrWhiteSpace(builder.Configuration["HTTP_PORTS"]) + && string.IsNullOrWhiteSpace(builder.Configuration["HTTPS_PORTS"])) + builder.WebHost.UseUrls("http://localhost:5012"); + } Directory.CreateDirectory(logPath); if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString())) logPath = logPath += Path.DirectorySeparatorChar; diff --git a/src/Nemera.slnx b/src/Nemera.slnx index 7319ce62..5cc8c12c 100644 --- a/src/Nemera.slnx +++ b/src/Nemera.slnx @@ -366,6 +366,7 @@ + diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReader.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReader.cs new file mode 100644 index 00000000..a22361c4 --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReader.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Reads an embedded resource from an assembly file without loading the assembly into the current process. +/// +/// +/// The published bundled plugin manifest verification inspects publish folders of other architectures, where loading the assembly would fail. +/// +[ExcludeFromCodeCoverage] +public static class PublishedAssemblyResourceReader +{ + /// + /// Reads an embedded resource from an assembly file without loading the assembly into the current process. + /// + /// The absolute path of the assembly file. + /// The name of the embedded resource. + /// The raw bytes of the embedded resource. + public static byte[] ReadEmbeddedResource(string assemblyPath, string resourceName) + { + using (FileStream assemblyStream = File.OpenRead(assemblyPath)) + { + using (PEReader peReader = new(assemblyStream)) + { + // A publish folder without managed metadata means the wrong artifact was passed, so fail instead of reporting a missing resource. + if (!peReader.HasMetadata) + throw new InvalidOperationException($"The assembly '{assemblyPath}' does not contain managed metadata."); + MetadataReader metadataReader = peReader.GetMetadataReader(); + foreach (ManifestResourceHandle resourceHandle in metadataReader.ManifestResources) + { + ManifestResource resource = metadataReader.GetManifestResource(resourceHandle); + // A resource with a non-null implementation is linked from another file, so its bytes are not stored in this resources directory. + if (!metadataReader.StringComparer.Equals(resource.Name, resourceName) || !resource.Implementation.IsNil) + continue; + // The embedded payloads live in the PE resources directory, and every resource offset is relative to the start of that directory. + PEMemoryBlock resourceDirectory = peReader.GetSectionData(peReader.PEHeaders.CorHeader!.ResourcesDirectory.RelativeVirtualAddress); + BlobReader resourceReader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); + // Every embedded resource is prefixed with a four-byte length before its payload. + int resourceLength = resourceReader.ReadInt32(); + return resourceReader.ReadBytes(resourceLength); + } + } + } + // Returning empty bytes would let the manifest verification compare against nothing, so a missing resource is treated as a broken artifact. + throw new InvalidOperationException($"The embedded resource '{resourceName}' is missing from '{assemblyPath}'."); + } +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReaderTests.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReaderTests.cs new file mode 100644 index 00000000..4873ba0f --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/PublishedAssemblyResourceReaderTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Contains integration tests for the test helper. +/// +[ExcludeFromCodeCoverage] +public class PublishedAssemblyResourceReaderTests +{ + /// + /// The resource name of the append-only trust list of previously released bundled plugin binaries. + /// + private const string HISTORICAL_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.historical.manifest"; + + [Fact] + public void ReadEmbeddedResource_WhenReadingTheLoadedAssemblyFile_ShouldMatchTheLoadedResourceStream() + { + // Arrange + // The loaded assembly's file is read directly, which is the same path the published artifact verification uses. + string assemblyPath = typeof(Program).Assembly.Location; + byte[] expectedResourceBytes; + using (Stream resourceStream = typeof(Program).Assembly.GetManifestResourceStream(HISTORICAL_MANIFEST_RESOURCE_NAME) + ?? throw new InvalidOperationException($"The embedded manifest resource '{HISTORICAL_MANIFEST_RESOURCE_NAME}' is missing.")) + { + using (MemoryStream resourceBuffer = new()) + { + resourceStream.CopyTo(resourceBuffer); + expectedResourceBytes = resourceBuffer.ToArray(); + } + } + + // Act + byte[] actualResourceBytes = PublishedAssemblyResourceReader.ReadEmbeddedResource(assemblyPath, HISTORICAL_MANIFEST_RESOURCE_NAME); + + // Assert + Assert.Equal(expectedResourceBytes, actualResourceBytes); + } +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs index 1132816f..736d892d 100644 --- a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs @@ -7,8 +7,6 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; -using System.Reflection; -using System.Runtime.Loader; using System.Xml.Linq; #endregion @@ -217,41 +215,30 @@ public class BundledPluginManifestReaderTests ?? throw new InvalidOperationException($"The environment variable '{PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE}' is not set."); string publishedApiAssemblyPath = BundledPluginManifestTestPaths.GetPublishedApiAssemblyPath(publishDirectory); string publishedPluginsDirectory = BundledPluginManifestTestPaths.GetPublishedPluginsDirectory(publishDirectory); - // Load the published API assembly in its own context, so the test reads the exact shipped binary without loading it into the test process. - AssemblyLoadContext loadContext = new("PublishedBundledPluginManifestVerification", isCollectible: true); - try + // Read the resource directly from the file. Loading the assembly would fail for a runtime whose architecture differs from the test process. + byte[] publishedManifestBytes = PublishedAssemblyResourceReader.ReadEmbeddedResource(publishedApiAssemblyPath, CURRENT_MANIFEST_RESOURCE_NAME); + using (MemoryStream manifestStream = new(publishedManifestBytes)) { - Assembly publishedApiAssembly = loadContext.LoadFromAssemblyPath(publishedApiAssemblyPath); - // The published assembly must embed the current manifest. A missing resource means the official publish step did not run. - using (Stream manifestStream = publishedApiAssembly.GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME) - ?? throw new InvalidOperationException("The published API assembly does not embed the current bundled plugin manifest.")) - { - // Act - IReadOnlyDictionary> publishedManifestEntries = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); + // Act + IReadOnlyDictionary> publishedManifestEntries = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); - // Assert - Assert.NotEmpty(publishedManifestEntries); - // The manifest and the published plugin folder must agree exactly: every entry has a file, and the counts match. - string[] publishedPluginAssemblyFileNames = [.. Directory.EnumerateFiles(publishedPluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN) - .Select(Path.GetFileName) - .OfType()]; - Assert.Equal(publishedManifestEntries.Count, publishedPluginAssemblyFileNames.Length); - foreach (KeyValuePair> entry in publishedManifestEntries) - { - Assert.Contains(entry.Key, publishedPluginAssemblyFileNames, StringComparer.OrdinalIgnoreCase); - string publishedAssemblyPath = Path.Combine(publishedPluginsDirectory, entry.Key); - Assert.True(File.Exists(publishedAssemblyPath), $"The published plugin assembly '{entry.Key}' is missing from '{publishedPluginsDirectory}'."); - string actualSha256 = _bundledPluginFileHashFixture.Create(publishedAssemblyPath); - string expectedSha256 = Assert.Single(entry.Value); - Assert.Equal(expectedSha256, actualSha256, ignoreCase: true); - } + // Assert + Assert.NotEmpty(publishedManifestEntries); + // The manifest and the published plugin folder must agree exactly: every entry has a file, and the counts match. + string[] publishedPluginAssemblyFileNames = [.. Directory.EnumerateFiles(publishedPluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN) + .Select(Path.GetFileName) + .OfType()]; + Assert.Equal(publishedManifestEntries.Count, publishedPluginAssemblyFileNames.Length); + foreach (KeyValuePair> entry in publishedManifestEntries) + { + Assert.Contains(entry.Key, publishedPluginAssemblyFileNames, StringComparer.OrdinalIgnoreCase); + string publishedAssemblyPath = Path.Combine(publishedPluginsDirectory, entry.Key); + Assert.True(File.Exists(publishedAssemblyPath), $"The published plugin assembly '{entry.Key}' is missing from '{publishedPluginsDirectory}'."); + string actualSha256 = _bundledPluginFileHashFixture.Create(publishedAssemblyPath); + string expectedSha256 = Assert.Single(entry.Value); + Assert.Equal(expectedSha256, actualSha256, ignoreCase: true); } } - finally - { - // Unload the collectible context so the published assembly does not stay locked for later test runs. - loadContext.Unload(); - } } /// @@ -285,8 +272,8 @@ public class BundledPluginManifestReaderTests { using (Stream stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException($"The embedded manifest resource '{resourceName}' is missing.")) - using (StreamReader reader = new(stream)) - return reader.ReadToEnd(); + using (StreamReader reader = new(stream)) + return reader.ReadToEnd(); } /// From 2a90022aa8974b016c08ccd4b505fe06b5d119d5 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 30 Nov 2026 21:20:44 +0200 Subject: [PATCH 2/2] Persists the activated theme without a redundant update --- .../Core/Themes/ThemeSynchronizer.cs | 20 ++-- .../Core/Themes/ThemeSynchronizerTests.cs | 92 +++++++++++++++ ...era.Infrastructure.IntegrationTests.csproj | 2 + .../Core/Themes/ThemeSynchronizerTests.cs | 105 +++++++----------- 4 files changed, 145 insertions(+), 74 deletions(-) create mode 100644 tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs diff --git a/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs index dc309bea..7ce1e692 100644 --- a/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs +++ b/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DataAccess.Entities.Themes; using Nemera.Application.Common.DataAccess.UoW; using Nemera.Application.Common.DTO.Filtering; @@ -7,7 +8,6 @@ using Nemera.Application.Common.Infrastructure.Models.DTO.Themes; using Nemera.Application.Common.Infrastructure.Themes; using Nemera.Domain.Common.Primitives; using Nemera.Domain.SharedKernel.Common.Enums.Themes; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -32,6 +32,8 @@ internal static class ThemeSynchronizer /// Cancellation token that can be used to stop the execution. internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken) { + // The installed themes are read tracked, so the current flag that EnsureCurrentThemeExists sets on an existing theme is + // persisted by the final SaveChangesAsync; a theme inserted during this synchronization is tracked as added by InsertAsync. Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) { @@ -127,7 +129,7 @@ internal static class ThemeSynchronizer } await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); - await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); + EnsureCurrentThemeExists(themeService, themes); Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) @@ -208,14 +210,11 @@ internal static class ThemeSynchronizer } /// - /// Activates the configured default theme when no theme is currently active, so the application always has an active theme. + /// Marks the configured default theme as current when no theme is currently active, so the application always has an active theme. /// /// Injected service for the server-side storage and serving of theme packs. - /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. - /// Injected logger used for logging. - /// Cancellation token that can be used to stop the execution. - private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, ILogger logger, CancellationToken cancellationToken) + internal static void EnsureCurrentThemeExists(IThemeService themeService, IReadOnlyList themes) { if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) return; @@ -231,10 +230,9 @@ internal static class ThemeSynchronizer if (defaultTheme is null) return; + // A theme inserted during this synchronization is not in the database yet, so an UpdateAsync call would fail with ThemeNotFound. + // The entity is already tracked, as added by InsertAsync or as an existing row from the tracked read, so setting the flag here + // is persisted by the SaveChangesAsync that follows the synchronization. defaultTheme.IsCurrent = true; - Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); - if (updateResult.IsFailure) - if (logger.IsEnabled(LogLevel.Warning)) - logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description); } } diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs new file mode 100644 index 00000000..1d31c292 --- /dev/null +++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Nemera.Application.Common.DataAccess.Entities.Themes; +using Nemera.Application.Common.Infrastructure.Models.DTO.Themes; +using Nemera.Application.Common.Infrastructure.Themes; +using Nemera.Application.Common.Infrastructure.Time; +using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; +using Nemera.DataAccess.Core.UoW; +using Nemera.Domain.Common.Primitives; +using Nemera.Infrastructure.Core.Themes; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Nemera.Infrastructure.IntegrationTests.Core.Themes; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeSynchronizerTests : IDisposable +{ + private readonly DbContextOptions _dbContextOptions; + private readonly NemeraDbContext _dbContext; + private readonly UnitOfWork _unitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ILogger _mockLogger; + private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly string _archivePath; + + /// + /// Initializes a new instance of the class. + /// + public ThemeSynchronizerTests() + { + _dbContextOptions = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; + _dbContext = new NemeraDbContext(_dbContextOptions); + _unitOfWork = new UnitOfWork(_dbContext, Substitute.For()); + _mockThemeService = Substitute.For(); + _mockLogger = Substitute.For(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); + _archivePath = Path.Combine(Path.GetTempPath(), $"nemera-theme-sync-{Guid.NewGuid():N}.zip"); + } + + [Fact] + public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldPersistTheActivatedTheme() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + File.WriteAllText(_archivePath, "theme-pack"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([_archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(_archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.HasThemePack(Arg.Any()).Returns(true); + _mockThemeService.DefaultThemeId.Returns(manifest.Id); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _unitOfWork, _mockLogger, CancellationToken.None); + + // Assert + // Activating an inserted theme must not attempt an update, which the repository would report as a failed activation warning. + _mockLogger.DidNotReceive().Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + // Read through a fresh context so the assertion proves SaveChanges wrote the activation, not only that the entity was tracked. + using (NemeraDbContext verificationContext = new(_dbContextOptions)) + { + ThemeEntity persistedTheme = Assert.Single(verificationContext.Themes); + Assert.True(persistedTheme.IsCurrent); + } + } + + /// + /// Releases the database context and removes the temporary archive file. + /// + public void Dispose() + { + _dbContext.Dispose(); + if (File.Exists(_archivePath)) + File.Delete(_archivePath); + } +} diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj index 6e411380..fe742b39 100644 --- a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj +++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj @@ -24,6 +24,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -40,6 +41,7 @@ + diff --git a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index 0cbf129b..ed622d8d 100644 --- a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DataAccess.Entities.Themes; using Nemera.Application.Common.DataAccess.Repositories.Themes; using Nemera.Application.Common.DataAccess.UoW; using Nemera.Application.Common.DTO.Filtering; -using Nemera.Application.Common.DTO.Pagination; using Nemera.Application.Common.Infrastructure.Models.DTO.Themes; using Nemera.Application.Common.Infrastructure.Themes; using Nemera.Application.Fixtures.Common.DataAccess.Entities.Themes; @@ -12,14 +12,10 @@ using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; using Nemera.Domain.Common.Primitives; using Nemera.Domain.SharedKernel.Common.Enums.Themes; using Nemera.Infrastructure.Core.Themes; -using Microsoft.Extensions.Logging; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; -using System.Reflection; using System.Threading; using System.Threading.Tasks; #endregion @@ -56,7 +52,7 @@ public class ThemeSynchronizerTests : IDisposable _mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.HasThemePack(Arg.Any()).Returns(true); _mockThemeService.DefaultThemeId.Returns("nemera-default"); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); @@ -68,7 +64,7 @@ public class ThemeSynchronizerTests : IDisposable public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn() { // Arrange - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()) .Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes")); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); @@ -85,7 +81,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange _mockLogger.IsEnabled(Arg.Any()).Returns(false); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()) .Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes")); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); @@ -124,7 +120,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.2.3"); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.2.3", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -143,7 +139,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0"); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); @@ -164,7 +160,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -182,7 +178,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); // The first pack check happens before the repair and reports the files as missing; the later checks report the files as present. @@ -204,7 +200,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); @@ -309,7 +305,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); // Act await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); @@ -324,7 +320,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success); @@ -342,7 +338,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -361,7 +357,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -381,7 +377,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -401,7 +397,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); // Act @@ -416,7 +412,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme")); @@ -435,7 +431,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1))); _mockThemeService.HasThemePack(Arg.Any()).Returns(false); _mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new InvalidOperationException("Unexpected failure"))); @@ -456,7 +452,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new OperationCanceledException())); @@ -489,7 +485,7 @@ public class ThemeSynchronizerTests : IDisposable updatedBy: Guid.NewGuid()); DateTime? initialUpdatedOnUtc = installedTheme.UpdatedOnUtc; Guid? initialUpdatedBy = installedTheme.UpdatedBy; - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); @@ -515,7 +511,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0"); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); @@ -544,7 +540,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0"); ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.HasThemePack(uploadedTheme.ThemeId).Returns(true); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -564,7 +560,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.5.0"); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.5.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); @@ -580,37 +576,35 @@ public class ThemeSynchronizerTests : IDisposable } [Fact] - public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme() + public void EnsureCurrentThemeExists_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme() { // Arrange ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false); // Act - await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]); + ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [currentTheme, otherTheme]); // Assert Assert.True(currentTheme.IsCurrent); Assert.NotEqual(true, otherTheme.IsCurrent); - await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); } [Fact] - public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme() + public void EnsureCurrentThemeExists_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme() { // Arrange ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true); // Act - await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]); + ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [deletedTheme]); // Assert Assert.NotEqual(true, deletedTheme.IsCurrent); - await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); } [Fact] - public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() + public void EnsureCurrentThemeExists_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() { // Arrange ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "nemera-default", installSource: ThemeInstallSource.Bundled, isDeleted: false); @@ -619,35 +613,33 @@ public class ThemeSynchronizerTests : IDisposable _mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false); // Act - await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]); + ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [userTheme, defaultTheme]); // Assert Assert.True(defaultTheme.IsCurrent); - await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any()); } [Fact] - public async Task EnsureCurrentThemeExistsAsync_WhenActivatingTheDefaultThemeFails_ShouldLogAndNotThrow() + public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldMarkTheInsertedThemeCurrentWithoutUpdatingIt() { // Arrange - ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "nemera-default", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Themes.UpdateFailed", "Failed to activate the theme")); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + ThemeEntity? insertedTheme = null; + _mockThemeRepository.InsertAsync(Arg.Do(theme => insertedTheme = theme), Arg.Any()).Returns(Result.Created); // Act - await InvokeEnsureCurrentThemeExistsAsync([defaultTheme]); + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); // Assert - Assert.True(defaultTheme.IsCurrent); - await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any()); - // A failed activation must not be silent, so it is logged instead of being discarded. - _mockLogger.Received(1).Log( - LogLevel.Warning, - Arg.Any(), - Arg.Any(), - Arg.Any(), - Arg.Any>()); + Assert.NotNull(insertedTheme); + Assert.True(insertedTheme!.IsCurrent); + // A theme inserted in this synchronization is not in the database yet, so UpdateAsync would fail with ThemeNotFound. + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } /// @@ -661,19 +653,6 @@ public class ThemeSynchronizerTests : IDisposable return archivePath; } - /// - /// Invokes the private EnsureCurrentThemeExistsAsync method of the synchronizer. - /// - /// The installed themes passed to the method. - /// A task that represents the asynchronous operation. - private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList themes) - { - MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic) - ?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer."); - Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, _mockLogger, CancellationToken.None])!; - await task.ConfigureAwait(false); - } - /// /// Removes the temporary files created by the tests. ///