Table of Contents

Google Pub/Sub Transport

BareWire can run on Google Cloud Pub/Sub through the BareWire.Transport.Google.PubSub adapter, built on the low-level PublisherServiceApiClient / SubscriberServiceApiClient from Google.Cloud.PubSub.V1. As with every BareWire transport, you register the core engine and the transport adapter together — with the single-call bundle package or the explicit two-call form.

Registration

The BareWire.Google.PubSub bundle depends on both the core and the Pub/Sub transport and exposes one method, AddBareWireWithPubSub. Configure the transport in the first delegate and (optionally) the bus in the second:

builder.Services.AddBareWireWithPubSub(
    transport => transport.ProjectId("my-gcp-project"),
    bus =>
    {
        // middleware, serializers...
    });

The bus delegate is optional — omit it when transport defaults are enough:

builder.Services.AddBareWireWithPubSub(transport => transport.ProjectId("my-gcp-project"));

Two calls — core and transport registered separately

AddBareWireWithPubSub is sugar over the explicit pair. Use the two-call form when you reference the core and transport packages separately:

builder.Services.AddBareWirePubSub(transport => transport.ProjectId("my-gcp-project"));
builder.Services.AddBareWire(bus => { /* middleware, serializer mappings... */ });

Both paths configure the transport through the same IPubSubConfigurator fluent API described below. See Configuration for the general bundle-vs-two-call story.

Authentication

The transport supports three authentication modes, selected by the configurator. The active mode is exposed by the PubSubAuthMode enum (ApplicationDefault, ServiceAccountJson, EmulatorInsecure).

Application Default Credentials (default)

UseApplicationDefaultCredentials() uses the Google ADC chain — the GOOGLE_APPLICATION_CREDENTIALS environment variable, the gcloud CLI, Workload Identity, or the Compute Engine metadata server. It is the default (so the call may be omitted) and the preferred mode for production, because no secrets are stored in the options.

Service account JSON key

Supply a service account key either by file path or as inline JSON content:

builder.Services.AddBareWirePubSub(cfg =>
{
    cfg.ProjectId("my-gcp-project");
    cfg.UseServiceAccountJson("/etc/secrets/sa.json");   // file path
    // or: cfg.UseServiceAccountJsonContent(jsonString); // inline JSON
});

The JSON key content is never logged, never included in diagnostic output, and never echoed in exception messages. The file path itself is treated as non-secret and may appear in diagnostics — the key material it points to is not.

Local emulator

UseEmulator(endpoint) connects to a local Pub/Sub emulator over plaintext (insecure) gRPC. It is intended for local development and integration tests only:

builder.Services.AddBareWirePubSub(cfg =>
{
    cfg.ProjectId("test-project");
    cfg.UseEmulator("localhost:8085");  // sets AuthMode = EmulatorInsecure
});

An emulator endpoint set under any non-emulator auth mode is rejected at startup, so production credentials can never be silently downgraded to plaintext gRPC.

Receive endpoints

A receive endpoint binds one or more consumers to a Pub/Sub subscription. The endpoint name is the subscription id:

builder.Services.AddBareWireWithPubSub(
    transport =>
    {
        transport.ProjectId("my-gcp-project");
        transport.MaxInFlightMessages(200);

        transport.ReceiveEndpoint("orders-sub", e =>
        {
            e.PrefetchCount = 32;           // in-flight credit limit enforced by the BareWire core
            e.ConcurrentMessageLimit = 8;   // concurrent handler invocations
            e.RetryCount = 3;
            e.RetryInterval = TimeSpan.FromSeconds(1);

            e.Consumer<OrderCreatedConsumer, OrderCreated>();
        });
    });

builder.Services.AddTransient<OrderCreatedConsumer>();

Consumers are resolved from the container, so register each consumer type (for example services.AddTransient<OrderCreatedConsumer>()). The topic and subscription must already exist — topology is manual, so provision them out of band (infrastructure as code, gcloud, or a deployment step) before the bus starts. An endpoint can also host a raw consumer (e.RawConsumer<T>()), a saga state machine (e.StateMachineSaga<T>()), several typed consumers, and per-key ordering; see Publishing and Consuming.

Things to know:

  • PrefetchCount is not a Pub/Sub setting. It is the credit limit the BareWire core uses to bound unsettled messages for the endpoint; the per-pull message cap is MaxOutstandingMessages.
  • MaxInFlightMessages is shared by all endpoints on the transport. Slots are reserved atomically before each pull, and a pull never asks Pub/Sub for more messages than the free slots, so a message is never pulled only to be skipped. Each endpoint also buffers at most its PrefetchCount messages. When the limit is exhausted, pulling pauses until a slot frees up. If a pulled message still cannot be registered, it is returned to the subscription immediately (acknowledgement deadline set to 0, in one call) instead of waiting for the acknowledgement deadline to expire. Sizing MaxInFlightMessages to at least the sum of the PrefetchCount values of all endpoints is a performance hint, not a correctness requirement: with a smaller limit, an endpoint may wait for a free slot.
  • Poison messages: a failing message is released for redelivery. It only reaches a dead-letter topic if the subscription has a DeadLetterPolicy (see Dead-letter topics). Without one, a poison message is redelivered indefinitely.
  • IBus.ConnectReceiveEndpoint (adding an endpoint at runtime) is not supported yet; declare every endpoint in the transport delegate.
  • Only one transport can be registered per service collection: registering a second, different transport throws BareWireConfigurationException, and support for hosting several transports in one service collection is planned.
  • Calling AddBareWirePubSub a second time on one service collection also throws BareWireConfigurationException; declare every receive endpoint in a single call.

Ordering keys

Call EnableMessageOrdering() so subscriptions are created with enable_message_ordering during topology deployment:

builder.Services.AddBareWirePubSub(cfg =>
{
    cfg.ProjectId("my-gcp-project");
    cfg.EnableMessageOrdering();
});

When a message carries the BW-OrderingKey header, that value is passed through to and from the PubsubMessage.OrderingKey field, so messages sharing a key are delivered in order. See Per-Key Consumer Ordering for the consumer-side "parallel across keys, ordered within a key" model that pairs with this.

Dead-letter topics

The adapter wires a native DeadLetterPolicy onto subscriptions during topology deployment when the bw.pubsub.dead-letter-topic and bw.pubsub.max-delivery-attempts arguments are set: messages exceeding the configured delivery-attempt count are forwarded to the dead-letter topic instead of being redelivered indefinitely. For this to work, the subscription's service account requires the roles/pubsub.publisher IAM role on the dead-letter topic — environment/IAM configuration granted outside BareWire.

Minimum IAM roles

Grant only the roles each part of the transport needs:

Capability Role Used for
Consume roles/pubsub.subscriber on the subscription pull, acknowledge and modify the acknowledgement deadline
Publish roles/pubsub.publisher on the topic publish
Deploy topology roles/pubsub.editor on the project (or equivalent custom role) create topics and subscriptions

Publishing and topology deployment are separate from consuming: an application that only consumes does not need the publisher or editor roles, and an application that deploys topology out of band does not need the editor role at runtime. For dead-lettering, see Dead-letter topics for the additional roles Pub/Sub requires.

Header mapping

BareWire headers are stored in PubsubMessage.Attributes (string-to-string). Pub/Sub enforces a maximum of 100 attributes per message, keys up to 256 UTF-8 bytes, and values up to 1024 UTF-8 bytes. Violations throw BareWireTransportException; the exception reports only counts and lengths, never the offending key text or values.

Options

All settings are configured through IPubSubConfigurator:

Method Default Meaning
ProjectId(string) — (required) Google Cloud project ID. Required in every auth mode.
AckDeadline(TimeSpan) 60 s Acknowledgement deadline applied to subscriptions at topology deploy time. Must be between 10 and 600 seconds.
MaxOutstandingMessages(int) 1000 Maximum messages retrieved per PullAsync call — the cap on outstanding unacknowledged messages.
MaxOutstandingBytes(long) 67,108,864 (64 MiB) Maximum total byte size of in-flight message bodies.
MaxInFlightMessages(int) 100 Maximum concurrent in-flight (consumed but not yet settled) messages tracked by the registry.
EnableMessageOrdering() off Creates subscriptions with message ordering enabled.
ReceiveEndpoint(string, Action<IReceiveEndpointConfigurator>) — Binds consumers to a subscription (endpoint name = subscription id). See Receive endpoints.
builder.Services.AddBareWirePubSub(cfg =>
{
    cfg.ProjectId("my-gcp-project");
    cfg.UseApplicationDefaultCredentials();
    cfg.AckDeadline(TimeSpan.FromSeconds(60));
    cfg.MaxOutstandingMessages(1000);
    cfg.MaxOutstandingBytes(64L * 1024 * 1024);
    cfg.MaxInFlightMessages(100);
});

MaxInFlightMessages, MaxOutstandingMessages, and MaxOutstandingBytes map directly onto BareWire's flow-control model: the in-flight registry size, the per-pull message cap, and the in-flight byte budget.

See also