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( (_endpoint.Component as ComponentBase)?.Context, $"firestore {_endpoint.CollectionPath} receive", ActivityKind.Consumer, "db.system", "firestore", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.CollectionPath, operation: "receive"); Exchange? exchange = null; try { var data = change.Document.ToDictionary(); object body = _options.RawJson ? JsonSerializer.Serialize(data) : data; exchange = Exchange.Create(new Message(body), _endpoint.ScopeFactory); exchange.In.Headers[FirestoreHeaders.DocumentId] = change.Document.Id; exchange.In.Headers[FirestoreHeaders.DocumentPath] = change.Document.Reference.Path; exchange.In.Headers[FirestoreHeaders.CollectionPath] = _endpoint.CollectionPath; exchange.In.Headers[FirestoreHeaders.ChangeType] = change.ChangeType.ToString(); exchange.In.Headers[FirestoreHeaders.CreateTime] = change.Document.CreateTime; exchange.In.Headers[FirestoreHeaders.UpdateTime] = change.Document.UpdateTime; exchange.In.Headers[FirestoreHeaders.ReadTime] = change.Document.ReadTime; // MessagesIn is counted by the core StatisticsProcessor - ownership audit. await _processor.Process(exchange, ct).ConfigureAwait(false); if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); } catch (OperationCanceledException ex) { // Our own stop is not a failure of the change; any other cancellation is. if (!ct.IsCancellationRequested) span.Activity.RecordFailure(ex); } catch (Exception ex) { span.Activity.RecordFailure(ex); // Pipeline errors are counted by the core StatisticsProcessor (ownership audit). _logger?.LogError(ex, "Firestore change processing failed: {Collection}/{DocId}", _endpoint.CollectionPath, change.Document.Id); } finally { if (exchange is not null) await exchange.DisposeAsync().ConfigureAwait(false); _drain.Decrement(); _concurrency.Release(); } } } Path: redb-route/redb.Route.Firebase/Firestore/FirestoreEndpointOptions.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/FirestoreEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.Firebase; /// /// Endpoint options for the Firestore component. /// Supports both producer (CRUD/Query) and consumer (realtime listener / polling) modes. /// public sealed class FirestoreEndpointOptions : EndpointOptions { // ── Auth ── /// Path to the Firebase service-account JSON file. public string? CredentialPath { get; set; } /// Firebase/GCP project ID. public string? ProjectId { get; set; } /// Firestore database id for multi-database projects (default: (default)). public string? DatabaseId { get; set; } /// Named reference from the registry. [RegistryReference(typeof(IFirebaseCredentialProvider))] public string? ConnectionFactory { get; set; } // ── Operation ── /// Producer operation type. Default: . public FirestoreOperationType Operation { get; set; } = FirestoreOperationType.Set; // ── Document targeting ── /// Document ID. Supports ${...} expressions. public DynamicValue? DocumentId { get; set; } // ── Query (consumer & producer Query) ── /// Where filter: "status==pending" or "age>18". Multiple separated by ;. public string? Where { get; set; } /// Order by field: "createdAt" or "createdAt desc". public string? OrderBy { get; set; } /// Maximum number of documents to return. public int? Limit { get; set; } /// Pagination offset. public int? Offset { get; set; } // ── Set/Update/BatchWrite ── /// Merge fields on Set instead of overwriting the entire document. public bool Merge { get; set; } /// /// BatchWrite: take the document id from this field of each item (the field itself is /// not written to the document). Without it every item gets an auto-generated id. /// public string? DocumentIdField { get; set; } // ── Consumer: Realtime Listener ── /// Use snapshot listener for realtime updates (default for consumer). public bool Realtime { get; set; } = true; /// /// Maximum number of document changes processed in parallel within one snapshot /// (realtime mode). Default: 16. /// public int MaxConcurrency { get; set; } = 16; // ── Consumer: Polling (Realtime=false) ── /// Poll interval (ms) for non-realtime mode. Default: 5000. public int Delay { get; set; } = 5000; /// Initial delay (ms) before first poll. Default: 1000. public int InitialDelay { get; set; } = 1000; // ── Serialization ── /// Body as raw JSON string instead of Dictionary<string, object?>. public bool RawJson { get; set; } /// public override void Validate() { if (string.IsNullOrWhiteSpace(CredentialPath) && string.IsNullOrWhiteSpace(ConnectionFactory) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("FIRESTORE_EMULATOR_HOST"))) throw new ArgumentOutOfRangeException(nameof(CredentialPath), "CredentialPath, ConnectionFactory, GOOGLE_APPLICATION_CREDENTIALS, or FIRESTORE_EMULATOR_HOST is required"); if (Delay < 100) throw new ArgumentOutOfRangeException(nameof(Delay), "Delay must be >= 100ms"); if (MaxConcurrency < 1) throw new ArgumentOutOfRangeException(nameof(MaxConcurrency), "MaxConcurrency must be >= 1"); if (Limit is not null && Limit < 1) throw new ArgumentOutOfRangeException(nameof(Limit), "Limit must be >= 1"); } } Path: redb-route/redb.Route.Firebase/Firestore/FirestoreHeaders.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/FirestoreHeaders.cs ---- namespace redb.Route.Firebase; /// /// Header constants for the Firestore connector. Prefix: redbFirestore. /// public static class FirestoreHeaders { /// Common prefix for all Firestore headers. public const string Prefix = "redbFirestore."; // ── Document identity ── /// Document ID within the collection. public const string DocumentId = "redbFirestore.DocumentId"; /// Full document path (e.g. users/user-123). public const string DocumentPath = "redbFirestore.DocumentPath"; /// Collection path (e.g. users, users/uid/orders). public const string CollectionPath = "redbFirestore.CollectionPath"; // ── Metadata ── /// Document creation timestamp. public const string CreateTime = "redbFirestore.CreateTime"; /// Last update timestamp. public const string UpdateTime = "redbFirestore.UpdateTime"; /// Read timestamp (snapshot read time). public const string ReadTime = "redbFirestore.ReadTime"; // ── Consumer: Change tracking ── /// Type of change: "Added", "Modified", or "Removed". public const string ChangeType = "redbFirestore.ChangeType"; // ── Producer results ── /// Write result timestamp (from Firestore server). public const string WriteTime = "redbFirestore.WriteTime"; // ── Query info ── /// Number of documents returned by a query or batch operation. public const string DocumentCount = "redbFirestore.DocumentCount"; } Path: redb-route/redb.Route.Firebase/Firestore/FirestoreOperationType.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/FirestoreOperationType.cs ---- namespace redb.Route.Firebase; /// /// Firestore operation types for the producer. /// Determines what CRUD action the producer performs. /// public enum FirestoreOperationType { /// Create or overwrite a document (uses SetAsync). Set, /// Read a single document by ID. Get, /// Partial update of a document (merge fields). Update, /// Delete a document by ID. Delete, /// Query a collection with filters, ordering, and limits. Query, /// Batch write multiple documents in a single commit. BatchWrite } Path: redb-route/redb.Route.Firebase/Firestore/FirestorePollingConsumer.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/FirestorePollingConsumer.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 polling consumer (Realtime=false) — runs the query every Delay ms /// and diffs the result against the previous poll (DocumentId → UpdateTime): /// a new id is Added, a changed UpdateTime is Modified, an id that left /// the result set is Removed (body is null — the old data is not retained). /// The first poll delivers everything as Added; the diff lives in memory, so a restart /// starts from a clean snapshot — same as the realtime listener's initial snapshot. /// Note: Removed is only visible within the query result window (Where/Limit shift it). /// internal sealed class FirestorePollingConsumer : DrainableConsumer { private readonly FirestoreEndpoint _endpoint; private readonly FirestoreEndpointOptions _options; private Google.Cloud.Firestore.Query? _query; private Dictionary _lastSeen = new(); /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"fstore://{_endpoint.CollectionPath} (polling)"; internal FirestorePollingConsumer(FirestoreEndpoint endpoint, IProcessor processor, FirestoreEndpointOptions options) : base(processor) { _endpoint = endpoint; _options = options; } /// protected override async Task OnStarting(CancellationToken ct) { var db = await _endpoint.GetOrCreateDbAsync(ct).ConfigureAwait(false); 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); _query = query; } /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { if (_options.InitialDelay > 0) await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); while (!pollCt.IsCancellationRequested) { try { await PollAsync(processingCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogError(ex, "Firestore polling failed: {Collection}", _endpoint.CollectionPath); _endpoint.RecordError(ex); } try { await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested) { break; } } } private async Task PollAsync(CancellationToken ct) { var snapshot = await _query!.GetSnapshotAsync(ct).ConfigureAwait(false); var current = new Dictionary(snapshot.Count); foreach (var doc in snapshot.Documents) { if (ct.IsCancellationRequested) return; current[doc.Id] = doc.UpdateTime; string changeType; if (!_lastSeen.TryGetValue(doc.Id, out var prevUpdate)) changeType = "Added"; else if (!Equals(prevUpdate, doc.UpdateTime)) changeType = "Modified"; else continue; // unchanged await EmitAsync(doc, changeType, snapshot.ReadTime, ct).ConfigureAwait(false); } // Ids that left the query result window foreach (var (docId, _) in _lastSeen) { if (ct.IsCancellationRequested) return; if (!current.ContainsKey(docId)) await EmitRemovedAsync(docId, snapshot.ReadTime, ct).ConfigureAwait(false); } _lastSeen = current; } private async Task EmitAsync(DocumentSnapshot doc, string changeType, Timestamp readTime, CancellationToken ct) { var data = doc.ToDictionary(); object body = _options.RawJson ? JsonSerializer.Serialize(data) : data; var exchange = Exchange.Create(new Message(body), _endpoint.ScopeFactory); exchange.In.Headers[FirestoreHeaders.DocumentId] = doc.Id; exchange.In.Headers[FirestoreHeaders.DocumentPath] = doc.Reference.Path; exchange.In.Headers[FirestoreHeaders.CollectionPath] = _endpoint.CollectionPath; exchange.In.Headers[FirestoreHeaders.ChangeType] = changeType; exchange.In.Headers[FirestoreHeaders.CreateTime] = doc.CreateTime; exchange.In.Headers[FirestoreHeaders.UpdateTime] = doc.UpdateTime; exchange.In.Headers[FirestoreHeaders.ReadTime] = readTime; // MessagesIn is counted by the core StatisticsProcessor - ownership audit. using var span = StartReceiveSpan(); await ProcessWithTracking(exchange, span, ct).ConfigureAwait(false); } /// The root span of one change: a Firestore document carries no trace context. private TransportSpan StartReceiveSpan() => RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"firestore {_endpoint.CollectionPath} receive", ActivityKind.Consumer, "db.system", "firestore", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.CollectionPath, operation: "receive"); private async Task EmitRemovedAsync(string docId, Timestamp readTime, CancellationToken ct) { var exchange = Exchange.Create(new Message(null), _endpoint.ScopeFactory); exchange.In.Headers[FirestoreHeaders.DocumentId] = docId; exchange.In.Headers[FirestoreHeaders.CollectionPath] = _endpoint.CollectionPath; exchange.In.Headers[FirestoreHeaders.ChangeType] = "Removed"; exchange.In.Headers[FirestoreHeaders.ReadTime] = readTime; // MessagesIn is counted by the core StatisticsProcessor - ownership audit. using var span = StartReceiveSpan(); await ProcessWithTracking(exchange, span, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route.Firebase/Firestore/FirestoreProducer.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/FirestoreProducer.cs ---- using System.Diagnostics; using System.Text.Json; using Google.Cloud.Firestore; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Firebase; /// /// Firestore producer — performs CRUD and query operations on Firestore collections. /// Dispatches by : Set, Get, Update, Delete, Query, BatchWrite. /// internal sealed class FirestoreProducer : ConnectableProducer { private readonly FirestoreEndpoint _endpoint; private readonly FirestoreEndpointOptions _options; private FirestoreDb? _db; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => _endpoint.Uri.NormalizedKey; internal FirestoreProducer(FirestoreEndpoint endpoint, FirestoreEndpointOptions options) { _endpoint = endpoint; _options = options; } /// protected override async Task ConnectAsync(CancellationToken ct) { _db = await _endpoint.GetOrCreateDbAsync(ct).ConfigureAwait(false); } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"firestore {_options.Operation}", ActivityKind.Client, "db.system", "firestore", _endpoint.Uri.NormalizedKey, destination: _endpoint.CollectionPath, operation: _options.Operation.ToString()); var collection = _db!.Collection(_endpoint.CollectionPath); try { switch (_options.Operation) { case FirestoreOperationType.Set: await ProcessSet(exchange, collection, ct).ConfigureAwait(false); break; case FirestoreOperationType.Get: await ProcessGet(exchange, collection, ct).ConfigureAwait(false); break; case FirestoreOperationType.Update: await ProcessUpdate(exchange, collection, ct).ConfigureAwait(false); break; case FirestoreOperationType.Delete: await ProcessDelete(exchange, collection, ct).ConfigureAwait(false); break; case FirestoreOperationType.Query: await ProcessQuery(exchange, collection, ct).ConfigureAwait(false); break; case FirestoreOperationType.BatchWrite: await ProcessBatchWrite(exchange, collection, ct).ConfigureAwait(false); break; default: throw new InvalidOperationException($"Unknown Firestore 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 ProcessSet(IExchange exchange, CollectionReference collection, CancellationToken ct) { var docId = ResolveDocumentId(exchange); var data = ResolveDocumentData(exchange); DocumentReference docRef = docId is not null ? collection.Document(docId) : collection.Document(); // auto-generate ID WriteResult writeResult; if (_options.Merge) writeResult = await docRef.SetAsync(data, SetOptions.MergeAll, ct).ConfigureAwait(false); else writeResult = await docRef.SetAsync(data, cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirestoreHeaders.DocumentId] = docRef.Id; exchange.In.Headers[FirestoreHeaders.DocumentPath] = docRef.Path; exchange.In.Headers[FirestoreHeaders.WriteTime] = writeResult.UpdateTime; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessGet(IExchange exchange, CollectionReference collection, CancellationToken ct) { var docId = ResolveDocumentId(exchange) ?? throw new InvalidOperationException("DocumentId is required for Get operation"); var snapshot = await collection.Document(docId).GetSnapshotAsync(ct).ConfigureAwait(false); if (!snapshot.Exists) { exchange.Out = new Message(null); } else { var data = snapshot.ToDictionary(); exchange.Out = _options.RawJson ? new Message(JsonSerializer.Serialize(data)) : new Message(data); exchange.Out.Headers[FirestoreHeaders.DocumentId] = snapshot.Id; exchange.Out.Headers[FirestoreHeaders.CreateTime] = snapshot.CreateTime; exchange.Out.Headers[FirestoreHeaders.UpdateTime] = snapshot.UpdateTime; } exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } private async Task ProcessUpdate(IExchange exchange, CollectionReference collection, CancellationToken ct) { var docId = ResolveDocumentId(exchange) ?? throw new InvalidOperationException("DocumentId is required for Update operation"); var data = ResolveDocumentData(exchange); var writeResult = await collection.Document(docId).UpdateAsync(data, cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirestoreHeaders.WriteTime] = writeResult.UpdateTime; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessDelete(IExchange exchange, CollectionReference collection, CancellationToken ct) { var docId = ResolveDocumentId(exchange) ?? throw new InvalidOperationException("DocumentId is required for Delete operation"); var writeResult = await collection.Document(docId).DeleteAsync(cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirestoreHeaders.WriteTime] = writeResult.UpdateTime; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessQuery(IExchange exchange, CollectionReference collection, CancellationToken ct) { Google.Cloud.Firestore.Query query = collection; // ${...} in Where is producer-Query-only: the query is built per exchange here, // so the template resolves against the current message. var where = _options.ResolveOption(_options.Where, exchange); if (where is not null) query = FirestoreQueryHelper.ApplyWhereFilters(query, where); if (_options.OrderBy is not null) query = FirestoreQueryHelper.ApplyOrderBy(query, _options.OrderBy); if (_options.Offset is not null) query = query.Offset(_options.Offset.Value); if (_options.Limit is not null) query = query.Limit(_options.Limit.Value); var snapshot = await query.GetSnapshotAsync(ct).ConfigureAwait(false); var docs = snapshot.Documents.Select(d => d.ToDictionary()).ToList(); exchange.Out = _options.RawJson ? new Message(JsonSerializer.Serialize(docs)) : new Message(docs); exchange.Out.Headers[FirestoreHeaders.DocumentCount] = snapshot.Count; exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } private async Task ProcessBatchWrite(IExchange exchange, CollectionReference collection, CancellationToken ct) { const int maxBatchSize = 500; // Firestore hard limit per batch var items = exchange.In.Body as IEnumerable> ?? throw new InvalidOperationException( "BatchWrite requires IEnumerable> body"); var totalCount = 0; var batchCount = 0; WriteBatch? batch = null; foreach (var item in items) { batch ??= _db!.StartBatch(); DocumentReference docRef; var data = item; if (_options.DocumentIdField is not null) { if (!item.TryGetValue(_options.DocumentIdField, out var idValue) || idValue is null) throw new InvalidOperationException( $"BatchWrite item is missing the '{_options.DocumentIdField}' field required by DocumentIdField"); docRef = collection.Document(idValue.ToString()); // The id source field is identity, not data — do not write it into the document. data = new Dictionary(item); data.Remove(_options.DocumentIdField); } else { docRef = collection.Document(); // auto-ID } if (_options.Merge) batch.Set(docRef, data, SetOptions.MergeAll); else batch.Set(docRef, data); totalCount++; batchCount++; if (batchCount >= maxBatchSize) { await batch.CommitAsync(ct).ConfigureAwait(false); batch = null; batchCount = 0; } } if (batch is not null && batchCount > 0) await batch.CommitAsync(ct).ConfigureAwait(false); exchange.In.Headers[FirestoreHeaders.DocumentCount] = totalCount; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } // ── Helpers ── private string? ResolveDocumentId(IExchange exchange) { return exchange.In.GetHeader(FirestoreHeaders.DocumentId) ?? _options.DocumentId?.Resolve(exchange); } private static IDictionary ResolveDocumentData(IExchange exchange) { if (exchange.In.Body is IDictionary dictNullable) return dictNullable; if (exchange.In.Body is IDictionary dict) return dict.ToDictionary(kv => kv.Key, kv => (object?)kv.Value); if (exchange.In.Body is string json) { // Deserialize to JsonElement first, then recursively convert to native types. // Direct Deserialize> produces JsonElement values // which Firestore SDK cannot serialize. var raw = JsonSerializer.Deserialize>(json) ?? throw new InvalidOperationException("Failed to deserialize JSON body to dictionary"); return ConvertJsonElements(raw); } throw new InvalidOperationException( $"Firestore Set/Update requires IDictionary or JSON string body, got {exchange.In.Body?.GetType().Name ?? "null"}"); } private static IDictionary ConvertJsonElements(Dictionary raw) { var result = new Dictionary(raw.Count); foreach (var (key, value) in raw) result[key] = ConvertJsonElement(value); return result; } private static object? ConvertJsonElement(JsonElement element) { return element.ValueKind switch { JsonValueKind.Null => null, JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Number when element.TryGetInt64(out var l) => l, JsonValueKind.Number => element.GetDouble(), JsonValueKind.String => element.GetString(), JsonValueKind.Array => element.EnumerateArray().Select(ConvertJsonElement).ToList(), JsonValueKind.Object => element.EnumerateObject() .ToDictionary(p => p.Name, p => ConvertJsonElement(p.Value)), _ => element.GetRawText() }; } } Path: redb-route/redb.Route.Firebase/Firestore/FirestoreQueryHelper.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/FirestoreQueryHelper.cs ---- using Google.Cloud.Firestore; namespace redb.Route.Firebase; /// /// Shared Firestore query building logic used by both producer and consumer. /// Eliminates code duplication for Where/OrderBy filter parsing. /// internal static class FirestoreQueryHelper { /// /// Parses "field==value;field2>10" into chained Firestore query filters. /// Supports: ==, !=, <, <=, >, >=, array-contains /// internal static Query ApplyWhereFilters(Query query, string where) { var conditions = where.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var condition in conditions) { var (field, op, value) = ParseCondition(condition); query = op switch { "==" => query.WhereEqualTo(field, ParseValue(value)), "!=" => query.WhereNotEqualTo(field, ParseValue(value)), ">=" => query.WhereGreaterThanOrEqualTo(field, ParseValue(value)), "<=" => query.WhereLessThanOrEqualTo(field, ParseValue(value)), ">" => query.WhereGreaterThan(field, ParseValue(value)), "<" => query.WhereLessThan(field, ParseValue(value)), "array-contains" => query.WhereArrayContains(field, ParseValue(value)), _ => throw new InvalidOperationException($"Unknown Firestore filter operator: {op}") }; } return query; } /// /// Parses "fieldName [desc]" into an OrderBy clause. /// internal static Query ApplyOrderBy(Query query, string orderBy) { var parts = orderBy.Split(' ', StringSplitOptions.RemoveEmptyEntries); var field = parts[0]; var desc = parts.Length > 1 && parts[1].Equals("desc", StringComparison.OrdinalIgnoreCase); return desc ? query.OrderByDescending(field) : query.OrderBy(field); } internal static (string field, string op, string value) ParseCondition(string condition) { // `array-contains` only as a SPACED token: a field whose NAME contains the // substring ("my-array-contains-x==5") must not tear the condition apart. const string arrayContainsToken = " array-contains "; var acIdx = condition.IndexOf(arrayContainsToken, StringComparison.Ordinal); if (acIdx > 0) return (condition[..acIdx].Trim(), "array-contains", condition[(acIdx + arrayContainsToken.Length)..].Trim()); string[] operators = ["!=", ">=", "<=", "==", ">", "<"]; foreach (var op in operators) { var idx = condition.IndexOf(op, StringComparison.Ordinal); if (idx > 0) return (condition[..idx].Trim(), op, condition[(idx + op.Length)..].Trim()); } throw new InvalidOperationException($"Cannot parse Firestore where condition: {condition}"); } internal static object ParseValue(string value) { // Quoted literal: 'text' — strictly a string, no type coercion ('007' stays "007"). if (value.Length >= 2 && value[0] == '\'' && value[^1] == '\'') return value[1..^1]; if (int.TryParse(value, out var intVal)) return intVal; if (long.TryParse(value, out var longVal)) return longVal; if (double.TryParse(value, System.Globalization.CultureInfo.InvariantCulture, out var dblVal)) return dblVal; if (bool.TryParse(value, out var boolVal)) return boolVal; return value; } } Path: redb-route/redb.Route.Firebase/Fluent/FcmDsl.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/Fluent/FcmDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Firebase; /// /// Fluent API entry point for FCM push notification endpoints. /// /// /// // Send to a specific device: /// .To(Fcm.Token("${header.deviceToken}") /// .CredentialPath("/secrets/firebase-sa.json") /// .Title("Order update").Build()) /// /// // Topic broadcast: /// .To(Fcm.Topic("news").CredentialPath("/secrets/firebase-sa.json").Build()) /// /// // Condition targeting: /// .To(Fcm.Condition("'sports' in topics && 'news' in topics").Build()) /// /// /// public static class Fcm { /// Creates a Token-targeted FCM producer endpoint. public static FcmBuilder Token(string token) => new(FcmMessageType.Token, "token", token); /// Creates a Token-targeted FCM producer endpoint with expression. public static FcmBuilder Token(IExpression token) => new(FcmMessageType.Token, "token", token.ToTemplateString()); /// Creates a Topic-targeted FCM producer endpoint. public static FcmBuilder Topic(string topic) => new(FcmMessageType.Topic, "topic", topic); /// Creates a Topic-targeted FCM producer endpoint with expression. public static FcmBuilder Topic(IExpression topic) => new(FcmMessageType.Topic, "topic", topic.ToTemplateString()); /// Creates a Condition-targeted FCM producer endpoint. public static FcmBuilder Condition(string condition) => new(FcmMessageType.Condition, "condition", condition); /// Creates a Condition-targeted FCM producer endpoint with expression. public static FcmBuilder Condition(IExpression condition) => new(FcmMessageType.Condition, "condition", condition.ToTemplateString()); /// Multicast: the same message to many tokens (body or Tokens header). public static FcmBuilder Multicast() => new(FcmOperationType.Multicast); /// Subscribe device tokens (body or Tokens header) to the topic. public static FcmBuilder SubscribeToTopic(string topic) => new FcmBuilder(FcmOperationType.SubscribeToTopic).Set("topic", topic); /// Unsubscribe device tokens (body or Tokens header) from the topic. public static FcmBuilder UnsubscribeFromTopic(string topic) => new FcmBuilder(FcmOperationType.UnsubscribeFromTopic).Set("topic", topic); } /// /// Fluent builder for FCM endpoint URIs. /// public sealed class FcmBuilder { private readonly FcmMessageType _type; private readonly Dictionary _params = new(); internal FcmBuilder(FcmMessageType type, string targetKey, string targetValue) { _type = type; _params["messageType"] = type.ToString(); _params[targetKey] = targetValue; } internal FcmBuilder(FcmOperationType operation) { _type = FcmMessageType.Token; _params["operation"] = operation.ToString(); } /// Notification title. public FcmBuilder Title(string v) => Set("title", v); /// Notification title from expression. public FcmBuilder Title(IExpression v) => Set("title", v.ToTemplateString()); /// Notification body text. public FcmBuilder Body(string v) => Set("body", v); /// Notification body from expression. public FcmBuilder Body(IExpression v) => Set("body", v.ToTemplateString()); /// Notification image URL. public FcmBuilder ImageUrl(string v) => Set("imageUrl", v); /// Path to service-account JSON file. public FcmBuilder CredentialPath(string v) => Set("credentialPath", v); /// Firebase project ID. public FcmBuilder ProjectId(string v) => Set("projectId", v); /// Named connection factory reference. public FcmBuilder ConnectionFactory(string v) => Set("connectionFactory", v); /// Send as data-only message (no visible notification). public FcmBuilder DataOnly(bool v = true) => Set("dataOnly", v); /// Validate message without sending. public FcmBuilder DryRun(bool v = true) => Set("dryRun", v); /// Android priority: "normal" or "high". public FcmBuilder AndroidPriority(string p) => Set("androidPriority", p); /// Android TTL in seconds. public FcmBuilder AndroidTtlSeconds(int s) => Set("androidTtlSeconds", s); /// Android notification channel ID. public FcmBuilder AndroidChannelId(string id) => Set("androidChannelId", id); /// APNS priority: "5" or "10". public FcmBuilder ApnsPriority(string p) => Set("apnsPriority", p); /// APNS collapse identifier. public FcmBuilder ApnsCollapseId(string id) => Set("apnsCollapseId", id); /// Web push click action URL. public FcmBuilder WebPushLink(string url) => Set("webPushLink", url); /// Builds the FCM URI string. public string Build() { var sb = new StringBuilder("fcm://send?"); var first = true; foreach (var (key, value) in _params) { if (!first) sb.Append('&'); sb.Append(key).Append('=').Append(Uri.EscapeDataString(value)); first = false; } return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(FcmBuilder b) => b.Build(); /// public override string ToString() => Build(); internal FcmBuilder Set(string k, object v) { _params[k] = v.ToString()!; return this; } } Path: redb-route/redb.Route.Firebase/Fluent/FirebaseStorageDsl.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/Fluent/FirebaseStorageDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Firebase; /// /// Fluent API entry point for Firebase Storage endpoints. /// /// /// // Consumer: poll for new uploads /// .From(FirebaseStorage.Bucket("my-app.appspot.com") /// .Prefix("uploads/").Include("*.csv") /// .DeleteAfterRead().Delay(10000).Build()) /// /// // Producer: upload /// .To(FirebaseStorage.Bucket("my-app.appspot.com") /// .Operation(FirebaseStorageOperationType.Upload) /// .ObjectName("${header.fileName}") /// .ContentType("application/json").Build()) /// /// // Producer: download /// .To(FirebaseStorage.Bucket("my-app.appspot.com") /// .Operation(FirebaseStorageOperationType.Download).Build()) /// /// /// public static class FirebaseStorage { /// Creates a Firebase Storage endpoint builder for the given bucket. /// Bucket name (e.g. "my-app.appspot.com"). public static FirebaseStorageBuilder Bucket(string bucket) => new(bucket, null); /// Creates a Firebase Storage endpoint builder for a bucket with prefix. /// Bucket name. /// Object prefix (e.g. "uploads/"). public static FirebaseStorageBuilder Bucket(string bucket, string prefix) => new(bucket, prefix); } /// /// Fluent builder for Firebase Storage endpoint URIs. /// public sealed class FirebaseStorageBuilder { private readonly string _bucket; private readonly string? _prefix; private readonly Dictionary _params = new(); internal FirebaseStorageBuilder(string bucket, string? prefix) { ArgumentException.ThrowIfNullOrWhiteSpace(bucket); _bucket = bucket; _prefix = prefix; } /// Producer operation type. public FirebaseStorageBuilder Operation(FirebaseStorageOperationType op) => Set("operation", op); /// Object name/key. public FirebaseStorageBuilder ObjectName(string name) => Set("objectName", name); /// Object name from expression. public FirebaseStorageBuilder ObjectName(IExpression name) => Set("objectName", name.ToTemplateString()); /// MIME content type. public FirebaseStorageBuilder ContentType(string ct) => Set("contentType", ct); /// Cache-Control header value. public FirebaseStorageBuilder CacheControl(string value) => Set("cacheControl", value); /// Path to service-account JSON file. public FirebaseStorageBuilder CredentialPath(string v) => Set("credentialPath", v); /// Firebase project ID. public FirebaseStorageBuilder ProjectId(string v) => Set("projectId", v); /// Named connection factory reference. public FirebaseStorageBuilder ConnectionFactory(string v) => Set("connectionFactory", v); /// Destination object name for the Copy operation. public FirebaseStorageBuilder DestinationObjectName(string name) => Set("destinationObjectName", name); /// Destination object name from expression. public FirebaseStorageBuilder DestinationObjectName(IExpression name) => Set("destinationObjectName", name.ToTemplateString()); /// Destination bucket for the Copy operation. public FirebaseStorageBuilder DestinationBucket(string bucket) => Set("destinationBucket", bucket); /// TTL for CreateDownloadLink signed URLs (ms). public FirebaseStorageBuilder SignedUrlExpiration(long ms) => Set("signedUrlExpiration", ms); /// Download as Stream (true) or byte[] (false). public FirebaseStorageBuilder StreamBody(bool v = true) => Set("streamBody", v); /// Poll interval (ms). public FirebaseStorageBuilder Delay(int ms) => Set("delay", ms); /// Object name prefix for listing. public FirebaseStorageBuilder Prefix(string p) => Set("prefix", p); /// Max objects per poll cycle. public FirebaseStorageBuilder MaxMessagesPerPoll(int n) => Set("maxMessagesPerPoll", n); /// Delete object after consumer processing. public FirebaseStorageBuilder DeleteAfterRead(bool v = true) => Set("deleteAfterRead", v); /// Move objects to prefix after processing. public FirebaseStorageBuilder MoveAfterRead(string prefix) => Set("moveAfterRead", prefix); /// Quarantine prefix for objects whose processing failed. public FirebaseStorageBuilder MoveFailed(string prefix) => Set("moveFailed", prefix); /// Skip previously processed objects. public FirebaseStorageBuilder Idempotent(bool v = true) => Set("idempotent", v); /// Named IIdempotentRepository from the context registry (survives restarts). public FirebaseStorageBuilder IdempotentRepository(string name) => Set("idempotentRepository", name); /// Create the bucket on consumer start when missing. public FirebaseStorageBuilder AutoCreateBucket(bool v = true) => Set("autoCreateBucket", v); /// Include glob pattern. public FirebaseStorageBuilder Include(string glob) => Set("include", glob); /// Exclude glob pattern. public FirebaseStorageBuilder Exclude(string glob) => Set("exclude", glob); /// Include downloaded body in exchange. public FirebaseStorageBuilder IncludeBody(bool v = true) => Set("includeBody", v); /// Builds the Firebase Storage URI string. public string Build() { var path = _prefix is not null ? $"{_bucket}/{_prefix}" : _bucket; if (_params.Count == 0) return $"fbstorage://{path}"; var sb = new StringBuilder($"fbstorage://{path}?"); var first = true; foreach (var (key, value) in _params) { if (!first) sb.Append('&'); sb.Append(key).Append('=').Append(Uri.EscapeDataString(value)); first = false; } return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(FirebaseStorageBuilder b) => b.Build(); /// public override string ToString() => Build(); private FirebaseStorageBuilder Set(string k, object v) { _params[k] = v.ToString()!; return this; } } Path: redb-route/redb.Route.Firebase/Fluent/FirestoreDsl.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/Fluent/FirestoreDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Firebase; /// /// Fluent API entry point for Firestore endpoints. /// /// /// // Realtime consumer: /// .From(Firestore.Collection("orders") /// .Where("status==pending") /// .CredentialPath("/secrets/firebase-sa.json").Build()) /// /// // CRUD producer: /// .To(Firestore.Collection("orders") /// .Operation(FirestoreOperationType.Update) /// .DocumentId("${header['redbFirestore.DocumentId']}") /// .CredentialPath("/secrets/firebase-sa.json").Build()) /// /// // Query producer: /// .To(Firestore.Collection("users") /// .Operation(FirestoreOperationType.Query) /// .Where("age>18").OrderBy("name").Limit(50).Build()) /// /// /// public static class Firestore { /// Creates a Firestore endpoint builder for the given collection path. /// Collection path (e.g. "users", "users/uid/orders"). public static FirestoreBuilder Collection(string path) => new(path); } /// /// Fluent builder for Firestore endpoint URIs. /// public sealed class FirestoreBuilder { private readonly string _collectionPath; private readonly Dictionary _params = new(); internal FirestoreBuilder(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); _collectionPath = path; } /// Producer operation type. public FirestoreBuilder Operation(FirestoreOperationType op) => Set("operation", op); /// Document ID (static value). public FirestoreBuilder DocumentId(string id) => Set("documentId", id); /// Document ID from expression. public FirestoreBuilder DocumentId(IExpression id) => Set("documentId", id.ToTemplateString()); /// Where filter (e.g. "status==pending"). public FirestoreBuilder Where(string filter) => Set("where", filter); /// Order by field (e.g. "createdAt" or "createdAt desc"). public FirestoreBuilder OrderBy(string field) => Set("orderBy", field); /// Max documents to return. public FirestoreBuilder Limit(int n) => Set("limit", n); /// Pagination offset. public FirestoreBuilder Offset(int n) => Set("offset", n); /// Merge fields on Set instead of overwriting. public FirestoreBuilder Merge(bool v = true) => Set("merge", v); /// BatchWrite: take the document id from this field of each item. public FirestoreBuilder DocumentIdField(string field) => Set("documentIdField", field); /// Use realtime snapshot listener (default: true). public FirestoreBuilder Realtime(bool v = true) => Set("realtime", v); /// Max parallel document changes per snapshot (realtime mode, default 16). public FirestoreBuilder MaxConcurrency(int n) => Set("maxConcurrency", n); /// Poll interval (ms) for non-realtime mode. public FirestoreBuilder Delay(int ms) => Set("delay", ms); /// Initial delay (ms) before the first poll (non-realtime mode). public FirestoreBuilder InitialDelay(int ms) => Set("initialDelay", ms); /// Body as raw JSON string. public FirestoreBuilder RawJson(bool v = true) => Set("rawJson", v); /// Path to service-account JSON file. public FirestoreBuilder CredentialPath(string v) => Set("credentialPath", v); /// Firebase project ID. public FirestoreBuilder ProjectId(string v) => Set("projectId", v); /// Firestore database id (multi-database projects). public FirestoreBuilder DatabaseId(string v) => Set("databaseId", v); /// Named connection factory reference. public FirestoreBuilder ConnectionFactory(string v) => Set("connectionFactory", v); /// Builds the Firestore URI string. public string Build() { if (_params.Count == 0) return $"fstore://{_collectionPath}"; var sb = new StringBuilder($"fstore://{_collectionPath}?"); var first = true; foreach (var (key, value) in _params) { if (!first) sb.Append('&'); sb.Append(key).Append('=').Append(Uri.EscapeDataString(value)); first = false; } return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(FirestoreBuilder b) => b.Build(); /// public override string ToString() => Build(); private FirestoreBuilder Set(string k, object v) { _params[k] = v.ToString()!; return this; } } Path: redb-route/redb.Route.Firebase/README.md 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/README.md ---- # redb.Route.Firebase > Documentation and articles: Firebase transport for the **redb.Route** ESB framework — **Firestore**, **Cloud Storage (GCS)**, and **FCM** in a single package. Firestore producer with CRUD, queries, and 500-doc batch writes. Realtime snapshot listener consumer. Cloud Storage producer with upload/download (buffered or true streaming)/delete/copy/list/metadata, signed download links and bucket operations (create/delete/list, auto-create on the consumer). Polling consumer with idempotency (in-memory or a named shared repository), glob filtering, move/delete after read and a `MoveFailed` quarantine. FCM producer with full platform support — Android priority/TTL/channel, APNS content-available/mutable-content, WebPush. Shared `IFirebaseCredentialProvider` across all three services — one credential setup, three transports. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Firebase?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Firebase) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) | | | |---|---| | **Schemes** | `fstore`, `fbstorage`, `fcm` | | **NuGet** | `redb.Route.Firebase` | | **Dependencies** | Google.Cloud.Firestore 3.13.0 · Google.Cloud.Storage.V1 4.14.0 · FirebaseAdmin 3.5.0 | | **Namespace** | `redb.Route.Firebase` | --- ## Quick Start ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteFirebase(); // Realtime Firestore → log changes route.AddRoutes(r => r .From(Firestore.Collection("orders") .Where("status==pending") .CredentialPath("/secrets/firebase.json")) .RouteId("firestore-watch") .To("log:order-change")); // Upload file to GCS bucket route.AddRoutes(r => r .From("direct:upload") .RouteId("storage-upload") .To(FirebaseStorage.Bucket("media-uploads") .Operation(FirebaseStorageOperationType.Upload) .ObjectName(new HeaderExpression("fileName")) .ContentType("application/pdf") .CacheControl("public, max-age=86400") .CredentialPath("/secrets/firebase.json"))); // Send push notification route.AddRoutes(r => r .From("direct:notify") .RouteId("push-notify") .To(Fcm.Token(new HeaderExpression("deviceToken")) .Title("New Order") .Body(RouteBuilder.Expr("Order ${body['id']} is ready")) .CredentialPath("/secrets/firebase.json"))); }); ``` --- ## Credential Resolution All three components share the same resolution order: 1. `ConnectionFactory` — named `IFirebaseCredentialProvider` from the service registry 2. `CredentialPath` — path to a service-account JSON file 3. `GOOGLE_APPLICATION_CREDENTIALS` environment variable (default credential) 4. Emulator environment variables (for development) — `FIRESTORE_EMULATOR_HOST` (e.g. `localhost:8086`) and `STORAGE_EMULATOR_HOST`. The storage SDK uses `STORAGE_EMULATOR_HOST` verbatim as the service base URI, so for fake-gcs-server pass the full path: `http://localhost:4443/storage/v1/`. ```csharp // Option 1: Explicit credential file .CredentialPath("/secrets/firebase.json") // Option 2: Named provider from the context registry — several service accounts per process context.AddToRegistry("myFirebase", new FirebaseCredentialProvider { DefaultProjectId = "my-project", DefaultCredentialPath = "/secrets/firebase-sa.json", }); // ...then on any endpoint: .ConnectionFactory("myFirebase") // Option 3: Environment variable (no code needed) // Set GOOGLE_APPLICATION_CREDENTIALS=/secrets/firebase.json ``` Firebase apps are created as named instances — the connector never touches (or deletes) the process-global `[DEFAULT]` app, so it coexists with a host that initializes Firebase Admin SDK itself. The Firestore project id must be configured explicitly (endpoint `projectId`, `AddRedbRouteFirebase(o => o.ProjectId = ...)`, `DefaultProjectId`, or the `FIREBASE_PROJECT` environment variable) — a missing project is a loud startup error, never a silent default. --- # Firestore (`fstore`) ## URI Format ``` fstore://collection-path?option=value&... ``` **Consumer** — realtime snapshot listener (default): ``` fstore://orders?where=status==pending&credentialPath=/secrets/fb.json ``` **Producer** — default operation `Set`: ``` fstore://users?documentId=${header.userId}&merge=true fstore://events?operation=Query&where=type==purchase;amount>100&orderBy=createdAt desc&limit=50 fstore://bulk?operation=BatchWrite ``` Sub-collections use path segments: ``` fstore://users/uid-123/orders?operation=Query&limit=10 ``` ## Producer Operations 6 operations available, set via `operation` URI parameter. | Operation | Description | Key Input | Key Output Headers | |---|---|---|---| | **Set** | Create or overwrite a document | Body: `Dictionary` | `DocumentId`, `DocumentPath`, `WriteTime` | | **Get** | Read a single document by ID | `DocumentId` header or option | Body: document data, `DocumentId` | | **Update** | Update specific fields | Body: fields to update, `DocumentId` | `DocumentId`, `WriteTime` | | **Delete** | Delete a document by ID | `DocumentId` header or option | `DocumentId` | | **Query** | Query with filters, ordering, pagination | `Where`, `OrderBy`, `Limit`, `Offset` | Body: list of documents, `DocumentCount` | | **BatchWrite** | Write up to N documents (auto-chunked at 500) | Body: `IEnumerable>` | `DocumentCount` | ### Set with Merge ```csharp // Overwrite entire document (default) route.From("direct:save") .To(Firestore.Collection("users") .DocumentId(new HeaderExpression("userId"))); // Merge — only update provided fields route.From("direct:update-partial") .To(Firestore.Collection("users") .DocumentId(new HeaderExpression("userId")) .Merge()); ``` ### Where syntax `field OP value` conditions separated by `;`. Operators: `==`, `!=`, `<`, `<=`, `>`, `>=`, and ` array-contains ` (as a spaced token: `tags array-contains 'admin'`). Unquoted values are type-inferred (int/long/double/bool, else string); a single-quoted value is STRICTLY a string — `status=='007'` matches the string `"007"`, never the number 7. `${...}` templates in `Where` resolve per exchange on the producer `Query` operation only; a consumer with `${...}` in `Where` fails at startup (the subscription query is built once — there is no exchange to resolve against). ### Query ```csharp route.From("timer:poll?delay=60000") .To(Firestore.Collection("events") .Operation(FirestoreOperationType.Query) .Where("type==purchase;amount>100") .OrderBy("createdAt desc") .Limit(50)) .To("log:results"); ``` Filter syntax: `field==value`, separated by `;`. Operators: `==`, `!=`, `>`, `>=`, `<`, `<=`, `array-contains`. ### BatchWrite ```csharp route.From("direct:bulk-import") .To(Firestore.Collection("products") .Operation(FirestoreOperationType.BatchWrite)); ``` Automatically chunks into batches of 500 (Firestore hard limit). Body must be `IEnumerable>`. With `.DocumentIdField("id")` the document id is taken from that field of each item (and the field itself is not written to the document); without it every item gets an auto-generated id. Note: batches commit sequentially — a failure between chunks leaves the earlier chunks written (the .NET SDK ships no BulkWriter, so cross-batch atomicity is not promised). ## Consumer Realtime snapshot listener — receives document changes as they happen via gRPC stream. ```csharp route.From(Firestore.Collection("orders") .Where("status==pending") .OrderBy("createdAt")) .Process(async (exchange, ct) => { var changeType = exchange.In.GetHeader(FirestoreHeaders.ChangeType); var docId = exchange.In.GetHeader(FirestoreHeaders.DocumentId); // changeType: "Added", "Modified", or "Removed" }); ``` Each document change creates a separate exchange. All changes within a snapshot are processed in parallel with graceful drain on stop. A permanently failed listener (revoked credentials, deleted project) does not kill the consumer silently: the error is recorded in endpoint statistics and the subscription is re-created with exponential backoff (1s → 60s cap). Note that every (re)subscription delivers the current query results as an initial snapshot of `Added` changes. `MaxConcurrency` (default 16) bounds how many changes of one snapshot are processed in parallel. ### Polling mode `.Realtime(false)` switches to an honest poll loop: the query runs every `Delay` ms (`InitialDelay` before the first poll) and the result is diffed against the previous poll by `DocumentId → UpdateTime` — new id = `Added`, changed `UpdateTime` = `Modified`, id gone from the result = `Removed` (body is `null`; the old data is not retained). The first poll delivers everything as `Added`; the diff lives in memory, so a restart starts from a clean snapshot. `Removed` is only visible within the query result window — `Where`/`Limit` shift it. ### Consumer Headers | Header | Type | Description | |---|---|---| | `redbFirestore.DocumentId` | `string` | Document ID | | `redbFirestore.DocumentPath` | `string` | Full path (`collection/docId`) | | `redbFirestore.CollectionPath` | `string` | Collection path | | `redbFirestore.ChangeType` | `string` | `"Added"`, `"Modified"`, or `"Removed"` | | `redbFirestore.CreateTime` | `Timestamp?` | Document creation time | | `redbFirestore.UpdateTime` | `Timestamp?` | Last modification time | | `redbFirestore.ReadTime` | `Timestamp?` | Snapshot read time | ### Body Format Default: `Dictionary` (Firestore native types). With `RawJson(true)`: serialized JSON string. --- # Cloud Storage (`fbstorage`) ## URI Format ``` fbstorage://bucket-name?option=value&... fbstorage://bucket-name/prefix?option=value&... ``` The path after the bucket is a folder-like prefix: `bucket/uploads` and `bucket/uploads/` both mean the `uploads/` folder — Upload joins names with `/` (`uploads/file.txt`) and the consumer lists under the same folder. A raw (non-folder) string prefix is available via the `prefix` option instead. **Consumer** — polls bucket for objects: ``` fbstorage://incoming-data?prefix=uploads/&include=*.csv&deleteAfterRead=true&delay=30000 ``` **Producer** — default operation `Upload`: ``` fbstorage://media-bucket?objectName=${header.fileName}&contentType=image/png fbstorage://media-bucket?operation=Download fbstorage://media-bucket?operation=List&prefix=archive/ ``` ## Producer Operations 5 operations available, set via `operation` URI parameter. | Operation | Description | Key Input | Key Output Headers | |---|---|---|---| | **Upload** | Upload an object | Body: `byte[]`, `Stream`, or `string` | `ObjectName`, `BucketName`, `Md5Hash`, `Generation`, `MediaLink` | | **Download** | Download an object | `ObjectName` header or option | Body: `byte[]` (or `Stream` with `StreamBody`), full metadata headers | | **Delete** | Delete an object | `ObjectName` header or option | — | | **List** | List objects in prefix | `Prefix` option | Body: `List`, `ObjectCount` header | | **GetMetadata** | Get object metadata without downloading | `ObjectName` header or option | Full metadata headers, Body: custom metadata dict | ### Upload ```csharp route.From("direct:upload") .To(FirebaseStorage.Bucket("media") .ObjectName(RouteBuilder.Expr("uploads/${header.category}/${header.fileName}")) .ContentType("application/pdf") .CacheControl("public, max-age=3600")); ``` Body can be `byte[]`, `Stream`, `string`, or any object (auto-serialized to JSON). If `ObjectName` is not set, a GUID is generated. ### Download with Streaming ```csharp // Default: byte[] in memory route.From("direct:download") .To(FirebaseStorage.Bucket("media") .Operation(FirebaseStorageOperationType.Download)); // Large files: Stream (caller must dispose) route.From("direct:download-large") .To(FirebaseStorage.Bucket("media") .Operation(FirebaseStorageOperationType.Download) .StreamBody()); ``` Download runs object retrieval and metadata fetch in parallel for optimal performance. ## Consumer Polls the bucket with `ListObjectsAsync`, downloads matching objects, and optionally deletes/moves them. ```csharp route.From(FirebaseStorage.Bucket("incoming") .Prefix("data/") .Include("*.json") .Exclude("*.tmp") .DeleteAfterRead() .MaxMessagesPerPoll(50) .Delay(10_000) .CredentialPath("/secrets/firebase.json")) .To("direct:process"); ``` ### Consumer Pipeline ``` ListObjects → Filter (prefix/include/exclude) → Idempotency Check → Download Body → Process → Post-Process (delete/move) ``` ### Consumer Options | Option | Default | Description | |---|---|---| | `Delay` | `5000` | Poll interval in milliseconds | | `InitialDelay` | `1000` | Delay before first poll | | `Prefix` | — | Object name prefix filter | | `MaxMessagesPerPoll` | `10` | Max objects per cycle | | `IncludeBody` | `true` | Download object content into exchange body | | `Include` | — | Glob pattern for object names to include (`*.csv`, `data/**/*.json`) — matched against the FULL object name (S3's sibling matches the last `/`-segment only) | | `Exclude` | — | Glob pattern for object names to exclude (`*.tmp`) | | `Idempotent` | `false` | Skip previously processed objects (in-memory, double-buffer eviction at 10K entries) | | `IdempotentRepository` | — | Named `IIdempotentRepository` from the registry (`context.AddIdempotentRepository(name, repo)`) — two-phase claim, survives restarts/scale-out with a persistent repo | | `AutoCreateBucket` | `false` | Create the bucket on consumer start (needs `projectId` or `FIREBASE_PROJECT`) | | `DeleteAfterRead` | `false` | Delete object after successful processing | | `MoveAfterRead` | — | Move objects to this prefix after processing (copy + delete); takes file keys, see below | | `MoveFailed` | — | Quarantine prefix for objects whose processing failed (copy + delete); takes file keys, see below | Both prefixes take the file keys of the object (`${file:ext}`, `${file:name.noext}`, `${file:parent}`, `${file:size}`, `${file:modified}` and the rest of the file language), matching ignoring case. The object keeps its name: the move writes the prefix, keys substituted, followed by the object name, so `moveFailed=failed/${file:ext}/` moves `in/a.csv` to `failed/csv/in/a.csv`. Renaming the object is not what these options do. `${file:name}` is the whole object name, as in S3's `doneFileName`; the path keys write nothing. An unknown key fails when the endpoint is created. Delete/move-after-read happens **only when the exchange succeeded** (no unhandled exception, not marked rollback-only by `.RollbackAll()`). A failed object stays in place and is retried on the next poll — or, with `MoveFailed` set, is moved to the quarantine prefix so the poll loop stops retrying it. With `Idempotent` enabled, only successfully processed objects are marked as seen. ### Consumer Headers | Header | Type | Description | |---|---|---| | `redbStorage.ObjectName` | `string` | Object name (key) | | `redbStorage.BucketName` | `string` | Bucket name | | `redbStorage.ContentType` | `string` | MIME type | | `redbStorage.ContentLength` | `ulong?` | Size in bytes | | `redbStorage.Md5Hash` | `string` | MD5 hash | | `redbStorage.Generation` | `long?` | Object generation | | `redbStorage.TimeCreated` | `DateTimeOffset?` | Creation timestamp | | `redbStorage.Updated` | `DateTimeOffset?` | Last update timestamp | | `redbStorage.MediaLink` | `string` | Direct download URL | --- # FCM (`fcm`) ## URI Format ``` fcm://send?messageType=Token&token=DEVICE_TOKEN&credentialPath=/secrets/fb.json fcm://send?messageType=Topic&topic=news fcm://send?messageType=Condition&condition='news' in topics && 'premium' in topics ``` ## Producer (send-only) FCM is producer-only — no consumer. Sends push notifications via Firebase Cloud Messaging. Beyond the classic send, three operations (`?operation=`): **Multicast** — the same message to many device tokens (`IEnumerable` body or a comma-separated `redbFcm.Tokens` header); **SubscribeToTopic** / **UnsubscribeFromTopic** — topic management for a token list. All three report `redbFcm.SuccessCount` / `redbFcm.FailureCount`. ```csharp .To(Fcm.Multicast().Title("Broadcast").Build()) // body: List of tokens .To(Fcm.SubscribeToTopic("news").Build()) // body: tokens to subscribe ``` ### Token Targeting (single device) ```csharp route.From("direct:push") .To(Fcm.Token(new HeaderExpression("deviceToken")) .Title("Order Shipped") .Body(RouteBuilder.Expr("Your order ${body['orderId']} is on the way")) .ImageUrl("https://example.com/shipped.png") .CredentialPath("/secrets/firebase.json")); ``` ### Topic Targeting (broadcast) ```csharp route.From("direct:broadcast") .To(Fcm.Topic("breaking-news") .Title("Breaking News") .Body(RouteBuilder.Expr("${body['headline']}")) .CredentialPath("/secrets/firebase.json")); ``` ### Condition Targeting (topic expressions) ```csharp route.From("direct:targeted") .To(Fcm.Condition("'premium' in topics && 'news' in topics") .Title("Premium News") .CredentialPath("/secrets/firebase.json")); ``` ### Data-Only Messages ```csharp // Silent push — no visible notification, just data payload route.From("direct:sync") .To(Fcm.Token(new HeaderExpression("deviceToken")) .DataOnly() .CredentialPath("/secrets/firebase.json")); // Body as Dictionary → FCM data payload // Or set headers with prefix: redbFcm.Data.key = value ``` ### Platform-Specific Configuration ```csharp route.From("direct:push") .To(Fcm.Token(new HeaderExpression("deviceToken")) .Title("Update Available") // Android .AndroidPriority("high") .AndroidTtlSeconds(3600) .AndroidChannelId("updates") // iOS .ApnsPriority("10") .ApnsCollapseId("update-group") // Web .WebPushLink("https://app.example.com/updates") .CredentialPath("/secrets/firebase.json")); ``` ### Dynamic Targeting via Headers Target can be overridden at runtime by setting exchange headers: ```csharp exchange.In.Headers[FcmHeaders.Token] = "dynamic-device-token"; exchange.In.Headers[FcmHeaders.Title] = "Dynamic Title"; exchange.In.Headers[FcmHeaders.Body] = "Dynamic body text"; // Data payload via header prefix exchange.In.Headers["redbFcm.Data.orderId"] = "12345"; exchange.In.Headers["redbFcm.Data.action"] = "refresh"; ``` ### Output Headers | Header | Type | Description | |---|---|---| | `redbFcm.MessageId` | `string` | Server-assigned message ID (`projects/*/messages/*`) | --- ## Fluent DSL Reference ```csharp using redb.Route.Firebase; ``` ### Firestore | Category | Methods | |---|---| | **Entry** | `Firestore.Collection(path)` | | **Operation** | `.Operation(op)` | | **Document** | `.DocumentId(id)`, `.DocumentId(expr)` | | **Query** | `.Where(filter)`, `.OrderBy(field)`, `.Limit(n)`, `.Offset(n)` | | **Write** | `.Merge()`, `.DocumentIdField(name)` | | **Consumer** | `.Realtime()`, `.MaxConcurrency(n)`, `.Delay(ms)`, `.InitialDelay(ms)` | | **Database** | `.DatabaseId(id)` — multi-database projects (default `(default)`) | | **Format** | `.RawJson()` | | **Auth** | `.CredentialPath(p)`, `.ProjectId(id)`, `.ConnectionFactory(name)` | ### Cloud Storage | Category | Methods | |---|---| | **Entry** | `FirebaseStorage.Bucket(name)`, `FirebaseStorage.Bucket(name, prefix)` | | **Operation** | `.Operation(op)` | | **Object** | `.ObjectName(name)`, `.ObjectName(expr)`, `.ContentType(ct)`, `.CacheControl(v)` | | **Consumer** | `.Delay(ms)`, `.Prefix(p)`, `.MaxMessagesPerPoll(n)` | | **Post** | `.DeleteAfterRead()`, `.MoveAfterRead(prefix)`, `.MoveFailed(prefix)`, `.Idempotent()` | | **Filter** | `.Include(glob)`, `.Exclude(glob)` | | **Body** | `.IncludeBody()`, `.StreamBody()` | | **Auth** | `.CredentialPath(p)`, `.ProjectId(id)`, `.ConnectionFactory(name)` | ### FCM | Category | Methods | |---|---| | **Entry** | `Fcm.Token(v)`, `Fcm.Topic(v)`, `Fcm.Condition(v)`, `Fcm.Multicast()`, `Fcm.SubscribeToTopic(t)`, `Fcm.UnsubscribeFromTopic(t)` | | **Notification** | `.Title(v)`, `.Body(v)`, `.ImageUrl(url)` | | **Mode** | `.DataOnly()`, `.DryRun()` | | **Android** | `.AndroidPriority(p)`, `.AndroidTtlSeconds(s)`, `.AndroidChannelId(id)` | | **APNS** | `.ApnsPriority(p)`, `.ApnsCollapseId(id)` | | **Web** | `.WebPushLink(url)` | | **Auth** | `.CredentialPath(p)`, `.ProjectId(id)`, `.ConnectionFactory(name)` | All builders support `implicit operator string` — pass directly to `.From()` / `.To()`. --- ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint`: - **Consumers.** Firestore, realtime and polling alike: one `Consumer` span per routed change, `firestore {collection} receive`. Storage: one per routed object, `gcs {bucket} receive`. A change or an object carries no trace context, so the span is a root, never a child of the activity the consumer inherited from whoever started the routes; nothing arriving opens none. A failed route marks it an error, whether the failure stays on the exchange or escapes it; our own stop does not. A Storage object whose route failed is not deleted either way. - **Producers.** FCM (`fcm {operation}`), Firestore (`firestore {operation}`) and Storage (`gcs {operation}`) open one span per call; an error when the call fails, unless our own token cancelled it. - `RouteEngineOptions.EnableTelemetry = false` opens none of these spans. Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageComponent.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/Storage/FirebaseStorageComponent.cs ---- using Google.Cloud.Storage.V1; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Firebase; /// /// Firebase Storage component registered with scheme fbstorage. /// Firebase Storage = GCS bucket — uses Google.Cloud.Storage.V1. /// internal sealed class FirebaseStorageComponent : ComponentBase { /// public override string Scheme => "fbstorage"; /// 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 FirebaseStorageEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return new FirebaseStorageEndpoint(uri, this, options); } } /// /// Firebase Storage endpoint. Creates producers for file operations /// and consumers for polling bucket contents. /// URI path format: fbstorage://bucket-name or fbstorage://bucket-name/prefix. /// internal sealed class FirebaseStorageEndpoint : EndpointBase, IDisposable { private StorageClient? _client; private readonly SemaphoreSlim _lock = new(1, 1); internal FirebaseStorageEndpoint(EndpointUri uri, FirebaseStorageComponent component, FirebaseStorageEndpointOptions options) : base(uri, component, options) { // Parse bucket name from URI path (first segment) var path = uri.Path; var slashIdx = path.IndexOf('/'); BucketName = options.BucketName ?? (slashIdx > 0 ? path[..slashIdx] : path); // The path after the bucket is folder-like: "bucket/uploads" and "bucket/uploads/" // both mean the "uploads/" prefix — Upload must never produce "uploadsfile.txt". // A raw (non-folder) string prefix is still available via the Prefix option. var rawPrefix = slashIdx > 0 ? path[(slashIdx + 1)..] : null; ObjectPrefix = string.IsNullOrEmpty(rawPrefix) ? null : rawPrefix.EndsWith('/') ? rawPrefix : rawPrefix + "/"; } /// Bucket name parsed from the URI path or options. internal string BucketName { get; } /// Optional object prefix from the URI path. internal string? ObjectPrefix { get; } /// The owning Storage component. internal FirebaseStorageComponent StorageComponent => (FirebaseStorageComponent)Component; /// Typed options for external access. internal FirebaseStorageEndpointOptions EndpointOptions => Options; /// Gets or creates a shared . internal async Task GetOrCreateClientAsync(CancellationToken ct = default) { if (_client is not null) return _client; await _lock.WaitAsync(ct).ConfigureAwait(false); try { if (_client is not null) return _client; var provider = ResolveCredentialProvider(); _client = provider.GetStorageClient(Options.CredentialPath); return _client; } finally { _lock.Release(); } } /// Signer for CreateDownloadLink — requires a service-account credential. internal Google.Cloud.Storage.V1.UrlSigner GetUrlSigner() => ResolveCredentialProvider().GetUrlSigner(Options.CredentialPath); /// /// Project id for bucket-level operations (CreateBucket/ListBuckets/AutoCreateBucket) — /// GCS needs it to own the bucket; a missing project is a loud error, never a guess. /// internal string RequireProjectId() => Options.ProjectId ?? Environment.GetEnvironmentVariable("FIREBASE_PROJECT") ?? throw new InvalidOperationException( "Bucket operations require a project id. Set it on the endpoint (?projectId=...) " + "or via the FIREBASE_PROJECT environment variable."); /// public override IProducer CreateProducer() => new FirebaseStorageProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new FirebaseStorageConsumer(this, processor, Options); } /// public void Dispose() { // Do NOT dispose _client — it's owned by the shared IFirebaseCredentialProvider singleton. // Only dispose our own synchronization primitive. _lock.Dispose(); } private IFirebaseCredentialProvider ResolveCredentialProvider() { // A set-but-unknown name fails loud -- never a silent fallback. if (!string.IsNullOrEmpty(Options.ConnectionFactory)) return StorageComponent.Context .GetRequiredFromRegistry(Options.ConnectionFactory); return StorageComponent.CredentialProvider ?? throw new InvalidOperationException( "No IFirebaseCredentialProvider available. Register via AddRedbRouteFirebase() or set ConnectionFactory."); } } Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageConsumer.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/Storage/FirebaseStorageConsumer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Text.RegularExpressions; using Google.Cloud.Storage.V1; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Telemetry; namespace redb.Route.Firebase; /// /// Firebase Storage consumer — polls a bucket for objects using ListObjectsAsync. /// Extends for graceful two-CTS shutdown. /// Supports prefix/include/exclude filtering, idempotency, delete-after-read, /// and move-after-read (copy + delete). /// internal sealed class FirebaseStorageConsumer : DrainableConsumer { private readonly FirebaseStorageEndpoint _endpoint; private readonly FirebaseStorageEndpointOptions _options; private StorageClient? _client; private const int MaxIdempotentEntries = 10_000; private ConcurrentDictionary? _currentIdempotentRepo; private ConcurrentDictionary? _previousIdempotentRepo; private readonly bool _idempotent; // Named repository: the shared IIdempotentRepository contract of the route-level // IdempotentConsumer EIP — dedup survives consumer restarts (and process restarts with // a persistent implementation). private IIdempotentRepository? _sharedRepo; private readonly Regex? _includeRegex; private readonly Regex? _excludeRegex; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"fbstorage://{_endpoint.BucketName}"; internal FirebaseStorageConsumer(FirebaseStorageEndpoint endpoint, IProcessor processor, FirebaseStorageEndpointOptions options) : base(processor) { _endpoint = endpoint; _options = options; if (options.Idempotent) { _idempotent = true; _currentIdempotentRepo = new ConcurrentDictionary(); } if (!string.IsNullOrEmpty(options.Include)) _includeRegex = GlobToRegex(options.Include); if (!string.IsNullOrEmpty(options.Exclude)) _excludeRegex = GlobToRegex(options.Exclude); } /// protected override async Task OnStarting(CancellationToken ct) { _client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false); if (!string.IsNullOrEmpty(_options.IdempotentRepository)) { var context = (_endpoint.Component as ComponentBase)?.Context ?? throw new InvalidOperationException( $"IdempotentRepository '{_options.IdempotentRepository}' requires a route context " + "(register the repository with context.AddIdempotentRepository(name, ...))."); _sharedRepo = context.GetIdempotentRepositoryProvider().Get(_options.IdempotentRepository); } if (_options.AutoCreateBucket) { try { await _client.CreateBucketAsync(_endpoint.RequireProjectId(), _endpoint.BucketName, cancellationToken: ct).ConfigureAwait(false); } catch (Google.GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.Conflict) { // already exists } } } /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { if (_options.InitialDelay > 0) await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); while (!pollCt.IsCancellationRequested) { try { await PollBucketAsync(processingCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogError(ex, "Firebase Storage consumer poll error on bucket {Bucket}", _endpoint.BucketName); _endpoint.RecordError(ex); } try { await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested) { break; } } } private async Task PollBucketAsync(CancellationToken ct) { var prefix = _options.Prefix ?? _endpoint.ObjectPrefix; var objects = _client!.ListObjectsAsync(_endpoint.BucketName, prefix); var processed = 0; // Double-buffer eviction: when current fills up, rotate to previous // and start fresh — retains up to 2×MaxIdempotentEntries of history. if (_idempotent && _currentIdempotentRepo!.Count > MaxIdempotentEntries) { _previousIdempotentRepo = _currentIdempotentRepo; _currentIdempotentRepo = new ConcurrentDictionary(); } await foreach (var obj in objects.ConfigureAwait(false)) { if (ct.IsCancellationRequested || processed >= _options.MaxMessagesPerPoll) break; // Filter by include/exclude if (_includeRegex is not null && !_includeRegex.IsMatch(obj.Name)) continue; if (_excludeRegex is not null && _excludeRegex.IsMatch(obj.Name)) continue; // Idempotency: check only — the "seen" mark is written after a SUCCESSFUL // exchange, so a failed object is offered again on the next poll. if (_idempotent && (_currentIdempotentRepo!.ContainsKey(obj.Name) || _previousIdempotentRepo?.ContainsKey(obj.Name) == true)) continue; if (_sharedRepo is not null && await _sharedRepo.Contains(SharedKey(obj.Name), ct).ConfigureAwait(false)) continue; // Named repo: two-phase claim (Add → process → Confirm / Remove), same as the // route-level EIP — a concurrent consumer cannot take the same object twice. if (_sharedRepo is not null && !await _sharedRepo.Add(SharedKey(obj.Name), ct).ConfigureAwait(false)) continue; bool success; try { var exchange = await CreateExchange(obj, ct).ConfigureAwait(false); success = await ProcessExchangeAsync(exchange, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (Exception ex) { // Download/exchange creation failed — the object was never delivered: // no post-processing, no idempotent mark, retry on the next poll. Logger?.LogError(ex, "Firebase Storage: error reading object {Object}", obj.Name); _endpoint.RecordError(ex); await ReleaseSharedClaimAsync(obj.Name, ct).ConfigureAwait(false); processed++; continue; } try { if (success) { if (_idempotent) _currentIdempotentRepo!.TryAdd(obj.Name, true); if (_sharedRepo is not null) await _sharedRepo.Confirm(SharedKey(obj.Name), ct).ConfigureAwait(false); await PostProcessObject(obj, ct).ConfigureAwait(false); } else { await ReleaseSharedClaimAsync(obj.Name, ct).ConfigureAwait(false); if (_options.MoveFailed is not null) await MoveObjectAsync(obj, _options.MoveFailed, ct).ConfigureAwait(false); } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogError(ex, "Firebase Storage: post-processing failed for {Object}", obj.Name); _endpoint.RecordError(ex); } processed++; } } /// /// Runs the exchange through the processor, inside the root span of the object (an object carries no trace /// context), and reports whether it succeeded. A processing failure must not delete/move the object (data loss): /// leaves a failure /// that escaped the pipeline on the exchange too, so an unhandled exchange.Exception is the failure either way. /// A rollback-only exchange (.RollbackAll()) is a failure as well /// (): the object stays, or goes to moveFailed. /// private async Task ProcessExchangeAsync(Exchange exchange, CancellationToken ct) { using var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"gcs {_endpoint.BucketName} receive", ActivityKind.Consumer, "redb.system", "gcs", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.BucketName, operation: "receive"); await ProcessWithTracking(exchange, span, ct).ConfigureAwait(false); return !exchange.EndedInFailure(); } private async Task CreateExchange(Google.Apis.Storage.v1.Data.Object obj, CancellationToken ct) { object? body = null; if (_options.IncludeBody) { var ms = new MemoryStream(); await _client!.DownloadObjectAsync(_endpoint.BucketName, obj.Name, ms, cancellationToken: ct).ConfigureAwait(false); body = ms.ToArray(); // BytesIn is the core's estimate of the same payload } var exchange = Exchange.Create(new Message(body), _endpoint.ScopeFactory); exchange.In.Headers[FirebaseStorageHeaders.ObjectName] = obj.Name; exchange.In.Headers[FirebaseStorageHeaders.BucketName] = _endpoint.BucketName; exchange.In.Headers[FirebaseStorageHeaders.ContentType] = obj.ContentType; exchange.In.Headers[FirebaseStorageHeaders.ContentLength] = obj.Size; exchange.In.Headers[FirebaseStorageHeaders.Md5Hash] = obj.Md5Hash; exchange.In.Headers[FirebaseStorageHeaders.Generation] = obj.Generation; exchange.In.Headers[FirebaseStorageHeaders.TimeCreated] = GcsDateTimeHelper.SafeParse(() => obj.TimeCreatedDateTimeOffset, obj.TimeCreatedRaw); exchange.In.Headers[FirebaseStorageHeaders.Updated] = GcsDateTimeHelper.SafeParse(() => obj.UpdatedDateTimeOffset, obj.UpdatedRaw); exchange.In.Headers[FirebaseStorageHeaders.MediaLink] = obj.MediaLink; // MessagesIn is counted by the core StatisticsProcessor - ownership audit. return exchange; } private async Task PostProcessObject(Google.Apis.Storage.v1.Data.Object obj, CancellationToken ct) { if (_options.MoveAfterRead is not null) { await MoveObjectAsync(obj, _options.MoveAfterRead, ct).ConfigureAwait(false); } else if (_options.DeleteAfterRead) { await _client!.DeleteObjectAsync(_endpoint.BucketName, obj.Name, cancellationToken: ct).ConfigureAwait(false); } } private string SharedKey(string objectName) => $"{_endpoint.BucketName}/{objectName}"; /// Releases the two-phase claim so a failed object is offered again. private async Task ReleaseSharedClaimAsync(string objectName, CancellationToken ct) { if (_sharedRepo is null) return; try { await _sharedRepo.Remove(SharedKey(objectName), ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { Logger?.LogWarning(ex, "Firebase Storage: releasing idempotent claim for {Object} failed — the object stays marked until manual cleanup", objectName); } } /// /// The object name a move of writes to: the prefix with its file keys read from the /// object (failed/${file:ext}/), then the object name, which the move keeps. /// internal static string MoveDestination(string destPrefix, string objectName, long? size, DateTimeOffset? updated) => FileLanguage.Substitute(destPrefix, new ObjectKeyFacts(objectName, size, updated), StringComparison.OrdinalIgnoreCase) + objectName; private async Task MoveObjectAsync(Google.Apis.Storage.v1.Data.Object obj, string destPrefix, CancellationToken ct) { var objectName = obj.Name; var destName = MoveDestination(destPrefix, objectName, (long?)obj.Size, GcsDateTimeHelper.SafeParse(() => obj.UpdatedDateTimeOffset, obj.UpdatedRaw)); await _client!.CopyObjectAsync(_endpoint.BucketName, objectName, _endpoint.BucketName, destName, cancellationToken: ct).ConfigureAwait(false); try { await _client.DeleteObjectAsync(_endpoint.BucketName, objectName, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { // Copy succeeded but delete failed — object is duplicated. // Log and continue; next poll will skip via idempotency or retry delete. Logger?.LogWarning(ex, "Firebase Storage: move copied {Src} → {Dest} but delete of source failed. " + "Object exists in both locations until next successful delete", objectName, destName); } } private static Regex GlobToRegex(string glob) { var pattern = "^" + Regex.Escape(glob) .Replace("\\*\\*", ".*") .Replace("\\*", "[^/]*") .Replace("\\?", "[^/]") + "$"; return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); } } Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageEndpointOptions.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/Storage/FirebaseStorageEndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Firebase; /// /// Endpoint options for the Firebase Storage component. /// Supports producer (upload/download/delete/list/metadata) and consumer (polling) modes. /// Firebase Storage = GCS bucket — compatible with Google.Cloud.Storage.V1. /// public sealed class FirebaseStorageEndpointOptions : EndpointOptions { // ── Auth ── /// Path to the Firebase service-account JSON file. public string? CredentialPath { get; set; } /// Firebase/GCP project ID. public string? ProjectId { get; set; } /// Named reference from the registry. [RegistryReference(typeof(IFirebaseCredentialProvider))] public string? ConnectionFactory { get; set; } // ── Target ── /// Producer operation type. Default: . public FirebaseStorageOperationType Operation { get; set; } = FirebaseStorageOperationType.Upload; /// Override bucket name (default from URI path). public string? BucketName { get; set; } // ── Upload ── /// Object name/key. Supports ${...} expressions. public DynamicValue? ObjectName { get; set; } /// MIME content type override. public string? ContentType { get; set; } /// Cache-Control header (e.g. "public, max-age=3600"). public string? CacheControl { get; set; } // ── Copy ── /// Destination object name for the Copy operation. Supports ${...} expressions. public DynamicValue? DestinationObjectName { get; set; } /// Destination bucket for the Copy operation (default: source bucket). public string? DestinationBucket { get; set; } // ── Signed URLs ── /// TTL for CreateDownloadLink signed URLs, in milliseconds. Default: 1 hour. public long SignedUrlExpiration { get; set; } = 3_600_000; // ── Download ── /// Download body as Stream (true) or byte[] (false). public bool StreamBody { get; set; } // ── Consumer: Polling ── /// Poll interval (ms). Default: 5000. public int Delay { get; set; } = 5000; /// Initial delay (ms) before first poll. Default: 1000. public int InitialDelay { get; set; } = 1000; /// Object name prefix filter for listing. public string? Prefix { get; set; } /// Maximum number of objects to process per poll cycle. public int MaxMessagesPerPoll { get; set; } = 10; /// Download object body into exchange (default: true). public bool IncludeBody { get; set; } = true; /// Delete object after successful consumer processing. public bool DeleteAfterRead { get; set; } /// Move objects to this prefix after processing (copy + delete). public string? MoveAfterRead { get; set; } /// /// Move objects whose processing FAILED (an unhandled exception, or an exchange marked rollback-only) to this /// prefix (copy + delete) — a quarantine /// pocket so the poll loop stops retrying them. When unset, a failed object stays in /// place and is offered again on the next poll. /// public string? MoveFailed { get; set; } /// Skip previously processed objects (in-memory idempotent repository). public bool Idempotent { get; set; } /// /// Name of an IIdempotentRepository registered via /// context.AddIdempotentRepository(name, repo) — the same contract the route-level /// IdempotentConsumer EIP uses. With a persistent repository (RedbIdempotentRepository) /// deduplication survives restarts and scale-out. Takes precedence over the in-memory /// flag. /// [RegistryReference(typeof(IIdempotentRepository))] public string? IdempotentRepository { get; set; } /// /// Create the bucket on consumer start when it does not exist (requires /// or FIREBASE_PROJECT). Default: false. /// public bool AutoCreateBucket { get; set; } // ── Consumer: Filtering ── /// Include glob pattern for object names. public string? Include { get; set; } /// Exclude glob pattern for object names. public string? Exclude { get; set; } /// public override void Validate() { // STORAGE_EMULATOR_HOST is the env var Google.Cloud.Storage.V1 actually honors // (FIREBASE_STORAGE_EMULATOR_HOST belongs to the Firebase client SDKs, not this one). if (string.IsNullOrWhiteSpace(CredentialPath) && string.IsNullOrWhiteSpace(ConnectionFactory) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("STORAGE_EMULATOR_HOST"))) throw new ArgumentOutOfRangeException(nameof(CredentialPath), "CredentialPath, ConnectionFactory, GOOGLE_APPLICATION_CREDENTIALS, or STORAGE_EMULATOR_HOST required"); if (Delay < 100) throw new ArgumentOutOfRangeException(nameof(Delay), "Delay must be >= 100ms"); if (MaxMessagesPerPoll < 1) throw new ArgumentOutOfRangeException(nameof(MaxMessagesPerPoll), "MaxMessagesPerPoll must be >= 1"); // The file keys of the move prefixes, checked here so a wrong key fails when the endpoint is created. ValidateFileKeys("moveAfterRead", MoveAfterRead); ValidateFileKeys("moveFailed", MoveFailed); } private static void ValidateFileKeys(string option, string? prefix) { if (!string.IsNullOrEmpty(prefix) && redb.Route.Expressions.FileLanguage.FindUnknownKey(prefix, StringComparison.OrdinalIgnoreCase) is { } key) throw new InvalidOperationException($"{option}='{prefix}': {redb.Route.Expressions.FileLanguage.UnknownKeyMessage(key)}"); } } Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageHeaders.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/Storage/FirebaseStorageHeaders.cs ---- namespace redb.Route.Firebase; /// /// Header constants for the Firebase Storage connector. Prefix: redbStorage. /// public static class FirebaseStorageHeaders { /// Common prefix for all Storage headers. public const string Prefix = "redbStorage."; /// Bucket name. public const string BucketName = "redbStorage.BucketName"; /// Object name (key) within the bucket. public const string ObjectName = "redbStorage.ObjectName"; /// Content-Type MIME type of the object. public const string ContentType = "redbStorage.ContentType"; /// Content-Length in bytes. public const string ContentLength = "redbStorage.ContentLength"; /// MD5 hash of the object. public const string Md5Hash = "redbStorage.Md5Hash"; /// CRC32C checksum. public const string Crc32c = "redbStorage.Crc32c"; /// Object generation (version) number. public const string Generation = "redbStorage.Generation"; /// Metadata generation number. public const string MetaGeneration = "redbStorage.MetaGeneration"; /// Object creation timestamp. public const string TimeCreated = "redbStorage.TimeCreated"; /// Last update timestamp. public const string Updated = "redbStorage.Updated"; /// Direct download URL (media link). public const string MediaLink = "redbStorage.MediaLink"; /// Prefix for custom metadata entries. public const string MetadataPrefix = "redbStorage.Meta."; /// Number of objects in a list result. public const string ObjectCount = "redbStorage.ObjectCount"; /// Destination object name for the Copy operation. public const string DestinationObjectName = "redbStorage.DestinationObjectName"; /// Destination bucket for the Copy operation (default: source bucket). public const string DestinationBucket = "redbStorage.DestinationBucket"; /// Signed download URL produced by CreateDownloadLink. public const string DownloadUrl = "redbStorage.DownloadUrl"; /// Number of buckets in a ListBuckets result. public const string BucketCount = "redbStorage.BucketCount"; } Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageOperationType.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/Storage/FirebaseStorageOperationType.cs ---- namespace redb.Route.Firebase; /// /// Firebase Storage operation types for the producer. /// Firebase Storage is GCS-compatible — uses Google.Cloud.Storage.V1. /// public enum FirebaseStorageOperationType { /// Upload a file/byte[]/stream to Storage. Upload, /// Download an object to exchange body (byte[] or Stream). Download, /// Delete an object by name. Delete, /// List objects in the bucket with optional prefix filter. List, /// Get object metadata without downloading the body. GetMetadata, /// Copy an object server-side (no download) to another name/bucket. Copy, /// Create a signed download URL with a TTL (requires service-account credentials). CreateDownloadLink, /// Create a bucket. CreateBucket, /// Delete a bucket (must be empty). DeleteBucket, /// List buckets of the project. ListBuckets } Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageProducer.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/Storage/FirebaseStorageProducer.cs ---- using System.Diagnostics; using System.Text; using System.Text.Json; using Google.Apis.Storage.v1.Data; using Google.Cloud.Storage.V1; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Firebase; /// /// Firebase Storage producer — upload, download, delete, list, and get metadata /// for objects in a Google Cloud Storage (Firebase Storage) bucket. /// internal sealed class FirebaseStorageProducer : ConnectableProducer { private readonly FirebaseStorageEndpoint _endpoint; private readonly FirebaseStorageEndpointOptions _options; private StorageClient? _client; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => _endpoint.Uri.NormalizedKey; internal FirebaseStorageProducer(FirebaseStorageEndpoint endpoint, FirebaseStorageEndpointOptions options) { _endpoint = endpoint; _options = options; } /// protected override async Task ConnectAsync(CancellationToken ct) { _client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false); } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); // redb.system: house attribute for object storage — OTel defines no db.system value // for GCS/S3, and the S3 sibling already ships "redb.system". using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"gcs {_options.Operation}", ActivityKind.Client, "redb.system", "gcs", _endpoint.Uri.NormalizedKey, destination: _endpoint.BucketName, operation: _options.Operation.ToString()); try { switch (_options.Operation) { case FirebaseStorageOperationType.Upload: await ProcessUpload(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.Download: await ProcessDownload(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.Delete: await ProcessDelete(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.List: await ProcessList(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.GetMetadata: await ProcessGetMetadata(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.Copy: await ProcessCopy(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.CreateDownloadLink: ProcessCreateDownloadLink(exchange); break; case FirebaseStorageOperationType.CreateBucket: await ProcessCreateBucket(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.DeleteBucket: await ProcessDeleteBucket(exchange, ct).ConfigureAwait(false); break; case FirebaseStorageOperationType.ListBuckets: await ProcessListBuckets(exchange, ct).ConfigureAwait(false); break; default: throw new InvalidOperationException($"Unknown Storage 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 ProcessUpload(IExchange exchange, CancellationToken ct) { var objectName = ResolveObjectName(exchange) ?? Guid.NewGuid().ToString(); // Prepend prefix if present in URI if (_endpoint.ObjectPrefix is not null) objectName = _endpoint.ObjectPrefix + objectName; var bodyIsStream = exchange.In.Body is Stream; var stream = GetBodyStream(exchange); try { var contentType = _options.ContentType ?? exchange.In.ContentType ?? "application/octet-stream"; // Upload with metadata in a single API call (includes CacheControl if set) var obj = await _client!.UploadObjectAsync( new Google.Apis.Storage.v1.Data.Object { Bucket = _endpoint.BucketName, Name = objectName, ContentType = contentType, CacheControl = _options.CacheControl }, stream, cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirebaseStorageHeaders.ObjectName] = obj.Name; exchange.In.Headers[FirebaseStorageHeaders.BucketName] = obj.Bucket; exchange.In.Headers[FirebaseStorageHeaders.Md5Hash] = obj.Md5Hash; exchange.In.Headers[FirebaseStorageHeaders.Generation] = obj.Generation; exchange.In.Headers[FirebaseStorageHeaders.MediaLink] = obj.MediaLink; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } finally { // Dispose only streams we created (not the caller's original stream) if (!bodyIsStream) await stream.DisposeAsync().ConfigureAwait(false); } } private async Task ProcessDownload(IExchange exchange, CancellationToken ct) { var objectName = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? ResolveObjectName(exchange) ?? throw new InvalidOperationException("ObjectName header or option is required for Download"); if (_options.StreamBody) { // True streaming: the download is pumped into a Pipe in the background and // the exchange gets the reader side — nothing is buffered whole in memory. // The exchange owns the stream; disposing it (Exchange.DisposeAsync) tears the // pipe down and aborts a still-running download. var meta = await _client!.GetObjectAsync( _endpoint.BucketName, objectName, cancellationToken: ct).ConfigureAwait(false); var pipe = new System.IO.Pipelines.Pipe(); _ = Task.Run(async () => { try { var writerStream = pipe.Writer.AsStream(leaveOpen: true); await using (writerStream.ConfigureAwait(false)) { await _client.DownloadObjectAsync( _endpoint.BucketName, objectName, writerStream, cancellationToken: CancellationToken.None) .ConfigureAwait(false); } await pipe.Writer.CompleteAsync().ConfigureAwait(false); } catch (Exception ex) { // Surfaces to the consumer of the reader stream on its next read. await pipe.Writer.CompleteAsync(ex).ConfigureAwait(false); } }, CancellationToken.None); exchange.Out = new Message(pipe.Reader.AsStream()); SetMetadataHeaders(exchange.Out, meta); exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordBytesIn((long)(meta.Size ?? 0UL)); _endpoint.RecordMessageIn(); return; } var ms = new MemoryStream(); try { // Run download and metadata retrieval in parallel var downloadTask = _client!.DownloadObjectAsync( _endpoint.BucketName, objectName, ms, cancellationToken: ct); var metaTask = _client.GetObjectAsync( _endpoint.BucketName, objectName, cancellationToken: ct); await Task.WhenAll(downloadTask, metaTask).ConfigureAwait(false); _endpoint.RecordBytesIn(ms.Length); exchange.Out = new Message(ms.ToArray()); SetMetadataHeaders(exchange.Out, metaTask.Result); exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } finally { ms.Dispose(); } } private async Task ProcessCopy(IExchange exchange, CancellationToken ct) { var sourceName = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? ResolveObjectName(exchange) ?? throw new InvalidOperationException("ObjectName header or option is required for Copy"); var destName = exchange.In.GetHeader(FirebaseStorageHeaders.DestinationObjectName) ?? _options.DestinationObjectName?.Resolve(exchange) ?? throw new InvalidOperationException( "DestinationObjectName header or option is required for Copy"); var destBucket = exchange.In.GetHeader(FirebaseStorageHeaders.DestinationBucket) ?? _options.DestinationBucket ?? _endpoint.BucketName; var copied = await _client!.CopyObjectAsync( _endpoint.BucketName, sourceName, destBucket, destName, cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirebaseStorageHeaders.ObjectName] = copied.Name; exchange.In.Headers[FirebaseStorageHeaders.BucketName] = copied.Bucket; exchange.In.Headers[FirebaseStorageHeaders.Generation] = copied.Generation; exchange.In.Headers[FirebaseStorageHeaders.MediaLink] = copied.MediaLink; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessDelete(IExchange exchange, CancellationToken ct) { var objectName = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? ResolveObjectName(exchange) ?? throw new InvalidOperationException("ObjectName header or option is required for Delete"); await _client!.DeleteObjectAsync(_endpoint.BucketName, objectName, cancellationToken: ct).ConfigureAwait(false); // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessList(IExchange exchange, CancellationToken ct) { var prefix = _options.Prefix ?? _endpoint.ObjectPrefix; var objects = _client!.ListObjectsAsync(_endpoint.BucketName, prefix); var list = new List(); await foreach (var obj in objects.ConfigureAwait(false)) { ct.ThrowIfCancellationRequested(); list.Add(new Dictionary { ["Name"] = obj.Name, ["Size"] = obj.Size, ["ContentType"] = obj.ContentType, ["TimeCreated"] = GcsDateTimeHelper.SafeParse(() => obj.TimeCreatedDateTimeOffset, obj.TimeCreatedRaw) }); } exchange.Out = new Message(list); exchange.Out.Headers[FirebaseStorageHeaders.ObjectCount] = list.Count; exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } private async Task ProcessGetMetadata(IExchange exchange, CancellationToken ct) { var objectName = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? ResolveObjectName(exchange) ?? throw new InvalidOperationException("ObjectName header or option is required for GetMetadata"); var meta = await _client!.GetObjectAsync(_endpoint.BucketName, objectName, cancellationToken: ct).ConfigureAwait(false); exchange.Out = new Message(meta.Metadata); SetMetadataHeaders(exchange.Out, meta); exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } private void ProcessCreateDownloadLink(IExchange exchange) { var objectName = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? ResolveObjectName(exchange) ?? throw new InvalidOperationException( "ObjectName header or option is required for CreateDownloadLink"); var signer = _endpoint.GetUrlSigner(); var url = signer.Sign(_endpoint.BucketName, objectName, TimeSpan.FromMilliseconds(_options.SignedUrlExpiration), HttpMethod.Get); exchange.Out = new Message(url); exchange.Out.Headers[FirebaseStorageHeaders.DownloadUrl] = url; exchange.Out.Headers[FirebaseStorageHeaders.ObjectName] = objectName; exchange.Out.Headers[FirebaseStorageHeaders.BucketName] = _endpoint.BucketName; exchange.Pattern = ExchangePattern.InOut; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessCreateBucket(IExchange exchange, CancellationToken ct) { var bucket = await _client!.CreateBucketAsync( _endpoint.RequireProjectId(), _endpoint.BucketName, cancellationToken: ct).ConfigureAwait(false); exchange.In.Headers[FirebaseStorageHeaders.BucketName] = bucket.Name; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessDeleteBucket(IExchange exchange, CancellationToken ct) { await _client!.DeleteBucketAsync(_endpoint.BucketName, cancellationToken: ct) .ConfigureAwait(false); exchange.In.Headers[FirebaseStorageHeaders.BucketName] = _endpoint.BucketName; // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } private async Task ProcessListBuckets(IExchange exchange, CancellationToken ct) { var names = new List(); await foreach (var bucket in _client!.ListBucketsAsync(_endpoint.RequireProjectId()) .ConfigureAwait(false)) { ct.ThrowIfCancellationRequested(); names.Add(bucket.Name); } exchange.Out = new Message(names); exchange.Out.Headers[FirebaseStorageHeaders.BucketCount] = names.Count; exchange.Pattern = ExchangePattern.InOut; _endpoint.RecordMessageIn(); } // ── Helpers ── private string? ResolveObjectName(IExchange exchange) { return _options.ObjectName?.Resolve(exchange); } private static Stream GetBodyStream(IExchange exchange) { return exchange.In.Body switch { byte[] bytes => new MemoryStream(bytes), Stream s => s, string str => new MemoryStream(Encoding.UTF8.GetBytes(str)), null => throw new InvalidOperationException("Upload requires a non-null body"), _ => new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(exchange.In.Body))) }; } private static void SetMetadataHeaders(IMessage message, Google.Apis.Storage.v1.Data.Object meta) { message.Headers[FirebaseStorageHeaders.ObjectName] = meta.Name; message.Headers[FirebaseStorageHeaders.BucketName] = meta.Bucket; message.Headers[FirebaseStorageHeaders.ContentType] = meta.ContentType; message.Headers[FirebaseStorageHeaders.ContentLength] = meta.Size; message.Headers[FirebaseStorageHeaders.Md5Hash] = meta.Md5Hash; message.Headers[FirebaseStorageHeaders.Crc32c] = meta.Crc32c; message.Headers[FirebaseStorageHeaders.Generation] = meta.Generation; message.Headers[FirebaseStorageHeaders.MetaGeneration] = meta.Metageneration; message.Headers[FirebaseStorageHeaders.TimeCreated] = GcsDateTimeHelper.SafeParse(() => meta.TimeCreatedDateTimeOffset, meta.TimeCreatedRaw); message.Headers[FirebaseStorageHeaders.Updated] = GcsDateTimeHelper.SafeParse(() => meta.UpdatedDateTimeOffset, meta.UpdatedRaw); message.Headers[FirebaseStorageHeaders.MediaLink] = meta.MediaLink; if (meta.Metadata is not null) { foreach (var (key, value) in meta.Metadata) message.Headers[FirebaseStorageHeaders.MetadataPrefix + key] = value; } } } Path: redb-route/redb.Route.Firebase/Storage/GcsDateTimeHelper.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/Storage/GcsDateTimeHelper.cs ---- using System.Globalization; namespace redb.Route.Firebase; /// /// Safely reads DateTimeOffset from a GCS object, falling back to manual parsing /// when the SDK's typed accessor throws (e.g. non-RFC 3339 from emulators). /// Always returns ? — never a raw string. /// internal static class GcsDateTimeHelper { /// /// Safely resolves a DateTimeOffset from a GCS object property. /// /// SDK typed accessor (e.g. obj.TimeCreatedDateTimeOffset). /// Raw JSON string (e.g. obj.TimeCreatedRaw). internal static DateTimeOffset? SafeParse(Func accessor, string? raw) { try { return accessor(); } catch (FormatException) { // SDK couldn't parse — try manual parse of the raw string. if (raw is not null && DateTimeOffset.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var dto)) { return dto; } return null; } } } Path: redb-route/redb.Route.Firebase/redb.Route.Firebase.csproj 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/redb.Route.Firebase.csproj ---- redb.Route.Firebase redb.Route.Firebase Firebase connector for redb.Route — FCM push notifications, Firestore realtime listeners, Firebase Storage file operations esb;messaging;firebase;fcm;firestore;storage;gcs;redb README.md