From 42936c2a328d147f6f4bde8b125ceaf2f7bbef74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Wed, 4 Nov 2026 19:57:08 +0100 Subject: [PATCH 1/6] Add the Google Cloud Pub/Sub transport --- .github/workflows/ci.yml | 33 ++++++++++++- README.md | 1 + docs/README.md | 1 + docs/google-pubsub-transport.md | 37 +++++++++++++++ docs/testing.md | 15 ++++++ docs/usage-report.md | 3 ++ src/Directory.Packages.props | 4 ++ src/ProjectReferences.Transports.props | 1 + src/ServiceControl.Audit/App.config | 4 ++ src/ServiceControl.Monitoring/App.config | 4 ++ .../ConnectionStringTests.cs | 47 +++++++++++++++++++ .../EnvironmentDataTests.cs | 32 +++++++++++++ ...ntrol.Transports.GooglePubSub.Tests.csproj | 34 ++++++++++++++ .../ServiceControlAuditEndpointTests.cs | 6 +++ .../ServiceControlMonitoringEndpointTests.cs | 6 +++ .../ServiceControlPrimaryEndpointTests.cs | 6 +++ .../TransportTestsConfiguration.cs | 32 +++++++++++++ .../GooglePubSubConnectionString.cs | 36 ++++++++++++++ .../GooglePubSubTransportCustomization.cs | 44 +++++++++++++++++ .../NoOpQueueLengthProvider.cs | 15 ++++++ ...viceControl.Transports.GooglePubSub.csproj | 29 ++++++++++++ .../transport.manifest | 15 ++++++ ...s_exist_in_specified_assembly.approved.txt | 1 + .../DevelopmentTransportLocations.cs | 1 + src/ServiceControl.slnx | 2 + src/ServiceControl/App.config | 4 ++ .../APIApprovals.TransportNames.approved.txt | 5 ++ .../DeploymentPackageTests.cs | 3 +- 28 files changed, 419 insertions(+), 2 deletions(-) create mode 100644 docs/google-pubsub-transport.md create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/EnvironmentDataTests.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControl.Transports.GooglePubSub.Tests.csproj create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlAuditEndpointTests.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlMonitoringEndpointTests.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlPrimaryEndpointTests.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/TransportTestsConfiguration.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub/NoOpQueueLengthProvider.cs create mode 100644 src/ServiceControl.Transports.GooglePubSub/ServiceControl.Transports.GooglePubSub.csproj create mode 100644 src/ServiceControl.Transports.GooglePubSub/transport.manifest diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b276a4134..c923b69845 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,13 +25,17 @@ jobs: # The slowest healthy job finishes in under 18 minutes. Anything still running at 30 has lost its # runner or hung on infrastructure, and without a cap it would occupy the runner for 6 hours. timeout-minutes: 30 + permissions: + contents: read + # Google Cloud workload identity federation for the GooglePubSub category + id-token: write strategy: matrix: os: [windows-latest, ubuntu-latest] # Categories are declared by the property in each test project. A category can # span several projects that share infrastructure, so that the container is provisioned once # and the union of their build closures is compiled once. - test-category: [ DefaultCore, DefaultMonitoring, Raven, SqlServer, PostgreSql, RabbitMQ, AzureServiceBus, AzureStorageQueues, MSMQ, SQS, IBMMQ ] + test-category: [ DefaultCore, DefaultMonitoring, Raven, SqlServer, PostgreSql, RabbitMQ, AzureServiceBus, AzureStorageQueues, MSMQ, SQS, IBMMQ, GooglePubSub ] include: - os: windows-latest os-name: Windows @@ -185,6 +189,23 @@ jobs: tag: ServiceControl env: REGION_OVERRIDE: eastus + - name: Authenticate to Google Cloud + id: gcp-auth + if: matrix.test-category == 'GooglePubSub' + uses: google-github-actions/auth@v3.0.0 + with: + workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ vars.GCP_SERVICE_ACCOUNT }} + - name: Setup Google Cloud SDK + if: matrix.test-category == 'GooglePubSub' + uses: google-github-actions/setup-gcloud@v3.0.1 + - name: Setup Google Pub/Sub environment variables + if: matrix.test-category == 'GooglePubSub' + run: | + # The prefix keeps parallel runs apart and scopes the cleanup step to this run's topics and subscriptions + $prefix = "gha-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.os-name }}-" + echo "PUBSUB_TEST_PREFIX=$prefix" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf-8 -Append + echo "ServiceControl_TransportTests_GooglePubSub_ConnectionString=ProjectId=${{ vars.GOOGLE_CLOUD_PROJECT }};ResourceNamePrefix=$prefix" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf-8 -Append - name: Run tests uses: Particular/run-tests-action@v1.9.0 with: @@ -194,6 +215,16 @@ jobs: ServiceControl_TESTS_FILTER: ${{ matrix.test-category }} PARTICULARSOFTWARE_LICENSE: ${{ secrets.LICENSETEXT }} AZURE_ACI_CREDENTIALS: ${{ secrets.AZURE_ACI_CREDENTIALS }} + - name: Clean up Google Pub/Sub resources + if: always() && steps.gcp-auth.outcome == 'success' + run: | + $project = '${{ vars.GOOGLE_CLOUD_PROJECT }}' + $filter = "name:$Env:PUBSUB_TEST_PREFIX" + $subscriptions = @(gcloud pubsub subscriptions list --project=$project --filter=$filter --format="value(name.basename())" --verbosity=error) + if ($subscriptions.Count -gt 0) { gcloud pubsub subscriptions delete @subscriptions --project=$project --quiet --verbosity=error } + $topics = @(gcloud pubsub topics list --project=$project --filter=$filter --format="value(name.basename())" --verbosity=error) + if ($topics.Count -gt 0) { gcloud pubsub topics delete @topics --project=$project --quiet --verbosity=error } + Write-Host "Deleted $($subscriptions.Count) subscriptions and $($topics.Count) topics with prefix $Env:PUBSUB_TEST_PREFIX" compile: name: ${{ matrix.os-name }}-Compile diff --git a/README.md b/README.md index acde17004e..57074f2e48 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ Transports: - `AzureServiceBus` - `AzureStorageQueues` +- `GooglePubSub` - `IBMMQ` - `MSMQ` - `RabbitMQ` (all four classic/quorum and conventional/direct routing combinations) diff --git a/docs/README.md b/docs/README.md index 4c6ebc1521..b3a005ebbd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,7 @@ This section points to sources that explain why ServiceControl is designed the w - [Message body storage](message-body-storage.md) — where the Audit SQL Server and PostgreSQL persisters keep message bodies, how retention removes them, and which settings are optional - [Bulk retries design](bulk-retries-design.md) — how ServiceControl retries failed messages in bulk - [Retries over Azure Storage Queues transport](retries-asq-transport.md) — how retries behave with one or several storage accounts +- [Google Cloud Pub/Sub transport](google-pubsub-transport.md) — why credentials come only from Application Default Credentials, and which platform features the transport limits - [Data versioning design](data-versioning-design.md) — which invariant keeps a cached API response from going stale - [Event log design](eventlog-design.md) — what the event log is and what it records - [Multiple ServiceControl instances communication](multipleservicecontrolinstancescommunication.md) — how primary, audit, and monitoring instances talk to each other diff --git a/docs/google-pubsub-transport.md b/docs/google-pubsub-transport.md new file mode 100644 index 0000000000..67b1f55b9d --- /dev/null +++ b/docs/google-pubsub-transport.md @@ -0,0 +1,37 @@ +# Google Cloud Pub/Sub transport + +The primary, audit, and monitoring instances can run on the `NServiceBus.Transport.GooglePubSub` package. The transport maps each queue to a topic and a subscription with the same ID. This page covers how ServiceControl uses the transport and which platform features the transport limits. + +## Connection string + +The connection string accepts `ProjectId`, `ResourceNamePrefix`, and `ServiceEndpoint`, and each maps to the `GooglePubSubTransportOptions` property of the same name. All three are optional. The parser rejects any other key, so credentials cannot end up in the connection string or in the instance configuration. + +Without `ProjectId`, the transport reads the `GOOGLE_CLOUD_PROJECT` or `GCLOUD_PROJECT` environment variable, then the Google Cloud metadata server. When `PUBSUB_EMULATOR_HOST` is set, the transport connects to the Pub/Sub emulator. + +## Credentials + +ServiceControl uses Application Default Credentials (ADC) for every component. Error ingestion, audit ingestion, retries, and the throughput queue create their receivers through `TransportCustomization.CreateTransportInfrastructure`, which passes no service provider to the transport. Without a service provider, the transport uses ADC. A credential registered in dependency injection would reach only the NServiceBus endpoints. + +## Transaction mode + +The transport supports `None` and `ReceiveOnly`. The retry dequeuer requests `SendsAtomicWithReceive` and falls back to `ReceiveOnly`. Forwarding a retried message and acknowledging its staged copy are separate operations, so a failure between them makes ServiceControl forward the message again. + +## Delayed delivery + +The transport throws for delayed sends and saga timeouts, and it limits delayed retries to 600 seconds. ServiceControl sends no delayed messages and disables sagas. The primary and monitoring instances set delayed retries to zero, which passes the transport's startup check. The audit instance is send-only, so the transport skips the check for it. + +## Time to be received + +The transport does not support time to be received, and its dispatcher ignores the setting. Heartbeats, custom check results, and metrics that endpoints send to ServiceControl stay in their subscription until an instance reads them or the subscription's message retention expires. The transport creates subscriptions with seven days of retention. + +## Integration events + +The primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic only when an endpoint subscribes to the event with installers enabled. Until then, each publish logs a warning and Pub/Sub has nowhere to deliver the event, so no subscriber misses it. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. + +## Queue length + +The monitoring instance does not report queue lengths for this transport yet. The Pub/Sub API has no backlog count, so queue length has to come from Cloud Monitoring. + +## Headers with empty values + +The transport drops headers whose value is empty or null, because Pub/Sub does not deliver an attribute with an empty value. ServiceControl's own headers always have a value. A header that a user empties while editing a failed message is not sent with the retried message. diff --git a/docs/testing.md b/docs/testing.md index a360f3d9ec..8dde241f00 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -38,6 +38,21 @@ The SQL Server and PostgreSQL persistence test projects contain a `SlowMigration Transport tests run the transport test suite for each transport. +### Google Cloud Pub/Sub + +The `GooglePubSub` tests read their connection string from `ServiceControl_TransportTests_GooglePubSub_ConnectionString`. CI runs them against a Google Cloud project rather than the Pub/Sub emulator, because the emulator delivers headers with empty values that Pub/Sub drops. The job signs in through workload identity federation with the `GCP_WORKLOAD_IDENTITY_PROVIDER` and `GCP_SERVICE_ACCOUNT` repository variables, and creates its resources in the project named by `GOOGLE_CLOUD_PROJECT`. The service account needs the Pub/Sub Editor role (`roles/pubsub.editor`) to create and delete topics and subscriptions. + +Each job sets `ResourceNamePrefix` to a prefix built from the run ID, the attempt, and the operating system, so that parallel jobs do not share resources. The last step deletes every subscription and topic with that prefix, even when the tests fail. + +To run the tests locally against the emulator: + +1. Start the emulator: `docker run --rm -p 8085:8085 gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators gcloud beta emulators pubsub start --host-port=0.0.0.0:8085` +2. Set `PUBSUB_EMULATOR_HOST=localhost:8085`. +3. Set `ServiceControl_TransportTests_GooglePubSub_ConnectionString=ProjectId=local-test`. +4. Set `ServiceControl_TESTS_FILTER=GooglePubSub` and run the `ServiceControl.Transports.GooglePubSub.Tests` project. + +To run them against a Google Cloud project instead, leave `PUBSUB_EMULATOR_HOST` unset, sign in with `gcloud auth application-default login`, and set `ProjectId` and a personal `ResourceNamePrefix` in the connection string. + ## Acceptance tests Acceptance tests run the full ServiceControl and use the HTTP API to validate results. LearningTransport is used for all tests. diff --git a/docs/usage-report.md b/docs/usage-report.md index de35263c28..38854e5617 100644 --- a/docs/usage-report.md +++ b/docs/usage-report.md @@ -120,6 +120,7 @@ The primary's `TransportEnvironmentDataProvider` emits `Transport.Type` and adds | `Transport.AmazonSQS.LargeMessageBucket` | `None`, `Configured` | `S3BucketForLargeMessages` | Unreleased | | `Transport.AmazonSQS.MessageWrapping` | `Enabled`, `Disabled` | `DoNotWrapOutgoingMessages` | Unreleased | | `Transport.AmazonSQS.ReservedBytesInMessageSize` | `Default` or number | `ReservedBytesInMessageSize` | Unreleased | +| `Transport.GooglePubSub.NamePrefix` | `None`, `Configured` | `ResourceNamePrefix` in the connection string | Unreleased | | `Transport.RabbitMQ.DeliveryLimitValidation` | `Enabled`, `Disabled` | `ValidateDeliveryLimits` | Unreleased | | `Transport.RabbitMQ.ManagementApi` | `Default`, `Configured` | `ManagementApiUrl` | Unreleased | | `Transport.SQLServer.QueueSchema` | `Default`, `Custom` | `Queue Schema` in the connection string | Unreleased | @@ -286,6 +287,7 @@ A setting that identifies and is also security configuration is listed as Identi | `Cors.AllowAnyOrigin` and whether origins are restricted | Security configuration | | | `ForwardedHeaders.Enabled`, `TrustAllProxies` and whether proxies are restricted | Security configuration | | | Transport authentication, encryption and certificate validation options in the connection string, for example RabbitMQ `UseExternalAuthMechanism` and `DisableRemoteCertificateValidation` | Security configuration | | +| Google Pub/Sub `ServiceEndpoint` | Security configuration | A custom endpoint usually means a regional endpoint or the restricted endpoint of VPC Service Controls, which restricts access. | | Database authentication, encryption and certificate validation options, for example SQL Server `Encrypt` and `TrustServerCertificate` or PostgreSQL `SSL Mode`, and whether a RavenDB client certificate is used | Security configuration | | | Body storage authentication mode | Security configuration | 6.20.0 to 6.21.2 report it as `Persistence.BodyStorage.Auth`. | | Email notification TLS and SMTP authentication | Security configuration | | @@ -299,6 +301,7 @@ A setting that identifies and is also security configuration is listed as Identi | `--error-ingestion-only` | Not a choice | A worker mode. Workers do not build reports. | | RavenDB `MaintenanceMode` | Not a choice | An instance in maintenance mode serves no API, so it cannot build a report. | | `ASPNETCORE_ENVIRONMENT=Development` | Not a choice | A development mode. | +| `PUBSUB_EMULATOR_HOST` | Not a choice | Selects the Pub/Sub emulator, a development mode. | | `DOTNET_RUNNING_IN_CONTAINER` | Not a choice | Already covered by `Host.Model`. | | Retry, archive, unarchive, resolve, edit and group comment operations | Not a choice | These are actions. Their on/off switch, where one exists, is reported. | | Custom checks | Not a choice | Endpoints report them and ServiceControl stores them. Deleting one does not keep a muted state. | diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 70db5dd3cd..d80eacd465 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -58,6 +58,7 @@ + @@ -103,6 +104,7 @@ + @@ -110,7 +112,9 @@ + + diff --git a/src/ProjectReferences.Transports.props b/src/ProjectReferences.Transports.props index ae9bd3bd3d..d77e7a6a15 100644 --- a/src/ProjectReferences.Transports.props +++ b/src/ProjectReferences.Transports.props @@ -3,6 +3,7 @@ + diff --git a/src/ServiceControl.Audit/App.config b/src/ServiceControl.Audit/App.config index e2284f20d8..9600e2c5fb 100644 --- a/src/ServiceControl.Audit/App.config +++ b/src/ServiceControl.Audit/App.config @@ -12,6 +12,7 @@ These settings are only here so that we can debug ServiceControl while developin + @@ -88,6 +89,9 @@ These settings are only here so that we can debug ServiceControl while developin + + + diff --git a/src/ServiceControl.Monitoring/App.config b/src/ServiceControl.Monitoring/App.config index be1b700c36..6b70a81b19 100644 --- a/src/ServiceControl.Monitoring/App.config +++ b/src/ServiceControl.Monitoring/App.config @@ -13,6 +13,7 @@ These settings are only here so that we can debug ServiceControl while developin + @@ -81,6 +82,9 @@ These settings are only here so that we can debug ServiceControl while developin + + + diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs new file mode 100644 index 0000000000..b04fc5d3e4 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs @@ -0,0 +1,47 @@ +namespace ServiceControl.Transport.Tests; + +using System; +using NUnit.Framework; +using Transports.GooglePubSub; + +[TestFixture] +class ConnectionStringTests +{ + [Test] + public void Should_accept_an_empty_connection_string() + { + var connectionString = new GooglePubSubConnectionString(null); + + using (Assert.EnterMultipleScope()) + { + Assert.That(connectionString.ProjectId, Is.Null); + Assert.That(connectionString.ResourceNamePrefix, Is.Null); + Assert.That(connectionString.ServiceEndpoint, Is.Null); + } + } + + [Test] + public void Should_read_every_supported_key_case_insensitively() + { + var connectionString = new GooglePubSubConnectionString("projectid=contoso-project;ResourceNamePrefix=dev-;SERVICEENDPOINT=europe-west1-pubsub.googleapis.com:443"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(connectionString.ProjectId, Is.EqualTo("contoso-project")); + Assert.That(connectionString.ResourceNamePrefix, Is.EqualTo("dev-")); + Assert.That(connectionString.ServiceEndpoint, Is.EqualTo("europe-west1-pubsub.googleapis.com:443")); + } + } + + [Test] + public void Should_reject_unsupported_keys_without_echoing_their_values() + { + var exception = Assert.Throws(() => _ = new GooglePubSubConnectionString("ProjectId=contoso-project;CredentialsJson=contoso-secret")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exception.Message, Does.Contain("CredentialsJson").IgnoreCase); + Assert.That(exception.Message, Does.Not.Contain("contoso-secret")); + } + } +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/EnvironmentDataTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/EnvironmentDataTests.cs new file mode 100644 index 0000000000..63d2fe5dd8 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/EnvironmentDataTests.cs @@ -0,0 +1,32 @@ +namespace ServiceControl.Transport.Tests; + +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Transports; +using Transports.GooglePubSub; + +[TestFixture] +class EnvironmentDataTests +{ + [Test] + public void Should_report_no_name_prefix_by_default() => + Assert.That(Read("ProjectId=contoso-project")["Transport.GooglePubSub.NamePrefix"], Is.EqualTo("None")); + + [Test] + public void Should_report_a_configured_name_prefix_without_its_value() + { + var data = Read("ProjectId=contoso-project;ResourceNamePrefix=contoso-;ServiceEndpoint=contoso.example.com:443"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(data["Transport.GooglePubSub.NamePrefix"], Is.EqualTo("Configured")); + Assert.That(string.Join("|", data.Values), Does.Not.Contain("contoso").IgnoreCase); + } + } + + static Dictionary Read(string connectionString) => + new GooglePubSubTransportCustomization() + .GetEnvironmentData(new TransportSettings { ConnectionString = connectionString }) + .ToDictionary(datum => datum.Key, datum => datum.ReadValue()); +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControl.Transports.GooglePubSub.Tests.csproj b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControl.Transports.GooglePubSub.Tests.csproj new file mode 100644 index 0000000000..289a475040 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControl.Transports.GooglePubSub.Tests.csproj @@ -0,0 +1,34 @@ + + + + net10.0 + GooglePubSub + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlAuditEndpointTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlAuditEndpointTests.cs new file mode 100644 index 0000000000..20c547e296 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlAuditEndpointTests.cs @@ -0,0 +1,6 @@ +namespace ServiceControl.Transport.Tests; + +partial class ServiceControlAuditEndpointTests +{ + private static partial int GetTransportDefaultConcurrency() => 32; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlMonitoringEndpointTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlMonitoringEndpointTests.cs new file mode 100644 index 0000000000..4e004d0253 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlMonitoringEndpointTests.cs @@ -0,0 +1,6 @@ +namespace ServiceControl.Transport.Tests; + +partial class ServiceControlMonitoringEndpointTests +{ + private static partial int GetTransportDefaultConcurrency() => 32; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlPrimaryEndpointTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlPrimaryEndpointTests.cs new file mode 100644 index 0000000000..465bba2734 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ServiceControlPrimaryEndpointTests.cs @@ -0,0 +1,6 @@ +namespace ServiceControl.Transport.Tests; + +partial class ServiceControlPrimaryEndpointTests +{ + private static partial int GetTransportDefaultConcurrency() => 10; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/TransportTestsConfiguration.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/TransportTestsConfiguration.cs new file mode 100644 index 0000000000..c3899c2ba8 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/TransportTestsConfiguration.cs @@ -0,0 +1,32 @@ +namespace ServiceControl.Transport.Tests; + +using System; +using System.Threading; +using System.Threading.Tasks; +using Transports; +using Transports.GooglePubSub; + +class TransportTestsConfiguration +{ + public string ConnectionString { get; private set; } + + public ITransportCustomization TransportCustomization { get; private set; } + + public Task Configure(CancellationToken cancellationToken = default) + { + TransportCustomization = new GooglePubSubTransportCustomization(); + ConnectionString = Environment.GetEnvironmentVariable(ConnectionStringKey) + ?? Environment.GetEnvironmentVariable(ConnectionStringKey.ToUpperInvariant()); // Env keys are case sensitive, POSIX is all uppercase + + if (string.IsNullOrEmpty(ConnectionString)) + { + throw new Exception($"Environment variable {ConnectionStringKey} is required for Google Pub/Sub transport tests to run"); + } + + return Task.CompletedTask; + } + + public Task Cleanup(CancellationToken cancellationToken = default) => Task.CompletedTask; + + static readonly string ConnectionStringKey = "ServiceControl_TransportTests_GooglePubSub_ConnectionString"; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs new file mode 100644 index 0000000000..5a6fbc44ab --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs @@ -0,0 +1,36 @@ +namespace ServiceControl.Transports.GooglePubSub; + +using System; +using System.Data.Common; +using System.Linq; + +class GooglePubSubConnectionString +{ + public GooglePubSubConnectionString(string connectionString) + { + var builder = new DbConnectionStringBuilder { ConnectionString = connectionString ?? string.Empty }; + + var unknownKeys = builder.Keys.Cast().Where(key => !Array.Exists(SupportedKeys, supported => string.Equals(supported, key, StringComparison.OrdinalIgnoreCase))).ToArray(); + if (unknownKeys.Length > 0) + { + throw new ArgumentException($"The Google Pub/Sub connection string contains unsupported keys: {string.Join(", ", unknownKeys)}. Supported keys are {string.Join(", ", SupportedKeys)}. Credentials come from Application Default Credentials, not the connection string."); + } + + ProjectId = Read(builder, ProjectIdKey); + ResourceNamePrefix = Read(builder, ResourceNamePrefixKey); + ServiceEndpoint = Read(builder, ServiceEndpointKey); + } + + public string ProjectId { get; } + public string ResourceNamePrefix { get; } + public string ServiceEndpoint { get; } + + static string Read(DbConnectionStringBuilder builder, string key) => + builder.TryGetValue(key, out var value) && value is string text && !string.IsNullOrWhiteSpace(text) ? text : null; + + const string ProjectIdKey = "ProjectId"; + const string ResourceNamePrefixKey = "ResourceNamePrefix"; + const string ServiceEndpointKey = "ServiceEndpoint"; + + static readonly string[] SupportedKeys = [ProjectIdKey, ResourceNamePrefixKey, ServiceEndpointKey]; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs new file mode 100644 index 0000000000..06788d4c68 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs @@ -0,0 +1,44 @@ +namespace ServiceControl.Transports.GooglePubSub; + +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using NServiceBus; +using Transport.GooglePubSub; + +public class GooglePubSubTransportCustomization : TransportCustomization +{ + protected override void CustomizeTransportForPrimaryEndpoint(EndpointConfiguration endpointConfiguration, GooglePubSubTransport transportDefinition, TransportSettings transportSettings) { } + + protected override void CustomizeTransportForAuditEndpoint(EndpointConfiguration endpointConfiguration, GooglePubSubTransport transportDefinition, TransportSettings transportSettings) { } + + protected override void CustomizeTransportForMonitoringEndpoint(EndpointConfiguration endpointConfiguration, GooglePubSubTransport transportDefinition, TransportSettings transportSettings) { } + + protected override void AddTransportForMonitoringCore(IServiceCollection services, TransportSettings transportSettings) + { + services.AddSingleton(); + services.AddHostedService(provider => provider.GetRequiredService()); + } + + public override IEnumerable GetEnvironmentData(TransportSettings transportSettings) => + [ + new("Transport.GooglePubSub.NamePrefix", () => new GooglePubSubConnectionString(transportSettings.ConnectionString).ResourceNamePrefix is null ? "None" : "Configured") + ]; + + protected override GooglePubSubTransport CreateTransport(TransportSettings transportSettings, TransportTransactionMode preferredTransactionMode = TransportTransactionMode.ReceiveOnly) + { + var connectionString = new GooglePubSubConnectionString(transportSettings.ConnectionString); + + // Credentials always come from Application Default Credentials. See docs/google-pubsub-transport.md#credentials + var transport = new GooglePubSubTransport(new GooglePubSubTransportOptions + { + ProjectId = connectionString.ProjectId, + ResourceNamePrefix = connectionString.ResourceNamePrefix, + ServiceEndpoint = connectionString.ServiceEndpoint + }); + + transport.TransportTransactionMode = transport.GetSupportedTransactionModes().Contains(preferredTransactionMode) ? preferredTransactionMode : TransportTransactionMode.ReceiveOnly; + + return transport; + } +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/NoOpQueueLengthProvider.cs b/src/ServiceControl.Transports.GooglePubSub/NoOpQueueLengthProvider.cs new file mode 100644 index 0000000000..666a2a47ab --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub/NoOpQueueLengthProvider.cs @@ -0,0 +1,15 @@ +namespace ServiceControl.Transports.GooglePubSub; + +using System.Threading; +using System.Threading.Tasks; + +class NoOpQueueLengthProvider : IProvideQueueLength +{ + public void TrackEndpointInputQueue(EndpointToQueueMapping queueToTrack) + { + } + + public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; +} \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/ServiceControl.Transports.GooglePubSub.csproj b/src/ServiceControl.Transports.GooglePubSub/ServiceControl.Transports.GooglePubSub.csproj new file mode 100644 index 0000000000..07f5092e04 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub/ServiceControl.Transports.GooglePubSub.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + true + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ServiceControl.Transports.GooglePubSub/transport.manifest b/src/ServiceControl.Transports.GooglePubSub/transport.manifest new file mode 100644 index 0000000000..18f6ffe2c4 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub/transport.manifest @@ -0,0 +1,15 @@ +{ + "Definitions": [ + { + "Name": "GooglePubSub", + "DisplayName": "Google Cloud Pub/Sub", + "AssemblyName": "ServiceControl.Transports.GooglePubSub", + "TypeName": "ServiceControl.Transports.GooglePubSub.GooglePubSubTransportCustomization, ServiceControl.Transports.GooglePubSub", + "SampleConnectionString": "ProjectId=;ResourceNamePrefix=;ServiceEndpoint=", + "AvailableInSCMU": true, + "Help": "All keys are optional. 'ProjectId' defaults to the GOOGLE_CLOUD_PROJECT environment variable or the Google Cloud metadata server. Credentials come from Application Default Credentials, for example the GOOGLE_APPLICATION_CREDENTIALS environment variable, and are never part of the connection string. Set PUBSUB_EMULATOR_HOST to use the Pub/Sub emulator.", + "Aliases": [ + ] + } + ] +} diff --git a/src/ServiceControl.Transports.Tests/ApprovalFiles/TransportManifestLibraryTests.All_types_defined_in_manifest_files_exist_in_specified_assembly.approved.txt b/src/ServiceControl.Transports.Tests/ApprovalFiles/TransportManifestLibraryTests.All_types_defined_in_manifest_files_exist_in_specified_assembly.approved.txt index 397809505d..732ee35f99 100644 --- a/src/ServiceControl.Transports.Tests/ApprovalFiles/TransportManifestLibraryTests.All_types_defined_in_manifest_files_exist_in_specified_assembly.approved.txt +++ b/src/ServiceControl.Transports.Tests/ApprovalFiles/TransportManifestLibraryTests.All_types_defined_in_manifest_files_exist_in_specified_assembly.approved.txt @@ -1,6 +1,7 @@ [ "AmazonSQS", "AzureStorageQueue", + "GooglePubSub", "IBMMQ", "LearningTransport", "LearningTransport", diff --git a/src/ServiceControl.Transports/DevelopmentTransportLocations.cs b/src/ServiceControl.Transports/DevelopmentTransportLocations.cs index 95e7e8c021..5358eadd12 100644 --- a/src/ServiceControl.Transports/DevelopmentTransportLocations.cs +++ b/src/ServiceControl.Transports/DevelopmentTransportLocations.cs @@ -19,6 +19,7 @@ static DevelopmentTransportLocations() { ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.ASBS")); ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.ASQ")); + ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.GooglePubSub")); ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.IBMMQ")); ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.Learning")); ManifestFiles.Add(BuildManifestPath(srcFolder, "ServiceControl.Transports.Msmq", "net10.0-windows")); diff --git a/src/ServiceControl.slnx b/src/ServiceControl.slnx index e9a507b944..85753bcd0b 100644 --- a/src/ServiceControl.slnx +++ b/src/ServiceControl.slnx @@ -90,6 +90,7 @@ + @@ -102,6 +103,7 @@ + diff --git a/src/ServiceControl/App.config b/src/ServiceControl/App.config index 8bc0d1f457..b626baa568 100644 --- a/src/ServiceControl/App.config +++ b/src/ServiceControl/App.config @@ -17,6 +17,7 @@ These settings are only here so that we can debug ServiceControl while developin + @@ -95,6 +96,9 @@ These settings are only here so that we can debug ServiceControl while developin + + + diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/APIApprovals.TransportNames.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/APIApprovals.TransportNames.approved.txt index 58499293d7..52e280b74b 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/APIApprovals.TransportNames.approved.txt +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/APIApprovals.TransportNames.approved.txt @@ -35,6 +35,11 @@ "ServiceControl.Transports.AzureStorageQueues.ServiceControlAzureStorageQueueTransport, ServiceControl.Transports.AzureStorageQueues" ] }, + { + "Name": "GooglePubSub", + "DisplayName": "Google Cloud Pub/Sub", + "Aliases": [] + }, { "Name": "IBMMQ", "DisplayName": "IBM MQ", diff --git a/src/ServiceControlInstaller.Packaging.UnitTests/DeploymentPackageTests.cs b/src/ServiceControlInstaller.Packaging.UnitTests/DeploymentPackageTests.cs index 9ca885c014..6fda9a9637 100644 --- a/src/ServiceControlInstaller.Packaging.UnitTests/DeploymentPackageTests.cs +++ b/src/ServiceControlInstaller.Packaging.UnitTests/DeploymentPackageTests.cs @@ -143,7 +143,8 @@ public void Should_package_all_transports() "AmazonSQS", "LearningTransport", "PostgreSql", - "IBMMQ"}; + "IBMMQ", + "GooglePubSub"}; var bundledTransports = deploymentPackage.DeploymentUnits .Where(u => u.Category == "Transports") From 8f6917456e978590576c437038715d0042ebf4bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Wed, 25 Nov 2026 08:37:49 +0100 Subject: [PATCH 2/6] Select the Pub/Sub emulator through the connection string --- docs/google-pubsub-transport.md | 4 ++-- docs/testing.md | 2 +- docs/usage-report.md | 2 +- src/ServiceControl.Audit/App.config | 2 +- src/ServiceControl.Monitoring/App.config | 2 +- .../ConnectionStringTests.cs | 10 +++++++++- .../GooglePubSubConnectionString.cs | 15 ++++++++++++++- .../GooglePubSubTransportCustomization.cs | 11 +++++++++-- .../transport.manifest | 4 ++-- src/ServiceControl/App.config | 2 +- 10 files changed, 41 insertions(+), 13 deletions(-) diff --git a/docs/google-pubsub-transport.md b/docs/google-pubsub-transport.md index 67b1f55b9d..3194023082 100644 --- a/docs/google-pubsub-transport.md +++ b/docs/google-pubsub-transport.md @@ -4,9 +4,9 @@ The primary, audit, and monitoring instances can run on the `NServiceBus.Transpo ## Connection string -The connection string accepts `ProjectId`, `ResourceNamePrefix`, and `ServiceEndpoint`, and each maps to the `GooglePubSubTransportOptions` property of the same name. All three are optional. The parser rejects any other key, so credentials cannot end up in the connection string or in the instance configuration. +The connection string accepts `ProjectId`, `ResourceNamePrefix`, `ServiceEndpoint`, and `EmulatorDetection`, and each maps to the `GooglePubSubTransportOptions` property of the same name. All four are optional. The parser rejects any other key, so credentials cannot end up in the connection string or in the instance configuration. -Without `ProjectId`, the transport reads the `GOOGLE_CLOUD_PROJECT` or `GCLOUD_PROJECT` environment variable, then the Google Cloud metadata server. When `PUBSUB_EMULATOR_HOST` is set, the transport connects to the Pub/Sub emulator. +Without `ProjectId`, the transport reads the `GOOGLE_CLOUD_PROJECT` or `GCLOUD_PROJECT` environment variable, then the Google Cloud metadata server. The transport ignores the Pub/Sub emulator unless `EmulatorDetection` is `EmulatorOnly` or `EmulatorOrProduction`. With either value, it connects to the address in `PUBSUB_EMULATOR_HOST`, without authentication or encryption. ## Credentials diff --git a/docs/testing.md b/docs/testing.md index 8dde241f00..ca02d66420 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -48,7 +48,7 @@ To run the tests locally against the emulator: 1. Start the emulator: `docker run --rm -p 8085:8085 gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators gcloud beta emulators pubsub start --host-port=0.0.0.0:8085` 2. Set `PUBSUB_EMULATOR_HOST=localhost:8085`. -3. Set `ServiceControl_TransportTests_GooglePubSub_ConnectionString=ProjectId=local-test`. +3. Set `ServiceControl_TransportTests_GooglePubSub_ConnectionString=ProjectId=local-test;EmulatorDetection=EmulatorOnly`. 4. Set `ServiceControl_TESTS_FILTER=GooglePubSub` and run the `ServiceControl.Transports.GooglePubSub.Tests` project. To run them against a Google Cloud project instead, leave `PUBSUB_EMULATOR_HOST` unset, sign in with `gcloud auth application-default login`, and set `ProjectId` and a personal `ResourceNamePrefix` in the connection string. diff --git a/docs/usage-report.md b/docs/usage-report.md index 38854e5617..58942fb59b 100644 --- a/docs/usage-report.md +++ b/docs/usage-report.md @@ -301,7 +301,7 @@ A setting that identifies and is also security configuration is listed as Identi | `--error-ingestion-only` | Not a choice | A worker mode. Workers do not build reports. | | RavenDB `MaintenanceMode` | Not a choice | An instance in maintenance mode serves no API, so it cannot build a report. | | `ASPNETCORE_ENVIRONMENT=Development` | Not a choice | A development mode. | -| `PUBSUB_EMULATOR_HOST` | Not a choice | Selects the Pub/Sub emulator, a development mode. | +| Google Pub/Sub `EmulatorDetection`, `PUBSUB_EMULATOR_HOST` | Not a choice | They select the Pub/Sub emulator, a development mode. | | `DOTNET_RUNNING_IN_CONTAINER` | Not a choice | Already covered by `Host.Model`. | | Retry, archive, unarchive, resolve, edit and group comment operations | Not a choice | These are actions. Their on/off switch, where one exists, is reported. | | Custom checks | Not a choice | Endpoints report them and ServiceControl stores them. Deleting one does not keep a muted state. | diff --git a/src/ServiceControl.Audit/App.config b/src/ServiceControl.Audit/App.config index 9600e2c5fb..4b9a589d36 100644 --- a/src/ServiceControl.Audit/App.config +++ b/src/ServiceControl.Audit/App.config @@ -89,7 +89,7 @@ These settings are only here so that we can debug ServiceControl while developin - + diff --git a/src/ServiceControl.Monitoring/App.config b/src/ServiceControl.Monitoring/App.config index 6b70a81b19..7d10eecd22 100644 --- a/src/ServiceControl.Monitoring/App.config +++ b/src/ServiceControl.Monitoring/App.config @@ -82,7 +82,7 @@ These settings are only here so that we can debug ServiceControl while developin - + diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs index b04fc5d3e4..abb1c0fd18 100644 --- a/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/ConnectionStringTests.cs @@ -1,6 +1,7 @@ namespace ServiceControl.Transport.Tests; using System; +using Google.Api.Gax; using NUnit.Framework; using Transports.GooglePubSub; @@ -17,22 +18,29 @@ public void Should_accept_an_empty_connection_string() Assert.That(connectionString.ProjectId, Is.Null); Assert.That(connectionString.ResourceNamePrefix, Is.Null); Assert.That(connectionString.ServiceEndpoint, Is.Null); + Assert.That(connectionString.EmulatorDetection, Is.Null); } } [Test] public void Should_read_every_supported_key_case_insensitively() { - var connectionString = new GooglePubSubConnectionString("projectid=contoso-project;ResourceNamePrefix=dev-;SERVICEENDPOINT=europe-west1-pubsub.googleapis.com:443"); + var connectionString = new GooglePubSubConnectionString("projectid=contoso-project;ResourceNamePrefix=dev-;SERVICEENDPOINT=europe-west1-pubsub.googleapis.com:443;EmulatorDetection=emulatoronly"); using (Assert.EnterMultipleScope()) { Assert.That(connectionString.ProjectId, Is.EqualTo("contoso-project")); Assert.That(connectionString.ResourceNamePrefix, Is.EqualTo("dev-")); Assert.That(connectionString.ServiceEndpoint, Is.EqualTo("europe-west1-pubsub.googleapis.com:443")); + Assert.That(connectionString.EmulatorDetection, Is.EqualTo(EmulatorDetection.EmulatorOnly)); } } + [TestCase("Emulator")] + [TestCase("7")] + public void Should_reject_an_unknown_emulator_detection(string value) => + Assert.Throws(() => _ = new GooglePubSubConnectionString($"EmulatorDetection={value}")); + [Test] public void Should_reject_unsupported_keys_without_echoing_their_values() { diff --git a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs index 5a6fbc44ab..1b95ee3208 100644 --- a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs +++ b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubConnectionString.cs @@ -3,6 +3,7 @@ namespace ServiceControl.Transports.GooglePubSub; using System; using System.Data.Common; using System.Linq; +using Google.Api.Gax; class GooglePubSubConnectionString { @@ -19,11 +20,22 @@ public GooglePubSubConnectionString(string connectionString) ProjectId = Read(builder, ProjectIdKey); ResourceNamePrefix = Read(builder, ResourceNamePrefixKey); ServiceEndpoint = Read(builder, ServiceEndpointKey); + + if (Read(builder, EmulatorDetectionKey) is { } emulatorDetection) + { + if (!Enum.TryParse(emulatorDetection, ignoreCase: true, out var parsed) || !Enum.IsDefined(parsed)) + { + throw new ArgumentException($"'{emulatorDetection}' is not a valid {EmulatorDetectionKey} value. Use one of {string.Join(", ", Enum.GetNames())}."); + } + + EmulatorDetection = parsed; + } } public string ProjectId { get; } public string ResourceNamePrefix { get; } public string ServiceEndpoint { get; } + public EmulatorDetection? EmulatorDetection { get; } static string Read(DbConnectionStringBuilder builder, string key) => builder.TryGetValue(key, out var value) && value is string text && !string.IsNullOrWhiteSpace(text) ? text : null; @@ -31,6 +43,7 @@ static string Read(DbConnectionStringBuilder builder, string key) => const string ProjectIdKey = "ProjectId"; const string ResourceNamePrefixKey = "ResourceNamePrefix"; const string ServiceEndpointKey = "ServiceEndpoint"; + const string EmulatorDetectionKey = "EmulatorDetection"; - static readonly string[] SupportedKeys = [ProjectIdKey, ResourceNamePrefixKey, ServiceEndpointKey]; + static readonly string[] SupportedKeys = [ProjectIdKey, ResourceNamePrefixKey, ServiceEndpointKey, EmulatorDetectionKey]; } \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs index 06788d4c68..3199b6f058 100644 --- a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs +++ b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs @@ -30,12 +30,19 @@ protected override GooglePubSubTransport CreateTransport(TransportSettings trans var connectionString = new GooglePubSubConnectionString(transportSettings.ConnectionString); // Credentials always come from Application Default Credentials. See docs/google-pubsub-transport.md#credentials - var transport = new GooglePubSubTransport(new GooglePubSubTransportOptions + var options = new GooglePubSubTransportOptions { ProjectId = connectionString.ProjectId, ResourceNamePrefix = connectionString.ResourceNamePrefix, ServiceEndpoint = connectionString.ServiceEndpoint - }); + }; + + if (connectionString.EmulatorDetection is { } emulatorDetection) + { + options.EmulatorDetection = emulatorDetection; + } + + var transport = new GooglePubSubTransport(options); transport.TransportTransactionMode = transport.GetSupportedTransactionModes().Contains(preferredTransactionMode) ? preferredTransactionMode : TransportTransactionMode.ReceiveOnly; diff --git a/src/ServiceControl.Transports.GooglePubSub/transport.manifest b/src/ServiceControl.Transports.GooglePubSub/transport.manifest index 18f6ffe2c4..99a88d9de9 100644 --- a/src/ServiceControl.Transports.GooglePubSub/transport.manifest +++ b/src/ServiceControl.Transports.GooglePubSub/transport.manifest @@ -5,9 +5,9 @@ "DisplayName": "Google Cloud Pub/Sub", "AssemblyName": "ServiceControl.Transports.GooglePubSub", "TypeName": "ServiceControl.Transports.GooglePubSub.GooglePubSubTransportCustomization, ServiceControl.Transports.GooglePubSub", - "SampleConnectionString": "ProjectId=;ResourceNamePrefix=;ServiceEndpoint=", + "SampleConnectionString": "ProjectId=;ResourceNamePrefix=;ServiceEndpoint=;EmulatorDetection=", "AvailableInSCMU": true, - "Help": "All keys are optional. 'ProjectId' defaults to the GOOGLE_CLOUD_PROJECT environment variable or the Google Cloud metadata server. Credentials come from Application Default Credentials, for example the GOOGLE_APPLICATION_CREDENTIALS environment variable, and are never part of the connection string. Set PUBSUB_EMULATOR_HOST to use the Pub/Sub emulator.", + "Help": "All keys are optional. 'ProjectId' defaults to the GOOGLE_CLOUD_PROJECT environment variable or the Google Cloud metadata server. Credentials come from Application Default Credentials, for example the GOOGLE_APPLICATION_CREDENTIALS environment variable, and are never part of the connection string. To use the Pub/Sub emulator, set 'EmulatorDetection' to 'EmulatorOnly' and the PUBSUB_EMULATOR_HOST environment variable to the emulator address.", "Aliases": [ ] } diff --git a/src/ServiceControl/App.config b/src/ServiceControl/App.config index b626baa568..2527fb6081 100644 --- a/src/ServiceControl/App.config +++ b/src/ServiceControl/App.config @@ -96,7 +96,7 @@ These settings are only here so that we can debug ServiceControl while developin - + From 2e1035d1e15cf2d9ecea3f3f91c2f08bce67ee50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Wed, 25 Nov 2026 08:37:49 +0100 Subject: [PATCH 3/6] Update the Google Pub/Sub transport to 0.0.0-alpha.0.55 --- docs/google-pubsub-transport.md | 6 +----- src/Directory.Packages.props | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/google-pubsub-transport.md b/docs/google-pubsub-transport.md index 3194023082..54eca91cc5 100644 --- a/docs/google-pubsub-transport.md +++ b/docs/google-pubsub-transport.md @@ -20,13 +20,9 @@ The transport supports `None` and `ReceiveOnly`. The retry dequeuer requests `Se The transport throws for delayed sends and saga timeouts, and it limits delayed retries to 600 seconds. ServiceControl sends no delayed messages and disables sagas. The primary and monitoring instances set delayed retries to zero, which passes the transport's startup check. The audit instance is send-only, so the transport skips the check for it. -## Time to be received - -The transport does not support time to be received, and its dispatcher ignores the setting. Heartbeats, custom check results, and metrics that endpoints send to ServiceControl stay in their subscription until an instance reads them or the subscription's message retention expires. The transport creates subscriptions with seven days of retention. - ## Integration events -The primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic only when an endpoint subscribes to the event with installers enabled. Until then, each publish logs a warning and Pub/Sub has nowhere to deliver the event, so no subscriber misses it. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. +The primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic when an endpoint with installers enabled publishes or subscribes to the event. The primary never enables installers, so its publish to a topic that no subscriber has created throws. `EventDispatcherHostedService` logs the failure and raises `ExternalIntegrationEventFailedToBePublished`. No subscriber misses the event, because Pub/Sub discards a message published to a topic without subscriptions. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. ## Queue length diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index d80eacd465..d478a42642 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -58,7 +58,7 @@ - + From 47602056c6e80fd6c61f24db51d7d8cd9afabdaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Wed, 25 Nov 2026 08:53:24 +0100 Subject: [PATCH 4/6] State that integration events fail only when external integrations publishing is on --- docs/google-pubsub-transport.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/google-pubsub-transport.md b/docs/google-pubsub-transport.md index 54eca91cc5..7c7c97befb 100644 --- a/docs/google-pubsub-transport.md +++ b/docs/google-pubsub-transport.md @@ -22,7 +22,7 @@ The transport throws for delayed sends and saga timeouts, and it limits delayed ## Integration events -The primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic when an endpoint with installers enabled publishes or subscribes to the event. The primary never enables installers, so its publish to a topic that no subscriber has created throws. `EventDispatcherHostedService` logs the failure and raises `ExternalIntegrationEventFailedToBePublished`. No subscriber misses the event, because Pub/Sub discards a message published to a topic without subscriptions. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. +With `EnableExternalIntegrationsPublishing`, the primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic when an endpoint with installers enabled publishes or subscribes to the event. The primary never enables installers, so its publish to a topic that no subscriber has created throws. `EventDispatcherHostedService` logs the failure and raises `ExternalIntegrationEventFailedToBePublished`. No subscriber misses the event, because Pub/Sub discards a message published to a topic without subscriptions. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. ## Queue length From 04bedae6341b9af00bfe6ef2d59232809a70f8b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Mon, 30 Nov 2026 10:28:19 +0100 Subject: [PATCH 5/6] Update the Google Pub/Sub transport to 0.0.0-alpha.0.64 --- src/Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index d478a42642..9c65d82ba0 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -58,7 +58,7 @@ - + From 6a73e835061a5516134f340256cc821f2843ecb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20=C3=96hlund?= Date: Mon, 30 Nov 2026 10:28:19 +0100 Subject: [PATCH 6/6] Create the topics of published integration events during setup --- docs/google-pubsub-transport.md | 4 +- .../.editorconfig | 4 ++ .../PublishedEventTopicTests.cs | 71 +++++++++++++++++++ .../GooglePubSubTransportCustomization.cs | 6 ++ 4 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/.editorconfig create mode 100644 src/ServiceControl.Transports.GooglePubSub.Tests/PublishedEventTopicTests.cs diff --git a/docs/google-pubsub-transport.md b/docs/google-pubsub-transport.md index 7c7c97befb..57884368ee 100644 --- a/docs/google-pubsub-transport.md +++ b/docs/google-pubsub-transport.md @@ -22,7 +22,9 @@ The transport throws for delayed sends and saga timeouts, and it limits delayed ## Integration events -With `EnableExternalIntegrationsPublishing`, the primary publishes integration events to topics named `{ResourceNamePrefix}events.{full type name}`. The transport creates an event topic when an endpoint with installers enabled publishes or subscribes to the event. The primary never enables installers, so its publish to a topic that no subscriber has created throws. `EventDispatcherHostedService` logs the failure and raises `ExternalIntegrationEventFailedToBePublished`. No subscriber misses the event, because Pub/Sub discards a message published to a topic without subscriptions. ServiceControl does not create these topics itself, because that would duplicate the transport's naming rules. +With `EnableExternalIntegrationsPublishing`, the primary publishes integration events to the transport's default event topics. The running primary has installers disabled, and the transport throws when it publishes to a missing topic. The customization therefore declares each type in `TransportSettings.EventTypesPublished` with `Topology.Publishes`, and the transport creates their topics when setup calls `ProvisionQueues`. ServiceControl leaves topic naming to the transport. + +Setup declares the event types only when `EnableExternalIntegrationsPublishing` is on. An instance that turns the setting on later must run setup again before it publishes. ## Queue length diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/.editorconfig b/src/ServiceControl.Transports.GooglePubSub.Tests/.editorconfig new file mode 100644 index 0000000000..5f68a610b3 --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# Justification: Test project +dotnet_diagnostic.CA2007.severity = none diff --git a/src/ServiceControl.Transports.GooglePubSub.Tests/PublishedEventTopicTests.cs b/src/ServiceControl.Transports.GooglePubSub.Tests/PublishedEventTopicTests.cs new file mode 100644 index 0000000000..5f3f0483dd --- /dev/null +++ b/src/ServiceControl.Transports.GooglePubSub.Tests/PublishedEventTopicTests.cs @@ -0,0 +1,71 @@ +namespace ServiceControl.Transport.Tests; + +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using NServiceBus.Routing; +using NServiceBus.Transport; +using NUnit.Framework; +using Transports; + +[TestFixture] +class PublishedEventTopicTests +{ + [SetUp] + public async Task Setup() + { + configuration = new TransportTestsConfiguration(); + await configuration.Configure(); + + // A prefix per test keeps topics created by earlier runs from hiding a missing topic + var builder = new DbConnectionStringBuilder { ConnectionString = configuration.ConnectionString }; + var prefix = builder.TryGetValue("ResourceNamePrefix", out var existing) ? (string)existing : ""; + builder["ResourceNamePrefix"] = $"{prefix}t{Path.GetRandomFileName().Replace(".", string.Empty)}-"; + connectionString = builder.ConnectionString; + } + + [Test] + public async Task Should_publish_events_declared_at_setup_without_installers() + { + var transportSettings = CreateTransportSettings(); + + Assert.ThrowsAsync(() => Publish(transportSettings, CancellationToken.None), "Publishing before setup should find no topic, or this test proves nothing"); + + await configuration.TransportCustomization.ProvisionQueues(CreateTransportSettings(), []); + + Assert.DoesNotThrowAsync(() => Publish(transportSettings, CancellationToken.None)); + } + + TransportSettings CreateTransportSettings() => new() + { + ConnectionString = connectionString, + EndpointName = "published-events", + MaxConcurrency = 1, + EventTypesPublished = new HashSet { typeof(PublishedEventTopicTestEvent) } + }; + + async Task Publish(TransportSettings transportSettings, CancellationToken cancellationToken) + { + var infrastructure = await configuration.TransportCustomization.CreateTransportInfrastructure("published-events", transportSettings, cancellationToken: cancellationToken); + try + { + var operation = new TransportOperation( + new OutgoingMessage(Guid.NewGuid().ToString(), [], "{}"u8.ToArray()), + new MulticastAddressTag(typeof(PublishedEventTopicTestEvent))); + + await infrastructure.Dispatcher.Dispatch(new TransportOperations(operation), new TransportTransaction(), cancellationToken); + } + finally + { + await infrastructure.Shutdown(cancellationToken); + } + } + + TransportTestsConfiguration configuration; + string connectionString; +} + +public class PublishedEventTopicTestEvent; \ No newline at end of file diff --git a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs index 3199b6f058..86d0e7aa25 100644 --- a/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs +++ b/src/ServiceControl.Transports.GooglePubSub/GooglePubSubTransportCustomization.cs @@ -44,6 +44,12 @@ protected override GooglePubSubTransport CreateTransport(TransportSettings trans var transport = new GooglePubSubTransport(options); + // Setup creates the topics of declared event types, because the running primary has installers disabled + foreach (var eventType in transportSettings.EventTypesPublished) + { + transport.Topology.Publishes(eventType); + } + transport.TransportTransactionMode = transport.GetSupportedTransactionModes().Contains(preferredTransactionMode) ? preferredTransactionMode : TransportTransactionMode.ReceiveOnly; return transport;