From 7e6daf50315d943f0b68fdd08a9056b4dd8fdc9f Mon Sep 17 00:00:00 2001 From: Tomasz Maruszak Date: Tue, 25 Aug 2026 11:24:07 +0200 Subject: [PATCH] Add Google Cloud Pub/Sub transport Signed-off-by: Tomasz Maruszak --- .github/workflows/build.yml | 6 + README.md | 2 + build/tasks.ps1 | 1 + docs/README.md | 5 +- docs/provider_google_pubsub.md | 267 +++++++++++++++++ docs/provider_google_pubsub.t.md | 267 +++++++++++++++++ src/Host.Plugin.Properties.xml | 2 +- .../SlimMessageBus.Host.Configuration.csproj | 2 +- .../Config/Delegates.cs | 15 + .../GooglePubSubConsumerBuilderExtensions.cs | 34 +++ .../GooglePubSubProducerBuilderExtensions.cs | 22 ++ .../Config/GooglePubSubProperties.cs | 9 + .../Config/GooglePubSubSettingsExtensions.cs | 10 + .../Config/MessageBusBuilderExtensions.cs | 18 ++ .../Consumer/GooglePubSubConsumer.cs | 116 ++++++++ .../GooglePubSubConsumerContextExtensions.cs | 25 ++ .../IGooglePubSubConsumerErrorHandler.cs | 6 + .../GooglePubSubMessageBus.cs | 270 ++++++++++++++++++ .../GooglePubSubMessageBusSettings.cs | 108 +++++++ ...bSubMessageBusSettingsValidationService.cs | 51 ++++ .../GooglePubSubResourceName.cs | 14 + .../GooglePubSubTopologyService.cs | 163 +++++++++++ .../GooglePubSubTopologySettings.cs | 26 ++ .../DefaultGooglePubSubHeaderSerializer.cs | 61 ++++ .../Headers/IGooglePubSubHeaderSerializer.cs | 10 + .../SlimMessageBus.Host.GooglePubSub.csproj | 22 ++ .../Usings.cs | 10 + src/SlimMessageBus.sln | 40 ++- ...efaultGooglePubSubHeaderSerializerTests.cs | 71 +++++ .../GooglePubSubConfigurationTests.cs | 109 +++++++ ...glePubSubConsumerContextExtensionsTests.cs | 29 ++ .../GooglePubSubFixture.cs | 19 ++ .../GooglePubSubMessageBusIt.cs | 80 ++++++ .../GooglePubSubMessageBusSettingsTests.cs | 72 +++++ ...essageBusSettingsValidationServiceTests.cs | 142 +++++++++ .../GooglePubSubMessageBusTests.cs | 60 ++++ .../GooglePubSubTopologyServiceTests.cs | 181 ++++++++++++ ...imMessageBus.Host.GooglePubSub.Test.csproj | 22 ++ .../Usings.cs | 24 ++ .../appsettings.json | 1 + 40 files changed, 2380 insertions(+), 12 deletions(-) create mode 100644 docs/provider_google_pubsub.md create mode 100644 docs/provider_google_pubsub.t.md create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/Delegates.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubConsumerBuilderExtensions.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProducerBuilderExtensions.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProperties.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubSettingsExtensions.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Config/MessageBusBuilderExtensions.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumer.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumerContextExtensions.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Consumer/IGooglePubSubConsumerErrorHandler.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBus.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettings.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettingsValidationService.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubResourceName.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologyService.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologySettings.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Headers/DefaultGooglePubSubHeaderSerializer.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Headers/IGooglePubSubHeaderSerializer.cs create mode 100644 src/SlimMessageBus.Host.GooglePubSub/SlimMessageBus.Host.GooglePubSub.csproj create mode 100644 src/SlimMessageBus.Host.GooglePubSub/Usings.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/DefaultGooglePubSubHeaderSerializerTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConfigurationTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConsumerContextExtensionsTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubFixture.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusIt.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsValidationServiceTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubTopologyServiceTests.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/SlimMessageBus.Host.GooglePubSub.Test.csproj create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/Usings.cs create mode 100644 src/Tests/SlimMessageBus.Host.GooglePubSub.Test/appsettings.json diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8a47d07a..4ca3d844 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -178,6 +178,12 @@ jobs: test_path: "Tests/SlimMessageBus.Host.PostgreSql.Test" docker_services: "" + - transport: GooglePubSub + name: Google Pub/Sub + filter: "Category=Integration&Transport=GooglePubSub" + test_path: "Tests/SlimMessageBus.Host.GooglePubSub.Test" + docker_services: "" + # Outbox – four parallel sub-legs: # 1a. Sql.DbContext OutboxTests – AzureSB + Kafka; SQL Server via local docker - transport: Outbox.SqlDbContext.Tests diff --git a/README.md b/README.md index 863aac6b..ad7a8548 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ The configuration can be [modularized](docs/intro.md#modularization-of-configura - [Apache Kafka](docs/provider_kafka.md) - [Azure EventHubs](docs/provider_azure_eventhubs.md) - [Azure ServiceBus](docs/provider_azure_servicebus.md) + - [Google Cloud Pub/Sub](docs/provider_google_pubsub.md) - [Hybrid](docs/provider_hybrid.md) - [MQTT](docs/provider_mqtt.md) - [Memory](docs/provider_memory.md) @@ -152,6 +153,7 @@ The configuration can be [modularized](docs/intro.md#modularization-of-configura | `.Host.AmazonSQS` | Transport provider for Amazon SQS / SNS | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.AmazonSQS.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.AmazonSQS) | | `.Host.AzureEventHub` | Transport provider for Azure Event Hubs | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.AzureEventHub.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.AzureEventHub) | | `.Host.AzureServiceBus` | Transport provider for Azure Service Bus | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.AzureServiceBus.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.AzureServiceBus) | +| `.Host.GooglePubSub` | Transport provider for Google Cloud Pub/Sub | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.GooglePubSub.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.GooglePubSub) | | `.Host.Kafka` | Transport provider for Apache Kafka | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.Kafka.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.Kafka) | | `.Host.MQTT` | Transport provider for MQTT | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.MQTT.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.MQTT) | | `.Host.Memory` | Transport provider implementation for in-process (in memory) message passing (no messaging infrastructure required) | [![NuGet](https://img.shields.io/nuget/v/SlimMessageBus.Host.Memory.svg)](https://www.nuget.org/packages/SlimMessageBus.Host.Memory) | diff --git a/build/tasks.ps1 b/build/tasks.ps1 index d2b660cf..256559e7 100644 --- a/build/tasks.ps1 +++ b/build/tasks.ps1 @@ -28,6 +28,7 @@ $projects = @( "SlimMessageBus.Host.Kafka", "SlimMessageBus.Host.AzureEventHub", "SlimMessageBus.Host.AzureServiceBus", + "SlimMessageBus.Host.GooglePubSub", "SlimMessageBus.Host.Memory", "SlimMessageBus.Host.Redis", "SlimMessageBus.Host.Mqtt", diff --git a/docs/README.md b/docs/README.md index 820c65a3..18f339c7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,8 +5,9 @@ - [Amazon SQS/SNS](provider_amazon_sqs.md) - [Apache Kafka](provider_kafka.md) - [Azure EventHubs](provider_azure_eventhubs.md) - - [Azure ServiceBus](provider_azure_servicebus.md) - - [Hybrid](provider_hybrid.md) + - [Azure ServiceBus](provider_azure_servicebus.md) + - [Google Cloud Pub/Sub](provider_google_pubsub.md) + - [Hybrid](provider_hybrid.md) - [MQTT](provider_mqtt.md) - [Memory](provider_memory.md) - [NATS](provider_nats.md) diff --git a/docs/provider_google_pubsub.md b/docs/provider_google_pubsub.md new file mode 100644 index 00000000..1d3c608a --- /dev/null +++ b/docs/provider_google_pubsub.md @@ -0,0 +1,267 @@ ++# SlimMessageBus - Google Cloud Pub/Sub Transport + +Before using this provider, read the [Introduction](intro.md). + +## Installation + +Install the transport and a serializer: + +```shell +dotnet add package SlimMessageBus.Host.GooglePubSub +dotnet add package SlimMessageBus.Host.Serialization.SystemTextJson +``` + +Then import the provider namespace: + +```csharp +using SlimMessageBus.Host.GooglePubSub; +``` + +This provider supports standard Google Cloud Pub/Sub topics and pull subscriptions. Pub/Sub Lite is not supported because Google shut down that service on March 18, 2026. + +## Basic configuration + +```csharp +services.AddSlimMessageBus(mbb => +{ + mbb.WithProviderGooglePubSub(settings => + { + settings.ProjectId = "my-google-cloud-project"; + }); + + mbb.AddJsonSerializer(); + + mbb.Produce(x => x + .DefaultTopic("orders")); + + mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .WithConsumer()); +}); +``` + +`ProjectId` is used to turn short IDs such as `orders` into full Google resource names. Fully qualified names such as `projects/another-project/topics/orders` are also accepted. + +Each consumer needs a subscription name. Google subscription IDs are unique within a project and a subscription belongs to exactly one topic, so use a distinct subscription for each independently consuming application or consumer group. + +## Authentication + +### Application Default Credentials + +[Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) are used automatically when no client factories or explicit credentials are configured. This is the recommended configuration. + +ADC searches for credentials in Google's standard order, including: + +- the service account attached to the Google Cloud runtime; +- credentials referenced by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable; +- local development credentials created by `gcloud auth application-default login`. + +On Google Cloud, attach a service account to the workload and grant only the roles it requires. Applications that publish and consume normally need `roles/pubsub.publisher` and `roles/pubsub.subscriber`. Because topology provisioning is enabled by default, the identity also needs permission to inspect and create topics and subscriptions, for example `roles/pubsub.editor`. If infrastructure is provisioned separately, disable topology provisioning and omit the administrative role. + +### Credential JSON file + +A trusted service-account credential file can be selected explicitly: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.UseCredentialsPath(configuration["GoogleCloud:CredentialsPath"]); +}); +``` + +Do not commit credential JSON files to source control. Prefer workload identity or an attached service account in production. + +An already constructed `GoogleCredential` can also be supplied (`using Google.Apis.Auth.OAuth2;`): + +```csharp +GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(); + +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.UseGoogleCredential(credential); +}); +``` + +The four client factories on `GooglePubSubMessageBusSettings` can be replaced when credentials, endpoints, channel counts, or other native client settings need to be controlled separately. + +### API keys + +[Google Cloud Pub/Sub does not support API keys](https://cloud.google.com/pubsub/docs/authentication) as an authentication method. Use OAuth 2.0 credentials through ADC, a service account, workload identity federation, or another `GoogleCredential`. + +## Producing messages + +Declare a default topic and publish normally: + +```csharp +mbb.Produce(x => x.DefaultTopic("orders")); + +await bus.Publish(new OrderCreated(...)); +``` + +A native `PubsubMessage` can be customized globally or per producer: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.WithModifier((message, transportMessage) => + { + transportMessage.Attributes["application"] = "billing"; + }); +}); + +mbb.Produce(x => x + .DefaultTopic("orders") + .WithModifier((message, transportMessage) => + { + transportMessage.OrderingKey = message.CustomerId; + })); +``` + +If ordering keys are used, configure the native publisher to enable ordering and enable ordering on the provisioned subscription: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.PublisherClientFactory = (_, topic, cancellationToken) => + new PublisherClientBuilder + { + TopicName = topic, + Settings = new PublisherClient.Settings + { + EnableMessageOrdering = true + } + }.BuildAsync(cancellationToken); +}); + +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .CreateSubscriptionOptions(subscription => + { + subscription.EnableMessageOrdering = true; + }) + .WithConsumer()); +``` + +Publisher clients are cached per topic and disposed with the bus. + +## Consuming messages + +Consumers use Google pull subscriptions: + +```csharp +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .Instances(8) + .WithConsumer()); +``` + +Successful processing acknowledges the Pub/Sub message. A failed message is negatively acknowledged and becomes eligible for redelivery according to its subscription retry and dead-letter policies. + +The native message and subscription name are available from `IConsumerContext`: + +```csharp +public class BillingConsumer(IConsumerContext context) : IConsumer +{ + public Task OnHandle(OrderCreated message, CancellationToken cancellationToken) + { + PubsubMessage transportMessage = context.GetTransportMessage(); + string subscriptionName = context.GetSubscriptionName(); + + return Task.CompletedTask; + } +} +``` + +A transport-specific error handler can implement `IGooglePubSubConsumerErrorHandler` or derive from `GooglePubSubConsumerErrorHandler`. + +## Request-response + +Configure a reply topic and a dedicated subscription for the application instance: + +```csharp +mbb.ExpectRequestResponses(x => x + .ReplyToTopic("billing-responses") + .SubscriptionName("billing-api-instance-1") + .DefaultTimeout(TimeSpan.FromSeconds(30))); +``` + +The request handler publishes responses to the reply topic. The requester receives them through the configured pull subscription. Each simultaneously running requester needs its own subscription name. + +## Topology provisioning + +Topology provisioning is enabled by default. At startup the provider creates missing declared topics and subscriptions; it does not update existing resources. + +Disable it when Terraform, Pulumi, Deployment Manager, or another system owns the infrastructure: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.TopologyProvisioning.Enabled = false; +}); +``` + +Creation permissions can be controlled independently: + +```csharp +settings.TopologyProvisioning.CanProducerCreateTopic = false; +settings.TopologyProvisioning.CanConsumerCreateTopic = true; +settings.TopologyProvisioning.CanConsumerCreateSubscription = true; +``` + +Global native creation options apply to every newly created resource: + +```csharp +settings.TopologyProvisioning.CreateTopicOptions = topic => +{ + topic.Labels["application"] = "billing"; +}; + +settings.TopologyProvisioning.CreateSubscriptionOptions = subscription => +{ + subscription.AckDeadlineSeconds = 60; +}; +``` + +They can be refined on individual declarations (`using Google.Protobuf.WellKnownTypes;` for `Duration`): + +```csharp +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .CreateSubscriptionOptions(subscription => + { + subscription.Filter = "attributes.region = \"eu\""; + subscription.EnableExactlyOnceDelivery = true; + subscription.RetryPolicy = new RetryPolicy + { + MinimumBackoff = Duration.FromTimeSpan(TimeSpan.FromSeconds(10)), + MaximumBackoff = Duration.FromTimeSpan(TimeSpan.FromMinutes(5)) + }; + subscription.DeadLetterPolicy = new DeadLetterPolicy + { + DeadLetterTopic = "projects/my-google-cloud-project/topics/orders-dead-letter", + MaxDeliveryAttempts = 10 + }; + }) + .WithConsumer()); +``` + +Only pull subscriptions are supported. Configuring push, BigQuery, or Cloud Storage delivery on a SlimMessageBus consumer is rejected. + +## Headers + +Pub/Sub attributes contain string values, while SlimMessageBus headers can contain objects. `DefaultGooglePubSubHeaderSerializer` adds type markers for common primitives, GUIDs, `DateTime`, and `DateTimeOffset` so their types survive a round trip. Plain string values remain unchanged. + +Replace `GooglePubSubMessageBusSettings.HeaderSerializer` with an `IGooglePubSubHeaderSerializer` implementation when another wire format is required. + +## Emulator + +Set `PUBSUB_EMULATOR_HOST` and replace the four client factories with builders configured with `EmulatorDetection.EmulatorOrProduction`. The factories are exposed on `GooglePubSubMessageBusSettings` so publisher, subscriber, and topology clients can all use the same emulator endpoint. diff --git a/docs/provider_google_pubsub.t.md b/docs/provider_google_pubsub.t.md new file mode 100644 index 00000000..1d3c608a --- /dev/null +++ b/docs/provider_google_pubsub.t.md @@ -0,0 +1,267 @@ ++# SlimMessageBus - Google Cloud Pub/Sub Transport + +Before using this provider, read the [Introduction](intro.md). + +## Installation + +Install the transport and a serializer: + +```shell +dotnet add package SlimMessageBus.Host.GooglePubSub +dotnet add package SlimMessageBus.Host.Serialization.SystemTextJson +``` + +Then import the provider namespace: + +```csharp +using SlimMessageBus.Host.GooglePubSub; +``` + +This provider supports standard Google Cloud Pub/Sub topics and pull subscriptions. Pub/Sub Lite is not supported because Google shut down that service on March 18, 2026. + +## Basic configuration + +```csharp +services.AddSlimMessageBus(mbb => +{ + mbb.WithProviderGooglePubSub(settings => + { + settings.ProjectId = "my-google-cloud-project"; + }); + + mbb.AddJsonSerializer(); + + mbb.Produce(x => x + .DefaultTopic("orders")); + + mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .WithConsumer()); +}); +``` + +`ProjectId` is used to turn short IDs such as `orders` into full Google resource names. Fully qualified names such as `projects/another-project/topics/orders` are also accepted. + +Each consumer needs a subscription name. Google subscription IDs are unique within a project and a subscription belongs to exactly one topic, so use a distinct subscription for each independently consuming application or consumer group. + +## Authentication + +### Application Default Credentials + +[Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) are used automatically when no client factories or explicit credentials are configured. This is the recommended configuration. + +ADC searches for credentials in Google's standard order, including: + +- the service account attached to the Google Cloud runtime; +- credentials referenced by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable; +- local development credentials created by `gcloud auth application-default login`. + +On Google Cloud, attach a service account to the workload and grant only the roles it requires. Applications that publish and consume normally need `roles/pubsub.publisher` and `roles/pubsub.subscriber`. Because topology provisioning is enabled by default, the identity also needs permission to inspect and create topics and subscriptions, for example `roles/pubsub.editor`. If infrastructure is provisioned separately, disable topology provisioning and omit the administrative role. + +### Credential JSON file + +A trusted service-account credential file can be selected explicitly: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.UseCredentialsPath(configuration["GoogleCloud:CredentialsPath"]); +}); +``` + +Do not commit credential JSON files to source control. Prefer workload identity or an attached service account in production. + +An already constructed `GoogleCredential` can also be supplied (`using Google.Apis.Auth.OAuth2;`): + +```csharp +GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(); + +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.UseGoogleCredential(credential); +}); +``` + +The four client factories on `GooglePubSubMessageBusSettings` can be replaced when credentials, endpoints, channel counts, or other native client settings need to be controlled separately. + +### API keys + +[Google Cloud Pub/Sub does not support API keys](https://cloud.google.com/pubsub/docs/authentication) as an authentication method. Use OAuth 2.0 credentials through ADC, a service account, workload identity federation, or another `GoogleCredential`. + +## Producing messages + +Declare a default topic and publish normally: + +```csharp +mbb.Produce(x => x.DefaultTopic("orders")); + +await bus.Publish(new OrderCreated(...)); +``` + +A native `PubsubMessage` can be customized globally or per producer: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.WithModifier((message, transportMessage) => + { + transportMessage.Attributes["application"] = "billing"; + }); +}); + +mbb.Produce(x => x + .DefaultTopic("orders") + .WithModifier((message, transportMessage) => + { + transportMessage.OrderingKey = message.CustomerId; + })); +``` + +If ordering keys are used, configure the native publisher to enable ordering and enable ordering on the provisioned subscription: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.PublisherClientFactory = (_, topic, cancellationToken) => + new PublisherClientBuilder + { + TopicName = topic, + Settings = new PublisherClient.Settings + { + EnableMessageOrdering = true + } + }.BuildAsync(cancellationToken); +}); + +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .CreateSubscriptionOptions(subscription => + { + subscription.EnableMessageOrdering = true; + }) + .WithConsumer()); +``` + +Publisher clients are cached per topic and disposed with the bus. + +## Consuming messages + +Consumers use Google pull subscriptions: + +```csharp +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .Instances(8) + .WithConsumer()); +``` + +Successful processing acknowledges the Pub/Sub message. A failed message is negatively acknowledged and becomes eligible for redelivery according to its subscription retry and dead-letter policies. + +The native message and subscription name are available from `IConsumerContext`: + +```csharp +public class BillingConsumer(IConsumerContext context) : IConsumer +{ + public Task OnHandle(OrderCreated message, CancellationToken cancellationToken) + { + PubsubMessage transportMessage = context.GetTransportMessage(); + string subscriptionName = context.GetSubscriptionName(); + + return Task.CompletedTask; + } +} +``` + +A transport-specific error handler can implement `IGooglePubSubConsumerErrorHandler` or derive from `GooglePubSubConsumerErrorHandler`. + +## Request-response + +Configure a reply topic and a dedicated subscription for the application instance: + +```csharp +mbb.ExpectRequestResponses(x => x + .ReplyToTopic("billing-responses") + .SubscriptionName("billing-api-instance-1") + .DefaultTimeout(TimeSpan.FromSeconds(30))); +``` + +The request handler publishes responses to the reply topic. The requester receives them through the configured pull subscription. Each simultaneously running requester needs its own subscription name. + +## Topology provisioning + +Topology provisioning is enabled by default. At startup the provider creates missing declared topics and subscriptions; it does not update existing resources. + +Disable it when Terraform, Pulumi, Deployment Manager, or another system owns the infrastructure: + +```csharp +mbb.WithProviderGooglePubSub(settings => +{ + settings.ProjectId = "my-google-cloud-project"; + settings.TopologyProvisioning.Enabled = false; +}); +``` + +Creation permissions can be controlled independently: + +```csharp +settings.TopologyProvisioning.CanProducerCreateTopic = false; +settings.TopologyProvisioning.CanConsumerCreateTopic = true; +settings.TopologyProvisioning.CanConsumerCreateSubscription = true; +``` + +Global native creation options apply to every newly created resource: + +```csharp +settings.TopologyProvisioning.CreateTopicOptions = topic => +{ + topic.Labels["application"] = "billing"; +}; + +settings.TopologyProvisioning.CreateSubscriptionOptions = subscription => +{ + subscription.AckDeadlineSeconds = 60; +}; +``` + +They can be refined on individual declarations (`using Google.Protobuf.WellKnownTypes;` for `Duration`): + +```csharp +mbb.Consume(x => x + .Topic("orders") + .SubscriptionName("orders-billing") + .CreateSubscriptionOptions(subscription => + { + subscription.Filter = "attributes.region = \"eu\""; + subscription.EnableExactlyOnceDelivery = true; + subscription.RetryPolicy = new RetryPolicy + { + MinimumBackoff = Duration.FromTimeSpan(TimeSpan.FromSeconds(10)), + MaximumBackoff = Duration.FromTimeSpan(TimeSpan.FromMinutes(5)) + }; + subscription.DeadLetterPolicy = new DeadLetterPolicy + { + DeadLetterTopic = "projects/my-google-cloud-project/topics/orders-dead-letter", + MaxDeliveryAttempts = 10 + }; + }) + .WithConsumer()); +``` + +Only pull subscriptions are supported. Configuring push, BigQuery, or Cloud Storage delivery on a SlimMessageBus consumer is rejected. + +## Headers + +Pub/Sub attributes contain string values, while SlimMessageBus headers can contain objects. `DefaultGooglePubSubHeaderSerializer` adds type markers for common primitives, GUIDs, `DateTime`, and `DateTimeOffset` so their types survive a round trip. Plain string values remain unchanged. + +Replace `GooglePubSubMessageBusSettings.HeaderSerializer` with an `IGooglePubSubHeaderSerializer` implementation when another wire format is required. + +## Emulator + +Set `PUBSUB_EMULATOR_HOST` and replace the four client factories with builders configured with `EmulatorDetection.EmulatorOrProduction`. The factories are exposed on `GooglePubSubMessageBusSettings` so publisher, subscriber, and topology clients can all use the same emulator endpoint. diff --git a/src/Host.Plugin.Properties.xml b/src/Host.Plugin.Properties.xml index 0e2fc918..7c3b304d 100644 --- a/src/Host.Plugin.Properties.xml +++ b/src/Host.Plugin.Properties.xml @@ -3,6 +3,6 @@ - 3.6.0-rc100 + 3.6.0-rc101 diff --git a/src/SlimMessageBus.Host.Configuration/SlimMessageBus.Host.Configuration.csproj b/src/SlimMessageBus.Host.Configuration/SlimMessageBus.Host.Configuration.csproj index 0677d0bd..18c2443a 100644 --- a/src/SlimMessageBus.Host.Configuration/SlimMessageBus.Host.Configuration.csproj +++ b/src/SlimMessageBus.Host.Configuration/SlimMessageBus.Host.Configuration.csproj @@ -5,7 +5,7 @@ Core configuration interfaces of SlimMessageBus SlimMessageBus SlimMessageBus.Host - 3.5.0 + 3.6.0-rc101 diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/Delegates.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/Delegates.cs new file mode 100644 index 00000000..a0297858 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/Delegates.cs @@ -0,0 +1,15 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +/// +/// Allows the native Google Cloud Pub/Sub message to be customized before it is published. +/// +public delegate void GooglePubSubMessageModifier(T message, PubsubMessage transportMessage); + +/// +/// Intercepts topology provisioning and can run custom logic before or after it. +/// +public delegate Task GooglePubSubTopologyInterceptor( + PublisherServiceApiClient publisherClient, + SubscriberServiceApiClient subscriberClient, + Func provision, + CancellationToken cancellationToken); diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubConsumerBuilderExtensions.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubConsumerBuilderExtensions.cs new file mode 100644 index 00000000..e525fd16 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubConsumerBuilderExtensions.cs @@ -0,0 +1,34 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public static class GooglePubSubConsumerBuilderExtensions +{ + public static TBuilder SubscriptionName(this TBuilder builder, string subscriptionName) + where TBuilder : IAbstractConsumerBuilder + { + if (builder is null) throw new ArgumentNullException(nameof(builder)); + if (subscriptionName is null) throw new ArgumentNullException(nameof(subscriptionName)); + + builder.ConsumerSettings.SetSubscriptionName(subscriptionName); + return builder; + } + + public static TBuilder CreateTopicOptions(this TBuilder builder, Action configure) + where TBuilder : IAbstractConsumerBuilder + { + if (builder is null) throw new ArgumentNullException(nameof(builder)); + if (configure is null) throw new ArgumentNullException(nameof(configure)); + + GooglePubSubProperties.CreateTopicOptions.Set(builder.ConsumerSettings, configure); + return builder; + } + + public static TBuilder CreateSubscriptionOptions(this TBuilder builder, Action configure) + where TBuilder : IAbstractConsumerBuilder + { + if (builder is null) throw new ArgumentNullException(nameof(builder)); + if (configure is null) throw new ArgumentNullException(nameof(configure)); + + GooglePubSubProperties.CreateSubscriptionOptions.Set(builder.ConsumerSettings, configure); + return builder; + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProducerBuilderExtensions.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProducerBuilderExtensions.cs new file mode 100644 index 00000000..5e5b097e --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProducerBuilderExtensions.cs @@ -0,0 +1,22 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public static class GooglePubSubProducerBuilderExtensions +{ + public static ProducerBuilder WithModifier(this ProducerBuilder builder, GooglePubSubMessageModifier modifier) + { + if (builder is null) throw new ArgumentNullException(nameof(builder)); + if (modifier is null) throw new ArgumentNullException(nameof(modifier)); + + GooglePubSubProperties.MessageModifier.Set(builder.Settings, (message, transportMessage) => modifier((T)message, transportMessage)); + return builder; + } + + public static ProducerBuilder CreateTopicOptions(this ProducerBuilder builder, Action configure) + { + if (builder is null) throw new ArgumentNullException(nameof(builder)); + if (configure is null) throw new ArgumentNullException(nameof(configure)); + + GooglePubSubProperties.CreateTopicOptions.Set(builder.Settings, configure); + return builder; + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProperties.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProperties.cs new file mode 100644 index 00000000..ef17dfb5 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubProperties.cs @@ -0,0 +1,9 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +internal static class GooglePubSubProperties +{ + internal static readonly ProviderExtensionProperty SubscriptionName = new("GooglePubSub_SubscriptionName"); + internal static readonly ProviderExtensionProperty> MessageModifier = new("GooglePubSub_MessageModifier"); + internal static readonly ProviderExtensionProperty> CreateTopicOptions = new("GooglePubSub_CreateTopicOptions"); + internal static readonly ProviderExtensionProperty> CreateSubscriptionOptions = new("GooglePubSub_CreateSubscriptionOptions"); +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubSettingsExtensions.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubSettingsExtensions.cs new file mode 100644 index 00000000..ef546dcb --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/GooglePubSubSettingsExtensions.cs @@ -0,0 +1,10 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +internal static class GooglePubSubSettingsExtensions +{ + internal static string GetSubscriptionName(this AbstractConsumerSettings settings) + => settings.GetOrDefault(GooglePubSubProperties.SubscriptionName); + + internal static void SetSubscriptionName(this HasProviderExtensions settings, string subscriptionName) + => GooglePubSubProperties.SubscriptionName.Set(settings, subscriptionName); +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Config/MessageBusBuilderExtensions.cs b/src/SlimMessageBus.Host.GooglePubSub/Config/MessageBusBuilderExtensions.cs new file mode 100644 index 00000000..be17e4b3 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Config/MessageBusBuilderExtensions.cs @@ -0,0 +1,18 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public static class MessageBusBuilderExtensions +{ + /// + /// Configures Google Cloud Pub/Sub as the transport provider. + /// + public static MessageBusBuilder WithProviderGooglePubSub(this MessageBusBuilder mbb, Action configure) + { + if (mbb is null) throw new ArgumentNullException(nameof(mbb)); + if (configure is null) throw new ArgumentNullException(nameof(configure)); + + var providerSettings = new GooglePubSubMessageBusSettings(); + configure(providerSettings); + + return mbb.WithProvider(settings => new GooglePubSubMessageBus(settings, providerSettings)); + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumer.cs b/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumer.cs new file mode 100644 index 00000000..15edf0a8 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumer.cs @@ -0,0 +1,116 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public class GooglePubSubConsumer : AbstractConsumer +{ + private readonly GooglePubSubMessageBus _messageBus; + private readonly SubscriptionName _subscriptionName; + private readonly IMessageProcessor _messageProcessor; + private readonly int _concurrency; + private SubscriberClient _subscriberClient; + private SemaphoreSlim _concurrencySemaphore; + private Task _subscriberTask; + + public GooglePubSubConsumer( + GooglePubSubMessageBus messageBus, + SubscriptionName subscriptionName, + IMessageProcessor messageProcessor, + IEnumerable consumerSettings) + : base( + messageBus.LoggerFactory.CreateLogger(), + consumerSettings, + subscriptionName.ToString(), + messageBus.Settings.ServiceProvider.GetServices()) + { + _messageBus = messageBus; + _subscriptionName = subscriptionName; + _messageProcessor = messageProcessor; + + var concurrencyValues = Settings.Select(x => x.Instances).Distinct().ToList(); + if (concurrencyValues.Count > 1) + { + throw new ConfigurationMessageBusException($"All consumers on subscription {_subscriptionName} must use the same Instances setting."); + } + _concurrency = concurrencyValues.SingleOrDefault(); + if (_concurrency <= 0) + { + _concurrency = 1; + } + } + + protected override async Task OnStart() + { + _concurrencySemaphore = new SemaphoreSlim(_concurrency, _concurrency); + _subscriberClient = await _messageBus.ProviderSettings.SubscriberClientFactory( + _messageBus.Settings.ServiceProvider, + _subscriptionName, + CancellationToken).ConfigureAwait(false); + + if (Logger.IsEnabled(LogLevel.Information)) + { + Logger.LogInformation("Starting Google Pub/Sub consumer for subscription {Subscription}", _subscriptionName); + } + _subscriberTask = _subscriberClient.StartAsync(ProcessMessage); + } + + private async Task ProcessMessage(PubsubMessage message, CancellationToken cancellationToken) + { + await _concurrencySemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (cancellationToken.IsCancellationRequested) + { + return SubscriberClient.Reply.Nack; + } + + var headers = _messageBus.DeserializeHeaders(message.Attributes); + var result = await _messageProcessor.ProcessMessage(message, headers, cancellationToken: cancellationToken).ConfigureAwait(false); + + if (result.Result is ProcessResult.SuccessState) + { + if (Logger.IsEnabled(LogLevel.Debug)) + { + Logger.LogDebug("Acknowledging Pub/Sub message {MessageId} on subscription {Subscription}", message.MessageId, _subscriptionName); + } + return SubscriberClient.Reply.Ack; + } + + if (Logger.IsEnabled(LogLevel.Warning)) + { + Logger.LogWarning(result.Exception, "Negatively acknowledging Pub/Sub message {MessageId} on subscription {Subscription}", message.MessageId, _subscriptionName); + } + return SubscriberClient.Reply.Nack; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return SubscriberClient.Reply.Nack; + } + finally + { + _concurrencySemaphore.Release(); + } + } + + protected override async Task OnStop() + { + if (_subscriberClient == null) + { + return; + } + + if (Logger.IsEnabled(LogLevel.Information)) + { + Logger.LogInformation("Stopping Google Pub/Sub consumer for subscription {Subscription}", _subscriptionName); + } + await _subscriberClient.StopAsync(new SubscriberClient.ShutdownOptions(), CancellationToken.None).ConfigureAwait(false); + if (_subscriberTask != null) + { + await _subscriberTask.ConfigureAwait(false); + _subscriberTask = null; + } + await _subscriberClient.DisposeAsync().ConfigureAwait(false); + _subscriberClient = null; + + _concurrencySemaphore?.Dispose(); + _concurrencySemaphore = null; + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumerContextExtensions.cs b/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumerContextExtensions.cs new file mode 100644 index 00000000..bc85b607 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Consumer/GooglePubSubConsumerContextExtensions.cs @@ -0,0 +1,25 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public static class GooglePubSubConsumerContextExtensions +{ + private const string MessageKey = "GooglePubSub_Message"; + private const string SubscriptionNameKey = "GooglePubSub_SubscriptionName"; + + public static PubsubMessage GetTransportMessage(this IConsumerContext context) + { + if (context is null) throw new ArgumentNullException(nameof(context)); + return context.GetPropertyOrDefault(MessageKey); + } + + public static string GetSubscriptionName(this IConsumerContext context) + { + if (context is null) throw new ArgumentNullException(nameof(context)); + return context.GetPropertyOrDefault(SubscriptionNameKey); + } + + internal static void SetTransportMessage(this ConsumerContext context, PubsubMessage message) + => context.Properties[MessageKey] = message; + + internal static void SetSubscriptionName(this ConsumerContext context, string subscriptionName) + => context.Properties[SubscriptionNameKey] = subscriptionName; +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Consumer/IGooglePubSubConsumerErrorHandler.cs b/src/SlimMessageBus.Host.GooglePubSub/Consumer/IGooglePubSubConsumerErrorHandler.cs new file mode 100644 index 00000000..4deff783 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Consumer/IGooglePubSubConsumerErrorHandler.cs @@ -0,0 +1,6 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public interface IGooglePubSubConsumerErrorHandler : IConsumerErrorHandler; + +public abstract class GooglePubSubConsumerErrorHandler + : ConsumerErrorHandler, IGooglePubSubConsumerErrorHandler; diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBus.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBus.cs new file mode 100644 index 00000000..befa1cdd --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBus.cs @@ -0,0 +1,270 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +using System.Collections.Concurrent; + +public class GooglePubSubMessageBus : MessageBusBase +{ + private readonly ILogger _logger; + private readonly ConcurrentDictionary>> _publishers = new(StringComparer.Ordinal); + private GooglePubSubTopologyService _topologyService; + + public GooglePubSubMessageBus(MessageBusSettings settings, GooglePubSubMessageBusSettings providerSettings) + : base(settings, providerSettings) + { + _logger = LoggerFactory.CreateLogger(); + OnBuildProvider(); + } + + protected override IMessageBusSettingsValidationService ValidationService + => new GooglePubSubMessageBusSettingsValidationService(Settings, ProviderSettings); + + protected override void Build() + { + base.Build(); + + if (ProviderSettings.TopologyProvisioning?.Enabled ?? false) + { + if (ProviderSettings.PublisherServiceApiClientFactory == null) + { + throw new ConfigurationMessageBusException($"The {nameof(ProviderSettings.PublisherServiceApiClientFactory)} is not set while topology provisioning is enabled"); + } + if (ProviderSettings.SubscriberServiceApiClientFactory == null) + { + throw new ConfigurationMessageBusException($"The {nameof(ProviderSettings.SubscriberServiceApiClientFactory)} is not set while topology provisioning is enabled"); + } + + InitTaskList.Add(InitializeTopology, CancellationToken); + } + } + + private async Task InitializeTopology() + { + var publisherServiceApiClient = await ProviderSettings.PublisherServiceApiClientFactory(Settings.ServiceProvider, CancellationToken).ConfigureAwait(false); + var subscriberServiceApiClient = await ProviderSettings.SubscriberServiceApiClientFactory(Settings.ServiceProvider, CancellationToken).ConfigureAwait(false); + _topologyService = new GooglePubSubTopologyService( + LoggerFactory.CreateLogger(), + Settings, + ProviderSettings, + publisherServiceApiClient, + subscriberServiceApiClient); + + await ProvisionTopology().ConfigureAwait(false); + } + + public override async Task ProvisionTopology() + { + await base.ProvisionTopology().ConfigureAwait(false); + if (_topologyService != null) + { + await _topologyService.Provision(CancellationToken).ConfigureAwait(false); + } + } + + protected override async Task CreateConsumers() + { + await base.CreateConsumers().ConfigureAwait(false); + + MessageProvider GetMessageProvider(string path) + => SerializerProvider.GetSerializer(path).GetMessageProvider(message => message.Data.ToByteArray()); + + void AddSubscriptionConsumer( + string topic, + string subscription, + IMessageProcessor messageProcessor, + IEnumerable consumerSettings) + { + var subscriptionName = GooglePubSubResourceName.ResolveSubscription(ProviderSettings.ProjectId, subscription); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Creating Google Pub/Sub consumer for topic {Topic}, subscription {Subscription}", topic, subscriptionName); + } + AddConsumer(new GooglePubSubConsumer(this, subscriptionName, messageProcessor, consumerSettings)); + } + + foreach (var group in Settings.Consumers.GroupBy(x => (Topic: x.Path, Subscription: x.GetSubscriptionName()))) + { + var consumerSettings = group.ToList(); + var topic = group.Key.Topic; + var subscription = group.Key.Subscription; + + void InitializeConsumerContext(PubsubMessage message, ConsumerContext context) + { + context.SetTransportMessage(message); + context.SetSubscriptionName(subscription); + } + + var processor = new MessageProcessor( + consumerSettings, + this, + messageProvider: GetMessageProvider(topic), + path: topic, + responseProducer: this, + consumerContextInitializer: InitializeConsumerContext, + consumerErrorHandlerOpenGenericType: typeof(IGooglePubSubConsumerErrorHandler<>)); + + AddSubscriptionConsumer(topic, subscription, processor, consumerSettings); + } + + if (Settings.RequestResponse != null) + { + var topic = Settings.RequestResponse.Path; + var subscription = Settings.RequestResponse.GetSubscriptionName(); + var processor = new ResponseMessageProcessor( + LoggerFactory, + Settings.RequestResponse, + GetMessageProvider(topic), + PendingRequestStore, + TimeProvider); + + AddSubscriptionConsumer(topic, subscription, processor, [Settings.RequestResponse]); + } + } + + internal IReadOnlyDictionary DeserializeHeaders(IDictionary attributes) + { + if (attributes == null || attributes.Count == 0) + { + return new Dictionary(); + } + + return attributes.ToDictionary( + item => item.Key, + item => ProviderSettings.HeaderSerializer.Deserialize(item.Key, item.Value)); + } + + private Task GetPublisher(string path) + { + var lazyPublisher = _publishers.GetOrAdd(path, topicPath => + new Lazy>( + () => ProviderSettings.PublisherClientFactory( + Settings.ServiceProvider, + GooglePubSubResourceName.ResolveTopic(ProviderSettings.ProjectId, topicPath), + CancellationToken), + LazyThreadSafetyMode.ExecutionAndPublication)); + + return lazyPublisher.Value; + } + + private PubsubMessage CreateTransportMessage( + object message, + Type messageType, + string path, + IDictionary messageHeaders) + { + OnProduceToTransport(message, messageType, path, messageHeaders); + + var transportMessage = new PubsubMessage(); + if (message != null) + { + var payload = SerializerProvider.GetSerializer(path).Serialize(messageType, messageHeaders, message, transportMessage); + transportMessage.Data = ByteString.CopyFrom(payload); + } + + if (messageHeaders != null) + { + foreach (var header in messageHeaders) + { + transportMessage.Attributes[header.Key] = ProviderSettings.HeaderSerializer.Serialize(header.Key, header.Value); + } + } + + InvokeModifier(message, messageType, transportMessage, ProviderSettings); + if (messageType != null) + { + InvokeModifier(message, messageType, transportMessage, GetProducerSettings(messageType)); + } + + return transportMessage; + } + + private void InvokeModifier(object message, Type messageType, PubsubMessage transportMessage, HasProviderExtensions settings) + { + try + { + settings.GetOrDefault(GooglePubSubProperties.MessageModifier)?.Invoke(message, transportMessage); + } + catch (Exception exception) + { + _logger.LogWarning(exception, "The Google Pub/Sub message modifier failed for message type {MessageType}", messageType); + } + } + + public override async Task ProduceToTransport( + object message, + Type messageType, + string path, + IDictionary messageHeaders, + IMessageBusTarget targetBus, + CancellationToken cancellationToken) + { + try + { + var publisher = await GetPublisher(path).ConfigureAwait(false); + var transportMessage = CreateTransportMessage(message, messageType, path, messageHeaders); + try + { + await publisher.PublishAsync(transportMessage).ConfigureAwait(false); + } + catch (RpcException exception) when (exception.StatusCode == StatusCode.NotFound && _topologyService != null) + { + var producerSettings = GetProducerSettings(messageType); + await _topologyService.EnsureTopic( + path, + ProviderSettings.TopologyProvisioning.CanProducerCreateTopic, + [producerSettings.GetOrDefault(GooglePubSubProperties.CreateTopicOptions)], + cancellationToken).ConfigureAwait(false); + await publisher.PublishAsync(transportMessage).ConfigureAwait(false); + } + } + catch (Exception exception) when (exception is not ProducerMessageBusException && exception is not TaskCanceledException) + { + throw new ProducerMessageBusException(GetProducerErrorMessage(path, message, messageType, exception), exception); + } + } + + public override async Task> ProduceToTransportBulk( + IReadOnlyCollection envelopes, + string path, + IMessageBusTarget targetBus, + CancellationToken cancellationToken) + { + var dispatched = new List(envelopes.Count); + try + { + var publisher = await GetPublisher(path).ConfigureAwait(false); + var publishes = envelopes.Select(async envelope => + { + await publisher.PublishAsync(CreateTransportMessage(envelope.Message, envelope.MessageType, path, envelope.Headers)).ConfigureAwait(false); + lock (dispatched) + { + dispatched.Add(envelope); + } + }); + + cancellationToken.ThrowIfCancellationRequested(); + await Task.WhenAll(publishes).ConfigureAwait(false); + return new(dispatched, null); + } + catch (Exception exception) + { + _logger.LogError(exception, "Publishing a Google Pub/Sub message batch to {Topic} failed", path); + return new(dispatched, exception); + } + } + + protected override async ValueTask DisposeAsyncCore() + { + await base.DisposeAsyncCore().ConfigureAwait(false); + + var publisherTasks = _publishers.Values.Where(x => x.IsValueCreated).Select(x => x.Value).ToList(); + _publishers.Clear(); + if (publisherTasks.Count > 0) + { + var publishers = await Task.WhenAll(publisherTasks).ConfigureAwait(false); + foreach (var publisher in publishers) + { + await publisher.DisposeAsync().ConfigureAwait(false); + } + } + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettings.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettings.cs new file mode 100644 index 00000000..a0aa5fec --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettings.cs @@ -0,0 +1,108 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public class GooglePubSubMessageBusSettings : HasProviderExtensions +{ + /// + /// Google Cloud project used when topic and subscription IDs are not fully qualified resource names. + /// + public string ProjectId { get; set; } + + /// + /// Creates a long-lived publisher for a topic. Defaults to Application Default Credentials. + /// + public Func> PublisherClientFactory { get; set; } + = (_, topic, _) => PublisherClient.CreateAsync(topic); + + /// + /// Creates a long-lived pull subscriber. Defaults to Application Default Credentials. + /// + public Func> SubscriberClientFactory { get; set; } + = (_, subscription, _) => SubscriberClient.CreateAsync(subscription); + + /// + /// Creates the topic administration client used by topology provisioning. + /// + public Func> PublisherServiceApiClientFactory { get; set; } + = (_, _) => PublisherServiceApiClient.CreateAsync(); + + /// + /// Creates the subscription administration client used by topology provisioning. + /// + public Func> SubscriberServiceApiClientFactory { get; set; } + = (_, _) => SubscriberServiceApiClient.CreateAsync(); + + public IGooglePubSubHeaderSerializer HeaderSerializer { get; set; } = new DefaultGooglePubSubHeaderSerializer(); + + /// + /// Topology provisioning settings. Provisioning is enabled by default. + /// + public GooglePubSubTopologySettings TopologyProvisioning { get; set; } = new(); + + public GooglePubSubMessageBusSettings WithModifier(GooglePubSubMessageModifier modifier, bool executePrevious = true) + { + if (modifier is null) throw new ArgumentNullException(nameof(modifier)); + + var previous = executePrevious ? GetOrDefault(GooglePubSubProperties.MessageModifier) : null; + GooglePubSubProperties.MessageModifier.Set(this, previous == null + ? modifier + : (message, transportMessage) => + { + previous(message, transportMessage); + modifier(message, transportMessage); + }); + + return this; + } + + public GooglePubSubMessageBusSettings WithModifier(GooglePubSubMessageModifier modifier, bool executePrevious = true) + { + if (modifier is null) throw new ArgumentNullException(nameof(modifier)); + + return WithModifier((message, transportMessage) => + { + if (message is T typedMessage) + { + modifier(typedMessage, transportMessage); + } + }, executePrevious); + } + + /// + /// Uses a trusted service-account credential JSON file instead of Application Default Credentials. + /// + public GooglePubSubMessageBusSettings UseCredentialsPath(string credentialsPath) + { + if (credentialsPath is null) throw new ArgumentNullException(nameof(credentialsPath)); + var credential = CredentialFactory.FromFile(credentialsPath).ToGoogleCredential(); + return UseGoogleCredential(credential); + } + + /// + /// Uses an explicitly created Google credential instead of Application Default Credentials. + /// + public GooglePubSubMessageBusSettings UseGoogleCredential(GoogleCredential credential) + { + if (credential is null) throw new ArgumentNullException(nameof(credential)); + + PublisherClientFactory = (_, topic, cancellationToken) => new PublisherClientBuilder + { + TopicName = topic, + GoogleCredential = credential + }.BuildAsync(cancellationToken); + SubscriberClientFactory = (_, subscription, cancellationToken) => new SubscriberClientBuilder + { + SubscriptionName = subscription, + GoogleCredential = credential + }.BuildAsync(cancellationToken); + PublisherServiceApiClientFactory = (_, cancellationToken) => new PublisherServiceApiClientBuilder + { + GoogleCredential = credential + }.BuildAsync(cancellationToken); + SubscriberServiceApiClientFactory = (_, cancellationToken) => new SubscriberServiceApiClientBuilder + { + GoogleCredential = credential + }.BuildAsync(cancellationToken); + + return this; + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettingsValidationService.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettingsValidationService.cs new file mode 100644 index 00000000..0c4cdaf0 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubMessageBusSettingsValidationService.cs @@ -0,0 +1,51 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +internal class GooglePubSubMessageBusSettingsValidationService( + MessageBusSettings settings, + GooglePubSubMessageBusSettings providerSettings) + : DefaultMessageBusSettingsValidationService(settings, providerSettings) +{ + public override void AssertSettings() + { + if (string.IsNullOrWhiteSpace(ProviderSettings.ProjectId)) + { + ThrowFieldNotSet(nameof(ProviderSettings.ProjectId)); + } + if (ProviderSettings.PublisherClientFactory == null) ThrowFieldNotSet(nameof(ProviderSettings.PublisherClientFactory)); + if (ProviderSettings.SubscriberClientFactory == null) ThrowFieldNotSet(nameof(ProviderSettings.SubscriberClientFactory)); + if (ProviderSettings.HeaderSerializer == null) ThrowFieldNotSet(nameof(ProviderSettings.HeaderSerializer)); + + base.AssertSettings(); + } + + protected override void AssertProducer(ProducerSettings producerSettings) + { + if (producerSettings.PathKind != PathKind.Topic) + { + ThrowProducerFieldNotSet(producerSettings, nameof(producerSettings.PathKind), "must be Topic for Google Cloud Pub/Sub"); + } + base.AssertProducer(producerSettings); + } + + protected override void AssertConsumer(ConsumerSettings consumerSettings) + { + if (consumerSettings.PathKind != PathKind.Topic) + { + ThrowConsumerFieldNotSet(consumerSettings, nameof(consumerSettings.PathKind)); + } + if (string.IsNullOrWhiteSpace(consumerSettings.GetSubscriptionName())) + { + ThrowConsumerFieldNotSet(consumerSettings, nameof(GooglePubSubConsumerBuilderExtensions.SubscriptionName)); + } + base.AssertConsumer(consumerSettings); + } + + protected override void AssertRequestResponseSettings() + { + base.AssertRequestResponseSettings(); + if (Settings.RequestResponse != null && string.IsNullOrWhiteSpace(Settings.RequestResponse.GetSubscriptionName())) + { + ThrowRequestResponseFieldNotSet(nameof(GooglePubSubConsumerBuilderExtensions.SubscriptionName)); + } + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubResourceName.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubResourceName.cs new file mode 100644 index 00000000..2a556d42 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubResourceName.cs @@ -0,0 +1,14 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +internal static class GooglePubSubResourceName +{ + internal static TopicName ResolveTopic(string projectId, string path) + => path.StartsWith("projects/", StringComparison.Ordinal) + ? TopicName.Parse(path) + : TopicName.FromProjectTopic(projectId, path); + + internal static SubscriptionName ResolveSubscription(string projectId, string path) + => path.StartsWith("projects/", StringComparison.Ordinal) + ? SubscriptionName.Parse(path) + : SubscriptionName.FromProjectSubscription(projectId, path); +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologyService.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologyService.cs new file mode 100644 index 00000000..020a3c16 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologyService.cs @@ -0,0 +1,163 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +internal class GooglePubSubTopologyService( + ILogger logger, + MessageBusSettings settings, + GooglePubSubMessageBusSettings providerSettings, + PublisherServiceApiClient publisherClient, + SubscriberServiceApiClient subscriberClient) +{ + private static bool IsNotFound(RpcException exception) => exception.StatusCode == StatusCode.NotFound; + private static bool IsAlreadyExists(RpcException exception) => exception.StatusCode == StatusCode.AlreadyExists; + + internal async Task EnsureTopic( + string path, + bool canCreate, + IEnumerable> configureActions, + CancellationToken cancellationToken) + { + var topicName = GooglePubSubResourceName.ResolveTopic(providerSettings.ProjectId, path); + try + { + await publisherClient.GetTopicAsync(topicName, cancellationToken: cancellationToken).ConfigureAwait(false); + return; + } + catch (RpcException exception) when (IsNotFound(exception)) + { + // The topic will be created below when topology provisioning permits it. + } + + if (!canCreate) + { + logger.LogWarning("Topic {Topic} does not exist and topic creation is disabled", topicName); + return; + } + + var topic = new Topic { TopicName = topicName }; + providerSettings.TopologyProvisioning.CreateTopicOptions?.Invoke(topic); + foreach (var configure in configureActions.Where(x => x != null)) + { + configure(topic); + } + topic.TopicName = topicName; + + try + { + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating Google Pub/Sub topic {Topic}", topicName); + } + await publisherClient.CreateTopicAsync(topic, cancellationToken: cancellationToken).ConfigureAwait(false); + } + catch (RpcException exception) when (IsAlreadyExists(exception)) + { + // Another application instance created the topic concurrently. + } + } + + internal async Task EnsureSubscription( + string topicPath, + string subscriptionPath, + IEnumerable> configureActions, + CancellationToken cancellationToken) + { + var topicName = GooglePubSubResourceName.ResolveTopic(providerSettings.ProjectId, topicPath); + var subscriptionName = GooglePubSubResourceName.ResolveSubscription(providerSettings.ProjectId, subscriptionPath); + + try + { + var existing = await subscriberClient.GetSubscriptionAsync(subscriptionName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (!existing.TopicAsTopicName.Equals(topicName)) + { + throw new ConfigurationMessageBusException($"Google Pub/Sub subscription {subscriptionName} already belongs to topic {existing.Topic}; it cannot also consume from {topicName}."); + } + return; + } + catch (RpcException exception) when (IsNotFound(exception)) + { + // The subscription will be created below when topology provisioning permits it. + } + + if (!providerSettings.TopologyProvisioning.CanConsumerCreateSubscription) + { + logger.LogWarning("Subscription {Subscription} does not exist and subscription creation is disabled", subscriptionName); + return; + } + + var subscription = new Subscription + { + SubscriptionName = subscriptionName, + TopicAsTopicName = topicName + }; + providerSettings.TopologyProvisioning.CreateSubscriptionOptions?.Invoke(subscription); + foreach (var configure in configureActions.Where(x => x != null)) + { + configure(subscription); + } + + if (subscription.PushConfig != null || subscription.BigqueryConfig != null || subscription.CloudStorageConfig != null) + { + throw new ConfigurationMessageBusException($"Google Pub/Sub subscription {subscriptionName} must be a pull subscription."); + } + + // Resource identity always comes from the SlimMessageBus declaration. + subscription.SubscriptionName = subscriptionName; + subscription.TopicAsTopicName = topicName; + + try + { + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating Google Pub/Sub subscription {Subscription} on topic {Topic}", subscriptionName, topicName); + } + await subscriberClient.CreateSubscriptionAsync(subscription, cancellationToken: cancellationToken).ConfigureAwait(false); + } + catch (RpcException exception) when (IsAlreadyExists(exception)) + { + // Another application instance created the subscription concurrently. + } + } + + internal Task Provision(CancellationToken cancellationToken) + => providerSettings.TopologyProvisioning.OnProvisionTopology( + publisherClient, + subscriberClient, + () => ProvisionCore(cancellationToken), + cancellationToken); + + private async Task ProvisionCore(CancellationToken cancellationToken) + { + logger.LogInformation("Google Pub/Sub topology provisioning started"); + + var consumerGroups = settings.Consumers.Cast() + .Concat(settings.RequestResponse == null ? [] : [settings.RequestResponse]) + .GroupBy(x => (Topic: x.Path, Subscription: x.GetSubscriptionName())); + + foreach (var group in consumerGroups) + { + var declarations = group.ToList(); + await EnsureTopic( + group.Key.Topic, + providerSettings.TopologyProvisioning.CanConsumerCreateTopic, + declarations.Select(x => x.GetOrDefault(GooglePubSubProperties.CreateTopicOptions)), + cancellationToken).ConfigureAwait(false); + + await EnsureSubscription( + group.Key.Topic, + group.Key.Subscription, + declarations.Select(x => x.GetOrDefault(GooglePubSubProperties.CreateSubscriptionOptions)), + cancellationToken).ConfigureAwait(false); + } + + foreach (var producer in settings.Producers.Where(x => !string.IsNullOrWhiteSpace(x.DefaultPath))) + { + await EnsureTopic( + producer.DefaultPath, + providerSettings.TopologyProvisioning.CanProducerCreateTopic, + [producer.GetOrDefault(GooglePubSubProperties.CreateTopicOptions)], + cancellationToken).ConfigureAwait(false); + } + + logger.LogInformation("Google Pub/Sub topology provisioning finished"); + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologySettings.cs b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologySettings.cs new file mode 100644 index 00000000..1c9708b0 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/GooglePubSubTopologySettings.cs @@ -0,0 +1,26 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +public class GooglePubSubTopologySettings +{ + /// + /// Indicates whether declared topics and subscriptions are created when missing. Default is true. + /// + public bool Enabled { get; set; } = true; + + public bool CanProducerCreateTopic { get; set; } = true; + public bool CanConsumerCreateTopic { get; set; } = true; + public bool CanConsumerCreateSubscription { get; set; } = true; + + /// + /// Default customization applied when a topic is created. + /// + public Action CreateTopicOptions { get; set; } + + /// + /// Default customization applied when a pull subscription is created. + /// + public Action CreateSubscriptionOptions { get; set; } + + public GooglePubSubTopologyInterceptor OnProvisionTopology { get; set; } + = (_, _, provision, _) => provision(); +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Headers/DefaultGooglePubSubHeaderSerializer.cs b/src/SlimMessageBus.Host.GooglePubSub/Headers/DefaultGooglePubSubHeaderSerializer.cs new file mode 100644 index 00000000..1eb6310a --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Headers/DefaultGooglePubSubHeaderSerializer.cs @@ -0,0 +1,61 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +using System.Globalization; + +/// +/// Default serializer for Pub/Sub attributes. Type markers preserve common SlimMessageBus header value types. +/// +public class DefaultGooglePubSubHeaderSerializer : IGooglePubSubHeaderSerializer +{ + private const string Prefix = "smb:"; + + public string Serialize(string key, object value) => value switch + { + null => $"{Prefix}null:", + bool boolean => $"{Prefix}bool:{boolean}", + byte number => $"{Prefix}byte:{number.ToString(CultureInfo.InvariantCulture)}", + short number => $"{Prefix}short:{number.ToString(CultureInfo.InvariantCulture)}", + int number => $"{Prefix}int:{number.ToString(CultureInfo.InvariantCulture)}", + long number => $"{Prefix}long:{number.ToString(CultureInfo.InvariantCulture)}", + float number => $"{Prefix}float:{number.ToString("R", CultureInfo.InvariantCulture)}", + double number => $"{Prefix}double:{number.ToString("R", CultureInfo.InvariantCulture)}", + decimal number => $"{Prefix}decimal:{number.ToString(CultureInfo.InvariantCulture)}", + Guid guid => $"{Prefix}guid:{guid:D}", + DateTime dateTime => $"{Prefix}datetime:{dateTime.ToString("O", CultureInfo.InvariantCulture)}", + DateTimeOffset dateTimeOffset => $"{Prefix}datetimeoffset:{dateTimeOffset.ToString("O", CultureInfo.InvariantCulture)}", + _ => value.ToString() + }; + + public object Deserialize(string key, string value) + { + if (value == null || !value.StartsWith(Prefix, StringComparison.Ordinal)) + { + return value; + } + + var separator = value.IndexOf(':', Prefix.Length); + if (separator < 0) + { + return value; + } + + var type = value.Substring(Prefix.Length, separator - Prefix.Length); + var serialized = value.Substring(separator + 1); + return type switch + { + "null" => null, + "bool" when bool.TryParse(serialized, out var parsed) => parsed, + "byte" when byte.TryParse(serialized, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed, + "short" when short.TryParse(serialized, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed, + "int" when int.TryParse(serialized, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed, + "long" when long.TryParse(serialized, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) => parsed, + "float" when float.TryParse(serialized, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) => parsed, + "double" when double.TryParse(serialized, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) => parsed, + "decimal" when decimal.TryParse(serialized, NumberStyles.Number, CultureInfo.InvariantCulture, out var parsed) => parsed, + "guid" when Guid.TryParse(serialized, out var parsed) => parsed, + "datetime" when DateTime.TryParse(serialized, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed) => parsed, + "datetimeoffset" when DateTimeOffset.TryParse(serialized, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed) => parsed, + _ => value + }; + } +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/Headers/IGooglePubSubHeaderSerializer.cs b/src/SlimMessageBus.Host.GooglePubSub/Headers/IGooglePubSubHeaderSerializer.cs new file mode 100644 index 00000000..67f0ce51 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Headers/IGooglePubSubHeaderSerializer.cs @@ -0,0 +1,10 @@ +namespace SlimMessageBus.Host.GooglePubSub; + +/// +/// Converts SlimMessageBus header values to and from Pub/Sub string attributes. +/// +public interface IGooglePubSubHeaderSerializer +{ + string Serialize(string key, object value); + object Deserialize(string key, string value); +} diff --git a/src/SlimMessageBus.Host.GooglePubSub/SlimMessageBus.Host.GooglePubSub.csproj b/src/SlimMessageBus.Host.GooglePubSub/SlimMessageBus.Host.GooglePubSub.csproj new file mode 100644 index 00000000..e802b240 --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/SlimMessageBus.Host.GooglePubSub.csproj @@ -0,0 +1,22 @@ + + + + + + Google Cloud Pub/Sub provider for SlimMessageBus + Google Cloud Pub/Sub GCP provider SlimMessageBus MessageBus messaging client + + + + + + + + + + + + + + + diff --git a/src/SlimMessageBus.Host.GooglePubSub/Usings.cs b/src/SlimMessageBus.Host.GooglePubSub/Usings.cs new file mode 100644 index 00000000..da03446d --- /dev/null +++ b/src/SlimMessageBus.Host.GooglePubSub/Usings.cs @@ -0,0 +1,10 @@ +global using Google.Cloud.PubSub.V1; +global using Google.Protobuf; +global using Google.Apis.Auth.OAuth2; +global using Grpc.Core; + +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.Logging; + +global using SlimMessageBus.Host.Consumer.ErrorHandling; +global using SlimMessageBus.Host.Services; diff --git a/src/SlimMessageBus.sln b/src/SlimMessageBus.sln index 0550becd..b1509ca7 100644 --- a/src/SlimMessageBus.sln +++ b/src/SlimMessageBus.sln @@ -133,8 +133,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{CBE53E71-7 ..\docs\provider_amazon_sqs.md = ..\docs\provider_amazon_sqs.md ..\docs\provider_amazon_sqs.t.md = ..\docs\provider_amazon_sqs.t.md ..\docs\provider_azure_eventhubs.md = ..\docs\provider_azure_eventhubs.md - ..\docs\provider_azure_servicebus.md = ..\docs\provider_azure_servicebus.md - ..\docs\provider_hybrid.md = ..\docs\provider_hybrid.md + ..\docs\provider_azure_servicebus.md = ..\docs\provider_azure_servicebus.md + ..\docs\provider_google_pubsub.md = ..\docs\provider_google_pubsub.md + ..\docs\provider_google_pubsub.t.md = ..\docs\provider_google_pubsub.t.md + ..\docs\provider_hybrid.md = ..\docs\provider_hybrid.md ..\docs\provider_kafka.t.md = ..\docs\provider_kafka.t.md ..\docs\provider_memory.t.md = ..\docs\provider_memory.t.md ..\docs\provider_mqtt.md = ..\docs\provider_mqtt.md @@ -293,8 +295,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Artifacts", "Artifacts", "{ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlimMessageBus.Host.AmazonSQS", "SlimMessageBus.Host.AmazonSQS\SlimMessageBus.Host.AmazonSQS.csproj", "{4DF4BC7C-5EE3-4310-BC40-054C1494444E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlimMessageBus.Host.AmazonSQS.Test", "Tests\SlimMessageBus.Host.AmazonSQS.Test\SlimMessageBus.Host.AmazonSQS.Test.csproj", "{9255A33D-9697-4E69-9418-AD31656FF8AC}" -EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlimMessageBus.Host.AmazonSQS.Test", "Tests\SlimMessageBus.Host.AmazonSQS.Test\SlimMessageBus.Host.AmazonSQS.Test.csproj", "{9255A33D-9697-4E69-9418-AD31656FF8AC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlimMessageBus.Host.GooglePubSub", "SlimMessageBus.Host.GooglePubSub\SlimMessageBus.Host.GooglePubSub.csproj", "{A147F17C-A123-47AA-9C77-47DC1B479F01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlimMessageBus.Host.GooglePubSub.Test", "Tests\SlimMessageBus.Host.GooglePubSub.Test\SlimMessageBus.Host.GooglePubSub.Test.csproj", "{B247F17C-B234-48BB-AD88-58ED2C58AF02}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlimMessageBus.Host.CircuitBreaker", "SlimMessageBus.Host.CircuitBreaker\SlimMessageBus.Host.CircuitBreaker.csproj", "{2FC8813B-D882-4B08-A886-5C6C6F8CB334}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlimMessageBus.Host.CircuitBreaker.Test", "Tests\SlimMessageBus.Host.CircuitBreaker.Test\SlimMessageBus.Host.CircuitBreaker.Test.csproj", "{B05BA0C5-8E47-4361-8C62-BC6B8682B7AA}" @@ -957,8 +963,24 @@ Global {9255A33D-9697-4E69-9418-AD31656FF8AC}.Debug|x86.Build.0 = Debug|Any CPU {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|Any CPU.Build.0 = Release|Any CPU - {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|x86.ActiveCfg = Release|Any CPU - {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|x86.Build.0 = Release|Any CPU + {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|x86.ActiveCfg = Release|Any CPU + {9255A33D-9697-4E69-9418-AD31656FF8AC}.Release|x86.Build.0 = Release|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Debug|x86.ActiveCfg = Debug|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Debug|x86.Build.0 = Debug|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Release|Any CPU.Build.0 = Release|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Release|x86.ActiveCfg = Release|Any CPU + {A147F17C-A123-47AA-9C77-47DC1B479F01}.Release|x86.Build.0 = Release|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Debug|x86.ActiveCfg = Debug|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Debug|x86.Build.0 = Debug|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Release|Any CPU.Build.0 = Release|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Release|x86.ActiveCfg = Release|Any CPU + {B247F17C-B234-48BB-AD88-58ED2C58AF02}.Release|x86.Build.0 = Release|Any CPU {2FC8813B-D882-4B08-A886-5C6C6F8CB334}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2FC8813B-D882-4B08-A886-5C6C6F8CB334}.Debug|Any CPU.Build.0 = Debug|Any CPU {2FC8813B-D882-4B08-A886-5C6C6F8CB334}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -1118,8 +1140,10 @@ Global {46C40625-D1AC-4EA1-9562-4F1837D417CE} = {A5B15524-93B8-4CCE-AC6D-A22984498BA0} {5250E48D-36C7-4214-8D7E-5924A9E337C6} = {59F88FB5-6D19-4520-87E8-227B3539BBB3} {9FCBF788-1F0C-43E2-909D-1F96B2685F38} = {9F005B5C-A856-4351-8C0C-47A8B785C637} - {4DF4BC7C-5EE3-4310-BC40-054C1494444E} = {9291D340-B4FA-44A3-8060-C14743FB1712} - {9255A33D-9697-4E69-9418-AD31656FF8AC} = {9F005B5C-A856-4351-8C0C-47A8B785C637} + {4DF4BC7C-5EE3-4310-BC40-054C1494444E} = {9291D340-B4FA-44A3-8060-C14743FB1712} + {9255A33D-9697-4E69-9418-AD31656FF8AC} = {9F005B5C-A856-4351-8C0C-47A8B785C637} + {A147F17C-A123-47AA-9C77-47DC1B479F01} = {9291D340-B4FA-44A3-8060-C14743FB1712} + {B247F17C-B234-48BB-AD88-58ED2C58AF02} = {9F005B5C-A856-4351-8C0C-47A8B785C637} {2FC8813B-D882-4B08-A886-5C6C6F8CB334} = {FE36338C-0DA2-499E-92CA-F9D5CE594B9F} {B05BA0C5-8E47-4361-8C62-BC6B8682B7AA} = {9F005B5C-A856-4351-8C0C-47A8B785C637} {E5C8477B-8446-4C6C-C4FB-675D012BB09E} = {B7CDA0D2-98AB-42B6-A41A-9D893C1B9DCB} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/DefaultGooglePubSubHeaderSerializerTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/DefaultGooglePubSubHeaderSerializerTests.cs new file mode 100644 index 00000000..ae81e9bd --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/DefaultGooglePubSubHeaderSerializerTests.cs @@ -0,0 +1,71 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public class DefaultGooglePubSubHeaderSerializerTests +{ + public static readonly TheoryData Values = new() + { + null, + "123", + true, + (byte)12, + (short)123, + 1234, + 12345L, + 12.5f, + 123.456d, + 123.456m, + Guid.Parse("529194F3-AEAA-497D-A495-C84DD67C2DDA"), + new DateTime(2026, 8, 25, 12, 30, 0, DateTimeKind.Utc), + new DateTimeOffset(2026, 8, 25, 12, 30, 0, TimeSpan.FromHours(2)) + }; + + [Theory] + [MemberData(nameof(Values))] + public void When_HeaderIsSerialized_Then_ValueAndTypeArePreserved(object value) + { + var serializer = new DefaultGooglePubSubHeaderSerializer(); + + var serialized = serializer.Serialize("header", value); + var restored = serializer.Deserialize("header", serialized); + + restored.Should().Be(value); + } + + [Fact] + public void When_StringLooksLikeAnotherType_Then_ItRemainsAString() + { + var serializer = new DefaultGooglePubSubHeaderSerializer(); + + serializer.Deserialize("header", serializer.Serialize("header", "123")) + .Should().BeOfType().Which.Should().Be("123"); + } + + [Theory] + [InlineData("smb:bool:not-a-bool")] + [InlineData("smb:byte:not-a-byte")] + [InlineData("smb:short:not-a-short")] + [InlineData("smb:int:not-an-int")] + [InlineData("smb:long:not-a-long")] + [InlineData("smb:float:not-a-float")] + [InlineData("smb:double:not-a-double")] + [InlineData("smb:decimal:not-a-decimal")] + [InlineData("smb:guid:not-a-guid")] + [InlineData("smb:datetime:not-a-datetime")] + [InlineData("smb:datetimeoffset:not-a-datetimeoffset")] + [InlineData("smb:unknown:value")] + [InlineData("smb:missing-separator")] + public void When_MarkedValueIsInvalid_Then_OriginalValueIsReturned(string value) + { + var serializer = new DefaultGooglePubSubHeaderSerializer(); + + serializer.Deserialize("header", value).Should().Be(value); + } + + [Fact] + public void When_NullValueIsDeserialized_Then_NullIsReturned() + { + var serializer = new DefaultGooglePubSubHeaderSerializer(); + + serializer.Deserialize("header", null).Should().BeNull(); + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConfigurationTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConfigurationTests.cs new file mode 100644 index 00000000..ef8c530a --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConfigurationTests.cs @@ -0,0 +1,109 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public class GooglePubSubConfigurationTests +{ + private record TestMessage(string Id); + + [Fact] + public void TopologyProvisioning_IsEnabledByDefault() + { + var settings = new GooglePubSubMessageBusSettings(); + + settings.TopologyProvisioning.Enabled.Should().BeTrue(); + settings.TopologyProvisioning.CanProducerCreateTopic.Should().BeTrue(); + settings.TopologyProvisioning.CanConsumerCreateTopic.Should().BeTrue(); + settings.TopologyProvisioning.CanConsumerCreateSubscription.Should().BeTrue(); + } + + [Fact] + public void SubscriptionName_SetsConsumerProperty() + { + var settings = new MessageBusSettings(); + var builder = new ConsumerBuilder(settings); + + var result = builder.SubscriptionName("orders-worker"); + + result.Should().BeSameAs(builder); + builder.ConsumerSettings.GetSubscriptionName().Should().Be("orders-worker"); + } + + [Fact] + public void ConsumerTopologyOptions_SetConsumerProperties() + { + var builder = new ConsumerBuilder(new MessageBusSettings()); + Action topicOptions = topic => topic.Labels["source"] = "consumer"; + Action subscriptionOptions = subscription => subscription.AckDeadlineSeconds = 30; + + var result = builder + .CreateTopicOptions(topicOptions) + .CreateSubscriptionOptions(subscriptionOptions); + + result.Should().BeSameAs(builder); + builder.ConsumerSettings.GetOrDefault(GooglePubSubProperties.CreateTopicOptions).Should().BeSameAs(topicOptions); + builder.ConsumerSettings.GetOrDefault(GooglePubSubProperties.CreateSubscriptionOptions).Should().BeSameAs(subscriptionOptions); + } + + [Fact] + public void WithModifier_SetsTypedProducerModifier() + { + var producerSettings = new ProducerSettings { MessageType = typeof(TestMessage) }; + var builder = new ProducerBuilder(producerSettings); + builder.WithModifier((message, transportMessage) => transportMessage.OrderingKey = message.Id); + + var modifier = producerSettings.GetOrDefault(GooglePubSubProperties.MessageModifier); + var transportMessage = new PubsubMessage(); + modifier(new TestMessage("customer-1"), transportMessage); + + transportMessage.OrderingKey.Should().Be("customer-1"); + } + + [Fact] + public void ProducerCreateTopicOptions_SetsProducerProperty() + { + var builder = new ProducerBuilder(new ProducerSettings { MessageType = typeof(TestMessage) }); + Action topicOptions = topic => topic.Labels["source"] = "producer"; + + var result = builder.CreateTopicOptions(topicOptions); + + result.Should().BeSameAs(builder); + builder.Settings.GetOrDefault(GooglePubSubProperties.CreateTopicOptions).Should().BeSameAs(topicOptions); + } + + [Fact] + public void BuilderExtensions_RejectNullArguments() + { + var consumerBuilder = new ConsumerBuilder(new MessageBusSettings()); + var producerBuilder = new ProducerBuilder(new ProducerSettings { MessageType = typeof(TestMessage) }); + + Action nullConsumerBuilder = () => GooglePubSubConsumerBuilderExtensions.SubscriptionName>(null, "subscription"); + Action nullSubscriptionName = () => consumerBuilder.SubscriptionName(null); + Action nullConsumerTopicOptions = () => consumerBuilder.CreateTopicOptions(null); + Action nullConsumerSubscriptionOptions = () => consumerBuilder.CreateSubscriptionOptions(null); + Action nullProducerBuilder = () => GooglePubSubProducerBuilderExtensions.WithModifier(null, (_, _) => { }); + Action nullProducerModifier = () => producerBuilder.WithModifier(null); + Action nullProducerTopicOptions = () => producerBuilder.CreateTopicOptions(null); + Action nullMessageBusBuilder = () => MessageBusBuilderExtensions.WithProviderGooglePubSub(null, _ => { }); + Action nullProviderConfiguration = () => MessageBusBuilder.Create().WithProviderGooglePubSub(null); + + nullConsumerBuilder.Should().Throw(); + nullSubscriptionName.Should().Throw(); + nullConsumerTopicOptions.Should().Throw(); + nullConsumerSubscriptionOptions.Should().Throw(); + nullProducerBuilder.Should().Throw(); + nullProducerModifier.Should().Throw(); + nullProducerTopicOptions.Should().Throw(); + nullMessageBusBuilder.Should().Throw(); + nullProviderConfiguration.Should().Throw(); + } + + [Fact] + public void ResourceNames_AcceptIdsAndFullyQualifiedNames() + { + GooglePubSubResourceName.ResolveTopic("project-a", "orders").ToString() + .Should().Be("projects/project-a/topics/orders"); + GooglePubSubResourceName.ResolveTopic("ignored", "projects/project-b/topics/orders").ToString() + .Should().Be("projects/project-b/topics/orders"); + GooglePubSubResourceName.ResolveSubscription("project-a", "orders-worker").ToString() + .Should().Be("projects/project-a/subscriptions/orders-worker"); + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConsumerContextExtensionsTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConsumerContextExtensionsTests.cs new file mode 100644 index 00000000..71b0e54c --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubConsumerContextExtensionsTests.cs @@ -0,0 +1,29 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public class GooglePubSubConsumerContextExtensionsTests +{ + [Fact] + public void TransportMessageAndSubscriptionName_RoundTripThroughContext() + { + var context = new ConsumerContext(); + var message = new PubsubMessage { MessageId = "message-1" }; + + context.SetTransportMessage(message); + context.SetSubscriptionName("orders-worker"); + + ((IConsumerContext)context).GetTransportMessage().Should().BeSameAs(message); + ((IConsumerContext)context).GetSubscriptionName().Should().Be("orders-worker"); + } + + [Fact] + public void ContextAccessors_RejectNullContext() + { + IConsumerContext context = null; + + Action getMessage = () => context.GetTransportMessage(); + Action getSubscription = () => context.GetSubscriptionName(); + + getMessage.Should().Throw(); + getSubscription.Should().Throw(); + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubFixture.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubFixture.cs new file mode 100644 index 00000000..6006f6e1 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubFixture.cs @@ -0,0 +1,19 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public sealed class GooglePubSubFixture : IAsyncLifetime +{ + private readonly PubSubContainer _container = new PubSubBuilder( + "gcr.io/google.com/cloudsdktool/google-cloud-cli:446.0.1-emulators").Build(); + + public string EmulatorEndpoint => _container.GetEmulatorEndpoint(); + + public Task InitializeAsync() => _container.StartAsync(); + + public async Task DisposeAsync() + { + await _container.DisposeAsync(); + } +} + +[CollectionDefinition(nameof(GooglePubSubCollection))] +public sealed class GooglePubSubCollection : ICollectionFixture; diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusIt.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusIt.cs new file mode 100644 index 00000000..42513c67 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusIt.cs @@ -0,0 +1,80 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +[Trait("Category", "Integration")] +[Trait("Transport", "GooglePubSub")] +[Collection(nameof(GooglePubSubCollection))] +public class GooglePubSubMessageBusIt(ITestOutputHelper output, GooglePubSubFixture fixture) + : BaseIntegrationTest(output) +{ + private readonly string _topic = $"orders-{Guid.NewGuid():N}"; + private readonly string _subscription = $"orders-worker-{Guid.NewGuid():N}"; + + protected override void SetupServices(ServiceCollection services, IConfigurationRoot configuration) + { + services.AddSlimMessageBus(mbb => + { + mbb.WithProviderGooglePubSub(settings => + { + settings.ProjectId = "slim-message-bus-tests"; + ConfigureEmulatorClients(settings, fixture.EmulatorEndpoint); + }); + mbb.Produce(x => x.DefaultTopic(_topic)); + mbb.Consume(x => x.Topic(_topic).SubscriptionName(_subscription)); + mbb.AddServicesFromAssemblyContaining(); + mbb.AddJsonSerializer(); + }); + + services.AddSingleton>(); + } + + [Fact] + public async Task ProvisionsTopologyAndDeliversPublishedMessage() + { + var messageBus = ServiceProvider.GetRequiredService(); + var consumedMessages = ServiceProvider.GetRequiredService>(); + var message = new OrderSubmitted(Guid.NewGuid(), 42); + + await EnsureConsumersStarted(); + await messageBus.Publish(message, headers: new Dictionary { ["source"] = "integration-test" }); + await consumedMessages.WaitUntilArriving(newMessagesTimeout: 30, expectedCount: 1); + + consumedMessages.Snapshot().Should().ContainSingle().Which.Should().Be(message); + } + + private static void ConfigureEmulatorClients(GooglePubSubMessageBusSettings settings, string endpoint) + { + settings.PublisherClientFactory = (_, topic, cancellationToken) => new PublisherClientBuilder + { + TopicName = topic, + Endpoint = endpoint, + ChannelCredentials = ChannelCredentials.Insecure + }.BuildAsync(cancellationToken); + settings.SubscriberClientFactory = (_, subscription, cancellationToken) => new SubscriberClientBuilder + { + SubscriptionName = subscription, + Endpoint = endpoint, + ChannelCredentials = ChannelCredentials.Insecure + }.BuildAsync(cancellationToken); + settings.PublisherServiceApiClientFactory = (_, cancellationToken) => new PublisherServiceApiClientBuilder + { + Endpoint = endpoint, + ChannelCredentials = ChannelCredentials.Insecure + }.BuildAsync(cancellationToken); + settings.SubscriberServiceApiClientFactory = (_, cancellationToken) => new SubscriberServiceApiClientBuilder + { + Endpoint = endpoint, + ChannelCredentials = ChannelCredentials.Insecure + }.BuildAsync(cancellationToken); + } + + public record OrderSubmitted(Guid OrderId, int Quantity); + + public class OrderSubmittedConsumer(TestEventCollector messages) : IConsumer + { + public Task OnHandle(OrderSubmitted message, CancellationToken cancellationToken) + { + messages.Add(message); + return Task.CompletedTask; + } + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsTests.cs new file mode 100644 index 00000000..c17053a3 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsTests.cs @@ -0,0 +1,72 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +using Google.Apis.Auth.OAuth2; + +public class GooglePubSubMessageBusSettingsTests +{ + private record TestMessage(string Id); + + [Fact] + public void WithModifier_ComposesGlobalModifiers() + { + var settings = new GooglePubSubMessageBusSettings(); + settings.WithModifier((_, message) => message.Attributes["first"] = "1"); + settings.WithModifier((message, transportMessage) => transportMessage.OrderingKey = message.Id); + var modifier = settings.GetOrDefault(GooglePubSubProperties.MessageModifier); + var transportMessage = new PubsubMessage(); + + modifier(new TestMessage("customer-1"), transportMessage); + + transportMessage.Attributes["first"].Should().Be("1"); + transportMessage.OrderingKey.Should().Be("customer-1"); + } + + [Fact] + public void WithModifier_CanReplacePreviousModifierAndIgnoresOtherTypes() + { + var settings = new GooglePubSubMessageBusSettings(); + settings.WithModifier((_, message) => message.Attributes["previous"] = "true"); + settings.WithModifier((message, transportMessage) => transportMessage.OrderingKey = message.Id, executePrevious: false); + var modifier = settings.GetOrDefault(GooglePubSubProperties.MessageModifier); + var transportMessage = new PubsubMessage(); + + modifier("not-a-test-message", transportMessage); + + transportMessage.Attributes.Should().BeEmpty(); + transportMessage.OrderingKey.Should().BeEmpty(); + } + + [Fact] + public void SettingsMethods_RejectNullArguments() + { + var settings = new GooglePubSubMessageBusSettings(); + + Action nullModifier = () => settings.WithModifier((GooglePubSubMessageModifier)null); + Action nullTypedModifier = () => settings.WithModifier(null); + Action nullCredentialsPath = () => settings.UseCredentialsPath(null); + Action nullCredential = () => settings.UseGoogleCredential(null); + + nullModifier.Should().Throw(); + nullTypedModifier.Should().Throw(); + nullCredentialsPath.Should().Throw(); + nullCredential.Should().Throw(); + } + + [Fact] + public void UseGoogleCredential_ReplacesAllClientFactories() + { + var settings = new GooglePubSubMessageBusSettings(); + var publisherFactory = settings.PublisherClientFactory; + var subscriberFactory = settings.SubscriberClientFactory; + var publisherAdminFactory = settings.PublisherServiceApiClientFactory; + var subscriberAdminFactory = settings.SubscriberServiceApiClientFactory; + + var result = settings.UseGoogleCredential(GoogleCredential.FromAccessToken("test-token")); + + result.Should().BeSameAs(settings); + settings.PublisherClientFactory.Should().NotBeSameAs(publisherFactory); + settings.SubscriberClientFactory.Should().NotBeSameAs(subscriberFactory); + settings.PublisherServiceApiClientFactory.Should().NotBeSameAs(publisherAdminFactory); + settings.SubscriberServiceApiClientFactory.Should().NotBeSameAs(subscriberAdminFactory); + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsValidationServiceTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsValidationServiceTests.cs new file mode 100644 index 00000000..e187a70b --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusSettingsValidationServiceTests.cs @@ -0,0 +1,142 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public class GooglePubSubMessageBusSettingsValidationServiceTests +{ + private record TestMessage; + + private readonly MessageBusSettings _settings = new() + { + Name = "TestBus", + ServiceProvider = Mock.Of() + }; + + [Fact] + public void ProjectId_IsRequired() + { + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = null }); + + Action act = validator.AssertSettings; + act.Should().Throw() + .WithMessage("*ProjectId*"); + } + + [Theory] + [InlineData("publisher")] + [InlineData("subscriber")] + [InlineData("headers")] + public void RequiredProviderServices_AreValidated(string missingService) + { + var providerSettings = new GooglePubSubMessageBusSettings { ProjectId = "project" }; + switch (missingService) + { + case "publisher": + providerSettings.PublisherClientFactory = null; + break; + case "subscriber": + providerSettings.SubscriberClientFactory = null; + break; + case "headers": + providerSettings.HeaderSerializer = null; + break; + } + var validator = new GooglePubSubMessageBusSettingsValidationService(_settings, providerSettings); + + Action act = validator.AssertSettings; + + act.Should().Throw(); + } + + [Fact] + public void TopicConsumer_RequiresSubscriptionName() + { + _ = new ConsumerBuilder(_settings) + .Topic("orders") + .WithConsumer>(); + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = "project" }); + + Action act = validator.AssertSettings; + act.Should().Throw() + .WithMessage("*SubscriptionName*"); + } + + [Fact] + public void Producer_MustTargetTopic() + { + _settings.Producers.Add(new ProducerSettings + { + MessageType = typeof(TestMessage), + DefaultPath = "orders", + PathKind = PathKind.Queue + }); + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = "project" }); + + Action act = validator.AssertSettings; + + act.Should().Throw() + .WithMessage("*Topic*"); + } + + [Fact] + public void Consumer_MustTargetTopic() + { + var consumerBuilder = new ConsumerBuilder(_settings); + consumerBuilder.ConsumerSettings.Path = "orders"; + consumerBuilder.ConsumerSettings.PathKind = PathKind.Queue; + _ = consumerBuilder + .SubscriptionName("orders-worker") + .WithConsumer>(); + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = "project" }); + + Action act = validator.AssertSettings; + + act.Should().Throw() + .WithMessage("*PathKind*"); + } + + [Fact] + public void RequestResponse_RequiresSubscriptionName() + { + _settings.RequestResponse = new RequestResponseSettings + { + Path = "replies", + PathKind = PathKind.Topic + }; + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = "project" }); + + Action act = validator.AssertSettings; + + act.Should().Throw() + .WithMessage("*SubscriptionName*"); + } + + [Fact] + public void ValidTopicProducerAndConsumer_AreAccepted() + { + _settings.Producers.Add(new ProducerSettings + { + MessageType = typeof(TestMessage), + DefaultPath = "orders", + PathKind = PathKind.Topic + }); + _ = new ConsumerBuilder(_settings) + .Topic("orders") + .SubscriptionName("orders-worker") + .WithConsumer>(); + var validator = new GooglePubSubMessageBusSettingsValidationService( + _settings, + new GooglePubSubMessageBusSettings { ProjectId = "project" }); + + Action act = validator.AssertSettings; + act.Should().NotThrow(); + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusTests.cs new file mode 100644 index 00000000..e59473a1 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubMessageBusTests.cs @@ -0,0 +1,60 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +public class GooglePubSubMessageBusTests +{ + private record TestMessage(string Id); + + [Fact] + public async Task Publish_UsesTopicClientHeadersPayloadAndModifier() + { + var publisher = new Mock(); + publisher.Setup(x => x.PublishAsync(It.IsAny())).ReturnsAsync("message-id"); + + var serializer = new Mock(); + serializer.Setup(x => x.Serialize(typeof(TestMessage), It.IsAny>(), It.IsAny(), It.IsAny())) + .Returns([1, 2, 3]); + var serializerProvider = new Mock(); + serializerProvider.Setup(x => x.GetSerializer("orders")).Returns(serializer.Object); + + var serviceProvider = CreateServiceProvider(serializerProvider.Object); + var builder = MessageBusBuilder.Create().WithServiceProvider(serviceProvider); + builder.Produce(x => x + .DefaultTopic("orders") + .WithModifier((message, transportMessage) => transportMessage.OrderingKey = message.Id)); + + var settings = new GooglePubSubMessageBusSettings + { + ProjectId = "project", + TopologyProvisioning = new GooglePubSubTopologySettings { Enabled = false }, + PublisherClientFactory = (_, topic, _) => + { + topic.ToString().Should().Be("projects/project/topics/orders"); + return Task.FromResult(publisher.Object); + } + }; + builder.WithProvider(messageBusSettings => new GooglePubSubMessageBus(messageBusSettings, settings)); + await using var bus = (GooglePubSubMessageBus)builder.Build(); + + await bus.ProducePublish(new TestMessage("customer-1"), headers: new Dictionary { ["attempt"] = 3 }); + + publisher.Verify(x => x.PublishAsync(It.Is(message => + message.Data.ToByteArray().SequenceEqual(new byte[] { 1, 2, 3 }) && + message.OrderingKey == "customer-1" && + message.Attributes["attempt"] == "smb:int:3")), Times.Once); + } + + private static IServiceProvider CreateServiceProvider(IMessageSerializerProvider serializerProvider) + { + var serviceProvider = new Mock(); + serviceProvider.Setup(x => x.GetService(It.Is(type => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)))) + .Returns(Enumerable.Empty()); + serviceProvider.Setup(x => x.GetService(typeof(IMessageSerializerProvider))).Returns(serializerProvider); + serviceProvider.Setup(x => x.GetService(typeof(IMessageTypeResolver))).Returns(new AssemblyQualifiedNameMessageTypeResolver()); + serviceProvider.Setup(x => x.GetService(typeof(IEnumerable))).Returns(Array.Empty()); + serviceProvider.Setup(x => x.GetService(typeof(TimeProvider))).Returns(TimeProvider.System); + serviceProvider.Setup(x => x.GetService(typeof(RuntimeTypeCache))).Returns(new RuntimeTypeCache()); + serviceProvider.Setup(x => x.GetService(typeof(IPendingRequestManager))) + .Returns(new PendingRequestManager(new InMemoryPendingRequestStore(), TimeProvider.System, NullLoggerFactory.Instance)); + return serviceProvider.Object; + } +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubTopologyServiceTests.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubTopologyServiceTests.cs new file mode 100644 index 00000000..09f093e2 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/GooglePubSubTopologyServiceTests.cs @@ -0,0 +1,181 @@ +namespace SlimMessageBus.Host.GooglePubSub.Test; + +using Grpc.Core; + +public class GooglePubSubTopologyServiceTests +{ + private readonly Mock _publisher = new(); + private readonly Mock _subscriber = new(); + private readonly GooglePubSubMessageBusSettings _providerSettings = new() { ProjectId = "project" }; + + private GooglePubSubTopologyService CreateSubject() => new( + NullLogger.Instance, + new MessageBusSettings(), + _providerSettings, + _publisher.Object, + _subscriber.Object); + + [Fact] + public async Task EnsureTopic_CreatesMissingTopicAndAppliesOptions() + { + var topicName = TopicName.FromProjectTopic("project", "orders"); + _publisher.Setup(x => x.GetTopicAsync(topicName, It.IsAny())) + .ThrowsAsync(NotFound()); + _publisher.Setup(x => x.CreateTopicAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((Topic topic, CancellationToken _) => topic); + _providerSettings.TopologyProvisioning.CreateTopicOptions = topic => topic.Labels["global"] = "true"; + + await CreateSubject().EnsureTopic( + "orders", + canCreate: true, + [topic => topic.Labels["local"] = "true"], + CancellationToken.None); + + _publisher.Verify(x => x.CreateTopicAsync(It.Is(topic => + topic.TopicName == topicName && + topic.Labels["global"] == "true" && + topic.Labels["local"] == "true"), It.IsAny()), Times.Once); + } + + [Fact] + public async Task EnsureTopic_DoesNotCreateWhenDisabled() + { + var topicName = TopicName.FromProjectTopic("project", "orders"); + _publisher.Setup(x => x.GetTopicAsync(topicName, It.IsAny())) + .ThrowsAsync(NotFound()); + + await CreateSubject().EnsureTopic("orders", canCreate: false, [], CancellationToken.None); + + _publisher.Verify(x => x.CreateTopicAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task EnsureTopic_DoesNotCreateExistingTopic() + { + var topicName = TopicName.FromProjectTopic("project", "orders"); + _publisher.Setup(x => x.GetTopicAsync(topicName, It.IsAny())) + .ReturnsAsync(new Topic { TopicName = topicName }); + + await CreateSubject().EnsureTopic("orders", canCreate: true, [], CancellationToken.None); + + _publisher.Verify(x => x.CreateTopicAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task EnsureTopic_IgnoresConcurrentCreation() + { + var topicName = TopicName.FromProjectTopic("project", "orders"); + _publisher.Setup(x => x.GetTopicAsync(topicName, It.IsAny())) + .ThrowsAsync(NotFound()); + _publisher.Setup(x => x.CreateTopicAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(AlreadyExists()); + + var act = () => CreateSubject().EnsureTopic("orders", canCreate: true, [], CancellationToken.None); + + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task EnsureSubscription_CreatesMissingPullSubscriptionAndAppliesOptions() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ThrowsAsync(NotFound()); + _subscriber.Setup(x => x.CreateSubscriptionAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((Subscription subscription, CancellationToken _) => subscription); + + await CreateSubject().EnsureSubscription( + "orders", + "orders-worker", + [subscription => subscription.AckDeadlineSeconds = 60], + CancellationToken.None); + + _subscriber.Verify(x => x.CreateSubscriptionAsync(It.Is(subscription => + subscription.SubscriptionName == subscriptionName && + subscription.Topic == "projects/project/topics/orders" && + subscription.AckDeadlineSeconds == 60), It.IsAny()), Times.Once); + } + + [Fact] + public async Task EnsureSubscription_DoesNotCreateExistingMatchingSubscription() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ReturnsAsync(new Subscription + { + SubscriptionName = subscriptionName, + TopicAsTopicName = TopicName.FromProjectTopic("project", "orders") + }); + + await CreateSubject().EnsureSubscription("orders", "orders-worker", [], CancellationToken.None); + + _subscriber.Verify(x => x.CreateSubscriptionAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task EnsureSubscription_RejectsExistingSubscriptionForDifferentTopic() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ReturnsAsync(new Subscription + { + SubscriptionName = subscriptionName, + TopicAsTopicName = TopicName.FromProjectTopic("project", "other") + }); + + var act = () => CreateSubject().EnsureSubscription("orders", "orders-worker", [], CancellationToken.None); + + await act.Should().ThrowAsync() + .WithMessage("*already belongs to topic*"); + } + + [Fact] + public async Task EnsureSubscription_DoesNotCreateWhenDisabled() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ThrowsAsync(NotFound()); + _providerSettings.TopologyProvisioning.CanConsumerCreateSubscription = false; + + await CreateSubject().EnsureSubscription("orders", "orders-worker", [], CancellationToken.None); + + _subscriber.Verify(x => x.CreateSubscriptionAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task EnsureSubscription_IgnoresConcurrentCreation() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ThrowsAsync(NotFound()); + _subscriber.Setup(x => x.CreateSubscriptionAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(AlreadyExists()); + + var act = () => CreateSubject().EnsureSubscription("orders", "orders-worker", [], CancellationToken.None); + + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task EnsureSubscription_RejectsNonPullSubscription() + { + var subscriptionName = SubscriptionName.FromProjectSubscription("project", "orders-worker"); + _subscriber.Setup(x => x.GetSubscriptionAsync(subscriptionName, It.IsAny())) + .ThrowsAsync(NotFound()); + + var act = () => CreateSubject().EnsureSubscription( + "orders", + "orders-worker", + [subscription => subscription.PushConfig = new PushConfig { PushEndpoint = "https://example.test/messages" }], + CancellationToken.None); + + await act.Should().ThrowAsync() + .WithMessage("*pull subscription*"); + } + + private static RpcException NotFound() + => new(new Status(StatusCode.NotFound, "not found")); + + private static RpcException AlreadyExists() + => new(new Status(StatusCode.AlreadyExists, "already exists")); +} diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/SlimMessageBus.Host.GooglePubSub.Test.csproj b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/SlimMessageBus.Host.GooglePubSub.Test.csproj new file mode 100644 index 00000000..29b16edc --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/SlimMessageBus.Host.GooglePubSub.Test.csproj @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/Usings.cs b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/Usings.cs new file mode 100644 index 00000000..d54ea84a --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/Usings.cs @@ -0,0 +1,24 @@ +global using AwesomeAssertions; + +global using Google.Cloud.PubSub.V1; + +global using Grpc.Core; + +global using Microsoft.Extensions.Configuration; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.Logging.Abstractions; + +global using Moq; + +global using SlimMessageBus; +global using SlimMessageBus.Host; +global using SlimMessageBus.Host.Collections; +global using SlimMessageBus.Host.Interceptor; +global using SlimMessageBus.Host.Serialization; +global using SlimMessageBus.Host.Serialization.SystemTextJson; +global using SlimMessageBus.Host.Test.Common.IntegrationTest; + +global using Testcontainers.PubSub; + +global using Xunit; +global using Xunit.Abstractions; diff --git a/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/appsettings.json b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/appsettings.json new file mode 100644 index 00000000..0967ef42 --- /dev/null +++ b/src/Tests/SlimMessageBus.Host.GooglePubSub.Test/appsettings.json @@ -0,0 +1 @@ +{}