diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 00f10c4..55300e0 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,11 +1,22 @@ name: Docs -# Builds the documentation site with DocFX and publishes it to GitHub Pages. One workflow, two sites: -# - in StellarEngine-Core: the site of the core (docfx.json): Docs/, the API reference, the schemas, the installer; -# - in the mirror (StellarEngine-Mono), recognized by the .orchestra file scripts/mirror.ps1 puts at its root: -# the site of the orchestra (scripts/orchestra-site.ps1), the core and every module in one site. -# Pull requests and manual runs on other branches only build; the site is deployed from master only. -# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions". +# Publishes the documentation of this repository to GitHub Pages for the Prometheus site (the team site). +# GitHub Pages is only the storage of the site: static files (the installer, the schemas), the documentation as data +# (bundle/) and a small embed that redirects to the site when the site is up. +# +# This file is a thin wrapper and does not need updates: the steps (ci.py, the bundle builder, the embed) are +# downloaded from the site on every run (/docs-kit.zip), so they are always the same version as the site. +# What to build is described by the repository itself in prometheus.json (format prometheus-repo/1, see the DOCS +# page of the site); without it: Docs/ and the API of the projects in docfx.json. +# If the site is down, the static files and a page that leads to the site are published; the next run fixes the rest. +# +# Repository settings: +# Settings -> Pages -> Source = "GitHub Actions" (once) +# Variables (optional): PROMETHEUS_SITE (https://notagood.org by default), +# PROMETHEUS_PROJECT, PROMETHEUS_TITLE (override prometheus.json) +# Secrets (optional): PROMETHEUS_SYNC_KEY an API key of the site with the "sync" scope: the site learns about +# the new build at once instead of on its next check +# Pull requests and manual runs on other branches only build; Pages is deployed from master only. on: push: @@ -24,49 +35,88 @@ env: DOCFX_VERSION: '2.81.0' DOTNET_NOLOGO: 'true' DOTNET_CLI_TELEMETRY_OPTOUT: 'true' + PROMETHEUS_SITE: ${{ vars.PROMETHEUS_SITE || 'https://notagood.org' }} + PROMETHEUS_PROJECT: ${{ vars.PROMETHEUS_PROJECT }} + PROMETHEUS_TITLE: ${{ vars.PROMETHEUS_TITLE }} + OUT: artifacts/pages jobs: build: - name: Build site - runs-on: ubuntu-latest + name: Build + runs-on: ubuntu-latest # pwsh, python3 and bash are there: "prepare" scripts may use any of them steps: - name: Checkout uses: actions/checkout@v5 - name: Setup .NET + if: hashFiles('global.json') != '' uses: actions/setup-dotnet@v5 with: global-json-file: global.json - # Installed outside the checkout so the repository NuGet.config (local "packages" feed) is not involved. + - name: Setup .NET (no global.json) + if: hashFiles('global.json') == '' + uses: actions/setup-dotnet@v5 + with: + dotnet-version: '9.0.x' + + # Installed outside the checkout so a repository NuGet.config (a local feed) is not involved. - name: Install DocFX working-directory: ${{ runner.temp }} run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx" - - name: Choose the site - id: site - shell: pwsh + - name: Prometheus + id: prometheus + continue-on-error: true run: | - # The local feed of an installation: empty here, but NuGet wants the folder it names to exist - New-Item -ItemType Directory -Force packages | Out-Null - if (Test-Path .orchestra) { - ./scripts/orchestra-site.ps1 - "config=docfx.orchestra.json" >> $env:GITHUB_OUTPUT - "output=artifacts/docs/orchestra-site" >> $env:GITHUB_OUTPUT - } else { - "config=docfx.json" >> $env:GITHUB_OUTPUT - "output=artifacts/docs/site" >> $env:GITHUB_OUTPUT - } + set -euo pipefail + # NuGet wants the local feed folder of an installation to exist, even empty + mkdir -p packages + curl -fsSL --retry 2 "$PROMETHEUS_SITE/docs-kit.zip" -o "$RUNNER_TEMP/kit.zip" + unzip -q -o "$RUNNER_TEMP/kit.zip" -d "$RUNNER_TEMP/kit" + python3 -m pip install --quiet pyyaml + python3 "$RUNNER_TEMP/kit/ci.py" --out "$OUT" --docfx "$RUNNER_TEMP/docfx/docfx" - # metadata (the API reference from the managed projects), then build - - name: Build documentation - run: '"$RUNNER_TEMP/docfx/docfx" "${{ steps.site.outputs.config }}" --warningsAsErrors' + # The site is down or the build failed: publish the static files and a page that leads to the site. + # Self-contained on purpose (no kit): the installer and the schemas keep their addresses whatever happens. + - name: Fallback + if: steps.prometheus.outcome == 'failure' + run: | + echo "::warning title=Prometheus::The documentation was not built (is $PROMETHEUS_SITE up?); publishing the static files only" + mkdir -p "$OUT" && touch "$OUT/.nojekyll" + python3 - <<'PY' + import glob, html, json, os, re, shutil + out = os.environ["OUT"] + cfg = json.load(open("prometheus.json", encoding="utf-8-sig")) if os.path.isfile("prometheus.json") else {} + static = cfg.get("static") or next((a.get("docfx") if isinstance(a, dict) else a for a in cfg.get("api") or []), None) \ + or ("docfx.json" if os.path.isfile("docfx.json") else None) + for config in ([static] if isinstance(static, str) else static or []): + if not os.path.isfile(config): + continue + base = os.path.dirname(os.path.abspath(config)) + for r in json.load(open(config, encoding="utf-8-sig")).get("build", {}).get("resource", []): + src, dest = os.path.join(base, r.get("src", "")), os.path.join(out, r.get("dest", "")) + for pattern in r.get("files", []): + for f in glob.glob(os.path.join(src, pattern), recursive=True): + if os.path.isfile(f): + t = os.path.join(dest, os.path.relpath(f, src)) + os.makedirs(os.path.dirname(t), exist_ok=True) + shutil.copy2(f, t) + repo = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1] + project = os.environ.get("PROMETHEUS_PROJECT") or cfg.get("project") or re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-") + url = html.escape(f"{os.environ['PROMETHEUS_SITE'].rstrip('/')}/docs/{project}") + title = html.escape(os.environ.get("PROMETHEUS_TITLE") or cfg.get("title") or repo) + with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as f: + f.write(f'{title}' + f'' + f'

{title} documentation

') + PY - name: Upload Pages artifact if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' uses: actions/upload-pages-artifact@v5 with: - path: ${{ steps.site.outputs.output }} + path: ${{ env.OUT }} deploy: name: Deploy to GitHub Pages @@ -87,3 +137,13 @@ jobs: - name: Deploy id: deployment uses: actions/deploy-pages@v5 + + # The site would notice the new bundle on its next check anyway; this makes it immediate. + - name: Nudge the site + continue-on-error: true + env: + KEY: ${{ secrets.PROMETHEUS_SYNC_KEY }} + run: | + if [ -z "$KEY" ]; then echo "::notice::PROMETHEUS_SYNC_KEY is not set: the site picks the docs up on its next check"; exit 0; fi + sleep 30 # Pages needs a moment to serve the new files + curl -fsS -X POST -H "Authorization: Bearer $KEY" "$PROMETHEUS_SITE/api/v1/sync" diff --git a/.github/workflows/marks.yml b/.github/workflows/marks.yml new file mode 100644 index 0000000..aa54a8d --- /dev/null +++ b/.github/workflows/marks.yml @@ -0,0 +1,55 @@ +name: Marks + +# Marks in the comments of the code (Docs/Engine/Marks.md): one that stops a commit, or that nobody knows, does not +# get in. The hooks of git check the same on a machine; they can be skipped, this cannot. +# +# One workflow for every repository: the core runs it as it is, a module calls it. The kinds of marks and the command +# are those of the core, so a module is checked out into modules/ of a checkout of the core. + +on: + push: + branches: [develop, master] + pull_request: + workflow_call: + +permissions: + contents: read + +jobs: + marks: + name: Marks + if: vars.STELLAR_MIRROR != 'true' + runs-on: ubuntu-latest + env: + IS_CORE: ${{ github.event.repository.name == 'StellarEngine-Core' }} + steps: + - name: Checkout + if: env.IS_CORE == 'true' + uses: actions/checkout@v5 + + - name: Checkout the core + if: env.IS_CORE != 'true' + uses: actions/checkout@v5 + with: + repository: QuantumDevTeam/StellarEngine-Core + ref: develop + + - name: Checkout the module + if: env.IS_CORE != 'true' + uses: actions/checkout@v5 + with: + path: modules/${{ github.event.repository.name }} + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + global-json-file: global.json + + # A pull request into master is a release: what may lie in develop may not go there + - name: Check the marks + env: + STAGE: ${{ (github.base_ref == 'master' || github.ref == 'refs/heads/master') && 'release' || 'commit' }} + TARGET: ${{ github.event.repository.name == 'StellarEngine-Core' && '.' || format('modules/{0}', github.event.repository.name) }} + run: | + mkdir -p packages + dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check "$TARGET" --stage "$STAGE" diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml index 71a86a5..c9ffa9f 100644 --- a/.github/workflows/mirror.yml +++ b/.github/workflows/mirror.yml @@ -23,10 +23,18 @@ name: Mirror # The first snapshot comes from a machine: scripts/mirror.ps1 -Push. After that this workflow is the only writer: # on a machine, mirror.ps1 without -Push shows the next snapshot, Run workflow here publishes it. +# It never starts by itself on a timer: a release of the core sends 'orchestra-release' (release.yml), or a person +# presses Run workflow. Run workflow also takes a component the mirror does not hold yet. + on: + repository_dispatch: + types: [orchestra-release] workflow_dispatch: - schedule: - - cron: '17 3 * * *' + inputs: + add: + description: 'New components, e.g. modules/Stellar.LoggingSystem (comma separated). Empty: the ones of the mirror' + required: false + default: '' permissions: contents: write @@ -62,6 +70,8 @@ jobs: shell: pwsh env: COMPONENTS_TOKEN: ${{ secrets.STELLAR_MIRROR_TOKEN || github.token }} + # Through the environment, never pasted into the script + ADD: ${{ inputs.add }} run: | if (-not (Test-Path .orchestra)) { throw 'No .orchestra here: make the first snapshot on a machine with scripts/mirror.ps1 -Push' @@ -85,6 +95,13 @@ jobs: $workspace = Join-Path $env:RUNNER_TEMP 'orchestra' $components = @((Get-Content .orchestra -Raw | ConvertFrom-Json).Components) + # New components: a repository of the organization of the mirror, at its default branch + foreach ($entry in @("$env:ADD" -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })) { + if ($entry -cnotmatch '^(modules|tools)/([A-Za-z][A-Za-z0-9.-]*)$') { throw "Not modules/ or tools/: $entry" } + $area, $name = $Matches[1], $Matches[2] + if ($components | Where-Object { $_.Name -eq $name }) { throw "$name is in the mirror already" } + $components += [pscustomobject]@{ Name = $name; Area = $area; Repository = "https://github.com/${{ github.repository_owner }}/$name.git" } + } foreach ($component in $components) { if ("$($component.Repository)" -like 'https://github.com/*' -and ($component.Repository -replace '\.git$', '') -ne $mirrorRepository) { Set-Credentials $component.Repository $env:COMPONENTS_TOKEN @@ -108,6 +125,18 @@ jobs: "path=$workspace" >> $env:GITHUB_OUTPUT "keep=$($keep -join ',')" >> $env:GITHUB_OUTPUT + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + global-json-file: global.json + + # The core and every component of the snapshot, as it will be pushed + - name: Check the marks + working-directory: ${{ steps.workspace.outputs.path }} + run: | + mkdir -p packages + dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check --all --stage release + - name: Snapshot and push id: snapshot shell: pwsh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index af08d79..b9a9f5e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,9 +5,9 @@ name: Release # into the tag v and a GitHub release of the core. # # The orchestra is released by the mirror: its workflow tags the snapshot with the same version and publishes the -# release the installer installs. With the secret STELLAR_DISPATCH_TOKEN (a fine-grained token allowed to run the -# Actions of the mirror) this workflow starts it at once; without it the release of the orchestra waits for the -# nightly run of the mirror, or for Run workflow there. +# release the installer installs. With the variable STELLAR_MIRROR_APP_ID and the secret STELLAR_MIRROR_APP_KEY (the app +# that writes the mirror, see mirror.yml) this workflow starts it at once; without them the release of the orchestra +# waits for Run workflow in the mirror. Merge the modules into their master before the core: a snapshot takes it. # # The mirror holds this file too, as everything of the core: it never runs there (STELLAR_MIRROR is 'true'). @@ -34,6 +34,17 @@ jobs: with: fetch-depth: 0 + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + global-json-file: global.json + + # Nothing that a mark stops is released: a tag cannot be taken back + - name: Check the marks + run: | + mkdir -p packages + dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check --stage release + - name: Tag and publish id: release shell: pwsh @@ -77,14 +88,20 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "gh release create $tag failed" } "released=true" >> $env:GITHUB_OUTPUT + # Only a release starts the mirror. Without the app here, Run workflow in the mirror does it + - name: Token of the mirror app + id: app + if: steps.release.outputs.released == 'true' && vars.STELLAR_MIRROR_APP_ID != '' + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.STELLAR_MIRROR_APP_ID }} + private-key: ${{ secrets.STELLAR_MIRROR_APP_KEY }} + owner: ${{ github.repository_owner }} + repositories: StellarEngine-Mono + permission-contents: write + - name: Start the mirror - if: steps.release.outputs.released == 'true' + if: steps.app.outputs.token != '' env: - GH_TOKEN: ${{ secrets.STELLAR_DISPATCH_TOKEN }} - MIRROR: ${{ vars.STELLAR_MIRROR_REPOSITORY || 'QuantumDevTeam/StellarEngine-Mono' }} - run: | - if [ -z "$GH_TOKEN" ]; then - echo "::notice::No STELLAR_DISPATCH_TOKEN: the orchestra is released by the next run of the mirror ($MIRROR)" - exit 0 - fi - gh workflow run mirror.yml --repo "$MIRROR" --ref master + GH_TOKEN: ${{ steps.app.outputs.token }} + run: gh api "repos/${{ github.repository_owner }}/StellarEngine-Mono/dispatches" -f event_type=orchestra-release diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..c3f2d00 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,80 @@ +name: Tests + +# Builds everything, native and managed, and runs the tests. One workflow for every repository, as marks.yml: the core +# runs it as it is; a module calls it and is checked out into modules/ of a checkout of the core. +# +# Windows with the Visual Studio the native toolset asks for (Shared/Build/Stellar.Native.props), C++/CLI included. +# +# By itself only on the way into master; on any other branch by hand (Run workflow). + +on: + workflow_dispatch: + push: + branches: [master] + pull_request: + branches: [master] + workflow_call: + +permissions: + contents: read + +concurrency: + group: tests-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + tests: + name: Tests + if: vars.STELLAR_MIRROR != 'true' + runs-on: windows-2025-vs2026 + timeout-minutes: 45 + env: + IS_CORE: ${{ github.event.repository.name == 'StellarEngine-Core' }} + DOTNET_NOLOGO: 'true' + DOTNET_CLI_TELEMETRY_OPTOUT: 'true' + steps: + - name: Checkout + if: env.IS_CORE == 'true' + uses: actions/checkout@v5 + + - name: Checkout the core + if: env.IS_CORE != 'true' + uses: actions/checkout@v5 + with: + repository: QuantumDevTeam/StellarEngine-Core + ref: develop + + - name: Checkout the module + if: env.IS_CORE != 'true' + uses: actions/checkout@v5 + with: + path: modules/${{ github.event.repository.name }} + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + global-json-file: global.json + + - name: Build and test the core + if: env.IS_CORE == 'true' + shell: pwsh + run: | + New-Item -ItemType Directory -Force packages | Out-Null + ./scripts/build.ps1 -Configuration Debug + + # Its own tests ran in the repository of the core + - name: Install the core + if: env.IS_CORE != 'true' + shell: pwsh + run: | + New-Item -ItemType Directory -Force packages | Out-Null + ./scripts/build.ps1 -Configuration Debug -SkipTests -Install -NoUserRegistration -SkipModules + + - name: Build and test the module + if: env.IS_CORE != 'true' + shell: pwsh + env: + MODULE: ${{ github.event.repository.name }} + run: | + dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -c Debug --no-build -- modules build $env:MODULE --tests --pack + exit $LASTEXITCODE diff --git a/.gitignore b/.gitignore index 65937a5..33ae65d 100644 --- a/.gitignore +++ b/.gitignore @@ -16,8 +16,6 @@ /StellarEngine.*.slnf # The bare repository scripts/mirror.ps1 builds the snapshots of the orchestra in /.mirror/ -# The DocFX project of the orchestra site, generated by scripts/orchestra-site.ps1 -/docfx.orchestra.json # ---- Build output ---- [Bb]in/ diff --git a/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs b/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs index 0f4b62d..29ccf85 100644 --- a/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs +++ b/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs @@ -3,9 +3,7 @@ using Stellar.Core.Global; using Stellar.Core.Native; using Stellar.Core.Quantization; -using Stellar.Kernel; using Stellar.Kernel.Configuration; -using Stellar.Kernel.EntryPoint; using Stellar.Kernel.Lifecycle; using Stellar.Kernel.Services; using Stellar.Kernel.Threading; @@ -18,7 +16,7 @@ namespace Stellar.Core.Tests; /// public class EngineInstanceTests { - [Fact] + [NativeFact] public void TwoEngines_HaveTheirOwnServicesAndRegistries() { var editor = new FakeEngine("Editor"); @@ -57,7 +55,7 @@ public void Outside_AnyEngine_TheDefaultIsUsed() } } - [Fact] + [NativeFact] public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads() { var engine = new FakeEngine("Flowing"); @@ -67,7 +65,7 @@ public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads() await Task.Yield(); CoreEngine.Current.Instance.Should().BeSameAs(engine); - var seen = await Task.Run(() => CoreEngine.Current.Instance); + IEngineInstance? seen = await Task.Run(() => CoreEngine.Current.Instance); seen.Should().BeSameAs(engine); IEngineInstance? onThread = null; @@ -80,7 +78,7 @@ public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads() CoreEngine.Release(engine); } - [Fact] + [NativeFact] public void AQuant_LeavesTheRegistryOfTheEngineItWasMadeIn() { var first = new FakeEngine("First"); @@ -106,11 +104,11 @@ public void AQuant_LeavesTheRegistryOfTheEngineItWasMadeIn() CoreEngine.Release(second); } - [Fact] + [NativeFact] public void Releasing_AnEngine_DisposesItsNativeRegistries() { var engine = new FakeEngine("Short"); - var native = CoreEngine.For(engine).Native; + CoreContext native = CoreEngine.For(engine).Native; CoreEngine.Release(engine).Should().BeTrue(); @@ -119,7 +117,7 @@ public void Releasing_AnEngine_DisposesItsNativeRegistries() CoreEngine.Release(engine).Should().BeFalse(); } - [Fact] + [NativeFact] public void TheCoreModule_RunsForTheEngineOfItsContext() { var engine = new FakeEngine("Hosted"); @@ -155,6 +153,6 @@ private sealed class FakeEngine(string name) public IMainThreadDispatcher Dispatcher => throw new NotSupportedException(); - public IServiceCatalog? Services => CoreEngine.For(this).Services; + public IServiceCatalog Services => CoreEngine.For(this).Services; } } diff --git a/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs b/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs index 9e5c475..84bc331 100644 --- a/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs +++ b/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs @@ -26,11 +26,21 @@ private sealed class RecordingLogger : ILogger public Kernel.Data.Registry.IRegistrations Registrations => throw new NotSupportedException(); - public TMeta? FindMeta() where TMeta : class, IMetaQuant => null; + public TMeta? FindMeta() + where TMeta : class, IMetaQuant + { + return null; + } - public void Log(LogLevel level, string message) => Lines.Add((level, message)); + public void Log(LogLevel level, string message) + { + Lines.Add((level, message)); + } - public void LogWithoutFormat(string message) => Lines.Add((LogLevel.Info, message)); + public void LogWithoutFormat(string message) + { + Lines.Add((LogLevel.Info, message)); + } public void Start() { @@ -47,21 +57,28 @@ private sealed class RecordingControl : IEngineControl public Failure? Stopped { get; private set; } - public void RequestStop(StopReason reason, Failure? failure = null) => Stopped = failure; + public void RequestStop(StopReason reason, Failure? failure = null) + { + Stopped = failure; + } } private sealed class Recorder : IFailureHandler { public List Heard { get; } = []; - public void Handle(Failure failure) => Heard.Add(failure); + public void Handle(Failure failure) + { + Heard.Add(failure); + } } [Theory] [InlineData(FailureLevel.NonCritical, FailureReaction.None)] [InlineData(FailureLevel.Warning, FailureReaction.Log)] [InlineData(FailureLevel.Error, FailureReaction.Log | FailureReaction.StopExecution)] - [InlineData(FailureLevel.CriticalError, FailureReaction.Log | FailureReaction.StopExecution | FailureReaction.StopEngine)] + [InlineData(FailureLevel.CriticalError, + FailureReaction.Log | FailureReaction.StopExecution | FailureReaction.StopEngine)] public void Levels_HaveTheirReactionsByDefault(FailureLevel level, FailureReaction reaction) { new FailureSystem().ReactionTo(new Failure(FailureKind.Engine, level, "x")).Should().Be(reaction); @@ -130,8 +147,8 @@ public void AFailureThatLetsTheWorkGoOn_GivesTheFallback() { using var catcher = new Catcher(FailureKind.FileSystem, FailureLevel.Warning); - var save = catcher.Try(() => throw new IOException("no save"), fallback: "empty"); - var next = catcher.Run(() => { }); + string save = catcher.Try(() => throw new IOException("no save"), "empty"); + bool next = catcher.Run(() => { }); save.Should().Be("empty"); next.Should().BeTrue(); @@ -142,9 +159,9 @@ public void AFailureThatLetsTheWorkGoOn_GivesTheFallback() [Fact] public void AFailureThatStopsTheWork_IsThrownOn_AndTheWholeTryStops() { - var reached = false; + bool reached = false; - var block = () => + Action block = () => { using var catcher = new Catcher(FailureKind.FileSystem); catcher.Run(() => throw new IOException("disk gone")); @@ -158,8 +175,8 @@ public void AFailureThatStopsTheWork_IsThrownOn_AndTheWholeTryStops() [Fact] public void CatchBlocks_HandleTheirExceptions_AndAreNotReported() { - var firstRun = false; - using var catcher = new Catcher(FailureKind.FileSystem) + bool firstRun = false; + using Catcher catcher = new Catcher(FailureKind.FileSystem) .Catch(_ => firstRun = true) .Catch(FailureLevel.Warning); @@ -175,9 +192,9 @@ public void ErrorsOfTheEngine_KeepTheirFailure() { using var catcher = new Catcher(FailureKind.Application, FailureLevel.Warning); - var block = () => catcher.Run(() => throw new DomainNotFoundException("assets")); + Func block = () => catcher.Run(() => throw new DomainNotFoundException("assets")); - var thrown = block.Should().Throw().Which; + DomainNotFoundException thrown = block.Should().Throw().Which; thrown.Failure.Kind.Should().Be(FailureKind.FileSystem); catcher.Failures.Should().ContainSingle().Which.Should().BeSameAs(thrown.Failure); } @@ -192,7 +209,7 @@ public void AFailureCaughtAgain_KeepsItsFirstReaction() using var outer = new Catcher(system, FailureKind.Engine, FailureLevel.Warning); // A stop goes up through every catcher, as if none were there, until a plain try; it is reported once - var block = () => outer.Run(() => + Func block = () => outer.Run(() => { using var inner = new Catcher(system, FailureKind.Engine); inner.Run(() => throw new InvalidOperationException("deep")); @@ -209,7 +226,7 @@ public void ACatcherThatKeepsAFew_KeepsTheLastOnes_AndCountsThemAll() using var catcher = new Catcher(FailureKind.Engine, FailureLevel.Warning) { Keeps = 2 }; using var forgetful = new Catcher(FailureKind.Engine, FailureLevel.Warning) { Keeps = 0 }; - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { catcher.Report($"failure {i}"); forgetful.Report($"failure {i}"); @@ -219,7 +236,7 @@ public void ACatcherThatKeepsAFew_KeepsTheLastOnes_AndCountsThemAll() catcher.Failures.Select(failure => failure.Message).Should().Equal("failure 3", "failure 4"); forgetful.HasFailed.Should().BeTrue(); forgetful.Failures.Should().BeEmpty(); - var negative = () => new Catcher { Keeps = -1 }; + Func negative = () => new Catcher { Keeps = -1 }; negative.Should().Throw(); } @@ -228,7 +245,8 @@ public void Guard_NeverThrows_AndGivesTheFailure() { using var catcher = new Catcher(FailureKind.Engine, FailureLevel.CriticalError); - var failure = catcher.Guard(() => throw new InvalidOperationException("boom"), "the frame", phase: FramePhase.Update); + Failure? failure = catcher.Guard(() => throw new InvalidOperationException("boom"), "the frame", + phase: FramePhase.Update); failure.Should().NotBeNull(); failure!.Message.Should().Be("the frame: boom"); @@ -257,7 +275,8 @@ public void Cancellation_IsNotAFailure() { using var catcher = new Catcher(); - catcher.Invoking(c => c.Run(() => throw new OperationCanceledException())).Should().Throw(); + catcher.Invoking(c => c.Run(() => throw new OperationCanceledException())).Should() + .Throw(); catcher.HasFailed.Should().BeFalse(); } @@ -269,10 +288,11 @@ public void ThrowIfFailed_ThrowsTheWorst() catcher.Report(new InvalidOperationException("worse"), level: FailureLevel.NonCritical); catcher.Report("the worst", FailureLevel.Warning); - catcher.Invoking(c => c.ThrowIfFailed()).Should().Throw().WithMessage("a placeholder was used"); + catcher.Invoking(c => c.ThrowIfFailed()).Should().Throw() + .WithMessage("a placeholder was used"); } - [Fact] + [NativeFact] public void InAnEngine_TheCatcherReportsToItsSystem() { var engine = new ScopeEngine("Failing"); @@ -283,7 +303,9 @@ public void InAnEngine_TheCatcherReportsToItsSystem() using (EngineScope.Enter(engine)) using (var catcher = new Catcher(FailureKind.Engine, FailureLevel.Warning)) + { catcher.Run(() => throw new InvalidOperationException("in the engine")); + } recorder.Count.Should().Be(1); CoreEngine.Release(engine); @@ -293,7 +315,10 @@ private sealed class FailureSystemRecorder : IFailureHandler { public int Count { get; private set; } - public void Handle(Failure failure) => Count++; + public void Handle(Failure failure) + { + Count++; + } } } @@ -310,12 +335,12 @@ public void EntryPoint_IsQuantAndDisposable() [Fact] public void Constructor_WithNullConfiguration_Throws() { - var action = () => new EntryPoint(null!); + Func action = () => new EntryPoint(null!); action.Should().Throw(); } - [Fact] + [NativeFact] public void Run_PublishesTheFailureSystem_AndDisposeWithdrawsIt() { var engine = new ScopeEngine("Entry"); diff --git a/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs b/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs index 9f3cde8..76c69a7 100644 --- a/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs +++ b/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs @@ -1,7 +1,6 @@ using Stellar.Core.Data.Registry; using Stellar.Core.Global; using Stellar.Core.Quantization; -using Stellar.Kernel; using Stellar.Kernel.Data.Registry; using Stellar.Kernel.Lifecycle; using Stellar.Kernel.Quantization; @@ -31,7 +30,7 @@ private sealed class Prop() public void ADerivedQuant_IsInTheRegistryOfItsBase_AndFoundAsWhatItIs() { using var player = new Player(); - var actors = CoreEngine.Current.Registry.Of(); + IRegistry actors = CoreEngine.Current.Registry.Of(); actors.Get(player.UID).Should().BeSameAs(player); actors.Get(player.UID).Should().BeSameAs(player); @@ -49,7 +48,7 @@ public void AGetOfTheWrongType_IsNull_NotAGuess() public void MarkedTypes_HaveRegistriesOfTheirOwn() { using var player = new Player(); - var registries = CoreEngine.Current.Registry; + CoreEngine.CoreRegistries registries = CoreEngine.Current.Registry; registries.Of().Get(player.UID).Should().BeSameAs(player); registries.Of().Get(player.UID).Should().BeSameAs(player); @@ -60,9 +59,9 @@ public void MarkedTypes_HaveRegistriesOfTheirOwn() [Fact] public void KeysAndValues_FollowTheRegistry() { - var registry = CoreEngine.Current.Registry.Of(); + IRegistry registry = CoreEngine.Current.Registry.Of(); var first = new Crate(); - var values = registry.Values; + ICollection values = registry.Values; registry.Values.Should().BeSameAs(values); using var second = new Crate(); @@ -79,7 +78,7 @@ private sealed class Crate() public void Dispose_LeavesEveryRegistry() { var player = new Player(); - var registries = CoreEngine.Current.Registry; + CoreEngine.CoreRegistries registries = CoreEngine.Current.Registry; player.Dispose(); @@ -93,7 +92,7 @@ public void Dispose_LeavesEveryRegistry() public void AnyRegistry_CanTakeAnObject_AndTheObjectKnows() { using var prop = new Prop(); - var mine = new Registry(); + Registry mine = new(); prop.Registrations.Should().BeEmpty(); CoreEngine.Current.Registry.Of().Exists(prop.UID).Should().BeFalse(); @@ -110,7 +109,7 @@ public void AnyRegistry_CanTakeAnObject_AndTheObjectKnows() public void Dispose_LeavesARegistryMadeByHand() { var prop = new Prop(); - var mine = new Registry(); + Registry mine = new(); mine.Register(prop); prop.Dispose(); @@ -121,23 +120,31 @@ public void Dispose_LeavesARegistryMadeByHand() [Fact] public void ATypeWithoutRegistrableObjects_HasNoRegistry() { - FluentActions.Invoking(() => CoreEngine.Current.Registry.Of(typeof(string))).Should().Throw(); + FluentActions.Invoking(() => CoreEngine.Current.Registry.Of(typeof(string))).Should() + .Throw(); } - [Fact] + [NativeFact] public void RegistriesOfTwoEngines_AreApart() { var first = new ScopeEngine("First"); var second = new ScopeEngine("Second"); Actor actor; - using (EngineScope.Enter(first)) actor = new Actor(); + using (EngineScope.Enter(first)) + { + actor = new Actor(); + } CoreEngine.For(first).Registry.Of().Exists(actor.UID).Should().BeTrue(); CoreEngine.For(second).Registry.Of().Exists(actor.UID).Should().BeFalse(); // Disposed anywhere, it leaves the registries it is really in - using (EngineScope.Enter(second)) actor.Dispose(); + using (EngineScope.Enter(second)) + { + actor.Dispose(); + } + CoreEngine.For(first).Registry.Of().Exists(actor.UID).Should().BeFalse(); CoreEngine.Release(first); @@ -148,7 +155,7 @@ public void RegistriesOfTwoEngines_AreApart() [Collection(DetachedPolicyCollection.Name)] public class DetachedPolicyTests { - [Fact] + [NativeFact] public void Outside_AnyEngine_TheDefaultIsUsed_UnlessThePolicySaysOtherwise() { using (EngineScope.Enter(null)) @@ -156,14 +163,18 @@ public void Outside_AnyEngine_TheDefaultIsUsed_UnlessThePolicySaysOtherwise() EngineScope.Resolve().Should().BeNull(); CoreEngine.Current.Should().BeSameAs(CoreEngine.Default); - var previous = EngineScope.Detached; + DetachedPolicy previous = EngineScope.Detached; EngineScope.Detached = DetachedPolicy.Throw; try { FluentActions.Invoking(() => CoreEngine.Current).Should().Throw(); var engine = new ScopeEngine("Strict"); - using (EngineScope.Enter(engine)) CoreEngine.Current.Instance.Should().BeSameAs(engine); + using (EngineScope.Enter(engine)) + { + CoreEngine.Current.Instance.Should().BeSameAs(engine); + } + CoreEngine.Release(engine); } finally diff --git a/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs b/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs index c30694e..3d25f0b 100644 --- a/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs +++ b/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs @@ -1,12 +1,11 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using Stellar.Core.Data.Registry; -using Stellar.Core.Modules; -using Stellar.Core.Native; + using Stellar.Kernel; using Stellar.Kernel.Interop; using Stellar.Kernel.Versioning; +using Stellar.Core.Native; namespace Stellar.Core.Tests; @@ -17,7 +16,8 @@ internal static class Build { private static string Metadata(string key) { - return typeof(Build).Assembly.GetCustomAttributes() + return typeof(Build).Assembly + .GetCustomAttributes() .Single(attribute => attribute.Key == key).Value ?? string.Empty; } @@ -61,11 +61,14 @@ public class ContractTests [InlineData(1u, 1u, 1u, 2u, false)] [InlineData(2u, 0u, 1u, 0u, false)] [InlineData(1u, 0u, 2u, 0u, false)] - public void Satisfies_FollowsTheVersionRule(uint major, uint minor, uint requiredMajor, uint requiredMinor, - bool expected) + public void Satisfies_FollowsTheVersionRule( + uint major, uint minor, uint requiredMajor, uint requiredMinor, + bool expected + ) { - new ContractVersion(major, minor).Satisfies(new ContractVersion(requiredMajor, requiredMinor)).Should() - .Be(expected); + new ContractVersion(major, minor) + .Satisfies(new ContractVersion(requiredMajor, requiredMinor)) + .Should().Be(expected); } [Fact] @@ -85,7 +88,7 @@ public void Handle_WithZeroGeneration_IsInvalid() } /// -/// The behaviour every wrapper must have. The suite runs once per wrapper: -p:StellarNativeWrapper=.... +/// The behavior every wrapper must have. The suite runs once per wrapper: -p:StellarNativeWrapper=.... /// public class WrapperTests { @@ -99,14 +102,19 @@ public void Wrapper_IsTheOneTheSdkChose() public void Identifier_HasTheBytesOfTheNativeCore() { // The vector of the native tests: the same text gives the same 16 bytes on both sides - Identifier.Parse("00112233-4455-6677-8899-aabbccddeeff").ToBytes().Should().Equal( - 0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF); + Identifier.Parse("00112233-4455-6677-8899-aabbccddeeff").ToBytes() + .Should().Equal( + 0x33, 0x22, 0x11, 0x00, + 0x55, 0x44, + 0x77, 0x66, + 0x88, 0x99, + 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF); } [NativeFact] public void Failures_ComeBackAsExceptions() { - var load = () => CoreContext.Current.Modules.Load("no-such-module.dll"); + Func load = () => CoreContext.Current.Modules.Load("no-such-module.dll"); load.Should().Throw() .Where(exception => exception.Result == NativeResult.NotFound) @@ -117,9 +125,9 @@ public void Failures_ComeBackAsExceptions() public void StaleModuleHandle_IsRejected() { var stale = new NativeHandle(1000, 1); - var getName = () => CoreContext.Current.Modules.GetName(stale); - CoreContext.Current.Modules.Unload(stale).Should().BeFalse(); + + Func getName = () => CoreContext.Current.Modules.GetName(stale); getName.Should().Throw() .Where(exception => exception.Result == NativeResult.InvalidHandle); } @@ -137,39 +145,29 @@ public class WrapperParityTests internal static string ManagedPath => Path.Combine(Build.EngineCoreDir, "artifacts", "bin", "Stellar.Native.Core.Wrapper.Managed", Build.Configuration, "Stellar.Native.Core.Wrapper.Managed.dll"); - [BothWrappersFact] - public void Wrappers_DefineTheSameApi() - { - var cli = Surface(CliPath); - var managed = Surface(ManagedPath); - - cli.Except(managed).Should().BeEmpty("the C++/CLI wrapper must not have what the Managed one lacks"); - managed.Except(cli).Should().BeEmpty("the Managed wrapper must not have what the C++/CLI one lacks"); - } - private static SortedSet Surface(string path) { - var runtime = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll"); - var kernel = typeof(NativeHandle).Assembly.Location; + string[] runtime = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll"); + string kernel = typeof(NativeHandle).Assembly.Location; var resolver = new PathAssemblyResolver(runtime.Append(kernel).Append(path)); using var context = new MetadataLoadContext(resolver); - var assembly = context.LoadFromAssemblyPath(path); - var surface = new SortedSet(StringComparer.Ordinal); + Assembly assembly = context.LoadFromAssemblyPath(path); + SortedSet surface = new(StringComparer.Ordinal); const BindingFlags members = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; - foreach (var type in assembly.GetExportedTypes()) + foreach (Type type in assembly.GetExportedTypes()) { surface.Add($"type {type.FullName}"); - foreach (var member in type.GetMembers(members)) + foreach (MemberInfo member in type.GetMembers(members)) { - var signature = member switch + string? signature = member switch { - MethodBase { IsSpecialName: true } method when !method.IsConstructor && - !method.Name.StartsWith("op_") => null, + MethodBase { IsSpecialName: true, IsConstructor: false } method + when !method.Name.StartsWith("op_") => null, MethodBase method => $"{Name(method)}({string.Join(", ", method.GetParameters().Select(Parameter))})" + (method is MethodInfo info ? $" : {TypeName(info.ReturnType)}" : string.Empty), @@ -211,4 +209,14 @@ static string Parameter(ParameterInfo parameter) $"{TypeName(parameter.ParameterType)} {parameter.Name}{(parameter.IsOptional ? " = optional" : string.Empty)}"; } } + + [BothWrappersFact] + public void Wrappers_DefineTheSameApi() + { + SortedSet cli = Surface(CliPath); + SortedSet managed = Surface(ManagedPath); + + cli.Except(managed).Should().BeEmpty("the C++/CLI wrapper must not have what the Managed one lacks"); + managed.Except(cli).Should().BeEmpty("the Managed wrapper must not have what the C++/CLI one lacks"); + } } diff --git a/Docs/Architecture/NativeAbi.md b/Docs/Architecture/NativeAbi.md index 3cae2f5..3cd5611 100644 --- a/Docs/Architecture/NativeAbi.md +++ b/Docs/Architecture/NativeAbi.md @@ -230,7 +230,7 @@ The native core follows the handle and umbrella rules of the Kernel: ``` A native project of a module gets the include directories, `STELLAR_KERNEL_STATIC` and the import libraries from -`Shared/Build/Stellar.Native.Module.props` (see [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html)); the toolchain itself comes from +`Shared/Build/Stellar.Native.Module.props` (see [Modules](../Engine/Modules.md)); the toolchain itself comes from `Shared/Build/Stellar.Native.props`, shared with the core. Inside a module, paths start at the root of the module. Headers of the C++/CLI wrapper end with `.cli.h`: MSVC also searches the folders of the open includes, and a wrapper diff --git a/Docs/Architecture/Runtime.md b/Docs/Architecture/Runtime.md index 2f03918..4bc17b4 100644 --- a/Docs/Architecture/Runtime.md +++ b/Docs/Architecture/Runtime.md @@ -271,7 +271,7 @@ wins: | `ModuleInitializationParallelism` | `1` | How many modules of one level start at once | | `Verbose` | `false` | The runtime tells every step on the error output | -Settings the runtime does not know stay in `RuntimeConfiguration.Settings` for the modules. +Modules find all of them in `RuntimeConfiguration.Settings`, the command line included, by names in any case. ## Exit codes diff --git a/Docs/Architecture/Sdk.md b/Docs/Architecture/Sdk.md index 537af99..eb60aac 100644 --- a/Docs/Architecture/Sdk.md +++ b/Docs/Architecture/Sdk.md @@ -26,14 +26,14 @@ them, but Rider shows an item written in a project file as a file of the project The SDK version is pinned once, in `global.json`, not in every project: ```json -{ "msbuild-sdks": { "Stellar.Sdk": "0.4.1" } } +{ "msbuild-sdks": { "Stellar.Sdk": "0.4.2" } } ``` The SDK itself comes from the local feed through `NuGet.config`. `stellar project new` and `stellar modules new` generate both files; a project under the root of the installation also finds the `NuGet.config` of the root. A module project needs even less: it is nearly empty, and the SDK takes its kind, version and dependencies from its -descriptor. See [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html). Every property: [Sdk.Properties](../Reference/Sdk.Properties.md). +descriptor. See [Modules](../Engine/Modules.md). Every property: [Sdk.Properties](../Reference/Sdk.Properties.md). ## Kinds of projects @@ -136,7 +136,7 @@ NuGet cache: the next restore of a game takes the new ones. | Target | Task | Result | Switch (`=false`) | |---|---|---|---| | `StellarResolveProject` | `ResolveStellarProject` | Parses `.stellar.project`, selects assets | `StellarEnableAssets` for the assets | -| `StellarCompileResources` | `CompileStellarResources` | `resources/**/*.sres` in the output | `StellarEnableResourceCompilation` | +| `StellarCompileResources` | `CompileStellarResources` | `Resources/**/*.sres` in the output | `StellarEnableResourceCompilation` | | `StellarGenerateRuntimeConfiguration` | `GenerateRuntimeConfiguration` | `{Project}.stellar.runtime.config.json` | `StellarEnableRuntimeConfiguration` | | `StellarGenerateLauncher` | `GenerateStellarLauncher` | The `Main` of an executable module | `StellarEnableLauncher` | diff --git a/Docs/Architecture/Tools.md b/Docs/Architecture/Tools.md index 9dd801d..6643782 100644 --- a/Docs/Architecture/Tools.md +++ b/Docs/Architecture/Tools.md @@ -83,7 +83,7 @@ Later additions win, and anything no compiler claims is packed as is by `RawReso | `stellar uninstall [path]` | Remove an installation: unregister it, drop its packages from the NuGet cache, remove what the installer made; `--all`, `--artifacts`, `--dry-run` | | `stellar modules list` | Show the manifest in load order | | `stellar modules sync` | Find the modules, apply the manifest, check the rules, regenerate the catalog | -| `stellar modules new`, `templates`, `add`, `enable`, `disable`, `reset`, `build` | See [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html) | +| `stellar modules new`, `templates`, `add`, `enable`, `disable`, `reset`, `build` | See [Modules](../Engine/Modules.md) | | `stellar solution sync [directory]` | Write the `.sln` again: the projects of the solution, the engine when `"Engine"` is `Sources` | | `stellar run [target]` | Build and run a game or a tool of the solution, or several at once; see [`.stellar.solution`](../Formats/SolutionFile.md) | | `stellar project new