Bundle: redb-route / redb.Route.Firebase (redb.Route.Firebase.txt), 29 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Firebase/AssemblyInfo.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/AssemblyInfo.cs
----
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("redb.Route.Tests.Firebase")]
Path: redb-route/redb.Route.Firebase/Auth/FirebaseCredentialProvider.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Auth/FirebaseCredentialProvider.cs
----
using System.Collections.Concurrent;
using FirebaseAdmin;
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Firestore;
using Google.Cloud.Storage.V1;
namespace redb.Route.Firebase;
///
/// Resolves Firebase credentials from:
/// 1. Explicit JSON path (credentialPath argument, else )
/// 2. GOOGLE_APPLICATION_CREDENTIALS env var (Application Default Credentials)
/// 3. Emulator env vars — FIRESTORE_EMULATOR_HOST (Firestore),
/// STORAGE_EMULATOR_HOST (Storage) — via .
///
/// Firebase apps are created as NAMED instances (never the process-global [DEFAULT]),
/// so the connector coexists with a host that initialized Firebase Admin SDK itself, and one
/// process can serve several service accounts. Apps are cached per
/// (credentialPath, projectId), Firestore clients per (projectId, credentialPath),
/// storage clients per credentialPath. Thread-safe.
///
///
/// Public so a named instance can be put into the context registry and referenced from
/// endpoint URIs via connectionFactory=…:
///
/// context.AddToRegistry("myFirebase", new FirebaseCredentialProvider
/// {
/// DefaultProjectId = "my-project",
/// DefaultCredentialPath = "/secrets/firebase-sa.json",
/// });
/// // fstore://orders?connectionFactory=myFirebase
///
///
///
public sealed class FirebaseCredentialProvider : IFirebaseCredentialProvider, IDisposable
{
private readonly ConcurrentDictionary> _apps = new();
private readonly ConcurrentDictionary> _firestoreDbs = new();
private readonly ConcurrentDictionary> _storageClients = new();
private readonly string _instanceId = Guid.NewGuid().ToString("N")[..8];
private int _appCounter;
/// Project ID used when the endpoint does not specify one.
public string? DefaultProjectId { get; init; }
/// Service-account JSON path used when the endpoint does not specify one.
public string? DefaultCredentialPath { get; init; }
///
public FirebaseApp GetOrCreateApp(string? credentialPath = null, string? projectId = null)
{
var credPath = credentialPath ?? DefaultCredentialPath;
var pid = projectId ?? DefaultProjectId;
// Lazy inside GetOrAdd so a racing second factory never creates a throwaway app.
return _apps.GetOrAdd($"{credPath}\n{pid}", _ => new Lazy(() =>
{
var options = new AppOptions
{
Credential = credPath is not null
? LoadCredential(credPath)
: GoogleCredential.GetApplicationDefault(),
};
if (!string.IsNullOrWhiteSpace(pid))
options.ProjectId = pid;
// Named app: the host's [DEFAULT] instance is never touched.
var name = $"redb.route:{_instanceId}:{Interlocked.Increment(ref _appCounter)}";
return FirebaseApp.Create(options, name);
})).Value;
}
///
public FirestoreDb GetFirestoreDb(string? projectId = null, string? credentialPath = null, string? databaseId = null)
{
var credPath = credentialPath ?? DefaultCredentialPath;
var pid = projectId
?? DefaultProjectId
?? Environment.GetEnvironmentVariable("FIREBASE_PROJECT")
?? throw new InvalidOperationException(
"Firebase project id is not configured. Set it on the endpoint (?projectId=...), " +
"in AddRedbRouteFirebase(o => o.ProjectId = ...), on the credential provider " +
"(DefaultProjectId), or via the FIREBASE_PROJECT environment variable.");
// Lazy inside GetOrAdd so a racing second factory never builds a throwaway client.
return _firestoreDbs.GetOrAdd(
$"{pid}\n{credPath}\n{databaseId}",
_ => new Lazy(() =>
{
var builder = new FirestoreDbBuilder
{
ProjectId = pid,
DatabaseId = databaseId,
EmulatorDetection = EmulatorDetection.EmulatorOrProduction,
};
if (credPath is not null)
builder.GoogleCredential = LoadCredential(credPath);
return builder.Build();
})).Value;
}
///
public StorageClient GetStorageClient(string? credentialPath = null)
{
var credPath = credentialPath ?? DefaultCredentialPath;
return _storageClients.GetOrAdd(
credPath ?? "",
_ => new Lazy(() =>
{
var builder = new StorageClientBuilder
{
EmulatorDetection = EmulatorDetection.EmulatorOrProduction,
};
if (credPath is not null)
builder.GoogleCredential = LoadCredential(credPath);
return builder.Build();
})).Value;
}
///
public UrlSigner GetUrlSigner(string? credentialPath = null)
{
var credPath = credentialPath
?? DefaultCredentialPath
?? Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")
?? throw new InvalidOperationException(
"Signed URLs require a service-account JSON with a private key to sign with — " +
"set credentialPath on the endpoint, DefaultCredentialPath on the provider, " +
"or GOOGLE_APPLICATION_CREDENTIALS. Plain ADC cannot sign.");
return _urlSigners.GetOrAdd(
credPath,
_ => new Lazy(() => UrlSigner.FromCredential(LoadCredential(credPath)))).Value;
}
private readonly ConcurrentDictionary> _urlSigners = new();
private static GoogleCredential LoadCredential(string credentialPath)
{
// GoogleCredential.FromStream is deprecated in favor of CredentialFactory,
// but CredentialFactory is not available in all target framework versions.
#pragma warning disable CS0618
using var stream = File.OpenRead(credentialPath);
return GoogleCredential.FromStream(stream);
#pragma warning restore CS0618
}
///
public void Dispose()
{
foreach (var client in _storageClients.Values)
{
if (client.IsValueCreated)
client.Value.Dispose();
}
// Delete only OUR named apps — a host-owned [DEFAULT] is never ours.
foreach (var app in _apps.Values)
{
if (app.IsValueCreated)
app.Value.Delete();
}
}
}
Path: redb-route/redb.Route.Firebase/Auth/IFirebaseCredentialProvider.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Auth/IFirebaseCredentialProvider.cs
----
using FirebaseAdmin;
using Google.Cloud.Firestore;
using Google.Cloud.Storage.V1;
namespace redb.Route.Firebase;
///
/// Abstraction for Firebase credential resolution.
/// Enables mocking in unit tests without real service accounts.
///
public interface IFirebaseCredentialProvider
{
///
/// Gets or creates a using the specified credentials.
/// Thread-safe with lazy initialization.
///
/// Optional path to service-account JSON file.
/// Optional Firebase project ID override.
/// Initialized instance.
FirebaseApp GetOrCreateApp(string? credentialPath = null, string? projectId = null);
///
/// Gets a for the specified project. Clients are cached per
/// (projectId, credentialPath) pair. Detects FIRESTORE_EMULATOR_HOST
/// for local development; falls back to production with the given service-account file
/// or Application Default Credentials.
///
/// Optional project ID override.
/// Optional path to service-account JSON file.
/// Firestore database client.
FirestoreDb GetFirestoreDb(string? projectId = null, string? credentialPath = null, string? databaseId = null);
///
/// Gets a . Clients are cached per .
/// Detects STORAGE_EMULATOR_HOST for local development; falls back to production
/// with the given service-account file or Application Default Credentials.
///
/// Optional path to service-account JSON file.
/// Google Cloud Storage client.
StorageClient GetStorageClient(string? credentialPath = null);
///
/// Gets a for signed download URLs. Requires a service-account
/// JSON with a private key — plain ADC cannot sign. Default implementation throws
/// so test doubles stay small.
///
/// Optional path to service-account JSON file.
UrlSigner GetUrlSigner(string? credentialPath = null)
=> throw new NotSupportedException(
$"{GetType().Name} does not provide a UrlSigner.");
}
Path: redb-route/redb.Route.Firebase/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Firebase;
///
/// Extension methods for registering Firebase components (FCM, Firestore, Storage) in DI.
///
public static class ServiceCollectionExtensions
{
///
/// Registers all Firebase components (fcm://, fstore://, fbstorage://) in the route context.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteFirebase();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteFirebase(
this IServiceCollection services,
Action? configure = null)
{
var options = new FirebaseOptions();
configure?.Invoke(options);
services.AddSingleton(sp =>
{
var provider = new FirebaseCredentialProvider
{
DefaultProjectId = options.ProjectId,
DefaultCredentialPath = options.CredentialPath,
};
// Fail fast on an unreadable credential file at registration time.
if (options.CredentialPath is not null)
provider.GetOrCreateApp(options.CredentialPath, options.ProjectId);
return provider;
});
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup —
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var credProvider = sp.GetRequiredService();
var fcm = sp.GetRequiredService();
fcm.CredentialProvider = credProvider;
context.AddComponent(fcm);
var firestore = sp.GetRequiredService();
firestore.CredentialProvider = credProvider;
context.AddComponent(firestore);
var storage = sp.GetRequiredService();
storage.CredentialProvider = credProvider;
context.AddComponent(storage);
});
return services;
}
}
///
/// Configuration options for the Firebase connector registration.
///
public sealed class FirebaseOptions
{
/// Path to the Firebase service-account JSON file.
public string? CredentialPath { get; set; }
/// Firebase/GCP project ID.
public string? ProjectId { get; set; }
}
Path: redb-route/redb.Route.Firebase/Fcm/FcmComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Fcm/FcmComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Firebase;
///
/// FCM component registered with scheme fcm.
/// Creates producer-only endpoints for sending push notifications.
///
[EndpointRole(EndpointRole.Producer, Hint = "FCM messages are received on client devices.")]
internal sealed class FcmComponent : ComponentBase
{
///
public override string Scheme => "fcm";
/// Shared credential provider. Set by DI registration or manually.
internal IFirebaseCredentialProvider? CredentialProvider { get; set; }
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new FcmEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new FcmEndpoint(uri, this, options);
}
}
///
/// FCM endpoint. Producer-only — consumers are not supported
/// (FCM messages are received on client devices, not server-side).
///
internal sealed class FcmEndpoint : EndpointBase
{
internal FcmEndpoint(EndpointUri uri, FcmComponent component, FcmEndpointOptions options)
: base(uri, component, options) { }
/// The owning FCM component.
internal FcmComponent FcmComponent => (FcmComponent)Component;
/// Typed options for external access.
internal FcmEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer()
=> new FcmProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
=> throw new NotSupportedException(
"FCM does not support server-side consumers. Messages are received on client devices.");
}
Path: redb-route/redb.Route.Firebase/Fcm/FcmEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Fcm/FcmEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Firebase;
///
/// Endpoint options for the FCM (Firebase Cloud Messaging) component.
/// FCM is producer-only — push notifications are sent to devices, topics, or conditions.
///
public sealed class FcmEndpointOptions : EndpointOptions
{
// ── Auth ──
/// Path to the Firebase service-account JSON file.
public string? CredentialPath { get; set; }
/// Firebase project ID.
public string? ProjectId { get; set; }
/// Named reference from the registry.
[RegistryReference(typeof(IFirebaseCredentialProvider))]
public string? ConnectionFactory { get; set; }
// ── Operation ──
/// Producer operation: Send (default), Multicast, Subscribe/UnsubscribeFromTopic.
public FcmOperationType Operation { get; set; } = FcmOperationType.Send;
// ── Target ──
/// Message target type: Token, Topic, or Condition (Send operation only).
public FcmMessageType MessageType { get; set; } = FcmMessageType.Token;
/// Device registration token. Supports ${...} expressions.
[Sensitive]
public DynamicValue? Token { get; set; }
/// Topic name for topic-based targeting. Supports ${...} expressions.
public DynamicValue? Topic { get; set; }
/// Topic condition expression. Supports ${...} expressions.
public DynamicValue? Condition { get; set; }
// ── Notification ──
/// Notification title. Supports ${...} expressions.
public DynamicValue? Title { get; set; }
/// Notification body text. Overrides exchange.In.Body. Supports ${...} expressions.
public DynamicValue? Body { get; set; }
/// Notification image URL.
public string? ImageUrl { get; set; }
// ── Android ──
/// Android notification priority: "normal" or "high".
public string? AndroidPriority { get; set; }
/// Time-to-live for Android push notifications (seconds).
public int? AndroidTtlSeconds { get; set; }
/// Android notification channel ID.
public string? AndroidChannelId { get; set; }
// ── APNS (iOS) ──
/// APNS priority: "5" (normal) or "10" (immediate).
public string? ApnsPriority { get; set; }
/// APNS collapse identifier for notification grouping.
public string? ApnsCollapseId { get; set; }
/// Enable APNS content-available for background updates.
public bool? ApnsContentAvailable { get; set; }
/// Enable APNS mutable-content for Notification Service Extension.
public bool? ApnsMutableContent { get; set; }
// ── Web (VAPID) ──
/// Click action URL for web push notifications.
public string? WebPushLink { get; set; }
// ── Data ──
/// Send as data-only message (no visible notification).
public bool DataOnly { get; set; }
/// Validate message without actually sending.
public bool DryRun { get; set; }
///
public override void Validate()
{
if (string.IsNullOrWhiteSpace(CredentialPath)
&& string.IsNullOrWhiteSpace(ConnectionFactory)
&& string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")))
throw new ArgumentOutOfRangeException(nameof(CredentialPath),
"CredentialPath, ConnectionFactory, or GOOGLE_APPLICATION_CREDENTIALS is required");
// Target checks apply to the classic Send only: multicast takes tokens from the
// body/header, topic management takes the Topic option.
if (Operation == FcmOperationType.Send)
{
if (MessageType == FcmMessageType.Token && Token is null)
throw new ArgumentOutOfRangeException(nameof(Token),
"Token is required for Token message type");
if (MessageType == FcmMessageType.Topic && Topic is null)
throw new ArgumentOutOfRangeException(nameof(Topic),
"Topic is required for Topic message type");
if (MessageType == FcmMessageType.Condition && Condition is null)
throw new ArgumentOutOfRangeException(nameof(Condition),
"Condition is required for Condition message type");
}
if (Operation is FcmOperationType.SubscribeToTopic or FcmOperationType.UnsubscribeFromTopic
&& Topic is null)
throw new ArgumentOutOfRangeException(nameof(Topic),
$"Topic is required for the {Operation} operation");
if (AndroidTtlSeconds is not null && AndroidTtlSeconds < 0)
throw new ArgumentOutOfRangeException(nameof(AndroidTtlSeconds),
"AndroidTtlSeconds must be >= 0");
}
}
Path: redb-route/redb.Route.Firebase/Fcm/FcmHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Fcm/FcmHeaders.cs
----
namespace redb.Route.Firebase;
///
/// Header constants for the FCM connector. Prefix: redbFcm.
///
public static class FcmHeaders
{
/// Common prefix for all FCM headers.
public const string Prefix = "redbFcm.";
// ── Set by producer after send ──
/// FCM message ID returned by the server (projects/*/messages/*).
public const string MessageId = "redbFcm.MessageId";
/// Success count for Multicast and topic-management operations.
public const string SuccessCount = "redbFcm.SuccessCount";
/// Failure count for Multicast and topic-management operations.
public const string FailureCount = "redbFcm.FailureCount";
// ── Read from exchange for targeting ──
/// Device registration token override (from exchange header).
public const string Token = "redbFcm.Token";
///
/// Device tokens for Multicast/Subscribe/Unsubscribe: an IEnumerable<string> or a
/// comma-separated string. Overrides the exchange body.
///
public const string Tokens = "redbFcm.Tokens";
/// Topic name override (from exchange header).
public const string Topic = "redbFcm.Topic";
/// Topic condition expression override (from exchange header).
public const string Condition = "redbFcm.Condition";
// ── Notification payload from headers ──
/// Notification title override.
public const string Title = "redbFcm.Title";
/// Notification body override.
public const string Body = "redbFcm.Body";
/// Notification image URL.
public const string ImageUrl = "redbFcm.ImageUrl";
// ── Data payload ──
///
/// Prefix for data entries. Headers starting with redbFcm.Data. are sent
/// as key-value pairs in the FCM data payload.
/// Example: redbFcm.Data.orderId → data key orderId.
///
public const string DataPrefix = "redbFcm.Data.";
}
Path: redb-route/redb.Route.Firebase/Fcm/FcmMessageType.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Fcm/FcmMessageType.cs
----
namespace redb.Route.Firebase;
///
/// FCM message target type. Determines how the push notification is addressed.
///
public enum FcmMessageType
{
/// Send to a specific device registration token.
Token,
/// Send to all subscribers of a topic.
Topic,
/// Send to devices matching a topic condition expression.
Condition
}
///
/// FCM producer operation. is the classic single-message send;
/// the rest are later additions (multicast and topic management).
///
public enum FcmOperationType
{
/// Send one message to a token/topic/condition (default).
Send,
/// Send the same message to many device tokens (body or Tokens header).
Multicast,
/// Subscribe device tokens (body or Tokens header) to the topic.
SubscribeToTopic,
/// Unsubscribe device tokens (body or Tokens header) from the topic.
UnsubscribeFromTopic
}
Path: redb-route/redb.Route.Firebase/Fcm/FcmProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Fcm/FcmProducer.cs
----
using System.Diagnostics;
using System.Text.Json;
using FcmMessage = FirebaseAdmin.Messaging.Message;
using FcmNotification = FirebaseAdmin.Messaging.Notification;
using FirebaseAdmin.Messaging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Firebase;
///
/// FCM producer — sends push notifications via Firebase Cloud Messaging HTTP v1 API.
/// Supports Token, Topic, and Condition targeting with platform-specific configuration.
///
internal sealed class FcmProducer : ConnectableProducer
{
private readonly FcmEndpoint _endpoint;
private readonly FcmEndpointOptions _options;
private FirebaseMessaging? _messaging;
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => _endpoint.Uri.NormalizedKey;
internal FcmProducer(FcmEndpoint endpoint, FcmEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
}
///
protected override Task ConnectAsync(CancellationToken ct)
{
var provider = ResolveCredentialProvider();
var app = provider.GetOrCreateApp(_options.CredentialPath, _options.ProjectId);
_messaging = FirebaseMessaging.GetMessaging(app);
return Task.CompletedTask;
}
///
protected override Task DisconnectAsync(CancellationToken ct)
{
_messaging = null;
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"fcm {_options.Operation}", ActivityKind.Producer,
"messaging.system", "fcm",
_endpoint.Uri.NormalizedKey,
operation: _options.Operation.ToString().ToLowerInvariant());
try
{
switch (_options.Operation)
{
case FcmOperationType.Send:
await ProcessSend(exchange, activity, ct).ConfigureAwait(false);
break;
case FcmOperationType.Multicast:
await ProcessMulticast(exchange, activity, ct).ConfigureAwait(false);
break;
case FcmOperationType.SubscribeToTopic:
case FcmOperationType.UnsubscribeFromTopic:
await ProcessTopicManagement(exchange, activity).ConfigureAwait(false);
break;
default:
throw new InvalidOperationException($"Unknown FCM operation: {_options.Operation}");
}
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the call is a stop; any other failure marks the span.
activity.RecordFailure(ex);
throw;
}
}
private async Task ProcessSend(IExchange exchange, Activity? activity, CancellationToken ct)
{
var message = BuildMessage(exchange);
// Destination for the span: topic/condition are addresses, a device token is a secret —
// it goes into telemetry only as the literal "token".
activity?.SetTag("messaging.destination.name", message.Topic ?? message.Condition ?? "token");
var messageId = await _messaging!.SendAsync(message, _options.DryRun, ct).ConfigureAwait(false);
exchange.In.Headers[FcmHeaders.MessageId] = messageId;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
private async Task ProcessMulticast(IExchange exchange, Activity? activity, CancellationToken ct)
{
var tokens = ResolveTokens(exchange);
activity?.SetTag("messaging.destination.name", "multicast");
var message = new MulticastMessage { Tokens = tokens };
FillPayload(message, exchange);
var response = await _messaging!.SendEachForMulticastAsync(message, _options.DryRun, ct)
.ConfigureAwait(false);
exchange.In.Headers[FcmHeaders.SuccessCount] = response.SuccessCount;
exchange.In.Headers[FcmHeaders.FailureCount] = response.FailureCount;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
private async Task ProcessTopicManagement(IExchange exchange, Activity? activity)
{
var topic = exchange.In.GetHeader(FcmHeaders.Topic)
?? _options.Topic?.Resolve(exchange)
?? throw new InvalidOperationException(
$"FCM Topic is required for the {_options.Operation} operation");
var tokens = ResolveTokens(exchange);
activity?.SetTag("messaging.destination.name", topic);
var response = _options.Operation == FcmOperationType.SubscribeToTopic
? await _messaging!.SubscribeToTopicAsync(tokens, topic).ConfigureAwait(false)
: await _messaging!.UnsubscribeFromTopicAsync(tokens, topic).ConfigureAwait(false);
exchange.In.Headers[FcmHeaders.SuccessCount] = response.SuccessCount;
exchange.In.Headers[FcmHeaders.FailureCount] = response.FailureCount;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
/// Tokens for Multicast/Subscribe/Unsubscribe: Tokens header wins over the body.
private static IReadOnlyList ResolveTokens(IExchange exchange)
{
var source = exchange.In.Headers.TryGetValue(FcmHeaders.Tokens, out var header) && header is not null
? header
: exchange.In.Body;
return source switch
{
IReadOnlyList list => list,
IEnumerable seq => seq.ToList(),
string csv => csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
_ => throw new InvalidOperationException(
"Device tokens are required: pass IEnumerable (or a comma-separated string) " +
$"as the body or in the '{FcmHeaders.Tokens}' header."),
};
}
///
/// Payload for a multicast message. Unlike there are no
/// body-fallbacks: the exchange body carries the TOKENS, not the notification text.
///
private void FillPayload(MulticastMessage message, IExchange exchange)
{
if (!_options.DataOnly)
{
var title = exchange.In.GetHeader(FcmHeaders.Title)
?? _options.Title?.Resolve(exchange);
var body = exchange.In.GetHeader(FcmHeaders.Body)
?? _options.Body?.Resolve(exchange);
if (title is not null || body is not null)
{
message.Notification = new FcmNotification
{
Title = title,
Body = body,
ImageUrl = exchange.In.GetHeader(FcmHeaders.ImageUrl) ?? _options.ImageUrl
};
}
}
var data = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (key.StartsWith(FcmHeaders.DataPrefix, StringComparison.Ordinal) && value is not null)
data[key[FcmHeaders.DataPrefix.Length..]] = value.ToString()!;
}
if (data.Count > 0)
message.Data = data;
message.Android = BuildAndroidConfig();
message.Apns = BuildApnsConfig();
message.Webpush = BuildWebpushConfig();
}
private FcmMessage BuildMessage(IExchange exchange)
{
var message = new FcmMessage();
// 1. Target resolution (header override > option)
switch (_options.MessageType)
{
case FcmMessageType.Token:
message.Token = exchange.In.GetHeader(FcmHeaders.Token)
?? _options.Token?.Resolve(exchange)
?? throw new InvalidOperationException("FCM Token is required but not set");
break;
case FcmMessageType.Topic:
message.Topic = exchange.In.GetHeader(FcmHeaders.Topic)
?? _options.Topic?.Resolve(exchange)
?? throw new InvalidOperationException("FCM Topic is required but not set");
break;
case FcmMessageType.Condition:
message.Condition = exchange.In.GetHeader(FcmHeaders.Condition)
?? _options.Condition?.Resolve(exchange)
?? throw new InvalidOperationException("FCM Condition is required but not set");
break;
}
// 2. Notification (unless DataOnly)
if (!_options.DataOnly)
{
var title = exchange.In.GetHeader(FcmHeaders.Title)
?? _options.Title?.Resolve(exchange);
var body = exchange.In.GetHeader(FcmHeaders.Body)
?? _options.Body?.Resolve(exchange)
?? exchange.In.Body?.ToString();
if (title is not null || body is not null)
{
message.Notification = new FcmNotification
{
Title = title,
Body = body,
ImageUrl = exchange.In.GetHeader(FcmHeaders.ImageUrl) ?? _options.ImageUrl
};
}
}
// 3. Data payload from headers with prefix
var data = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (key.StartsWith(FcmHeaders.DataPrefix, StringComparison.Ordinal) && value is not null)
data[key[FcmHeaders.DataPrefix.Length..]] = value.ToString()!;
}
// For DataOnly: body as Dictionary or JSON
if (_options.DataOnly && exchange.In.Body is not null)
{
if (exchange.In.Body is IDictionary bodyDict)
{
foreach (var kv in bodyDict)
data[kv.Key] = kv.Value;
}
else if (exchange.In.Body is IDictionary bodyObjDict)
{
foreach (var kv in bodyObjDict)
data[kv.Key] = kv.Value?.ToString() ?? "";
}
else
{
data["payload"] = exchange.In.Body.ToString() ?? "";
}
}
if (data.Count > 0)
message.Data = data;
// 4. Platform-specific configuration
message.Android = BuildAndroidConfig();
message.Apns = BuildApnsConfig();
message.Webpush = BuildWebpushConfig();
return message;
}
private AndroidConfig? BuildAndroidConfig()
{
if (_options.AndroidPriority is null && _options.AndroidTtlSeconds is null && _options.AndroidChannelId is null)
return null;
var config = new AndroidConfig();
if (_options.AndroidPriority is not null)
config.Priority = _options.AndroidPriority.Equals("high", StringComparison.OrdinalIgnoreCase)
? Priority.High : Priority.Normal;
if (_options.AndroidTtlSeconds is not null)
config.TimeToLive = TimeSpan.FromSeconds(_options.AndroidTtlSeconds.Value);
if (_options.AndroidChannelId is not null)
config.Notification = new AndroidNotification { ChannelId = _options.AndroidChannelId };
return config;
}
private ApnsConfig? BuildApnsConfig()
{
if (_options.ApnsPriority is null && _options.ApnsCollapseId is null
&& _options.ApnsContentAvailable is null && _options.ApnsMutableContent is null)
return null;
var config = new ApnsConfig();
var headers = new Dictionary();
if (_options.ApnsPriority is not null)
headers["apns-priority"] = _options.ApnsPriority;
if (_options.ApnsCollapseId is not null)
headers["apns-collapse-id"] = _options.ApnsCollapseId;
if (headers.Count > 0)
config.Headers = headers;
if (_options.ApnsContentAvailable is not null || _options.ApnsMutableContent is not null)
{
config.Aps = new Aps();
if (_options.ApnsContentAvailable == true)
config.Aps.ContentAvailable = true;
if (_options.ApnsMutableContent == true)
config.Aps.MutableContent = true;
}
return config;
}
private WebpushConfig? BuildWebpushConfig()
{
if (_options.WebPushLink is null)
return null;
return new WebpushConfig
{
FcmOptions = new WebpushFcmOptions { Link = _options.WebPushLink }
};
}
private IFirebaseCredentialProvider ResolveCredentialProvider()
{
// 1. ConnectionFactory from registry — a set-but-unknown name fails loud.
if (!string.IsNullOrEmpty(_options.ConnectionFactory))
return _endpoint.FcmComponent.Context
.GetRequiredFromRegistry(_options.ConnectionFactory);
// 2. Fall back to component-level provider
return _endpoint.FcmComponent.CredentialProvider
?? throw new InvalidOperationException(
"No IFirebaseCredentialProvider available. Register via AddRedbRouteFirebase() or set ConnectionFactory.");
}
}
Path: redb-route/redb.Route.Firebase/Firestore/FirestoreComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Firestore/FirestoreComponent.cs
----
using Google.Cloud.Firestore;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Firebase;
///
/// Firestore component registered with scheme fstore.
/// Creates endpoints for CRUD operations and realtime listeners.
///
internal sealed class FirestoreComponent : ComponentBase
{
///
public override string Scheme => "fstore";
/// Shared credential provider. Set by DI registration or manually.
internal IFirebaseCredentialProvider? CredentialProvider { get; set; }
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new FirestoreEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new FirestoreEndpoint(uri, this, options);
}
}
///
/// Firestore endpoint. Creates producers for CRUD operations and consumers for realtime listeners.
/// The URI path specifies the collection (e.g. fstore://users, fstore://users/uid/orders).
///
internal sealed class FirestoreEndpoint : EndpointBase, IDisposable
{
private FirestoreDb? _db;
private readonly SemaphoreSlim _lock = new(1, 1);
internal FirestoreEndpoint(EndpointUri uri, FirestoreComponent component, FirestoreEndpointOptions options)
: base(uri, component, options) { }
/// Collection path from the URI.
internal string CollectionPath => Uri.Path;
/// The owning Firestore component.
internal FirestoreComponent FirestoreComponent => (FirestoreComponent)Component;
/// Typed options for external access.
internal FirestoreEndpointOptions EndpointOptions => Options;
/// Gets or creates a shared client.
internal async Task GetOrCreateDbAsync(CancellationToken ct = default)
{
if (_db is not null) return _db;
await _lock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_db is not null) return _db;
var provider = ResolveCredentialProvider();
_db = provider.GetFirestoreDb(Options.ProjectId, Options.CredentialPath, Options.DatabaseId);
return _db;
}
finally
{
_lock.Release();
}
}
///
public override IProducer CreateProducer()
=> new FirestoreProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
// ${...} in Where is producer-Query-only: the consumer query is built once per
// subscription/poll loop — there is no exchange to resolve the template against.
if (Options.Where?.Contains("${") == true)
throw new InvalidOperationException(
"Where with ${...} expressions is supported only on the producer Query operation: " +
"the consumer query is built once per subscription, there is no exchange to resolve against.");
return Options.Realtime
? new FirestoreConsumer(this, processor, Options)
: new FirestorePollingConsumer(this, processor, Options);
}
///
public void Dispose()
{
_lock.Dispose();
}
private IFirebaseCredentialProvider ResolveCredentialProvider()
{
// A set-but-unknown name fails loud — never a silent fallback.
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
return FirestoreComponent.Context
.GetRequiredFromRegistry(Options.ConnectionFactory);
return FirestoreComponent.CredentialProvider
?? throw new InvalidOperationException(
"No IFirebaseCredentialProvider available. Register via AddRedbRouteFirebase() or set ConnectionFactory.");
}
}
Path: redb-route/redb.Route.Firebase/Firestore/FirestoreConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Firebase/Firestore/FirestoreConsumer.cs
----
using System.Diagnostics;
using System.Text.Json;
using Google.Cloud.Firestore;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Firebase;
///
/// Firestore realtime consumer — subscribes to collection snapshots via gRPC stream.
/// Each document change (Added, Modified, Removed) produces a separate exchange.
/// Uses for graceful shutdown (same pattern as MQTT consumer).
/// A permanently failed listener (revoked credentials, deleted project, callback fault) is
/// observed by a monitor task: the error is recorded on the endpoint and the subscription is
/// re-created with exponential backoff — the consumer never dies silently.
///
internal sealed class FirestoreConsumer : IConsumer
{
private static readonly TimeSpan InitialBackoff = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxBackoff = TimeSpan.FromSeconds(60);
private static readonly TimeSpan BackoffResetAfter = TimeSpan.FromMinutes(1);
private readonly FirestoreEndpoint _endpoint;
private readonly IProcessor _processor;
private readonly FirestoreEndpointOptions _options;
private readonly InflightDrainGuard _drain = new();
private readonly SemaphoreSlim _concurrency;
private FirestoreChangeListener? _listener;
private Task? _monitorTask;
private CancellationTokenSource? _monitorCts;
private ILogger? _logger;
/// Test seam: invoked with every snapshot BEFORE per-change processing.
/// A throw here faults the listener — used to exercise the resubscribe monitor.
internal Action? SnapshotInterceptor { get; set; }
///
public IEndpoint Endpoint => _endpoint;
internal FirestoreConsumer(FirestoreEndpoint endpoint, IProcessor processor, FirestoreEndpointOptions options)
{
_endpoint = endpoint;
_processor = processor;
_options = options;
_concurrency = new SemaphoreSlim(options.MaxConcurrency, options.MaxConcurrency);
_logger = (endpoint.Component as ComponentBase)?.Logger;
}
///
public async Task Start(CancellationToken ct = default)
{
_drain.Start(ct);
var db = await _endpoint.GetOrCreateDbAsync(ct).ConfigureAwait(false);
var query = BuildQuery(db);
_monitorCts = new CancellationTokenSource();
_listener = query.Listen(OnSnapshotAsync, _drain.ProcessingToken);
_monitorTask = MonitorListenerAsync(query, _monitorCts.Token);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("Firestore consumer started: {Collection}", _endpoint.CollectionPath);
}
///
public async Task Stop(CancellationToken ct = default)
{
// 1. Stop the resubscribe monitor from creating new listeners
_monitorCts?.Cancel();
// 2. Stop accepting new snapshots
var listener = _listener;
if (listener is not null)
await listener.StopAsync(ct).ConfigureAwait(false);
// 3. Let the monitor settle (it may have swapped the listener before seeing the cancel)
if (_monitorTask is not null)
{
try { await _monitorTask.ConfigureAwait(false); }
catch (OperationCanceledException) { }
}
if (!ReferenceEquals(_listener, listener) && _listener is not null)
await _listener.StopAsync(ct).ConfigureAwait(false);
// 4. Drain in-flight processing
await _drain.DrainAsync(ct, _logger, $"fstore://{_endpoint.CollectionPath}").ConfigureAwait(false);
_drain.Dispose();
_monitorCts?.Dispose();
_monitorCts = null;
_logger?.LogInformation("Firestore consumer stopped: {Collection}", _endpoint.CollectionPath);
}
private Google.Cloud.Firestore.Query BuildQuery(FirestoreDb db)
{
Google.Cloud.Firestore.Query query = db.Collection(_endpoint.CollectionPath);
if (_options.Where is not null)
query = FirestoreQueryHelper.ApplyWhereFilters(query, _options.Where);
if (_options.OrderBy is not null)
query = FirestoreQueryHelper.ApplyOrderBy(query, _options.OrderBy);
if (_options.Limit is not null)
query = query.Limit(_options.Limit.Value);
return query;
}
///
/// Watches the current listener's .
/// A graceful StopAsync ends the loop; a fault records the error and re-creates
/// the subscription with exponential backoff (reset after a stable minute).
///
private async Task MonitorListenerAsync(Google.Cloud.Firestore.Query query, CancellationToken ct)
{
var backoff = InitialBackoff;
while (!ct.IsCancellationRequested)
{
var listener = _listener;
if (listener is null) return;
var startedAt = DateTime.UtcNow;
try
{
await listener.ListenerTask.ConfigureAwait(false);
return; // graceful stop
}
catch (OperationCanceledException)
{
return; // processing token cancelled — shutdown
}
catch (Exception ex)
{
if (ct.IsCancellationRequested) return;
_endpoint.RecordError(ex);
if (DateTime.UtcNow - startedAt > BackoffResetAfter)
backoff = InitialBackoff;
_logger?.LogError(ex,
"Firestore listener failed: {Collection}; resubscribing in {Delay}",
_endpoint.CollectionPath, backoff);
}
try
{
await Task.Delay(backoff, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
backoff = TimeSpan.FromSeconds(Math.Min(backoff.TotalSeconds * 2, MaxBackoff.TotalSeconds));
if (ct.IsCancellationRequested) return;
_listener = query.Listen(OnSnapshotAsync, _drain.ProcessingToken);
_logger?.LogInformation("Firestore listener resubscribed: {Collection}", _endpoint.CollectionPath);
}
}
private async Task OnSnapshotAsync(QuerySnapshot snapshot, CancellationToken ct)
{
SnapshotInterceptor?.Invoke(snapshot);
var tasks = new List();
foreach (var change in snapshot.Changes)
{
if (ct.IsCancellationRequested)
break;
_drain.Increment();
tasks.Add(ProcessChangeAsync(change, ct));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
private async Task ProcessChangeAsync(DocumentChange change, CancellationToken ct)
{
// MaxConcurrency: an initial snapshot delivers the WHOLE collection at once —
// unbounded parallel processing would flood the pipeline.
try
{
await _concurrency.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
_drain.Decrement(); // Increment happened in OnSnapshotAsync; never throw into the listener
return;
}
// A document change carries no trace context: its span is a root, never a child of the listener's activity.
using var span = RouteTelemetryExtensions.StartConsumerSpan