From 85df481defd56bfdc28881477f9c252ef1857a66 Mon Sep 17 00:00:00 2001 From: Rhys Bevilaqua Date: Fri, 27 Nov 2026 08:52:39 +0800 Subject: [PATCH 1/2] Add automated version of smoke testing script to aspire test tool --- docs/load-testing.md | 7 +- docs/testing-scenarios.md | 2 + docs/testing.md | 6 +- tools/testing-tool/README.md | 61 +- .../TestingTool.AppHost/AppHost.cs | 8 +- .../TestingTool.Contracts/SmokeRunInfo.cs | 50 ++ .../TestingTool.Tests/Smoke/Fakes.cs | 53 ++ .../Smoke/SmokeApiClientTests.cs | 149 +++++ .../Smoke/SmokeChecksTests.cs | 247 ++++++++ .../Smoke/SmokeEndpointLifecycleTests.cs | 250 ++++++++ .../Smoke/SmokeHandlerTests.cs | 75 +++ .../Smoke/SmokeRunnerTests.cs | 220 +++++++ .../CustomChecks/ReportCustomCheckResult.cs | 2 +- .../TestingTool/NServiceBusSetup.cs | 89 ++- tools/testing-tool/TestingTool/Program.cs | 66 +- .../TestingTool/Smoke/SmokeApiClient.cs | 248 ++++++++ .../TestingTool/Smoke/SmokeCheck.cs | 82 +++ .../TestingTool/Smoke/SmokeChecks.cs | 577 ++++++++++++++++++ .../TestingTool/Smoke/SmokeEndpoint.cs | 124 ++++ .../TestingTool/Smoke/SmokeMessages.cs | 193 ++++++ .../TestingTool/Smoke/SmokeRunner.cs | 232 +++++++ .../TestingTool/Smoke/SmokeRunnerLifecycle.cs | 21 + .../TestingTool/TestingTool.csproj | 2 + .../TestingTool/TestingToolOptions.cs | 14 +- .../TestingTool/wwwroot/index.html | 64 ++ 25 files changed, 2791 insertions(+), 51 deletions(-) create mode 100644 tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs create mode 100644 tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs diff --git a/docs/load-testing.md b/docs/load-testing.md index 75245ef57b..a063b0061a 100644 --- a/docs/load-testing.md +++ b/docs/load-testing.md @@ -1,12 +1,12 @@ # Load testing -The [ServiceControl Testing Tool](../tools/testing-tool/README.md) is a stateless .NET service that generates error load and real-world failure scenarios against a test ServiceControl instance, to validate error-ingestion performance. It has a web UI for manual control, built-in failure scenarios (third-party outage, timeout spike, poison message, and more), and OpenTelemetry telemetry. +The [ServiceControl Testing Tool](../tools/testing-tool/README.md) is a .NET service that generates error load and real-world failure scenarios against a test ServiceControl instance, to validate error-ingestion performance. It has a web UI for manual control, built-in failure scenarios (third-party outage, timeout spike, poison message, and more), and OpenTelemetry telemetry. The [testing tool README](../tools/testing-tool/README.md) is the full reference: every scenario, API endpoint, configuration setting, container usage, and scaling notes. ## Quick start: full stack with Aspire -The Aspire AppHost starts the whole system with a single command: the ServiceControl platform (Learning transport), the testing tool, and a complete observability stack (OTel Collector, Jaeger, Prometheus, and Grafana with a prebuilt dashboard). +The Aspire AppHost starts the whole system with a single command: the ServiceControl platform (RabbitMQ by default), the testing tool, and a complete observability stack (OTel Collector, Jaeger, Prometheus, and Grafana with a prebuilt dashboard). ```bash aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj @@ -14,6 +14,8 @@ aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj Aspire assigns dynamic ports. Open the web UI of the testing tool through the link in the Aspire dashboard. +The AppHost enables external integration-event publishing on the error instances, so ServiceControl writes and publishes a `MessageFailed` event for each ingested failure. This can change ingestion baselines compared with a run without it. + Useful flags, passed after `--`: | Flag | Description | @@ -43,6 +45,7 @@ Everything is controllable from the web UI, or via the HTTP API: - Scenarios: the six built-in scenarios (`third-party-outage`, `timeout-spike`, `poison-message`, `deserialization-failure`, `background-noise`, `large-messages`), each producing errors that group naturally. `large-messages` starts at 3 messages per second unless `rate` is set, sends bodies of about 256 KiB (the wire envelope is slightly larger), fails 20% of them to the error queue, and audits the rest. The bypass writer fails every message by design, so it sends the large bodies only as failures. Start with `POST /api/scenarios/{name}/start` (optional `rate` and `durationSeconds`). - Bypass writer: high-throughput load that writes failed-message envelopes directly to the ServiceControl error queue, skipping the message handler (`POST /api/bypass/start`). - Jobs: retry, archive, search, retention sweep, and custom-check-failure jobs exercise ServiceControl's recoverability, FTS search, and retention pipelines against the load. Jobs do not start automatically. Start them from the UI or `/api/jobs`. +- Smoke tests: the **Smoke tests** tab runs an API-verified version of the functionality checklist in the [testing scenarios](testing-scenarios.md) against the instance under test, with manual rows for what only a person can verify. Do not confuse it with the load presets: it sends a few messages per check and reads the results back through the ServiceControl APIs. The [testing tool README](../tools/testing-tool/README.md#smoke-tests) lists each check, its prerequisites and its limits. - Release-test presets: named presets mapped from the [testing scenarios](testing-scenarios.md), for example `POST /api/release-tests/ingestion-load/start`. ## Observing the run diff --git a/docs/testing-scenarios.md b/docs/testing-scenarios.md index a344192632..dfd7f5d6ba 100644 --- a/docs/testing-scenarios.md +++ b/docs/testing-scenarios.md @@ -12,6 +12,8 @@ This list is long but not exhaustive. Not every change needs every test. ## Functionality +The **Smoke tests** tab of the [testing tool](../tools/testing-tool/README.md#smoke-tests) automates the API-level part of the custom checks, heartbeats, recoverability, audits, saga auditing, integration events and monitoring items below: it generates the messages and verifies the results through the ServiceControl APIs. The ServicePulse screens, the installation steps, the public integration events sample, chaos testing and performance testing stay manual. The manual rows of the tab list them. + - [ ] Install and run ServiceControl Primary, Audit, and Monitoring instances - [ ] [Install the ServiceControl.SmokeTesting tool](https://github.com/Particular/ServiceControl.SmokeTest#installing) - [ ] Start the smoke testing tool, for example `dotnet servicecontrol.smoketest rabbitmq` diff --git a/docs/testing.md b/docs/testing.md index 7ffe8d1abf..a360f3d9ec 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -113,4 +113,8 @@ Containers built by a PR and stored on GitHub Container Registry can be tested l * Audit API * Monitoring API * ServicePulse (latest from Docker Hub) -6. Exit the CLI process. Aspire stops the application automatically. \ No newline at end of file +6. Exit the CLI process. Aspire stops the application automatically. + +## Smoke tests with the testing tool + +The [testing tool](../tools/testing-tool/README.md#smoke-tests) has a **Smoke tests** tab that sends deterministic messages with a run-specific identifier and verifies custom checks, heartbeats, retries, message editing, redirects, audit data, conversations, sagas, integration events and monitoring data through the ServiceControl APIs. Start it with the Aspire AppHost and `--audit-instances 1`, as described in the [load testing](load-testing.md) page. It complements the [testing scenarios](testing-scenarios.md) checklist: the rows it does not automate stay manual. diff --git a/tools/testing-tool/README.md b/tools/testing-tool/README.md index 4f2ba3d39d..28f8336b0b 100644 --- a/tools/testing-tool/README.md +++ b/tools/testing-tool/README.md @@ -1,8 +1,6 @@ # ServiceControl Testing Tool -A stateless, horizontally-scalable .NET 10 service that generates error load and real-world failure -scenarios against a test ServiceControl instance to validate its error-ingestion performance, with -OpenTelemetry observability and a simple web UI for manual scenario control. +A horizontally scalable .NET 10 service that generates failure scenarios, verifies smoke checks, and measures error-ingestion performance against a test ServiceControl instance. It includes OpenTelemetry observability and a web UI. The tool drives both ingestion paths: failed messages into the primary ServiceControl instance, and audited messages and saga snapshots into a ServiceControl.Audit instance. @@ -103,6 +101,50 @@ release-test scenarios can be kicked off manually by name: - `GET /api/release-tests` — list all presets - `POST /api/release-tests/{name}/start` — start a preset (e.g. `retry-message-group`, `ingestion-load`) +### Smoke tests + +The **Smoke tests** tab runs an API-verified version of the functionality checklist in [docs/testing-scenarios.md](/docs/testing-scenarios.md). **Run all** executes the automated checks one after another, **Stop** cancels the run, and each row shows pending, running, passed, failed, canceled or manual with the observed detail. The run state lives in the tool, so reloading the page shows the current or last run. + +Every check sends its own messages with a run identifier (`smoke-<8 hex digits>`) and reads the effect back through the ServiceControl APIs. A check matches only what it created: a custom check id, an endpoint name, a message id, a conversation id, a saga id or a failure group that contains the run identifier. Background load and leftovers from earlier runs cannot satisfy a check. An HTTP 202 alone never passes a check, and a transport error or an unexpected status fails the check with the reason. When ServiceControl reports incomplete cross-instance results (`X-Particular-Incomplete-Results`), the check keeps polling and names the missing instances in the timeout detail; data that matches the run identifier still passes. Checks run in order, and a failed check does not stop later checks. Each check attempts cleanup after completion, cancellation, or shutdown. + +| Check | What it does | What it verifies | +|---|---|---| +| `custom-check-fail-then-pass` | Reports a failed, then a passed custom check with id `Smoke.` to the primary input queue | `GET /api/customchecks?status=fail` lists it with the failure reason, then `?status=pass` lists it and `?status=fail` does not | +| `heartbeat-beating-then-dead` | Starts a real in-process endpoint `TestingTool.Smoke.` with the NServiceBus.Heartbeat plugin, then stops its host | `GET /api/endpoints` shows `heartbeat_information.reported_status` `beating`, then `dead` (about 45 seconds after the host stops with the default 40 second grace period; the check waits up to 100 seconds) | +| `audit-ingestion-fulltext` | Handles a message with a run-specific word in the body | `GET /api/messages/search?q=` finds it with status `successful`, and `GET /api/messages/{id}/body` contains the word | +| `fanout-conversation` | Handles a message that sends two children per level for two levels, with a run-specific conversation id | `GET /api/conversations/{id}` returns the seven messages, and every `NServiceBus.RelatedTo` header points at a parent in the conversation | +| `saga-audit` | Runs a real saga (start, step, finish) with saga auditing to the audit queue | `GET /api/messages/search` finds the start message with its saga id, and `GET /api/sagas/{id}` lists `new`, `updated`, `completed` | +| `monitoring-data` | Starts a real endpoint `TestingTool.Smoke.` with the NServiceBus.Metrics.ServiceControl plugin (2 second interval, as the load endpoint) and handles three messages that each take 100 ms | `GET /monitored-endpoints` on the monitoring instance lists the endpoint with a `processingTime` average above zero. Cleanup deletes the instance ids that monitoring reports for it | +| `integration-event` | Subscribes the tool endpoint to `ServiceControl.Contracts.MessageFailed` and fails one message | The published event arrives with the run header and the failed message id that `GET /api/recoverability/groups/{id}/errors` returns | +| `retry-single` | Fails two messages in a group unique to the run, then retries one with `POST /api/errors/{id}/retry` | The tool handled and `GET /api/errors/{id}` reports `resolved` for that message, and its sibling is unresolved and unhandled | +| `retry-group` | Fails three messages in a unique group, then retries the group with `POST /api/recoverability/groups/{id}/errors/retry` | Every message was handled and is `resolved` | +| `edit-and-retry` | Fails a message, then edits it with `POST /api/edit/{id}` (snake_case body, every original header, `Fail` cleared) | The edited message arrives with `ServiceControl.EditOf` set to the failed message id and the edited text | +| `retry-through-redirect` | Starts real endpoints `TestingTool.Smoke..Source` and `.Target`, fails a message in Source, creates a redirect from the Source input address to the Target input address with `POST /api/redirects`, retries it | The failed message has the Source address as its queue, the redirect is listed, the message is handled by Target (a retry that Source handles fails the check) and is `resolved`, and the redirect is gone after `DELETE /api/redirects/{id}`. It runs last because a redirect changes retry routing while it exists | + +Failures come from the real message handler, not from the load scenarios. A smoke message fails when its `Fail` flag is set and its marker was not released, so a retry succeeds when the check releases the marker and an edit succeeds when it clears the flag. The handler throws a `SmokeFailureException` and the tool rewrites the fault headers so ServiceControl groups it under the exception type `TestingTool.Smoke.Failure__`, which makes the group unique to one check. At the end of a check, unresolved failed messages of that check are archived. The redirect check removes only the redirect it created. + +Prerequisites on the instance under test: + +- The primary needs a remote audit instance for the audit, conversation and saga checks. With the Aspire AppHost, pass `--audit-instances 1`. The checks fail with that hint when `GET /api/configuration/remotes` is empty or a remote is not online. +- Integration events need `SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true` on the instances that ingest errors. The AppHost sets it on the primary and on the error-ingestion scale units. +- Message editing needs `SERVICECONTROL_ALLOWMESSAGEEDITING=true`. The AppHost sets it. +- The monitoring check needs `TestingTool__MonitoringApiUrl` to point at the monitoring instance. The AppHost sets it. +- Stop the retry, archive and retention-sweep jobs first: they act on every failed message group, so a start is refused while one runs. Scenarios and bypass writers may keep running. + +Run it against a test instance only. Cleanup stops the run-scoped endpoint hosts, removes custom checks, endpoint and monitoring records, and redirects, and archives unresolved failures. Audited messages and resolved or archived failures remain subject to ServiceControl retention. If cleanup fails, the row reports the error and warns that data may remain. + +Limits of the automation: + +- The heartbeat, monitoring and redirect checks start real NServiceBus endpoints, each in its own host in the tool process, next to `TestingTool.Load`. They use the same transport, topology and serializer as the load endpoint, send failures to the same error queue, and handle only smoke messages. Their input addresses come from the transport (`ReceiveAddresses.MainReceiveAddress`), so SQL Server schema and catalog are included. Stopping a host, which a check does explicitly for the heartbeat and always at the end (before any API cleanup, so an unreachable ServiceControl cannot delay it), stops that endpoint and its plugins; it does not stop the tool or the load endpoint. It also does not delete the queues or tables the endpoint created: those run-scoped transport entities stay until the broker or database is torn down. The check exercises the NServiceBus.Heartbeat and NServiceBus.Metrics.ServiceControl plugins. +- The saga is a real saga in the tool endpoint with the NServiceBus.SagaAudit plugin and learning persistence in the temp folder, not a snapshot written by hand. +- Rows marked manual are not automated: instance installation and upgrade, how ServicePulse renders custom checks, heartbeats, recoverability screens, search, the sequence diagram, the saga view and the monitoring graphs, the public integration events sample, chaos testing, and performance, load and stability testing. The API data behind the rendered views is verified by the automated rows above. + +API: + +- `GET /api/smoke` — the current or last run, or the idle checklist +- `POST /api/smoke/start` — start a run; 400 when one is running or a conflicting job is running +- `POST /api/smoke/stop` — cancel the current run + ## Layout ``` @@ -111,6 +153,7 @@ tools/testing-tool/ Dockerfile # multi-stage container build (build context = repo root) TestingTool/ # ASP.NET Core host — API endpoints, web UI, NServiceBus endpoint, # scenario runner, bypass writer, recoverability/search jobs, + # smoke test runner and checks (Smoke/), # OTel setup, ServiceControl REST client TestingTool.Scenarios/ # IScenario contract + the six scenario implementations TestingTool.Contracts/ # shared DTOs (scenarios, status, jobs, bypass) @@ -190,7 +233,7 @@ separator) or `--name:value` (colon separator): | `--transport` | `RabbitMq` | `RabbitMq`, `SqlServer` | Transport shared by ServiceControl and the testing tool. `SqlServer` reuses the storage SQL Server container with a separate `Transport` database | | `--tag` | *(none — uses the current build's image)* | any image tag, e.g. `pr-1234` or `6.3.1` | Override the ServiceControl container image tag (useful for testing PR-based prereleases) | | `--error-ingestion-scale-unit` | `0` | non-negative integer | Number of additional error-ingestion-only scale-out instances to spin up alongside the primary error instance (each runs with `--error-ingestion-only`) | -| `--audit-instances` | `1` | non-negative integer | Number of ServiceControl.Audit instances to add. They take the same `--storage` backend, report custom checks to the primary and export OTel to the collector | +| `--audit-instances` | `0` | non-negative integer | Number of ServiceControl.Audit instances to add. They take the same `--storage` backend, report custom checks to the primary and export OTel to the collector | | `--azure-blob-body-storage` | *(none — uses file-system body storage)* | `""` | Store message bodies in Azure Blob Storage instead of the container file system. Applies only with `--storage:SqlServer` or `--storage:PostgreSql`. Quote the value because connection strings contain semicolons. The error instance and its scale-out units share the `error-bodies` container, and each audit instance gets its own `audit-bodies-` container | | `--s3-body-storage` | *(none — uses file-system body storage)* | `` | Store message bodies in an S3 bucket instead of the container file system. Applies only with `--storage:SqlServer` or `--storage:PostgreSql`, and cannot be combined with `--azure-blob-body-storage`. Setup creates the bucket if it is missing and the credentials permit it. The error instance and its scale-out units share the `error-bodies/` key prefix, and each audit instance gets its own `audit-bodies-/` prefix | | `--s3-region` | SDK default | region name, e.g. `eu-west-1` | Region for `--s3-body-storage`. Requires `--s3-body-storage` | @@ -241,9 +284,7 @@ and cumulative), ingestion duration p95, and ingestion outcome by result. ## Horizontal scaling -The tool is **stateless** — all state is in-memory per replica. Run a single instance via -`dotnet run` or the Aspire AppHost; for multi-replica deployments, bring your own orchestration -and give each replica a distinct shard id so deterministic failure decisions don't overlap: +Load counters, job controls, and smoke-run results are in-memory per replica. The smoke saga uses learning persistence in a local temporary directory. Run a single instance with `dotnet run` or the Aspire AppHost. For multiple replicas, provide orchestration and a distinct shard id for each replica so deterministic failure decisions do not overlap: | Shard id source | When | |---|---| @@ -269,7 +310,7 @@ on its own, set it to the broker your ServiceControl instance uses: | not set or empty | Learning transport (local standalone runs only — ServiceControl won't see the messages) | | anything else | startup fails with an error naming `ConnectionStrings__transport` | -The selected transport is logged at startup (`Using RabbitMQ transport` etc.). +The selected transport is logged at startup (`Using RabbitMQ transport` etc.). The smoke tests start their own run-scoped endpoints with the same selection, so they need the same `ConnectionStrings__transport`. The Standard Service Bus tier limits a message to 256 KiB including headers. The `large-messages` scenario serializes to about 190 KiB, so it leaves room for headers on Standard and still exceeds the 100 KB external body storage threshold. @@ -296,6 +337,10 @@ All configuration is via environment variables (no files, no database). Settings | `TestingTool__AuditQueueName` | `audit` | NServiceBus audit queue the ServiceControl.Audit instance drains | | `TestingTool__AuditSagaSnapshotRatio` | `0.2` | Default saga snapshots per processed message for the audit-queue writer | | `TestingTool__MonitoringQueueName` | `Particular.Monitoring` | ServiceControl monitoring instance queue that endpoint metrics are sent to | +| `TestingTool__MonitoringApiUrl` | `http://localhost:33633` | ServiceControl.Monitoring API base URL, used by the smoke tests | +| `TestingTool__SmokePollInterval` | `00:00:01` | Interval between polls while a smoke check waits for an effect | +| `TestingTool__SmokePollTimeout` | `00:01:00` | How long a smoke check waits for one effect before it fails | +| `TestingTool__SmokeCheckTimeout` | `00:03:00` | How long one smoke check may take in total | | `TestingTool__ErrorQueueName` | `error` | NServiceBus error queue (ServiceControl monitors this) | | `TestingTool__AutoStartBackgroundNoise` | `false` | Auto-start the background-noise scenario on startup | | `SHARD_ID` (env) | *(auto: hostname ordinal or machine name)* | Shard id for disjoint scenario slices when scaled | diff --git a/tools/testing-tool/TestingTool.AppHost/AppHost.cs b/tools/testing-tool/TestingTool.AppHost/AppHost.cs index 7be6d5586e..0d9c950666 100644 --- a/tools/testing-tool/TestingTool.AppHost/AppHost.cs +++ b/tools/testing-tool/TestingTool.AppHost/AppHost.cs @@ -32,7 +32,7 @@ .WithEnvironment("SERVICECONTROL_ERRORINGESTIONMAXPARALLELWRITERS", "4") .WithEnvironment("SERVICECONTROL_ERRORINGESTIONBATCHTIMEOUT", "00:00:00.100") .WithEnvironment("SERVICECONTROL_ALLOWMESSAGEEDITING", "true") - .WithEnvironment("SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING", "true") + .WithEnvironment("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) .WithStorageType(storageType, azureBlobBodyStorage, s3BodyStorage) .WithRunMode(PlatformRunMode.SetupAndRun); @@ -42,8 +42,8 @@ .AddServiceControlErrorInstance("error-scale-" + i, raven) .WithArgs("--error-ingestion-only") .WithEnvironment("SERVICECONTROL_INSTANCENAME", "Error-scale-" + i) + .WithEnvironment("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) - .WithEnvironment("SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING", "true") //scale settings .WithEnvironment("SERVICECONTROL_MAXIMUMCONCURRENCYLEVEL", "100") @@ -56,7 +56,8 @@ .WithRunMode(PlatformRunMode.Run); } -platform.AddServicePulse("pulse", primaryErrorInstance, platform.AddServiceControlMonitoringInstance("monitoring")); +var monitoringInstance = platform.AddServiceControlMonitoringInstance("monitoring"); +platform.AddServicePulse("pulse", primaryErrorInstance, monitoringInstance); // EF persistence lives in the audit instance itself, so audit load needs a real audit container. // The platform persistence argument stays RavenDB because the Aspire package only knows about @@ -83,6 +84,7 @@ builder.AddProject("testing-tool") .WithParticularPlatform(platform) .WithEnvironment("TestingTool__ServiceControlApiUrl", primaryErrorInstance.GetEndpoint("http")) + .WithEnvironment("TestingTool__MonitoringApiUrl", monitoringInstance.GetEndpoint("http")) .WithEnvironment("TestingTool__AutoStartBackgroundNoise", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) // this should wait for the platform but cannot because error scale out leaves nodes unhealthy diff --git a/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs b/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs new file mode 100644 index 0000000000..321a0dce12 --- /dev/null +++ b/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs @@ -0,0 +1,50 @@ +using System.Text.Json.Serialization; + +namespace TestingTool.Contracts; + +/// +/// State of the smoke-test checklist returned by GET /api/smoke: the current run, or the last +/// finished one, or the idle checklist before the first run. +/// +public sealed class SmokeRunInfo +{ + /// The identifier that scopes every message, custom check and endpoint of the run. Null before the first run. + public string? RunId { get; init; } + + public bool Running { get; init; } + + public string? StartedAt { get; init; } + + public string? FinishedAt { get; init; } + + public required IReadOnlyList Checks { get; init; } +} + +public sealed class SmokeCheckInfo +{ + public required string Id { get; init; } + + public required string Title { get; init; } + + /// What the check does and which ServiceControl API effect it verifies, or for a manual row what a person must verify. + public required string Description { get; init; } + + public SmokeCheckStatus Status { get; init; } + + /// What the check observed. For a failed check, the reason and the last observed state. + public string? Detail { get; init; } + + public double? DurationSeconds { get; init; } +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum SmokeCheckStatus +{ + Pending, + Running, + Passed, + Failed, + /// The check is not automated. A person verifies it. + Manual, + Canceled +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs b/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs new file mode 100644 index 0000000000..9d23f181cc --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs @@ -0,0 +1,53 @@ +using System.Net; +using System.Text; +using NServiceBus; + +namespace TestingTool.Tests.Smoke; + +sealed class FakeMessageSession : IMessageSession +{ + public List<(object Message, SendOptions Options)> Sent { get; } = []; + public List Subscribed { get; } = []; + public List Unsubscribed { get; } = []; + + public Task Send(object message, SendOptions sendOptions, CancellationToken cancellationToken = default) + { + Sent.Add((message, sendOptions)); + return Task.CompletedTask; + } + + public Task Subscribe(Type eventType, SubscribeOptions subscribeOptions, CancellationToken cancellationToken = default) + { + Subscribed.Add(eventType); + return Task.CompletedTask; + } + + public Task Unsubscribe(Type eventType, UnsubscribeOptions unsubscribeOptions, CancellationToken cancellationToken = default) + { + Unsubscribed.Add(eventType); + return Task.CompletedTask; + } + + public Task Send(Action messageConstructor, SendOptions sendOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task Publish(object message, PublishOptions publishOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task Publish(Action messageConstructor, PublishOptions publishOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); +} + +sealed class FakeHttpHandler(Func respond) : HttpMessageHandler +{ + public List<(HttpMethod Method, string PathAndQuery, string Body)> Requests { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken); + Requests.Add((request.Method, request.RequestUri!.PathAndQuery, body)); + return respond(request); + } + + public static HttpResponseMessage Json(string json, HttpStatusCode status = HttpStatusCode.OK) => + new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + + public static HttpResponseMessage Status(HttpStatusCode status) => new(status); +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs new file mode 100644 index 0000000000..792a70dbe5 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs @@ -0,0 +1,149 @@ +using System.Net; +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeApiClientTests +{ + static (SmokeApiClient Client, FakeHttpHandler Handler) Create(Func respond) + { + var handler = new FakeHttpHandler(respond); + return (new SmokeApiClient(new HttpClient(handler) { BaseAddress = new Uri("http://sc.test") }), handler); + } + + [Test] + public void An_unexpected_status_fails_with_the_status_and_body() + { + var (client, _) = Create(_ => FakeHttpHandler.Json("""{"error":"nope"}""", HttpStatusCode.InternalServerError)); + + var ex = Assert.ThrowsAsync(() => client.GetEndpoints(CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("GET /api/endpoints returned 500").And.Contain("nope")); + } + + [Test] + public void A_transport_error_fails_the_check_instead_of_returning_an_empty_list() + { + var (client, _) = Create(_ => throw new HttpRequestException("connection refused")); + + var ex = Assert.ThrowsAsync(() => client.GetGroups(CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("could not reach http://sc.test/").And.Contain("connection refused")); + } + + [Test] + public async Task A_missing_failed_message_is_null_until_it_is_ingested() + { + var (client, _) = Create(r => r.RequestUri!.AbsolutePath.EndsWith("/missing") + ? FakeHttpHandler.Status(HttpStatusCode.NotFound) + : FakeHttpHandler.Json("""{"status":"retryIssued","processing_attempts":[{"headers":{"NServiceBus.MessageId":"m1"}}]}""")); + + Assert.That(await client.FindFailedMessage("missing", CancellationToken.None), Is.Null); + var found = await client.FindFailedMessage("known", CancellationToken.None); + Assert.That(found!.Status, Is.EqualTo("retryIssued")); + Assert.That(found.ProcessingAttempts[^1].Headers["NServiceBus.MessageId"], Is.EqualTo("m1")); + } + + [Test] + public async Task Edit_sends_snake_case_names_and_reports_an_ignored_edit() + { + var (client, handler) = Create(_ => FakeHttpHandler.Json("""{"edit_ignored":true}""")); + + var accepted = await client.EditMessage("id1", "{}", new Dictionary { ["NServiceBus.MessageId"] = "m1" }, CancellationToken.None); + + Assert.That(accepted, Is.False); + Assert.That(handler.Requests[0].Body, Is.EqualTo("""{"message_body":"{}","message_headers":{"NServiceBus.MessageId":"m1"}}""")); + } + + [Test] + public async Task Redirect_request_uses_the_lowercase_names_of_the_api() + { + var (client, handler) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.Created)); + + await client.CreateRedirect("from-queue", "to-queue", CancellationToken.None); + + Assert.That(handler.Requests[0].Body, Is.EqualTo("""{"fromphysicaladdress":"from-queue","tophysicaladdress":"to-queue","retryexisting":false}""")); + } + + [Test] + public async Task Search_exposes_the_instances_that_did_not_answer() + { + var (client, _) = Create(_ => + { + var response = FakeHttpHandler.Json("[]"); + response.Headers.Add("X-Particular-Incomplete-Results", "audit1:unavailable"); + return response; + }); + + var result = await client.SearchMessages("token", CancellationToken.None); + + Assert.That(result.Incomplete, Is.EqualTo("audit1:unavailable")); + } + + [Test] + public async Task Saga_is_null_while_the_primary_answers_no_content() + { + var (client, _) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.NoContent)); + + Assert.That((await client.GetSaga(Guid.NewGuid(), CancellationToken.None)).Value, Is.Null); + } + + [Test] + public async Task Paged_lists_are_read_until_a_short_page() + { + var (client, handler) = Create(r => + { + var page = int.Parse(System.Web.HttpUtility.ParseQueryString(r.RequestUri!.Query)["page"]!); + var count = page == 1 ? 100 : 3; + var items = string.Join(",", Enumerable.Range(0, count).Select(i => $$"""{"id":"{{page}}-{{i}}","custom_check_id":"c","status":"fail","reported_at":"2026-01-01T00:00:00Z"}""")); + return FakeHttpHandler.Json($"[{items}]"); + }); + + var checks = await client.GetCustomChecks("fail", CancellationToken.None); + + Assert.That(checks, Has.Count.EqualTo(103)); + Assert.That(handler.Requests.Select(r => r.PathAndQuery), Is.EqualTo(["/api/customchecks?status=fail&page=1&per_page=100", "/api/customchecks?status=fail&page=2&per_page=100"])); + } + + [Test] + public async Task Message_body_follows_the_relative_body_url_of_the_audit_instance() + { + var (client, handler) = Create(_ => FakeHttpHandler.Json("body text")); + var message = new SmokeApiClient.AuditedMessage("row-id", "m1", "T", "successful", null, "/messages/body-1/body?instance_id=audit-1", null, null); + + await client.GetMessageBody(message, CancellationToken.None); + + Assert.That(handler.Requests[0].PathAndQuery, Is.EqualTo("/api/messages/body-1/body?instance_id=audit-1")); + } + + [Test] + public void Message_body_without_a_body_url_fails_clearly() + { + var (client, _) = Create(_ => FakeHttpHandler.Json("")); + var message = new SmokeApiClient.AuditedMessage("row-id", "m1", "T", "successful", null, null, null, null); + + var ex = Assert.ThrowsAsync(() => client.GetMessageBody(message, CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("no body_url")); + } + + [TestCase("0f8fad5b-d9cb-469f-a165-70867728950e")] + [TestCase("CustomChecks/0f8fad5b-d9cb-469f-a165-70867728950e")] + public async Task Custom_check_delete_uses_only_the_guid(string id) + { + var (client, handler) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.Accepted)); + + await client.DeleteCustomCheck(id, CancellationToken.None); + + Assert.That(handler.Requests[0].PathAndQuery, Is.EqualTo("/api/customchecks/0f8fad5b-d9cb-469f-a165-70867728950e")); + } + + [TestCase("retry", true)] + [TestCase("ARCHIVE", true)] + [TestCase("Retention-Sweep", true)] + [TestCase("search", false)] + [TestCase("custom-check-failures", false)] + public void Only_jobs_that_act_on_every_failure_group_conflict_with_a_smoke_run(string job, bool conflicts) => + Assert.That(SmokeJobConflicts.Conflicts(job), Is.EqualTo(conflicts)); +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs new file mode 100644 index 0000000000..e9686d816b --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs @@ -0,0 +1,247 @@ +using System.Net; +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using NServiceBus; +using NUnit.Framework; +using ServiceControl.Plugin.CustomChecks.Messages; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeChecksTests +{ + const string RunId = "smoke-test0001"; + + FakeMessageSession session = null!; + SmokeObservations observations = null!; + + [SetUp] + public void SetUp() + { + session = new FakeMessageSession(); + observations = new SmokeObservations(); + } + + SmokeChecks CreateChecks(Func serviceControl) => + new(new SmokeApiClient(new HttpClient(new FakeHttpHandler(serviceControl)) { BaseAddress = new Uri("http://sc.test") }), + new SmokeMonitoringClient(new HttpClient(new FakeHttpHandler(_ => FakeHttpHandler.Json("[]"))) { BaseAddress = new Uri("http://monitoring.test") }), + session, + observations, + Options.Create(new TestingToolOptions()), + new ConfigurationBuilder().Build()); + + static SmokeContext Context() => new(RunId, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(100)); + + static async Task Run(SmokeChecks checks, string id, SmokeContext context) + { + try + { + await checks.Create().Single(c => c.Id == id).Run!(context, CancellationToken.None); + } + finally + { + foreach (var cleanup in context.Cleanups.Reverse()) + { + await cleanup(CancellationToken.None); + } + } + } + + IEnumerable Reports => session.Sent.Select(s => s.Message).OfType(); + + [Test] + public async Task Custom_check_passes_when_the_api_shows_this_runs_check_fail_then_pass() + { + var checks = CreateChecks(r => + { + var failed = r.RequestUri!.Query.Contains("status=fail"); + var own = Reports.LastOrDefault(); + var ownIsListed = own is not null && own.HasFailed == failed; + var entry = ownIsListed ? $$"""{"id":"u1","custom_check_id":"{{own!.CustomCheckId}}","status":"{{(failed ? "fail" : "pass")}}","failure_reason":{{JsonSerializer.Serialize(own.FailureReason)}},"reported_at":"2026-01-01T00:00:00Z"}""" : ""; + return r.Method == HttpMethod.Delete ? FakeHttpHandler.Status(HttpStatusCode.Accepted) : FakeHttpHandler.Json($"[{entry}]"); + }); + + await Run(checks, "custom-check-fail-then-pass", Context()); + + Assert.That(Reports.Select(r => r.HasFailed).ToArray(), Is.EqualTo(new[] { true, false })); + Assert.That(Reports.Select(r => r.CustomCheckId).Distinct().Single(), Is.EqualTo($"Smoke.{RunId}")); + } + + [Test] + public void Custom_check_ignores_a_failed_check_from_another_run() + { + var checks = CreateChecks(r => FakeHttpHandler.Json("""[{"id":"u0","custom_check_id":"Smoke.smoke-older","status":"fail","failure_reason":"x","reported_at":"2026-01-01T00:00:00Z"}]""")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "custom-check-fail-then-pass", Context())); + + Assert.That(ex!.Message, Does.Contain($"no failed check with id Smoke.{RunId}")); + } + + [Test] + public void Audit_check_fails_without_a_remote_audit_instance() + { + var checks = CreateChecks(_ => FakeHttpHandler.Json("[]")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "audit-ingestion-fulltext", Context())); + + Assert.That(ex!.Message, Does.Contain("no remote audit instance")); + } + + [Test] + public void Audit_check_ignores_search_hits_for_other_messages() + { + var checks = CreateChecks(r => r.RequestUri!.AbsolutePath.EndsWith("/remotes") + ? FakeHttpHandler.Json("""[{"api_uri":"http://audit","status":"online"}]""") + : FakeHttpHandler.Json("""[{"id":"a1","message_id":"someone-elses","message_type":"X","status":"successful"}]""")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "audit-ingestion-fulltext", Context())); + + Assert.That(ex!.Message, Does.Contain("none with message id")); + } + + [Test] + public async Task Retry_single_retries_only_the_chosen_message_in_a_group_unique_to_the_run() + { + var server = new FailureServer(session, observations); + var checks = CreateChecks(server.Handle); + + await Run(checks, "retry-single", Context()); + + var failing = session.Sent.Select(s => (Message: (SmokeMessage)s.Message, Headers: s.Options.GetHeaders())).ToList(); + Assert.That(failing, Has.Count.EqualTo(2)); + Assert.That(failing.Select(f => f.Message.FailureType).Distinct().Single(), Is.EqualTo($"TestingTool.Smoke.Failure_{RunId.Replace('-', '_')}_retry_single")); + Assert.That(failing.All(f => f.Message.Fail && f.Headers[SmokeHeaders.RunId] == RunId), Is.True); + Assert.That(server.Retried, Has.Count.EqualTo(1)); + } + + [Test] + public void Retry_single_fails_when_the_retry_also_resolves_the_sibling() + { + var server = new FailureServer(session, observations) { RetryResolvesEverything = true }; + var checks = CreateChecks(server.Handle); + + var ex = Assert.ThrowsAsync(() => Run(checks, "retry-single", Context())); + + Assert.That(ex!.Message, Does.Contain("also acted on its sibling")); + } + + [Test] + public void Retry_group_fails_when_a_message_is_not_handled_even_though_the_api_accepted_the_retry() + { + var server = new FailureServer(session, observations) { HandlesRetries = false }; + var checks = CreateChecks(server.Handle); + + var ex = Assert.ThrowsAsync(() => Run(checks, "retry-group", Context())); + + Assert.That(ex!.Message, Does.Contain("handled by the endpoint: False")); + } + + [Test] + public async Task Failed_messages_left_unresolved_are_archived_when_the_check_ends() + { + var server = new FailureServer(session, observations); + var checks = CreateChecks(server.Handle); + + await Run(checks, "retry-single", Context()); + + Assert.That(server.Archived, Has.Count.EqualTo(1)); + Assert.That(server.Archived.Single(), Is.Not.EqualTo(server.Retried.Single())); + } + + [Test] + public async Task Endpoint_record_cleanup_deletes_only_the_named_run_endpoints() + { + var deleted = new List(); + var checks = CreateChecks(r => + { + if (r.Method == HttpMethod.Delete) + { + deleted.Add(r.RequestUri!.AbsolutePath); + return FakeHttpHandler.Status(HttpStatusCode.NoContent); + } + + return FakeHttpHandler.Json(""" + [{"id":"00000000-0000-0000-0000-000000000001","name":"TestingTool.Smoke.smoke-test0001.Source","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000002","name":"TestingTool.Smoke.smoke-test0001.Target","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000003","name":"TestingTool.Smoke.smoke-other.Source","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000004","name":"Sales","monitor_heartbeat":true}] + """); + }); + var context = Context(); + + checks.DeleteEndpointRecords(context, $"TestingTool.Smoke.{RunId}.Source", $"TestingTool.Smoke.{RunId}.Target"); + foreach (var cleanup in context.Cleanups) + { + await cleanup(CancellationToken.None); + } + + Assert.That(deleted, Is.EqualTo(["/api/endpoints/00000000-0000-0000-0000-000000000001", "/api/endpoints/00000000-0000-0000-0000-000000000002"])); + } + + /// Answers the failed-message API calls for the messages the checks sent through the fake session. + sealed class FailureServer(FakeMessageSession session, SmokeObservations observations) + { + readonly Dictionary status = []; + + public bool RetryResolvesEverything { get; init; } + public bool HandlesRetries { get; init; } = true; + public List Retried { get; } = []; + public List Archived { get; } = []; + + IEnumerable<(string MessageId, SmokeMessage Message, string ExceptionType)> Failing => session.Sent + .Where(s => s.Message is SmokeMessage) + .Select(s => (s.Options.GetMessageId()!, (SmokeMessage)s.Message, ((SmokeMessage)s.Message).FailureType)); + + string StatusOf(string messageId) => status.GetValueOrDefault(messageId, "unresolved"); + + public HttpResponseMessage Handle(HttpRequestMessage request) + { + var path = request.RequestUri!.AbsolutePath; + var failing = Failing.ToList(); + if (path == "/api/recoverability/groups") + { + return FakeHttpHandler.Json($$"""[{"id":"g1","title":"{{failing[0].ExceptionType}}: SmokeMessageHandler.Fail()","count":{{failing.Count}}}]"""); + } + + if (path == "/api/recoverability/groups/g1/errors") + { + return FakeHttpHandler.Json("[" + string.Join(",", failing.Select(f => $$"""{"id":"{{f.MessageId}}","message_id":"{{f.MessageId}}","status":"{{StatusOf(f.MessageId)}}","queue_address":"TestingTool.Load"}""")) + "]"); + } + + if (path == "/api/recoverability/groups/g1/errors/retry") + { + failing.ForEach(f => Resolve(f.MessageId, f.Message)); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + if (path == "/api/errors/archive") + { + var ids = JsonSerializer.Deserialize(request.Content!.ReadAsStringAsync().Result)!; + Archived.AddRange(ids); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + var id = path.Split('/')[3]; + if (path.EndsWith("/retry")) + { + Retried.Add(id); + failing.Where(f => RetryResolvesEverything || f.MessageId == id).ToList().ForEach(f => Resolve(f.MessageId, f.Message)); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + return FakeHttpHandler.Json($$$"""{"status":"{{{StatusOf(id)}}}","processing_attempts":[{"headers":{}}]}"""); + } + + void Resolve(string messageId, SmokeMessage message) + { + if (HandlesRetries) + { + observations.Release(message.Marker); + SmokeMessageHandler.Process(observations, message, null, "Endpoint"); + } + + status[messageId] = "resolved"; + } + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs new file mode 100644 index 0000000000..6ab908db1a --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs @@ -0,0 +1,250 @@ +using System.Text.Json; +using NServiceBus; +using NServiceBus.Features; +using Microsoft.Extensions.Logging.Abstractions; +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +/// Runs real in-process endpoints on the Learning transport in a temporary folder. No broker is needed. +[NonParallelizable] +public class SmokeEndpointLifecycleTests +{ + string storage = null!; + SmokeObservations observations = null!; + + [SetUp] + public void SetUp() + { + storage = Path.Combine(Path.GetTempPath(), "smoke-lifecycle-" + Guid.NewGuid().ToString("N")); + observations = new SmokeObservations(); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(storage)) + { + Directory.Delete(storage, recursive: true); + } + } + + Task Start(string name, Action? configure = null, CancellationToken ct = default) => + SmokeEndpoint.Start(name, config => config.UseTransport(new LearningTransport { StorageDirectory = storage }), configure, observations, "error", ct); + + static Dictionary Headers(string metadataFile) => + JsonSerializer.Deserialize>(File.ReadAllText(metadataFile))!; + + IEnumerable> QueueHeaders(string queue) => + Directory.Exists(Path.Combine(storage, queue)) ? Directory.GetFiles(Path.Combine(storage, queue), "*.metadata.txt").Select(Headers) : []; + + static async Task WaitUntil(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(15); + while (!condition()) + { + Assert.That(DateTime.UtcNow, Is.LessThan(deadline), "Timed out waiting for the condition"); + await Task.Delay(50); + } + } + + [Test] + public async Task Two_endpoints_handle_messages_with_their_own_identity_and_can_be_recreated() + { + await using var source = await Start("Smoke.Source"); + await using var target = await Start("Smoke.Target"); + Assert.That(source.MainAddress, Is.Not.EqualTo(target.MainAddress)); + + var send = new SendOptions(); + send.SetDestination(target.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "to-target" }, send); + await WaitUntil(() => observations.FindHandled("to-target") is not null); + Assert.That(observations.FindHandled("to-target")!.Endpoint, Is.EqualTo("Smoke.Target")); + + await target.StopAsync(CancellationToken.None); + await target.StopAsync(CancellationToken.None); + + await using var recreated = await Start("Smoke.Target"); + var again = new SendOptions(); + again.SetDestination(recreated.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "to-recreated" }, again); + await WaitUntil(() => observations.FindHandled("to-recreated") is not null); + Assert.That(recreated.MainAddress, Is.EqualTo(target.MainAddress)); + } + + [Test] + public async Task A_failing_message_reaches_the_error_queue_from_the_endpoint_that_failed_it() + { + await using var source = await Start("Smoke.Source"); + var send = new SendOptions(); + send.SetDestination(source.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "fails", Fail = true, FailureType = "TestingTool.Smoke.Failure_run_check" }, send); + + await WaitUntil(() => QueueHeaders("error").Any()); + var headers = QueueHeaders("error").Single(); + Assert.That(headers["NServiceBus.FailedQ"], Is.EqualTo(source.MainAddress)); + Assert.That(headers["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("TestingTool.Smoke.Failure_run_check")); + Assert.That(observations.FindHandled("fails"), Is.Null); + } + + [Test] + public async Task The_heartbeat_plugin_sends_heartbeats_to_the_service_control_queue() + { + Directory.CreateDirectory(Path.Combine(storage, "Particular.ServiceControl")); + + await using var endpoint = await Start("Smoke.Heartbeat", config => config.SendHeartbeatTo("Particular.ServiceControl", TimeSpan.FromSeconds(1))); + + await WaitUntil(() => QueueHeaders("Particular.ServiceControl").Any(h => h["NServiceBus.EnclosedMessageTypes"] == "ServiceControl.Plugin.Heartbeat.Messages.EndpointHeartbeat")); + } + + [Test] + public async Task The_metrics_plugin_reports_processing_time_of_handled_messages_with_scanning_disabled() + { + Directory.CreateDirectory(Path.Combine(storage, "Particular.Monitoring")); + + await using var endpoint = await Start("Smoke.Metrics", config => config.EnableMetrics().SendMetricDataToServiceControl("Particular.Monitoring", TimeSpan.FromSeconds(1))); + var send = new SendOptions(); + send.SetDestination(endpoint.MainAddress); + for (var i = 0; i < 3; i++) + { + await endpoint.Session.Send(new SmokeMessage { Marker = $"metrics-{i}", DelayMilliseconds = 100 }, send); + } + + await WaitUntil(() => Enumerable.Range(0, 3).All(i => observations.FindHandled($"metrics-{i}")?.Endpoint == endpoint.Name)); + await WaitUntil(() => QueueHeaders("Particular.Monitoring").Any(h => h.GetValueOrDefault("NServiceBus.Metric.Type") == "ProcessingTime")); + } + + [Test] + public async Task A_host_that_fails_to_start_is_disposed_and_a_later_start_works() + { + var blockedStorage = Path.Combine(Path.GetTempPath(), "smoke-blocked-" + Guid.NewGuid().ToString("N")); + await File.WriteAllTextAsync(blockedStorage, "a file where the storage folder should be"); + try + { + var ex = Assert.ThrowsAsync(() => SmokeEndpoint.Start( + "Smoke.Broken", config => config.UseTransport(new LearningTransport { StorageDirectory = blockedStorage }), null, observations, "error", CancellationToken.None)); + Assert.That(ex!.Message, Does.Contain("Smoke.Broken could not start")); + } + finally + { + File.Delete(blockedStorage); + } + + await using var working = await Start("Smoke.Broken"); + Assert.That(working.MainAddress, Is.Not.Empty); + } + + [Test] + public async Task Canceling_while_the_host_is_starting_keeps_the_cancellation_and_stops_the_services_that_started() + { + var probe = new StartupProbe(); + using var cancel = new CancellationTokenSource(); + var start = Start("Smoke.Cancelled", config => + { + EarlierFeature.Probe = probe; + config.EnableFeature(); + config.EnableFeature(); + }, cancel.Token); + + await WaitUntil(() => probe.Blocking); + cancel.Cancel(); + + Assert.CatchAsync(async () => await start); + Assert.That(probe.EarlierStarted && probe.EarlierStopped, Is.True, "the service that had started was stopped when the start was canceled"); + } + + [Test] + public void A_pre_cancelled_start_throws_cancellation() + { + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + Assert.CatchAsync(() => Start("Smoke.PreCancelled", ct: cancelled.Token)); + } + + [Test] + public async Task The_runner_stops_endpoint_hosts_before_http_cleanup_that_never_finishes_and_disposes_them() + { + var checkEndpoint = default(SmokeEndpoint); + var stopped = false; + var cleanupSawStoppedHost = false; + var check = new SmokeCheck("a", "a", "a", async (ctx, ct) => + { + checkEndpoint = await Start("Smoke.Runner"); + ctx.OnCleanup(async token => + { + // Like an API call that blocks until its time limit, registered before the host stop. + cleanupSawStoppedHost = stopped; + await Task.Delay(Timeout.Infinite, token); + }); + ctx.OnEndpointStop(async token => + { + await checkEndpoint.StopAsync(token); + stopped = true; + }); + }); + var runner = new SmokeRunner([check], () => null, TimeSpan.FromSeconds(30), TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(50), NullLogger.Instance); + + Assert.That(runner.TryStart(out _), Is.True); + await runner.WaitForCompletionAsync(); + + Assert.That(cleanupSawStoppedHost, Is.True); + var send = new SendOptions(); + send.SetDestination(checkEndpoint!.MainAddress); + await using var other = await Start("Smoke.Other"); + await other.Session.Send(new SmokeMessage { Marker = "after-stop" }, send); + await Task.Delay(500); + Assert.That(observations.FindHandled("after-stop"), Is.Null, "the stopped host no longer receives messages"); + } + + sealed class StartupProbe + { + public volatile bool EarlierStarted; + public volatile bool EarlierStopped; + public volatile bool Blocking; + } + + /// Starts and completes first, so a later cancellation leaves a started service behind. + sealed class EarlierFeature : Feature + { + public static StartupProbe Probe { get; set; } = new(); + + protected override void Setup(FeatureConfigurationContext context) => + context.RegisterStartupTask(new EarlierTask(Probe)); + + sealed class EarlierTask(StartupProbe probe) : FeatureStartupTask + { + protected override Task OnStart(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.EarlierStarted = true; + return Task.CompletedTask; + } + + protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.EarlierStopped = true; + return Task.CompletedTask; + } + } + } + + sealed class BlockingFeature : Feature + { + public BlockingFeature() => DependsOn(); + + protected override void Setup(FeatureConfigurationContext context) => + context.RegisterStartupTask(new BlockingTask(EarlierFeature.Probe)); + + sealed class BlockingTask(StartupProbe probe) : FeatureStartupTask + { + protected override async Task OnStart(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.Blocking = true; + await Task.Delay(Timeout.Infinite, cancellationToken); + } + + protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken = default) => Task.CompletedTask; + } + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs new file mode 100644 index 0000000000..635d06c426 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs @@ -0,0 +1,75 @@ +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeHandlerTests +{ + [Test] + public void Failure_headers_group_by_the_check() + { + var message = new SmokeMessage { Marker = "m1", Fail = true, FailureType = "TestingTool.Smoke.Failure_run_check" }; + var thrown = Assert.Throws(() => SmokeMessageHandler.Process(new SmokeObservations(), message, null, "Endpoint")); + var faultHeaders = new Dictionary + { + ["NServiceBus.FailedQ"] = "Source@dbo", + ["NServiceBus.ExceptionInfo.ExceptionType"] = "TestingTool.Smoke.SmokeFailureException", + ["NServiceBus.ExceptionInfo.Message"] = thrown!.Message + }; + + SmokeHeaders.CustomizeFailure(faultHeaders); + + Assert.That(faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("TestingTool.Smoke.Failure_run_check")); + Assert.That(faultHeaders["NServiceBus.FailedQ"], Is.EqualTo("Source@dbo")); + } + + [Test] + public void Failure_headers_leave_other_messages_untouched() + { + var faultHeaders = new Dictionary + { + ["NServiceBus.FailedQ"] = "TestingTool.Load", + ["NServiceBus.ExceptionInfo.ExceptionType"] = "System.Exception", + ["NServiceBus.ExceptionInfo.Message"] = "Something|else" + }; + + SmokeHeaders.CustomizeFailure(faultHeaders); + + Assert.That(faultHeaders, Has.Count.EqualTo(3)); + Assert.That(faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("System.Exception")); + } + + [Test] + public void Redirect_check_passes_only_when_the_target_handled_the_retry() + { + Assert.DoesNotThrow(() => SmokeChecks.RequireHandledBy(new SmokeObservations.HandledMessage(null, "", "Target"), "Target", "Source")); + var bySource = Assert.Throws(() => SmokeChecks.RequireHandledBy(new SmokeObservations.HandledMessage(null, "", "Source"), "Target", "Source")); + Assert.That(bySource!.Message, Does.Contain("handled by 'Source'")); + Assert.Throws(() => SmokeChecks.RequireHandledBy(null, "Target", "Source")); + } + + [Test] + public void A_failing_smoke_message_throws_until_its_marker_is_released() + { + var observations = new SmokeObservations(); + var message = new SmokeMessage { Marker = "m1", Fail = true }; + + Assert.Throws(() => SmokeMessageHandler.Process(observations, message, null, "Endpoint")); + Assert.That(observations.FindHandled("m1"), Is.Null); + + observations.Release("m1"); + SmokeMessageHandler.Process(observations, message, "failed-1", "Endpoint-A"); + + Assert.That(observations.FindHandled("m1")!.EditOf, Is.EqualTo("failed-1")); + Assert.That(observations.FindHandled("m1")!.Endpoint, Is.EqualTo("Endpoint-A")); + } + + [Test] + public void Releasing_one_marker_does_not_release_another() + { + var observations = new SmokeObservations(); + observations.Release("m1"); + + Assert.Throws(() => SmokeMessageHandler.Process(observations, new SmokeMessage { Marker = "m2", Fail = true }, null, "Endpoint")); + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs new file mode 100644 index 0000000000..3777c51146 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs @@ -0,0 +1,220 @@ +using Microsoft.Extensions.Logging.Abstractions; +using NUnit.Framework; +using TestingTool.Contracts; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeRunnerTests +{ + static SmokeRunner Create(IReadOnlyList checks, Func? conflict = null, TimeSpan? checkTimeout = null, TimeSpan? cleanupTimeout = null) => + new(checks, conflict ?? (() => null), checkTimeout ?? TimeSpan.FromSeconds(5), cleanupTimeout ?? TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(50), NullLogger.Instance); + + static SmokeCheck Check(string id, Func run, TimeSpan? timeout = null) => new(id, id, id, run, timeout); + + static async Task RunToEnd(SmokeRunner runner) + { + Assert.That(runner.TryStart(out var error), Is.True, error); + await runner.WaitForCompletionAsync(); + return runner.GetSnapshot(); + } + + [Test] + public async Task Runs_checks_in_order_and_continues_after_a_failure() + { + var order = new List(); + var runner = Create([ + Check("a", (_, _) => { order.Add("a"); return Task.CompletedTask; }), + Check("b", (_, _) => { order.Add("b"); throw new SmokeCheckFailedException("expected effect missing"); }), + SmokeCheck.Manual("m", "manual", "a person checks this"), + Check("c", (ctx, _) => { order.Add("c"); ctx.Detail = "ok"; return Task.CompletedTask; })]); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["a", "b", "c"])); + Assert.That(run.Checks.Select(c => c.Status), Is.EqualTo([SmokeCheckStatus.Passed, SmokeCheckStatus.Failed, SmokeCheckStatus.Manual, SmokeCheckStatus.Passed])); + Assert.That(run.Checks[1].Detail, Is.EqualTo("expected effect missing")); + Assert.That(run.Checks[3].Detail, Is.EqualTo("ok")); + Assert.That(run.Running, Is.False); + Assert.That(run.FinishedAt, Is.Not.Null); + } + + [Test] + public async Task Unexpected_errors_fail_the_check_with_the_error_type() + { + var runner = Create([Check("a", (_, _) => throw new HttpRequestException("connection refused"))]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Is.EqualTo("HttpRequestException: connection refused")); + } + + [Test] + public async Task Manual_rows_are_listed_before_and_after_a_run_without_executing() + { + var runner = Create([SmokeCheck.Manual("m", "manual", "desc")]); + Assert.That(runner.GetSnapshot().Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Manual)); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Manual)); + Assert.That(run.Checks[0].DurationSeconds, Is.Null); + } + + [Test] + public async Task Rejects_a_second_start_while_running_and_accepts_one_after() + { + var release = new TaskCompletionSource(); + var runner = Create([Check("a", async (_, _) => await release.Task)]); + Assert.That(runner.TryStart(out _), Is.True); + + Assert.That(runner.TryStart(out var error), Is.False); + Assert.That(error, Does.Contain("already in progress")); + Assert.That(runner.GetSnapshot().Running, Is.True); + + release.SetResult(); + await runner.WaitForCompletionAsync(); + Assert.That(runner.TryStart(out _), Is.True); + await runner.WaitForCompletionAsync(); + } + + [Test] + public void Refuses_to_start_when_a_conflicting_job_is_running() + { + var runner = Create([Check("a", (_, _) => Task.CompletedTask)], () => "Stop the 'retry' job first."); + + Assert.That(runner.TryStart(out var error), Is.False); + Assert.That(error, Is.EqualTo("Stop the 'retry' job first.")); + Assert.That(runner.GetSnapshot().RunId, Is.Null); + } + + [Test] + public async Task Stop_cancels_the_running_check_and_the_pending_ones_and_still_cleans_up() + { + var started = new TaskCompletionSource(); + var cleaned = false; + var secondRan = false; + var runner = Create([ + Check("a", async (ctx, ct) => + { + ctx.OnCleanup(_ => { cleaned = true; return Task.CompletedTask; }); + started.SetResult(); + await Task.Delay(Timeout.Infinite, ct); + }), + Check("b", (_, _) => { secondRan = true; return Task.CompletedTask; })]); + runner.TryStart(out _); + await started.Task; + + runner.Stop(); + await runner.WaitForCompletionAsync(); + + var run = runner.GetSnapshot(); + Assert.That(run.Checks.Select(c => c.Status), Is.EqualTo([SmokeCheckStatus.Canceled, SmokeCheckStatus.Canceled])); + Assert.That(cleaned, Is.True); + Assert.That(secondRan, Is.False); + } + + [Test] + public async Task A_check_that_exceeds_its_timeout_fails_and_the_next_check_runs() + { + var runner = Create([ + Check("slow", (_, ct) => Task.Delay(Timeout.Infinite, ct), TimeSpan.FromMilliseconds(30)), + Check("next", (_, _) => Task.CompletedTask)]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Does.Contain("did not finish within")); + Assert.That(run.Checks[1].Status, Is.EqualTo(SmokeCheckStatus.Passed)); + } + + [Test] + public async Task Cleanups_run_in_reverse_order_after_a_failure_and_a_cleanup_error_is_reported() + { + var order = new List(); + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(_ => { order.Add("first"); return Task.CompletedTask; }); + ctx.OnCleanup(_ => throw new InvalidOperationException("could not delete")); + throw new SmokeCheckFailedException("boom"); + })]); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["first"])); + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Does.StartWith("boom").And.Contain("could not delete")); + } + + [Test] + public async Task WaitFor_reports_the_last_observation_when_it_times_out() + { + var runner = Create([Check("a", async (ctx, ct) => + await ctx.WaitFor("the effect", _ => Task.FromResult(PollResult.Waiting("saw 2 of 3")), ct))]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Detail, Does.Contain("waiting for the effect").And.Contain("Last observed: saw 2 of 3")); + } + + [Test] + public async Task Each_run_gets_its_own_run_id_and_the_last_run_stays_visible() + { + var ids = new List(); + var runner = Create([Check("a", (ctx, _) => { ids.Add(ctx.RunId); return Task.CompletedTask; })]); + + var first = await RunToEnd(runner); + var second = await RunToEnd(runner); + + Assert.That(ids, Has.Count.EqualTo(2)); + Assert.That(ids[0], Is.Not.EqualTo(ids[1])); + Assert.That(first.RunId, Is.EqualTo(ids[0])); + Assert.That(second.RunId, Is.EqualTo(ids[1])); + Assert.That(runner.GetSnapshot().Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Passed)); + } + + [Test] + public async Task A_cleanup_that_outlives_its_time_limit_is_cancelled_and_awaited_not_abandoned() + { + var observedCancellation = false; + var finished = false; + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(async token => + { + try { await Task.Delay(Timeout.Infinite, token); } + catch (OperationCanceledException) { observedCancellation = true; throw; } + finally { finished = true; } + }); + return Task.CompletedTask; + })], cleanupTimeout: TimeSpan.FromMilliseconds(50)); + + var run = await RunToEnd(runner); + + Assert.That(observedCancellation && finished, Is.True); + Assert.That(run.Checks[0].Detail, Does.Contain("timed out")); + } + + [Test] + public async Task Endpoint_stops_run_before_cleanups_even_when_a_stop_fails_and_a_cleanup_blocks() + { + var order = new List(); + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(async token => + { + order.Add("blocking cleanup"); + await Task.Delay(Timeout.Infinite, token); + }); + ctx.OnEndpointStop(_ => { order.Add("stop first"); return Task.CompletedTask; }); + ctx.OnEndpointStop(_ => { order.Add("stop second"); throw new InvalidOperationException("stop failed"); }); + return Task.CompletedTask; + })], cleanupTimeout: TimeSpan.FromMilliseconds(50)); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["stop second", "stop first", "blocking cleanup"])); + Assert.That(run.Checks[0].Detail, Does.Contain("stop failed").And.Contain("timed out")); + } +} diff --git a/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs b/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs index 09f6da9f2e..71c85a6462 100644 --- a/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs +++ b/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs @@ -17,7 +17,7 @@ namespace ServiceControl.Plugin.CustomChecks.Messages; /// pass/fail reports that ServiceControl ingests as if a real endpoint (or ServiceControl /// itself) had produced them. /// -sealed class ReportCustomCheckResult : ICommand +public sealed class ReportCustomCheckResult : ICommand { /// Stable id of the host that ran the check. ServiceControl groups custom checks /// by HostId + CustomCheckId + Category, so a stable value per check gives coherent state diff --git a/tools/testing-tool/TestingTool/NServiceBusSetup.cs b/tools/testing-tool/TestingTool/NServiceBusSetup.cs index 499c08d9e8..05baee80d5 100644 --- a/tools/testing-tool/TestingTool/NServiceBusSetup.cs +++ b/tools/testing-tool/TestingTool/NServiceBusSetup.cs @@ -2,7 +2,9 @@ using Microsoft.Data.SqlClient; using Microsoft.Extensions.Options; using NServiceBus; +using NServiceBus.Features; using TestingTool.Auditing; +using TestingTool.Smoke; namespace TestingTool; @@ -30,8 +32,61 @@ public static class NServiceBusEndpointExtensions /// public static IServiceCollection AddTestingToolEndpoint(this IServiceCollection services, TestingToolOptions options, IConfiguration configuration) { - var config = new EndpointConfiguration("TestingTool.Load"); + var config = new EndpointConfiguration(LoadEndpointName); + var selectedTransport = ConfigureTransport(config, configuration); + services.AddSingleton(selectedTransport); + services.AddSingleton(new SmokeEndpointIdentity(LoadEndpointName)); + + // Route failures to the ServiceControl error queue. + config.SendFailedMessagesTo(options.ErrorQueueName); + config.AuditProcessedMessagesTo(options.AuditQueueName); + + // Lets the direct audit-queue writer replace the wire message after serialization, which is + // the only stage late enough to control NServiceBus.EnclosedMessageTypes and the timestamps. + config.Pipeline.Register(new RawAuditPayloadBehavior(), "Applies raw audit envelopes from the direct audit-queue writer"); + config.SendHeartbeatTo(options.ServiceControlInputQueue); + + // enable metrics + var metrics = config.EnableMetrics(); + metrics.SendMetricDataToServiceControl( + serviceControlMetricsAddress: options.MonitoringQueueName, + interval: TimeSpan.FromSeconds(2) + ); + + // Simplified serializer; the testing tool generates volume, not complex payloads. + config.UseSerialization(); + + // Disable immediate retries to make error groups cleaner; deferred retries are handled + // by ServiceControl's retry mechanism. + var recoverability = config.Recoverability(); + recoverability.Immediate(im => im.NumberOfRetries(0)); + recoverability.Delayed(d => d.NumberOfRetries(0)); + + // Smoke checks: a saga with saga auditing, SmokeMessage failures grouped per check, and the + // ServiceControl integration events, subscribed explicitly while a smoke check needs them. + config.UsePersistence().SagaStorageDirectory(Path.Combine(Path.GetTempPath(), "TestingTool.Sagas")); + config.AuditSagaStateChanges(options.AuditQueueName); + recoverability.Failed(failed => failed.HeaderCustomization(SmokeHeaders.CustomizeFailure)); + config.DisableFeature(); + config.Conventions().DefiningEventsAs(type => + typeof(IEvent).IsAssignableFrom(type) || type.Namespace?.StartsWith("ServiceControl.Contracts", StringComparison.Ordinal) == true); + + config.EnableInstallers(); + + services.AddNServiceBusEndpoint(config); + return services; + } + + public const string LoadEndpointName = "TestingTool.Load"; + + /// + /// Selects the transport from the transport connection string, as documented on + /// . The smoke tests call it for their own endpoints too, so they + /// share the transport and topology of the load endpoint. + /// + public static SelectedTransport ConfigureTransport(EndpointConfiguration config, IConfiguration configuration) + { var transportConnectionString = configuration.GetConnectionString("transport"); string transportName; if (string.IsNullOrWhiteSpace(transportConnectionString)) @@ -65,37 +120,7 @@ public static IServiceCollection AddTestingToolEndpoint(this IServiceCollection "Initial Catalog/Database for SQL Server. Leave it unset to use the Learning transport."); } - services.AddSingleton(new SelectedTransport(transportName)); - - // Route failures to the ServiceControl error queue. - config.SendFailedMessagesTo(options.ErrorQueueName); - config.AuditProcessedMessagesTo(options.AuditQueueName); - - // Lets the direct audit-queue writer replace the wire message after serialization, which is - // the only stage late enough to control NServiceBus.EnclosedMessageTypes and the timestamps. - config.Pipeline.Register(new RawAuditPayloadBehavior(), "Applies raw audit envelopes from the direct audit-queue writer"); - config.SendHeartbeatTo(options.ServiceControlInputQueue); - - // enable metrics - var metrics = config.EnableMetrics(); - metrics.SendMetricDataToServiceControl( - serviceControlMetricsAddress: options.MonitoringQueueName, - interval: TimeSpan.FromSeconds(2) - ); - - // Simplified serializer; the testing tool generates volume, not complex payloads. - config.UseSerialization(); - - // Disable immediate retries to make error groups cleaner; deferred retries are handled - // by ServiceControl's retry mechanism. - var recoverability = config.Recoverability(); - recoverability.Immediate(im => im.NumberOfRetries(0)); - recoverability.Delayed(d => d.NumberOfRetries(0)); - - config.EnableInstallers(); - - services.AddNServiceBusEndpoint(config); - return services; + return new SelectedTransport(transportName); } static bool IsAzureServiceBusConnectionString(string connectionString) diff --git a/tools/testing-tool/TestingTool/Program.cs b/tools/testing-tool/TestingTool/Program.cs index 6ea727445d..8183d9128b 100644 --- a/tools/testing-tool/TestingTool/Program.cs +++ b/tools/testing-tool/TestingTool/Program.cs @@ -4,6 +4,7 @@ using TestingTool.Contracts; using TestingTool.Jobs; using TestingTool.Scenarios; +using TestingTool.Smoke; // --- Configuration --- @@ -59,6 +60,39 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); +// --- Smoke tests --- +// An API-verified checklist run from the "Smoke tests" tab. See SmokeChecks for what each check verifies. + +builder.Services.AddHttpClient((sp, client) => +{ + client.BaseAddress = new Uri(sp.GetRequiredService>().Value.ServiceControlApiUrl); + client.Timeout = TimeSpan.FromSeconds(30); +}); +builder.Services.AddHttpClient((sp, client) => +{ + client.BaseAddress = new Uri(sp.GetRequiredService>().Value.MonitoringApiUrl); + client.Timeout = TimeSpan.FromSeconds(30); +}); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => +{ + var opts = sp.GetRequiredService>().Value; + var jobs = sp.GetRequiredService(); + return new SmokeRunner( + sp.GetRequiredService().Create(), + () => jobs.All.FirstOrDefault(j => j.IsRunning && SmokeJobConflicts.Conflicts(j.Name)) is { } job + ? $"Stop the '{job.Name}' job first. It acts on every failed message group, not only the groups of the smoke run." + : null, + opts.SmokeCheckTimeout, + TimeSpan.FromSeconds(60), + opts.SmokePollInterval, + opts.SmokePollTimeout, + sp.GetRequiredService>()); +}); +// Registered after the NServiceBus endpoint so it stops first and the run can still clean up through the endpoint. +builder.Services.AddHostedService(); + // --- Application pipeline --- var app = builder.Build(); @@ -70,6 +104,7 @@ var scClient = app.Services.GetRequiredService(); var jobRunner = app.Services.GetRequiredService(); var startedAt = DateTimeOffset.UtcNow; +var smokeStartGate = new Lock(); // Auto-start background noise after the endpoint is ready. app.Lifetime.ApplicationStarted.Register(() => @@ -160,14 +195,21 @@ app.MapGet("/api/jobs", () => Results.Ok(jobRunner.GetSnapshot())); -app.MapPost("/api/jobs/{name}/start", (string name, StartJobRequest? request) => +app.MapPost("/api/jobs/{name}/start", (string name, StartJobRequest? request, SmokeRunner smokeRunner) => { var interval = request?.IntervalSeconds is { } secs and > 0 ? TimeSpan.FromSeconds(secs) : (TimeSpan?)null; - if (!jobRunner.TryStart(name, interval, request, out var error)) - return Results.BadRequest(new { error }); + // The same lock guards smoke start, so a conflicting job and a smoke run cannot both pass their check. + lock (smokeStartGate) + { + if (SmokeJobConflicts.Conflicts(name) && smokeRunner.GetSnapshot().Running) + return Results.BadRequest(new { error = $"Job '{name}' acts on every failed message group, so it cannot start while a smoke run is in progress." }); + + if (!jobRunner.TryStart(name, interval, request, out var error)) + return Results.BadRequest(new { error }); + } var snapshot = jobRunner.GetSnapshot() .First(j => j.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); @@ -275,6 +317,24 @@ return Results.Ok(new { started = preset.Name, scenario = preset.ScenarioName, rate = preset.Rate }); }); +// --- Smoke test endpoints --- + +app.MapGet("/api/smoke", (SmokeRunner runner) => Results.Ok(runner.GetSnapshot())); + +app.MapPost("/api/smoke/start", (SmokeRunner runner) => +{ + lock (smokeStartGate) + { + return runner.TryStart(out var error) ? Results.Ok(runner.GetSnapshot()) : Results.BadRequest(new { error }); + } +}); + +app.MapPost("/api/smoke/stop", (SmokeRunner runner) => +{ + runner.Stop(); + return Results.Ok(runner.GetSnapshot()); +}); + app.MapFallbackToFile("index.html"); app.Run(); \ No newline at end of file diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs new file mode 100644 index 0000000000..76bc92aa02 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace TestingTool.Smoke; + +/// +/// Strict ServiceControl primary API client for the smoke checks. Unlike +/// every transport error, timeout and unexpected status throws , +/// so a check never reads an empty result as "nothing found". +/// +public sealed class SmokeApiClient(HttpClient http) +{ + // ServiceControl's JSON contract is snake_case with camelCase string enums. + static readonly JsonSerializerOptions ServiceControlJson = new(JsonSerializerDefaults.Web) + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + const string IncompleteResultsHeader = "X-Particular-Incomplete-Results"; + const int PageSize = 100; + const int MaxPages = 50; + + public static string UriEscape(string value) => Uri.EscapeDataString(value); + + public async Task> GetRemotes(CancellationToken ct) => + await Get>("/api/configuration/remotes", ct) ?? []; + + public Task> GetCustomChecks(string status, CancellationToken ct) => + GetAllPages($"/api/customchecks?status={status}", ct); + + /// The RavenDB persister returns ids as CustomChecks/{guid}, but the delete route takes the guid. + public Task DeleteCustomCheck(string id, CancellationToken ct) => + Run(HttpMethod.Delete, $"/api/customchecks/{id[(id.LastIndexOf('/') + 1)..]}", null, ct, HttpStatusCode.Accepted); + + public async Task> GetEndpoints(CancellationToken ct) => + await Get>("/api/endpoints", ct) ?? []; + + public Task DeleteEndpoint(Guid id, CancellationToken ct) => Run(HttpMethod.Delete, $"/api/endpoints/{id}", null, ct, HttpStatusCode.NoContent); + + public async Task> GetGroups(CancellationToken ct) => + await Get>("/api/recoverability/groups", ct) ?? []; + + public Task> GetGroupErrors(string groupId, CancellationToken ct) => + GetAllPages($"/api/recoverability/groups/{UriEscape(groupId)}/errors", ct); + + /// Returns null while ServiceControl answers 404, that is before the failure is ingested. + public async Task FindFailedMessage(string id, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, $"/api/errors/{UriEscape(id)}", null, ct, HttpStatusCode.OK, HttpStatusCode.NotFound); + return response.StatusCode == HttpStatusCode.NotFound ? null : await Read(response, ct); + } + + public Task RetryMessage(string id, CancellationToken ct) => Run(HttpMethod.Post, $"/api/errors/{UriEscape(id)}/retry", null, ct, HttpStatusCode.Accepted); + + public Task RetryGroup(string groupId, CancellationToken ct) => + Run(HttpMethod.Post, $"/api/recoverability/groups/{UriEscape(groupId)}/errors/retry", null, ct, HttpStatusCode.Accepted); + + public Task ArchiveMessages(IReadOnlyList ids, CancellationToken ct) => Run(HttpMethod.Patch, "/api/errors/archive", ids, ct, HttpStatusCode.Accepted); + + public async Task EditMessage(string id, string body, Dictionary headers, CancellationToken ct) + { + using var response = await Send(HttpMethod.Post, $"/api/edit/{UriEscape(id)}", new EditRequest(body, headers), ct, HttpStatusCode.Accepted, HttpStatusCode.OK); + return response.StatusCode == HttpStatusCode.Accepted; + } + + public Task> GetRedirects(CancellationToken ct) => GetAllPages("/api/redirects", ct); + + public Task CreateRedirect(string from, string to, CancellationToken ct) => + Run(HttpMethod.Post, "/api/redirects", new RedirectRequest(from, to, false), ct, HttpStatusCode.Created); + + public Task DeleteRedirect(Guid id, CancellationToken ct) => Run(HttpMethod.Delete, $"/api/redirects/{id}", null, ct, HttpStatusCode.NoContent); + + public Task>> SearchMessages(string query, CancellationToken ct) => + GetAudited>($"/api/messages/search?q={UriEscape(query)}", ct, []); + + public Task>> GetConversation(string conversationId, CancellationToken ct) => + GetAudited>($"/api/conversations/{UriEscape(conversationId)}?per_page={PageSize}", ct, []); + + /// Follows the relative body_url of an audited message, which names the instance that stores the body. + public async Task GetMessageBody(AuditedMessage message, CancellationToken ct) + { + if (string.IsNullOrEmpty(message.BodyUrl)) + { + throw new SmokeCheckFailedException($"Audited message {message.MessageId} has no body_url, so its stored body cannot be read"); + } + + using var response = await Send(HttpMethod.Get, "/api" + message.BodyUrl, null, ct, HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(ct); + } + + /// The primary answers 204 until the audit instance has ingested the saga. + public async Task> GetSaga(Guid sagaId, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, $"/api/sagas/{sagaId}", null, ct, HttpStatusCode.OK, HttpStatusCode.NoContent); + var incomplete = IncompleteInstances(response); + return new Audited(response.StatusCode == HttpStatusCode.NoContent ? null : await Read(response, ct), incomplete); + } + + async Task> GetAudited(string path, CancellationToken ct, T fallback) + { + using var response = await Send(HttpMethod.Get, path, null, ct, HttpStatusCode.OK); + return new Audited(await Read(response, ct) ?? fallback, IncompleteInstances(response)); + } + + async Task Get(string path, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, path, null, ct, HttpStatusCode.OK); + return await Read(response, ct); + } + + async Task> GetAllPages(string path, CancellationToken ct) + { + var all = new List(); + var separator = path.Contains('?') ? '&' : '?'; + for (var page = 1; page <= MaxPages; page++) + { + var items = await Get>($"{path}{separator}page={page}&per_page={PageSize}", ct) ?? []; + all.AddRange(items); + if (items.Count < PageSize) + { + return all; + } + } + + throw new SmokeCheckFailedException($"GET {path} has more than {MaxPages * PageSize} entries, which the smoke checks do not page through"); + } + + static string? IncompleteInstances(HttpResponseMessage response) => + response.Headers.TryGetValues(IncompleteResultsHeader, out var values) ? string.Join(", ", values) : null; + + static async Task Read(HttpResponseMessage response, CancellationToken ct) + { + try + { + return await response.Content.ReadFromJsonAsync(ServiceControlJson, ct); + } + catch (JsonException ex) + { + throw new SmokeCheckFailedException($"{response.RequestMessage?.RequestUri?.PathAndQuery} returned a body that is not the expected JSON: {ex.Message}"); + } + } + + async Task Run(HttpMethod method, string path, object? body, CancellationToken ct, params HttpStatusCode[] accepted) + { + using var response = await Send(method, path, body, ct, accepted); + } + + Task Send(HttpMethod method, string path, object? body, CancellationToken ct, params HttpStatusCode[] accepted) => + SmokeHttp.Send(http, method, path, body is null ? null : JsonContent.Create(body, body.GetType(), null, ServiceControlJson), ct, accepted); + + public sealed record RemoteInstance(string ApiUri, string Status); + + public sealed record CustomCheckView(string Id, string CustomCheckId, string Status, string? FailureReason, DateTime ReportedAt); + + public sealed record EndpointView(Guid Id, string Name, bool MonitorHeartbeat, HeartbeatInformation? HeartbeatInformation); + + public sealed record HeartbeatInformation(string ReportedStatus); + + public sealed record FailedMessageView(string Id, string MessageId, string Status, string? QueueAddress, bool Edited, string? EditOf); + + public sealed record FailedMessageDetail(string Status, List ProcessingAttempts); + + public sealed record ProcessingAttempt(Dictionary Headers); + + public sealed record RedirectView(Guid MessageRedirectId, string FromPhysicalAddress, string ToPhysicalAddress); + + public sealed record AuditedMessage(string Id, string MessageId, string MessageType, string Status, string? ConversationId, string? BodyUrl, List? Headers, List? InvokedSagas) + { + public string? Header(string name) => Headers?.FirstOrDefault(h => h.Key == name)?.Value; + } + + public sealed record HeaderEntry(string Key, string? Value); + + public sealed record SagaReference(Guid SagaId, string SagaType); + + public sealed record SagaHistory(Guid SagaId, string SagaType, List Changes); + + public sealed record SagaChange(string Status, DateTime FinishTime); + + /// A read that spans instances. names the instances that did not answer. + public sealed record Audited(T Value, string? Incomplete); + + sealed record EditRequest(string MessageBody, Dictionary MessageHeaders); + + sealed record RedirectRequest( + [property: JsonPropertyName("fromphysicaladdress")] string From, + [property: JsonPropertyName("tophysicaladdress")] string To, + [property: JsonPropertyName("retryexisting")] bool RetryExisting); +} + +/// +/// ServiceControl.Monitoring API client for the smoke checks. Routes have no /api prefix and +/// the JSON is camelCase. +/// +public sealed class SmokeMonitoringClient(HttpClient http) +{ + static readonly JsonSerializerOptions MonitoringJson = new(JsonSerializerDefaults.Web); + + public async Task> GetMonitoredEndpoints(CancellationToken ct) + { + using var response = await SmokeHttp.Send(http, HttpMethod.Get, "/monitored-endpoints", null, ct, HttpStatusCode.OK); + return await response.Content.ReadFromJsonAsync>(MonitoringJson, ct) ?? []; + } + + public async Task DeleteInstance(string endpointName, string instanceId, CancellationToken ct) + { + using var response = await SmokeHttp.Send(http, HttpMethod.Delete, + $"/monitored-instance/{Uri.EscapeDataString(endpointName)}/{Uri.EscapeDataString(instanceId)}", null, ct, HttpStatusCode.OK); + } + + public sealed record MonitoredEndpoint(string Name, bool IsStale, string[]? EndpointInstanceIds, Dictionary Metrics); + + public sealed record MonitoredValues(double? Average); +} + +static class SmokeHttp +{ + public static async Task Send(HttpClient http, HttpMethod method, string path, HttpContent? content, CancellationToken ct, params HttpStatusCode[] accepted) + { + using var request = new HttpRequestMessage(method, path) { Content = content }; + HttpResponseMessage response; + try + { + response = await http.SendAsync(request, ct); + } + catch (HttpRequestException ex) + { + throw new SmokeCheckFailedException($"{method} {path} could not reach {http.BaseAddress}: {ex.Message}"); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new SmokeCheckFailedException($"{method} {path} to {http.BaseAddress} timed out"); + } + + if (!accepted.Contains(response.StatusCode)) + { + var text = await response.Content.ReadAsStringAsync(ct); + var status = (int)response.StatusCode; + response.Dispose(); + throw new SmokeCheckFailedException($"{method} {path} returned {status}: {(text.Length > 300 ? text[..300] : text)}"); + } + + return response; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs b/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs new file mode 100644 index 0000000000..fa1625a1a2 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs @@ -0,0 +1,82 @@ +namespace TestingTool.Smoke; + +/// +/// One row of the smoke checklist. A null marks a manual row that the runner +/// lists but never executes. +/// +public sealed record SmokeCheck( + string Id, + string Title, + string Description, + Func? Run, + TimeSpan? Timeout = null) +{ + public bool IsManual => Run is null; + + public static SmokeCheck Manual(string id, string title, string description) => new(id, title, description, null); +} + +/// A check's expectation was not met. The message is shown in the UI as the failure detail. +public sealed class SmokeCheckFailedException(string message) : Exception(message); + +public readonly record struct PollResult(bool IsDone, T? Value, string Observed); + +public static class PollResult +{ + public static PollResult Done(T value) => new(true, value, ""); + + public static PollResult Waiting(string observed) => new(false, default, observed); +} + +/// +/// Per-check state: the run identifier that scopes everything the check creates, bounded polling, +/// and cleanup actions the runner always executes after the check. +/// +public sealed class SmokeContext(string runId, TimeSpan pollInterval, TimeSpan pollTimeout) +{ + readonly List> cleanups = []; + readonly List> endpointStops = []; + + public string RunId { get; } = runId; + + /// Text shown as the detail of a passed check. + public string? Detail { get; set; } + + /// Registers an action the runner always awaits after the check. Its token cancels when the cleanup time limit passes. + public void OnCleanup(Func cleanup) => cleanups.Add(cleanup); + + /// + /// Registers the stop of an endpoint host the check started. The runner awaits all stops before any + /// cleanup, so an unavailable API cannot use up the time that stopping the hosts needs. + /// + public void OnEndpointStop(Func stop) => endpointStops.Add(stop); + + public IReadOnlyList> EndpointStops => endpointStops; + + public IReadOnlyList> Cleanups => cleanups; + + /// + /// Calls until it reports done or passes. + /// Exceptions from the probe, such as an API or transport error, fail the check immediately. + /// + public async Task WaitFor(string description, Func>> probe, CancellationToken ct, TimeSpan? timeout = null) + { + var limit = timeout ?? pollTimeout; + var started = System.Diagnostics.Stopwatch.StartNew(); + while (true) + { + var result = await probe(ct); + if (result.IsDone) + { + return result.Value!; + } + + if (started.Elapsed >= limit) + { + throw new SmokeCheckFailedException($"Timed out after {limit.TotalSeconds:0.#}s waiting for {description}. Last observed: {result.Observed}"); + } + + await Task.Delay(pollInterval, ct); + } + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs new file mode 100644 index 0000000000..77bafc24aa --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs @@ -0,0 +1,577 @@ +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using NServiceBus; +using ServiceControl.Plugin.CustomChecks.Messages; +using static TestingTool.Smoke.SmokeApiClient; + +namespace TestingTool.Smoke; + +/// +/// The smoke checklist. Every automated check sends its own messages with a run-scoped identifier, then +/// reads the effect back through the ServiceControl APIs. Nothing is matched by anything the background +/// load could also produce. +/// +public sealed class SmokeChecks( + SmokeApiClient api, + SmokeMonitoringClient monitoring, + IMessageSession session, + SmokeObservations observations, + IOptions options, + IConfiguration configuration) +{ + /// Heartbeats are marked dead 40 seconds after the last one, checked every 5 seconds. + static readonly TimeSpan HeartbeatDeadTimeout = TimeSpan.FromSeconds(100); + + public IReadOnlyList Create() => + [ + new("custom-check-fail-then-pass", "Custom check fails, then passes", + "Reports a failed then a passed custom check with a run-specific id to the primary input queue, and reads it from GET /api/customchecks?status=fail and ?status=pass.", + CustomCheckFailThenPass), + new("heartbeat-beating-then-dead", "Heartbeat is healthy, then the endpoint is reported dead", + "Starts a real endpoint named after the run with the NServiceBus.Heartbeat plugin and reads heartbeat_information.reported_status from GET /api/endpoints: beating, then dead after the endpoint host stops. Takes about a minute.", + HeartbeatBeatingThenDead, TimeSpan.FromMinutes(4)), + new("audit-ingestion-fulltext", "Audited message is ingested and found by full-text search", + "Processes a message carrying a run-specific word, then finds it with GET /api/messages/search and reads its body from GET /api/messages/{id}/body. Needs an audit instance registered as a remote of the primary.", + AuditIngestionFulltext), + new("fanout-conversation", "Fan-out conversation keeps its parent links", + "Processes a message that sends two children per level for two levels, then reads the seven-message conversation from GET /api/conversations/{id} and checks each NServiceBus.RelatedTo header. Needs an audit instance.", + FanOutConversation), + new("saga-audit", "Saga audit data records new, updated and completed", + "Runs a real saga through three state changes with saga auditing on, finds the audited start message with GET /api/messages/search and reads GET /api/sagas/{id}. Needs an audit instance.", + SagaAudit), + new("monitoring-data", "Monitoring reports processing time for an endpoint", + "Starts a real endpoint named after the run with the NServiceBus.Metrics.ServiceControl plugin, handles three messages that each take 100 ms, and reads the processingTime average for that endpoint from GET /monitored-endpoints on the monitoring instance.", + MonitoringData), + new("integration-event", "MessageFailed integration event is received", + "Subscribes this endpoint to ServiceControl.Contracts.MessageFailed, fails one message, and matches the published event by a run header and the failed message id. Needs SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true on the instance that ingests errors.", + IntegrationEvent), + new("retry-single", "Retry one failed message", + "Fails two messages in a run-specific group, retries one with POST /api/errors/{id}/retry, and checks that it was handled and resolved while the other stayed unresolved.", + RetrySingle), + new("retry-group", "Retry a failed message group", + "Fails three messages in a run-specific group, retries the group with POST /api/recoverability/groups/{id}/errors/retry, and checks that each message was handled and resolved.", + RetryGroup), + new("edit-and-retry", "Edit the body of a failed message and retry it", + "Fails a message, sends the edited body that no longer fails through POST /api/edit/{id} with every original header, and checks that the edited message arrived with ServiceControl.EditOf and the edited text. Needs SERVICECONTROL_ALLOWMESSAGEEDITING=true.", + EditAndRetry), + new("retry-through-redirect", "Retry through a redirect", + "Starts a Source and a Target endpoint, fails a message in Source, creates a redirect from the Source input address to the Target input address with POST /api/redirects, retries it, and checks that Target handled it and it is resolved. Runs last because a redirect changes retry routing while it exists.", + RetryThroughRedirect), + + SmokeCheck.Manual("manual-installation", "Instance installation and upgrade", + "Not automated. Upgrade and create instances with the installer and with the PowerShell scripts, on localhost and on a custom hostname, as listed under Instance management installation."), + SmokeCheck.Manual("manual-servicepulse-custom-checks-heartbeats", "ServicePulse: custom checks and heartbeats views", + "Not automated. The API data is verified above. A person confirms that ServicePulse shows the custom check warning and clears it, and moves an endpoint from healthy to unhealthy."), + SmokeCheck.Manual("manual-servicepulse-recoverability", "ServicePulse: recoverability screens", + "Not automated. The API effects are verified above. A person confirms the retry, edit and redirect screens in ServicePulse, including Configuration > Create redirect."), + SmokeCheck.Manual("manual-servicepulse-audit-saga", "ServicePulse: message search, sequence diagram and saga view", + "Not automated. The audit, conversation and saga data is verified above. A person confirms that the search box finds a message, that the sequence diagram draws the fan-out, and that the saga view draws the graph."), + SmokeCheck.Manual("manual-integration-events-sample", "Integration events sample", + "Not automated. This tool verifies reception in its own endpoint. A person runs the public integration events sample on the transport under test and confirms that its subscriber receives MessageFailed."), + SmokeCheck.Manual("manual-monitoring-graphs", "ServicePulse: monitoring tab", + "Not automated. The metric data is verified above for a real run-scoped endpoint. A person confirms that the endpoints, the failed messages indicator and the graphs render."), + SmokeCheck.Manual("manual-chaos", "Chaos testing", + "Not automated. Stop ServiceControl processes gracefully and with kill while ingestion and large retry groups run, and verify storage and logic afterwards."), + SmokeCheck.Manual("manual-performance", "Performance, load and stability testing", + "Not automated. Use the load scenarios and bypass writers for performance on clean, moderate and large databases, and check reboots, service stops, virtual machine kills and upgrades under load.") + ]; + + async Task CustomCheckFailThenPass(SmokeContext ctx, CancellationToken ct) + { + var checkId = $"Smoke.{ctx.RunId}"; + var hostId = Guid.NewGuid(); + var reason = $"Smoke run {ctx.RunId} reports a failure"; + ctx.OnCleanup(async token => + { + foreach (var status in new[] { "fail", "pass" }) + { + foreach (var view in (await api.GetCustomChecks(status, token)).Where(c => c.CustomCheckId == checkId)) + { + await api.DeleteCustomCheck(view.Id, token); + } + } + }); + + await SendCustomCheck(checkId, hostId, ctx.RunId, failed: true, reason, ct); + await ctx.WaitFor("the custom check to appear as failed", async token => + { + var checks = (await api.GetCustomChecks("fail", token)).Where(c => c.CustomCheckId == checkId).ToList(); + return checks.Count == 0 + ? PollResult.Waiting($"no failed check with id {checkId}") + : checks[0].FailureReason == reason + ? PollResult.Done(checks[0]) + : PollResult.Waiting($"failure reason was '{checks[0].FailureReason}'"); + }, ct); + + await SendCustomCheck(checkId, hostId, ctx.RunId, failed: false, null, ct); + await ctx.WaitFor("the custom check to pass and leave the failed list", async token => + { + var passed = (await api.GetCustomChecks("pass", token)).Any(c => c.CustomCheckId == checkId); + var stillFailed = (await api.GetCustomChecks("fail", token)).Any(c => c.CustomCheckId == checkId); + return passed && !stillFailed ? PollResult.Done(true) : PollResult.Waiting($"passed list has it: {passed}, failed list has it: {stillFailed}"); + }, ct); + + ctx.Detail = $"Custom check {checkId} was reported failed, then passed."; + } + + Task SendCustomCheck(string checkId, Guid hostId, string runId, bool failed, string? reason, CancellationToken ct) + { + var send = new SendOptions(); + send.SetDestination(options.Value.ServiceControlInputQueue); + return session.Send(new ReportCustomCheckResult + { + HostId = hostId, + CustomCheckId = checkId, + Category = "Smoke", + HasFailed = failed, + FailureReason = reason, + ReportedAt = DateTime.UtcNow, + EndpointName = $"TestingTool.Smoke.{runId}", + Host = "TestingTool.Smoke" + }, send, ct); + } + + async Task HeartbeatBeatingThenDead(SmokeContext ctx, CancellationToken ct) + { + var name = $"TestingTool.Smoke.{ctx.RunId}"; + DeleteEndpointRecords(ctx, name); + + var endpoint = await StartEndpoint(ctx, name, config => config.SendHeartbeatTo(options.Value.ServiceControlInputQueue), ct); + await ctx.WaitFor("the endpoint to report beating", token => EndpointStatus(name, "beating", token), ct); + var beating = DateTime.UtcNow; + + await endpoint.StopAsync(ct); + await ctx.WaitFor("the endpoint to report dead after it stopped", token => EndpointStatus(name, "dead", token), ct, HeartbeatDeadTimeout); + + ctx.Detail = $"Endpoint {name} sent heartbeats with the NServiceBus.Heartbeat plugin, was reported beating, and was reported dead {(DateTime.UtcNow - beating).TotalSeconds:0}s after its host stopped."; + } + + /// Deletes the primary instance's records of exactly these endpoint names, and no others. It runs after the endpoint hosts stop. + public void DeleteEndpointRecords(SmokeContext ctx, params string[] names) => + ctx.OnCleanup(async token => + { + foreach (var view in (await api.GetEndpoints(token)).Where(e => names.Contains(e.Name))) + { + await api.DeleteEndpoint(view.Id, token); + } + }); + + /// Starts a run-scoped endpoint on the transport of the load endpoint. The cleanup stops it if the check did not. + async Task StartEndpoint(SmokeContext ctx, string name, Action? configure, CancellationToken ct) + { + var endpoint = await SmokeEndpoint.Start(name, config => NServiceBusEndpointExtensions.ConfigureTransport(config, configuration), configure, observations, options.Value.ErrorQueueName, ct); + ctx.OnEndpointStop(token => endpoint.StopAsync(token)); + return endpoint; + } + + async Task> EndpointStatus(string endpoint, string expected, CancellationToken ct) + { + var view = (await api.GetEndpoints(ct)).FirstOrDefault(e => e.Name == endpoint); + var status = view?.HeartbeatInformation?.ReportedStatus; + return view is { MonitorHeartbeat: true } && string.Equals(status, expected, StringComparison.OrdinalIgnoreCase) + ? PollResult.Done(true) + : PollResult.Waiting(view is null ? $"endpoint {endpoint} is not listed" : $"reported_status is '{status}', monitor_heartbeat is {view.MonitorHeartbeat}"); + } + + async Task AuditIngestionFulltext(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var token = Token("smokeaudit"); + var messageId = Guid.NewGuid().ToString(); + await SendSmoke(ctx, new SmokeMessage { RunId = ctx.RunId, Marker = messageId, Note = $"full text {token}" }, messageId, ct: ct); + + var audited = await ctx.WaitFor("the audited message to be found by search", async _ => + { + var result = await api.SearchMessages(token, ct); + var match = result.Value.FirstOrDefault(m => m.MessageId == messageId); + return match is not null ? PollResult.Done(match) : PollResult.Waiting(Describe(result, $"{result.Value.Count} results for '{token}', none with message id {messageId}")); + }, ct); + + if (!string.Equals(audited.Status, "successful", StringComparison.OrdinalIgnoreCase)) + { + throw new SmokeCheckFailedException($"The audited message has status '{audited.Status}', expected successful"); + } + + var body = await api.GetMessageBody(audited, ct); + if (!body.Contains(token, StringComparison.Ordinal)) + { + throw new SmokeCheckFailedException($"The stored body of audited message {audited.Id} does not contain '{token}'"); + } + + ctx.Detail = $"Message {messageId} was found by searching '{token}' and its body contains the word."; + } + + async Task FanOutConversation(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var conversationId = Guid.NewGuid().ToString(); + var rootId = Guid.NewGuid().ToString(); + var expected = (1 << (SmokeFanOutHandler.Levels + 1)) - 1; + await SendSmoke(ctx, new SmokeFanOutMessage(), rootId, send => send.SetHeader(Headers.ConversationId, conversationId), ct: ct); + + var messages = await ctx.WaitFor($"{expected} audited messages in the conversation", async _ => + { + var result = await api.GetConversation(conversationId, ct); + return result.Value.Count >= expected ? PollResult.Done(result.Value) : PollResult.Waiting>(Describe(result, $"{result.Value.Count} messages")); + }, ct); + + var ids = messages.Select(m => m.MessageId).ToHashSet(); + var parentOf = messages.ToDictionary(m => m.MessageId, m => m.Header(Headers.RelatedTo)); + var problems = new List(); + if (messages.Count != expected) + { + problems.Add($"expected {expected} messages, found {messages.Count}"); + } + + if (!parentOf.TryGetValue(rootId, out var rootParent) || rootParent is not null) + { + problems.Add("the root message is missing or has a parent"); + } + + problems.AddRange(parentOf.Where(p => p.Key != rootId && (p.Value is null || !ids.Contains(p.Value))).Select(p => $"message {p.Key} has RelatedTo '{p.Value}' that is not in the conversation")); + var rootChildren = parentOf.Count(p => p.Value == rootId); + if (rootChildren != 2) + { + problems.Add($"the root has {rootChildren} children, expected 2"); + } + + if (problems.Count > 0) + { + throw new SmokeCheckFailedException($"Conversation {conversationId} is wrong: {string.Join("; ", problems)}"); + } + + ctx.Detail = $"Conversation {conversationId} has {messages.Count} messages, each linked to its parent."; + } + + async Task SagaAudit(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var correlationId = Token("smokesaga"); + await session.Send(new SmokeSagaStart { CorrelationId = correlationId }, RouteHere(ctx.RunId), ct); + + var sagaId = await ctx.WaitFor("the audited saga start message with its saga id", async _ => + { + var result = await api.SearchMessages(correlationId, ct); + var saga = result.Value.Select(m => m.InvokedSagas?.FirstOrDefault()).FirstOrDefault(s => s is not null); + return saga is not null ? PollResult.Done(saga) : PollResult.Waiting(Describe(result, $"{result.Value.Count} results for '{correlationId}', none with an invoked saga")); + }, ct); + + var history = await ctx.WaitFor("three saga state changes", async _ => + { + var result = await api.GetSaga(sagaId.SagaId, ct); + var changes = result.Value?.Changes.Count ?? 0; + return changes >= 3 ? PollResult.Done(result.Value!) : PollResult.Waiting(Describe(result, $"{changes} changes")); + }, ct); + + var statuses = history.Changes.OrderBy(c => c.FinishTime).Select(c => c.Status.ToLowerInvariant()).ToArray(); + if (!statuses.SequenceEqual(["new", "updated", "completed"])) + { + throw new SmokeCheckFailedException($"Saga {sagaId.SagaId} has state changes [{string.Join(", ", statuses)}], expected [new, updated, completed]"); + } + + ctx.Detail = $"Saga {sagaId.SagaId} ({history.SagaType}) recorded new, updated and completed."; + } + + async Task MonitoringData(SmokeContext ctx, CancellationToken ct) + { + var name = $"TestingTool.Smoke.{ctx.RunId}"; + ctx.OnCleanup(async token => + { + // The instance ids are the ones monitoring reports for the endpoint, after the host stopped and reports no more. + var reported = (await monitoring.GetMonitoredEndpoints(token)).FirstOrDefault(e => e.Name == name); + foreach (var instanceId in reported?.EndpointInstanceIds ?? []) + { + await monitoring.DeleteInstance(name, instanceId, token); + } + }); + + var endpoint = await StartEndpoint(ctx, name, config => config.EnableMetrics().SendMetricDataToServiceControl(options.Value.MonitoringQueueName, TimeSpan.FromSeconds(2)), ct); + for (var i = 0; i < 3; i++) + { + await SendSmoke(ctx, new SmokeMessage { RunId = ctx.RunId, Marker = $"{ctx.RunId}-monitoring-{i}", Note = "monitoring", DelayMilliseconds = 100 }, destination: endpoint.MainAddress, ct: ct); + } + + var average = await ctx.WaitFor("monitoring to report processing time for the endpoint", async token => + { + var found = (await monitoring.GetMonitoredEndpoints(token)).FirstOrDefault(e => e.Name == name); + var value = found?.Metrics.FirstOrDefault(m => string.Equals(m.Key, "processingTime", StringComparison.OrdinalIgnoreCase)).Value?.Average; + return value > 0 ? PollResult.Done(value.Value) : PollResult.Waiting(found is null ? $"endpoint {name} is not listed" : "processingTime has no average yet"); + }, ct); + + ctx.Detail = $"Endpoint {name} reported an average processing time of {average:0.#} ms with the NServiceBus.Metrics.ServiceControl plugin."; + } + + async Task IntegrationEvent(SmokeContext ctx, CancellationToken ct) + { + await session.Subscribe(ct); + ctx.OnCleanup(token => session.Unsubscribe(token)); + + var failures = await FailMessages(ctx, "event", 1, ct: ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + var eventFailedId = await ctx.WaitFor( + "the MessageFailed event (the instance that ingests errors needs SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true)", + _ => Task.FromResult(observations.FindFailureEvent(failures.MessageIds[0]) is { } id ? PollResult.Done(id) : PollResult.Waiting($"no event for message id {failures.MessageIds[0]}")), + ct); + + if (eventFailedId != failed.Id) + { + throw new SmokeCheckFailedException($"The MessageFailed event carries failed message id {eventFailedId}, the API lists {failed.Id}"); + } + + ctx.Detail = $"MessageFailed was received for failed message {failed.Id}."; + } + + async Task RetrySingle(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "retry-single", 2, ct: ct); + var group = await WaitForFailures(ctx, failures, ct); + failures.Markers.ToList().ForEach(observations.Release); + + var retried = group.Messages[0]; + var untouched = group.Messages[1]; + await api.RetryMessage(retried.Id, ct); + await WaitUntilRetried(ctx, retried, failures.MarkerOf(retried), ct); + + var other = await api.FindFailedMessage(untouched.Id, ct); + if (!string.Equals(other?.Status, "unresolved", StringComparison.OrdinalIgnoreCase) || observations.FindHandled(failures.MarkerOf(untouched)) is not null) + { + throw new SmokeCheckFailedException($"Retrying one message also acted on its sibling {untouched.Id}: status '{other?.Status}'"); + } + + ctx.Detail = $"Message {retried.Id} was handled and resolved. Its sibling {untouched.Id} stayed unresolved."; + } + + async Task RetryGroup(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "retry-group", 3, ct: ct); + var group = await WaitForFailures(ctx, failures, ct); + failures.Markers.ToList().ForEach(observations.Release); + + await api.RetryGroup(group.GroupId, ct); + foreach (var message in group.Messages) + { + await WaitUntilRetried(ctx, message, failures.MarkerOf(message), ct); + } + + ctx.Detail = $"All {group.Messages.Count} messages of group {group.GroupId} were handled and resolved."; + } + + async Task EditAndRetry(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "edit", 1, ct: ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + var detail = await api.FindFailedMessage(failed.Id, ct) ?? throw new SmokeCheckFailedException($"Failed message {failed.Id} disappeared"); + + var token = Token("smokeedit"); + var editedMarker = $"{failures.MarkerOf(failed)}-edited"; + var body = JsonSerializer.Serialize(new SmokeMessage { RunId = ctx.RunId, Marker = editedMarker, Note = $"edited {token}", Fail = false }); + var accepted = await api.EditMessage(failed.Id, body, new Dictionary(detail.ProcessingAttempts[^1].Headers), ct); + if (!accepted) + { + throw new SmokeCheckFailedException($"ServiceControl ignored the edit of {failed.Id} (edit_ignored)"); + } + + var handled = await ctx.WaitFor("the edited message to be handled", _ => + Task.FromResult(observations.FindHandled(editedMarker) is { } h ? PollResult.Done(h) : PollResult.Waiting("the edited message has not arrived")), ct); + + if (handled.EditOf != failed.Id || !handled.Note.Contains(token, StringComparison.Ordinal)) + { + throw new SmokeCheckFailedException($"The edited message arrived with EditOf '{handled.EditOf}' and note '{handled.Note}', expected EditOf {failed.Id} and the edited text"); + } + + ctx.Detail = $"The edited body of {failed.Id} arrived with ServiceControl.EditOf and the edited text, and no longer failed."; + } + + async Task RetryThroughRedirect(SmokeContext ctx, CancellationToken ct) + { + var sourceName = $"TestingTool.Smoke.{ctx.RunId}.Source"; + var targetName = $"TestingTool.Smoke.{ctx.RunId}.Target"; + // The failure that Source reports makes ServiceControl save an endpoint record for it. + DeleteEndpointRecords(ctx, sourceName, targetName); + var source = await StartEndpoint(ctx, sourceName, null, ct); + var target = await StartEndpoint(ctx, targetName, null, ct); + var from = source.MainAddress; + var to = target.MainAddress; + + var failures = await FailMessages(ctx, "redirect", 1, source.MainAddress, ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + if (failed.QueueAddress != from) + { + throw new SmokeCheckFailedException($"The failed message has queue '{failed.QueueAddress}', expected the source address '{from}'"); + } + + var marker = failures.MarkerOf(failed); + observations.Release(marker); + + ctx.OnCleanup(async token => + { + foreach (var redirect in (await api.GetRedirects(token)).Where(r => r.FromPhysicalAddress == from)) + { + await api.DeleteRedirect(redirect.MessageRedirectId, token); + } + }); + + await api.CreateRedirect(from, to, ct); + var listed = await ctx.WaitFor("the redirect to be listed", async token => + { + var found = (await api.GetRedirects(token)).FirstOrDefault(r => r.FromPhysicalAddress == from && r.ToPhysicalAddress == to); + return found is not null ? PollResult.Done(found) : PollResult.Waiting($"no redirect from {from} to {to}"); + }, ct); + + await api.RetryMessage(failed.Id, ct); + await WaitUntilRetried(ctx, failed, marker, ct); + RequireHandledBy(observations.FindHandled(marker), target.Name, source.Name); + + await api.DeleteRedirect(listed.MessageRedirectId, ct); + var remaining = (await api.GetRedirects(ct)).Count(r => r.FromPhysicalAddress == from); + if (remaining != 0) + { + throw new SmokeCheckFailedException($"The redirect from {from} is still listed after DELETE"); + } + + ctx.Detail = $"A message that failed in {source.Name} ({from}) was retried through a redirect to {target.Name} ({to}), handled there and resolved. The redirect was removed."; + } + + /// A retry that the source handled itself means the redirect did nothing, so only the target passes. + public static void RequireHandledBy(SmokeObservations.HandledMessage? handled, string target, string source) + { + if (handled?.Endpoint != target) + { + throw new SmokeCheckFailedException($"The retried message was handled by '{handled?.Endpoint ?? "no endpoint"}', expected the redirect target '{target}' and not the source '{source}'"); + } + } + + // --- Shared steps --- + + sealed record Failures(string RunId, string ExceptionType, IReadOnlyList MessageIds, IReadOnlyList Markers) + { + public string MarkerOf(FailedMessageView view) => Markers[MessageIds.ToList().IndexOf(view.MessageId)]; + } + + sealed record FailureGroup(string GroupId, IReadOnlyList Messages); + + /// + /// Sends failing messages that ServiceControl groups under an exception type unique to this check of + /// this run. The group therefore holds only these messages, so a group retry cannot touch anything else. + /// + async Task FailMessages(SmokeContext ctx, string checkId, int count, string? destination = null, CancellationToken ct = default) + { + var exceptionType = $"TestingTool.Smoke.Failure_{ctx.RunId}_{checkId}".Replace('-', '_'); + var messageIds = new List(); + var markers = new List(); + var failures = new Failures(ctx.RunId, exceptionType, messageIds, markers); + ctx.OnCleanup(token => ArchiveLeftovers(failures, token)); + + for (var i = 0; i < count; i++) + { + var messageId = Guid.NewGuid().ToString(); + var marker = $"{ctx.RunId}-{checkId}-{i}"; + messageIds.Add(messageId); + markers.Add(marker); + await SendSmoke(ctx, new SmokeMessage + { + RunId = ctx.RunId, + Marker = marker, + Fail = true, + Note = checkId, + FailureType = exceptionType + }, messageId, destination: destination, ct: ct); + } + + return failures; + } + + async Task WaitForFailures(SmokeContext ctx, Failures failures, CancellationToken ct) + { + var expected = failures.MessageIds.Count; + return await ctx.WaitFor($"{expected} failed message(s) in the group for {failures.ExceptionType}", async token => + { + var group = (await api.GetGroups(token)).FirstOrDefault(g => g.Title.StartsWith(failures.ExceptionType + ":", StringComparison.Ordinal)); + if (group is null) + { + return PollResult.Waiting("the group does not exist yet"); + } + + var mine = (await api.GetGroupErrors(group.Id, token)).Where(m => failures.MessageIds.Contains(m.MessageId)).ToList(); + return mine.Count == expected && mine.All(m => string.Equals(m.Status, "unresolved", StringComparison.OrdinalIgnoreCase)) + ? PollResult.Done(new FailureGroup(group.Id, mine)) + : PollResult.Waiting($"group {group.Id} lists {mine.Count} of the run's messages: [{string.Join(", ", mine.Select(m => m.Status))}]"); + }, ct); + } + + Task WaitUntilRetried(SmokeContext ctx, FailedMessageView message, string marker, CancellationToken ct) => + ctx.WaitFor($"failed message {message.Id} to be handled and resolved", async token => + { + var handled = observations.FindHandled(marker) is not null; + var detail = await api.FindFailedMessage(message.Id, token); + return handled && string.Equals(detail?.Status, "resolved", StringComparison.OrdinalIgnoreCase) + ? PollResult.Done(true) + : PollResult.Waiting($"handled by the endpoint: {handled}, status: {detail?.Status}"); + }, ct); + + async Task ArchiveLeftovers(Failures failures, CancellationToken ct) + { + var group = (await api.GetGroups(ct)).FirstOrDefault(g => g.Title.StartsWith(failures.ExceptionType + ":", StringComparison.Ordinal)); + if (group is null) + { + return; + } + + var leftovers = (await api.GetGroupErrors(group.Id, ct)) + .Where(m => failures.MessageIds.Contains(m.MessageId) && string.Equals(m.Status, "unresolved", StringComparison.OrdinalIgnoreCase)) + .Select(m => m.Id) + .ToList(); + if (leftovers.Count > 0) + { + await api.ArchiveMessages(leftovers, ct); + } + } + + async Task RequireAuditInstance(CancellationToken ct) + { + var remotes = await api.GetRemotes(ct); + if (remotes.Count == 0) + { + throw new SmokeCheckFailedException("The primary instance has no remote audit instance, so it cannot return audit data. Start the AppHost with --audit-instances 1."); + } + + var offline = remotes.Where(r => !string.Equals(r.Status, "online", StringComparison.OrdinalIgnoreCase)).ToList(); + if (offline.Count > 0) + { + throw new SmokeCheckFailedException($"Remote instance(s) not online: {string.Join(", ", offline.Select(r => $"{r.ApiUri} is {r.Status}"))}"); + } + } + + static string Describe(Audited result, string observed) => + result.Incomplete is null ? observed : $"{observed}; the primary reports incomplete results from {result.Incomplete}"; + + static string Token(string prefix) => prefix + Guid.NewGuid().ToString("N")[..10]; + + static SendOptions RouteHere(string runId) + { + var send = new SendOptions(); + send.RouteToThisEndpoint(); + send.SetHeader(SmokeHeaders.RunId, runId); + return send; + } + + Task SendSmoke(SmokeContext ctx, object message, string? messageId = null, Action? configure = null, string? destination = null, CancellationToken ct = default) + { + var send = RouteHere(ctx.RunId); + if (destination is not null) + { + send = new SendOptions(); + send.SetDestination(destination); + send.SetHeader(SmokeHeaders.RunId, ctx.RunId); + } + + if (messageId is not null) + { + send.SetMessageId(messageId); + } + + configure?.Invoke(send); + return session.Send(message, send, ct); + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs new file mode 100644 index 0000000000..1a7cc2523d --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NServiceBus; + +namespace TestingTool.Smoke; + +/// The name of the endpoint a handler runs in, so a check can prove which endpoint handled a message. +public sealed record SmokeEndpointIdentity(string Name); + +/// +/// A real NServiceBus endpoint that lives for one smoke check, in its own host next to the load endpoint. +/// Stopping it releases its connections and stops its plugins. The queues or tables it created stay in +/// the transport. +/// +public sealed class SmokeEndpoint : IAsyncDisposable +{ + IHost? host; + + SmokeEndpoint(IHost host, string name, string mainAddress) + { + this.host = host; + Name = name; + MainAddress = mainAddress; + Session = host.Services.GetRequiredService(); + } + + public string Name { get; } + + /// The input address the transport reports, for example with the schema and catalog of SQL Server. + public string MainAddress { get; } + + public IMessageSession Session { get; } + + /// Production passes so the endpoint uses the transport of the load endpoint. + public static async Task Start( + string name, + Action configureTransport, + Action? configure, + SmokeObservations observations, + string errorQueue, + CancellationToken ct) + { + var config = new EndpointConfiguration(name); + config.AssemblyScanner().Disable = true; + config.AddHandler(); + config.UseSerialization(); + config.SendFailedMessagesTo(errorQueue); + var recoverability = config.Recoverability(); + recoverability.Immediate(immediate => immediate.NumberOfRetries(0)); + recoverability.Delayed(delayed => delayed.NumberOfRetries(0)); + recoverability.Failed(failed => failed.HeaderCustomization(SmokeHeaders.CustomizeFailure)); + config.EnableInstallers(); + configureTransport(config); + configure?.Invoke(config); + + var builder = Host.CreateApplicationBuilder(); + builder.Logging.SetMinimumLevel(LogLevel.Critical); + builder.Services.AddSingleton(observations); + builder.Services.AddSingleton(new SmokeEndpointIdentity(name)); + builder.Services.AddNServiceBusEndpoint(config); + + var host = builder.Build(); + try + { + await host.StartAsync(ct); + return new SmokeEndpoint(host, name, host.Services.GetRequiredService().MainReceiveAddress); + } + catch (Exception ex) + { + await StopPartiallyStarted(host); + if (ex is OperationCanceledException) + { + throw; + } + + throw new SmokeCheckFailedException($"Endpoint {name} could not start: {ex.Message}"); + } + } + + /// + /// A host whose start failed or was canceled may have started some of its services, so it is stopped + /// before it is disposed. The stop is bounded, and its own failure never replaces the startup error. + /// + static async Task StopPartiallyStarted(IHost host) + { + try + { + using var limit = new CancellationTokenSource(PartialStartStopTimeout); + await host.StopAsync(limit.Token); + } + catch + { + // The startup error is the one to report. + } + finally + { + host.Dispose(); + } + } + + static readonly TimeSpan PartialStartStopTimeout = TimeSpan.FromSeconds(10); + + /// Stops and disposes the host. Calling it again does nothing. + public async Task StopAsync(CancellationToken ct) + { + var current = Interlocked.Exchange(ref host, null); + if (current is null) + { + return; + } + + try + { + await current.StopAsync(ct); + } + finally + { + current.Dispose(); + } + } + + public async ValueTask DisposeAsync() => await StopAsync(CancellationToken.None); +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs b/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs new file mode 100644 index 0000000000..ad92dfc383 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs @@ -0,0 +1,193 @@ +using System.Collections.Concurrent; +using NServiceBus; + +namespace TestingTool.Smoke; + +/// +/// The message every smoke check sends. is decided by the sender, so a retry or an +/// edit that clears it recovers the message, which the hash-based load scenarios cannot do. +/// +public sealed class SmokeMessage +{ + public string RunId { get; set; } = ""; + + /// Unique per message. lets a failing message succeed on its next attempt. + public string Marker { get; set; } = ""; + + public string Note { get; set; } = ""; + + public bool Fail { get; set; } + + /// The exception type ServiceControl groups the failure under. It makes the group unique to one check of one run. + public string FailureType { get; set; } = ""; + + /// Time the handler waits before it finishes, so the processing time that metrics report is above zero. + public int DelayMilliseconds { get; set; } +} + +public sealed class SmokeFanOutMessage +{ + public int Level { get; set; } +} + +public sealed class SmokeSagaStart +{ + public string CorrelationId { get; set; } = ""; +} + +public sealed class SmokeSagaStep +{ + public string CorrelationId { get; set; } = ""; +} + +public sealed class SmokeSagaFinish +{ + public string CorrelationId { get; set; } = ""; +} + +/// +/// The failure of a . NServiceBus offers headers customization only on the fault +/// headers, not on the message headers, so the exception message carries what needs. +/// +public sealed class SmokeFailureException(string marker, string failureType) + : Exception($"Smoke message {marker} was told to fail{Separator}{failureType}") +{ + const string Separator = "|"; + + public static bool TryDecode(string exceptionMessage, out string failureType) + { + var parts = exceptionMessage.Split(Separator); + var isSmokeFailure = parts.Length == 2 && parts[0].StartsWith("Smoke message ", StringComparison.Ordinal); + failureType = isSmokeFailure ? parts[1] : ""; + return isSmokeFailure; + } +} + +public static class SmokeHeaders +{ + public const string RunId = "TestingTool.Smoke.RunId"; + + public const string EditOf = "ServiceControl.EditOf"; + + /// Rewrites the exception type in the fault headers of smoke messages, so ServiceControl groups each check separately. + public static void CustomizeFailure(Dictionary faultHeaders) + { + if (faultHeaders.TryGetValue("NServiceBus.ExceptionInfo.Message", out var message) && SmokeFailureException.TryDecode(message, out var failureType)) + { + faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"] = failureType; + } + } +} + +/// What the smoke handlers saw, keyed by message marker or message id. Entries are tiny and live as long as the process. +public sealed class SmokeObservations +{ + readonly ConcurrentDictionary released = new(); + readonly ConcurrentDictionary handled = new(); + readonly ConcurrentDictionary failureEvents = new(); + + public void Release(string marker) => released[marker] = 0; + + public bool IsReleased(string marker) => released.ContainsKey(marker); + + public void RecordHandled(string marker, string? editOf, string note, string endpoint) => handled[marker] = new HandledMessage(editOf, note, endpoint); + + public HandledMessage? FindHandled(string marker) => handled.GetValueOrDefault(marker); + + public void RecordFailureEvent(string messageId, string failedMessageId) => failureEvents[messageId] = failedMessageId; + + /// The failed message id carried by the MessageFailed event for this message id, or null if none arrived. + public string? FindFailureEvent(string messageId) => failureEvents.GetValueOrDefault(messageId); + + public sealed record HandledMessage(string? EditOf, string Note, string Endpoint); +} + +public sealed class SmokeMessageHandler(SmokeObservations observations, SmokeEndpointIdentity identity) : IHandleMessages +{ + public async Task Handle(SmokeMessage message, IMessageHandlerContext context) + { + if (message.DelayMilliseconds > 0) + { + await Task.Delay(message.DelayMilliseconds, context.CancellationToken); + } + + Process(observations, message, context.MessageHeaders.GetValueOrDefault(SmokeHeaders.EditOf), identity.Name); + } + + public static void Process(SmokeObservations observations, SmokeMessage message, string? editOf, string endpoint) + { + if (message.Fail && !observations.IsReleased(message.Marker)) + { + Fail(message); + } + + observations.RecordHandled(message.Marker, editOf, message.Note, endpoint); + } + + // A dedicated method so the first stack frame ServiceControl groups on never matches the load scenarios. + static void Fail(SmokeMessage message) => + throw new SmokeFailureException(message.Marker, message.FailureType); +} + +/// Sends two children per level, so the audit data holds a conversation tree with parent links. +public sealed class SmokeFanOutHandler : IHandleMessages +{ + public const int Levels = 2; + + public async Task Handle(SmokeFanOutMessage message, IMessageHandlerContext context) + { + if (message.Level >= Levels) + { + return; + } + + for (var i = 0; i < 2; i++) + { + await context.SendLocal(new SmokeFanOutMessage { Level = message.Level + 1 }); + } + } +} + +public sealed class SmokeSaga : Saga, + IAmStartedByMessages, + IHandleMessages, + IHandleMessages +{ + protected override void ConfigureHowToFindSaga(SagaPropertyMapper mapper) => + mapper.MapSaga(saga => saga.CorrelationId) + .ToMessage(m => m.CorrelationId) + .ToMessage(m => m.CorrelationId) + .ToMessage(m => m.CorrelationId); + + // Each step sends the next one to itself, so the three state changes happen strictly in order. + public Task Handle(SmokeSagaStart message, IMessageHandlerContext context) => + context.SendLocal(new SmokeSagaStep { CorrelationId = message.CorrelationId }); + + public Task Handle(SmokeSagaStep message, IMessageHandlerContext context) => + context.SendLocal(new SmokeSagaFinish { CorrelationId = message.CorrelationId }); + + public Task Handle(SmokeSagaFinish message, IMessageHandlerContext context) + { + MarkAsComplete(); + return Task.CompletedTask; + } +} + +public sealed class SmokeSagaData : ContainSagaData +{ + public string CorrelationId { get; set; } = ""; +} + +/// Records the MessageFailed integration events that ServiceControl publishes to this endpoint. +public sealed class MessageFailedEventHandler(SmokeObservations observations) : IHandleMessages +{ + public Task Handle(ServiceControl.Contracts.MessageFailed message, IMessageHandlerContext context) + { + if (message.MessageDetails?.Headers?.TryGetValue(SmokeHeaders.RunId, out _) == true) + { + observations.RecordFailureEvent(message.MessageDetails.MessageId, message.FailedMessageId); + } + + return Task.CompletedTask; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs b/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs new file mode 100644 index 0000000000..79c270b9bd --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs @@ -0,0 +1,232 @@ +using Microsoft.Extensions.Logging; +using TestingTool.Contracts; + +namespace TestingTool.Smoke; + +/// +/// Runs the smoke checklist once at a time, sequentially. A failed check does not stop later checks. +/// The state of the current or last run stays in memory so the UI can reload and show it. +/// +public sealed class SmokeRunner( + IReadOnlyList checks, + Func findStartConflict, + TimeSpan defaultCheckTimeout, + TimeSpan cleanupTimeout, + TimeSpan pollInterval, + TimeSpan pollTimeout, + ILogger logger) +{ + readonly Lock gate = new(); + readonly CheckState[] states = [.. checks.Select(c => new CheckState(c))]; + RunState? run; + + public bool TryStart(out string? error) + { + lock (gate) + { + if (run is { FinishedAt: null }) + { + error = "A smoke run is already in progress"; + return false; + } + + if (findStartConflict() is { } conflict) + { + error = conflict; + return false; + } + + foreach (var state in states) + { + state.Reset(); + } + + var current = new RunState($"smoke-{Guid.NewGuid():N}"[..14]); + run = current; + current.Completion = Task.Run(() => ExecuteAsync(current)); + } + + error = null; + return true; + } + + public void Stop() + { + lock (gate) + { + if (run is { FinishedAt: null } current) + { + current.Cancellation.Cancel(); + } + } + } + + /// Completes when the current run, if any, has finished and cleaned up. + public Task WaitForCompletionAsync() + { + lock (gate) + { + return run?.Completion ?? Task.CompletedTask; + } + } + + public SmokeRunInfo GetSnapshot() + { + lock (gate) + { + return new SmokeRunInfo + { + RunId = run?.RunId, + Running = run is { FinishedAt: null }, + StartedAt = run?.StartedAt.ToString("O"), + FinishedAt = run?.FinishedAt?.ToString("O"), + Checks = [.. states.Select(s => s.ToInfo())] + }; + } + } + + async Task ExecuteAsync(RunState current) + { + try + { + foreach (var state in states.Where(s => !s.Check.IsManual)) + { + if (current.Cancellation.IsCancellationRequested) + { + Update(state, SmokeCheckStatus.Canceled, "The run was stopped before this check started"); + continue; + } + + await RunCheckAsync(current, state); + } + } + finally + { + lock (gate) + { + current.FinishedAt = DateTimeOffset.UtcNow; + } + + current.Cancellation.Dispose(); + } + } + + async Task RunCheckAsync(RunState current, CheckState state) + { + Update(state, SmokeCheckStatus.Running, null); + var started = DateTimeOffset.UtcNow; + var context = new SmokeContext(current.RunId, pollInterval, pollTimeout); + var timeout = state.Check.Timeout ?? defaultCheckTimeout; + string? cleanupProblem = null; + + SmokeCheckStatus status; + string? detail; + try + { + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(current.Cancellation.Token); + timeoutSource.CancelAfter(timeout); + try + { + await state.Check.Run!(context, timeoutSource.Token); + (status, detail) = (SmokeCheckStatus.Passed, context.Detail); + } + catch (OperationCanceledException) when (current.Cancellation.IsCancellationRequested) + { + (status, detail) = (SmokeCheckStatus.Canceled, "The run was stopped while this check was running"); + } + catch (OperationCanceledException) when (timeoutSource.IsCancellationRequested) + { + (status, detail) = (SmokeCheckStatus.Failed, $"The check did not finish within {timeout.TotalSeconds:0.#}s"); + } + } + catch (SmokeCheckFailedException ex) + { + (status, detail) = (SmokeCheckStatus.Failed, ex.Message); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Smoke check {Check} failed with an unexpected error", state.Check.Id); + (status, detail) = (SmokeCheckStatus.Failed, $"{ex.GetType().Name}: {ex.Message}"); + } + finally + { + cleanupProblem = await RunCleanupsAsync(context); + } + + if (cleanupProblem is not null) + { + detail = string.IsNullOrEmpty(detail) ? cleanupProblem : $"{detail} {cleanupProblem}"; + } + + Update(state, status, detail, DateTimeOffset.UtcNow - started); + } + + async Task RunCleanupsAsync(SmokeContext context) + { + var failures = new List(); + await RunAll(context.EndpointStops, failures); + await RunAll(context.Cleanups, failures); + return failures.Count == 0 ? null : $"Cleanup failed, leftover data may remain: {string.Join("; ", failures)}"; + } + + // Every action runs in reverse order of registration with the token of one shared time limit, and is awaited to the end. + async Task RunAll(IReadOnlyList> actions, List failures) + { + using var limit = new CancellationTokenSource(cleanupTimeout); + foreach (var action in actions.Reverse()) + { + try + { + await action(limit.Token); + } + catch (OperationCanceledException) when (limit.IsCancellationRequested) + { + failures.Add($"timed out after {cleanupTimeout.TotalSeconds:0.#}s"); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Smoke cleanup failed"); + failures.Add(ex.Message); + } + } + } + + void Update(CheckState state, SmokeCheckStatus status, string? detail, TimeSpan? duration = null) + { + lock (gate) + { + state.Status = status; + state.Detail = detail; + state.Duration = duration; + } + } + + sealed class RunState(string runId) + { + public string RunId { get; } = runId; + public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; + public DateTimeOffset? FinishedAt { get; set; } + public CancellationTokenSource Cancellation { get; } = new(); + public Task Completion { get; set; } = Task.CompletedTask; + } + + sealed class CheckState(SmokeCheck check) + { + public SmokeCheck Check { get; } = check; + public SmokeCheckStatus Status { get; set; } = check.IsManual ? SmokeCheckStatus.Manual : SmokeCheckStatus.Pending; + public string? Detail { get; set; } + public TimeSpan? Duration { get; set; } + + public void Reset() => (Status, Detail, Duration) = (Check.IsManual ? SmokeCheckStatus.Manual : SmokeCheckStatus.Pending, null, null); + + public SmokeCheckInfo ToInfo() => new() + { + Id = Check.Id, + Title = Check.Title, + Description = Check.Description, + Status = Status, + Detail = Detail, + DurationSeconds = Duration is { } d ? Math.Round(d.TotalSeconds, 1) : null + }; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs b/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs new file mode 100644 index 0000000000..d51e203c7c --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs @@ -0,0 +1,21 @@ +namespace TestingTool.Smoke; + +/// Stops a running smoke run on shutdown and waits for its cleanup to finish. +public sealed class SmokeRunnerLifecycle(SmokeRunner runner) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public async Task StopAsync(CancellationToken cancellationToken) + { + runner.Stop(); + await runner.WaitForCompletionAsync().WaitAsync(cancellationToken); + } +} + +/// The jobs that act on every failed message group, so they must not run together with a smoke run. +public static class SmokeJobConflicts +{ + static readonly HashSet Names = new(["retry", "archive", "retention-sweep"], StringComparer.OrdinalIgnoreCase); + + public static bool Conflicts(string jobName) => Names.Contains(jobName); +} diff --git a/tools/testing-tool/TestingTool/TestingTool.csproj b/tools/testing-tool/TestingTool/TestingTool.csproj index aaa8de3952..2002b20620 100644 --- a/tools/testing-tool/TestingTool/TestingTool.csproj +++ b/tools/testing-tool/TestingTool/TestingTool.csproj @@ -17,8 +17,10 @@ + + diff --git a/tools/testing-tool/TestingTool/TestingToolOptions.cs b/tools/testing-tool/TestingTool/TestingToolOptions.cs index 18402e953b..2f0574e67a 100644 --- a/tools/testing-tool/TestingTool/TestingToolOptions.cs +++ b/tools/testing-tool/TestingTool/TestingToolOptions.cs @@ -81,4 +81,16 @@ public sealed class TestingToolOptions /// ServiceControl monitoring instance input queue that endpoint metrics are sent to. public string MonitoringQueueName { get; set; } = "Particular.Monitoring"; -} \ No newline at end of file + + /// Base URL of the ServiceControl.Monitoring instance (e.g. http://monitoring:33633). Only the smoke tests use it. + public string MonitoringApiUrl { get; set; } = "http://localhost:33633"; + + /// Interval between polls of a ServiceControl API while a smoke check waits for an effect. + public TimeSpan SmokePollInterval { get; set; } = TimeSpan.FromSeconds(1); + + /// How long a smoke check waits for one effect before it fails. + public TimeSpan SmokePollTimeout { get; set; } = TimeSpan.FromSeconds(60); + + /// How long one smoke check may run in total, including all of its waits. + public TimeSpan SmokeCheckTimeout { get; set; } = TimeSpan.FromMinutes(3); +} diff --git a/tools/testing-tool/TestingTool/wwwroot/index.html b/tools/testing-tool/TestingTool/wwwroot/index.html index 4afb60252e..dff3c2dd90 100644 --- a/tools/testing-tool/TestingTool/wwwroot/index.html +++ b/tools/testing-tool/TestingTool/wwwroot/index.html @@ -88,6 +88,13 @@ .tab { padding: .5rem 1rem; border: none; background: none; color: var(--muted); cursor: pointer; font-size: .95rem; border-bottom: 2px solid transparent; margin-bottom: -1px; transition: color .15s, border-color .15s; } .tab.active { color: var(--text); border-bottom-color: var(--accent); } .tab:hover { color: var(--text); } + .smoke-row { background: var(--surface); border: 1px solid var(--border); border-left: 3px solid var(--border); border-radius: var(--radius); padding: .6rem .9rem; margin-bottom: .5rem; } + .smoke-row .head { display: flex; justify-content: space-between; gap: 1rem; font-weight: 600; } + .smoke-row .desc, .smoke-row .detail { color: var(--muted); font-size: .85rem; margin-top: .2rem; } + .smoke-row.passed { border-left-color: var(--ok); } .smoke-row.passed .status { color: var(--ok); } + .smoke-row.failed { border-left-color: var(--err); } .smoke-row.failed .status, .smoke-row.failed .detail { color: var(--err); } + .smoke-row.running { border-left-color: var(--warn); } .smoke-row.running .status { color: var(--warn); } + .smoke-row.manual { border-left-style: dashed; } .tab-panel { display: none; } .tab-panel.active { display: block; } .btn { padding: .4rem .9rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface-2); color: var(--text); cursor: pointer; font-size: .85rem; transition: opacity .15s; } @@ -195,6 +202,7 @@

🎯 ServiceControl Testing Tool

+ @@ -288,6 +296,24 @@

Direct Audit-Queue Writer

+ +
+ +
+

Smoke tests

+ + + + +
+
+ Sends its own messages with a run-specific identifier and checks the effects through the ServiceControl APIs. Run it against a test instance only: it creates failed messages, custom checks, endpoints and a redirect. Cleanup removes temporary check, endpoint and redirect records, and archives unresolved failures; message data remains subject to ServiceControl retention. Rows marked manual are not automated. +
+
+
Loading checks…
+ +
+