From b928b18a74b07cb9385b9fe001499e51c8bd4248 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 13:03:45 -0500 Subject: [PATCH 1/3] feat(metrics): add metrics capture and verification Add Compono.Metrics, a reflection-free System.Diagnostics.Metrics testing package. UseMetrics() composes IMeterFactory as a CapturingMeterFactory; tests read typed measurements and assert on them with GetMeasurements/Verify, WithValue/WithTag/WithoutTag/Matching, and Once/Never/Exactly/AtLeast/AtMost. Capture is scope-isolated per factory via one lazy MeterListener with no static state, observable instruments are polled only on explicit RecordObservableInstruments(), and disposal stays test-owned. Ships RESEARCH-0039, ADR-0072 (with dated amendments), PLAN-0074, the package, tests across net8.0-net11.0, a Native AOT smoke test, documentation/API reference, the Compono skill entry and evals, a BasicUsage sample, and CI/packaging wiring. Zero third-party dependency beyond core Compono. Refs #165, #161. --- .github/scripts/generate-api-reference.sh | 2 +- .github/scripts/inspect-packed-nupkgs.sh | 9 +- .github/workflows/aot-validation.yaml | 37 +- .github/workflows/docs.yml | 4 +- .github/workflows/package-validation.yaml | 4 +- .gitignore | 4 + Compono.slnx | 2 + Directory.Packages.props | 7 + README.md | 1 + ...compono-metrics-testing-support-package.md | 724 ++++++++++++++++++ docs/adr/README.md | 1 + .../architecture/current/provider-pipeline.md | 4 +- docs/getting-started/installation.md | 1 + docs/how-to/verify-metrics-across-a-host.md | 108 +++ docs/index.md | 1 + docs/packages/compono-metrics.md | 404 ++++++++++ docs/packages/index.md | 5 +- ...mpono-metrics-testing-support-impl-plan.md | 380 +++++++++ docs/plans/README.md | 3 +- ...trics.CapturedMeasurement_T_.Instrument.md | 18 + ...ono.Metrics.CapturedMeasurement_T_.Tags.md | 16 + ...no.Metrics.CapturedMeasurement_T_.Value.md | 14 + .../Compono.Metrics.CapturedMeasurement_T_.md | 31 + ...ingMeterFactory.CapturingMeterFactory().md | 11 + ...ystem.Diagnostics.Metrics.MeterOptions).md | 36 + ...Metrics.CapturingMeterFactory.Dispose().md | 15 + .../Compono.Metrics.CapturingMeterFactory.md | 44 ++ ...Metrics(thisCompono.CompositionBuilder).md | 36 + ...no.Metrics.CompositionBuilderExtensions.md | 16 + ...mentVerificationBuilder_T_.AtLeast(int).md | 21 + ...ementVerificationBuilder_T_.AtMost(int).md | 21 + ...mentVerificationBuilder_T_.Exactly(int).md | 21 + ...o.Metrics.CapturedMeasurement_T_,bool_).md | 25 + ...asurementVerificationBuilder_T_.Never().md | 15 + ...easurementVerificationBuilder_T_.Once().md | 15 + ...cationBuilder_T_.WithTag(string,object).md | 30 + ...mentVerificationBuilder_T_.WithValue(T).md | 20 + ...rificationBuilder_T_.WithoutTag(string).md | 23 + ...trics.MeasurementVerificationBuilder_T_.md | 37 + ...stem.Diagnostics.Metrics.IMeterFactory).md | 24 + ...actoryTestingExtensions.GetMeasurements.md | 108 +++ ...stem.Diagnostics.Metrics.IMeterFactory).md | 27 + ...cs.MeterFactoryTestingExtensions.Verify.md | 111 +++ ...o.Metrics.MeterFactoryTestingExtensions.md | 28 + .../api/Compono.Metrics/Compono.Metrics.md | 14 + docs/reference/api/Compono.Metrics/index.md | 7 + docs/reference/index.md | 3 +- ...039-issue-165-metrics-testing-admission.md | 142 ++++ docs/samples/basic-usage.md | 6 +- docs/samples/index.md | 2 +- docs/troubleshooting/common-errors.md | 68 ++ mkdocs.yml | 3 + .../Compono.Samples.BasicUsage.csproj | 1 + samples/Compono.Samples.BasicUsage/Domain.cs | 32 + .../MetricsSampleProfile.cs | 11 + .../MetricsTests.cs | 28 + skills/compono/SKILL.md | 27 +- skills/compono/evals/evals.json | 39 + skills/compono/references/metrics.md | 226 ++++++ src/Compono.Metrics/CaptureState.cs | 218 ++++++ src/Compono.Metrics/CapturedMeasurement{T}.cs | 47 ++ src/Compono.Metrics/CapturingMeterFactory.cs | 275 +++++++ src/Compono.Metrics/Compono.Metrics.csproj | 43 ++ .../CompositionBuilderExtensions.cs | 30 + src/Compono.Metrics/IMeasurementBuffer.cs | 35 + src/Compono.Metrics/InstrumentValueTypes.cs | 50 ++ .../MeasurementVerificationBuilder{T}.cs | 238 ++++++ .../MeterFactoryTestingExtensions.cs | 167 ++++ src/Compono.Metrics/MetricsProvider.cs | 21 + src/Compono.Metrics/SelectionResult.cs | 43 ++ src/Compono.Metrics/StoredMeasurement.cs | 25 + src/Compono.Metrics/TypedCapture.cs | 70 ++ .../Compono.Metrics.AotSmokeTest.csproj | 53 ++ test/Compono.Metrics.AotSmokeTest/Program.cs | 165 ++++ .../Compono.Metrics.AotSmokeTest/nuget.config | 10 + .../pack-compono.sh | 28 + .../verify-packaging.sh | 108 +++ .../CapturingMeterFactoryTests.cs | 246 ++++++ .../Compono.Metrics.Tests.csproj | 48 ++ .../Compono.Metrics.Tests/CompositionTests.cs | 84 ++ .../CultureInvarianceTests.cs | 35 + .../GaugeCaptureTests.cs | 57 ++ test/Compono.Metrics.Tests/HostRecipeTests.cs | 95 +++ .../InstrumentCaptureTests.cs | 105 +++ .../IsolationAndConcurrencyTests.cs | 110 +++ test/Compono.Metrics.Tests/MisuseTests.cs | 52 ++ .../ObservableInstrumentTests.cs | 133 ++++ test/Compono.Metrics.Tests/SelectionTests.cs | 174 +++++ .../SnapshotAndDisposalTests.cs | 157 ++++ test/Compono.Metrics.Tests/TestFixtures.cs | 53 ++ .../VerificationBuilderTests.cs | 164 ++++ test/Compono.Metrics.Tests/xunit.runner.json | 3 + 92 files changed, 6180 insertions(+), 35 deletions(-) create mode 100644 docs/adr/0072-compono-metrics-testing-support-package.md create mode 100644 docs/how-to/verify-metrics-across-a-host.md create mode 100644 docs/packages/compono-metrics.md create mode 100644 docs/plans/0074-compono-metrics-testing-support-impl-plan.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Instrument.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Tags.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Value.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.CapturingMeterFactory().md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.Verify.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.md create mode 100644 docs/reference/api/Compono.Metrics/Compono.Metrics.md create mode 100644 docs/reference/api/Compono.Metrics/index.md create mode 100644 docs/research/0039-issue-165-metrics-testing-admission.md create mode 100644 samples/Compono.Samples.BasicUsage/MetricsSampleProfile.cs create mode 100644 samples/Compono.Samples.BasicUsage/MetricsTests.cs create mode 100644 skills/compono/references/metrics.md create mode 100644 src/Compono.Metrics/CaptureState.cs create mode 100644 src/Compono.Metrics/CapturedMeasurement{T}.cs create mode 100644 src/Compono.Metrics/CapturingMeterFactory.cs create mode 100644 src/Compono.Metrics/Compono.Metrics.csproj create mode 100644 src/Compono.Metrics/CompositionBuilderExtensions.cs create mode 100644 src/Compono.Metrics/IMeasurementBuffer.cs create mode 100644 src/Compono.Metrics/InstrumentValueTypes.cs create mode 100644 src/Compono.Metrics/MeasurementVerificationBuilder{T}.cs create mode 100644 src/Compono.Metrics/MeterFactoryTestingExtensions.cs create mode 100644 src/Compono.Metrics/MetricsProvider.cs create mode 100644 src/Compono.Metrics/SelectionResult.cs create mode 100644 src/Compono.Metrics/StoredMeasurement.cs create mode 100644 src/Compono.Metrics/TypedCapture.cs create mode 100644 test/Compono.Metrics.AotSmokeTest/Compono.Metrics.AotSmokeTest.csproj create mode 100644 test/Compono.Metrics.AotSmokeTest/Program.cs create mode 100644 test/Compono.Metrics.AotSmokeTest/nuget.config create mode 100755 test/Compono.Metrics.AotSmokeTest/pack-compono.sh create mode 100755 test/Compono.Metrics.AotSmokeTest/verify-packaging.sh create mode 100644 test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs create mode 100644 test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj create mode 100644 test/Compono.Metrics.Tests/CompositionTests.cs create mode 100644 test/Compono.Metrics.Tests/CultureInvarianceTests.cs create mode 100644 test/Compono.Metrics.Tests/GaugeCaptureTests.cs create mode 100644 test/Compono.Metrics.Tests/HostRecipeTests.cs create mode 100644 test/Compono.Metrics.Tests/InstrumentCaptureTests.cs create mode 100644 test/Compono.Metrics.Tests/IsolationAndConcurrencyTests.cs create mode 100644 test/Compono.Metrics.Tests/MisuseTests.cs create mode 100644 test/Compono.Metrics.Tests/ObservableInstrumentTests.cs create mode 100644 test/Compono.Metrics.Tests/SelectionTests.cs create mode 100644 test/Compono.Metrics.Tests/SnapshotAndDisposalTests.cs create mode 100644 test/Compono.Metrics.Tests/TestFixtures.cs create mode 100644 test/Compono.Metrics.Tests/VerificationBuilderTests.cs create mode 100644 test/Compono.Metrics.Tests/xunit.runner.json diff --git a/.github/scripts/generate-api-reference.sh b/.github/scripts/generate-api-reference.sh index d0b035b6..111a3a6f 100755 --- a/.github/scripts/generate-api-reference.sh +++ b/.github/scripts/generate-api-reference.sh @@ -24,7 +24,7 @@ cd "$repo_root" # it doesn't recognize as a BCL type and links to a learn.microsoft.com URL # that 404s for a Compono type - caught during the Phase 1 tool bake-off. core_pkg=Compono -integration_pkgs=(Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.MSTest Compono.NUnit) +integration_pkgs=(Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.Metrics Compono.MSTest Compono.NUnit) links_dir=$(mktemp -d) trap 'rm -rf "$links_dir"' EXIT diff --git a/.github/scripts/inspect-packed-nupkgs.sh b/.github/scripts/inspect-packed-nupkgs.sh index cc3a7a1d..a4eeebef 100755 --- a/.github/scripts/inspect-packed-nupkgs.sh +++ b/.github/scripts/inspect-packed-nupkgs.sh @@ -245,7 +245,7 @@ main() { } local pkg nupkg extract_dir extra_paths nuspec - for pkg in Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.MSTest Compono.NUnit Compono.Options; do + for pkg in Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.Metrics Compono.MSTest Compono.NUnit Compono.Options; do nupkg=$(find "$pack_output" -maxdepth 1 -iname "${pkg}.[0-9]*.nupkg" | head -1) if [ -z "$nupkg" ]; then echo "FAIL: no .nupkg found for $pkg in $pack_output" >&2 @@ -342,6 +342,13 @@ main() { assert_exact_pin_dependency "$nuspec" "$pkg" "Compono" assert_dependency_range_per_tfm "$nuspec" "$pkg" "Microsoft.Extensions.Logging.Abstractions" "$packages_props" ;; + Compono.Metrics) + assert_manifest_field "$nuspec" "$pkg" "title" "Compono โ€” System.Diagnostics.Metrics Testing Support" + assert_exact_pin_dependency "$nuspec" "$pkg" "Compono" + # No third-party or package dependency of its own: CapturingMeterFactory rides the + # in-box System.Diagnostics.Metrics shared-framework types on every target TFM - nothing + # else to range-assert here (ADR-0072 "Package identity and dependency graph"). + ;; Compono.MSTest) assert_manifest_field "$nuspec" "$pkg" "title" "Compono โ€” MSTest Integration" assert_exact_pin_dependency "$nuspec" "$pkg" "Compono" diff --git a/.github/workflows/aot-validation.yaml b/.github/workflows/aot-validation.yaml index 080e7331..956df5cd 100644 --- a/.github/workflows/aot-validation.yaml +++ b/.github/workflows/aot-validation.yaml @@ -1,14 +1,14 @@ name: AOT Validation -# ADR-0041 Amendment 7: permanent, CI-blocking Native AOT smoke gate for the nine existing +# ADR-0041 Amendment 7: permanent, CI-blocking Native AOT smoke gate for the ten existing # test/*.AotSmokeTest projects, replacing the previous manual-only "run it by hand before release" -# verification. +# verification. (Compono.Metrics joined the matrix via ADR-0072/PLAN-0074's own B4 phase.) # # Deliberately NO `paths:` filter on this workflow's own `pull_request` trigger. A workflow entirely # skipped by trigger-level path filtering leaves its required status check `Pending` rather than # reporting success, under GitHub's required-check semantics - that would block a PR indefinitely # instead of passing it on an AOT-irrelevant change. Selectivity happens *inside* the workflow -# instead: the `changes` job below computes which of the nine legs are actually applicable from the +# instead: the `changes` job below computes which of the ten legs are actually applicable from the # PR's changed files (a small repository-owned `git diff` script, not a third-party changed-files # action), each leg's own publish-and-run job runs behind an `if:` reading that output (an # inapplicable leg reports an ordinary skipped conclusion, never a missing status), and `aot-gate` - @@ -16,22 +16,22 @@ name: AOT Validation # (`if: always()`) and always resolves to success or failure, so the required check never sits # Pending. # -# The exact guarantee the nine aot-smoke legs prove: the packaged Compono package's exercised public +# The exact guarantee the ten aot-smoke legs prove: the packaged Compono package's exercised public # API surface is callable from a Native-AOT-published, trimmed consumer application without runtime # AOT/trimming failures. This is deliberately narrower than "the package's public API surface": it # covers core `Compono` itself, not only integration packages, and it makes no claim of exhaustive # coverage of every public member - each leg is a throwaway console app calling a specific, real -# entry point of the packaged API directly. Those nine legs make NO claim that xUnit v3, TUnit, +# entry point of the packaged API directly. Those ten legs make NO claim that xUnit v3, TUnit, # MSTest, or NUnit's own test runners are Native-AOT compatible - no leg ever publishes a test # framework's runner/host as Native AOT. # -# The tenth leg, aot-xunitv3-aot-pipeline (ADR-0066/PLAN-0066), is the one exception to that last +# The eleventh leg, aot-xunitv3-aot-pipeline (ADR-0066/PLAN-0066), is the one exception to that last # sentence: it publishes a real Compono.XunitV3.Aot-consuming xUnit v3 test project - real # [Theory]+[Compose], real Compono.Generators-emitted RegisteredEngineConfig.RegisterTheoryDataRowFactory # registration, real xunit.v3.aot.mtp-v2 - and proves xUnit v3's own AOT discovery/execution pipeline # actually discovers and runs a Compono-composed test under Native AOT. This claim is scoped to # xUnit v3 (Phase 1's plain [Compose] only) specifically - it says nothing about TUnit/MSTest/NUnit's -# own runners, which remain covered only by the nine aot-smoke legs' narrower guarantee above. +# own runners, which remain covered only by the ten aot-smoke legs' narrower guarantee above. # # This repository does not use GitHub merge queues today - no `merge_group` trigger is added # speculatively; add one later only if that changes. @@ -65,13 +65,13 @@ jobs: echo "Changed files:" echo "$changed" - all_legs='["Compono","Compono.Http","Compono.Logging","Compono.MSTest","Compono.NUnit","Compono.Options","Compono.TestDoubles","Compono.TUnit","Compono.XunitV3"]' + all_legs='["Compono","Compono.Http","Compono.Logging","Compono.Metrics","Compono.MSTest","Compono.NUnit","Compono.Options","Compono.TestDoubles","Compono.TUnit","Compono.XunitV3"]' # A change to shared/core/generator infrastructure (or to this workflow itself) can affect - # every packaged leg at once - run all nine rather than reflexively narrowing to only the + # every packaged leg at once - run all ten rather than reflexively narrowing to only the # paths that happened to change (ADR-0041 Amendment 7's own "do not run it reflexively, but # do not under-run it either" balance). - # ADR-0066/PLAN-0066: the tenth leg (Compono.XunitV3.Aot's own real-generator, real-xUnit-AOT- + # ADR-0066/PLAN-0066: the eleventh leg (Compono.XunitV3.Aot's own real-generator, real-xUnit-AOT- # pipeline proof) shares this same core/generator/shared-config trigger, plus its own # dedicated paths, computed separately below since it runs as its own job # (aot-xunitv3-aot-pipeline), not part of the aot-smoke matrix - it needs a materially @@ -89,7 +89,7 @@ jobs: fi if [ "$core_or_shared_change" = "true" ]; then - echo "Core/generator/shared-config change detected - running all nine AotSmokeTest legs." + echo "Core/generator/shared-config change detected - running all ten AotSmokeTest legs." echo "legs=$all_legs" >> "$GITHUB_OUTPUT" exit 0 fi @@ -101,6 +101,7 @@ jobs: echo "$changed" | grep -q '^src/Compono\.Http/' && add_leg "Compono.Http" echo "$changed" | grep -q '^src/Compono\.Logging/' && add_leg "Compono.Logging" + echo "$changed" | grep -q '^src/Compono\.Metrics/' && add_leg "Compono.Metrics" echo "$changed" | grep -q '^src/Compono\.MSTest/' && add_leg "Compono.MSTest" echo "$changed" | grep -q '^src/Compono\.NUnit/' && add_leg "Compono.NUnit" echo "$changed" | grep -q '^src/Compono\.Options/' && add_leg "Compono.Options" @@ -110,7 +111,7 @@ jobs: echo "$changed" | grep -q '^src/Shared/Compono\.XunitV3/' && add_leg "Compono.XunitV3" # A change scoped to one leg's own AotSmokeTest project only needs that leg re-run, not all - # nine - extract which leg(s) directly from the changed paths. + # ten - extract which leg(s) directly from the changed paths. for proj in $(echo "$changed" | grep -oE '^test/[^/]+\.AotSmokeTest/' | sed -E 's#^test/(.+)\.AotSmokeTest/#\1#' | sort -u); do add_leg "$proj" done @@ -161,15 +162,19 @@ jobs: if: matrix.leg == 'Compono.Logging' run: bash test/Compono.Logging.AotSmokeTest/verify-packaging.sh + - name: Additional packaging verification (Compono.Metrics) + if: matrix.leg == 'Compono.Metrics' + run: bash test/Compono.Metrics.AotSmokeTest/verify-packaging.sh + - name: Additional analyzer-contract verification (Compono.Http) if: matrix.leg == 'Compono.Http' run: bash test/Compono.Http.AotSmokeTest/AnalyzerContract/verify-analyzer-contract.sh - # ADR-0066/PLAN-0066's tenth leg - critically different from the aot-smoke matrix above: this + # ADR-0066/PLAN-0066's eleventh leg - critically different from the aot-smoke matrix above: this # publishes a REAL Compono.XunitV3.Aot-consuming xUnit v3 test project (real [Theory]+[Compose], # real Compono.Generators-emitted RegisteredEngineConfig.RegisterTheoryDataRowFactory registration, # real xunit.v3.aot.mtp-v2), not a hand-dispatch console app - it proves xUnit's own AOT - # discovery/execution pipeline actually runs a Compono-composed test, which none of the nine + # discovery/execution pipeline actually runs a Compono-composed test, which none of the ten # aot-smoke legs attempt (ADR-0041 Amendment 7's own stated scope boundary). aot-xunitv3-aot-pipeline: needs: changes @@ -247,8 +252,8 @@ jobs: exit 1 fi - # Same fail-closed shape for the tenth leg (ADR-0066/PLAN-0066), gated on its own - # xunitv3_aot_applicable output rather than the nine-leg legs array. + # Same fail-closed shape for the eleventh leg (ADR-0066/PLAN-0066), gated on its own + # xunitv3_aot_applicable output rather than the ten-leg legs array. if [ "$xunitv3_aot_result" = "failure" ] || [ "$xunitv3_aot_result" = "cancelled" ]; then echo "::error::The Compono.XunitV3.Aot real-pipeline leg failed or was cancelled - see the aot-xunitv3-aot-pipeline job above." >&2 exit 1 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3a7298c6..2feaa977 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -26,6 +26,7 @@ on: - 'src/Compono.DependencyInjection/**' - 'src/Compono.Http/**' - 'src/Compono.Logging/**' + - 'src/Compono.Metrics/**' - 'src/Compono.MSTest/**' - 'src/Compono.NUnit/**' - 'Directory.Build.props' @@ -52,6 +53,7 @@ on: - 'src/Compono.DependencyInjection/**' - 'src/Compono.Http/**' - 'src/Compono.Logging/**' + - 'src/Compono.Metrics/**' - 'src/Compono.MSTest/**' - 'src/Compono.NUnit/**' - 'Directory.Build.props' @@ -97,7 +99,7 @@ jobs: - name: Build publishable packages (net10.0) run: | set -euo pipefail - for pkg in Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.MSTest Compono.NUnit; do + for pkg in Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.Metrics Compono.MSTest Compono.NUnit; do dotnet build "src/${pkg}/${pkg}.csproj" -c Release -f net10.0 done diff --git a/.github/workflows/package-validation.yaml b/.github/workflows/package-validation.yaml index 3c8fff34..f088bc6e 100644 --- a/.github/workflows/package-validation.yaml +++ b/.github/workflows/package-validation.yaml @@ -32,12 +32,12 @@ jobs: PACK_OUTPUT: ${{ github.workspace }}/artifacts/package-validation # Single authoritative publishable-package list (PLAN-0061 Phase 1) - the baseline-lookup and # pack steps below both derive from this one job-level env var instead of each repeating the - # same 11-package literal, so adding/removing a package can't drift across the two + # same 14-package literal, so adding/removing a package can't drift across the two # independently. A job-level `env:` entry is injected into every step's own # process environment by GitHub Actions itself, so this survives across the separate `run:` # steps below (each its own shell process) with no extra plumbing - deliberately not a Bash # array, which would only live for the one step that declared it. - PACKAGES: "Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.MSTest Compono.NUnit Compono.Options" + PACKAGES: "Compono Compono.XunitV3 Compono.XunitV3.Aot Compono.NSubstitute Compono.Bogus Compono.TUnit Compono.TestDoubles Compono.DependencyInjection Compono.Http Compono.Logging Compono.Metrics Compono.MSTest Compono.NUnit Compono.Options" steps: - uses: actions/checkout@v7 diff --git a/.gitignore b/.gitignore index d1f24c9f..0207b397 100644 --- a/.gitignore +++ b/.gitignore @@ -481,6 +481,10 @@ FodyWeavers.xsd # 10's Native AOT publish-and-run proof) - regenerated by that script, never committed. .local-nuget-feed-nunit-aot-smoke/ +# Local NuGet feed populated by Compono.Metrics.AotSmokeTest's pack-compono.sh (ADR-0072 / PLAN-0074 +# B4's Native AOT publish-and-run proof) - regenerated by that script, never committed. +.local-nuget-feed-metrics-aot-smoke/ + # Raw per-run outputs from skills/compono-workspace/ eval iterations - transient, regenerated by # each run. grading.json/timing.json/benchmark.json/feedback.json ARE committed (this repo's own # established evaluation-evidence convention, see skills/compono-workspace/benchmarks/), only the diff --git a/Compono.slnx b/Compono.slnx index 5aba1923..574e73fc 100644 --- a/Compono.slnx +++ b/Compono.slnx @@ -11,6 +11,7 @@ + @@ -27,6 +28,7 @@ + diff --git a/Directory.Packages.props b/Directory.Packages.props index be46b98e..7033fdb8 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -193,6 +193,13 @@ + + diff --git a/README.md b/README.md index 090afba9..30ffc60a 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ Compono determines **how** those requirements are satisfied. | `Compono.MSTest` | MSTest integration | [![NuGet](https://img.shields.io/nuget/v/Compono.MSTest.svg)](https://www.nuget.org/packages/Compono.MSTest) | [![NuGet Downloads](https://img.shields.io/nuget/dt/Compono.MSTest.svg)](https://www.nuget.org/packages/Compono.MSTest) | | `Compono.NUnit` | NUnit integration (no `[TestFixture]` required) | [![NuGet](https://img.shields.io/nuget/v/Compono.NUnit.svg)](https://www.nuget.org/packages/Compono.NUnit) | [![NuGet Downloads](https://img.shields.io/nuget/dt/Compono.NUnit.svg)](https://www.nuget.org/packages/Compono.NUnit) | | `Compono.Options` | `Microsoft.Extensions.Options` testing support (`TestOptionsSource`, `UseOptions()`) | [![NuGet](https://img.shields.io/nuget/v/Compono.Options.svg)](https://www.nuget.org/packages/Compono.Options) | [![NuGet Downloads](https://img.shields.io/nuget/dt/Compono.Options.svg)](https://www.nuget.org/packages/Compono.Options) | +| `Compono.Metrics` | `System.Diagnostics.Metrics` testing support (`UseMetrics()`, `CapturingMeterFactory`, `Verify()`) | [![NuGet](https://img.shields.io/nuget/v/Compono.Metrics.svg)](https://www.nuget.org/packages/Compono.Metrics) | [![NuGet Downloads](https://img.shields.io/nuget/dt/Compono.Metrics.svg)](https://www.nuget.org/packages/Compono.Metrics) | ## Example diff --git a/docs/adr/0072-compono-metrics-testing-support-package.md b/docs/adr/0072-compono-metrics-testing-support-package.md new file mode 100644 index 00000000..5a37aad0 --- /dev/null +++ b/docs/adr/0072-compono-metrics-testing-support-package.md @@ -0,0 +1,724 @@ +# [ADR-0072] `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support + +**Status:** Accepted + +**Date:** 2026-11-11 + +**Decision Makers:** product owner (maintainer interview, 2026-11-11), assisted by Claude Opus 5.5 + +## Context + +Issue [#165](https://github.com/LayeredCraft/compono/issues/165) (child of +[#161](https://github.com/LayeredCraft/compono/issues/161), item 2): a SUT +takes `IMeterFactory` and records counter, histogram, and gauge +measurements. Tests need to compose that SUT and assert the measurements' +values, instrument names, and tags. Today Compono has no metrics support. +Consumers hand-write an `IMeterFactory` and wire one +`MetricCollector` (`Microsoft.Extensions.Diagnostics.Testing`) per +instrument. + +[RESEARCH-0039](../research/0039-issue-165-metrics-testing-admission.md) +ran capability admission. Gates A and B are met, and the product owner +chose a new package over a documentation-only recipe. It also records the +empirical BCL facts this ADR relies on (spike on SDK 11.0.100, `net8.0` +and `net11.0`). In short: + +- Everything needed is in-box on every target TFM. No `PackageReference`. +- A per-factory `MeterListener` that enables only instruments whose + `Meter.Scope` is that factory isolates same-named meters across factories, + and its `RecordObservableInstruments()` polls only that factory's + observable instruments. +- `Gauge` exists on `net9.0+` only, but a generic measurement callback + receives it without naming the type. +- `services.AddMetrics()` registers its factory with `TryAdd`. +- `DefaultMeterFactory` caches meters, doesn't mutate the caller's + options, rejects a foreign scope, and throws `ObjectDisposedException` + after disposal. + +## Decision Drivers + +- Real consumer scenario (#161 migration, `dynamodb-distributed-lock`) + with the smallest maintainable public surface. +- No new dependency. No reflection, no generator work, Native AOT and + trimming compatible (`IsAotCompatible=true`). +- Deterministic results: parallel tests never see each other's + measurements, and reads have no side effects. +- Compono's non-owning composition model (ADR-0022 Amendment 4, + RESEARCH-0015). No ownership ADR is required. +- No static or ambient capture state. +- Consistency with `Compono.Logging` (ADR-0055) where it fits: composed + double is the handle, `[Shared]` reaches it, extension methods throw a + diagnostic on a non-Compono instance, verification forwards to core + `CallVerifier`. Different where metrics differ: values are typed and + value-centric, and observable instruments need an explicit poll. +- Low allocation on the measurement callback path. + +## Considered Options + +**Axis 1, home:** (1) new `Compono.Metrics` package; (2) documentation-only +recipe (hand-written factory + `MetricCollector`); (3) fold into an +existing package (`Compono.Logging`). + +**Axis 2, handle:** (1) the composed `IMeterFactory` is the handle +(`[Shared] IMeterFactory`, extension methods); (2) a test-owned collector +passed to `UseMetrics(collector)` (ADR-0071 `LogCollector` style); (3) both. + +**Axis 3, listener ownership:** (1) one lazily created listener per +factory, disposed with the factory; (2) one shared static listener that +routes by `Meter.Scope`, plus a transient listener for observable polls; +(3) block on a Compono disposal-ownership ADR. + +**Axis 4, value typing:** (1) typed (`CapturedMeasurement`); (2) +untyped (`object Value`); (3) normalized to `double`. + +**Axis 5, observable instruments:** (1) explicit +`RecordObservableInstruments()`; (2) poll automatically on every read; +(3) explicit plus an opt-in auto-poll option. + +**Axis 6, verification:** (1) snapshot reads plus a filter-then-count +`Verify` builder forwarding to `CallVerifier`; (2) option 1 plus +aggregate helpers (`Sum`, `LastValue`); (3) snapshot reads only. + +**Axis 7, host/DI path:** (1) documentation recipe only; (2) an +`AddComponoMetrics()` `IServiceCollection` extension; (3) defer. + +## Decision Outcome + +Chosen per axis, all confirmed in the maintainer interview (2026-11-11): +Axis 1 option 1, Axis 2 option 1, Axis 3 option 1, Axis 4 option 1, +Axis 5 option 1, Axis 6 option 1, Axis 7 option 1. Supporting decisions +from the same interview: an unknown instrument name yields no +measurements (it doesn't throw); tag matching is subset + `object.Equals`; +no timestamp; no wait API; `Meter` constructor parameters are not +composed; stage-6 precedence follows registration order. + +Settled in the product-owner review (2026-11-11): `CapturedMeasurement` +is a plain `readonly struct` (not a record struct, so `==` never suggests +value equality over `Tags`); meter and instrument names match ordinal, +case-sensitive; the type names below are accepted as proposed; the +package ships in the #161 release (v1.4.0); disposal, type conflicts, +snapshot lifetime, capture order, and the Native AOT validation matrix are +specified explicitly below. + +Accepted in the product-owner final review (2026-11-11), which confirmed: +unsupported measurement types are rejected with `ArgumentException`; the +same-named, conflicting-type instrument limitation is accepted for v1 with +no version or tag selectors; disposal stays explicit and test-owned, with +no ownership or disposal API; `InvalidOperationException` is used for +ambiguity, type conflicts, and misuse, with no custom exception hierarchy; +and the Native AOT validation matrix stands as documented. + +### Package identity and dependency graph + +``` +Compono.Metrics + -> Compono (CompositionBuilder.AddTestDoubleProvider, ICompositionValueProvider, CallVerifier) + (System.Diagnostics.Metrics: in-box shared framework on net8.0/net9.0/net10.0/net11.0) +``` + +- TFMs: `net8.0;net9.0;net10.0;net11.0`, matching the other packages. +- No `PackageReference`. Explicitly not added: + `System.Diagnostics.DiagnosticSource` (package), + `Microsoft.Extensions.Diagnostics`, + `Microsoft.Extensions.Diagnostics.Testing`, + `Microsoft.Extensions.DependencyInjection.Abstractions`. Test projects + may reference `Microsoft.Extensions.Hosting`/`Microsoft.Extensions.Diagnostics` + as test-only dependencies to prove the host recipe. +- No dependency on `Compono.Logging`, `Compono.TestDoubles`, or + `Compono.NSubstitute`. No generator or MSBuild props of its own. + `IMeterFactory` is non-generic, so the provider handles it directly. + +### Public API + +```csharp +namespace Compono.Metrics; + +public static class CompositionBuilderExtensions +{ + // Stage-6 provider: composes IMeterFactory as a new CapturingMeterFactory per request. + public static CompositionBuilder UseMetrics(this CompositionBuilder builder); +} + +// Test IMeterFactory. Publicly constructible (CapturingLogger precedent); UseMetrics() uses the same constructor. +public sealed class CapturingMeterFactory : IMeterFactory +{ + public CapturingMeterFactory(); + public Meter Create(MeterOptions options); + public void Dispose(); +} + +// Plain readonly struct (not a record struct): no synthesized value equality. +public readonly struct CapturedMeasurement where T : struct +{ + public T Value { get; } + public IReadOnlyList> Tags { get; } // per-measurement copy; empty, never null + public Instrument Instrument { get; } // the real instrument (and through it, its Meter); see "Snapshot lifetime" +} + +public static class MeterFactoryTestingExtensions +{ + public static IReadOnlyList> GetMeasurements( + this IMeterFactory factory, string instrumentName) where T : struct; + public static IReadOnlyList> GetMeasurements( + this IMeterFactory factory, string meterName, string instrumentName) where T : struct; + + public static MeasurementVerificationBuilder Verify( + this IMeterFactory factory, string instrumentName) where T : struct; + public static MeasurementVerificationBuilder Verify( + this IMeterFactory factory, string meterName, string instrumentName) where T : struct; + + public static void RecordObservableInstruments(this IMeterFactory factory); + public static void ClearMeasurements(this IMeterFactory factory); +} + +public sealed class MeasurementVerificationBuilder where T : struct +{ + public MeasurementVerificationBuilder WithValue(T value); + public MeasurementVerificationBuilder WithTag(string key, object? value); + public MeasurementVerificationBuilder WithoutTag(string key); + public MeasurementVerificationBuilder Matching(Func, bool> predicate); + + // One-line forwarders to core CallVerifier over the filtered measurement count. + public void Once(); + public void Never(); + public void Exactly(int times); + public void AtLeast(int times); + public void AtMost(int times); +} +``` + +Consumer shapes: + +```csharp +// Composed (any test framework). [Shared] makes the SUT and the test see the same factory. +[Theory, Compose] +public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) +{ + using var _ = meters; // the test owns disposal; see "Disposal patterns" + + sut.PlaceOrder(new Order("eu", 3)); + + meters.Verify("shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + meters.Verify("shop.orders.duration").Once(); // histogram: one recording + + var placed = meters.GetMeasurements("Shop.Orders", "shop.orders.placed"); + Assert.Equal(1, placed.Sum(m => m.Value)); // value math via LINQ +} + +public sealed class MetricsProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.UseMetrics(); +} + +// Observable instruments: poll explicitly, then read. +meters.RecordObservableInstruments(); +meters.Verify("shop.queue.depth").WithValue(7).Once(); + +// Direct construction, no composition. +using var meters = new CapturingMeterFactory(); +var sut = new OrderService(meters); + +// Generic Host / DI (documentation recipe, consumer's own DI API; not Compono surface). +using var meters = new CapturingMeterFactory(); +builder.Services.AddSingleton(meters); // AddMetrics() uses TryAdd, so this wins +``` + +### Factory semantics (`CapturingMeterFactory`) + +Parity with `DefaultMeterFactory` (RESEARCH-0039 ยง5 facts 9-10): + +- `Create(null)` throws `ArgumentNullException`. `Create` with a non-null + `options.Scope` that isn't this factory throws + `InvalidOperationException`. `Create` after `Dispose()` throws + `ObjectDisposedException`. +- The caller's `MeterOptions` is never mutated. The meter is constructed + from a copy whose `Scope` is this factory. +- Meters are cached: the same name, version, and tag set (order-insensitive, + `object.Equals` on values) returns the same `Meter`. Anything else + creates a new one. +- Thread-safe. + +### Capture semantics + +- **Listener:** each factory owns one `MeterListener`, created on its first + `Create` and started before the meter is returned. Its + `InstrumentPublished` enables an instrument only when + `ReferenceEquals(instrument.Meter.Scope, this)`. Callbacks are registered + for the seven numeric types the BCL supports (`byte`, `short`, `int`, + `long`, `float`, `double`, `decimal`). The per-instrument state passed to + `EnableMeasurementEvents` is a typed buffer, so measurements are never + boxed. A factory that never creates a meter never creates a listener. +- **What's captured:** every measurement of every enabled instrument kind: + `Counter`, `UpDownCounter`, `Histogram`, `Gauge` (`net9.0+`, + no TFM split in the capture code), and observable instruments when + polled. Raw measurements only. Compono doesn't aggregate, doesn't + interpret kind (no delta-vs-last-value semantics), and doesn't read + histogram bucket advice. +- **Tags:** the measurement's tags are copied into an array in callback + order (`Array.Empty` when there are none). Meter-level and + instrument-level tags are not merged in. They're reachable through + `CapturedMeasurement.Instrument`. +- **No timestamp.** Order is capture order (see "Capture order"). +- **Isolation:** two factories never see each other's measurements, even + for identical meter and instrument names. There's no static or shared + capture state. + +### Selection and matching + +`GetMeasurements` and `Verify` resolve their selection with the +same algorithm, in this order. The first rule that applies decides the +outcome. `Verify` resolves it when the builder is created, so a +conflict throws before any filter is added. + +1. **Arguments.** Null or empty `instrumentName`/`meterName` throws + `ArgumentException`. A `T` that isn't one of the seven BCL measurement + types (`byte`, `short`, `int`, `long`, `float`, `double`, `decimal`) + throws `ArgumentException`, whether or not any instrument exists. The + message names the requested type and lists the seven supported types. + No instrument can ever record such a `T`, so this catches the mistake + deterministically. +2. **Candidates.** Every instrument this factory has published whose + `Name` equals `instrumentName` and, with the two-argument overload, + whose `Meter.Name` equals `meterName`. Both comparisons are ordinal and + case-sensitive. The candidate set includes instruments of **every** + value type, not just `T`. Instruments are never pre-filtered by `T`, so + an instrument with an unexpected type can't be silently ignored. +3. **Unknown name.** No candidates yields an empty result. + `Verify(...).Never()` passes. A failing `Once()`/`Exactly(n)`/ + `AtLeast(n)` message lists the instruments that do exist (meter name, + instrument name, value type), so a typo is visible. +4. **Meter ambiguity** (one-argument overload only). Candidates from meters + with different `Meter.Name` values throw `InvalidOperationException`. + The message lists each candidate (meter name and version, instrument + name, value type) and points at the two-argument overload. +5. **Type conflict.** Candidates that record more than one value type + throw `InvalidOperationException`, **even when one of the types is + `T`**. The message lists each candidate with its meter name and version + and its value type, and says that one selection can't merge + measurements of different types. This can happen inside one meter + (`CreateCounter("x")` and `CreateCounter("x")` are distinct + instruments) or across same-named meters with different versions or + tags. A consumer resolves it by renaming an instrument in the SUT, or + by narrowing with the two-argument overload when the conflicting + instruments live in differently named meters. The package doesn't + offer version- or tag-level meter selection (non-goal; use + `Matching(m => m.Instrument.Meter.Version == "2")` after the types + agree). +6. **Type mismatch.** Candidates that all record one value type other than + `T` throw `InvalidOperationException` naming that type, for example + `instrument "shop.orders.placed" records int, not long`. +7. **Merge.** Otherwise every candidate records `T`. Their measurements are + merged in capture order. This covers same-named meters with a + different version or tags, and repeated instances of one instrument + name (RESEARCH-0039 fact 10). + +These exceptions are `InvalidOperationException`/`ArgumentException` +with descriptive messages, matching `Compono.Logging`'s misuse diagnostics. +No new public exception type is added. +- **`WithValue(value)`:** `EqualityComparer.Default`. Floating-point + equality is exact; use `Matching(...)` for tolerance. +- **`WithTag(key, value)`:** the measurement contains a tag with that key + (ordinal) whose value satisfies `object.Equals(tagValue, value)`. Other + tags are ignored. No numeric coercion: `200` (`int`) doesn't match `200L`. + The failure message shows each tag's actual runtime type. Chain calls for + several tags. +- **`WithoutTag(key)`:** the measurement has no tag with that key. +- **Exact tag-set** and other matches: `Matching(...)`. +- Failure-message fragments follow `LogVerificationBuilder`'s style, for + example `instrument "shop.orders.placed" (long) with tag region = "eu" + (string) and value 1: expected exactly 1 measurement(s), observed 0`. + +### Observable instruments + +- `RecordObservableInstruments()` calls this factory's listener's + `RecordObservableInstruments()`. Callbacks run synchronously on the + calling thread and only for this factory's observable instruments. Each + observation appends measurements. Calling it twice records twice. +- Reads (`GetMeasurements`, `Verify`) never poll and have no side effects. +- If a callback throws, the BCL behavior stands: the other callbacks still + run, then `AggregateException` propagates to the test. Compono doesn't + catch it. +- Before the first `Create`, or after disposal, it's a no-op. + +### Asynchronous measurements + +Measurements recorded on other threads (background work, hosted services) +are captured thread-safely as they arrive. Reads are point-in-time +snapshots. Compono provides no wait or timeout API. The test awaits its +own completion signal before asserting. `WaitForMeasurementsAsync` is +deferred, not rejected. It's additive if evidence asks for it. + +### Lifecycle and ownership + +- Composition stays non-owning. `UseMetrics()` composes a new factory per + request. `[Shared] IMeterFactory` gives the SUT and the test the same one, + exactly like `[Shared] ILogger`. +- `IMeterFactory` already extends `IDisposable`. `Dispose()` disposes every + meter the factory created (raising `MeasurementsCompleted`), then the + listener. It's idempotent and thread-safe. A measurement racing with + disposal may be captured or dropped, but never throws or corrupts state. +- After disposal, captured measurements stay readable, `ClearMeasurements` + works, `RecordObservableInstruments` is a no-op, and measurements on the + disposed meters' instruments aren't captured. +- Disposal is the test's responsibility. Consequence of skipping it: an + undisposed factory that created meters stays referenced by the BCL's + static meter list for the process lifetime (RESEARCH-0039 fact 8). Its + meters, listener, and captured measurements are kept with it, and the + listener stays registered. This is the same cost as an undisposed + `DefaultMeterFactory`. A factory that never created a meter costs + nothing. + +#### Disposal patterns + +No new ownership API is added. Compono composition never disposes the +factory (ADR-0022 Amendment 4). Whether a test framework disposes +`IDisposable` method arguments is framework-specific, and Compono doesn't +rely on it either way. `Dispose()` is idempotent, so a framework that +also disposes the argument is harmless. The documented patterns: + +1. **`[Compose]`-family tests (every framework adapter): dispose the + `[Shared]` parameter in the test body.** + + ```csharp + [Theory, Compose] + public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) + { + using var _ = meters; + sut.PlaceOrder(new Order("eu", 3)); + meters.Verify("shop.orders.placed").Once(); + } + ``` + + `[Shared]` guarantees the parameter is the same instance the SUT holds, + so disposing it disposes everything the SUT created through it. The + `using` declaration runs when the method exits, including when an + assertion throws. Assertions can go anywhere in the body because + captured data stays readable after disposal. In an `async` test, + `using var` works the same way and runs after the last `await`. + `IMeterFactory` isn't `IAsyncDisposable`, so `await using` doesn't + apply. The parameter must be `[Shared]`: without it, the test's factory + is a different instance from the SUT's, and the SUT's factory isn't + reachable to dispose (or to assert against). +2. **`Composer.Create` tests: construct the factory, then register it.** + + ```csharp + using var meters = new CapturingMeterFactory(); + var composer = Composer.Create(b => b.Register(() => meters)); + var sut = composer.Create(); + ``` + + An exact registration takes precedence over `UseMetrics()`, so + `UseMetrics()` isn't needed here. The test creates the instance, so it + owns it. +3. **Generic Host / DI:** the same, with + `services.AddSingleton(meters)`. An instance + registration isn't disposed by the container, so the test's `using` + owns it. Dispose the factory after the host has stopped. Disposal stops + capture, so measurements recorded during host shutdown are only + captured while the factory is alive. + +Dispose after the SUT's work is done. Measurements recorded after disposal +aren't captured, so disposing while background work is still running can +drop measurements. + +#### Snapshot lifetime + +- `GetMeasurements` returns a new list each call. Later captures, + `ClearMeasurements()`, and `Dispose()` never change a list already + returned. +- Each `Tags` list is a per-measurement copy taken in the callback. It + doesn't alias the BCL's tag span or any other measurement's tags. +- `CapturedMeasurement.Instrument` is the actual `Instrument` object the + SUT created. Through `Instrument.Meter` it references the actual + `Meter`, and through `Meter.Scope` the factory. A retained snapshot + therefore keeps the instrument, its meter, and the factory (and that + factory's captured measurements) reachable for as long as the test holds + it. That's ordinary object reachability and ends when the snapshot is + dropped. It isn't a registration and causes no capture. +- Snapshots stay valid after the factory is disposed. `Value`, `Tags`, and + `Instrument`'s descriptive members (`Name`, `Unit`, `Description`, + `IsObservable`, `Meter.Name`, `Meter.Version`, `Meter.Tags`) remain + readable. A disposed meter's instruments report `Enabled == false`, and + recording through them is a no-op. Reading a snapshot never throws + because of disposal. + +### Precedence and misuse + +- `UseMetrics()` registers a stage-6 provider that handles exactly + `typeof(IMeterFactory)` and returns `NotHandled` for everything else. + Precedence against `UseNSubstitute()`/`UseGeneratedTestDoubles()` + follows the existing first-registered-wins rule (ADR-0024). Register + `UseMetrics()` first. No generator exclusion is added. +- Every `MeterFactoryTestingExtensions` method throws + `InvalidOperationException` when the `IMeterFactory` isn't a + `CapturingMeterFactory`. The message names `UseMetrics()`, the + registration-order requirement, and the host recipe. It's detected by a + type check, not reflection. +- `Meter` constructor parameters are not composed by this package. + Consumers register them from the shared factory in a profile + (documented recipe). + +### Concurrency and allocation + +- One private lock per factory guards appends, clears, and reads. The tag + copy happens before the lock is taken. Reads return snapshot copies. + +#### Capture order + +- **Definition:** capture order is the order in which measurements are + successfully inserted into the factory's synchronized capture buffer. +- Each measurement gets a factory-wide sequence number, assigned **inside + the same lock acquisition that appends it**. Merged selections + (selection rule 7) and every snapshot are ordered by that sequence + number. +- Measurements recorded sequentially on one thread are captured in that + thread's program order, because each append completes before the next + recording starts. One `RecordObservableInstruments()` call appends in + the order the BCL invokes the callbacks and their observations. +- **No chronological ordering is claimed across concurrent producers.** + Two threads recording at about the same time may be captured in either + order, and capture order can differ from the order the `Add`/`Record` + calls began. Tests that need a cross-thread order must establish it + themselves. +- `ClearMeasurements()` doesn't reset the sequence. Order is only + meaningful within one factory. +- Per measurement: one tag array (none when the measurement has no tags) + and an amortized list append. No boxing of values, no LINQ, no closure + allocation in callbacks. + +### Native AOT and trimming + +No reflection, no `MakeGenericType`, no dynamic code, no generated +activation. The seven typed callbacks are ordinary generic instantiations +over value types that the compiler sees statically. `IsAotCompatible=true`. + +Validation matrix. Only what CI actually runs is claimed: + +| Coverage | net8.0 | net9.0 | net10.0 | net11.0 | +|---|---|---|---|---| +| Library build with trim/AOT analyzers (`IsAotCompatible`), warnings as errors | CI | CI | CI | CI | +| `Compono.Metrics.Tests` (JIT) | CI | CI | CI | CI | +| Native AOT publish + run of `Compono.Metrics.AotSmokeTest` (linux-x64) | not covered | not covered | CI | not covered | + +The AOT row matches the existing `aot-validation.yaml` smoke matrix: every +`*.AotSmokeTest` targets `net10.0` and publishes for `linux-x64`. This ADR +doesn't extend that. On net8.0, net9.0, and net11.0, AOT compatibility is +supported by the analyzers alone, not by a runtime run. An optional manual +publish on other TFMs (as ADR-0071 Amendment 2 did) may be recorded in the +plan as evidence, but it isn't a CI guarantee. The smoke test must +publish with zero IL2xxx/IL3xxx warnings and exit successfully. + +### Explicit non-goals + +- A metrics framework, aggregation engine, exporter, or OpenTelemetry + integration. +- Tracing (`ActivitySource`) testing. +- Composing `Meter` parameters, or a configurable meter name. +- An `IServiceCollection`/host extension (documentation recipe instead). +- Timestamps, `TimeProvider`, and wait/timeout APIs. +- Aggregate helpers (`Sum`, `LastValue`) and numeric tag coercion. +- Automatic disposal by composition. +- Replacing `Microsoft.Extensions.Diagnostics.Testing` for consumers who + prefer it. They can keep using it. + +### Positive Consequences + +- `IMeterFactory` SUTs compose with one `UseMetrics()` call. One handle + covers every instrument, isolated per factory. +- No dependencies at all. Combined with ADR-0071, the #161 suite no longer + needs `Microsoft.Extensions.Diagnostics.Testing`. +- Deterministic observable collection and side-effect-free reads. +- The same verification idiom as `Compono.Logging`/`Compono.TestDoubles`. + +### Negative Consequences + +- An undisposed factory with meters leaks for the process lifetime, and + disposal is one manual line per test (`using var _ = meters;`). + Mitigation: the three documented disposal patterns, `using` in every + example, the sample, and the skill reference. The leak is identical to + an undisposed `DefaultMeterFactory`. +- Same-named instruments with different value types in same-named meters + (for example, `Shop` v1 and v2) can't be read at all. Selection rule 5 + throws, and there's no version- or tag-level meter selector. Mitigation: + the conflict message names every instrument. The scenario is unusual, + and a selector is additive later if evidence asks for one. +- Typed reads require the test to know `T`. Mitigation: mismatches throw a + message naming the real type. +- No wait API, so tests asserting on background work must synchronize + themselves. Mitigation: documented, additive later. +- Wrong registration order against `UseNSubstitute()` produces a + substitute. Mitigation: the misuse exception names the cause. + +## Pros and Cons of the Options + +### Axis 1 (home) + +- **New package (chosen).** Good: `Compono.Http` precedent for a + zero-dependency BCL seam, and a clear package guide and skill route. + Bad: one more package to validate, document, and release. +- **Documentation recipe.** Good: no surface. Bad: keeps the heavy + dependency set and per-instrument collectors, and every consumer + re-derives isolation. +- **Fold into `Compono.Logging`.** Good: no new package. Bad: wrong + ecosystem name, and forces `Logging.Abstractions` on metrics users. + +### Axis 2 (handle) + +- **Composed factory (chosen).** Good: works from `[Compose]` attributes + and profiles with no test-body object, and matches ADR-0055. Bad: needs + `[Shared]`, like logging. +- **Test-owned collector.** Good: matches ADR-0071. Bad: awkward where no + test-body object exists, and adds a second type for no evidenced need. +- **Both.** Bad: more surface with no evidence. + +### Axis 3 (listener) + +- **Per-factory, lazy (chosen).** Good: no static state, observable polls + are naturally scoped, unused factories cost nothing. Bad: one listener + per active factory. Each costs a callback on every instrument publish in + the process. +- **Shared static router.** Good: one listener total. Bad: static state, + and a shared `RecordObservableInstruments()` would run every test's + callbacks, so it needs a second transient-listener mechanism. It doesn't + fix the meter leak either (fact 8). +- **Ownership ADR.** Bad: large, out of scope for #165 per RESEARCH-0015. + +### Axis 4 (typing) + +- **Typed (chosen).** Good: no boxing, compile-time value type, matches + `MetricCollector`. Bad: the test names `T`. +- **Untyped.** Bad: boxes every measurement, and moves `int`-vs-`long` + `Equals` pitfalls into tests. +- **Double.** Bad: loses `decimal` precision and `long` exactness above 2^53. + +### Axis 5 (observables) + +- **Explicit (chosen).** Good: reads have no side effects, BCL name, and + deterministic. Bad: one extra call. +- **Auto on read.** Bad: two reads record two observations, and SUT + callbacks run inside assertions. +- **Opt-in auto.** Bad: option surface without evidence. + +### Axis 6 (verification) + +- **Snapshot + filter `Verify` (chosen).** Good: diagnostic failure + messages, same shape as `LogVerificationBuilder`, value math stays in + LINQ. Bad: count-centric `Verify` doesn't express sums directly. +- **Aggregate helpers.** Bad: generic math over seven types, and + kind-dependent meaning (a sum of gauge values is meaningless). +- **Snapshot only.** Bad: loses Compono's diagnostic messages and idiom + consistency. + +### Axis 7 (host) + +- **Recipe (chosen).** Good: one line of the consumer's own DI API, and no + dependency added. Bad: no IntelliSense-discoverable Compono call. +- **`AddComponoMetrics()`.** Bad: adds `DependencyInjection.Abstractions` + to a zero-dependency package for a one-liner. +- **Defer.** Bad: host tests are a likely next question. + +## Links + +- Issue [#165](https://github.com/LayeredCraft/compono/issues/165); parent + [#161](https://github.com/LayeredCraft/compono/issues/161) +- [RESEARCH-0039](../research/0039-issue-165-metrics-testing-admission.md), + [RESEARCH-0036](../research/0036-issue-161-test-composition-gaps-intake.md), + [RESEARCH-0015](../research/0015-disposal-ownership-research.md), + [RESEARCH-0033](../research/0033-compono-logging-tests-concurrency-hang-investigation.md) +- [ADR-0055](0055-compono-logging-testing-support-package.md), + [ADR-0071](0071-compono-logging-host-wide-log-capture.md), + [ADR-0051](0051-compono-http-handler-based-testing-package.md), + [ADR-0024](0024-public-provider-extensibility-model.md), + [ADR-0022](0022-compono-xunit-package-design.md) Amendment 4 +- [PLAN-0074](../plans/0074-compono-metrics-testing-support-impl-plan.md) + +## Amendment (2026-11-11): instrument capture classifies by base type, so `Gauge` is captured on every TFM whose runtime provides it + +Implementation review caught that the "Capture semantics" section's +enumerated instrument-kind list (`Counter`, `UpDownCounter`, +`Histogram`, `Gauge`, and the observable kinds) was implemented with a +`Gauge`-recognizing branch gated behind `#if NET9_0_OR_GREATER`. That +compiles the branch out for a `net8.0`-targeted assembly, so a `net8.0` +consumer whose runtime provides `DiagnosticSource` 9.x (where `Gauge` +exists) would have had its gauge instruments silently ignored โ€” no buffer, +no capture, no diagnostic. + +The capture code now classifies an instrument by its BCL base type instead +of by naming each concrete kind: an instrument is captured when it is an +`Instrument` or an `ObservableInstrument`. Every supported synchronous +kind (`Counter`, `UpDownCounter`, `Histogram`, `Gauge`) derives +from `Instrument`, and every observable kind (`ObservableCounter`, +`ObservableUpDownCounter`, `ObservableGauge`) derives from +`ObservableInstrument`, so the set of captured kinds is unchanged; the +difference is that a kind the runtime introduces later is captured without a +compile-time branch. This is TFM-independent, needs no `PackageReference`, +and still boxes nothing. The original "what's captured" list is otherwise +unchanged. A `net8.0` test (compiled against `DiagnosticSource` 9.x, +test-only) records and verifies `Gauge` as a regression guard. + +## Amendment 2 (2026-11-11): meter-tag identity is a one-to-one (bag) match, so duplicate keys are significant + +The "Factory semantics" section says the same name, version, and tag set +(order-insensitive, `object.Equals` on values) returns the same `Meter`. The +first implementation compared tag sets with "every left entry matches some +right entry", which treats `[k=1, k=1]` and `[k=1, j=2]` as equal (both +left entries find the `k=1` on the right). + +Each entry on one side must now consume exactly one distinct entry on the +other side (a `bool[] matched` bag match), preserving order-insensitivity +while making duplicate keys significant: `[k=1, k=1]` equals `[k=1, k=1]`, +but not `[k=1, j=2]`, and `[k=1, k=1]` does not equal `[k=1]`. The common +case (no meter tags) still allocates nothing. + +This is intentionally **stricter** than `DefaultMeterFactory`: its +duplicate-tag comparison is not a true multiset comparison, so +Compono.Metrics does not claim tag-set parity with it here. A duplicate +meter-tag key is significant โ€” two sets with the same keys but different +duplicate multiplicities are never treated as the same meter โ€” which is the +predictable, documented behavior this framework wants. + +## Amendment 3 (2026-11-11): a test `IMeterFactory` wins host DI by being the *last* registration, not the first + +The "Disposal patterns" section's Generic Host example registered the test +factory with a comment claiming `AddMetrics()` uses `TryAdd`, "so this +wins". That inference is wrong for `Host.CreateApplicationBuilder()`, which +already registers a default `IMeterFactory` as part of its built-in service +setup. `IServiceProvider` resolves a **single** service to its **last** +registration, so the test factory wins because it is registered *after* the +builder is created โ€” not because it is registered first. `TryAdd`/ +`TryAddSingleton` would in fact keep the existing (default) registration and +discard the test factory. + +The documented recipe is therefore: `Host.CreateApplicationBuilder()`, then +`builder.Services.AddSingleton(meters)`; never +`TryAddSingleton` to replace a factory. Diagnostic and prose wording across +the package guide, host recipe, troubleshooting page, and the +`RequireCapturing` misuse message were corrected to this rule. No public +API changed. + +## Amendment 4 (2026-11-11): tag-value diagnostics describe the *expected* filter value, including its runtime type + +The "Selection and matching" section's `WithTag` bullet said the failure +message "shows each tag's actual runtime type". The implementation annotated +the *expected* value's compile-time type (for example `region = "eu" +(string)`), which is not the measurement's actual runtime tag type and read +as if it were. That annotation was removed. + +A later review restored a type annotation but made the wording unambiguous: +the message describes the **expected** value the test passed to `WithTag`, +never the captured measurement's tag. A string stays quoted without an +annotation (`region = "eu"` โ€” the quotes already convey the type), `null` +renders as `null`, and every other value shows its runtime type, for example +`status = 200 (int)`. Because the type comes from the argument the test +supplied, the message can never claim a type the measurement does not have. + +Failure messages also: join the filter descriptions with `with` (first) and +`and` (subsequent); format numeric values with the invariant culture; forward +the count to core `CallVerifier`'s `Expected exactly N call(s) to ..., +but received M.` wording; and, when an unknown instrument name matched +nothing, append a separate sentence naming the missing instrument and +listing the instruments the factory did publish (after the count sentence, +where it reads naturally). Example: +`Expected exactly 1 call(s) to instrument "shop.orders.placed" (long) with +tag region = "eu" and value 1, but received 0.` No public API changed, and +core `CallVerifier` is untouched. diff --git a/docs/adr/README.md b/docs/adr/README.md index 209a19e8..d4563dbd 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -130,3 +130,4 @@ the mechanics: numbering, status, and the index. | [0069](0069-xunitv3-require-fixture-accessor.md) | xUnit v3 Fixture Accessor for Composition Profiles (`RequireFixture()`) | Accepted | | [0070](0070-xunitv3-composedata-composed-theory-rows.md) | xUnit v3 Composed Theory Rows (`[ComposeData]`) | Accepted | | [0071](0071-compono-logging-host-wide-log-capture.md) | `Compono.Logging`: Host-Wide Log Capture (`LogCollector` + `AddComponoCapture`) | Accepted | +| [0072](0072-compono-metrics-testing-support-package.md) | `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support | Accepted | diff --git a/docs/architecture/current/provider-pipeline.md b/docs/architecture/current/provider-pipeline.md index 4bd53281..035bdee0 100644 --- a/docs/architecture/current/provider-pipeline.md +++ b/docs/architecture/current/provider-pipeline.md @@ -17,7 +17,7 @@ providers reordering themselves: | 3 | Exact registrations | **Hybrid**: a context-owned deterministic lookup against the exact-registration table, then โ€” only on a miss, if `UseServiceProvider(...)` was configured โ€” a fallback `IServiceProvider.GetService(typeof(T))` call. | | 4 | Configuration rules | Ordered `ICompositionProvider` collection populated by type/member value rules compiled from `builder.For()...`, whether reached directly or via a profile. | | 5 | Semantic value providers | Ordered `ICompositionProvider` collection. Public registration surface: `builder.AddSemanticProvider(ICompositionValueProvider)`. `Compono.Bogus`'s `BogusMemberNameProvider` is this stage's first real registrant. | -| 6 | Test-double providers | Ordered `ICompositionProvider` collection. Public registration surface: `builder.AddTestDoubleProvider(ICompositionValueProvider)`. `Compono.NSubstitute`'s `NSubstituteProvider`, `Compono.TestDoubles`'s `GeneratedTestDoubleProvider`, and `Compono.Logging`'s `LoggingProvider` are real registrants โ€” registration order between them decides which one resolves an interface request first when more than one is installed, same as any other stage. For `ILogger`/`ILogger` specifically, [ADR-0055](../../adr/0055-compono-logging-testing-support-package.md) Amendment 4 makes `GeneratedTestDoubleProvider` unable to handle those types at all once `ComponoGeneratedLogging` is enabled (they're Logging-owned, excluded from `Compono.TestDoubles` generation) โ€” so order against `UseGeneratedTestDoubles()` isn't observable for them. Register `UseLogging()` before `UseNSubstitute()` when `ILogger`/`ILogger` should resolve to a `CapturingLogger`/`CapturingLogger` rather than a substitute โ€” `NSubstituteProvider` is unaffected by Amendment 4 and still resolves them if registered first. | +| 6 | Test-double providers | Ordered `ICompositionProvider` collection. Public registration surface: `builder.AddTestDoubleProvider(ICompositionValueProvider)`. `Compono.NSubstitute`'s `NSubstituteProvider`, `Compono.TestDoubles`'s `GeneratedTestDoubleProvider`, `Compono.Logging`'s `LoggingProvider`, and `Compono.Metrics`'s `MetricsProvider` are real registrants โ€” registration order between them decides which one resolves an interface request first when more than one is installed, same as any other stage. For `ILogger`/`ILogger` specifically, [ADR-0055](../../adr/0055-compono-logging-testing-support-package.md) Amendment 4 makes `GeneratedTestDoubleProvider` unable to handle those types at all once `ComponoGeneratedLogging` is enabled (they're Logging-owned, excluded from `Compono.TestDoubles` generation) โ€” so order against `UseGeneratedTestDoubles()` isn't observable for them. Register `UseLogging()` before `UseNSubstitute()` when `ILogger`/`ILogger` should resolve to a `CapturingLogger`/`CapturingLogger` rather than a substitute โ€” `NSubstituteProvider` is unaffected by Amendment 4 and still resolves them if registered first. For `IMeterFactory`, register `UseMetrics()` before `UseNSubstitute()` so the request resolves to a `CapturingMeterFactory`; `NSubstituteProvider` resolves `IMeterFactory` (a non-generic interface) to a substitute if registered first โ€” see [ADR-0072](../../adr/0072-compono-metrics-testing-support-package.md). | | 7 | Built-in value providers | **Hybrid**: an ordered provider collection (primitives, enums, nullable value types) tried first, followed by a context-owned deterministic dispatch through `CollectionPlanCache` for the five built-in collection shapes. | | 8 | Generated composition plans | Context-owned deterministic dispatch via `PlanCache` โ€” **not** an `ICompositionProvider`; see [Generated Plans and Discovery](generated-plans-and-discovery.md). | | 9 | Diagnostic failure | Context-owned terminal stage | @@ -25,7 +25,7 @@ providers reordering themselves: Only stage 7 has anything registered *unconditionally* (`BuiltInProviders.Default`); every other stage is opt-in, populated only when a consumer actually calls `.For()` (stage 4), `UseNSubstitute()`/ -`UseGeneratedTestDoubles()` (stage 6), `UseBogus()` (stage 5), or registers +`UseGeneratedTestDoubles()`/`UseMetrics()` (stage 6), `UseBogus()` (stage 5), or registers a hand-written provider directly. Provider order *within* an extensible stage is registration order โ€” stage 7 alone holds three real providers (`PrimitiveValueProvider`, `EnumValueProvider`, `NullableValueProvider`), diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index cc27d868..844c6663 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -50,6 +50,7 @@ dotnet add package Compono.NSubstitute # automatic substitute compositio dotnet add package Compono.Bogus # semantic fake data (names, emails, ...) dotnet add package Compono.DependencyInjection # row.AsServiceProvider() bridge dotnet add package Compono.Http # TestHttpHandler for HttpClient tests +dotnet add package Compono.Metrics # System.Diagnostics.Metrics testing support ``` Every package targets `net8.0`/`net9.0`/`net10.0`/`net11.0` and has a diff --git a/docs/how-to/verify-metrics-across-a-host.md b/docs/how-to/verify-metrics-across-a-host.md new file mode 100644 index 00000000..ee0c51f5 --- /dev/null +++ b/docs/how-to/verify-metrics-across-a-host.md @@ -0,0 +1,108 @@ +# How Do I Verify Metrics Recorded by a Service in a Generic Host? + +Create the `CapturingMeterFactory`, register it as the host's +`IMeterFactory` singleton, run the host, then verify that factory. The +factory is the test-owned capture destination: it sees every measurement +recorded through the `IMeterFactory` its services resolve. See +[`Compono.Metrics`'s Package Guide](../packages/compono-metrics.md) for the +full capture, selection, and disposal semantics. + +## Basic case + +```csharp +using Compono.Metrics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Diagnostics.Metrics; + +[Fact] +public async Task Checkout_RecordsAnOrder() +{ + using var meters = new CapturingMeterFactory(); + + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(meters); // last IMeterFactory registration wins + builder.Services.AddSingleton(); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + + var service = host.Services.GetRequiredService(); + service.PlaceOrder(new Order("eu", 3)); + + await host.StopAsync(TestContext.Current.CancellationToken); + + meters.Verify("shop.orders.placed").WithTag("region", "eu").Once(); +} +``` + +`Host.CreateApplicationBuilder()` already registers a default +`IMeterFactory` as part of its built-in service setup, so `IMeterFactory` has +two registrations once you add yours. The container resolves a **single** +`IMeterFactory` to its **last** registration, so registering your instance +after the builder is created means the host resolves `meters`. Do **not** use +`TryAddSingleton` to install it: `TryAdd` keeps whatever is registered first, +so it would leave the default factory in place and silently discard yours. +The test creates the factory, so the test owns it โ€” +the container does not dispose an instance registration. Dispose the +factory (here, via `using var` at the end of the test) **after** the host +has stopped: a measurement recorded after disposal isn't captured. + +## Keep the factory for the whole test + +Captured measurements stay readable after the factory is disposed, and +`ClearMeasurements()` keeps working, so you can assert after disposal: + +```csharp +await host.StopAsync(TestContext.Current.CancellationToken); +meters.Dispose(); + +meters.Verify("shop.orders.placed").Once(); // still valid +``` + +Reads (`GetMeasurements`, `Verify`) never record anything and have no +side effects, so asserting never perturbs capture. + +## Observable instruments + +Observable instruments are only recorded when polled. Call +`RecordObservableInstruments()` after the code under test has run and before +asserting: + +```csharp +service.PlaceOrder(new Order("eu", 3)); + +meters.RecordObservableInstruments(); +meters.Verify("shop.queue.depth").WithValue(7).Once(); +``` + +Each call records one observation per observable instrument; calling it +twice records twice. Before the first `Create`, or after disposal, it is a +no-op. + +## Background and asynchronous work + +Measurements recorded on other threads โ€” a hosted service, a background +task โ€” are captured thread-safely as they arrive. Compono provides no wait +or timeout API, so the test must await its own completion signal before +asserting. There is no chronological ordering guarantee across concurrent +producers; if a test needs a cross-thread order, establish it itself. + +## What the host may not capture + +`UseMetrics()` and `CapturingMeterFactory` don't change how the host +resolves services. A service that captures its own `Meter` through +`new Meter(...)` (rather than through the injected `IMeterFactory`) is not +scoped to this factory, so its measurements are never captured โ€” its +`Meter.Scope` isn't the factory. Give the service the `IMeterFactory` and +let it create its meters from that, which is the shape this package targets. + +## See also + +- [`Compono.Metrics` Package Guide](../packages/compono-metrics.md) โ€” + selection rules, matching, disposal patterns, and snapshot lifetime. +- [Share a Value Across a Test](share-a-value-across-a-test.md) โ€” when a + composed service needs the same factory the test asserts against, without + a host. +- [Troubleshooting: metrics](../troubleshooting/common-errors.md#verify-metrics-on-a-non-compono-imeterfactory-throws) + โ€” the misuse and selection diagnostics. diff --git a/docs/index.md b/docs/index.md index 7f010a22..a475903d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -48,6 +48,7 @@ Compono determines **how** those requirements are satisfied. | `Compono.MSTest` | MSTest integration | | `Compono.NUnit` | NUnit integration (no `[TestFixture]` required) | | `Compono.Options` | `Microsoft.Extensions.Options` testing support (`TestOptionsSource`, `UseOptions()`) | +| `Compono.Metrics` | `System.Diagnostics.Metrics` testing support (`UseMetrics()`, `CapturingMeterFactory`, `Verify()`) | ## Example diff --git a/docs/packages/compono-metrics.md b/docs/packages/compono-metrics.md new file mode 100644 index 00000000..a6890088 --- /dev/null +++ b/docs/packages/compono-metrics.md @@ -0,0 +1,404 @@ +# Compono.Metrics + +First-class `System.Diagnostics.Metrics` testing support. `IMeterFactory` +composes naturally through `UseMetrics()`, backed by a hand-written +`CapturingMeterFactory` (`System.Diagnostics.Metrics` is in-box on every +target framework โ€” there is no third-party dependency and no +`Microsoft.Extensions.Diagnostics.Testing`). A composed factory captures +every measurement of every instrument a SUT creates โ€” counter, +up/down-counter, histogram, gauge, and observable instruments when polled +โ€” and exposes Compono-native typed reads and `Verify()` verification +reusing core `Compono`'s `CallVerifier` unmodified. See +[ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) for the +full decision record and +[RESEARCH-0039](../research/0039-issue-165-metrics-testing-admission.md) +for the design investigation and the empirical BCL facts this package +relies on. + +## When to install + +Your code under test takes an `IMeterFactory` constructor dependency and +records measurements, and the test wants to assert *what* was recorded โ€” +instrument names, values, and tags โ€” not substitute an unrelated +application interface or hand-write a factory plus one +`MetricCollector` per instrument: + +```bash +dotnet add package Compono +dotnet add package Compono.Metrics +``` + +This package depends only on `Compono`. `System.Diagnostics.Metrics` +(`IMeterFactory`, `Meter`, `MeterListener`, `Counter`, and so on) is +part of the shared framework on every supported target framework, so no +`PackageReference` is added โ€” not `System.Diagnostics.DiagnosticSource`, +not `Microsoft.Extensions.Diagnostics`, not +`Microsoft.Extensions.Diagnostics.Testing`, not +`Microsoft.Extensions.DependencyInjection.Abstractions`. + +**No MSBuild opt-in.** Unlike `Compono.TestDoubles`, there is nothing to +enable โ€” `Compono.Metrics` ships no generator, analyzer, or props asset. +`UseMetrics()` works as soon as the package is referenced. + +## What it gives you + +```csharp +using Compono; +using Compono.Metrics; +using System.Diagnostics.Metrics; + +var composer = Composer.Create(builder => builder.UseMetrics()); +var service = composer.Create(); // OrderService(IMeterFactory meters, ...) +``` + +```csharp +public sealed class MetricsProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => + builder.UseMetrics().Share(); +} + +[Theory] +[Compose] +public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) +{ + using var _ = meters; // the test owns disposal; see "Disposal patterns" + + sut.PlaceOrder(new Order("eu", 3)); + + meters.Verify("shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + meters.Verify("shop.orders.duration").Once(); // histogram: one recording +} +``` + +```csharp +var placed = meters.GetMeasurements("Shop.Orders", "shop.orders.placed"); +Assert.Equal(1, placed.Sum(m => m.Value)); // value math via LINQ +``` + +- **`UseMetrics()`** โ€” registers a stage-6 test-double provider so any + `IMeterFactory` request composes as a new `CapturingMeterFactory`. +- **`meters.GetMeasurements(instrumentName)`** / + **`GetMeasurements(meterName, instrumentName)`** โ€” a snapshot list of + the matching measurements. Direct inspection, no assertion framework + required. `T` is one of `byte`, `short`, `int`, `long`, `float`, + `double`, or `decimal`. +- **`meters.Verify(...)`** โ€” the fluent entry point: `.WithValue(value)`, + `.WithTag(key, value)`, `.WithoutTag(key)`, `.Matching(predicate)`, + ending in `.Once()` / `.Never()` / `.Exactly(n)` / `.AtLeast(n)` / + `.AtMost(n)` โ€” the exact same single-verb vocabulary + `Compono.TestDoubles`/`Compono.Http`/`Compono.Logging` already use + (`repository.Verify().Save().Once()`, `logger.Verify().AtLevel(...).Once()`), + each a thin, one-line forward through the same shared count-verification + semantics core `Compono`'s `CallVerifier` implements. The filter chain + narrows *which* measurements count, then the terminal counts them exactly + the same way regardless of which package it's reached through. +- **`meters.RecordObservableInstruments()`** โ€” polls this factory's + observable instruments. Reads never poll; see "Observable instruments." +- **`meters.ClearMeasurements()`** โ€” empties the capture buffer. Order is + otherwise capture order; see "Capture order." +- **`CapturingMeterFactory`** โ€” hand-written and publicly, directly + constructible with no composition involved at all: + ```csharp + using var meters = new CapturingMeterFactory(); + var sut = new OrderService(meters); + ``` + A `UseMetrics()`-composed factory and a directly-constructed one behave + identically โ€” one implementation, not two. + +## Factory semantics + +`CapturingMeterFactory` has parity with the BCL's own `DefaultMeterFactory`: + +- `Create(null)` throws `ArgumentNullException`. `Create` with a non-null + `options.Scope` that isn't this factory throws `InvalidOperationException`. + `Create` after `Dispose()` throws `ObjectDisposedException`. +- The caller's `MeterOptions` is never mutated. The meter is constructed + from a copy whose `Scope` is this factory, so `meter.Scope` is + reference-equal to the factory. +- Meters are cached: the same name, version, and tag set (order-insensitive, + `object.Equals` on values) returns the **same** `Meter`. Anything else + creates a new one. +- Thread-safe. + +## Capture semantics + +- **Listener.** Each factory owns one `MeterListener`, created on its first + `Create` and started before the meter is returned. It enables an + instrument only when `ReferenceEquals(instrument.Meter.Scope, this)`, so + two factories never see each other's measurements even for identical + meter and instrument names. There is no static or shared capture state. + A factory that never creates a meter never creates a listener. +- **What's captured.** Every measurement of every enabled instrument kind: + `Counter`, `UpDownCounter`, `Histogram`, `Gauge` (`net9.0+`), + and observable instruments when polled. Raw measurements only โ€” Compono + doesn't aggregate, doesn't interpret kind (no delta-vs-last-value + semantics), and doesn't read histogram bucket advice. +- **No timestamp.** Order is capture order (see "Capture order"). +- **Isolation.** Two factories never see each other's measurements. + +## Selection and matching + +`GetMeasurements` and `Verify` resolve their selection with the same +algorithm, in this order. The first rule that applies decides the outcome. +`Verify` resolves it when the builder is created, so a conflict throws +before any filter is added. + +1. **Arguments.** A null or empty `instrumentName`/`meterName` throws + `ArgumentException`. A `T` that isn't one of the seven BCL measurement + types throws `ArgumentException` whether or not any instrument exists; + the message names the requested type and lists the seven supported types. +2. **Candidates.** Every instrument this factory has published whose `Name` + equals `instrumentName` and, with the two-argument overload, whose + `Meter.Name` equals `meterName`. Both comparisons are ordinal and + case-sensitive. The candidate set includes instruments of **every** value + type, not just `T`. +3. **Unknown name.** No candidates yields an empty result. + `Verify(...).Never()` passes. A failing `Once()`/`Exactly(n)`/`AtLeast(n)` + message lists the instruments that do exist (meter name, instrument name, + value type), so a typo is visible. +4. **Meter ambiguity** (one-argument overload only). Candidates from meters + with different `Meter.Name` values throw `InvalidOperationException`. The + message lists each candidate and points at the two-argument overload. +5. **Type conflict.** Candidates that record more than one value type throw + `InvalidOperationException`, **even when one of the types is `T`**. This + can happen inside one meter (`CreateCounter("x")` and + `CreateCounter("x")` are distinct instruments) or across same-named + meters with different versions or tags. +6. **Type mismatch.** Candidates that all record one value type other than + `T` throw `InvalidOperationException` naming that type, for example + `instrument "shop.orders.placed" records int, not long`. +7. **Merge.** Otherwise every candidate records `T`. Their measurements are + merged in capture order. + +Matching filters: + +- **`WithValue(value)`** uses `EqualityComparer.Default`. Floating-point + equality is exact; use `Matching(...)` for tolerance. +- **`WithTag(key, value)`** matches a measurement that contains a tag with + that key (ordinal) whose value satisfies `object.Equals(tagValue, value)`. + Other tags are ignored. There is no numeric coercion: `200` (`int`) does + **not** match `200L`. Chain calls for several tags. +- **`WithoutTag(key)`** matches a measurement with no tag with that key. +- **`Matching(predicate)`** covers exact tag-set and any other condition. + +Failure messages follow `LogVerificationBuilder`'s style: the filters are +joined with `with`/`and`, and the count forwards to core `CallVerifier`'s +`Expected exactly N call(s) to ..., but received M.` wording. Numeric values +are formatted with the invariant culture. The message describes the filter +you asked for. A string tag value is shown quoted (`region = "eu"`); any +other value shows the runtime type of the value you passed to `WithTag` (for +example `200` renders as `200 (int)`), so it always matches the expectation +and never annotates the measurement's actual tag. For example: + +```text +Expected exactly 1 call(s) to instrument "shop.orders.placed" (long) with tag region = "eu" and value 1, but received 0. +``` + +```text +Expected exactly 1 call(s) to instrument "shop.orders.placed" (long) with tag status = 200 (int), but received 0. +``` + +When nothing matched an unknown instrument name, the message names the +instrument that doesn't exist and lists the ones that do: + +```text +Expected exactly 1 call(s) to instrument "shop.orders.placed" (long), but received 0. No instrument named "shop.orders.placed" has been published by this factory. Existing instruments: meter "Shop.Orders": instrument "orders.placed" (long). +``` + +These exceptions are `InvalidOperationException`/`ArgumentException` with +descriptive messages; no new public exception type is added. + +## Observable instruments + +- `RecordObservableInstruments()` calls this factory's listener's + `RecordObservableInstruments()`. Callbacks run synchronously on the + calling thread and only for this factory's observable instruments. Each + observation appends measurements. Calling it twice records twice. +- Reads (`GetMeasurements`, `Verify`) never poll and have no side effects. +- If a callback throws, the BCL behavior stands: the other callbacks still + run, then `AggregateException` propagates to the test. Compono doesn't + catch it. +- Before the first `Create`, or after disposal, it is a no-op. + +```csharp +meters.RecordObservableInstruments(); +meters.Verify("shop.queue.depth").WithValue(7).Once(); +``` + +## Asynchronous measurements + +Measurements recorded on other threads (background work, hosted services) +are captured thread-safely as they arrive. Reads are point-in-time +snapshots. Compono provides no wait or timeout API โ€” the test awaits its +own completion signal before asserting. + +## Disposal patterns + +No ownership or disposal API is added. Composition is non-owning +(`UseMetrics()` composes a new factory per request and never disposes it). +`IMeterFactory` already extends `IDisposable`, and `Dispose()` disposes +every meter the factory created, then the listener. It is idempotent and +thread-safe, so a test framework that also disposes the argument is +harmless. The documented patterns: + +1. **`[Compose]`-family tests: dispose the `[Shared]` parameter in the test + body.** + + ```csharp + [Theory, Compose] + public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService sut) + { + using var _ = meters; + sut.PlaceOrder(new Order("eu", 3)); + meters.Verify("shop.orders.placed").Once(); + } + ``` + + `[Shared]` guarantees the parameter is the same instance the SUT holds, + so disposing it disposes everything the SUT created through it. The + `using` declaration runs when the method exits, including when an + assertion throws. Assertions can go anywhere in the body because + captured data stays readable after disposal. In an `async` test, + `using var` works the same way and runs after the last `await`. + `IMeterFactory` isn't `IAsyncDisposable`, so `await using` doesn't apply. + +2. **`Composer.Create` tests: construct the factory, then register it.** + + ```csharp + using var meters = new CapturingMeterFactory(); + var composer = Composer.Create(b => b.Register(() => meters)); + var sut = composer.Create(); + ``` + + An exact registration takes precedence over `UseMetrics()`, so + `UseMetrics()` isn't needed here. The test creates the instance, so it + owns it. + +3. **Generic Host / DI:** the same, registered as a singleton instance. + + ```csharp + using var meters = new CapturingMeterFactory(); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(meters); // last IMeterFactory registration wins + builder.Services.AddSingleton(); + using var host = builder.Build(); + + // ... start the host, call the code under test ... + + meters.Verify("shop.orders.placed").Once(); + ``` + + `Host.CreateApplicationBuilder()` already registers a default + `IMeterFactory` as part of its built-in service setup, so `IMeterFactory` + has two registrations once you add yours. The container resolves a + **single** `IMeterFactory` to its **last** registration, so the host + resolves `meters`. Don't use `TryAddSingleton` to install it: `TryAdd` + keeps whatever is registered first, so it would leave the default factory + in place and discard yours. An instance registration isn't disposed by the + container, so the test's `using` owns it. Dispose the factory after the + host has stopped, so measurements recorded during host shutdown are still + captured. + +Dispose after the SUT's work is done. Measurements recorded after disposal +aren't captured, so disposing while background work is still running can +drop measurements. Consequence of skipping disposal: an undisposed factory +that created meters stays referenced by the BCL's static meter list for the +process lifetime โ€” the same cost as an undisposed `DefaultMeterFactory`. A +factory that never created a meter costs nothing. + +## Snapshot lifetime + +- `GetMeasurements` returns a new list each call. Later captures, + `ClearMeasurements()`, and `Dispose()` never change a list already + returned. +- Each `Tags` list is a per-measurement copy taken in the callback; it never + aliases the BCL's tag span or another measurement's tags. A measurement + with no tags yields `Tags` that is empty, never null. +- `CapturedMeasurement.Instrument` is the actual `Instrument` object the + SUT created. Through `Instrument.Meter` it references the actual `Meter`, + and through `Meter.Scope` the factory. That's ordinary object + reachability, not a registration; it causes no capture. +- Snapshots stay valid after the factory is disposed. `Value`, `Tags`, and + `Instrument`'s descriptive members remain readable; a disposed meter's + instruments report `Enabled == false`, and recording through them is a + no-op. Reading a snapshot never throws because of disposal. + +## Capture order + +- Capture order is the order in which measurements are successfully inserted + into the factory's synchronized capture buffer. +- Each measurement gets a factory-wide sequence number, assigned inside the + same lock acquisition that appends it. Merged selections and every + snapshot are ordered by that sequence number. +- Measurements recorded sequentially on one thread are captured in that + thread's program order. One `RecordObservableInstruments()` call appends + in the order the BCL invokes the callbacks and their observations. +- **No chronological ordering is claimed across concurrent producers.** Two + threads recording at about the same time may be captured in either order. +- `ClearMeasurements()` doesn't reset the sequence. Order is only meaningful + within one factory. +- One private lock per factory guards appends, clears, and reads; the tag + copy happens before the lock is taken. + +## Registration order and misuse + +- `UseMetrics()` registers a stage-6 provider that handles exactly + `typeof(IMeterFactory)` and returns `NotHandled` for everything else. + Precedence against `UseNSubstitute()`/`UseGeneratedTestDoubles()` follows + the existing first-registered-wins rule + ([ADR-0024](../adr/0024-public-provider-extensibility-model.md)). + Register `UseMetrics()` first: + ```csharp + builder.UseMetrics().UseNSubstitute(); // IMeterFactory -> CapturingMeterFactory + builder.UseNSubstitute().UseMetrics(); // IMeterFactory -> a substitute instead + ``` +- Every `MeterFactoryTestingExtensions` method throws + `InvalidOperationException` when the `IMeterFactory` isn't a + `CapturingMeterFactory`. The message names `UseMetrics()`, the + registration-order requirement, and the host recipe. It's detected by a + type check, not reflection. +- `Meter` constructor parameters are not composed by this package. Consumers + that want a specific `Meter` register it from the shared factory in a + profile. + +## Native AOT and trimming + +No reflection, no `MakeGenericType`, no dynamic code, no generated +activation. `IsAotCompatible=true`, so the library builds with the trim/AOT +analyzers on every target framework. The `Compono.Metrics.AotSmokeTest` +project publishes with `PublishAot=true` for `linux-x64` on `net10.0` in CI, +matching the existing smoke matrix. + +## v1 non-goals + +Deliberately not in this package โ€” see ADR-0072's Decision Outcome for the +rationale behind each: + +- A metrics framework, aggregation engine, exporter, or OpenTelemetry + integration. +- Tracing (`ActivitySource`) testing. +- Composing `Meter` parameters, or a configurable meter name. +- An `IServiceCollection`/host extension (documentation recipe instead). +- Timestamps, `TimeProvider`, and wait/timeout APIs. +- Aggregate helpers (`Sum`, `LastValue`) and numeric tag coercion. +- Automatic disposal by composition. +- Version- or tag-level meter selection. Same-named instruments with + conflicting value types in same-named meters can't be read at all; use + `Matching(m => m.Instrument.Meter.Version == "2")` after the types agree. +- Replacing `Microsoft.Extensions.Diagnostics.Testing` for consumers who + prefer it. + +## Next + +- [Basic Usage sample](../samples/basic-usage.md) (`MetricsTests`) โ€” a + concise `UseMetrics()`/`Verify()` scenario in this repo's single clearest + reference project. +- [Verify Metrics Across a Host](../how-to/verify-metrics-across-a-host.md) + โ€” the Generic Host recipe. +- [`Compono.XunitV3`](compono-xunitv3.md)/[`Compono.TUnit`](compono-tunit.md) + โ€” `[Compose]`/`[Shared]` used throughout the examples above. +- [`Compono.Logging`](compono-logging.md) โ€” the same "composed double is the + handle, `Verify()` forwards to `CallVerifier`" idiom for logging. +- [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) โ€” the + full decision record. diff --git a/docs/packages/index.md b/docs/packages/index.md index e4818207..6ac32154 100644 --- a/docs/packages/index.md +++ b/docs/packages/index.md @@ -1,6 +1,6 @@ # Package Guides -Compono ships as thirteen independently-installable NuGet packages. Pick +Compono ships as fourteen independently-installable NuGet packages. Pick which ones you need before reading any single guide in depth โ€” most projects only need the first two. @@ -19,6 +19,7 @@ projects only need the first two. | [`Compono.Http`](compono-http.md) | `TestHttpHandler` โ€” a reflection-free `HttpMessageHandler` test double: `OnGet`/`OnPost`/etc. + `When(...)` matching, strict unmatched-request behavior, registration-handle verification. | Your test needs to exercise the real `HttpClient` pipeline against a configured HTTP response, instead of substituting an application-level interface. | | [`Compono.Logging`](compono-logging.md) | `UseLogging()` โ€” `ILogger`/`ILogger` compose as a hand-written `CapturingLogger`/`CapturingLogger`, with structured-property extraction, real scope tracking, and `Verify()` verification. Generation is on by default once installed. | Your composed type takes an `ILogger`/`ILogger` dependency and the test wants to assert what was logged. | | [`Compono.Options`](compono-options.md) | `TestOptionsSource`/`UseOptions()` โ€” one test-configured source of truth coherently backing `IOptions`/`IOptionsSnapshot`/`IOptionsMonitor` for a settings type. | Your composed type depends on `IOptions`/`IOptionsSnapshot`/`IOptionsMonitor` and the test wants one coherent source, not hand-wired separate registrations or a buggy hand-rolled Monitor fake. | +| [`Compono.Metrics`](compono-metrics.md) | `UseMetrics()` โ€” `IMeterFactory` composes as a hand-written `CapturingMeterFactory`; typed `GetMeasurements()` and `Verify()`, explicit observable polling. | Your composed type takes an `IMeterFactory` and the test wants to assert recorded values and tags. | Every package targets `net8.0`/`net9.0`/`net10.0`/`net11.0` and has a stable release, except `Compono.XunitV3.Aot` (`net9.0`/`net10.0`/`net11.0` @@ -59,7 +60,7 @@ whether or not you're also using xUnit v3 integration). ## Version compatibility -All twelve packages ship in lockstep during the `0.x` line โ€” each integration +All fourteen packages ship in lockstep during the `0.x` line โ€” each integration package's dependency on `Compono` is exact-pinned at pack time, so mixing versions across packages (e.g. `Compono.XunitV3 0.3.0` with `Compono 0.5.0`) is not supported and will fail to restore. Always update all diff --git a/docs/plans/0074-compono-metrics-testing-support-impl-plan.md b/docs/plans/0074-compono-metrics-testing-support-impl-plan.md new file mode 100644 index 00000000..1e118b3c --- /dev/null +++ b/docs/plans/0074-compono-metrics-testing-support-impl-plan.md @@ -0,0 +1,380 @@ +# [PLAN-0074] `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support (Issue #165) + +**Status:** In Progress + +**Implements:** [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) +(issue [#165](https://github.com/LayeredCraft/compono/issues/165), child of +[#161](https://github.com/LayeredCraft/compono/issues/161)). ADR-0072 is +**Accepted** (product-owner final review, 2026-11-11), and so is this plan. +The design is approved. Implementation phases B1โ€“B6 are complete and +independently reviewed with follow-up corrections applied (see +`## Notes`); the change is uncommitted on `docs/165-metrics-planning`, +awaiting the single combined PR. + +## Goal + +A test can write `builder.UseMetrics()`, take `[Shared] IMeterFactory meters` +next to a SUT that records metrics, dispose it with `using var _ = meters;`, +and assert `meters.Verify("shop.orders.placed").WithTag("region", "eu").Once()`. +Measurements are isolated per factory, observable instruments poll only on +`RecordObservableInstruments()`, and the package has no dependency beyond +core `Compono`. It builds and tests on `net8.0`โ€“`net11.0`, packs, +package-validates, and passes the CI Native AOT smoke test (net10.0, +linux-x64). It ships with a package guide, a host recipe, one BasicUsage +sample, the API reference, and `compono` skill coverage. + +## Scope + +**In:** everything in ADR-0072's Decision Outcome. + +**Out (do not build):** everything in ADR-0072's "Explicit non-goals", plus: + +- Any change to core `Compono`, `Compono.Generators`, or any other `src/` + package. If implementation finds that core needs a change, stop and + raise it. It's a design question, not an implementation detail. +- Any `PackageReference` in `src/Compono.Metrics`. +- Any ownership/disposal API (ADR-0072 "Disposal patterns" is + documentation only). +- A new public exception type (conflicts use `InvalidOperationException`). +- Extending the CI AOT smoke matrix beyond its existing net10.0/linux-x64 + shape. +- Package version bumps and NuGet publishing (release-owner action). + +**Release:** ships in the #161 release, **v1.4.0**, alongside #164. + +**Delivery (D8, revised):** the maintainer decided the feature ships in **one +combined PR**. The planning artifacts (RESEARCH-0039, ADR-0072 `Accepted`, +this plan) travel on the same branch as the implementation (B1โ€“B6); there is +no separate planning-only PR and no planning-PR merge gate. The combined PR +also carries the `docs/plans/README.md` and `docs/adr/README.md` rows. + +**Dogfood:** optional per repo policy (2026-11-04). Not planned. In-repo +pack-and-consume and the AOT smoke test cover the integration risk. + +## Decisions already made (do not reopen during implementation) + +From the maintainer interview and review (2026-11-11), recorded in ADR-0072: + +| # | Decision | +|---|---| +| D1 | New package `Compono.Metrics`, no external dependency. | +| D2 | The composed `CapturingMeterFactory` is the handle (`[Shared] IMeterFactory`, extension methods). | +| D3 | One lazy `MeterListener` per factory, scope-filtered, disposed with the factory. No static state. | +| D4 | Typed reads: `CapturedMeasurement` (plain `readonly struct`), `GetMeasurements`, `Verify`. | +| D5 | Selection follows ADR-0072's seven ordered rules: unsupported `T` โ†’ `ArgumentException`; unknown name โ†’ empty; ambiguous meter names โ†’ throw; **mixed value types โ†’ type-conflict throw, even if one is `T`**; single other type โ†’ mismatch throw; otherwise merge. | +| D6 | Observable instruments poll only on explicit `RecordObservableInstruments()`. | +| D7 | `Verify` filters (`WithValue`, `WithTag`, `WithoutTag`, `Matching`) + `CallVerifier` counts. No aggregate helpers. | +| D8 | Docs PR first, then one implementation PR. | +| D9 | Host/DI path is a documentation recipe only. | +| D10 | `Meter` parameters aren't composed (documented recipe). | +| D11 | No wait API. No timestamp. Tag match is subset + `object.Equals`, no coercion. | +| D12 | Precedence is registration order (ADR-0024), documented. No generator exclusion. | +| D13 | Names are ordinal, case-sensitive. Type names: `CapturingMeterFactory`, `CapturedMeasurement`, `MeterFactoryTestingExtensions`, `MeasurementVerificationBuilder`. | +| D14 | Disposal is test-owned, through the three documented patterns. No ownership API. | +| D15 | Capture order is insertion order into the synchronized buffer. The sequence number is assigned under the append's lock. No cross-producer chronology. | +| D16 | Snapshots hold the real `Instrument`/`Meter` references and stay valid after disposal. | +| D17 | Release v1.4.0. One focused BasicUsage sample. | +| D18 | An unsupported `T` throws `ArgumentException`. The message names the requested type and lists the seven supported types. | +| D19 | The v1 limitation is accepted: same-named instruments with conflicting value types in same-named meters can't be read. No version or tag selectors. | +| D20 | `InvalidOperationException` for ambiguity, type conflicts, type mismatch, and misuse. No custom exception hierarchy. | +| D21 | Native AOT matrix as documented: analyzers on net8.0โ€“net11.0, CI publish-and-run on net10.0 linux-x64 only. | + +## Phases + +### B0 โ€” Acceptance (Done: design accepted) + +- [x] Product-owner review of RESEARCH-0039, ADR-0072, and this plan. + Refinements applied (2026-11-11). +- [x] Final review of the refinements. ADR-0072 `Status: Accepted`, and its + `docs/adr/README.md` row updated (2026-11-11). +- [x] Delivery revised (2026-11-11): the planning artifacts + (RESEARCH-0039, ADR-0072, PLAN-0074, both index rows, and the stale + PLAN-0072 row in `docs/plans/README.md` corrected to `Done`) land in + the **single combined PR** with the implementation, not a separate + planning-only PR. The obsolete planning-PR merge gate is removed. + +### B1 โ€” Package skeleton and factory (Done) + +- [x] `src/Compono.Metrics/Compono.Metrics.csproj`: TFMs + `net8.0;net9.0;net10.0;net11.0`, `IsAotCompatible=true`, + `ProjectReference` to `Compono` with the exact-version pin target + (copy `Compono.Logging.csproj`'s), `InternalsVisibleTo` the test + project. No `PackageReference`. +- [x] Add it to `Compono.slnx`. +- [x] `CapturingMeterFactory`: `DefaultMeterFactory` parity (null, + foreign-scope, and disposed checks; options copy; meter cache by name + + version + order-insensitive tags), lazy listener, idempotent + thread-safe `Dispose` (meters, then listener). +- [x] `MetricsProvider` (internal, stage 6, `typeof(IMeterFactory)` only) + and `UseMetrics()`. + +### B2 โ€” Capture, selection, verification (Done) + +- [x] Typed per-instrument buffers as listener state. Seven numeric + callbacks. Tag copy before taking the lock. One lock per factory. + The factory-wide sequence number is assigned in the same lock + acquisition as the append (D15). +- [x] `CapturedMeasurement` as a plain `readonly struct`. +- [x] Selection exactly per ADR-0072's seven rules, in order (D5). The + candidate set is never pre-filtered by `T`. +- [x] `MeterFactoryTestingExtensions`: `GetMeasurements` (new list per + call), `Verify` (resolves the selection when the builder is + created), `RecordObservableInstruments`, `ClearMeasurements`, misuse + `InvalidOperationException` (names `UseMetrics()`, order, host + recipe). +- [x] `MeasurementVerificationBuilder` with `LogVerificationBuilder`-style + failure messages, including the existing-instruments list on a + failed count. + +### B3 โ€” Tests (Done) + +See Test Plan. Bounded concurrency only (RESEARCH-0033). `test/Compono.Metrics.Tests` +passes on all four TFMs: net8.0 (77), net9.0 (78), net10.0 (78), net11.0 (78). + +### B4 โ€” Native AOT and packaging (Done) + +- [x] `test/Compono.Metrics.AotSmokeTest`, targeting `net10.0` only, like + every existing smoke test (copy the `Compono.Logging` layout: + `pack-compono.sh`, `nuget.config`, `verify-packaging.sh`). Exercise + composition, every instrument kind available on net10.0, observable + polling, tags, a type-conflict diagnostic, and `Verify`. +- [x] Wire `Compono.Metrics` into `.github/workflows/aot-validation.yaml` + (the `all_legs` list **and** the `src/Compono\.Metrics/` change + filter), `package-validation.yaml`, `docs.yml`, + `.github/scripts/inspect-packed-nupkgs.sh` (+ its `.tests.sh`), + `generate-api-reference.sh`, and `scripts/dogfood-validate.sh`'s + package list, following each file's `Compono.Logging` entry. +- [x] Package validation for a new package (no ApiCompat baseline yet). + Follow how the most recent new package was first validated. +- [x] The packed `.nuspec` has exactly one dependency (`Compono`, exact + version) per TFM group. +- [x] Optional, not a gate: a manual Native AOT publish of a consumer on + net8.0/net9.0/net11.0. If done, record it in Notes as evidence and + don't present it as CI coverage. + +### B5 โ€” Documentation, sample, and skill (Done) + +- [x] `docs/packages/compono-metrics.md` package guide: setup, `[Shared]`, + **disposal patterns (all three, with the "dispose after the SUT's + work is done" caveat and the undisposed-leak consequence)**, + instrument kinds, the selection rules (including type conflicts), + tag matching, observables, capture order (no cross-producer + chronology), snapshot lifetime, precedence, the `Meter` parameter + recipe, the Native AOT validation matrix as stated in ADR-0072, + non-goals, and migration from `MetricCollector`. +- [x] `docs/how-to/` recipe: assert metrics from a Generic Host + (`AddSingleton(meters)`, test-owned disposal after + the host stops). +- [x] `docs/troubleshooting/common-errors.md`: misuse, meter ambiguity, + type conflict, type mismatch, and unsupported-`T` messages. +- [x] `docs/packages/index.md`, `docs/index.md`, `README.md` package lists, + `mkdocs.yml` nav, `docs/architecture/current/provider-pipeline.md` + (stage-6 provider list). +- [x] One focused sample in `samples/Compono.Samples.BasicUsage`: a + `MetricsSampleProfile` (`UseMetrics()`), a small SUT that takes + `IMeterFactory`, and one `[Compose]` test using + `[Shared] IMeterFactory`, `using var _ = meters;`, and `Verify`. + Add the package reference the way the sample references + `Compono.Logging`. Update `docs/samples/basic-usage.md`. +- [x] Regenerate `docs/reference/api` before pushing (memory: API + reference drift). +- [x] `skills/compono/SKILL.md` detection table + `skills/compono/references/metrics.md` + (must show the disposal pattern) + evals in `skills/compono/evals/evals.json`. + +### B6 โ€” Validation gate and closeout (Done) + +- [x] `dotnet build` 0 warnings / 0 errors and `dotnet test` green on all + four TFMs. +- [x] Pack-and-consume check from a throwaway console project on a local + feed. +- [x] CI AOT smoke leg for `Compono.Metrics` green (net10.0, linux-x64, + zero IL2xxx/IL3xxx). +- [x] Plan tasks checked and validation recorded. The combined PR (D8, + revised) carries this plan and both index rows; the plan stays + `In Progress` until that PR merges, then its index row moves to + `Done`, #165 closes, and #161 is updated. + +## Critical Files + +New: + +- `src/Compono.Metrics/` โ€” `Compono.Metrics.csproj`, + `CompositionBuilderExtensions.cs`, `MetricsProvider.cs`, + `CapturingMeterFactory.cs`, `CapturedMeasurement{T}.cs`, + `MeterFactoryTestingExtensions.cs`, `MeasurementVerificationBuilder{T}.cs`, + internal capture buffer and selection types. +- `test/Compono.Metrics.Tests/`, `test/Compono.Metrics.AotSmokeTest/`. +- `docs/packages/compono-metrics.md`, a `docs/how-to/` host recipe, + `skills/compono/references/metrics.md`, `docs/reference/api/Compono.Metrics/`. +- `samples/Compono.Samples.BasicUsage/` โ€” `MetricsSampleProfile.cs`, + `MetricsTests.cs`, a small SUT type (or an addition to `Domain.cs`). + +Modified: + +- `Compono.slnx`, `.github/workflows/{aot-validation.yaml,package-validation.yaml,docs.yml}`, + `.github/scripts/{inspect-packed-nupkgs.sh,inspect-packed-nupkgs.tests.sh,generate-api-reference.sh}`, + `scripts/dogfood-validate.sh`, `mkdocs.yml`, `README.md`, + `docs/index.md`, `docs/packages/index.md`, `docs/samples/basic-usage.md`, + `docs/architecture/current/provider-pipeline.md`, + `docs/troubleshooting/common-errors.md`, `skills/compono/SKILL.md`, + `skills/compono/evals/evals.json`, + `samples/Compono.Samples.BasicUsage/Compono.Samples.BasicUsage.csproj`, + `Directory.Packages.props` (only if the sample's package-reference + pattern needs a version entry), `.gitignore` (if the AOT smoke test needs + the same entries as Logging's). +- Both index rows (`docs/adr/README.md` and `docs/plans/README.md`) travel in the single combined PR (D8, revised); there is no separate planning-only PR. + +Not modified: `src/Compono`, `src/Compono.Generators`, and every other +`src/` package. + +## Test Plan + +`test/Compono.Metrics.Tests` (xUnit v3 / MTP, all four TFMs). Each row is +an acceptance criterion for B3. + +| Area | Cases | +|---|---| +| Factory parity | null options; foreign scope throws; caller options not mutated; same name/version/tags cached (tag order irrelevant); different version โ†’ new meter; `Create` after dispose throws `ObjectDisposedException`. | +| Composition | `UseMetrics()` composes `IMeterFactory` as `CapturingMeterFactory`; `[Shared]` gives SUT and test one instance; without `[Shared]` they differ; provider ignores other types; an exact `Register` wins over `UseMetrics()`; order vs `UseNSubstitute()` (wrong order โ†’ misuse exception naming the cause). | +| Instrument kinds | `Counter`, `UpDownCounter`, `Histogram` on all TFMs; `Gauge` under `#if NET9_0_OR_GREATER`; each of the seven value types. | +| Observables | nothing recorded before poll; one poll records once; two polls โ†’ two measurements; reads don't poll; only this factory's callbacks run (two factories); throwing callback โ†’ `AggregateException` and the other callbacks are still recorded; no-op before the first `Create` and after dispose. | +| Selection (rules 1โ€“7, one test per rule) | unsupported `T` (e.g. `Guid`) โ†’ `ArgumentException` even with no instruments, and the message lists the seven supported types; null/empty names โ†’ `ArgumentException`; unknown name โ†’ empty, `Never()` passes, and a failed `Once()` lists existing instruments; different meter names with the one-argument overload โ†’ ambiguity throw, two-argument overload resolves it; **mixed types in one meter (`Counter("x")` + `Counter("x")`) โ†’ type-conflict throw for ``, ``, and ``, the message lists both instruments, and nothing is silently ignored**; mixed types across same-named meters with different versions โ†’ type-conflict throw; single other type โ†’ mismatch throw naming it; same-named meters with different versions and the same `T` โ†’ merged in capture order; `Verify` throws the conflict when the builder is created. | +| Matching | `WithValue` exact (incl. float); `WithTag` subset; `int` vs `long` doesn't match and the message shows the types; `WithoutTag`; chained filters; `Matching`; every `CallVerifier` terminal. | +| Tags | no-tag measurement โ†’ empty list (not null); tag order preserved; meter/instrument-level tags not merged; a returned `Tags` list isn't affected by later measurements. | +| Snapshot lifetime | a list returned before `ClearMeasurements()`/`Dispose()`/later captures is unchanged afterwards; after dispose `Value`, `Tags`, `Instrument.Name`, `Instrument.Meter.Name/Version` are readable and `Instrument.Enabled == false`; `Instrument` is reference-equal to the SUT's instrument. | +| Capture order | single-thread recordings across several instruments come back in program order (including a merged selection); one observable poll appends in callback order; under concurrency, sequence numbers are strictly increasing and gap-free per snapshot, with **no assertion of cross-thread chronology**. | +| Disposal patterns | pattern 1: a real `[Compose]`-style test body with `using var _ = meters;` disposes the shared factory on success **and** when an assertion throws (meters' instruments report `Enabled == false` afterwards); pattern 2: `Composer.Create` + `Register(() => meters)` captures and disposes; dispose idempotent and concurrent-safe; data readable after dispose; `ClearMeasurements` before/after dispose; recording after dispose not captured. | +| Isolation | two factories, identical meter and instrument names, running in parallel: no cross-contamination. | +| Concurrency | bounded multi-thread recording on several instruments alongside reads and clears; no lost or torn measurements (count invariant); bounded writers per RESEARCH-0033. | +| Host recipe (pattern 3) | real Generic Host (test-only `Microsoft.Extensions.Hosting`): `AddSingleton(meters)` before and after `AddMetrics()` โ†’ a SUT resolved from the host records into `meters`; the container doesn't dispose the instance; the test disposes it after the host stops. | +| Misuse | every extension method on a non-Compono `IMeterFactory` (hand-written stub) throws `InvalidOperationException`. | + +Plus the BasicUsage sample test (runs in the normal test run), the +`Compono.Metrics.AotSmokeTest` CI leg, and the pack-and-consume check (B6). + +Validation matrix (the same as ADR-0072's; only CI-backed cells are +claimed): + +| Coverage | net8.0 | net9.0 | net10.0 | net11.0 | +|---|---|---|---|---| +| Library build + trim/AOT analyzers (`IsAotCompatible`), warnings as errors | CI | CI | CI | CI | +| `Compono.Metrics.Tests` (JIT) | CI | CI | CI | CI | +| `Gauge` (sync) tests | n/a (BCL) | CI | CI | CI | +| Native AOT publish + run (`Compono.Metrics.AotSmokeTest`, linux-x64) | not covered | not covered | CI | not covered | + +Test-framework neutrality comes from core composition. No framework +adapter changes. Disposal pattern 1 is framework-independent C#. + +## Notes + +- 2026-11-11: Planning drafted from the maintainer interview. BCL facts + are in RESEARCH-0039 ยง5 (spike on SDK 11.0.100). +- 2026-11-11: Product-owner review. Disposal patterns, the type-conflict + rule, snapshot lifetime, the capture-order definition, and the explicit + AOT matrix were added. Open items resolved (D4, D13, D17; the PLAN-0072 + index fix is part of the same combined PR). One addition made while specifying selection: + an unsupported `T` throws `ArgumentException` (rule 1), so the conflict + and mismatch rules only deal with real measurement types. +- 2026-11-11: Final review. ADR-0072 and this plan accepted. D18โ€“D21 + confirmed (unsupported-`T` diagnostic, the accepted conflicting-type + limitation, `InvalidOperationException` only, the AOT matrix). + Implementation is not started. +- 2026-11-11: Implementation (B1โ€“B6) complete on `docs/165-metrics-planning`. + Evidence: + - `src/Compono.Metrics` builds with **0 warnings / 0 errors** on + net8.0โ€“net11.0 with the trim/AOT analyzers. + - `dotnet build Compono.slnx -c Debug` โ†’ Build succeeded, 0 Warning(s), + 0 Error(s). `dotnet test Compono.slnx -c Debug` โ†’ total 7403, failed 0, + succeeded 6902, skipped 501 (pre-existing platform/placeholder skips). + `Compono.Metrics.Tests` per TFM: net8.0 77, net9.0 78, net10.0 78, + net11.0 78 (net8.0 has no `Gauge`, which is `net9.0+` BCL). + - `samples/Compono.Samples.BasicUsage` (incl. the new `MetricsTests`) + โ†’ 8 tests, all passing. + - Packaged all 14 publishable packages at 1.0.0 into a temp folder and ran + `.github/scripts/inspect-packed-nupkgs.tests.sh` (all regression tests + passed) and `.github/scripts/inspect-packed-nupkgs.sh ` (all + package-contents assertions passed). `Compono.Metrics`-specific checks + confirmed: the expected file shape, `` + `Compono โ€” System.Diagnostics.Metrics Testing Support`, no `build/` or + `analyzers/`, and `Compono` pinned at the exact version per TFM group. + - Native AOT: `dotnet publish test/Compono.Metrics.AotSmokeTest -c Release + -f net10.0 -r osx-arm64 --self-contained -p:PublishAot=true` produced + zero IL2xxx/IL3xxx warnings, and the published binary ran to `PASS` + (exit 0). CI publishes the same project for linux-x64 only (ADR-0072's + matrix; not extended). + - `scripts/dogfood-validate.sh` deliberately needed no change: its + default set is the original four packages and `Compono.Logging` is + likewise absent; external dogfood is optional per repo policy. + - The implementation is left **uncommitted** on `docs/165-metrics-planning` + for independent review; no PR, push, merge, package publish, release-draft + edit, or issue close was performed. The feature ships in the single combined + PR (D8, revised); the plan stays `In Progress` until that PR merges. +- 2026-11-11: Independent review (Claude) approved the architecture and public + API and raised five follow-up corrections; all are applied and validated. + Delivery changed to **one combined PR** (D8, revised) โ€” the planning + artifacts, implementation, docs, and both index rows travel on + `docs/165-metrics-planning`; there is no separate planning-only PR and no + planning-PR merge gate. Corrections: + - **Gauge capture is TFM-independent.** `CaptureState.IsCapturedKind<T>` now + classifies with `instrument is Instrument<T> or ObservableInstrument<T>` + (both base types exist on every target), replacing the concrete-kind list + with its `#if NET9_0_OR_GREATER` `Gauge<T>` branch. A net8.0 consumer whose + runtime provides DiagnosticSource 9.x now records and verifies `Gauge<T>`. + New `GaugeCaptureTests` (3 tests) prove it on all four TFMs; the net8.0 + test assembly references `System.Diagnostics.DiagnosticSource` 9.0.0 + **test-only** (never a production `PackageReference`, per ADR-0072). + - **Meter-tag identity is a one-to-one bag match.** `TagSetsEqual` now + requires each left entry to consume a distinct right entry, so duplicate + keys are significant (`[k=1, k=1]` โ‰  `[k=1, j=2]`). This is intentionally + stricter than `DefaultMeterFactory`, whose duplicate-tag comparison is not a + true multiset comparison; the empty-tag case still allocates nothing. Three + `CapturingMeterFactoryTests` regression tests cover it + (`Create_ReturnsSameInstance_ForDuplicateKeysWithIdenticalValues`, + `Create_ReturnsDifferentInstance_ForDuplicateKeysWithDifferentSecondEntry`, + `Create_ReturnsDifferentInstance_ForDuplicateKeysWithDifferentCount`). + - **Host DI rule corrected.** A host's `HostApplicationBuilder` already + registers a default `IMeterFactory`; a test factory wins single-service + resolution by being the **last** `AddSingleton<IMeterFactory>` registration + (never `TryAddSingleton`, which keeps the existing one). The extension's + misuse message and the package guide, host recipe, and troubleshooting docs + were corrected. Three `HostRecipeTests` prove the default is present, the + later registration wins, and `TryAddSingleton` doesn't replace. + - **Verification diagnostics.** Filters join with `with`/`and`; numeric + values format with the invariant culture; a `WithTag` filter describes the + **expected** value the test passed - a string stays quoted with no + annotation, and every other non-null value shows its runtime type (e.g. + `status = 200 (int)`), so the message never implies it reports the captured + measurement's actual tag type; the unknown-instrument + suggestion is appended after the core `CallVerifier` count sentence (and + names the meter when the two-argument overload was used). `CallVerifier` + itself is unchanged, and no public API changed. + - **Regression coverage** added, each test identified by file and method: + interleaved/merged capture ordering - + `SnapshotAndDisposalTests.CaptureOrder_ForMergedSelection_OrdersByCaptureSequence_NotByMeterRegistration` + (fails if the capture-sequence sort is dropped); observable callback that + throws - + `ObservableInstrumentTests.RecordObservableInstruments_ThrowingCallback_PropagatesAggregateException_AndRecordsOthers`; + concurrent `Create`/`Dispose` - + `CapturingMeterFactoryTests.CreateAndDisposeConcurrently_DisposesSafely_AndRejectsLaterCreate`; + recording racing disposal - + `IsolationAndConcurrencyTests.RecordingWhileDisposing_DoesNotThrow_AndStopsCapturingAfterDispose`; + meaningful clear/record invariants - + `IsolationAndConcurrencyTests.ConcurrentClearAndRecord_KeepsCaptureConsistent`; + culture-invariant message formatting - + `CultureInvarianceTests.FailureMessage_FormatsNumericValueAndTagWithInvariantCulture`; + unknown meter/instrument diagnostics - + `SelectionTests.UnknownInstrumentName_NeverPasses_AndFailingOnce_ListsExistingInstruments` + and `SelectionTests.UnknownInstrumentNameInNamedMeter_ReportsTheMeterAndExistingInstruments`; + expected-tag-value type annotation - + `VerificationBuilderTests.FailureMessage_AnnotatesExpectedNonStringTagValueWithItsRuntimeType`. + Snapshot stability after disposal was already covered by the pre-existing + `SnapshotAndDisposalTests.Snapshot_StaysReadable_AfterDispose` (not + re-added). + - ADR-0072 records these as four dated Amendments; its original Decision text + is unchanged. + - Updated evidence: `Compono.Metrics.Tests` now passes **94** tests on + net9.0/net10.0/net11.0 and **93** on net8.0 (the difference is the single + in-box `Gauge<T>` test in `InstrumentCaptureTests`, `#if NET9_0_OR_GREATER`); + `HostRecipeTests` 5/5; full-solution build/test, pack-all + `inspect-packed-nupkgs.sh`, and the Native AOT publish-and-run are green + after the corrections. diff --git a/docs/plans/README.md b/docs/plans/README.md index 2d518d9d..0944d242 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -86,5 +86,6 @@ one. This file is just the mechanics: numbering, status, and the index. | [0069](0069-generator-wide-per-item-emission-failure-isolation-impl-plan.md) | Generator-Wide Per-Item Emission Failure Isolation (Issue #143) | Done | | [0070](0070-xunitv3-require-fixture-accessor-impl-plan.md) | xUnit v3 Fixture Accessor (`RequireFixture<TFixture>()`, Issue #162) | Done | | [0071](0071-xunitv3-composedata-composed-theory-rows-impl-plan.md) | xUnit v3 Composed Theory Rows (`[ComposeData]`, Issue #163) | Done | -| [0072](0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md) | `Compono.Logging` Host-Wide Log Capture (Issue #164) + .NET 11 GA Migration | In Progress | +| [0072](0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md) | `Compono.Logging` Host-Wide Log Capture (Issue #164) + .NET 11 GA Migration | Done | | [0073](0073-compono-nunit-classic-vstest-discovery-impl-plan.md) | Compono.NUnit: classic-VSTest discovery-time module initialization (Issue #171) | Done | +| [0074](0074-compono-metrics-testing-support-impl-plan.md) | `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support (Issue #165) | In Progress | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Instrument.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Instrument.md new file mode 100644 index 00000000..8ce333f8 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Instrument.md @@ -0,0 +1,18 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>') + +## CapturedMeasurement\<T\>\.Instrument Property + +The actual [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument') instance that recorded this measurement \(the one the SUT +created\)\. Through [System\.Diagnostics\.Metrics\.Instrument\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.meter 'System\.Diagnostics\.Metrics\.Instrument\.Meter') it references the +actual [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'), and through [System\.Diagnostics\.Metrics\.Meter\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter.scope 'System\.Diagnostics\.Metrics\.Meter\.Scope') the factory\. Descriptive members +\(for example [System\.Diagnostics\.Metrics\.Instrument\.Name](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.name 'System\.Diagnostics\.Metrics\.Instrument\.Name'), +[System\.Diagnostics\.Metrics\.Instrument\.Enabled](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.enabled 'System\.Diagnostics\.Metrics\.Instrument\.Enabled'), and the meter's name/version/tags\) +stay readable after the factory is disposed\. + +```csharp +public System.Diagnostics.Metrics.Instrument Instrument { get; } +``` + +#### Property Value +[System\.Diagnostics\.Metrics\.Instrument](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument 'System\.Diagnostics\.Metrics\.Instrument') \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Tags.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Tags.md new file mode 100644 index 00000000..56c2e00f --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Tags.md @@ -0,0 +1,16 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>') + +## CapturedMeasurement\<T\>\.Tags Property + +This measurement's tags, copied out of the BCL's callback span in callback order\. A per\-measurement +copy that never aliases the BCL's span or any other measurement's tags; empty \(never +[null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\) when the measurement had no tags\. Meter\-level and instrument\-level tags are +not merged in \- they're reachable through [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument')\. + +```csharp +public System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string,object?>> Tags { get; } +``` + +#### Property Value +[System\.Collections\.Generic\.IReadOnlyList<](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1')[System\.Collections\.Generic\.KeyValuePair<](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2 'System\.Collections\.Generic\.KeyValuePair\`2')[System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String')[,](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2 'System\.Collections\.Generic\.KeyValuePair\`2')[System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object')[>](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2 'System\.Collections\.Generic\.KeyValuePair\`2')[>](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1') \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Value.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Value.md new file mode 100644 index 00000000..eedf850c --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.Value.md @@ -0,0 +1,14 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>') + +## CapturedMeasurement\<T\>\.Value Property + +The recorded value, exactly as the instrument received it \(no normalization, no + aggregation\)\. + +```csharp +public T Value { get; } +``` + +#### Property Value +[T](Compono.Metrics.CapturedMeasurement_T_.md#Compono.Metrics.CapturedMeasurement_T_.T 'Compono\.Metrics\.CapturedMeasurement\<T\>\.T') \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.md new file mode 100644 index 00000000..a58f333a --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturedMeasurement_T_.md @@ -0,0 +1,31 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') + +## CapturedMeasurement\<T\> Struct + +A single captured measurement: the recorded value, its tags, and the [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument') that +recorded it\. A plain [readonly](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/readonly')[struct](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/struct') \- deliberately not a +[record](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/record 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/record')[struct](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/struct'), so there is no synthesized value equality that +would suggest `==` compares [Tags](Compono.Metrics.CapturedMeasurement_T_.Tags.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Tags') by value; use [Value](Compono.Metrics.CapturedMeasurement_T_.Value.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Value') directly or +the [Verify<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') filter chain\. +See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md\. + +```csharp +public readonly struct CapturedMeasurement<T> + where T : struct +``` +#### Type parameters + +<a name='Compono.Metrics.CapturedMeasurement_T_.T'></a> + +`T` + +The measurement's value type \- one of the seven BCL measurement value types + \([System\.Byte](https://learn.microsoft.com/en-us/dotnet/api/system.byte 'System\.Byte'), [System\.Int16](https://learn.microsoft.com/en-us/dotnet/api/system.int16 'System\.Int16'), [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32'), [System\.Int64](https://learn.microsoft.com/en-us/dotnet/api/system.int64 'System\.Int64'), [System\.Single](https://learn.microsoft.com/en-us/dotnet/api/system.single 'System\.Single'), + [System\.Double](https://learn.microsoft.com/en-us/dotnet/api/system.double 'System\.Double'), [System\.Decimal](https://learn.microsoft.com/en-us/dotnet/api/system.decimal 'System\.Decimal')\)\. + +| Properties | | +| :--- | :--- | +| [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument') | The actual [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument') instance that recorded this measurement \(the one the SUT created\)\. Through [System\.Diagnostics\.Metrics\.Instrument\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.meter 'System\.Diagnostics\.Metrics\.Instrument\.Meter') it references the actual [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'), and through [System\.Diagnostics\.Metrics\.Meter\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter.scope 'System\.Diagnostics\.Metrics\.Meter\.Scope') the factory\. Descriptive members \(for example [System\.Diagnostics\.Metrics\.Instrument\.Name](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.name 'System\.Diagnostics\.Metrics\.Instrument\.Name'), [System\.Diagnostics\.Metrics\.Instrument\.Enabled](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.instrument.enabled 'System\.Diagnostics\.Metrics\.Instrument\.Enabled'), and the meter's name/version/tags\) stay readable after the factory is disposed\. | +| [Tags](Compono.Metrics.CapturedMeasurement_T_.Tags.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Tags') | This measurement's tags, copied out of the BCL's callback span in callback order\. A per\-measurement copy that never aliases the BCL's span or any other measurement's tags; empty \(never [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\) when the measurement had no tags\. Meter\-level and instrument\-level tags are not merged in \- they're reachable through [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument')\. | +| [Value](Compono.Metrics.CapturedMeasurement_T_.Value.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Value') | The recorded value, exactly as the instrument received it \(no normalization, no aggregation\)\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.CapturingMeterFactory().md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.CapturingMeterFactory().md new file mode 100644 index 00000000..1a91d9a7 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.CapturingMeterFactory().md @@ -0,0 +1,11 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') + +## CapturingMeterFactory\(\) Constructor + +Creates a standalone [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory'), usable with no Compono composition involved +at all\. + +```csharp +public CapturingMeterFactory(); +``` \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md new file mode 100644 index 00000000..ea17f07c --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md @@ -0,0 +1,36 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') + +## CapturingMeterFactory\.Create\(MeterOptions\) Method + +Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set +\(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same +[System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. + +```csharp +public System.Diagnostics.Metrics.Meter Create(System.Diagnostics.Metrics.MeterOptions options); +``` +#### Parameters + +<a name='Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).options'></a> + +`options` [System\.Diagnostics\.Metrics\.MeterOptions](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions 'System\.Diagnostics\.Metrics\.MeterOptions') + +The meter options\. + +Implements [Create\(MeterOptions\)](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory.create#system-diagnostics-metrics-imeterfactory-create(system-diagnostics-metrics-meteroptions) 'System\.Diagnostics\.Metrics\.IMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') + +#### Returns +[System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[options](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md#Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).options 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)\.options') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[options](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md#Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).options 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)\.options')'s [System\.Diagnostics\.Metrics\.MeterOptions\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions.scope 'System\.Diagnostics\.Metrics\.MeterOptions\.Scope') + is non\-[null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null') and isn't this factory\. + +[System\.ObjectDisposedException](https://learn.microsoft.com/en-us/dotnet/api/system.objectdisposedexception 'System\.ObjectDisposedException') +This factory has been disposed\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md new file mode 100644 index 00000000..ed8a219f --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md @@ -0,0 +1,15 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') + +## CapturingMeterFactory\.Dispose\(\) Method + +Disposes every meter this factory created \(raising +`MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and +thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed +meters' instruments are no longer captured\. + +```csharp +public void Dispose(); +``` + +Implements [Dispose\(\)](https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose 'System\.IDisposable\.Dispose') \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md new file mode 100644 index 00000000..83279175 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md @@ -0,0 +1,44 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') + +## CapturingMeterFactory Class + +A hand\-written, reflection\-free [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') that captures the measurements of every +instrument its meters publish into an inspectable, thread\-safe, Compono\-native model +\([CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')\)\. Directly, publicly constructible \- composing through +[UseMetrics\(this CompositionBuilder\)](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)') is not required\. See +docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md\. + +```csharp +public sealed class CapturingMeterFactory : System.Diagnostics.Metrics.IMeterFactory, System.IDisposable +``` + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') โ†’ CapturingMeterFactory + +Implements [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory'), [System\.IDisposable](https://learn.microsoft.com/en-us/dotnet/api/system.idisposable 'System\.IDisposable') + +### Remarks + +Factory semantics match `DefaultMeterFactory`: [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') +rejects a [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')[System\.Diagnostics\.Metrics\.MeterOptions](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions 'System\.Diagnostics\.Metrics\.MeterOptions') and a foreign [System\.Diagnostics\.Metrics\.MeterOptions\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions.scope 'System\.Diagnostics\.Metrics\.MeterOptions\.Scope'), +throws [System\.ObjectDisposedException](https://learn.microsoft.com/en-us/dotnet/api/system.objectdisposedexception 'System\.ObjectDisposedException') after disposal, never mutates the caller's options, and caches +meters by name, version, and order-insensitive tag set. + +Each factory owns one lazily created [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener'), created on the first [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') +and disposed with the factory. It enables only instruments whose [System\.Diagnostics\.Metrics\.Meter\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter.scope 'System\.Diagnostics\.Metrics\.Meter\.Scope') is this factory, +so two factories never see each other's measurements even for identical meter and instrument names. There +is no static or shared capture state. + +Disposal is the test's responsibility ([System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') already extends +[System\.IDisposable](https://learn.microsoft.com/en-us/dotnet/api/system.idisposable 'System\.IDisposable')); composition never disposes the factory. An undisposed factory that created +meters stays referenced by the BCL's static meter list for the process lifetime - the same cost as an +undisposed `DefaultMeterFactory`. + +| Constructors | | +| :--- | :--- | +| [CapturingMeterFactory\(\)](Compono.Metrics.CapturingMeterFactory.CapturingMeterFactory().md 'Compono\.Metrics\.CapturingMeterFactory\.CapturingMeterFactory\(\)') | Creates a standalone [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory'), usable with no Compono composition involved at all\. | + +| Methods | | +| :--- | :--- | +| [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') | Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set \(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. | +| [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') | Disposes every meter this factory created \(raising `MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed meters' instruments are no longer captured\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md new file mode 100644 index 00000000..d67da9b2 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md @@ -0,0 +1,36 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[CompositionBuilderExtensions](Compono.Metrics.CompositionBuilderExtensions.md 'Compono\.Metrics\.CompositionBuilderExtensions') + +## CompositionBuilderExtensions\.UseMetrics\(this CompositionBuilder\) Method + +Registers a stage\-6 test\-double provider \(`Compono.Metrics.MetricsProvider`\) so a bare +[System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') composes as a new +[CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') per request\. + +```csharp +public static Compono.CompositionBuilder UseMetrics(this Compono.CompositionBuilder builder); +``` +#### Parameters + +<a name='Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).builder'></a> + +`builder` [CompositionBuilder](../Compono/Compono.CompositionBuilder.md 'Compono\.CompositionBuilder') + +The builder to register into\. + +#### Returns +[CompositionBuilder](../Compono/Compono.CompositionBuilder.md 'Compono\.CompositionBuilder') +The same [builder](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md#Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).builder 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)\.builder'), for chaining\. + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[builder](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md#Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).builder 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)\.builder') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. + +### Remarks +Register this \<b\>before\</b\>`UseNSubstitute()` if +[System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') should resolve through Compono\.Metrics rather +than an NSubstitute substitute \- Compono's stage\-6 providers resolve in registration order +\(first\-registered\-wins\), an existing, documented, `Accepted` pattern \(ADR\-0024\) this package +follows rather than replacing\. An exact `Register<IMeterFactory>(...)` always wins over +`UseMetrics()` regardless of order\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.md new file mode 100644 index 00000000..46f20839 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CompositionBuilderExtensions.md @@ -0,0 +1,16 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') + +## CompositionBuilderExtensions Class + +Registers [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') support into a [CompositionBuilder](../Compono/Compono.CompositionBuilder.md 'Compono\.CompositionBuilder')\. + +```csharp +public static class CompositionBuilderExtensions +``` + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') โ†’ CompositionBuilderExtensions + +| Methods | | +| :--- | :--- | +| [UseMetrics\(this CompositionBuilder\)](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)') | Registers a stage\-6 test\-double provider \(`Compono.Metrics.MetricsProvider`\) so a bare [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') composes as a new [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') per request\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md new file mode 100644 index 00000000..a25b750b --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md @@ -0,0 +1,21 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.AtLeast\(int\) Method + +Asserts the accumulated filters matched at least [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtLeast\(int\)\.times') times\. + +```csharp +public void AtLeast(int times); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).times'></a> + +`times` [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32') + +#### Exceptions + +[TestDoubleVerificationException](../Compono/Compono.TestDoubleVerificationException.md 'Compono\.TestDoubleVerificationException') +The filters matched fewer than + [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtLeast\(int\)\.times') times\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md new file mode 100644 index 00000000..ff629799 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md @@ -0,0 +1,21 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.AtMost\(int\) Method + +Asserts the accumulated filters matched at most [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtMost\(int\)\.times') times\. + +```csharp +public void AtMost(int times); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).times'></a> + +`times` [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32') + +#### Exceptions + +[TestDoubleVerificationException](../Compono/Compono.TestDoubleVerificationException.md 'Compono\.TestDoubleVerificationException') +The filters matched more than + [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtMost\(int\)\.times') times\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md new file mode 100644 index 00000000..30c4d9c2 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md @@ -0,0 +1,21 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.Exactly\(int\) Method + +Asserts the accumulated filters matched exactly [times](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)\.times') times\. + +```csharp +public void Exactly(int times); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).times'></a> + +`times` [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32') + +#### Exceptions + +[TestDoubleVerificationException](../Compono/Compono.TestDoubleVerificationException.md 'Compono\.TestDoubleVerificationException') +The filters did not match exactly + [times](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)\.times') times\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md new file mode 100644 index 00000000..7673b246 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md @@ -0,0 +1,25 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.Matching\(Func\<CapturedMeasurement\<T\>,bool\>\) Method + +Restricts matches to measurements satisfying an arbitrary [predicate](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).predicate 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)\.predicate') \- the + escape hatch for anything the named filters above don't cover \(an exact tag\-set match, a tolerance, and + so on\)\. + +```csharp +public Compono.Metrics.MeasurementVerificationBuilder<T> Matching(System.Func<Compono.Metrics.CapturedMeasurement<T>,bool> predicate); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).predicate'></a> + +`predicate` [System\.Func<](https://learn.microsoft.com/en-us/dotnet/api/system.func-2 'System\.Func\`2')[Compono\.Metrics\.CapturedMeasurement<](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T')[>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[,](https://learn.microsoft.com/en-us/dotnet/api/system.func-2 'System\.Func\`2')[System\.Boolean](https://learn.microsoft.com/en-us/dotnet/api/system.boolean 'System\.Boolean')[>](https://learn.microsoft.com/en-us/dotnet/api/system.func-2 'System\.Func\`2') + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[predicate](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).predicate 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)\.predicate') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md new file mode 100644 index 00000000..455c5291 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md @@ -0,0 +1,15 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.Never\(\) Method + +Asserts the accumulated filters never matched\. + +```csharp +public void Never(); +``` + +#### Exceptions + +[TestDoubleVerificationException](../Compono/Compono.TestDoubleVerificationException.md 'Compono\.TestDoubleVerificationException') +The filters matched at least once\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md new file mode 100644 index 00000000..b1bab198 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md @@ -0,0 +1,15 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.Once\(\) Method + +Asserts the accumulated filters matched exactly once\. + +```csharp +public void Once(); +``` + +#### Exceptions + +[TestDoubleVerificationException](../Compono/Compono.TestDoubleVerificationException.md 'Compono\.TestDoubleVerificationException') +The filters did not match exactly once\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md new file mode 100644 index 00000000..1e6db5b7 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md @@ -0,0 +1,30 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.WithTag\(string, object\) Method + +Restricts matches to measurements that contain a tag with key [key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithTag\(string, object\)\.key') \(ordinal\) + whose value satisfies [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)')\. Other tags are ignored, and there is + no numeric coercion \(`200`, an [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32'), doesn't match `200L`\)\. Chain calls for + several tags\. + +```csharp +public Compono.Metrics.MeasurementVerificationBuilder<T> WithTag(string key, object? value); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).key'></a> + +`key` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).value'></a> + +`value` [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithTag\(string, object\)\.key') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md new file mode 100644 index 00000000..f95503d4 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md @@ -0,0 +1,20 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.WithValue\(T\) Method + +Restricts matches to measurements whose value equals [value](Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).value 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithValue\(T\)\.value') exactly, using + [System\.Collections\.Generic\.EqualityComparer<>\.Default](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.equalitycomparer-1.default 'System\.Collections\.Generic\.EqualityComparer\`1\.Default')\. Floating\-point equality is exact \- use + [Matching\(Func<CapturedMeasurement<T>,bool>\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)') for a tolerance\. + +```csharp +public Compono.Metrics.MeasurementVerificationBuilder<T> WithValue(T value); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).value'></a> + +`value` [T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T') + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md new file mode 100644 index 00000000..b1f333d7 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md @@ -0,0 +1,23 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +## MeasurementVerificationBuilder\<T\>\.WithoutTag\(string\) Method + +Restricts matches to measurements that have no tag with key [key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithoutTag\(string\)\.key') \(ordinal\)\. + +```csharp +public Compono.Metrics.MeasurementVerificationBuilder<T> WithoutTag(string key); +``` +#### Parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).key'></a> + +`key` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeasurementVerificationBuilder_T_.md#Compono.Metrics.MeasurementVerificationBuilder_T_.T 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithoutTag\(string\)\.key') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.md new file mode 100644 index 00000000..8e0c8f60 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeasurementVerificationBuilder_T_.md @@ -0,0 +1,37 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') + +## MeasurementVerificationBuilder\<T\> Class + +A fluent filter chain over a resolved selection of captured measurements, ending in a thin, one\-line +forwarder to core [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') \- [Once\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Once\(\)')/[Never\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Never\(\)')/[Exactly\(int\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)') +each build a [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') from the filtered match count right here and call the corresponding +member\. [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') itself is never part of this type's public surface, and no new +counting/`Times` abstraction is introduced\. See +docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md ยง"Selection and matching"\. + +```csharp +public sealed class MeasurementVerificationBuilder<T> + where T : struct +``` +#### Type parameters + +<a name='Compono.Metrics.MeasurementVerificationBuilder_T_.T'></a> + +`T` + +The measurement value type \- one of the seven supported types\. + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') โ†’ MeasurementVerificationBuilder\<T\> + +| Methods | | +| :--- | :--- | +| [AtLeast\(int\)](Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtLeast\(int\)') | Asserts the accumulated filters matched at least [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtLeast(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtLeast\(int\)\.times') times\. | +| [AtMost\(int\)](Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtMost\(int\)') | Asserts the accumulated filters matched at most [times](Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.AtMost(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.AtMost\(int\)\.times') times\. | +| [Exactly\(int\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)') | Asserts the accumulated filters matched exactly [times](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).times 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)\.times') times\. | +| [Matching\(Func<CapturedMeasurement<T>,bool>\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)') | Restricts matches to measurements satisfying an arbitrary [predicate](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md#Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).predicate 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)\.predicate') \- the escape hatch for anything the named filters above don't cover \(an exact tag\-set match, a tolerance, and so on\)\. | +| [Never\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Never\(\)') | Asserts the accumulated filters never matched\. | +| [Once\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Once\(\)') | Asserts the accumulated filters matched exactly once\. | +| [WithoutTag\(string\)](Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithoutTag\(string\)') | Restricts matches to measurements that have no tag with key [key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithoutTag(string).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithoutTag\(string\)\.key') \(ordinal\)\. | +| [WithTag\(string, object\)](Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithTag\(string, object\)') | Restricts matches to measurements that contain a tag with key [key](Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithTag(string,object).key 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithTag\(string, object\)\.key') \(ordinal\) whose value satisfies [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)')\. Other tags are ignored, and there is no numeric coercion \(`200`, an [System\.Int32](https://learn.microsoft.com/en-us/dotnet/api/system.int32 'System\.Int32'), doesn't match `200L`\)\. Chain calls for several tags\. | +| [WithValue\(T\)](Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithValue\(T\)') | Restricts matches to measurements whose value equals [value](Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).md#Compono.Metrics.MeasurementVerificationBuilder_T_.WithValue(T).value 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.WithValue\(T\)\.value') exactly, using [System\.Collections\.Generic\.EqualityComparer<>\.Default](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.equalitycomparer-1.default 'System\.Collections\.Generic\.EqualityComparer\`1\.Default')\. Floating\-point equality is exact \- use [Matching\(Func<CapturedMeasurement<T>,bool>\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Matching(System.Func_Compono.Metrics.CapturedMeasurement_T_,bool_).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Matching\(System\.Func\<Compono\.Metrics\.CapturedMeasurement\<T\>,bool\>\)') for a tolerance\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md new file mode 100644 index 00000000..071df046 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md @@ -0,0 +1,24 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeterFactoryTestingExtensions](Compono.Metrics.MeterFactoryTestingExtensions.md 'Compono\.Metrics\.MeterFactoryTestingExtensions') + +## MeterFactoryTestingExtensions\.ClearMeasurements\(this IMeterFactory\) Method + +Discards every measurement captured by [factory](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md#Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)\.factory') so far\. Works before and + after disposal\. + +```csharp +public static void ClearMeasurements(this System.Diagnostics.Metrics.IMeterFactory factory); +``` +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md#Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md new file mode 100644 index 00000000..40645a5e --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md @@ -0,0 +1,108 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeterFactoryTestingExtensions](Compono.Metrics.MeterFactoryTestingExtensions.md 'Compono\.Metrics\.MeterFactoryTestingExtensions') + +## MeterFactoryTestingExtensions\.GetMeasurements Method + +| Overloads | | +| :--- | :--- | +| [GetMeasurements<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') | Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.instrumentName'), across every meter, merged in capture order \(ADR\-0072 selection rule 7\)\. A new list is returned on each call; later captures, [ClearMeasurements\(this IMeterFactory\)](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)'), and [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') never change a list already returned\. | +| [GetMeasurements<T>\(this IMeterFactory, string, string\)](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)') | Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.instrumentName') in the meter named [meterName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.meterName'), merged in capture order\. A new list is returned on each call\. | + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string)'></a> + +## MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this IMeterFactory, string\) Method + +Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.instrumentName'), across every +meter, merged in capture order \(ADR\-0072 selection rule 7\)\. A new list is returned on each call; +later captures, [ClearMeasurements\(this IMeterFactory\)](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)'), and [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') never +change a list already returned\. + +```csharp +public static System.Collections.Generic.IReadOnlyList<Compono.Metrics.CapturedMeasurement<T>> GetMeasurements<T>(this System.Diagnostics.Metrics.IMeterFactory factory, string instrumentName) + where T : struct; +``` +#### Type parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T'></a> + +`T` + +The measurement value type \- one of the seven supported types\. +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName'></a> + +`instrumentName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The instrument name to match \(ordinal, case\-sensitive\)\. + +#### Returns +[System\.Collections\.Generic\.IReadOnlyList<](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1')[Compono\.Metrics\.CapturedMeasurement<](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[T](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.T')[>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[>](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1') + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')\. + +[System\.ArgumentException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentexception 'System\.ArgumentException') +[instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.instrumentName') is null or empty; or + [T](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.T') is not one of the seven supported measurement value types\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string)'></a> + +## MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this IMeterFactory, string, string\) Method + +Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.instrumentName') in the meter named +[meterName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.meterName'), merged in capture order\. A new list is returned on each call\. + +```csharp +public static System.Collections.Generic.IReadOnlyList<Compono.Metrics.CapturedMeasurement<T>> GetMeasurements<T>(this System.Diagnostics.Metrics.IMeterFactory factory, string meterName, string instrumentName) + where T : struct; +``` +#### Type parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T'></a> + +`T` + +The measurement value type \- one of the seven supported types\. +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName'></a> + +`meterName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The meter name to match \(ordinal, case\-sensitive\)\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName'></a> + +`instrumentName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The instrument name to match \(ordinal, case\-sensitive\)\. + +#### Returns +[System\.Collections\.Generic\.IReadOnlyList<](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1')[Compono\.Metrics\.CapturedMeasurement<](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[T](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.T')[>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')[>](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1') + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')\. + +[System\.ArgumentException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentexception 'System\.ArgumentException') +[meterName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.meterName') or [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.instrumentName') + is null or empty; or [T](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.T') is not one of the seven supported measurement value + types\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md new file mode 100644 index 00000000..e4c68cc9 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md @@ -0,0 +1,27 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeterFactoryTestingExtensions](Compono.Metrics.MeterFactoryTestingExtensions.md 'Compono\.Metrics\.MeterFactoryTestingExtensions') + +## MeterFactoryTestingExtensions\.RecordObservableInstruments\(this IMeterFactory\) Method + +Polls this factory's observable instruments: calls this factory's listener's +[System\.Diagnostics\.Metrics\.MeterListener\.RecordObservableInstruments](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener.recordobservableinstruments 'System\.Diagnostics\.Metrics\.MeterListener\.RecordObservableInstruments')\. Callbacks run synchronously on the calling +thread and only for this factory's observable instruments; each observation appends measurements, so +calling it twice records twice\. Reads never poll\. A no\-op before the first +[Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') or after disposal\. + +```csharp +public static void RecordObservableInstruments(this System.Diagnostics.Metrics.IMeterFactory factory); +``` +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md#Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.RecordObservableInstruments\(this System\.Diagnostics\.Metrics\.IMeterFactory\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.Verify.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.Verify.md new file mode 100644 index 00000000..34a42cf5 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.Verify.md @@ -0,0 +1,111 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics').[MeterFactoryTestingExtensions](Compono.Metrics.MeterFactoryTestingExtensions.md 'Compono\.Metrics\.MeterFactoryTestingExtensions') + +## MeterFactoryTestingExtensions\.Verify Method + +| Overloads | | +| :--- | :--- | +| [Verify<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') | The entry point for fluent verification, for example `meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").Once()`\. The selection is resolved here, when the builder is created, so a meter ambiguity, type conflict, or type mismatch throws before any filter is added\. | +| [Verify<T>\(this IMeterFactory, string, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)') | The entry point for fluent verification scoped to one meter name\. The selection is resolved here, when the builder is created\. | + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string)'></a> + +## MeterFactoryTestingExtensions\.Verify\<T\>\(this IMeterFactory, string\) Method + +The entry point for fluent verification, for example +`meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").Once()`\. The selection is +resolved here, when the builder is created, so a meter ambiguity, type conflict, or type mismatch +throws before any filter is added\. + +```csharp +public static Compono.Metrics.MeasurementVerificationBuilder<T> Verify<T>(this System.Diagnostics.Metrics.IMeterFactory factory, string instrumentName) + where T : struct; +``` +#### Type parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T'></a> + +`T` + +The measurement value type \- one of the seven supported types\. +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName'></a> + +`instrumentName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The instrument name to match \(ordinal, case\-sensitive\)\. + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory'); the name matches instruments in more than one meter; the name + matches instruments that record more than one value type; or the matching instruments record a type + other than [T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.T')\. + +[System\.ArgumentException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentexception 'System\.ArgumentException') +[instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.instrumentName') is null or empty; or + [T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.T') is not one of the seven supported measurement value types\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string)'></a> + +## MeterFactoryTestingExtensions\.Verify\<T\>\(this IMeterFactory, string, string\) Method + +The entry point for fluent verification scoped to one meter name\. The selection is resolved here, when +the builder is created\. + +```csharp +public static Compono.Metrics.MeasurementVerificationBuilder<T> Verify<T>(this System.Diagnostics.Metrics.IMeterFactory factory, string meterName, string instrumentName) + where T : struct; +``` +#### Type parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T'></a> + +`T` + +The measurement value type \- one of the seven supported types\. +#### Parameters + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).factory'></a> + +`factory` [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') + +The capturing factory\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName'></a> + +`meterName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The meter name to match \(ordinal, case\-sensitive\)\. + +<a name='Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName'></a> + +`instrumentName` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +The instrument name to match \(ordinal, case\-sensitive\)\. + +#### Returns +[Compono\.Metrics\.MeasurementVerificationBuilder<](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>')[T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.T')[>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') + +#### Exceptions + +[System\.InvalidOperationException](https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception 'System\.InvalidOperationException') +[factory](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.factory') is not a + [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory'); the name matches instruments that record more than one value type; + or the matching instruments record a type other than [T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.T')\. + +[System\.ArgumentException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentexception 'System\.ArgumentException') +[meterName](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.meterName') or [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.instrumentName') + is null or empty; or [T](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).T 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.T') is not one of the seven supported measurement value + types\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.md new file mode 100644 index 00000000..d70c666e --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.MeterFactoryTestingExtensions.md @@ -0,0 +1,28 @@ +#### [Compono\.Metrics](index.md 'index') +### [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') + +## MeterFactoryTestingExtensions Class + +Direct inspection and fluent verification over any [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') \- no assertion framework +required\. Every method here requires the [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') it's called on to actually be a +[CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') \(produced by [UseMetrics\(this CompositionBuilder\)](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)'), or +directly via [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')'s public constructor\) \- calling any of these against a +substitute, a `Compono.TestDoubles`\-generated double, `DefaultMeterFactory`, +or any other non\-Compono [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') throws immediately, diagnostically, rather than +returning an empty/default result\. See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md's +"Precedence and misuse" section\. + +```csharp +public static class MeterFactoryTestingExtensions +``` + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') โ†’ MeterFactoryTestingExtensions + +| Methods | | +| :--- | :--- | +| [ClearMeasurements\(this IMeterFactory\)](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)') | Discards every measurement captured by [factory](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md#Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).factory 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)\.factory') so far\. Works before and after disposal\. | +| [GetMeasurements<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') | Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)\.instrumentName'), across every meter, merged in capture order \(ADR\-0072 selection rule 7\)\. A new list is returned on each call; later captures, [ClearMeasurements\(this IMeterFactory\)](Compono.Metrics.MeterFactoryTestingExtensions.ClearMeasurements(thisSystem.Diagnostics.Metrics.IMeterFactory).md 'Compono\.Metrics\.MeterFactoryTestingExtensions\.ClearMeasurements\(this System\.Diagnostics\.Metrics\.IMeterFactory\)'), and [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') never change a list already returned\. | +| [GetMeasurements<T>\(this IMeterFactory, string, string\)](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)') | Every measurement captured for instruments named [instrumentName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).instrumentName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.instrumentName') in the meter named [meterName](Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements.md#Compono.Metrics.MeterFactoryTestingExtensions.GetMeasurements_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string).meterName 'Compono\.Metrics\.MeterFactoryTestingExtensions\.GetMeasurements\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)\.meterName'), merged in capture order\. A new list is returned on each call\. | +| [RecordObservableInstruments\(this IMeterFactory\)](Compono.Metrics.MeterFactoryTestingExtensions.RecordObservableInstruments(thisSystem.Diagnostics.Metrics.IMeterFactory).md 'Compono\.Metrics\.MeterFactoryTestingExtensions\.RecordObservableInstruments\(this System\.Diagnostics\.Metrics\.IMeterFactory\)') | Polls this factory's observable instruments: calls this factory's listener's [System\.Diagnostics\.Metrics\.MeterListener\.RecordObservableInstruments](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener.recordobservableinstruments 'System\.Diagnostics\.Metrics\.MeterListener\.RecordObservableInstruments')\. Callbacks run synchronously on the calling thread and only for this factory's observable instruments; each observation appends measurements, so calling it twice records twice\. Reads never poll\. A no\-op before the first [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') or after disposal\. | +| [Verify<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') | The entry point for fluent verification, for example `meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").Once()`\. The selection is resolved here, when the builder is created, so a meter ambiguity, type conflict, or type mismatch throws before any filter is added\. | +| [Verify<T>\(this IMeterFactory, string, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string, string\)') | The entry point for fluent verification scoped to one meter name\. The selection is resolved here, when the builder is created\. | diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.md new file mode 100644 index 00000000..b1d1a512 --- /dev/null +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.md @@ -0,0 +1,14 @@ +#### [Compono\.Metrics](index.md 'index') + +## Compono\.Metrics Namespace + +| Classes | | +| :--- | :--- | +| [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') | A hand\-written, reflection\-free [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') that captures the measurements of every instrument its meters publish into an inspectable, thread\-safe, Compono\-native model \([CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>')\)\. Directly, publicly constructible \- composing through [UseMetrics\(this CompositionBuilder\)](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)') is not required\. See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md\. | +| [CompositionBuilderExtensions](Compono.Metrics.CompositionBuilderExtensions.md 'Compono\.Metrics\.CompositionBuilderExtensions') | Registers [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') support into a [CompositionBuilder](../Compono/Compono.CompositionBuilder.md 'Compono\.CompositionBuilder')\. | +| [MeasurementVerificationBuilder<T>](Compono.Metrics.MeasurementVerificationBuilder_T_.md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>') | A fluent filter chain over a resolved selection of captured measurements, ending in a thin, one\-line forwarder to core [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') \- [Once\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Once().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Once\(\)')/[Never\(\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Never().md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Never\(\)')/[Exactly\(int\)](Compono.Metrics.MeasurementVerificationBuilder_T_.Exactly(int).md 'Compono\.Metrics\.MeasurementVerificationBuilder\<T\>\.Exactly\(int\)') each build a [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') from the filtered match count right here and call the corresponding member\. [CallVerifier](../Compono/Compono.CallVerifier.md 'Compono\.CallVerifier') itself is never part of this type's public surface, and no new counting/`Times` abstraction is introduced\. See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md ยง"Selection and matching"\. | +| [MeterFactoryTestingExtensions](Compono.Metrics.MeterFactoryTestingExtensions.md 'Compono\.Metrics\.MeterFactoryTestingExtensions') | Direct inspection and fluent verification over any [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') \- no assertion framework required\. Every method here requires the [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') it's called on to actually be a [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory') \(produced by [UseMetrics\(this CompositionBuilder\)](Compono.Metrics.CompositionBuilderExtensions.UseMetrics(thisCompono.CompositionBuilder).md 'Compono\.Metrics\.CompositionBuilderExtensions\.UseMetrics\(this Compono\.CompositionBuilder\)'), or directly via [CapturingMeterFactory](Compono.Metrics.CapturingMeterFactory.md 'Compono\.Metrics\.CapturingMeterFactory')'s public constructor\) \- calling any of these against a substitute, a `Compono.TestDoubles`\-generated double, `DefaultMeterFactory`, or any other non\-Compono [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.imeterfactory 'System\.Diagnostics\.Metrics\.IMeterFactory') throws immediately, diagnostically, rather than returning an empty/default result\. See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md's "Precedence and misuse" section\. | + +| Structs | | +| :--- | :--- | +| [CapturedMeasurement<T>](Compono.Metrics.CapturedMeasurement_T_.md 'Compono\.Metrics\.CapturedMeasurement\<T\>') | A single captured measurement: the recorded value, its tags, and the [Instrument](Compono.Metrics.CapturedMeasurement_T_.Instrument.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Instrument') that recorded it\. A plain [readonly](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/readonly')[struct](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/struct') \- deliberately not a [record](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/record 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/record')[struct](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/struct'), so there is no synthesized value equality that would suggest `==` compares [Tags](Compono.Metrics.CapturedMeasurement_T_.Tags.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Tags') by value; use [Value](Compono.Metrics.CapturedMeasurement_T_.Value.md 'Compono\.Metrics\.CapturedMeasurement\<T\>\.Value') directly or the [Verify<T>\(this IMeterFactory, string\)](Compono.Metrics.MeterFactoryTestingExtensions.Verify.md#Compono.Metrics.MeterFactoryTestingExtensions.Verify_T_(thisSystem.Diagnostics.Metrics.IMeterFactory,string) 'Compono\.Metrics\.MeterFactoryTestingExtensions\.Verify\<T\>\(this System\.Diagnostics\.Metrics\.IMeterFactory, string\)') filter chain\. See docs/adr/0072\-compono\-metrics\-testing\-support\-package\.md\. | diff --git a/docs/reference/api/Compono.Metrics/index.md b/docs/reference/api/Compono.Metrics/index.md new file mode 100644 index 00000000..12312f0c --- /dev/null +++ b/docs/reference/api/Compono.Metrics/index.md @@ -0,0 +1,7 @@ +#### [Compono\.Metrics](index.md 'index') + +## Compono\.Metrics Assembly + +| Namespaces | | +| :--- | :--- | +| [Compono\.Metrics](Compono.Metrics.md 'Compono\.Metrics') | | diff --git a/docs/reference/index.md b/docs/reference/index.md index 4034a9d3..2a6d4faf 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -10,7 +10,8 @@ Reference should grow into filling. member's XML doc comment, one section per publishable package: [Compono](api/Compono/index.md), [Compono.XunitV3](api/Compono.XunitV3/index.md), [Compono.NSubstitute](api/Compono.NSubstitute/index.md), - [Compono.Bogus](api/Compono.Bogus/index.md). Mechanically regenerated by + [Compono.Bogus](api/Compono.Bogus/index.md), + [Compono.Metrics](api/Compono.Metrics/index.md). Mechanically regenerated by `.github/scripts/generate-api-reference.sh` โ€” never hand-edited, the same "generated file, don't hand-patch it" discipline this repo already applies to `Compono.Generators`' own output; CI fails on drift. diff --git a/docs/research/0039-issue-165-metrics-testing-admission.md b/docs/research/0039-issue-165-metrics-testing-admission.md new file mode 100644 index 00000000..4968dfff --- /dev/null +++ b/docs/research/0039-issue-165-metrics-testing-admission.md @@ -0,0 +1,142 @@ +# RESEARCH-0039: Issue #165 Metrics Testing โ€” Capability Admission and BCL Facts + +**Status:** Complete. The product owner confirmed the admission outcome +(new `Compono.Metrics` package) in the design interview on 2026-11-11. +The decision is recorded in the Accepted +[ADR-0072](../adr/0072-compono-metrics-testing-support-package.md). + +**Governing process:** +[`docs/architecture/capability-admission.md`](../architecture/capability-admission.md). +**Trigger:** [#165](https://github.com/LayeredCraft/compono/issues/165), +child of [#161](https://github.com/LayeredCraft/compono/issues/161) (item 2). +[RESEARCH-0036](0036-issue-161-test-composition-gaps-intake.md) classified +it as a missing capability with Gate A uncertain and asked for an +admission pass before any ADR. This document is that pass. + +## 1. Concrete problem (Step 1) + +A SUT takes `IMeterFactory` and records counter, histogram, and gauge +measurements. The test needs to compose the SUT and assert the values, +instrument names, and tags it recorded. Two real consumers have the need: + +- **#161 migration** (xUnit v3, .NET 11, Compono 1.3.2): hand-written test + `IMeterFactory` in a profile, plus one `MetricCollector<T>` per + instrument from `Microsoft.Extensions.Diagnostics.Testing`. +- **`dynamodb-distributed-lock`** (RESEARCH-0015 ยง3): `Register<Meter>(...)` + with 13 `[Shared] Meter` usages and a hand-written aggregator. + +## 2. How it's solved today (Step 2) + +- **Compono:** nothing. No source or doc mentions `IMeterFactory`, + `MeterListener`, or `MetricCollector<T>`. +- **BCL:** `IMeterFactory`, `Meter`, `MeterOptions.Scope`, and + `MeterListener` are in-box on every target TFM. The default + `IMeterFactory` implementation (`DefaultMeterFactory`) is internal and + reachable only through `services.AddMetrics()` in + `Microsoft.Extensions.Diagnostics`, so a composed-only test has no + factory to use without writing one. +- **First-party testing:** `MetricCollector<T>` captures **one instrument** + per collector (constructed from an `Instrument<T>`, or from + `meterScope + meterName + instrumentName`). A SUT with N instruments + needs N collectors, each disposed. The package brings + `Microsoft.Extensions.Logging`, `Microsoft.Extensions.Telemetry.Abstractions`, + and Options packages with it. + +The workaround is therefore roughly 15 lines of factory, plus per-instrument +collector wiring in every test, plus a heavy dependency set. That is +composition ceremony that drifts per consumer, not just a long call. + +## 3. Gate A (Step 3) + +| Criterion | Verdict | Evidence | +|---|---|---| +| 1. Compono-specific value | Pass | `UseMetrics()` makes `IMeterFactory` compose with no hand-written factory. One scope-isolated handle covers every instrument the SUT creates (not one collector per instrument). It reuses the existing `[Shared]` and profile mechanisms and one verification vocabulary with `Compono.Logging`/`Compono.TestDoubles` (`CallVerifier`). | +| 2. Native ecosystem fit | Pass | Built on `IMeterFactory`'s own contract (`MeterOptions.Scope`, meter caching, `IDisposable`) and `MeterListener`. Selection is by meter and instrument name and measurement tags, which are the BCL's identity terms. `RecordObservableInstruments` keeps the BCL name. | +| 3. Meaningful abstraction | Pass (narrowly) | Collapses factory + per-instrument collectors + disposal + isolation into one composed concept. A consumer couldn't get scope-filtered, all-instrument, deterministic observable collection in an afternoon without re-deriving ยง5's facts. | +| 4. Architectural fit | Pass | Existing public stage-6 extension point (`CompositionBuilder.AddTestDoubleProvider`, as `UseLogging()` uses). Non-generic `IMeterFactory` needs no generator work. No reflection, no static state. | +| 5. Package boundary | Pass | Doesn't belong in core (core stays a composition engine; this is a test double for a specific BCL seam). Doesn't fit `Compono.Logging` (would force `Logging.Abstractions` on metrics users and misname the ecosystem). `Compono.Http` is the precedent for a zero-dependency package around an in-box BCL seam. | + +## 4. Gate B (Step 4) + +Met. Real migration evidence (#161) plus a second independent consumer +(`dynamodb-distributed-lock`), plus an explicit product-owner request +(#165 and this interview). + +**Outcome:** roadmap item โ†’ new package `Compono.Metrics` +(ADR-0072). The documentation-only alternative (a cookbook recipe with +`MetricCollector<T>`) was considered and rejected by the product owner: +it leaves the dependency set and per-instrument wiring in place. + +## 5. BCL facts (spike, 2026-11-11) + +A throwaway console app on SDK 11.0.100, `net8.0` and `net11.0`, +`IsAotCompatible=true`, no package references on `net8.0`: + +1. `IMeterFactory`, `MeterOptions.Scope`, `Meter.Scope`, and `MeterListener` + compile and run on `net8.0` from the shared framework alone. A metrics + package needs **no `PackageReference`**. +2. A factory that sets `options.Scope = this` produces meters whose + `Meter.Scope` is that factory (reference-equal). +3. Two factories each create a meter named `"Shop"` and a counter named + `"orders"`. A listener per factory that enables only instruments whose + `instrument.Meter.Scope` is its own factory sees only its own + measurements. Same-named meters don't cross-contaminate. +4. `RecordObservableInstruments()` on factory A's listener invoked A's + observable callback once and B's zero times. Scoping observable + collection per factory is deterministic. +5. `Gauge<T>` (synchronous) exists on `net9.0+` only. A listener's generic + `SetMeasurementEventCallback<T>` receives `Gauge<T>` measurements without + the listener naming the type, so the capture code needs no TFM split. +6. Disposing a factory's meters raises `MeasurementsCompleted` for each + instrument. Measurements recorded on those instruments afterwards are + not delivered. +7. `services.AddMetrics()` registers `DefaultMeterFactory` with `TryAdd`. + A test factory registered as an `IMeterFactory` singleton before + `AddMetrics()` survives, so a host path is a one-line consumer + registration. +8. Undisposed meters stay in the BCL's static meter list and keep + `Meter.Scope` (the factory) alive. That is true regardless of how the + listener is owned, so listener design can't remove the leak. Only + disposing the factory does. + +`DefaultMeterFactory` parity checks (same spike, `services.AddMetrics()`, +`Microsoft.Extensions.Diagnostics` 11.0.0, on `net8.0` and `net11.0`): + +9. `Create(options)` doesn't mutate the caller's `MeterOptions` (its + `Scope` stays `null`). It returns the **same** `Meter` for the same name + (and version and tags), and a different one when the version differs. + `Create` with a foreign non-null `options.Scope` throws + `InvalidOperationException`. `Create` after disposal throws + `ObjectDisposedException`. +10. With `DiagnosticSource` 11.x, creating the same instrument name twice + on one meter returns the same instrument instance. Older in-box + versions may return distinct instances, so selection must not assume + one instrument per name. +11. When one observable callback throws during + `MeterListener.RecordObservableInstruments()`, the other callbacks + still run and the call then throws `AggregateException` wrapping the + callback's exception. + +## 6. Prior art: adopted vs. changed + +From `MetricCollector<T>`: + +- **Adopted:** scope-based isolation (`meterScope`), typed measurements + (`CollectedMeasurement<T>`: value + tags), explicit + `RecordObservableInstruments()`, snapshot reads. +- **Changed:** one handle per factory across all instruments, not one per + instrument. No timestamp or `TimeProvider`. No + `WaitForMeasurementsAsync`. No dependency on the package (same + independence reasoning as ADR-0055 for `FakeLogger`). Verification uses + Compono's `CallVerifier` counts with filters, not a separate assertion + surface. + +## Links + +- [#165](https://github.com/LayeredCraft/compono/issues/165), + [#161](https://github.com/LayeredCraft/compono/issues/161) +- [RESEARCH-0036](0036-issue-161-test-composition-gaps-intake.md), + [RESEARCH-0015](0015-disposal-ownership-research.md) +- [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md), + [ADR-0055](../adr/0055-compono-logging-testing-support-package.md), + [ADR-0051](../adr/0051-compono-http-handler-based-testing-package.md) diff --git a/docs/samples/basic-usage.md b/docs/samples/basic-usage.md index bfdd5539..90930c03 100644 --- a/docs/samples/basic-usage.md +++ b/docs/samples/basic-usage.md @@ -27,10 +27,14 @@ deliberately not broad. Real, buildable code: `ILogger<NotificationService>`, composed via `UseLogging()`, captures what `NotificationService` actually logged, asserted with `Verify()` โ€” see the [`Compono.Logging` Package Guide](../packages/compono-logging.md). +- A `Compono.Metrics` scenario (`MetricsTests`): a `[Shared]` + `IMeterFactory`, composed via `UseMetrics()`, captures the measurements a + service records, asserted with `Verify<T>()` โ€” see the + [`Compono.Metrics` Package Guide](../packages/compono-metrics.md). ## Packages -`Compono`, `Compono.XunitV3`, `Compono.Logging`. +`Compono`, `Compono.XunitV3`, `Compono.Logging`, `Compono.Metrics`. ## Running it diff --git a/docs/samples/index.md b/docs/samples/index.md index 0deb71fa..629c601c 100644 --- a/docs/samples/index.md +++ b/docs/samples/index.md @@ -12,7 +12,7 @@ short overview linking out to it, not the code itself. | Sample | Demonstrates | Packages | |---|---|---| -| [Basic Usage](basic-usage.md) | The core workflow: `Composer.Create()`/`Create<T>()`/`CreateMany<T>()`, a reusable profile, registrations and member rules, a composed xUnit v3 theory, deterministic seed reproduction, and an `ILogger<T>` logging scenario. | `Compono`, `Compono.XunitV3`, `Compono.Logging` | +| [Basic Usage](basic-usage.md) | The core workflow: `Composer.Create()`/`Create<T>()`/`CreateMany<T>()`, a reusable profile, registrations and member rules, a composed xUnit v3 theory, deterministic seed reproduction, an `ILogger<T>` logging scenario, and an `IMeterFactory` metrics scenario. | `Compono`, `Compono.XunitV3`, `Compono.Logging`, `Compono.Metrics` | | [ASP.NET API](aspnet-api.md) | The full ecosystem in one realistic API: a `[Shared]` NSubstitute substitute injected into the system under test, `Compono.Bogus`-generated request data, inline plus composed theory values, one integration-style endpoint test, an outbound-HTTP scenario, and a DI-composed row provider. | `Compono`, `Compono.XunitV3`, `Compono.NSubstitute`, `Compono.Bogus`, `Compono.Http`, `Compono.DependencyInjection` | Both samples restore against every package in their own "Packages" row diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 10702f89..64b27900 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -360,6 +360,74 @@ and a shared fixture may clear startup entries between tests. That's the default โ€” composition is independent per parameter unless you opt in with `[Shared]`. See [Shared Values](../concepts/shared-values.md). +### "Verify metrics on a non-Compono IMeterFactory throws" + +Every method on `MeterFactoryTestingExtensions` (`GetMeasurements<T>()`, +`Verify<T>()`, `RecordObservableInstruments()`, `ClearMeasurements()`) +requires the `IMeterFactory` to be Compono's `CapturingMeterFactory`, and +throws `InvalidOperationException` otherwise. This usually means one of: + +- **`UseMetrics()` isn't registered.** Add it to the profile or + `Composer.Create` call. +- **`UseMetrics()` is registered *after* `UseNSubstitute()`.** An interface + request resolves at whichever stage-6 provider is registered first, so + `NSubstituteProvider` wins and you get a substitute. Call `UseMetrics()` + first โ€” see [Registration order and misuse](../packages/compono-metrics.md#registration-order-and-misuse). +- **The Generic Host resolved its own default factory.** The builder already + registers a default `IMeterFactory`. Register the test's factory with + `builder.Services.AddSingleton<IMeterFactory>(meters)`; the container + resolves a single `IMeterFactory` to its **last** registration, so the + later one wins. Don't use `TryAddSingleton` โ€” it keeps the first + registration and would discard yours. See + [Verify Metrics Across a Host](../how-to/verify-metrics-across-a-host.md). + +### "`Verify<long>` throws `instrument "x" records int, not long`" + +The instrument records a different numeric type than the one you asked for. +Pass the real type to `GetMeasurements<T>`/`Verify<T>`, or read the actual +type from `CapturedMeasurement<T>.Instrument`. There is no numeric coercion โ€” +`int` and `long` are distinct instruments. + +### "`Verify` throws about one selection merging measurements of different types" + +Two instruments share a name but record different value types โ€” either two +instruments in one meter (`CreateCounter<int>("x")` and +`CreateCounter<long>("x")` are distinct), or same-named meters with +different versions or tags. A single selection can't merge different types. +Rename one instrument in the SUT, or narrow with the two-argument overload +when the conflicting instruments live in differently named meters โ€” see +selection rule 5 in the +[`Compono.Metrics` Package Guide](../packages/compono-metrics.md#selection-and-matching). + +### "`Verify<long>` throws about meter ambiguity" + +The one-argument overload matched instruments from more than one meter name. +Use the two-argument overload (`GetMeasurements<T>(meterName, instrumentName)` +or `Verify<T>(meterName, instrumentName)`) to pick the meter. + +### "`GetMeasurements<Guid>` throws `ArgumentException`" + +Only the seven BCL measurement types are supported: `byte`, `short`, `int`, +`long`, `float`, `double`, `decimal`. No instrument can record any other +type, so the mistake is caught deterministically. + +### "`Never()` passes but the counter was clearly incremented" + +`Never()` passes whenever no captured measurement matches, including when the +instrument name matched nothing at all. A failing `Once()`/`Exactly(n)` lists +the instruments that *do* exist, so check that message for a typo or an +unexpected meter name. + +### "An undisposed factory leaks for the process lifetime" + +A factory that created a meter stays referenced by the BCL's static meter +list until it's disposed, keeping its meters, listener, and captured +measurements alive โ€” the same cost as an undisposed `DefaultMeterFactory`. +Dispose it at the end of the test with `using var _ = meters;` on the +`[Shared]` parameter, or one of the other two patterns in +[Disposal patterns](../packages/compono-metrics.md#disposal-patterns). A +factory that never created a meter costs nothing. + ## Next - [FAQ](faq.md) โ€” design-decision questions that aren't a specific error. diff --git a/mkdocs.yml b/mkdocs.yml index d561540b..0f9a1de6 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -133,6 +133,7 @@ nav: - Use Profiles: how-to/use-profiles.md - Share a Value Across a Test: how-to/share-a-value-across-a-test.md - Assert Nothing Logged at Error or Above Across a Host: how-to/assert-nothing-logged-at-error-across-a-host.md + - Verify Metrics Across a Host: how-to/verify-metrics-across-a-host.md - Cookbook: cookbook/index.md - Samples: - Overview: samples/index.md @@ -153,6 +154,7 @@ nav: - Compono.Logging: packages/compono-logging.md - Compono.MSTest: packages/compono-mstest.md - Compono.NUnit: packages/compono-nunit.md + - Compono.Metrics: packages/compono-metrics.md - Best Practices: - Overview: best-practices/index.md - Organizing Profiles: best-practices/organizing-profiles.md @@ -192,6 +194,7 @@ nav: - Compono.Logging: reference/api/Compono.Logging/index.md - Compono.MSTest: reference/api/Compono.MSTest/index.md - Compono.NUnit: reference/api/Compono.NUnit/index.md + - Compono.Metrics: reference/api/Compono.Metrics/index.md - Diagnostics: reference/diagnostics.md - Glossary: reference/glossary.md - Roadmap: diff --git a/samples/Compono.Samples.BasicUsage/Compono.Samples.BasicUsage.csproj b/samples/Compono.Samples.BasicUsage/Compono.Samples.BasicUsage.csproj index 312b36a9..fbce915d 100644 --- a/samples/Compono.Samples.BasicUsage/Compono.Samples.BasicUsage.csproj +++ b/samples/Compono.Samples.BasicUsage/Compono.Samples.BasicUsage.csproj @@ -44,6 +44,7 @@ <ProjectReference Include="$(MSBuildThisFileDirectory)../../src/Compono/Compono.csproj" /> <ProjectReference Include="$(MSBuildThisFileDirectory)../../src/Compono.XunitV3/Compono.XunitV3.csproj" /> <ProjectReference Include="$(MSBuildThisFileDirectory)../../src/Compono.Logging/Compono.Logging.csproj" /> + <ProjectReference Include="$(MSBuildThisFileDirectory)../../src/Compono.Metrics/Compono.Metrics.csproj" /> <ProjectReference Include="$(MSBuildThisFileDirectory)../../src/Compono.Generators/Compono.Generators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> diff --git a/samples/Compono.Samples.BasicUsage/Domain.cs b/samples/Compono.Samples.BasicUsage/Domain.cs index 412bba0f..54fc43f1 100644 --- a/samples/Compono.Samples.BasicUsage/Domain.cs +++ b/samples/Compono.Samples.BasicUsage/Domain.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; namespace Compono.Samples.BasicUsage; @@ -51,3 +52,34 @@ public void Notify(CreateOrder order) => _logger.LogInformation( "Notified {CustomerName} about their order for {Quantity} units", order.CustomerName, order.Quantity); } + +/// <summary> +/// An <see cref="IMeterFactory"/>-dependent type - the natural fit for <c>Compono.Metrics</c>'s +/// sample scenario, composed via <c>UseMetrics()</c> so the measurements it records can be asserted +/// with <c>Verify<T>()</c> instead of substituted away. +/// </summary> +public sealed class CheckoutService +{ + private readonly Counter<long> _orders; + private readonly Histogram<double> _duration; + + /// <summary> + /// Creates the meters and instruments <see cref="CheckoutService"/> records through. + /// </summary> + public CheckoutService(IMeterFactory meterFactory) + { + var meter = meterFactory.Create("Shop.Checkout"); + _orders = meter.CreateCounter<long>("shop.orders.placed"); + _duration = meter.CreateHistogram<double>("shop.orders.duration"); + } + + /// <summary> + /// Counts the placed order and records how long it took, both tagged with the region. + /// </summary> + public void Place(CreateOrder order, string region, double durationMs) + { + var tag = new KeyValuePair<string, object?>("region", region); + _orders.Add(1, tag); + _duration.Record(durationMs, tag); + } +} diff --git a/samples/Compono.Samples.BasicUsage/MetricsSampleProfile.cs b/samples/Compono.Samples.BasicUsage/MetricsSampleProfile.cs new file mode 100644 index 00000000..c37ef94c --- /dev/null +++ b/samples/Compono.Samples.BasicUsage/MetricsSampleProfile.cs @@ -0,0 +1,11 @@ +using Compono.Metrics; + +namespace Compono.Samples.BasicUsage; + +// A dedicated profile for the metrics scenario, kept separate from the others - it composes +// IMeterFactory as a CapturingMeterFactory via UseMetrics(), a different concern from the logging +// profile's ILogger<T> capture or SampleApplicationProfile's own registration/member-rule demo. +public sealed class MetricsSampleProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.UseMetrics(); +} diff --git a/samples/Compono.Samples.BasicUsage/MetricsTests.cs b/samples/Compono.Samples.BasicUsage/MetricsTests.cs new file mode 100644 index 00000000..249afaad --- /dev/null +++ b/samples/Compono.Samples.BasicUsage/MetricsTests.cs @@ -0,0 +1,28 @@ +using System.Diagnostics.Metrics; +using Compono.Metrics; +using Compono.XunitV3; + +namespace Compono.Samples.BasicUsage; + +// Compono.Metrics: UseMetrics() composes IMeterFactory as a CapturingMeterFactory - no substitute +// needed to assert the measurements CheckoutService actually recorded. [Shared] reuses the exact +// same composed factory the service's own constructor received, so the test asserts against the +// measurements the service produced. The test owns disposal via "using var _ = meters;". +public sealed class MetricsTests +{ + [Theory] + [Compose<MetricsSampleProfile>] + public void Place_RecordsAnOrderCountAndDurationForTheRegion( + [Shared] IMeterFactory meters, CheckoutService service, CreateOrder order) + { + using var _ = meters; + + service.Place(order, "eu", durationMs: 12.5); + + meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + meters.Verify<double>("shop.orders.duration").WithTag("region", "eu").Once(); + + var placed = meters.GetMeasurements<long>("shop.orders.placed"); + Assert.Equal(1, placed.Sum(measurement => measurement.Value)); + } +} diff --git a/skills/compono/SKILL.md b/skills/compono/SKILL.md index c4900461..94949ac4 100644 --- a/skills/compono/SKILL.md +++ b/skills/compono/SKILL.md @@ -6,7 +6,7 @@ description: >- (composer.Create/CreateMany, [Composable], registrations, profiles, [Shared], [ComposeData]), plus optional integration packages - (XunitV3/XunitV3.Aot/TUnit/MSTest/NUnit/NSubstitute/Bogus/TestDoubles/DependencyInjection/Http/Logging/Options). + (XunitV3/XunitV3.Aot/TUnit/MSTest/NUnit/NSubstitute/Bogus/TestDoubles/DependencyInjection/Http/Logging/Options/Metrics). USE FOR: writing/reviewing Compono tests, diagnosing CMP00xx diagnostics or CompositionException failures, deciding on [Composable]/Register/.For/[Shared]/[ComposeData], adding Compono, migrating @@ -15,7 +15,7 @@ description: >- no Compono package referenced; reflection/DI questions; production object construction. SCOPES TO: only load the matching package reference file - (xunit-v3/tunit/mstest/nunit/nsubstitute/bogus/testdoubles/dependencyinjection/http/logging/options.md) + (xunit-v3/tunit/mstest/nunit/nsubstitute/bogus/testdoubles/dependencyinjection/http/logging/options/metrics.md) when that package is referenced. license: MIT metadata: @@ -54,6 +54,7 @@ some packages and not others. | `<PackageReference Include="Compono.Http"` | `.csproj` | Definitive | `TestHttpHandler`/`OnGet`/`OnPost`/etc. available โ€” load `references/http.md` | | `<PackageReference Include="Compono.Logging"` or `UseLogging()` in `*.cs` | `.csproj`/`*.cs` | Definitive | `ILogger`/`ILogger<T>` compose via `UseLogging()`, `CapturingLogger`/`CapturingLogger<T>`, `Verify()` available; host-wide capture via `LogCollector`/`AddComponoCapture` โ€” load `references/logging.md`. Generation is on by default once the package is referenced โ€” never suggest a manual MSBuild opt-in step | | `<PackageReference Include="Compono.Options"` or `UseOptions(` in `*.cs` | `.csproj`/`*.cs` | Definitive | `TestOptionsSource<T>`/`UseOptions<T>()` available โ€” load `references/options.md` | +| `<PackageReference Include="Compono.Metrics"` or `UseMetrics()` in `*.cs` | `.csproj`/`*.cs` | Definitive | `IMeterFactory` composes via `UseMetrics()` as a `CapturingMeterFactory`, with typed `GetMeasurements<T>()`/`Verify<T>()` and explicit observable polling available โ€” load `references/metrics.md` | | `Composer.Create(`, `.Create<`, `.CreateMany<`, `CompositionBuilder` | `*.cs` | High | Core Compono API in active use | | `[Compose]`, `[Compose<...>]`, `[ComposeData]`, `[Shared]` | `*.cs` | High | `Compono.XunitV3`, `Compono.TUnit`, `Compono.MSTest`, or `Compono.NUnit` attributes in active use - check which package is referenced before assuming which | | `ICompositionProfile` implementations | `*.cs` | Medium | Profile-based configuration convention already established โ€” follow it rather than inventing a new one | @@ -72,7 +73,7 @@ if it uses TUnit, `Compono.MSTest` if it uses MSTest (`MSTest.TestFramework` 4.0.0+ only โ€” see `references/mstest.md`), `Compono.NUnit` if it uses NUnit (`NUnit` `3.14.0`+ โ€” see `references/nunit.md`, no `[TestFixture]`/ `[Test]` needed alongside `[Compose]`), `Compono.NSubstitute`/ -`Compono.Bogus` only if the user wants those). Don't retrofit existing +`Compono.Bogus`/`Compono.Metrics` only if the user wants those). Don't retrofit existing passing tests to use Compono unprompted โ€” that's a scope decision for the user to make test-by-test, not something to do as a drive-by. @@ -201,6 +202,14 @@ matcher. Call-order verification remains unsupported by either. `UseNSubstitute()`/`UseGeneratedTestDoubles()`, register `UseLogging()` first โ€” see `references/logging.md`'s registration- order note. + - A composed type takes an `IMeterFactory` dependency and the test + wants to assert the measurements it recorded (values, instrument + names, tags) โ†’ `UseMetrics()` composing a `CapturingMeterFactory`, if + `Compono.Metrics` is referenced โ€” see `references/metrics.md`. Register + `UseMetrics()` before `UseNSubstitute()`, and never suggest a + hand-rolled fake `IMeterFactory` when this package is already + referenced. Observable instruments are read only after an explicit + `RecordObservableInstruments()` call; reads never poll. - A `string` member needs a realistic value (email, name, address) โ†’ `Compono.Bogus`'s member-name conventions or `UseBogus(...)`, if that package is referenced. Don't reach for Bogus everywhere โ€” plain @@ -369,8 +378,8 @@ undermines the reason Compono exists in this project. capability."** Only `Compono`, `Compono.XunitV3`, `Compono.XunitV3.Aot`, `Compono.TUnit`, `Compono.MSTest`, `Compono.NSubstitute`, `Compono.Bogus`, `Compono.TestDoubles`, `Compono.DependencyInjection`, `Compono.Http`, - `Compono.Logging`, and `Compono.Options` ship as packages today - (`Compono.XunitV3.Aot` is the Native AOT sibling of `Compono.XunitV3` โ€” + `Compono.Logging`, `Compono.Options`, and `Compono.Metrics` ship as packages + today (`Compono.XunitV3.Aot` is the Native AOT sibling of `Compono.XunitV3` โ€” the same `[Compose]` family in namespace `Compono.XunitV3.Aot`, mutually exclusive with `Compono.XunitV3` in one project, see `references/xunit-v3.md`; `Compono.TUnit` @@ -406,7 +415,12 @@ undermines the reason Compono exists in this project. `Compono.Options` ships `TestOptionsSource<T>`/`UseOptions<T>()` โ€” a coherent `IOptions<T>`/`IOptionsSnapshot<T>`/`IOptionsMonitor<T>` source, not a plain `IConfiguration` package, and there is no - `Compono.Configuration`, see `references/options.md`) + `Compono.Configuration`, see `references/options.md`; + `Compono.Metrics` ships `UseMetrics()` and `CapturingMeterFactory` for + `System.Diagnostics.Metrics` testing โ€” typed `GetMeasurements<T>()`/ + `Verify<T>()` and explicit `RecordObservableInstruments()` polling, one + factory handle for every instrument, no dependency beyond core `Compono`, + see `references/metrics.md`) โ€” there is no `Compono.FakeItEasy` or `Compono.Moq`, and never invent a plausible-looking API for one. That doesn't always mean the underlying capability is unsupported, though: @@ -499,4 +513,5 @@ Load only what the Detection table says is relevant to the current task. | `references/http.md` | `Compono.Http` is referenced โ€” `TestHttpHandler`/matching/verification/lifetime work | | `references/logging.md` | `Compono.Logging` is referenced or `UseLogging()` is called โ€” `ILogger`/`ILogger<T>` composition, `CapturingLogger`/`CapturingLogger<T>`, structured properties, scope semantics, `Verify()`, host-wide capture (`LogCollector`/`AddComponoCapture`, `Category`, `AtLevelOrAbove`/`InCategory`, host-vs-composed boundaries), and the `ComponoGeneratedLogging` default-on/opt-out behavior | | `references/options.md` | `Compono.Options` is referenced or `UseOptions(` is called โ€” `TestOptionsSource<T>`/`UseOptions<T>()` identity model, named options, the unconfigured-name diagnostic, `IConfiguration`-vs-`Compono.Options` routing, and the Finding B boundary | +| `references/metrics.md` | `Compono.Metrics` is referenced or `UseMetrics()` is called โ€” `IMeterFactory` composition, `CapturingMeterFactory`, typed `GetMeasurements<T>()`/`Verify<T>()`, observable polling, selection/matching rules, disposal patterns, and registration-order-vs-`UseNSubstitute()` | | `references/patterns-and-antipatterns.md` | Reviewing existing Compono usage for correctness, migrating from AutoFixture, or unsure whether an approach is idiomatic | diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index 31c2b041..946af420 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -823,6 +823,45 @@ "Notes that the Generic Host default lifetime does log Microsoft.Hosting.Lifetime on StartAsync, so the category itself is not wrong", "Does not suggest the collector is broken or that Never() is unreliable when capture is correctly wired" ] + }, + { + "id": 66, + "category": "routing", + "prompt": "This class takes an IMeterFactory constructor dependency and records a counter and a histogram. The project references Compono, Compono.XunitV3, and Compono.Metrics. Write the test that asserts the recorded values.", + "expected_output": "Adds builder.UseMetrics() (typically in an ICompositionProfile), composes the SUT directly, and takes [Shared] IMeterFactory meters so the test sees the same factory the SUT used; the test disposes it with 'using var _ = meters;'. Asserts with meters.Verify<long>(\"shop.orders.placed\").WithTag(\"region\", \"eu\").WithValue(1).Once() and meters.Verify<double>(\"shop.orders.duration\").Once(), or reads via meters.GetMeasurements<T>(...) and does value math with LINQ. Never hand-rolls an IMeterFactory, never reaches for Microsoft.Extensions.Diagnostics.Testing MetricCollector<T>, and never adds an MSBuild opt-in property (none exists for Compono.Metrics).", + "files": [], + "expectations": [ + "Registers UseMetrics() (or relies on it already being registered) rather than a hand-rolled IMeterFactory or MetricCollector<T>", + "Uses [Shared] IMeterFactory so the SUT and the test share one factory, and disposes it in the test body (using var _ = meters;)", + "Verifies via meters.Verify<T>(...) with WithTag/WithValue/Once (or GetMeasurements<T> plus LINQ), not a two-verb VerifyMetrics shape", + "Does not suggest adding a Microsoft.Extensions.Diagnostics.Testing dependency or an MSBuild opt-in property for Compono.Metrics" + ] + }, + { + "id": 67, + "category": "behavioral-correctness", + "prompt": "I registered both UseNSubstitute() and UseMetrics() but the order was builder.UseNSubstitute().UseMetrics(). When my test calls meters.Verify<long>(\"shop.orders.placed\") on the composed IMeterFactory it throws InvalidOperationException saying the instance is not a Compono metrics factory. Also, do I need to set an MSBuild property so UseMetrics() generates something?", + "expected_output": "Explains the real cause: Compono's stage-6 test-double providers resolve first-registered-wins, and UseNSubstitute() was registered before UseMetrics(), so IMeterFactory resolved to an NSubstitute substitute instead of a CapturingMeterFactory - the fix is reordering to builder.UseMetrics().UseNSubstitute(). Explicitly answers the second question: no MSBuild property is needed or exists - unlike Compono.Logging/Compono.TestDoubles there is no generation opt-in for Compono.Metrics at all; the failure is registration order, not a missing opt-in.", + "files": [], + "expectations": [ + "Correctly identifies first-registered-wins stage-6 provider precedence as the cause, not a Compono.Metrics bug", + "Recommends reordering to builder.UseMetrics().UseNSubstitute() (UseMetrics first for IMeterFactory)", + "Explicitly states no MSBuild opt-in property exists or is needed for Compono.Metrics", + "Does not suggest a priority/specificity mechanism that doesn't exist" + ] + }, + { + "id": 68, + "category": "behavioral-correctness", + "prompt": "My SUT registers an ObservableGauge<int> (and an ObservableCounter<int>) against the composed IMeterFactory, but meters.Verify<int>(\"shop.queue.depth\") finds nothing and GetMeasurements<int> is empty, even though the SUT ran. What am I missing?", + "expected_output": "Observable instruments are only captured when polled: Compono reads never poll, so the test must call meters.RecordObservableInstruments() explicitly before verifying/reading (callbacks run synchronously for this factory's observables only, and the other instruments still record normally). Notes calling it twice records twice, that reads are side-effect-free snapshots, and that Compono provides no wait/timeout API (Compono.Metrics is the package; there is no auto-poll option).", + "files": [], + "expectations": [ + "Explains reads (GetMeasurements/Verify) never poll observable instruments", + "Recommends calling meters.RecordObservableInstruments() before asserting", + "States the poll runs only this factory's observable callbacks, synchronously", + "Does not suggest an auto-poll-on-read option or a wait/timeout API (neither exists)" + ] } ] } diff --git a/skills/compono/references/metrics.md b/skills/compono/references/metrics.md new file mode 100644 index 00000000..74a34230 --- /dev/null +++ b/skills/compono/references/metrics.md @@ -0,0 +1,226 @@ +# Compono.Metrics + +Only relevant if the project references `Compono.Metrics`. `UseMetrics()` +composes `IMeterFactory` as a hand-written `CapturingMeterFactory`, which +captures every measurement a SUT records, isolated per factory. Tests assert +with typed `GetMeasurements<T>()`/`Verify<T>()`. The package depends only on +core `Compono` and `System.Diagnostics.Metrics` (in-box on every target +TFM) โ€” no `PackageReference`, no reflection, Native AOT/trimming compatible. + +```csharp +using Compono; +using Compono.Metrics; +using System.Diagnostics.Metrics; + +var composer = Composer.Create(builder => builder.UseMetrics()); +var service = composer.Create<CheckoutService>(); // CheckoutService(IMeterFactory meters, ...) +``` + +```csharp +public sealed class CheckoutProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.UseMetrics(); +} + +[Theory, Compose<CheckoutProfile>] +public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, CheckoutService service) +{ + using var _ = meters; // the test owns disposal + + service.Place(new Order("eu", 3)); + + meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); +} +``` + +## When to use it + +A composed type takes an `IMeterFactory` constructor dependency and the test +wants to assert *what* it recorded โ€” instrument name, value, or tags. +Concrete signs: the test hand-rolls an `IMeterFactory`, wires one +`MetricCollector<T>` (`Microsoft.Extensions.Diagnostics.Testing`) per +instrument, or substitutes the factory away and so can't observe anything. + +## When NOT to use it + +The test doesn't care about the recorded measurements โ€” an unconfigured +`UseNSubstitute()` substitute is fine when nothing asserts against metrics. +Don't introduce `Compono.Metrics` just because a constructor happens to take +an `IMeterFactory`. + +## No generation, no MSBuild opt-in + +Unlike `Compono.Logging` (`ComponoGeneratedLogging`) and +`Compono.TestDoubles` (`ComponoGeneratedTestDoubles`), `Compono.Metrics` +ships **no generator involvement and no MSBuild property at all**. It relies +only on the in-box `System.Diagnostics.Metrics` BCL types. Never suggest a +compile-time opt-in for it โ€” there is none. + +## Core usage vocabulary + +- `builder.UseMetrics()` โ€” registers the stage-6 provider that composes + `IMeterFactory` as a new `CapturingMeterFactory` per request. An exact + `Register<IMeterFactory>(() => meters)` takes precedence. +- `new CapturingMeterFactory()` โ€” direct construction, no composition, + identical behavior to a provider-composed instance. +- `meters.GetMeasurements<T>(instrumentName)` and + `GetMeasurements<T>(meterName, instrumentName)` โ€” typed snapshot reads, + a new list each call. `T` is one of the seven BCL measurement types: + `byte`, `short`, `int`, `long`, `float`, `double`, `decimal`. +- `meters.Verify<T>(instrumentName)` / `Verify<T>(meterName, instrumentName)` + โ€” the same `Verify()` idiom as `Compono.Logging`/`Compono.TestDoubles`: + `.WithValue(value)`, `.WithTag(key, value)`, `.WithoutTag(key)`, + `.Matching(m => ...)`, ending in `.Once()` / `.Never()` / `.Exactly(n)` / + `.AtLeast(n)` / `.AtMost(n)`, each a forward to the shared count + verification applied to the filtered measurement count. +- `meters.RecordObservableInstruments()` โ€” explicit poll of *this* factory's + observable instruments. Idempotent per call (twice records twice); a no-op + before the first `Create` or after `Dispose`. +- `meters.ClearMeasurements()` โ€” clears captured measurements (doesn't reset + capture order's sequence). + +Never suggest a two-verb `VerifyMetrics()...Verify()` shape or an aggregate +helper (`Sum`, `LastValue`) โ€” both were considered and rejected (ADR-0072). +Value math stays in LINQ over `GetMeasurements<T>()`. + +## Capture semantics + +- Every measurement of every enabled instrument kind is captured: + `Counter<T>`, `UpDownCounter<T>`, `Histogram<T>`, `Gauge<T>` (net9.0+ โ€” + in-box; no TFM split in capture code), and observable instruments when + polled. Raw measurements only: Compono doesn't aggregate or interpret + kind (no delta-vs-last-value), and doesn't read bucket advice. +- Tags are copied per measurement in callback order (`Array.Empty` when + none); meter- and instrument-level tags are **not** merged in (reach them + through `CapturedMeasurement<T>.Instrument`). No timestamp. +- One private lock per factory guards appends, clears, and reads; the tag + copy happens before the lock. Two factories never share capture state โ€” + identical instrument names stay isolated. +- Capture order is insertion order into the synchronized buffer (a + factory-wide sequence assigned inside the append lock). Sequentially + recorded measurements keep program order; **no cross-thread chronological + order is claimed** for concurrent producers. + +## Selection and matching rules + +`GetMeasurements<T>`/`Verify<T>` resolve their selection with the same +ordered algorithm; the first rule that applies decides. `Verify<T>` +resolves at builder creation, so a conflict throws before any filter. + +1. **Arguments.** Null/empty names โ†’ `ArgumentException`. A `T` outside the + seven supported types โ†’ `ArgumentException` naming the requested type and + listing all seven. +2. **Candidates.** Every published instrument whose `Name` matches, and, for + the two-argument overload, whose `Meter.Name` matches. Both ordinal and + case-sensitive. Candidates include **every** value type, not just `T`. +3. **Unknown name.** No candidates โ†’ empty result; `Never()` passes. A + failing count message lists the instruments that do exist. +4. **Meter ambiguity** (one-argument overload only) โ†’ `InvalidOperationException` + naming the candidates and pointing at the two-argument overload. +5. **Type conflict.** Candidates recording more than one value type โ†’ + `InvalidOperationException` **even when one of them is `T`**. Happens for + `CreateCounter<int>("x")` + `CreateCounter<long>("x")` in one meter, or + same-named meters with different versions/tags. Resolve by renaming, or + narrow with the two-argument overload. No version/tag meter selector + exists (use `Matching(m => m.Instrument.Meter.Version == "2")` after the + types agree). +6. **Type mismatch.** Candidates all recording one type other than `T` โ†’ + `InvalidOperationException`, e.g. `instrument "shop.orders.placed" + records int, not long`. +7. **Merge.** Otherwise every candidate records `T`; their measurements merge + in capture order. + +Matching (never invent a coercion): + +- `WithValue(value)` uses `EqualityComparer<T>.Default` โ€” floating-point + equality is **exact**; use `Matching(...)` for tolerance. +- `WithTag(key, value)` requires a tag whose key matches (ordinal) and whose + value satisfies `object.Equals`. Other tags are ignored. No numeric + coercion: `200` (`int`) doesn't match `200L`. +- `WithoutTag(key)` requires no such tag. +- Exact tag-set and other matches use `Matching(...)`. + +## Asynchronous measurements + +Measurements recorded on other threads are captured thread-safely as they +arrive; reads are point-in-time snapshots. There is **no wait/timeout API** +(`WaitForMeasurementsAsync` is deferred, not rejected). The test awaits its +own completion signal before asserting. + +## Disposal patterns + +`IMeterFactory` already extends `IDisposable`. Compono composition never +disposes the factory. `Dispose()` (idempotent, thread-safe) disposes every +meter the factory created, then its listener. After disposal: captured +measurements stay readable, `ClearMeasurements` works, +`RecordObservableInstruments` is a no-op, and recording on the disposed +meters' instruments isn't captured. Three documented patterns: + +1. `[Compose]` tests โ€” dispose the `[Shared]` parameter: `using var _ = meters;`. +2. `Composer.Create` tests โ€” construct the factory, then + `Register<IMeterFactory>(() => meters)` (which also beats `UseMetrics()`). +3. Generic Host/DI โ€” `services.AddSingleton<IMeterFactory>(meters)`. The + builder already registers a default `IMeterFactory` (for example from + `AddMetrics()`), and a single-service resolve returns the **last** + registration, so add yours after anything else that registers one; never + use `TryAddSingleton` to replace a factory (it keeps the existing one). + An instance registration isn't disposed by the container, so the test's + `using` owns it. Dispose after the host stops. + +An undisposed factory that created meters stays referenced by the BCL's +static meter list for the process lifetime โ€” the same cost as an undisposed +`DefaultMeterFactory`. A factory that never created a meter costs nothing. + +## Snapshot lifetime + +`GetMeasurements<T>` returns a new list each call; later captures, +`ClearMeasurements()`, and `Dispose()` never change a returned list. Each +`Tags` list is a per-measurement copy. `CapturedMeasurement<T>.Instrument` +is the real instrument, reachable through to its `Meter` and the factory โ€” +ordinary object reachability, not a registration. Snapshots stay valid after +disposal: `Value`, `Tags`, and the instrument's descriptive members remain +readable; a disposed meter's instruments report `Enabled == false`. + +## Registration order (stage-6 precedence) and misuse + +`UseMetrics()` shares stage 6 with `UseNSubstitute()`/`UseGeneratedTestDoubles()` +โ€” the existing first-registered-wins rule (ADR-0024) applies unchanged: + +```csharp +builder.UseMetrics().UseNSubstitute(); // IMeterFactory -> CapturingMeterFactory +builder.UseNSubstitute().UseMetrics(); // IMeterFactory -> an NSubstitute substitute instead +``` + +Register `UseMetrics()` first. Every `MeterFactoryTestingExtensions` method +throws `InvalidOperationException` when the `IMeterFactory` isn't a +`CapturingMeterFactory` (detected by a type check, not reflection); the +message names `UseMetrics()`, the registration-order requirement, and the +host recipe. `Meter` constructor parameters are **not** composed by this +package โ€” register them from the shared factory in a profile. + +## `Share<T>()` and `[Shared]` + +A composed `IMeterFactory` participates in `Share<T>()` like any other type +โ€” no metrics-specific mechanism. `[Shared] IMeterFactory meters` gives the +SUT and the test body the same factory, exactly like `[Shared] ILogger<T>`; +without `[Shared]` the test's factory is a different instance from the SUT's +and can't be asserted against or disposed. Prefer `Share<IMeterFactory>()` +in a profile for a reusable whole-suite intent. + +## Native AOT and trimming + +No reflection, no `MakeGenericType`, no dynamic code. The seven typed +callbacks are ordinary generic instantiations over value types the compiler +sees statically. `IsAotCompatible=true`; the package publishes and runs under +Native AOT (`Compono.Metrics.AotSmokeTest` on net10.0/linux-x64 in CI). + +## v1 boundaries โ€” do not invent capability beyond these + +No metrics framework/aggregation/exporter/OpenTelemetry integration, no +`ActivitySource`/tracing testing, no composing `Meter` parameters or +configurable meter name, no `IServiceCollection`/host extension (a +documentation recipe only โ€” `AddSingleton<IMeterFactory>(meters)`), no +timestamps/`TimeProvider`/wait APIs, no aggregate helpers, no numeric tag +coercion, no automatic disposal by composition, and no version- or tag-level +meter selection. It doesn't replace +`Microsoft.Extensions.Diagnostics.Testing` for consumers who prefer it. diff --git a/src/Compono.Metrics/CaptureState.cs b/src/Compono.Metrics/CaptureState.cs new file mode 100644 index 00000000..d207c09c --- /dev/null +++ b/src/Compono.Metrics/CaptureState.cs @@ -0,0 +1,218 @@ +using System.Diagnostics.Metrics; +using System.Text; + +namespace Compono.Metrics; + +/// <summary> +/// The capture state behind one <see cref="CapturingMeterFactory"/>: a single lock that guards appends, +/// clears, and reads (ADR-0072 "Concurrency and allocation"), a factory-wide sequence counter, and the +/// list of typed per-instrument buffers this factory has published. One instance per factory - there is no +/// static or shared capture state (ADR-0072 "Capture semantics"). Internal. +/// </summary> +internal sealed class CaptureState +{ + /// <summary>The single factory-wide lock. A plain <see cref="object"/> lock, not + /// <c>System.Threading.Lock</c> - this package multi-targets net8.0, which predates that type.</summary> + internal readonly object Gate = new(); + + /// <summary>The next factory-wide sequence number. Only ever read or written while holding + /// <see cref="Gate"/>.</summary> + internal long NextSequence; + + private readonly List<IMeasurementBuffer> _buffers = []; + + /// <summary> + /// Creates the typed buffer for <paramref name="instrument"/> and registers it, or returns + /// <see langword="null"/> when the instrument's value type isn't one of the seven supported types. The + /// buffer is a closed generic instantiation the compiler sees statically (no reflection, no dynamic + /// activation); it is passed straight to + /// <see cref="MeterListener.EnableMeasurementEvents(Instrument, object?)"/> as the instrument's state. + /// </summary> + public IMeasurementBuffer? TryCreateBuffer(Instrument instrument) + { + if (TryCreate<byte>(instrument, out var buffer)) + return Register(buffer); + if (TryCreate<short>(instrument, out buffer)) + return Register(buffer); + if (TryCreate<int>(instrument, out buffer)) + return Register(buffer); + if (TryCreate<long>(instrument, out buffer)) + return Register(buffer); + if (TryCreate<float>(instrument, out buffer)) + return Register(buffer); + if (TryCreate<double>(instrument, out buffer)) + return Register(buffer); + if (TryCreate<decimal>(instrument, out buffer)) + return Register(buffer); + + return null; + } + + /// <summary>Discards every captured measurement, across every published instrument.</summary> + public void Clear() + { + lock (Gate) + { + foreach (var buffer in _buffers) + buffer.Clear(); + } + } + + /// <summary> + /// Resolves a selection exactly per ADR-0072's seven ordered rules. Rules 1 (unsupported + /// <typeparamref name="T"/> and null/empty names) are enforced by the caller before this is reached. + /// </summary> + /// <param name="meterName">The meter name for the two-argument overload, or <see langword="null"/> for + /// the one-argument overload (which makes different meter names ambiguous, rule 4).</param> + /// <param name="instrumentName">The instrument name to match.</param> + public SelectionResult<T> Select<T>(string? meterName, string instrumentName) + where T : struct + { + lock (Gate) + { + var existing = new List<string>(_buffers.Count); + var candidates = new List<IMeasurementBuffer>(); + + foreach (var buffer in _buffers) + { + existing.Add(DescribeInstrument(buffer.Instrument, buffer.ValueType)); + + if (NameMatches(buffer.Instrument, meterName, instrumentName)) + candidates.Add(buffer); + } + + // Rule 3: unknown name - empty result (a failed count lists what does exist). + if (candidates.Count == 0) + return SelectionResult<T>.NoMatch(existing); + + // Rule 4: meter ambiguity (one-argument overload only). + if (meterName is null && CountDistinctMeterNames(candidates) > 1) + throw new InvalidOperationException(AmbiguityMessage(instrumentName, candidates)); + + // Rule 5: type conflict - more than one value type, even if one of them is T. + if (!AllSameValueType(candidates, out var valueType)) + throw new InvalidOperationException(ConflictMessage(instrumentName, candidates)); + + // Rule 6: type mismatch - one type, but not T. + if (valueType != typeof(T)) + throw new InvalidOperationException( + $"instrument \"{instrumentName}\" records {InstrumentValueTypes.DisplayName(valueType!)}, " + + $"not {InstrumentValueTypes.DisplayName(typeof(T))}."); + + // Rule 7: merge, in capture order. + var stored = new List<StoredMeasurement<T>>(); + foreach (var buffer in candidates) + ((IMeasurementBuffer<T>)buffer).CopyTo(stored); + + stored.Sort(static (left, right) => left.Sequence.CompareTo(right.Sequence)); + + var merged = new List<CapturedMeasurement<T>>(stored.Count); + foreach (var measurement in stored) + merged.Add(measurement.Measurement); + + return SelectionResult<T>.Match(merged, existing); + } + } + + private IMeasurementBuffer Register(IMeasurementBuffer buffer) + { + lock (Gate) + { + _buffers.Add(buffer); + } + + return buffer; + } + + private bool TryCreate<T>(Instrument instrument, out IMeasurementBuffer buffer) + where T : struct + { + if (IsCapturedKind<T>(instrument)) + { + buffer = new TypedCapture<T>(this, instrument); + return true; + } + + buffer = null!; + return false; + } + + private static bool IsCapturedKind<T>(Instrument instrument) + where T : struct => + instrument is Instrument<T> or ObservableInstrument<T>; + + private static bool NameMatches(Instrument instrument, string? meterName, string instrumentName) + { + if (!string.Equals(instrument.Name, instrumentName, StringComparison.Ordinal)) + return false; + + return meterName is null + || string.Equals(instrument.Meter.Name, meterName, StringComparison.Ordinal); + } + + private static int CountDistinctMeterNames(List<IMeasurementBuffer> candidates) + { + var names = new List<string>(); + foreach (var candidate in candidates) + { + if (!names.Contains(candidate.Instrument.Meter.Name)) + names.Add(candidate.Instrument.Meter.Name); + } + + return names.Count; + } + + private static bool AllSameValueType(List<IMeasurementBuffer> candidates, out Type? valueType) + { + valueType = candidates[0].ValueType; + for (var i = 1; i < candidates.Count; i++) + { + if (candidates[i].ValueType != valueType) + { + valueType = null; + return false; + } + } + + return true; + } + + private static string AmbiguityMessage(string instrumentName, List<IMeasurementBuffer> candidates) + { + var builder = new StringBuilder(); + builder.Append($"Instrument \"{instrumentName}\" matches candidates in more than one meter: "); + AppendCandidateList(builder, candidates); + builder.Append(". Use the two-argument GetMeasurements/Verify overload with a meter name to select one."); + return builder.ToString(); + } + + private static string ConflictMessage(string instrumentName, List<IMeasurementBuffer> candidates) + { + var builder = new StringBuilder(); + builder.Append($"Instrument \"{instrumentName}\" matches candidates that record more than one value type: "); + AppendCandidateList(builder, candidates); + builder.Append(". One selection can't merge measurements of different types - rename an instrument in the " + + "SUT, or narrow with the two-argument overload when the conflicting instruments live in differently " + + "named meters."); + return builder.ToString(); + } + + private static void AppendCandidateList(StringBuilder builder, List<IMeasurementBuffer> candidates) + { + for (var i = 0; i < candidates.Count; i++) + { + if (i > 0) + builder.Append("; "); + + builder.Append(DescribeInstrument(candidates[i].Instrument, candidates[i].ValueType)); + } + } + + private static string DescribeInstrument(Instrument instrument, Type valueType) + { + var meter = instrument.Meter; + var version = string.IsNullOrEmpty(meter.Version) ? string.Empty : $" v{meter.Version}"; + return $"meter \"{meter.Name}\"{version}: instrument \"{instrument.Name}\" " + + $"({InstrumentValueTypes.DisplayName(valueType)})"; + } +} diff --git a/src/Compono.Metrics/CapturedMeasurement{T}.cs b/src/Compono.Metrics/CapturedMeasurement{T}.cs new file mode 100644 index 00000000..b3e8be12 --- /dev/null +++ b/src/Compono.Metrics/CapturedMeasurement{T}.cs @@ -0,0 +1,47 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// <summary> +/// A single captured measurement: the recorded value, its tags, and the <see cref="Instrument"/> that +/// recorded it. A plain <see langword="readonly"/> <see langword="struct"/> - deliberately not a +/// <see langword="record"/> <see langword="struct"/>, so there is no synthesized value equality that +/// would suggest <c>==</c> compares <see cref="Tags"/> by value; use <see cref="Value"/> directly or +/// the <see cref="MeterFactoryTestingExtensions.Verify{T}(IMeterFactory, string)"/> filter chain. +/// See docs/adr/0072-compono-metrics-testing-support-package.md. +/// </summary> +/// <typeparam name="T">The measurement's value type - one of the seven BCL measurement value types +/// (<see cref="byte"/>, <see cref="short"/>, <see cref="int"/>, <see cref="long"/>, <see cref="float"/>, +/// <see cref="double"/>, <see cref="decimal"/>).</typeparam> +public readonly struct CapturedMeasurement<T> + where T : struct +{ + internal CapturedMeasurement(T value, IReadOnlyList<KeyValuePair<string, object?>> tags, Instrument instrument) + { + Value = value; + Tags = tags; + Instrument = instrument; + } + + /// <summary>The recorded value, exactly as the instrument received it (no normalization, no + /// aggregation).</summary> + public T Value { get; } + + /// <summary> + /// This measurement's tags, copied out of the BCL's callback span in callback order. A per-measurement + /// copy that never aliases the BCL's span or any other measurement's tags; empty (never + /// <see langword="null"/>) when the measurement had no tags. Meter-level and instrument-level tags are + /// not merged in - they're reachable through <see cref="Instrument"/>. + /// </summary> + public IReadOnlyList<KeyValuePair<string, object?>> Tags { get; } + + /// <summary> + /// The actual <see cref="Instrument"/> instance that recorded this measurement (the one the SUT + /// created). Through <see cref="System.Diagnostics.Metrics.Instrument.Meter"/> it references the + /// actual <see cref="Meter"/>, and through <see cref="Meter.Scope"/> the factory. Descriptive members + /// (for example <see cref="System.Diagnostics.Metrics.Instrument.Name"/>, + /// <see cref="System.Diagnostics.Metrics.Instrument.Enabled"/>, and the meter's name/version/tags) + /// stay readable after the factory is disposed. + /// </summary> + public Instrument Instrument { get; } +} diff --git a/src/Compono.Metrics/CapturingMeterFactory.cs b/src/Compono.Metrics/CapturingMeterFactory.cs new file mode 100644 index 00000000..8c1699d6 --- /dev/null +++ b/src/Compono.Metrics/CapturingMeterFactory.cs @@ -0,0 +1,275 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// <summary> +/// A hand-written, reflection-free <see cref="IMeterFactory"/> that captures the measurements of every +/// instrument its meters publish into an inspectable, thread-safe, Compono-native model +/// (<see cref="CapturedMeasurement{T}"/>). Directly, publicly constructible - composing through +/// <see cref="CompositionBuilderExtensions.UseMetrics"/> is not required. See +/// docs/adr/0072-compono-metrics-testing-support-package.md. +/// </summary> +/// <remarks> +/// <para> +/// Factory semantics match <c>DefaultMeterFactory</c>: <see cref="Create"/> +/// rejects a <see langword="null"/> <see cref="MeterOptions"/> and a foreign <see cref="MeterOptions.Scope"/>, +/// throws <see cref="ObjectDisposedException"/> after disposal, never mutates the caller's options, and caches +/// meters by name, version, and order-insensitive tag set (duplicate tag keys are significant - see +/// <see cref="Create"/>). +/// </para> +/// <para> +/// Each factory owns one lazily created <see cref="MeterListener"/>, created on the first <see cref="Create"/> +/// and disposed with the factory. It enables only instruments whose <see cref="Meter.Scope"/> is this factory, +/// so two factories never see each other's measurements even for identical meter and instrument names. There +/// is no static or shared capture state. +/// </para> +/// <para> +/// Disposal is the test's responsibility (<see cref="IMeterFactory"/> already extends +/// <see cref="IDisposable"/>); composition never disposes the factory. An undisposed factory that created +/// meters stays referenced by the BCL's static meter list for the process lifetime - the same cost as an +/// undisposed <c>DefaultMeterFactory</c>. +/// </para> +/// </remarks> +public sealed class CapturingMeterFactory : IMeterFactory +{ + // A plain object lock, not System.Threading.Lock - this project multi-targets net8.0, which predates + // that type. Guards meter caching, the lazy listener, and the disposed flag. Capture appends/reads use + // CaptureState's own gate (one lock for capture, one for the factory's meter/listener lifecycle). + private readonly object _factoryGate = new(); + private readonly CaptureState _capture = new(); + private readonly List<MeterEntry> _meters = []; + + private MeterListener? _listener; + private bool _disposed; + + /// <summary> + /// Creates a standalone <see cref="CapturingMeterFactory"/>, usable with no Compono composition involved + /// at all. + /// </summary> + public CapturingMeterFactory() + { + } + + /// <summary> + /// Creates a <see cref="Meter"/> bound to this factory. The same name, version, and tag set + /// (order-insensitive, <see cref="object.Equals(object, object)"/> on values) returns the same + /// <see cref="Meter"/>; anything else creates a new one. Duplicate tag keys are significant: + /// <c>[k=1, k=1]</c> is a different set from <c>[k=1, j=2]</c>. + /// </summary> + /// <param name="options">The meter options.</param> + /// <exception cref="ArgumentNullException"><paramref name="options"/> is <see langword="null"/>.</exception> + /// <exception cref="InvalidOperationException"><paramref name="options"/>'s <see cref="MeterOptions.Scope"/> + /// is non-<see langword="null"/> and isn't this factory.</exception> + /// <exception cref="ObjectDisposedException">This factory has been disposed.</exception> + public Meter Create(MeterOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + lock (_factoryGate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + if (options.Scope is not null && !ReferenceEquals(options.Scope, this)) + { + throw new InvalidOperationException( + "The MeterOptions.Scope of a meter created by a CapturingMeterFactory must be null or " + + "this factory. To record a SUT's measurements, give it this factory as its IMeterFactory " + + "and let it create its own meters."); + } + + var tags = NormalizeTags(options.Tags); + + foreach (var entry in _meters) + { + if (entry.Matches(options.Name, options.Version, tags)) + return entry.Meter; + } + + EnsureListener(); + + var owned = new MeterOptions(options.Name) + { + Version = options.Version, + Scope = this, + Tags = tags, + }; + + var meter = new Meter(owned); + _meters.Add(new MeterEntry(options.Name, options.Version, tags, meter)); + return meter; + } + } + + /// <summary> + /// Disposes every meter this factory created (raising + /// <c>MeasurementsCompleted</c>), then its <see cref="MeterListener"/>. Idempotent and + /// thread-safe. Captured measurements stay readable afterwards; measurements recorded on the disposed + /// meters' instruments are no longer captured. + /// </summary> + public void Dispose() + { + lock (_factoryGate) + { + if (_disposed) + return; + + _disposed = true; + } + + foreach (var entry in _meters) + entry.Meter.Dispose(); + + _listener?.Dispose(); + } + + /// <summary> + /// Calls this factory's listener's <see cref="MeterListener.RecordObservableInstruments"/>. Callbacks run + /// synchronously on the calling thread and only for this factory's observable instruments; each + /// observation appends measurements. A no-op before the first <see cref="Create"/> or after disposal. + /// </summary> + internal void RecordObservableInstruments() + { + MeterListener? listener; + lock (_factoryGate) + { + if (_disposed) + return; + + listener = _listener; + } + + listener?.RecordObservableInstruments(); + } + + /// <summary>Discards every captured measurement.</summary> + internal void ClearMeasurements() => _capture.Clear(); + + /// <summary>Resolves a selection per ADR-0072's seven ordered rules.</summary> + internal SelectionResult<T> Select<T>(string? meterName, string instrumentName) + where T : struct => + _capture.Select<T>(meterName, instrumentName); + + private void EnsureListener() + { + if (_listener is not null) + return; + + var listener = new MeterListener + { + InstrumentPublished = OnInstrumentPublished, + }; + + listener.SetMeasurementEventCallback<byte>(OnMeasurement); + listener.SetMeasurementEventCallback<short>(OnMeasurement); + listener.SetMeasurementEventCallback<int>(OnMeasurement); + listener.SetMeasurementEventCallback<long>(OnMeasurement); + listener.SetMeasurementEventCallback<float>(OnMeasurement); + listener.SetMeasurementEventCallback<double>(OnMeasurement); + listener.SetMeasurementEventCallback<decimal>(OnMeasurement); + + listener.Start(); + _listener = listener; + } + + private void OnInstrumentPublished(Instrument instrument, MeterListener listener) + { + // Scope isolation: enable only this factory's instruments, so two factories never see each other's + // measurements even for identical names (RESEARCH-0039 fact 3, ADR-0072 "Capture semantics"). + if (!ReferenceEquals(instrument.Meter.Scope, this)) + return; + + var buffer = _capture.TryCreateBuffer(instrument); + if (buffer is not null) + listener.EnableMeasurementEvents(instrument, buffer); + } + + private static void OnMeasurement<T>( + Instrument instrument, + T measurement, + ReadOnlySpan<KeyValuePair<string, object?>> tags, + object? state) + where T : struct + { + if (state is TypedCapture<T> capture) + capture.Record(measurement, tags); + } + + private static KeyValuePair<string, object?>[] NormalizeTags(IEnumerable<KeyValuePair<string, object?>>? tags) + { + if (tags is null) + return []; + + var list = new List<KeyValuePair<string, object?>>(); + foreach (var tag in tags) + list.Add(tag); + + return [.. list]; + } + + private static bool TagSetsEqual( + KeyValuePair<string, object?>[] left, + KeyValuePair<string, object?>[] right) + { + if (left.Length != right.Length) + return false; + + // The common case (no meter tags) must not allocate. + if (left.Length == 0) + return true; + + // Order-insensitive bag equality: each entry on the left consumes exactly one distinct + // entry on the right. A one-to-one match (rather than "every left entry matches some right + // entry") is what makes duplicate keys behave correctly - [k=1, k=1] must not equal + // [k=1, j=2] (both have length 2, and both left entries are individually present on the + // right). This is intentionally stricter than DefaultMeterFactory, whose duplicate-tag + // comparison is not a true multiset comparison; here a duplicate meter-tag key is + // significant. + var matched = new bool[right.Length]; + foreach (var tag in left) + { + var found = false; + for (var i = 0; i < right.Length; i++) + { + if (matched[i]) + continue; + + if (string.Equals(right[i].Key, tag.Key, StringComparison.Ordinal) + && Equals(right[i].Value, tag.Value)) + { + matched[i] = true; + found = true; + break; + } + } + + if (!found) + return false; + } + + return true; + } + + private sealed class MeterEntry + { + public MeterEntry(string name, string? version, KeyValuePair<string, object?>[] tags, Meter meter) + { + Name = name; + Version = version; + Tags = tags; + Meter = meter; + } + + public string Name { get; } + + public string? Version { get; } + + public KeyValuePair<string, object?>[] Tags { get; } + + public Meter Meter { get; } + + public bool Matches(string name, string? version, KeyValuePair<string, object?>[] tags) => + string.Equals(Name, name, StringComparison.Ordinal) + && string.Equals(Version, version, StringComparison.Ordinal) + && TagSetsEqual(Tags, tags); + } +} diff --git a/src/Compono.Metrics/Compono.Metrics.csproj b/src/Compono.Metrics/Compono.Metrics.csproj new file mode 100644 index 00000000..731bd6cc --- /dev/null +++ b/src/Compono.Metrics/Compono.Metrics.csproj @@ -0,0 +1,43 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <LangVersion>latest</LangVersion> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <TargetFrameworks>net8.0;net9.0;net10.0;net11.0</TargetFrameworks> + <Title>Compono โ€” System.Diagnostics.Metrics Testing Support + First-class System.Diagnostics.Metrics testing support for Compono - IMeterFactory composes naturally through UseMetrics(), backed by a hand-written CapturingMeterFactory that captures counter, up-down-counter, histogram, gauge, and observable measurements per factory (scope-isolated, thread-safe, typed, no boxing) and offers Compono-native Verify<T>() verification reusing core CallVerifier unmodified. No dependency beyond core Compono. See docs/adr/0072-compono-metrics-testing-support-package.md. + + true + + + + + + + + + + + + + + + <_ProjectReferencesWithVersions Update="@(_ProjectReferencesWithVersions)"> + [%(ProjectVersion)] + + + + + diff --git a/src/Compono.Metrics/CompositionBuilderExtensions.cs b/src/Compono.Metrics/CompositionBuilderExtensions.cs new file mode 100644 index 00000000..b78db7de --- /dev/null +++ b/src/Compono.Metrics/CompositionBuilderExtensions.cs @@ -0,0 +1,30 @@ +namespace Compono.Metrics; + +/// +/// Registers support into a . +/// +public static class CompositionBuilderExtensions +{ + /// + /// Registers a stage-6 test-double provider () so a bare + /// composes as a new + /// per request. + /// + /// + /// Register this before UseNSubstitute() if + /// should resolve through Compono.Metrics rather + /// than an NSubstitute substitute - Compono's stage-6 providers resolve in registration order + /// (first-registered-wins), an existing, documented, Accepted pattern (ADR-0024) this package + /// follows rather than replacing. An exact Register<IMeterFactory>(...) always wins over + /// UseMetrics() regardless of order. + /// + /// The builder to register into. + /// The same , for chaining. + /// is . + public static CompositionBuilder UseMetrics(this CompositionBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + + return builder.AddTestDoubleProvider(new MetricsProvider()); + } +} diff --git a/src/Compono.Metrics/IMeasurementBuffer.cs b/src/Compono.Metrics/IMeasurementBuffer.cs new file mode 100644 index 00000000..6fb0d9dc --- /dev/null +++ b/src/Compono.Metrics/IMeasurementBuffer.cs @@ -0,0 +1,35 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// +/// Non-generic view of one published instrument's typed capture buffer - what a +/// needs in order to enumerate published instruments, answer selection rules +/// 2-5 from an instrument's metadata alone, and clear every buffer. Internal. +/// +internal interface IMeasurementBuffer +{ + /// The instrument whose measurements this buffer owns. + Instrument Instrument { get; } + + /// The instrument's value type - which of the seven supported types this buffer stores. + Type ValueType { get; } + + /// Discards every measurement in this buffer. The caller must already hold + /// . + void Clear(); +} + +/// +/// Typed view of a capture buffer, used by selection rule 7 to merge one value type's measurements across +/// several same-named instruments. Internal. always equals +/// . +/// +/// One of the seven supported measurement value types. +internal interface IMeasurementBuffer : IMeasurementBuffer + where T : struct +{ + /// Appends this buffer's measurements (already in factory-wide sequence order) to + /// . The caller must already hold . + void CopyTo(List> destination); +} diff --git a/src/Compono.Metrics/InstrumentValueTypes.cs b/src/Compono.Metrics/InstrumentValueTypes.cs new file mode 100644 index 00000000..b48ba744 --- /dev/null +++ b/src/Compono.Metrics/InstrumentValueTypes.cs @@ -0,0 +1,50 @@ +namespace Compono.Metrics; + +/// +/// The seven value types instruments accept, and small helpers +/// for matching an instrument to its value type and for human-readable diagnostics. Internal - the set of +/// supported types is part of the public contract only through the diagnostics it produces (ADR-0072 +/// selection rule 1). +/// +internal static class InstrumentValueTypes +{ + /// The seven supported measurement value types, in the order used in diagnostics. + public static readonly Type[] Supported = + [ + typeof(byte), + typeof(short), + typeof(int), + typeof(long), + typeof(float), + typeof(double), + typeof(decimal), + ]; + + /// when is one of the seven supported types. + public static bool IsSupported(Type type) => Array.IndexOf(Supported, type) >= 0; + + /// A comma-separated list of the seven supported types' C# names, for diagnostics. + public static string SupportedList => "byte, short, int, long, float, double, decimal"; + + /// The C# keyword for a supported measurement type (for example long), falling back to + /// the type's simple name for anything else. + public static string DisplayName(Type type) + { + if (type == typeof(byte)) + return "byte"; + if (type == typeof(short)) + return "short"; + if (type == typeof(int)) + return "int"; + if (type == typeof(long)) + return "long"; + if (type == typeof(float)) + return "float"; + if (type == typeof(double)) + return "double"; + if (type == typeof(decimal)) + return "decimal"; + + return type.Name; + } +} diff --git a/src/Compono.Metrics/MeasurementVerificationBuilder{T}.cs b/src/Compono.Metrics/MeasurementVerificationBuilder{T}.cs new file mode 100644 index 00000000..86d9cddb --- /dev/null +++ b/src/Compono.Metrics/MeasurementVerificationBuilder{T}.cs @@ -0,0 +1,238 @@ +using System.Globalization; +using System.Text; + +namespace Compono.Metrics; + +/// +/// A fluent filter chain over a resolved selection of captured measurements, ending in a thin, one-line +/// forwarder to core - // +/// each build a from the filtered match count right here and call the corresponding +/// member. itself is never part of this type's public surface, and no new +/// counting/Times abstraction is introduced. See +/// docs/adr/0072-compono-metrics-testing-support-package.md ยง"Selection and matching". +/// +/// The measurement value type - one of the seven supported types. +public sealed class MeasurementVerificationBuilder + where T : struct +{ + private readonly IReadOnlyList> _measurements; + private readonly string _instrumentName; + private readonly string? _meterName; + private readonly IReadOnlyList _existingInstruments; + private readonly bool _hasCandidates; + private readonly List<(string Description, Func, bool> Predicate)> _filters = []; + + internal MeasurementVerificationBuilder( + SelectionResult selection, + string instrumentName, + string? meterName) + { + _measurements = selection.Measurements; + _instrumentName = instrumentName; + _meterName = meterName; + _existingInstruments = selection.ExistingInstruments; + _hasCandidates = selection.HasCandidates; + } + + /// Restricts matches to measurements whose value equals exactly, using + /// . Floating-point equality is exact - use + /// for a tolerance. + public MeasurementVerificationBuilder WithValue(T value) => + Add($"value {FormatValue(value)}", measurement => EqualityComparer.Default.Equals(measurement.Value, value)); + + /// Restricts matches to measurements that contain a tag with key (ordinal) + /// whose value satisfies . Other tags are ignored, and there is + /// no numeric coercion (200, an , doesn't match 200L). Chain calls for + /// several tags. + /// is . + public MeasurementVerificationBuilder WithTag(string key, object? value) + { + ArgumentNullException.ThrowIfNull(key); + + return Add( + $"tag {key} = {FormatTagValue(value)}", + measurement => HasTag(measurement, key, value)); + } + + /// Restricts matches to measurements that have no tag with key (ordinal). + /// is . + public MeasurementVerificationBuilder WithoutTag(string key) + { + ArgumentNullException.ThrowIfNull(key); + + return Add($"no tag {key}", measurement => !HasTagKey(measurement, key)); + } + + /// Restricts matches to measurements satisfying an arbitrary - the + /// escape hatch for anything the named filters above don't cover (an exact tag-set match, a tolerance, and + /// so on). + /// is . + public MeasurementVerificationBuilder Matching(Func, bool> predicate) + { + ArgumentNullException.ThrowIfNull(predicate); + + return Add("a custom condition", predicate); + } + + /// Asserts the accumulated filters matched exactly once. + /// The filters did not match exactly once. + public void Once() => Assert(verifier => verifier.Once()); + + /// Asserts the accumulated filters never matched. + /// The filters matched at least once. + public void Never() => Assert(verifier => verifier.Never()); + + /// Asserts the accumulated filters matched exactly times. + /// The filters did not match exactly + /// times. + public void Exactly(int times) => Assert(verifier => verifier.Exactly(times)); + + /// Asserts the accumulated filters matched at least times. + /// The filters matched fewer than + /// times. + public void AtLeast(int times) => Assert(verifier => verifier.AtLeast(times)); + + /// Asserts the accumulated filters matched at most times. + /// The filters matched more than + /// times. + public void AtMost(int times) => Assert(verifier => verifier.AtMost(times)); + + private MeasurementVerificationBuilder Add(string description, Func, bool> predicate) + { + _filters.Add((description, predicate)); + return this; + } + + private void Assert(Action assertion) + { + try + { + assertion(ToCallVerifier()); + } + catch (TestDoubleVerificationException exception) when (!_hasCandidates) + { + // Rule 3 (unknown name) is the one case where the empty selection is itself the diagnosis. The + // count message names the (missing) instrument; add why nothing was found, and what does exist. + throw new TestDoubleVerificationException(exception.Message + DescribeKnownInstruments()); + } + } + + private CallVerifier ToCallVerifier() + { + var matchCount = 0; + foreach (var measurement in _measurements) + { + var matches = true; + foreach (var (_, predicate) in _filters) + { + if (!predicate(measurement)) + { + matches = false; + break; + } + } + + if (matches) + matchCount++; + } + + return new CallVerifier(matchCount, Describe()); + } + + private string Describe() + { + var builder = new StringBuilder("instrument \""); + builder.Append(_instrumentName); + builder.Append('"'); + + if (_meterName is not null) + { + builder.Append(" in meter \""); + builder.Append(_meterName); + builder.Append('"'); + } + + builder.Append(" ("); + builder.Append(InstrumentValueTypes.DisplayName(typeof(T))); + builder.Append(')'); + + for (var i = 0; i < _filters.Count; i++) + { + builder.Append(i == 0 ? " with " : " and "); + builder.Append(_filters[i].Description); + } + + return builder.ToString(); + } + + private string DescribeKnownInstruments() + { + var builder = new StringBuilder(); + builder.Append(" No instrument named \""); + builder.Append(_instrumentName); + + if (_meterName is not null) + { + builder.Append("\" has been published by meter \""); + builder.Append(_meterName); + builder.Append("\"."); + } + else + { + builder.Append("\" has been published by this factory."); + } + + if (_existingInstruments.Count > 0) + { + builder.Append(" Existing instruments: "); + for (var i = 0; i < _existingInstruments.Count; i++) + { + if (i > 0) + builder.Append("; "); + + builder.Append(_existingInstruments[i]); + } + + builder.Append('.'); + } + + return builder.ToString(); + } + + private static bool HasTag(CapturedMeasurement measurement, string key, object? value) + { + foreach (var tag in measurement.Tags) + { + if (string.Equals(tag.Key, key, StringComparison.Ordinal) && Equals(tag.Value, value)) + return true; + } + + return false; + } + + private static bool HasTagKey(CapturedMeasurement measurement, string key) + { + foreach (var tag in measurement.Tags) + { + if (string.Equals(tag.Key, key, StringComparison.Ordinal)) + return true; + } + + return false; + } + + private static string FormatValue(T value) => + string.Create(CultureInfo.InvariantCulture, $"{value}"); + + // Describes the value the test passed to WithTag - never the captured measurement's tag. A string is + // shown quoted (the quotes already convey its type); every other value shows the runtime type of the + // expected value (for example "200 (int)"), so the message never implies a type it didn't check. + private static string FormatTagValue(object? value) => value switch + { + null => "null", + string text => $"\"{text}\"", + _ => string.Create( + CultureInfo.InvariantCulture, + $"{value} ({InstrumentValueTypes.DisplayName(value.GetType())})"), + }; +} diff --git a/src/Compono.Metrics/MeterFactoryTestingExtensions.cs b/src/Compono.Metrics/MeterFactoryTestingExtensions.cs new file mode 100644 index 00000000..e65b4a7c --- /dev/null +++ b/src/Compono.Metrics/MeterFactoryTestingExtensions.cs @@ -0,0 +1,167 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// +/// Direct inspection and fluent verification over any - no assertion framework +/// required. Every method here requires the it's called on to actually be a +/// (produced by , or +/// directly via 's public constructor) - calling any of these against a +/// substitute, a Compono.TestDoubles-generated double, DefaultMeterFactory, +/// or any other non-Compono throws immediately, diagnostically, rather than +/// returning an empty/default result. See docs/adr/0072-compono-metrics-testing-support-package.md's +/// "Precedence and misuse" section. +/// +public static class MeterFactoryTestingExtensions +{ + /// + /// Every measurement captured for instruments named , across every + /// meter, merged in capture order (ADR-0072 selection rule 7). A new list is returned on each call; + /// later captures, , and never + /// change a list already returned. + /// + /// The measurement value type - one of the seven supported types. + /// The capturing factory. + /// The instrument name to match (ordinal, case-sensitive). + /// is not a + /// . + /// is null or empty; or + /// is not one of the seven supported measurement value types. + public static IReadOnlyList> GetMeasurements( + this IMeterFactory factory, + string instrumentName) + where T : struct => + RequireCapturing(factory).Select(null, ValidateSelection(instrumentName)).Measurements; + + /// + /// Every measurement captured for instruments named in the meter named + /// , merged in capture order. A new list is returned on each call. + /// + /// The measurement value type - one of the seven supported types. + /// The capturing factory. + /// The meter name to match (ordinal, case-sensitive). + /// The instrument name to match (ordinal, case-sensitive). + /// is not a + /// . + /// or + /// is null or empty; or is not one of the seven supported measurement value + /// types. + public static IReadOnlyList> GetMeasurements( + this IMeterFactory factory, + string meterName, + string instrumentName) + where T : struct => + RequireCapturing(factory) + .Select(ValidateName(meterName), ValidateSelection(instrumentName)) + .Measurements; + + /// + /// The entry point for fluent verification, for example + /// meters.Verify<long>("shop.orders.placed").WithTag("region", "eu").Once(). The selection is + /// resolved here, when the builder is created, so a meter ambiguity, type conflict, or type mismatch + /// throws before any filter is added. + /// + /// The measurement value type - one of the seven supported types. + /// The capturing factory. + /// The instrument name to match (ordinal, case-sensitive). + /// is not a + /// ; the name matches instruments in more than one meter; the name + /// matches instruments that record more than one value type; or the matching instruments record a type + /// other than . + /// is null or empty; or + /// is not one of the seven supported measurement value types. + public static MeasurementVerificationBuilder Verify( + this IMeterFactory factory, + string instrumentName) + where T : struct => + new(RequireCapturing(factory).Select(null, ValidateSelection(instrumentName)), instrumentName, null); + + /// + /// The entry point for fluent verification scoped to one meter name. The selection is resolved here, when + /// the builder is created. + /// + /// The measurement value type - one of the seven supported types. + /// The capturing factory. + /// The meter name to match (ordinal, case-sensitive). + /// The instrument name to match (ordinal, case-sensitive). + /// is not a + /// ; the name matches instruments that record more than one value type; + /// or the matching instruments record a type other than . + /// or + /// is null or empty; or is not one of the seven supported measurement value + /// types. + public static MeasurementVerificationBuilder Verify( + this IMeterFactory factory, + string meterName, + string instrumentName) + where T : struct => + new(RequireCapturing(factory).Select(ValidateName(meterName), ValidateSelection(instrumentName)), + instrumentName, + meterName); + + /// + /// Polls this factory's observable instruments: calls this factory's listener's + /// . Callbacks run synchronously on the calling + /// thread and only for this factory's observable instruments; each observation appends measurements, so + /// calling it twice records twice. Reads never poll. A no-op before the first + /// or after disposal. + /// + /// The capturing factory. + /// is not a + /// . + public static void RecordObservableInstruments(this IMeterFactory factory) => + RequireCapturing(factory).RecordObservableInstruments(); + + /// Discards every measurement captured by so far. Works before and + /// after disposal. + /// The capturing factory. + /// is not a + /// . + public static void ClearMeasurements(this IMeterFactory factory) => + RequireCapturing(factory).ClearMeasurements(); + + private static CapturingMeterFactory RequireCapturing(IMeterFactory factory) + { + ArgumentNullException.ThrowIfNull(factory); + + if (factory is CapturingMeterFactory capturing) + return capturing; + + throw new InvalidOperationException( + $"'{factory.GetType()}' is not a Compono.Metrics capturing meter factory. This member is only usable " + + "against an IMeterFactory produced by Compono.Metrics (UseMetrics(), or a directly constructed " + + "CapturingMeterFactory). If this IMeterFactory was composed, confirm UseMetrics() is registered " + + "before UseNSubstitute() - Compono's stage-6 test-double providers resolve in registration order, " + + "and whichever provider is registered first wins for a given request. If this IMeterFactory came " + + "from a host's IServiceProvider (for example AddMetrics()'s DefaultMeterFactory), register a " + + "CapturingMeterFactory instance with services.AddSingleton(meters) instead. The " + + "container resolves a single IMeterFactory to its last registration, so add that call after anything " + + "else that registers IMeterFactory (including AddMetrics() or a host's default) - the later " + + "registration wins. Don't use TryAddSingleton to replace a factory: it would keep the existing " + + "registration."); + } + + private static string ValidateSelection(string instrumentName) + where T : struct + { + var name = ValidateName(instrumentName); + + if (!InstrumentValueTypes.IsSupported(typeof(T))) + { + throw new ArgumentException( + $"Compono.Metrics supports only the seven System.Diagnostics.Metrics measurement value types " + + $"({InstrumentValueTypes.SupportedList}), but the requested measurement type was " + + $"'{InstrumentValueTypes.DisplayName(typeof(T))}'. No instrument can record that type, so this " + + "selection can never match.", + nameof(T)); + } + + return name; + } + + private static string ValidateName(string name) + { + ArgumentException.ThrowIfNullOrEmpty(name); + return name; + } +} diff --git a/src/Compono.Metrics/MetricsProvider.cs b/src/Compono.Metrics/MetricsProvider.cs new file mode 100644 index 00000000..65202f75 --- /dev/null +++ b/src/Compono.Metrics/MetricsProvider.cs @@ -0,0 +1,21 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// +/// A stage-6 test-double provider that composes an request as a new +/// . Registered via . +/// It handles exactly and returns +/// for everything else (ADR-0072 "Precedence and misuse"). +/// +internal sealed class MetricsProvider : ICompositionValueProvider +{ + /// + public CompositionProviderResult TryProvide(in CompositionProviderRequest request, ICompositionContext context) + { + if (request.RequestedType == typeof(IMeterFactory)) + return CompositionProviderResult.Handled(new CapturingMeterFactory()); + + return CompositionProviderResult.NotHandled; + } +} diff --git a/src/Compono.Metrics/SelectionResult.cs b/src/Compono.Metrics/SelectionResult.cs new file mode 100644 index 00000000..96c26602 --- /dev/null +++ b/src/Compono.Metrics/SelectionResult.cs @@ -0,0 +1,43 @@ +namespace Compono.Metrics; + +/// +/// The outcome of resolving a selection (ADR-0072 "Selection and matching"). Carries the merged +/// measurements for the requested , whether any instrument matched the name at +/// all (rule 3, which decides whether a failed count lists existing instruments), and a description of +/// every instrument the factory has published for that diagnostic. Internal. +/// +/// The requested measurement value type. +internal readonly struct SelectionResult + where T : struct +{ + private SelectionResult( + IReadOnlyList> measurements, + bool hasCandidates, + IReadOnlyList existingInstruments) + { + Measurements = measurements; + HasCandidates = hasCandidates; + ExistingInstruments = existingInstruments; + } + + /// The merged, capture-order measurements for . + public IReadOnlyList> Measurements { get; } + + /// only when no instrument matched the requested name (rule 3). + public bool HasCandidates { get; } + + /// One description line per published instrument (meter name, version, instrument name, value + /// type), for the "existing instruments" diagnostic on a failed count against an unknown name. + public IReadOnlyList ExistingInstruments { get; } + + /// Rule 3: no instrument matched the requested name - an empty result. + public static SelectionResult NoMatch(IReadOnlyList existingInstruments) => + new([], hasCandidates: false, existingInstruments); + + /// Rules 4-7 resolved: candidate instruments exist and their measurements are merged for + /// . + public static SelectionResult Match( + IReadOnlyList> measurements, + IReadOnlyList existingInstruments) => + new(measurements, hasCandidates: true, existingInstruments); +} diff --git a/src/Compono.Metrics/StoredMeasurement.cs b/src/Compono.Metrics/StoredMeasurement.cs new file mode 100644 index 00000000..247c744e --- /dev/null +++ b/src/Compono.Metrics/StoredMeasurement.cs @@ -0,0 +1,25 @@ +namespace Compono.Metrics; + +/// +/// A captured measurement paired with the factory-wide sequence number assigned to it when it was +/// appended. Internal - the sequence number is what selection rule 7 and every snapshot use to order a +/// merged selection; it is never part of the public surface (ADR-0072 "Capture order"). The name +/// deliberately avoids "entry" to leave message wording free. +/// +/// The measurement's value type. +internal readonly struct StoredMeasurement + where T : struct +{ + public StoredMeasurement(long sequence, CapturedMeasurement measurement) + { + Sequence = sequence; + Measurement = measurement; + } + + /// The factory-wide sequence number, assigned inside the same lock acquisition that appended + /// this measurement. + public long Sequence { get; } + + /// The captured measurement itself. + public CapturedMeasurement Measurement { get; } +} diff --git a/src/Compono.Metrics/TypedCapture.cs b/src/Compono.Metrics/TypedCapture.cs new file mode 100644 index 00000000..a1409d66 --- /dev/null +++ b/src/Compono.Metrics/TypedCapture.cs @@ -0,0 +1,70 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics; + +/// +/// The typed capture buffer for one published instrument. Measurements are appended here without boxing, +/// the sequence number is assigned under in the same lock acquisition as +/// the append, and a snapshot copies out. Created only by once, at publish +/// time, from a closed generic instantiation the compiler already sees statically - never by reflection or +/// dynamic activation (ADR-0072 "Native AOT and trimming"). Internal. +/// +/// One of the seven supported measurement value types. +internal sealed class TypedCapture : IMeasurementBuffer + where T : struct +{ + private readonly CaptureState _state; + private readonly List> _measurements = []; + + public TypedCapture(CaptureState state, Instrument instrument) + { + _state = state; + Instrument = instrument; + } + + /// + public Instrument Instrument { get; } + + /// + public Type ValueType => typeof(T); + + /// + /// Appends one measurement. The tags are copied out of the BCL's span before the lock is taken + /// (ADR-0072 "Concurrency and allocation"); the sequence number is assigned inside the same lock + /// acquisition that appends (ADR-0072 "Capture order"). + /// + public void Record(T value, ReadOnlySpan> tags) + { + var tagCopy = CopyTags(tags); + + lock (_state.Gate) + { + var sequence = _state.NextSequence++; + _measurements.Add(new StoredMeasurement( + sequence, + new CapturedMeasurement(value, tagCopy, Instrument))); + } + } + + /// + public void Clear() => _measurements.Clear(); + + /// + public void CopyTo(List> destination) + { + for (var i = 0; i < _measurements.Count; i++) + destination.Add(_measurements[i]); + } + + private static KeyValuePair[] CopyTags(ReadOnlySpan> tags) + { + if (tags.Length == 0) + return []; + + var copy = new KeyValuePair[tags.Length]; + for (var i = 0; i < tags.Length; i++) + copy[i] = tags[i]; + + return copy; + } +} diff --git a/test/Compono.Metrics.AotSmokeTest/Compono.Metrics.AotSmokeTest.csproj b/test/Compono.Metrics.AotSmokeTest/Compono.Metrics.AotSmokeTest.csproj new file mode 100644 index 00000000..ec782ac6 --- /dev/null +++ b/test/Compono.Metrics.AotSmokeTest/Compono.Metrics.AotSmokeTest.csproj @@ -0,0 +1,53 @@ + + + + + Exe + + net10.0 + enable + enable + false + false + true + + false + + $(MSBuildThisFileDirectory)obj/.nuget-packages/ + + + + + + + + + + + + + + + diff --git a/test/Compono.Metrics.AotSmokeTest/Program.cs b/test/Compono.Metrics.AotSmokeTest/Program.cs new file mode 100644 index 00000000..2ed36472 --- /dev/null +++ b/test/Compono.Metrics.AotSmokeTest/Program.cs @@ -0,0 +1,165 @@ +using System.Diagnostics.Metrics; +using Compono; +using Compono.Metrics; + +namespace Compono.Metrics.AotSmokeTest; + +internal sealed class OrderService +{ + private readonly IMeterFactory _meters; + private readonly Counter _placed; + private readonly Histogram _duration; + + public OrderService(IMeterFactory meters) + { + _meters = meters; + var meter = meters.Create("Shop.Orders"); + _placed = meter.CreateCounter("shop.orders.placed"); + _duration = meter.CreateHistogram("shop.orders.duration"); + } + + public IMeterFactory Meters => _meters; + + public void PlaceOrder(string region, int quantity) + { + var tag = new KeyValuePair("region", region); + _placed.Add(1, tag); + _duration.Record(quantity * 1.5, tag); + } +} + +internal static class Program +{ + private static int Main() + { + try + { + // The generated composition path (ADR-0072 relies on the same generator-discovered + // activation other packages use), not direct construction alone - OrderService's own + // IMeterFactory constructor dependency is discovered by the shared Compono.Generators + // walk and satisfied by the stage-6 MetricsProvider that UseMetrics() registers. + var composer = Composer.Create(builder => builder.UseMetrics()); + var service = composer.Create(); + var meters = service.Meters; + + if (meters is not CapturingMeterFactory) + throw new InvalidOperationException( + $"Expected UseMetrics() to compose a CapturingMeterFactory, got '{meters.GetType()}'."); + + using var _ = meters; + + service.PlaceOrder("eu", 3); + + // Counter: exact value plus tag matching. + meters.Verify("shop.orders.placed").WithTag("region", "eu").WithValue(1).Once(); + + // Histogram: one recording, value math stays in LINQ. + var durations = meters.GetMeasurements("Shop.Orders", "shop.orders.duration"); + if (durations.Count != 1 || durations[0].Value != 4.5) + throw new InvalidOperationException( + $"Expected one histogram recording of 4.5, got {durations.Count}."); + + VerifyEveryInstrumentKindAndObservables(meters); + VerifyTagSnapshot(meters); + VerifyTypeConflictDiagnostic(meters); + VerifyDirectConstructionParity(); + + Console.WriteLine( + "PASS: UseMetrics()-composed IMeterFactory (generator-discovered activation), counter/" + + "histogram/up-down-counter/gauge capture, explicit observable polling, tag matching and " + + "snapshot copies, the type-conflict diagnostic, Verify(), and direct CapturingMeterFactory " + + "construction all survived Native AOT through the packaged Compono.Metrics dependency chain."); + return 0; + } + catch (Exception ex) + { + Console.WriteLine($"FAIL: {ex}"); + return 1; + } + } + + private static void VerifyEveryInstrumentKindAndObservables(IMeterFactory meters) + { + // A fresh factory so this factory's published-instrument set is exactly what this method makes. + using var local = new CapturingMeterFactory(); + var meter = local.Create("Kinds"); + + var counter = meter.CreateCounter("kind.counter"); + counter.Add(5); + + var upDown = meter.CreateUpDownCounter("kind.updown"); + upDown.Add(-2); + + var histogram = meter.CreateHistogram("kind.histogram"); + histogram.Record(1.25); + + var gauge = meter.CreateGauge("kind.gauge"); + gauge.Record(21.5); + + meter.CreateObservableGauge("kind.observable", () => 7); + + local.Verify("kind.counter").WithValue(5).Once(); + local.Verify("kind.updown").WithValue(-2).Once(); + local.Verify("kind.histogram").WithValue(1.25).Once(); + local.Verify("kind.gauge").WithValue(21.5).Once(); + + // Observable is captured only after an explicit poll; reads never poll. + local.Verify("kind.observable").Never(); + local.RecordObservableInstruments(); + local.Verify("kind.observable").WithValue(7).Once(); + } + + private static void VerifyTagSnapshot(IMeterFactory meters) + { + using var local = new CapturingMeterFactory(); + var meter = local.Create("Tags"); + var counter = meter.CreateCounter("tags.counter"); + + var source = new KeyValuePair[] + { + new("region", "eu"), + new("tier", "gold"), + }; + counter.Add(1, source); + + // Mutate the caller's array after recording: the captured snapshot must be an independent copy. + source[0] = new KeyValuePair("region", "us"); + + var measurement = local.GetMeasurements("tags.counter")[0]; + local.Verify("tags.counter").WithTag("region", "eu").WithTag("tier", "gold").Once(); + } + + private static void VerifyTypeConflictDiagnostic(IMeterFactory meters) + { + using var local = new CapturingMeterFactory(); + var meter = local.Create("Conflict"); + meter.CreateCounter("conflict.counter"); + meter.CreateCounter("conflict.counter"); + + try + { + local.GetMeasurements("conflict.counter"); + throw new InvalidOperationException("Expected a type-conflict InvalidOperationException."); + } + catch (InvalidOperationException ex) when (ex.Message.Contains("different types")) + { + // Expected: one selection can't merge measurements of different value types. + } + } + + private static void VerifyDirectConstructionParity() + { + // Direct construction, no composition - CapturingMeterFactory is publicly constructible. + using var direct = new CapturingMeterFactory(); + var meter = direct.Create("Direct"); + var counter = meter.CreateCounter("direct.counter"); + counter.Add(1); + direct.Verify("direct.counter").WithValue(1).Once(); + + // Reads stay valid after disposal. + var snapshot = direct.GetMeasurements("direct.counter"); + direct.Dispose(); + if (snapshot.Count != 1 || snapshot[0].Value != 1 || snapshot[0].Instrument.Name != "direct.counter") + throw new InvalidOperationException("Expected a snapshot to stay readable after disposal."); + } +} diff --git a/test/Compono.Metrics.AotSmokeTest/nuget.config b/test/Compono.Metrics.AotSmokeTest/nuget.config new file mode 100644 index 00000000..e6f831e8 --- /dev/null +++ b/test/Compono.Metrics.AotSmokeTest/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/test/Compono.Metrics.AotSmokeTest/pack-compono.sh b/test/Compono.Metrics.AotSmokeTest/pack-compono.sh new file mode 100755 index 00000000..dc3e6870 --- /dev/null +++ b/test/Compono.Metrics.AotSmokeTest/pack-compono.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Packs Compono and Compono.Metrics into this project's own local NuGet feed (nuget.config) so the +# AOT publish-and-run proof consumes Compono.Metrics via an ordinary PackageReference - the same way +# any real consumer does - rather than a ProjectReference, which propagates dotnet publish's global +# properties (PublishAot/RuntimeIdentifier/SelfContained) down into Compono.csproj's own +# analyzer-only ProjectReference to Compono.Generators.csproj (netstandard2.0) and fails with +# NETSDK1207 ("AOT is not supported for the target framework") for a project that's never actually +# part of the published app. No concurrency lock (unlike Compono.XunitV3.SampleTests' +# pack-to-local-feed.sh) - this project is a one-shot manual smoke test, not run concurrently across +# TFMs in CI. Mirrors test/Compono.Logging.AotSmokeTest/pack-compono.sh, packing Compono.Metrics +# instead of Compono.Logging. +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +feed_dir="$script_dir/../../.local-nuget-feed-metrics-aot-smoke" +restore_packages_path="$script_dir/obj/.nuget-packages" + +mkdir -p "$feed_dir" +rm -f "$feed_dir"/Compono.*.nupkg + +# NuGet treats a package id+version already present in a packages folder as immutable and never +# re-extracts it - without clearing this project's own isolated restore path (see the .csproj's +# RestorePackagesPath), a rerun after changing Compono/Compono.Metrics source would silently keep +# serving the first run's cached packages instead of the freshly repacked nupkgs below. +rm -rf "$restore_packages_path" + +dotnet pack "$script_dir/../../src/Compono/Compono.csproj" -c Release -o "$feed_dir" -p:Version=1.0.0 --nologo +dotnet pack "$script_dir/../../src/Compono.Metrics/Compono.Metrics.csproj" -c Release -o "$feed_dir" -p:Version=1.0.0 --nologo diff --git a/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh b/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh new file mode 100755 index 00000000..2c704766 --- /dev/null +++ b/test/Compono.Metrics.AotSmokeTest/verify-packaging.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# PLAN-0074 phase B4: makes the packaging shape ADR-0072 requires permanent and reproducible, +# rather than relying only on manual pack/inspect/consume verification during implementation. +# Mirrors test/Compono.Logging.AotSmokeTest/verify-packaging.sh's own "pack, then assert, fail +# loudly with the evidence" shape. +# +# Confirms, from a real packed .nupkg (not source, not a ProjectReference): +# 1. Compono.Metrics.nupkg ships no analyzer/props of its own. +# 2. Compono.Metrics.nupkg's .nuspec has exactly one dependency group per target TFM (4), each with +# exactly one dependency - Compono - pinned to the exact version (ADR-0072: zero dependency +# beyond core Compono; the exact-version pin target is the same one every other package uses). +# 3. A scratch PackageReference consumer of Compono.Metrics ALONE (no explicit property, no +# ProjectReference workaround) gets real generator-discovered IMeterFactory composition, capture, +# tag matching, and Verify() - proving the whole chain flows transitively through Compono. +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_root="$(cd "$script_dir/../.." && pwd)" +feed_dir="$repo_root/.local-nuget-feed-metrics-aot-smoke" +work_dir="$(mktemp -d)" +trap 'rm -rf "$work_dir"' EXIT + +echo "verify-packaging.sh: packing Compono/Compono.Metrics into the local feed ..." +bash "$script_dir/pack-compono.sh" + +echo "verify-packaging.sh: inspecting packed nupkg contents ..." +metrics_inspect="$work_dir/inspect-metrics" +mkdir -p "$metrics_inspect" +unzip -o -q "$feed_dir/Compono.Metrics.1.0.0.nupkg" -d "$metrics_inspect" + +fail() { + echo "verify-packaging.sh: FAIL - $1" >&2 + exit 1 +} + +[ -d "$metrics_inspect/analyzers" ] && fail "Compono.Metrics.nupkg unexpectedly contains an analyzers/ directory - it must ship no generator/analyzer DLL of its own" +[ -d "$metrics_inspect/build" ] && fail "Compono.Metrics.nupkg unexpectedly contains a build/ directory - it must ship no props of its own" + +nuspec=$(find "$metrics_inspect" -maxdepth 1 -name '*.nuspec' | head -n 1) +[ -n "$nuspec" ] || fail "Compono.Metrics.nupkg is missing its .nuspec" + +group_count=$(grep -o ' "$consumer_dir/nuget.config" < + + + + + + + +EOF +cat > "$consumer_dir/Consumer.csproj" < + + Exe + net10.0 + enable + enable + false + $consumer_dir/.nuget-packages + + + + + +EOF +cat > "$consumer_dir/Program.cs" <<'EOF' +using System.Diagnostics.Metrics; +using Compono; +using Compono.Metrics; + +var composer = Composer.Create(builder => builder.UseMetrics()); +var meters = composer.Create(); +using var _ = meters; + +var meter = meters.Create("Smoke"); +var counter = meter.CreateCounter("smoke.counter"); +counter.Add(1, new KeyValuePair("region", "eu")); + +meters.Verify("smoke.counter").WithTag("region", "eu").WithValue(1).Once(); +Console.WriteLine(meters is CapturingMeterFactory ? "METRICS-COMPOSITION-OK" : "UNEXPECTED-FACTORY"); +EOF + +consumer_output=$(cd "$consumer_dir" && dotnet run -c Release 2>&1) +echo "$consumer_output" | grep -q "METRICS-COMPOSITION-OK" || { + echo "verify-packaging.sh: FAIL - a PackageReference-only consumer of Compono.Metrics did not compose/capture as expected. Output:" >&2 + echo "$consumer_output" >&2 + exit 1 +} +echo "verify-packaging.sh: confirmed - PackageReference-only composition works." + +echo "verify-packaging.sh: PASS - all packaging/consumption behaviors confirmed against a real packed nupkg." diff --git a/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs b/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs new file mode 100644 index 00000000..14a66326 --- /dev/null +++ b/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs @@ -0,0 +1,246 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class CapturingMeterFactoryTests +{ + [Fact] + public void Create_Throws_WhenOptionsIsNull() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.Create(null!); + + act.Should().Throw(); + } + + [Fact] + public void Create_Throws_WhenScopeBelongsToAnotherFactory() + { + using var factory = new CapturingMeterFactory(); + var options = new MeterOptions("Shop") { Scope = new CapturingMeterFactory() }; + + var act = () => factory.Create(options); + + act.Should().Throw(); + } + + [Fact] + public void Create_ThrowsObjectDisposed_AfterDispose() + { + var factory = new CapturingMeterFactory(); + factory.Dispose(); + + var act = () => factory.Create(new MeterOptions("Shop")); + + act.Should().Throw(); + } + + [Fact] + public void Create_DoesNotMutateCallerOptions() + { + using var factory = new CapturingMeterFactory(); + var options = new MeterOptions("Shop"); + + var meter = factory.Create(options); + + options.Scope.Should().BeNull(); + meter.Scope.Should().BeSameAs(factory); + } + + [Fact] + public void Create_ReturnsSameInstance_ForSameNameVersionAndTags() + { + using var factory = new CapturingMeterFactory(); + var tags = new[] { new KeyValuePair("env", "test") }; + + var first = factory.Create(new MeterOptions("Shop") { Version = "1.0", Tags = tags }); + var second = factory.Create(new MeterOptions("Shop") { Version = "1.0", Tags = tags }); + + second.Should().BeSameAs(first); + } + + [Fact] + public void Create_TreatsTagOrderAsInsensitive() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("a", "1"), + new KeyValuePair("b", "2"), + ], + }); + var second = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("b", "2"), + new KeyValuePair("a", "1"), + ], + }); + + second.Should().BeSameAs(first); + } + + [Fact] + public void Create_ReturnsDifferentInstance_ForDifferentVersion() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") { Version = "1.0" }); + var second = factory.Create(new MeterOptions("Shop") { Version = "2.0" }); + + second.Should().NotBeSameAs(first); + } + + [Fact] + public void Create_ReturnsDifferentInstance_ForDifferentTags() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") + { + Tags = [new KeyValuePair("env", "test")], + }); + var second = factory.Create(new MeterOptions("Shop") + { + Tags = [new KeyValuePair("env", "prod")], + }); + + second.Should().NotBeSameAs(first); + } + + [Fact] + public void Create_ReturnsSameInstance_ForDuplicateKeysWithIdenticalValues() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("k", "1"), + new KeyValuePair("k", "1"), + ], + }); + var second = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("k", "1"), + new KeyValuePair("k", "1"), + ], + }); + + second.Should().BeSameAs(first); + } + + [Fact] + public void Create_ReturnsDifferentInstance_ForDuplicateKeysWithDifferentSecondEntry() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("k", "1"), + new KeyValuePair("k", "1"), + ], + }); + var second = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("k", "1"), + new KeyValuePair("j", "2"), + ], + }); + + second.Should().NotBeSameAs(first); + } + + [Fact] + public void Create_ReturnsDifferentInstance_ForDuplicateKeysWithDifferentCount() + { + using var factory = new CapturingMeterFactory(); + + var first = factory.Create(new MeterOptions("Shop") + { + Tags = [ + new KeyValuePair("k", "1"), + new KeyValuePair("k", "1"), + ], + }); + var second = factory.Create(new MeterOptions("Shop") + { + Tags = [new KeyValuePair("k", "1")], + }); + + second.Should().NotBeSameAs(first); + } + + [Fact] + public void Dispose_IsIdempotent() + { + var factory = new CapturingMeterFactory(); + factory.Create(new MeterOptions("Shop")); + + var act = () => + { + factory.Dispose(); + factory.Dispose(); + }; + + act.Should().NotThrow(); + } + + [Fact] + public void Create_IsThreadSafe_ReturnsSingleInstanceForConcurrentCallers() + { + using var factory = new CapturingMeterFactory(); + var results = new Meter[32]; + + Parallel.For(0, results.Length, i => results[i] = factory.Create(new MeterOptions("Shop"))); + + results.Distinct(ReferenceEqualityComparer.Instance).Should().ContainSingle(); + } + + [Fact] + public void CreateAndDisposeConcurrently_DisposesSafely_AndRejectsLaterCreate() + { + var factory = new CapturingMeterFactory(); + using var barrier = new Barrier(2); + Exception? unexpected = null; + + Parallel.Invoke( + () => + { + barrier.SignalAndWait(); + for (var i = 0; i < 200; i++) + { + try + { + factory.Create(new MeterOptions("Shop")); + } + catch (ObjectDisposedException) + { + // Disposal may win the race at any point; that is the documented outcome. + break; + } + catch (Exception exception) + { + unexpected = exception; + break; + } + } + }, + () => + { + barrier.SignalAndWait(); + factory.Dispose(); + }); + + unexpected.Should().BeNull(); + + var act = () => factory.Create(new MeterOptions("Shop")); + act.Should().Throw(); + } +} diff --git a/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj b/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj new file mode 100644 index 00000000..8d653b35 --- /dev/null +++ b/test/Compono.Metrics.Tests/Compono.Metrics.Tests.csproj @@ -0,0 +1,48 @@ + + + + enable + enable + Exe + Compono.Metrics.Tests + false + true + + true + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/Compono.Metrics.Tests/CompositionTests.cs b/test/Compono.Metrics.Tests/CompositionTests.cs new file mode 100644 index 00000000..37152506 --- /dev/null +++ b/test/Compono.Metrics.Tests/CompositionTests.cs @@ -0,0 +1,84 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class CompositionTests +{ + [Fact] + public void UseMetrics_ComposesIMeterFactory_AsCapturingMeterFactory() + { + var composer = Composer.Create(builder => builder.UseMetrics()); + + var service = composer.Create(); + + service.Meters.Should().BeOfType(); + } + + [Fact] + public void UseMetrics_DoesNotBreakComposition_ForTypesWithNoMeterDependency() + { + var composer = Composer.Create(builder => builder.UseMetrics()); + + var value = composer.Create(); + + value.Should().NotBeNull(); + } + + [Fact] + public void EachComposedRequest_GetsItsOwnFactory_AbsentShared() + { + var composer = Composer.Create(builder => builder.UseMetrics()); + + var first = composer.Create(); + var second = composer.Create(); + + second.Meters.Should().NotBeSameAs(first.Meters); + } + + [Fact] + public void Share_MakesMeterFactoryGraphWide_WithinOneRoot() + { + var composer = Composer.Create(builder => builder.UseMetrics().Share()); + + var coordinator = composer.Create(); + + coordinator.Meters.Should().BeSameAs(coordinator.Service.Meters); + } + + [Fact] + public void ExactRegistration_ForIMeterFactory_TakesPrecedenceOverUseMetrics() + { + using var registered = new CapturingMeterFactory(); + var composer = Composer.Create(builder => + { + builder.Register(() => registered); + builder.UseMetrics(); + }); + + var service = composer.Create(); + + service.Meters.Should().BeSameAs(registered); + } + + [Fact] + public void UseMetricsBeforeUseNSubstitute_IMeterFactory_ResolvesToCapturingMeterFactory() + { + var composer = Composer.Create(builder => builder.UseMetrics().UseNSubstitute()); + + var service = composer.Create(); + + service.Meters.Should().BeOfType(); + } + + [Fact] + public void UseNSubstituteBeforeUseMetrics_IMeterFactory_ResolvesToSubstitute() + { + // First-registered-wins (ADR-0024). Reversing order is the documented consequence, not a + // diagnostic - the misuse surface (MeterFactoryTestingExtensions) is what surfaces the cause. + var composer = Composer.Create(builder => builder.UseNSubstitute().UseMetrics()); + + var meters = composer.Create(); + + (meters is CapturingMeterFactory).Should().BeFalse(); + } +} diff --git a/test/Compono.Metrics.Tests/CultureInvarianceTests.cs b/test/Compono.Metrics.Tests/CultureInvarianceTests.cs new file mode 100644 index 00000000..429cb337 --- /dev/null +++ b/test/Compono.Metrics.Tests/CultureInvarianceTests.cs @@ -0,0 +1,35 @@ +using System.Diagnostics.Metrics; +using System.Globalization; + +namespace Compono.Metrics.Tests; + +public sealed class CultureInvarianceTests +{ + [Fact] + public void FailureMessage_FormatsNumericValueAndTagWithInvariantCulture() + { + var originalCulture = CultureInfo.CurrentCulture; + try + { + // de-DE renders a decimal point as a comma; the message must not follow it. + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateHistogram("duration").Record( + 1.5, + new KeyValuePair("ratio", 1.5)); + + var act = () => factory.Verify("duration").WithTag("ratio", 2.5).WithValue(9.5).Once(); + + act.Should().Throw() + .WithMessage( + "Expected exactly 1 call(s) to instrument \"duration\" (double) " + + "with tag ratio = 2.5 (double) and value 9.5, but received 0."); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } + } +} diff --git a/test/Compono.Metrics.Tests/GaugeCaptureTests.cs b/test/Compono.Metrics.Tests/GaugeCaptureTests.cs new file mode 100644 index 00000000..d809aa37 --- /dev/null +++ b/test/Compono.Metrics.Tests/GaugeCaptureTests.cs @@ -0,0 +1,57 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +/// +/// Regression coverage for the capture classification. +/// derives from , so it is captured on every target framework whose +/// runtime provides it - including a net8.0 consumer running against a newer +/// System.Diagnostics.DiagnosticSource (the net8.0 test build references 9.x for exactly this +/// reason). This file is deliberately not guarded by #if NET9_0_OR_GREATER: the whole point +/// is that capture is decided by the instrument's base type, not by the compile-time target. +/// +public sealed class GaugeCaptureTests +{ + [Fact] + public void GaugeDouble_IsCaptured_OnEveryTargetFramework() + { + using var meters = new CapturingMeterFactory(); + using var meter = meters.Create(new MeterOptions("Shop.Queue")); + var gauge = meter.CreateGauge("shop.queue.length"); + + gauge.Record(3.5); + + var captured = meters.GetMeasurements("shop.queue.length"); + + captured.Should().ContainSingle(); + captured[0].Value.Should().Be(3.5); + captured[0].Instrument.Should().BeSameAs(gauge); + } + + [Fact] + public void GaugeDouble_IsVerifiable_OnEveryTargetFramework() + { + using var meters = new CapturingMeterFactory(); + using var meter = meters.Create(new MeterOptions("Shop.Queue")); + var gauge = meter.CreateGauge("shop.queue.length"); + + gauge.Record(7.25, new KeyValuePair("region", "eu")); + + meters.Verify("shop.queue.length").WithValue(7.25).WithTag("region", "eu").Once(); + } + + [Fact] + public void GaugeDouble_ComposesAndCaptures_OnEveryTargetFramework() + { + var composer = Composer.Create(builder => builder.UseMetrics()); + var meters = (CapturingMeterFactory)composer.Create(); + using var _ = meters; + + using var meter = meters.Create(new MeterOptions("Shop.Queue")); + var gauge = meter.CreateGauge("shop.queue.length"); + gauge.Record(11.0); + + meters.GetMeasurements("shop.queue.length").Should().ContainSingle() + .Which.Instrument.Should().BeSameAs(gauge); + } +} diff --git a/test/Compono.Metrics.Tests/HostRecipeTests.cs b/test/Compono.Metrics.Tests/HostRecipeTests.cs new file mode 100644 index 00000000..16e0ffb2 --- /dev/null +++ b/test/Compono.Metrics.Tests/HostRecipeTests.cs @@ -0,0 +1,95 @@ +using System.Diagnostics.Metrics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; + +namespace Compono.Metrics.Tests; + +public sealed class HostRecipeTests +{ + [Fact] + public async Task HostRecipe_RegisteredFactoryIsTheOneTheSutUses() + { + using var meters = new CapturingMeterFactory(); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(meters); + builder.Services.AddSingleton(); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + var service = host.Services.GetRequiredService(); + service.Meters.Should().BeSameAs(meters); + service.PlaceOrder("eu", 2); + await host.StopAsync(TestContext.Current.CancellationToken); + + meters.Verify("Shop.Orders", "shop.orders.placed").WithTag("region", "eu").Once(); + } + + [Fact] + public async Task HostRecipe_TestOwnsDisposal_AfterHostStops() + { + var meters = new CapturingMeterFactory(); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(meters); + builder.Services.AddSingleton(); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + host.Services.GetRequiredService().PlaceOrder("us", 1); + await host.StopAsync(TestContext.Current.CancellationToken); + + // The container doesn't dispose an instance registration, so the test's own using owns it. + meters.Dispose(); + + meters.GetMeasurements("Shop.Orders", "shop.orders.duration").Should().ContainSingle(); + } + + [Fact] + public async Task HostRecipe_BuilderAlreadyRegistersADefaultMeterFactory() + { + var builder = Host.CreateApplicationBuilder(); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + var factory = host.Services.GetRequiredService(); + await host.StopAsync(TestContext.Current.CancellationToken); + + factory.Should().NotBeNull(); + (factory is CapturingMeterFactory).Should().BeFalse( + "the default host registers its own IMeterFactory before the test registers anything"); + } + + [Fact] + public async Task HostRecipe_LaterRegistrationWinsForSingleServiceResolution() + { + using var first = new CapturingMeterFactory(); + using var second = new CapturingMeterFactory(); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(first); + builder.Services.AddSingleton(second); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + var resolved = host.Services.GetRequiredService(); + await host.StopAsync(TestContext.Current.CancellationToken); + + resolved.Should().BeSameAs(second); + } + + [Fact] + public async Task HostRecipe_TryAddSingletonDoesNotReplaceAnExistingRegistration() + { + using var meters = new CapturingMeterFactory(); + var builder = Host.CreateApplicationBuilder(); + + // The host already registered a default IMeterFactory, so TryAddSingleton keeps that one. + builder.Services.TryAddSingleton(meters); + using var host = builder.Build(); + + await host.StartAsync(TestContext.Current.CancellationToken); + var resolved = host.Services.GetRequiredService(); + await host.StopAsync(TestContext.Current.CancellationToken); + + resolved.Should().NotBeSameAs(meters); + } +} diff --git a/test/Compono.Metrics.Tests/InstrumentCaptureTests.cs b/test/Compono.Metrics.Tests/InstrumentCaptureTests.cs new file mode 100644 index 00000000..ad0538b8 --- /dev/null +++ b/test/Compono.Metrics.Tests/InstrumentCaptureTests.cs @@ -0,0 +1,105 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class InstrumentCaptureTests +{ + [Fact] + public void Counter_Byte_IsCaptured() => AssertCounter(1); + + [Fact] + public void Counter_Short_IsCaptured() => AssertCounter(2); + + [Fact] + public void Counter_Int_IsCaptured() => AssertCounter(3); + + [Fact] + public void Counter_Long_IsCaptured() => AssertCounter(4); + + [Fact] + public void Counter_Float_IsCaptured() => AssertCounter(5.5f); + + [Fact] + public void Counter_Double_IsCaptured() => AssertCounter(6.5); + + [Fact] + public void Counter_Decimal_IsCaptured() => AssertCounter(7.5m); + + [Fact] + public void UpDownCounter_IsCaptured() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateUpDownCounter("shop.queue.depth"); + + counter.Add(-2); + + var measurements = factory.GetMeasurements("shop.queue.depth"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(-2); + } + + [Fact] + public void Histogram_IsCaptured() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var histogram = meter.CreateHistogram("shop.orders.duration"); + + histogram.Record(1.5); + histogram.Record(2.5); + + var measurements = factory.GetMeasurements("shop.orders.duration"); + measurements.Should().HaveCount(2); + measurements[0].Value.Should().Be(1.5); + measurements[1].Value.Should().Be(2.5); + } + +#if NET9_0_OR_GREATER + [Fact] + public void Gauge_IsCaptured() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var gauge = meter.CreateGauge("shop.queue.gauge"); + + gauge.Record(9.5); + + var measurements = factory.GetMeasurements("shop.queue.gauge"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(9.5); + } +#endif + + [Fact] + public void Capture_UsesMeterAndInstrumentNames_FromTheComposedFactoryOnly() + { + using var factory = new CapturingMeterFactory(); + using var other = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var otherMeter = other.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + var otherCounter = otherMeter.CreateCounter("orders"); + + counter.Add(1); + otherCounter.Add(99); + + var measurements = factory.GetMeasurements("orders"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(1); + } + + private static void AssertCounter(T value) + where T : struct + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("measured"); + + counter.Add(value); + + var measurements = factory.GetMeasurements("measured"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(value); + } +} diff --git a/test/Compono.Metrics.Tests/IsolationAndConcurrencyTests.cs b/test/Compono.Metrics.Tests/IsolationAndConcurrencyTests.cs new file mode 100644 index 00000000..f2275166 --- /dev/null +++ b/test/Compono.Metrics.Tests/IsolationAndConcurrencyTests.cs @@ -0,0 +1,110 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class IsolationAndConcurrencyTests +{ + [Fact] + public void TwoFactoriesUnderParallelExecution_NeverSeeEachOthersMeasurements() + { + using var first = new CapturingMeterFactory(); + using var second = new CapturingMeterFactory(); + var firstMeter = first.Create(new MeterOptions("Shop")); + var secondMeter = second.Create(new MeterOptions("Shop")); + var firstCounter = firstMeter.CreateCounter("orders"); + var secondCounter = secondMeter.CreateCounter("orders"); + + Parallel.Invoke( + () => { for (var i = 0; i < 500; i++) firstCounter.Add(1); }, + () => { for (var i = 0; i < 300; i++) secondCounter.Add(1); }); + + first.GetMeasurements("orders").Should().HaveCount(500); + second.GetMeasurements("orders").Should().HaveCount(300); + } + + [Fact] + public void ConcurrentRecordings_AreAllCaptured_AndReadsAreSafe() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + + Parallel.For(0, 1000, _ => + { + counter.Add(1); + factory.GetMeasurements("orders"); + factory.Verify("orders").AtLeast(0); + }); + + factory.GetMeasurements("orders").Should().HaveCount(1000); + } + + [Fact] + public void ConcurrentClearAndRecord_KeepsCaptureConsistent() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + const int iterations = 500; + var observed = new ConcurrentQueue(); + + Parallel.For(0, iterations, i => + { + counter.Add(1); + observed.Enqueue(factory.GetMeasurements("orders").Count); + if (i % 50 == 49) + factory.ClearMeasurements(); + }); + + factory.ClearMeasurements(); + + // Clear fully empties every instrument, and a recording is never lost, duplicated, or torn: + // every snapshot count sits between 0 and the number of recordings made by that point. + factory.GetMeasurements("orders").Should().BeEmpty(); + observed.Should().NotBeEmpty(); + observed.Should().OnlyContain(count => count >= 0 && count <= iterations); + observed.Should().Contain(count => count > 0); + } + + [Fact] + public void RecordingWhileDisposing_DoesNotThrow_AndStopsCapturingAfterDispose() + { + var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + using var barrier = new Barrier(2); + Exception? unexpected = null; + + Parallel.Invoke( + () => + { + barrier.SignalAndWait(); + try + { + for (var i = 0; i < 1000; i++) + counter.Add(1); + } + catch (Exception exception) + { + unexpected = exception; + } + }, + () => + { + barrier.SignalAndWait(); + factory.Dispose(); + }); + + unexpected.Should().BeNull(); + + var captured = factory.GetMeasurements("orders").Count; + captured.Should().BeInRange(0, 1000); + + // Disposal has completed, so a further recording is not captured - and reads/clears still work. + counter.Add(1); + factory.GetMeasurements("orders").Should().HaveCount(captured); + var act = () => factory.ClearMeasurements(); + act.Should().NotThrow(); + } +} diff --git a/test/Compono.Metrics.Tests/MisuseTests.cs b/test/Compono.Metrics.Tests/MisuseTests.cs new file mode 100644 index 00000000..fe54b77d --- /dev/null +++ b/test/Compono.Metrics.Tests/MisuseTests.cs @@ -0,0 +1,52 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class MisuseTests +{ + private static IMeterFactory ForeignFactory() => Substitute.For(); + + [Fact] + public void GetMeasurements_ThrowsOnForeignFactory_NamingUseMetrics() + { + var act = () => ForeignFactory().GetMeasurements("orders"); + + act.Should().Throw() + .WithMessage("*UseMetrics()*"); + } + + [Fact] + public void Verify_ThrowsOnForeignFactory() + { + var act = () => ForeignFactory().Verify("orders"); + + act.Should().Throw() + .WithMessage("*UseMetrics()*"); + } + + [Fact] + public void RecordObservableInstruments_ThrowsOnForeignFactory() + { + var act = () => ForeignFactory().RecordObservableInstruments(); + + act.Should().Throw(); + } + + [Fact] + public void ClearMeasurements_ThrowsOnForeignFactory() + { + var act = () => ForeignFactory().ClearMeasurements(); + + act.Should().Throw(); + } + + [Fact] + public void Extensions_ThrowArgumentNull_WhenFactoryIsNull() + { + IMeterFactory? factory = null; + + var act = () => factory!.ClearMeasurements(); + + act.Should().Throw(); + } +} diff --git a/test/Compono.Metrics.Tests/ObservableInstrumentTests.cs b/test/Compono.Metrics.Tests/ObservableInstrumentTests.cs new file mode 100644 index 00000000..94a220e7 --- /dev/null +++ b/test/Compono.Metrics.Tests/ObservableInstrumentTests.cs @@ -0,0 +1,133 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class ObservableInstrumentTests +{ + [Fact] + public void RecordObservableInstruments_PollsObservableCounter() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableCounter("shop.queue.depth", () => 7); + + factory.GetMeasurements("shop.queue.depth").Should().BeEmpty(); + + factory.RecordObservableInstruments(); + + var measurements = factory.GetMeasurements("shop.queue.depth"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(7); + } + + [Fact] + public void RecordObservableInstruments_PollsObservableGauge() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableGauge("shop.queue.gauge", () => 3.25); + + factory.RecordObservableInstruments(); + + var measurements = factory.GetMeasurements("shop.queue.gauge"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(3.25); + } + + [Fact] + public void RecordObservableInstruments_PollsObservableUpDownCounter() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableUpDownCounter("shop.queue.pending", () => 11L); + + factory.RecordObservableInstruments(); + + var measurements = factory.GetMeasurements("shop.queue.pending"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(11); + } + + [Fact] + public void ReadsDoNotPoll_AndHaveNoSideEffects() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableCounter("shop.queue.depth", () => 7); + + factory.GetMeasurements("shop.queue.depth").Should().BeEmpty(); + factory.GetMeasurements("shop.queue.depth").Should().BeEmpty(); + } + + [Fact] + public void RecordObservableInstruments_TwiceRecordsTwice() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableCounter("shop.queue.depth", () => 7); + + factory.RecordObservableInstruments(); + factory.RecordObservableInstruments(); + + factory.GetMeasurements("shop.queue.depth").Should().HaveCount(2); + } + + [Fact] + public void RecordObservableInstruments_BeforeFirstCreate_IsNoOp() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.RecordObservableInstruments(); + + act.Should().NotThrow(); + } + + [Fact] + public void RecordObservableInstruments_AfterDispose_IsNoOp() + { + var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateObservableCounter("shop.queue.depth", () => 7); + factory.Dispose(); + + var act = () => factory.RecordObservableInstruments(); + + act.Should().NotThrow(); + factory.GetMeasurements("shop.queue.depth").Should().BeEmpty(); + } + + [Fact] + public void PollingOneFactory_DoesNotPollAnother() + { + using var first = new CapturingMeterFactory(); + using var second = new CapturingMeterFactory(); + var firstMeter = first.Create(new MeterOptions("Shop")); + var secondMeter = second.Create(new MeterOptions("Shop")); + firstMeter.CreateObservableCounter("depth", () => 1); + secondMeter.CreateObservableCounter("depth", () => 2); + + first.RecordObservableInstruments(); + + var firstMeasurements = first.GetMeasurements("depth"); + firstMeasurements.Should().ContainSingle(); + firstMeasurements[0].Value.Should().Be(1); + second.GetMeasurements("depth").Should().BeEmpty(); + } + + [Fact] + public void RecordObservableInstruments_ThrowingCallback_PropagatesAggregateException_AndRecordsOthers() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + Func boom = () => throw new InvalidOperationException("boom"); + meter.CreateObservableGauge("boom", boom); + meter.CreateObservableCounter("depth", () => 5); + + var act = () => factory.RecordObservableInstruments(); + + act.Should().Throw() + .WithInnerException(); + factory.GetMeasurements("depth").Should().ContainSingle() + .Which.Value.Should().Be(5); + } +} diff --git a/test/Compono.Metrics.Tests/SelectionTests.cs b/test/Compono.Metrics.Tests/SelectionTests.cs new file mode 100644 index 00000000..421bf9b3 --- /dev/null +++ b/test/Compono.Metrics.Tests/SelectionTests.cs @@ -0,0 +1,174 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class SelectionTests +{ + [Fact] + public void NullInstrumentName_ThrowsArgumentException() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.GetMeasurements(null!); + + act.Should().Throw(); + } + + [Fact] + public void EmptyInstrumentName_ThrowsArgumentException() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.GetMeasurements(string.Empty); + + act.Should().Throw(); + } + + [Fact] + public void UnsupportedValueType_ThrowsArgumentException_NamingTheSevenTypes() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.GetMeasurements("anything"); + + act.Should().Throw() + .WithMessage("*byte, short, int, long, float, double, decimal*"); + } + + [Fact] + public void Verify_UnsupportedValueType_ThrowsArgumentException_AtBuilderCreation() + { + using var factory = new CapturingMeterFactory(); + + var act = () => factory.Verify("anything"); + + act.Should().Throw(); + } + + [Fact] + public void UnknownInstrumentName_YieldsEmptyResult() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders"); + + factory.GetMeasurements("no.such.instrument").Should().BeEmpty(); + } + + [Fact] + public void UnknownInstrumentName_NeverPasses_AndFailingOnce_ListsExistingInstruments() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders"); + + factory.Verify("typo").Never(); + + var act = () => factory.Verify("typo").Once(); + + act.Should().Throw() + .WithMessage( + "Expected exactly 1 call(s) to instrument \"typo\" (int), but received 0. " + + "No instrument named \"typo\" has been published by this factory. " + + "Existing instruments: meter \"Shop\": instrument \"orders\" (int)."); + } + + [Fact] + public void UnknownInstrumentNameInNamedMeter_ReportsTheMeterAndExistingInstruments() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders"); + + var act = () => factory.Verify("Shop", "typo").Once(); + + act.Should().Throw() + .WithMessage( + "Expected exactly 1 call(s) to instrument \"typo\" in meter \"Shop\" (int), but received 0. " + + "No instrument named \"typo\" has been published by meter \"Shop\". " + + "Existing instruments: meter \"Shop\": instrument \"orders\" (int)."); + } + + [Fact] + public void AmbiguousMeterNames_OnOneArgumentOverload_ThrowsInvalidOperationException() + { + using var factory = new CapturingMeterFactory(); + var first = factory.Create(new MeterOptions("A")); + var second = factory.Create(new MeterOptions("B")); + first.CreateCounter("shared"); + second.CreateCounter("shared"); + + var act = () => factory.GetMeasurements("shared"); + + act.Should().Throw() + .WithMessage("*two-argument*"); + } + + [Fact] + public void TwoArgumentOverload_ResolvesAmbiguityByMeterName() + { + using var factory = new CapturingMeterFactory(); + var first = factory.Create(new MeterOptions("A")); + var second = factory.Create(new MeterOptions("B")); + first.CreateCounter("shared").Add(1); + second.CreateCounter("shared").Add(2); + + var measurements = factory.GetMeasurements("A", "shared"); + measurements.Should().ContainSingle(); + measurements[0].Value.Should().Be(1); + } + + [Fact] + public void ConflictingValueTypes_ThrowInvalidOperationException_EvenWhenOneMatches() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("x"); + meter.CreateCounter("x"); + + var act = () => factory.GetMeasurements("x"); + + act.Should().Throw() + .WithMessage("*different types*"); + } + + [Fact] + public void ValueTypeMismatch_ThrowsInvalidOperationException_NamingTheRecordedType() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("x"); + + var act = () => factory.GetMeasurements("Shop", "x"); + + act.Should().Throw() + .WithMessage("*records int, not long*"); + } + + [Fact] + public void SameNamedMeters_WithDifferentVersions_MergeWhenTypesAgree() + { + using var factory = new CapturingMeterFactory(); + var v1 = factory.Create(new MeterOptions("Shop") { Version = "1.0" }); + var v2 = factory.Create(new MeterOptions("Shop") { Version = "2.0" }); + v1.CreateCounter("x").Add(1); + v2.CreateCounter("x").Add(2); + + var measurements = factory.GetMeasurements("Shop", "x"); + measurements.Should().HaveCount(2); + measurements.Select(m => m.Value).Should().BeEquivalentTo([1, 2]); + } + + [Fact] + public void TypeConflict_ThrowsAtBuilderCreation_BeforeAnyFilterIsAdded() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("x"); + meter.CreateCounter("x"); + + var act = () => factory.Verify("Shop", "x"); + + act.Should().Throw(); + } +} diff --git a/test/Compono.Metrics.Tests/SnapshotAndDisposalTests.cs b/test/Compono.Metrics.Tests/SnapshotAndDisposalTests.cs new file mode 100644 index 00000000..f6df1b3d --- /dev/null +++ b/test/Compono.Metrics.Tests/SnapshotAndDisposalTests.cs @@ -0,0 +1,157 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class SnapshotAndDisposalTests +{ + [Fact] + public void CapturedTags_AreACopy_UnaffectedByLaterMutationOfTheSourceArray() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + var tags = new[] { new KeyValuePair("region", "eu") }; + + counter.Add(1, tags); + tags[0] = new KeyValuePair("region", "us"); + + var measurements = factory.GetMeasurements("orders"); + measurements[0].Tags.Should().ContainSingle() + .Which.Value.Should().Be("eu"); + } + + [Fact] + public void MeasurementsWithoutTags_GetEmptyNonNullTagList() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1); + + var measurements = factory.GetMeasurements("orders"); + measurements[0].Tags.Should().NotBeNull(); + measurements[0].Tags.Should().BeEmpty(); + } + + [Fact] + public void GetMeasurements_ReturnsANewListEachCall() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1); + + var first = factory.GetMeasurements("orders"); + var second = factory.GetMeasurements("orders"); + + second.Should().NotBeSameAs(first); + } + + [Fact] + public void ClearMeasurements_EmptiesEveryInstrument() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1); + meter.CreateHistogram("duration").Record(1.0); + + factory.ClearMeasurements(); + + factory.GetMeasurements("orders").Should().BeEmpty(); + factory.GetMeasurements("duration").Should().BeEmpty(); + } + + [Fact] + public void CaptureOrder_IsPreservedForSequentialRecordings() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + counter.Add(1); + counter.Add(2); + counter.Add(3); + + factory.GetMeasurements("orders").Select(m => m.Value) + .Should().ContainInOrder(1L, 2L, 3L); + } + + [Fact] + public void CaptureOrder_ForMergedSelection_OrdersByCaptureSequence_NotByMeterRegistration() + { + using var factory = new CapturingMeterFactory(); + + // "2.0" is created (and publishes its instrument) before "1.0", so a naive concatenation of the + // two instruments' buffers would yield [1, 3, 2]. The merged selection must instead sort by the + // global capture sequence - removing that sort fails this test. + var v2 = factory.Create(new MeterOptions("Shop") { Version = "2.0" }); + var v1 = factory.Create(new MeterOptions("Shop") { Version = "1.0" }); + var v2Counter = v2.CreateCounter("x"); + var v1Counter = v1.CreateCounter("x"); + + v2Counter.Add(1); + v1Counter.Add(2); + v2Counter.Add(3); + + factory.GetMeasurements("Shop", "x").Select(m => m.Value) + .Should().Equal(1, 2, 3); + } + + [Fact] + public void Snapshot_StaysReadable_AfterDispose() + { + var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop") { Version = "1.0" }); + meter.CreateCounter("orders").Add(5, + new KeyValuePair("region", "eu")); + + var snapshot = factory.GetMeasurements("orders"); + factory.Dispose(); + + snapshot[0].Value.Should().Be(5); + snapshot[0].Tags.Should().ContainSingle().Which.Value.Should().Be("eu"); + snapshot[0].Instrument.Name.Should().Be("orders"); + snapshot[0].Instrument.Meter.Name.Should().Be("Shop"); + snapshot[0].Instrument.Meter.Version.Should().Be("1.0"); + } + + [Fact] + public void AfterDispose_RecordingIsNotCaptured_AndReadsStillWork() + { + var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + counter.Add(1); + factory.Dispose(); + + counter.Add(2); + + factory.GetMeasurements("orders").Should().ContainSingle() + .Which.Value.Should().Be(1L); + var act = () => factory.ClearMeasurements(); + act.Should().NotThrow(); + factory.GetMeasurements("orders").Should().BeEmpty(); + } + + [Fact] + public void ComposedDisposalPattern_HoldsTheSameFactoryTheSutUses() + { + var composer = Composer.Create(builder => builder.UseMetrics().Share()); + + var service = composer.Create(); + using var _ = service.Meters; + + service.PlaceOrder("eu", 3); + service.Meters.Verify("Shop.Orders", "shop.orders.placed").WithValue(1).Once(); + } + + [Fact] + public void DirectConstructThenRegister_Pattern_IsOwnedByTheTest() + { + using var meters = new CapturingMeterFactory(); + var composer = Composer.Create(builder => builder.Register(() => meters)); + + var service = composer.Create(); + service.PlaceOrder("eu", 3); + + service.Meters.Should().BeSameAs(meters); + meters.Verify("Shop.Orders", "shop.orders.duration").Once(); + } +} diff --git a/test/Compono.Metrics.Tests/TestFixtures.cs b/test/Compono.Metrics.Tests/TestFixtures.cs new file mode 100644 index 00000000..c450f096 --- /dev/null +++ b/test/Compono.Metrics.Tests/TestFixtures.cs @@ -0,0 +1,53 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +/// Composition profile that enables UseMetrics(), mirroring a real consumer profile. +public sealed class MetricsProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => builder.UseMetrics(); +} + +/// A small SUT that takes and records two instruments. +public sealed class OrderService +{ + private readonly IMeterFactory _meters; + private readonly Counter _placed; + private readonly Histogram _duration; + + public OrderService(IMeterFactory meters) + { + _meters = meters; + var meter = meters.Create(new MeterOptions("Shop.Orders")); + _placed = meter.CreateCounter("shop.orders.placed"); + _duration = meter.CreateHistogram("shop.orders.duration"); + } + + public IMeterFactory Meters => _meters; + + public void PlaceOrder(string region, int quantity) + { + _placed.Add(1, new KeyValuePair("region", region)); + _duration.Record(quantity * 1.5, new KeyValuePair("region", region)); + } +} + +/// A SUT with no dependency, for the "doesn't break other types" case. +public sealed class PlainRecord +{ + public int Value { get; set; } = 1; +} + +/// Two meter-factory consumers in one graph, to prove graph-wide sharing of . +public sealed class OrderCoordinator +{ + public OrderCoordinator(IMeterFactory meters, OrderService service) + { + Meters = meters; + Service = service; + } + + public IMeterFactory Meters { get; } + + public OrderService Service { get; } +} diff --git a/test/Compono.Metrics.Tests/VerificationBuilderTests.cs b/test/Compono.Metrics.Tests/VerificationBuilderTests.cs new file mode 100644 index 00000000..5f8dd224 --- /dev/null +++ b/test/Compono.Metrics.Tests/VerificationBuilderTests.cs @@ -0,0 +1,164 @@ +using System.Diagnostics.Metrics; + +namespace Compono.Metrics.Tests; + +public sealed class VerificationBuilderTests +{ + [Fact] + public void WithValue_MatchesExactly() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(3); + + factory.Verify("orders").WithValue(3).Once(); + } + + [Fact] + public void WithValue_WrongValue_Fails() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(3); + + var act = () => factory.Verify("orders").WithValue(4).Once(); + + act.Should().Throw() + .WithMessage("*with value 4*"); + } + + [Fact] + public void WithValue_FloatEqualityIsExact() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateHistogram("f").Record(0.1f); + + factory.Verify("f").WithValue(0.1f).Once(); + + var act = () => factory.Verify("f").WithValue(0.2f).Once(); + act.Should().Throw(); + } + + [Fact] + public void WithTag_IsSubsetMatch_AndIgnoresOtherTags() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1, + new KeyValuePair("region", "eu"), + new KeyValuePair("extra", "ignored")); + + factory.Verify("orders").WithTag("region", "eu").Once(); + } + + [Fact] + public void WithTag_DoesNotCoerceNumericTypes() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1, new KeyValuePair("code", 200)); + + factory.Verify("orders").WithTag("code", 200).Once(); + + var act = () => factory.Verify("orders").WithTag("code", 200L).Once(); + act.Should().Throw(); + } + + [Fact] + public void WithoutTag_MatchesMeasurementsMissingTheKey() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1, new KeyValuePair("region", "eu")); + + factory.Verify("orders").WithoutTag("tenant").Once(); + + var act = () => factory.Verify("orders").WithoutTag("region").Once(); + act.Should().Throw(); + } + + [Fact] + public void ChainedFilters_AllApply() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + counter.Add(1, new KeyValuePair("region", "eu")); + counter.Add(1, new KeyValuePair("region", "us")); + + factory.Verify("orders").WithTag("region", "eu").WithValue(1).Once(); + } + + [Fact] + public void Matching_UsesCustomPredicate() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateHistogram("duration").Record(250.0); + + factory.Verify("duration").Matching(m => m.Value > 200).Once(); + } + + [Fact] + public void Never_PassesWhenNoMeasurementMatches() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1); + + factory.Verify("orders").WithValue(99).Never(); + } + + [Fact] + public void Exactly_AtLeast_AtMost_BehaveAsCounts() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + counter.Add(1); + counter.Add(1); + + factory.Verify("orders").Exactly(2); + factory.Verify("orders").AtLeast(1); + factory.Verify("orders").AtMost(3); + + var act = () => factory.Verify("orders").Exactly(1); + act.Should().Throw(); + } + + [Fact] + public void FailureMessage_DescribesInstrumentTagsAndValue() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + meter.CreateCounter("orders").Add(1, new KeyValuePair("region", "eu")); + + var act = () => factory.Verify("orders").WithTag("region", "us").WithValue(9).Once(); + + act.Should().Throw() + .WithMessage( + "Expected exactly 1 call(s) to instrument \"orders\" (long) " + + "with tag region = \"us\" and value 9, but received 0."); + } + + [Fact] + public void FailureMessage_AnnotatesExpectedNonStringTagValueWithItsRuntimeType() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + + // The measurement's tag is a string, but the expected value passed to WithTag is an int: the + // typed message describes the expectation, not the captured measurement. + meter.CreateCounter("orders").Add( + 1, + new KeyValuePair("status", "bad")); + + var act = () => factory.Verify("orders").WithTag("status", 200).Once(); + + act.Should().Throw() + .WithMessage( + "Expected exactly 1 call(s) to instrument \"orders\" (long) " + + "with tag status = 200 (int), but received 0."); + } +} diff --git a/test/Compono.Metrics.Tests/xunit.runner.json b/test/Compono.Metrics.Tests/xunit.runner.json new file mode 100644 index 00000000..86c7ea05 --- /dev/null +++ b/test/Compono.Metrics.Tests/xunit.runner.json @@ -0,0 +1,3 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json" +} From d68a0689d1347f5b2ba0c4302a3f0684ac94411e Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 13:07:30 -0500 Subject: [PATCH 2/3] docs(metrics): regenerate API reference for CapturingMeterFactory docs --- ...actory.Create(System.Diagnostics.Metrics.MeterOptions).md | 3 ++- .../Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md index ea17f07c..4e602eca 100644 --- a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md @@ -5,7 +5,8 @@ Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set \(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same -[System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. +[System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. Duplicate tag keys are significant: +`[k=1, k=1]` is a different set from `[k=1, j=2]`\. ```csharp public System.Diagnostics.Metrics.Meter Create(System.Diagnostics.Metrics.MeterOptions options); diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md index 83279175..f2cea748 100644 --- a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md @@ -22,7 +22,8 @@ Implements [System\.Diagnostics\.Metrics\.IMeterFactory](https://learn.microsoft Factory semantics match `DefaultMeterFactory`: [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') rejects a [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')[System\.Diagnostics\.Metrics\.MeterOptions](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions 'System\.Diagnostics\.Metrics\.MeterOptions') and a foreign [System\.Diagnostics\.Metrics\.MeterOptions\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions.scope 'System\.Diagnostics\.Metrics\.MeterOptions\.Scope'), throws [System\.ObjectDisposedException](https://learn.microsoft.com/en-us/dotnet/api/system.objectdisposedexception 'System\.ObjectDisposedException') after disposal, never mutates the caller's options, and caches -meters by name, version, and order-insensitive tag set. +meters by name, version, and order-insensitive tag set (duplicate tag keys are significant - see +[Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)')). Each factory owns one lazily created [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener'), created on the first [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') and disposed with the factory. It enables only instruments whose [System\.Diagnostics\.Metrics\.Meter\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter.scope 'System\.Diagnostics\.Metrics\.Meter\.Scope') is this factory, @@ -40,5 +41,5 @@ undisposed `DefaultMeterFactory`. | Methods | | | :--- | :--- | -| [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') | Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set \(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. | +| [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') | Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set \(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. Duplicate tag keys are significant: `[k=1, k=1]` is a different set from `[k=1, j=2]`\. | | [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') | Disposes every meter this factory created \(raising `MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed meters' instruments are no longer captured\. | From 03e75e10e3ff838ae2ab638a43c70f2954033a32 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 13:13:35 -0500 Subject: [PATCH 3/3] fix(metrics): keep cached meters alive until factory disposal A SUT that disposes (or 'using's) the Meter it obtained from CapturingMeterFactory.Create no longer disables capture for every other holder of the cached meter. Mirrors DefaultMeterFactory: meters handed to consumers ignore consumer Dispose; only the factory releases them (on factory Dispose). Adds FactoryMeter and a regression test. --- ...Metrics.CapturingMeterFactory.Dispose().md | 4 ++- .../Compono.Metrics.CapturingMeterFactory.md | 5 +-- src/Compono.Metrics/CapturingMeterFactory.cs | 32 +++++++++++++++---- .../CapturingMeterFactoryTests.cs | 23 +++++++++++++ 4 files changed, 55 insertions(+), 9 deletions(-) diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md index ed8a219f..d3fbea80 100644 --- a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.Dispose().md @@ -6,7 +6,9 @@ Disposes every meter this factory created \(raising `MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed -meters' instruments are no longer captured\. +meters' instruments are no longer captured\. Disposing a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') a consumer obtained from +[Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') is a no\-op \- the factory owns the meter's lifetime, matching +`DefaultMeterFactory`\. ```csharp public void Dispose(); diff --git a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md index f2cea748..c648f88e 100644 --- a/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md +++ b/docs/reference/api/Compono.Metrics/Compono.Metrics.CapturingMeterFactory.md @@ -23,7 +23,8 @@ Factory semantics match `DefaultMeterFactory`: [Create\(MeterOptions\)](Compono. rejects a [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')[System\.Diagnostics\.Metrics\.MeterOptions](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions 'System\.Diagnostics\.Metrics\.MeterOptions') and a foreign [System\.Diagnostics\.Metrics\.MeterOptions\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meteroptions.scope 'System\.Diagnostics\.Metrics\.MeterOptions\.Scope'), throws [System\.ObjectDisposedException](https://learn.microsoft.com/en-us/dotnet/api/system.objectdisposedexception 'System\.ObjectDisposedException') after disposal, never mutates the caller's options, and caches meters by name, version, and order-insensitive tag set (duplicate tag keys are significant - see -[Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)')). +[Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)')). Disposing a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') a consumer obtained from [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') is a +no-op: the factory owns the meter's lifetime and releases it on [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)'). Each factory owns one lazily created [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener'), created on the first [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') and disposed with the factory. It enables only instruments whose [System\.Diagnostics\.Metrics\.Meter\.Scope](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter.scope 'System\.Diagnostics\.Metrics\.Meter\.Scope') is this factory, @@ -42,4 +43,4 @@ undisposed `DefaultMeterFactory`. | Methods | | | :--- | :--- | | [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') | Creates a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') bound to this factory\. The same name, version, and tag set \(order\-insensitive, [System\.Object\.Equals\(System\.Object,System\.Object\)](https://learn.microsoft.com/en-us/dotnet/api/system.object.equals#system-object-equals(system-object-system-object) 'System\.Object\.Equals\(System\.Object,System\.Object\)') on values\) returns the same [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter'); anything else creates a new one\. Duplicate tag keys are significant: `[k=1, k=1]` is a different set from `[k=1, j=2]`\. | -| [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') | Disposes every meter this factory created \(raising `MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed meters' instruments are no longer captured\. | +| [Dispose\(\)](Compono.Metrics.CapturingMeterFactory.Dispose().md 'Compono\.Metrics\.CapturingMeterFactory\.Dispose\(\)') | Disposes every meter this factory created \(raising `MeasurementsCompleted`\), then its [System\.Diagnostics\.Metrics\.MeterListener](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meterlistener 'System\.Diagnostics\.Metrics\.MeterListener')\. Idempotent and thread\-safe\. Captured measurements stay readable afterwards; measurements recorded on the disposed meters' instruments are no longer captured\. Disposing a [System\.Diagnostics\.Metrics\.Meter](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.metrics.meter 'System\.Diagnostics\.Metrics\.Meter') a consumer obtained from [Create\(MeterOptions\)](Compono.Metrics.CapturingMeterFactory.Create(System.Diagnostics.Metrics.MeterOptions).md 'Compono\.Metrics\.CapturingMeterFactory\.Create\(System\.Diagnostics\.Metrics\.MeterOptions\)') is a no\-op \- the factory owns the meter's lifetime, matching `DefaultMeterFactory`\. | diff --git a/src/Compono.Metrics/CapturingMeterFactory.cs b/src/Compono.Metrics/CapturingMeterFactory.cs index 8c1699d6..be51ef13 100644 --- a/src/Compono.Metrics/CapturingMeterFactory.cs +++ b/src/Compono.Metrics/CapturingMeterFactory.cs @@ -15,7 +15,8 @@ namespace Compono.Metrics; /// rejects a and a foreign , /// throws after disposal, never mutates the caller's options, and caches /// meters by name, version, and order-insensitive tag set (duplicate tag keys are significant - see -/// ). +/// ). Disposing a a consumer obtained from is a +/// no-op: the factory owns the meter's lifetime and releases it on . /// /// /// Each factory owns one lazily created , created on the first @@ -94,7 +95,7 @@ public Meter Create(MeterOptions options) Tags = tags, }; - var meter = new Meter(owned); + var meter = new FactoryMeter(owned); _meters.Add(new MeterEntry(options.Name, options.Version, tags, meter)); return meter; } @@ -104,7 +105,9 @@ public Meter Create(MeterOptions options) /// Disposes every meter this factory created (raising /// MeasurementsCompleted), then its . Idempotent and /// thread-safe. Captured measurements stay readable afterwards; measurements recorded on the disposed - /// meters' instruments are no longer captured. + /// meters' instruments are no longer captured. Disposing a a consumer obtained from + /// is a no-op - the factory owns the meter's lifetime, matching + /// DefaultMeterFactory. /// public void Dispose() { @@ -117,7 +120,7 @@ public void Dispose() } foreach (var entry in _meters) - entry.Meter.Dispose(); + entry.Meter.Release(); _listener?.Dispose(); } @@ -251,7 +254,7 @@ private static bool TagSetsEqual( private sealed class MeterEntry { - public MeterEntry(string name, string? version, KeyValuePair[] tags, Meter meter) + public MeterEntry(string name, string? version, KeyValuePair[] tags, FactoryMeter meter) { Name = name; Version = version; @@ -265,11 +268,28 @@ public MeterEntry(string name, string? version, KeyValuePair[] public KeyValuePair[] Tags { get; } - public Meter Meter { get; } + public FactoryMeter Meter { get; } public bool Matches(string name, string? version, KeyValuePair[] tags) => string.Equals(Name, name, StringComparison.Ordinal) && string.Equals(Version, version, StringComparison.Ordinal) && TagSetsEqual(Tags, tags); } + + // A meter whose consumer-facing Dispose is a no-op, so a SUT that disposes (or `using`s) the meter it + // obtained from Create cannot disable capture for every other consumer that shares the cached meter - the + // same lifecycle DefaultMeterFactory provides. Only the factory releases it, via Release(). + private sealed class FactoryMeter : Meter + { + public FactoryMeter(MeterOptions options) + : base(options) + { + } + + internal void Release() => base.Dispose(true); + + protected override void Dispose(bool disposing) + { + } + } } diff --git a/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs b/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs index 14a66326..d79bf6c1 100644 --- a/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs +++ b/test/Compono.Metrics.Tests/CapturingMeterFactoryTests.cs @@ -243,4 +243,27 @@ public void CreateAndDisposeConcurrently_DisposesSafely_AndRejectsLaterCreate() var act = () => factory.Create(new MeterOptions("Shop")); act.Should().Throw(); } + + [Fact] + public void ConsumerDisposingACachedMeter_IsANoOp_AndCaptureContinues() + { + using var factory = new CapturingMeterFactory(); + var meter = factory.Create(new MeterOptions("Shop")); + var counter = meter.CreateCounter("orders"); + + // A SUT that disposes (or `using`s) the meter it obtained must not disable capture for every other + // holder of the cached meter - DefaultMeterFactory makes consumer meter disposal a no-op. + meter.Dispose(); + + var again = factory.Create(new MeterOptions("Shop")); + again.Should().BeSameAs(meter); + + // The instrument created before the consumer dispose is still enabled... + counter.Add(1); + // ...and the cached meter keeps minting working instruments. + again.CreateCounter("orders").Add(2); + + factory.GetMeasurements("orders").Select(m => m.Value) + .Should().Equal(1L, 2L); + } }