Bundle: redb-route / demo/redb.Route.Demo (demo.redb.Route.Demo.txt), 23 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/demo/redb.Route.Demo/DemoItemProps.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/demo/redb.Route.Demo/DemoItemProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Demo; /// /// Simple Props model for CRUD demo via named IRedbService. /// [RedbScheme("Demo Item")] public class DemoItemProps { public string Title { get; set; } = ""; public string? Description { get; set; } public int Priority { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } Path: redb-route/demo/redb.Route.Demo/DemoLifecycle.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/demo/redb.Route.Demo/DemoLifecycle.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Demo; // ═══════════════════════════════════════════════════════════════════════════════ // ProducerTemplateStarter — starts the shared ProducerTemplate after context start // ═══════════════════════════════════════════════════════════════════════════════ /// /// Starts the shared once the context is up so the /// LLM agent engine can dispatch tool routes through it. Without this, the first /// tool call from /api/llm/shell would throw "ProducerTemplate is not started". /// internal sealed class ProducerTemplateStarter : IRouteLifecycleListener { private readonly ProducerTemplate _template; private readonly ILogger? _log; public ProducerTemplateStarter(ProducerTemplate template, ILogger? log) { _template = template; _log = log; } public Task OnContextStarting(IRouteContext context, CancellationToken ct) => Task.CompletedTask; public Task OnContextStarted(IRouteContext context, CancellationToken ct) { if (!_template.IsStarted) { _template.Start(); _log?.LogInformation("[LLM] ProducerTemplate started (tool dispatch ready)"); } return Task.CompletedTask; } public Task OnContextStopping(IRouteContext context, CancellationToken ct) { if (_template.IsStarted) _template.Stop(); return Task.CompletedTask; } public Task OnContextStopped(IRouteContext context, CancellationToken ct) => Task.CompletedTask; public Task OnRouteStarted(string routeId, CancellationToken ct) => Task.CompletedTask; public Task OnRouteStopped(string routeId, CancellationToken ct) => Task.CompletedTask; public Task OnRouteSuspending(string routeId, CancellationToken ct) => Task.CompletedTask; public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) => Task.CompletedTask; public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) => Task.CompletedTask; } // ═══════════════════════════════════════════════════════════════════════════════ // DemoLifecycleListener — logs all context & route lifecycle events // ═══════════════════════════════════════════════════════════════════════════════ /// /// Logs every lifecycle event to demonstrate . /// Register via context.AddLifecycleListener(...) in InitRoute. /// public class DemoLifecycleListener : IRouteLifecycleListener { private readonly ILogger? _log; public DemoLifecycleListener(ILogger? logger) => _log = logger; // ── Context-level events ── public Task OnContextStarting(IRouteContext context, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ▶ Context STARTING"); return Task.CompletedTask; } public Task OnContextStarted(IRouteContext context, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ✔ Context STARTED"); return Task.CompletedTask; } public Task OnContextStopping(IRouteContext context, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ■ Context STOPPING"); return Task.CompletedTask; } public Task OnContextStopped(IRouteContext context, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ✖ Context STOPPED"); return Task.CompletedTask; } // ── Route-level events ── public Task OnRouteStarted(string routeId, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ▶ Route '{RouteId}' STARTED", routeId); return Task.CompletedTask; } public Task OnRouteStopped(string routeId, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ■ Route '{RouteId}' STOPPED", routeId); return Task.CompletedTask; } public Task OnRouteSuspending(string routeId, CancellationToken ct) { _log?.LogInformation("[LIFECYCLE] ⏸ Route '{RouteId}' SUSPENDING", routeId); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { _log?.LogWarning(ex, "[LIFECYCLE] ✖ Route '{RouteId}' ERRORED", routeId); return Task.CompletedTask; } public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { _log?.LogWarning("[LIFECYCLE] ⏱ Route '{RouteId}' exchange {ExchangeId} timed out after {Elapsed}", routeId, exchangeId, elapsed); return Task.CompletedTask; } } // ═══════════════════════════════════════════════════════════════════════════════ // DemoRoutePolicy — logs per-route lifecycle and per-exchange events // ═══════════════════════════════════════════════════════════════════════════════ /// /// Demonstrates by logging every policy hook. /// Attach to a route via .RoutePolicy(new DemoRoutePolicy(logger)). /// public class DemoRoutePolicy : RoutePolicySupport { private readonly ILogger? _log; public DemoRoutePolicy(ILogger? logger) => _log = logger; public override Task OnInit(IRouteContext context, CompiledRoute route, CancellationToken ct) { base.OnInit(context, route, ct); _log?.LogInformation("[POLICY] Route '{RouteId}' — OnInit (compiled, not yet started)", RouteId); return Task.CompletedTask; } public override Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) { _log?.LogInformation("[POLICY] Route '{RouteId}' — OnStart", RouteId); return Task.CompletedTask; } public override Task OnStop(IRouteContext context, CompiledRoute route, CancellationToken ct) { _log?.LogInformation("[POLICY] Route '{RouteId}' — OnStop", RouteId); return Task.CompletedTask; } public override Task OnRemove(IRouteContext context, CompiledRoute route, CancellationToken ct) { _log?.LogInformation("[POLICY] Route '{RouteId}' — OnRemove", RouteId); return Task.CompletedTask; } public override Task OnSuspend(IRouteContext context, CompiledRoute route, CancellationToken ct) { _log?.LogInformation("[POLICY] Route '{RouteId}' — OnSuspend", RouteId); return Task.CompletedTask; } public override Task OnResume(IRouteContext context, CompiledRoute route, CancellationToken ct) { _log?.LogInformation("[POLICY] Route '{RouteId}' — OnResume", RouteId); return Task.CompletedTask; } public override Task OnExchangeBegin(IRouteContext context, IExchange exchange, CancellationToken ct) { _log?.LogDebug("[POLICY] Route '{RouteId}' — ExchangeBegin {ExchangeId}", RouteId, exchange.ExchangeId); return Task.CompletedTask; } public override Task OnExchangeDone(IRouteContext context, IExchange exchange, CancellationToken ct) { _log?.LogDebug("[POLICY] Route '{RouteId}' — ExchangeDone {ExchangeId} (failed={Failed})", RouteId, exchange.ExchangeId, exchange.Exception != null); return Task.CompletedTask; } } Path: redb-route/demo/redb.Route.Demo/EnvLoader.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/demo/redb.Route.Demo/EnvLoader.cs ---- using System.Runtime.CompilerServices; namespace redb.Route.Demo; /// /// Loads redb.Tsak/publish/keys/.env.local into /// on first assembly use, so the LLM demo routes find their API keys without /// the operator having to export them by hand. Existing environment variables /// are never overwritten — production containers that set keys via /// environment: in compose continue to win. /// /// Missing file = silent no-op (CI / fresh checkout). The lookup climbs from /// AppContext.BaseDirectory upwards looking for a sibling /// redb.Tsak/publish/keys/.env.local, matching the layout this repo uses. /// /// internal static class EnvLoader { [ModuleInitializer] internal static void Load() { var dir = AppContext.BaseDirectory; while (!string.IsNullOrEmpty(dir)) { var candidate = Path.Combine(dir, "redb.Tsak", "publish", "keys", ".env.local"); if (System.IO.File.Exists(candidate)) { Apply(candidate); return; } dir = Directory.GetParent(dir)?.FullName; } } private static void Apply(string path) { foreach (var rawLine in System.IO.File.ReadAllLines(path)) { var line = rawLine.Trim(); if (line.Length == 0 || line.StartsWith('#')) continue; var eq = line.IndexOf('='); if (eq <= 0) continue; var key = line[..eq].Trim(); var value = line[(eq + 1)..].Trim().Trim('"'); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(key))) continue; Environment.SetEnvironmentVariable(key, value); } } } Path: redb-route/demo/redb.Route.Demo/InitRoute.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/demo/redb.Route.Demo/InitRoute.cs ---- using System.Data.Common; using Microsoft.Extensions.DependencyInjection; using Npgsql; using redb.Route.Abstractions; using redb.Route.Amqp; using redb.Route.Core; using redb.Route.Exec; using redb.Route.File; using redb.Route.Grpc; using redb.Route.Http; using redb.Route.IbmMq; using redb.Route.Kafka; using redb.Route.Llm; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb; using redb.Route.Mail; using redb.Route.MqttNet; using redb.Route.Quartz; using redb.Route.RabbitMQ; using redb.Route.Redis; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Tcp; using redb.Route.WebSocket; using Microsoft.Extensions.Logging; using redb.Route.Demo.Routes; namespace redb.Route.Demo; /// /// Tsak module entry point. Discovered automatically via namespace + class name "InitRoute". /// Full DSL showcase: 18 transports × 50+ EIP patterns × observability × transactions. /// public static class InitRoute { private const string PgConn = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb"; public static IRouteContext main(IRouteContext context) { var logger = context.GetService(); // ── Log module config loaded via Tsak 5-layer pipeline ── LogContextConfig(context); // ── Register transport components ── var httpComponent = new HttpComponent { ServerManager = new SharedHttpServerManager() }; context.AddComponent(httpComponent); context.AddComponent(new RabbitMQComponent()); context.AddComponent(new AmqpComponent()); context.AddComponent(new GrpcComponent()); context.AddComponent(new IbmMqComponent()); context.AddComponent(new KafkaComponent()); context.AddComponent(new SqlComponent()); context.AddComponent(new FileComponent()); context.AddComponent(new RedisComponent()); context.AddComponent(new TcpComponent()); context.AddComponent(new WsComponent()); context.AddComponent(new MqttComponent()); context.AddComponent(new QuartzTimerComponent()); context.AddComponent(new CronComponent()); context.AddComponent(new SmtpComponent()); context.AddComponent(new LlmComponent()); context.AddComponent(new ExecComponent()); // ── LLM wiring (stub provider — no API key required) ── // Factory in registry → resolved by `llm://demo-stub` and `.Llm("demo-stub")`. context.AddToRegistry("demo-stub", new LlmConnectionFactory { Name = "demo-stub", Provider = "stub", ModelId = "stub-model", Temperature = 0.0 }); // ── Live Claude factory for the HTTP LLM showcase ── // Skipped silently when REDB_LLM_ANT_API03_KEY is not set so the rest // of the demo module still loads cleanly in environments without keys. var anthropicKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"); if (!string.IsNullOrWhiteSpace(anthropicKey)) { context.AddToRegistry("haiku", new LlmConnectionFactory { Name = "haiku", Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = anthropicKey, Temperature = 0.0, MaxTokens = 512 }); logger?.LogInformation("[LLM] 'haiku' factory wired (anthropic / claude-haiku-4-5)"); } else { logger?.LogWarning("[LLM] REDB_LLM_ANT_API03_KEY not set — /api/llm/* endpoints will 500. " + "Set it in redb.Tsak/publish/keys/.env.local or as an env var."); } // Tool descriptor registry — populated by `.AsLlmTool(...)` at route build time. context.AddService(typeof(IToolDescriptorRegistry), new ToolDescriptorRegistry()); // Producer template + agent engine — needed for tool-using LLM routes. // The template is started by ProducerTemplateStarter once the context is up. var producerTemplate = new ProducerTemplate(context); context.AddService(typeof(IProducerTemplate), producerTemplate); // Conversation store — Tsak registers an IServiceScopeFactory per named redb // instance under "redb-factory:{name}" (see NamedRedbRoutes for usage). // RedbConversationStore now takes IRouteContext directly: per-call it asks // context.GetRedbService("pg-test", exchange) which: // 1) reuses the per-exchange scope cached in exchange.Properties on repeat calls, // 2) creates a fresh scope from "redb-factory:pg-test" and caches it on first call, // 3) falls back to a singleton via "redb:pg-test" when no exchange is in scope. // Result: no manual scope-factory plumbing here, scope is auto-disposed with the exchange. // The string "pg-test" must match the named instance configured in // redb.Route.Demo.config.json under the Redb section. // Choices are registered, not passed: the engine is then built from the context, so a seam the // package adds (claims, cache, cost) reaches this host without an edit here. context.AddService(typeof(IConversationStore), new RedbConversationStore(context, defaultRedbName: "pg-test")); //context.AddService(typeof(IConversationStore), new InMemoryConversationStore()); context.AddService(typeof(IAgentEngine), AgentEngine.FromContext(context)); context.AddLifecycleListener(new ProducerTemplateStarter(producerTemplate, logger)); // ── Register Npgsql ADO.NET provider for SQL component ── DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance); // ── Register named data source in context registry ── context.AddToRegistry("pg-demo", (ISqlConnectionFactory)new SqlConnectionFactory( new SqlConnectionOptions { ConnectionString = PgConn, ProviderName = "Npgsql" })); // ── Broker connection factories ── // Credentials live in the factory (referenced by name from the endpoint URI as // connectionFactory=), never inline in the URI. Dev defaults target the local // demo containers; a real deployment would source them from config or a secret store. context.AddToRegistry("rabbit-demo", new RabbitMQConnectionFactory { Host = "localhost", Port = 5672, Username = "admin", Password = "admin" }); context.AddToRegistry("amqp-demo", new AmqpConnectionFactory { Host = "localhost", Port = 5673, User = "admin", Password = "admin" }); context.AddToRegistry("wmq-demo", new IbmMqConnectionFactory { Host = "localhost", Port = 1414, Channel = "DEV.APP.SVRCONN", QueueManager = "QM1", User = "app", Password = "admin" }); // ── Register lifecycle listener (logs context & route events) ── context.AddLifecycleListener(new DemoLifecycleListener(logger)); // ── Create demo_log table (idempotent) ── CreateTable(); // ── Register all demo routes ── ((RouteContext)context) .AddRoutes(new MainPipelineRoutes(logger)) .AddRoutes(new ErrorHandlingRoutes(logger)) .AddRoutes(new EipRoutes(logger)) .AddRoutes(new TransportRoutes(logger)) .AddRoutes(new DataObservabilityRoutes(logger)) .AddRoutes(new TransactionRoutes(logger)) .AddRoutes(new LifecycleRoutes(logger)) .AddRoutes(new NamedRedbRoutes(logger)) .AddRoutes(new ScopeDiagRoutes(logger)) .AddRoutes(new DeepDslShowcaseRoutes(logger)) .AddRoutes(new LlmDemoRoutes(logger)) .AddRoutes(new LlmHttpRoutes(logger)) .AddRoutes(new EchoRoutes(logger)); return context; } private static void CreateTable() { using var conn = new NpgsqlConnection(PgConn); conn.Open(); using var cmd = conn.CreateCommand(); cmd.CommandText = """ CREATE TABLE IF NOT EXISTS demo_log ( id SERIAL PRIMARY KEY, exchange_id TEXT NOT NULL, message TEXT, status TEXT, created_at TIMESTAMP DEFAULT NOW() ) """; cmd.ExecuteNonQuery(); } /// /// Reads and logs context properties injected by Tsak config pipeline /// (from redb.Route.Demo.config.json → Layer 4). /// private static void LogContextConfig(IRouteContext context) { var logger = context.GetService(); if (logger == null) return; logger.LogInformation("═══ redb.Route.Demo — Module Configuration ═══"); // Nested object: DemoSettings var demoSettings = context.GetProperty>("DemoSettings"); if (demoSettings != null) { logger.LogInformation("[CONFIG] DemoSettings:"); foreach (var (key, value) in demoSettings) logger.LogInformation(" {Key} = {Value}", key, value); } else { logger.LogWarning("[CONFIG] DemoSettings: NOT FOUND (config file not loaded?)"); } // Nested object: RabbitMQ var rabbitConfig = context.GetProperty>("RabbitMQ"); if (rabbitConfig != null) { logger.LogInformation("[CONFIG] RabbitMQ:"); foreach (var (key, value) in rabbitConfig) logger.LogInformation(" {Key} = {Value}", key, value); } // Nested object: Redis var redisConfig = context.GetProperty>("Redis"); if (redisConfig != null) { logger.LogInformation("[CONFIG] Redis:"); foreach (var (key, value) in redisConfig) logger.LogInformation(" {Key} = {Value}", key, value); } // Nested object: FeatureFlags var features = context.GetProperty>("FeatureFlags"); if (features != null) { logger.LogInformation("[CONFIG] FeatureFlags:"); foreach (var (key, value) in features) logger.LogInformation(" {Key} = {Value}", key, value); } // Simple properties (from appsettings layers) var autoStart = context.GetProperty("AutoStart"); if (autoStart != null) logger.LogInformation("[CONFIG] AutoStart = {AutoStart}", autoStart); logger.LogInformation("═══ End of Module Configuration ═══"); } } Path: redb-route/demo/redb.Route.Demo/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/demo/redb.Route.Demo/README.md ---- # redb.Route.Demo Full-featured showcase of the redb.Route ESB framework — **18 of its 27 transports, the EIP patterns listed below, observability, transactions, and lifecycle events** wired into a single runnable module of 39 routes. This project is designed to be **deployed into [redb.Tsak](https://github.com/redbase-app/redb-tsak)** (the redb.Route runtime container), but can also be studied as the definitive reference implementation for every feature of the framework. --- ## What This Demonstrates | Section | Routes | What you learn | |---------|--------|----------------| | **1. Main Pipeline** | 8 | HTTP entry → throttle → dedup → 4 broker RPC calls → SQL → WireTap fan-out → response | | **2. Error Handling** | 4 | `DoTry/DoCatch/DoFinally`, `CircuitBreaker`, `Retry` with backoff, `DeadLetterChannel` | | **3. EIP Patterns** | 9 | Aggregator, Multicast, RecipientList, DynamicRouter, Loop, Resequencer, Enrich, IdempotentConsumer, Throttle | | **4. Transport Showcase** | 8 | Timer, Cron, SEDA, Redis Pub/Sub, TCP echo, WebSocket, MQTT, IBM MQ topic | | **5. Data & Observability** | 4 | JSON Schema validation, Marshal/Unmarshal, `Traced`+`Metered`, expression showcase | | **6. Transactions** | 2 | `Transacted()` scope, `BeginTransaction`/`CommitTransaction`/`RollbackTransaction` | | **7. Policies & Lifecycle** | 2 | Route policies, cluster-ready checks | | **8. Named Redb Instances** | 1 | CRUD via named `IRedbService` from inside a route | | **9. Scope Diagnostics** | 1 | Exchange introspection, route ID, property/header dump | **Total: 39 routes across 9 sections.** --- ## Transports Used | Transport | Role in demo | |-----------|-------------| | HTTP (`http:`) | Entry point — `POST /api/demo` triggers the main pipeline | | RabbitMQ (`rabbitmq:`) | RPC round-trip — worker stamps body and replies | | AMQP 1.0 (`amqp:`) | RPC round-trip — Artemis broker | | gRPC (`grpc:`) | RPC round-trip — client/server in the same process | | IBM MQ (`wmq:`) | RPC round-trip + topic pub/sub | | Kafka (`kafka:`) | WireTap async audit — fire-and-forget | | SQL / PostgreSQL (`sql:`) | INSERT + SELECT inside a transaction | | File (`file:`) | WireTap snapshot — writes `{traceId}.json` to `output/` | | Redis (`redis:`) | Pub/Sub channel fan-out | | TCP (`tcp:`) | Echo server — receives message, stamps, returns | | WebSocket (`websocket:`) | Push server — broadcasts to connected clients | | MQTT (`mqtt:`) | Publish to `demo/telemetry`, subscribe consumer | | SEDA (`seda:`) | In-process async queue for background processing | | DirectVM (`direct-vm:`) | Cross-context synchronous enrichment call | | Timer (`timer:`) | Heartbeat — fires every 10 seconds | | Cron (`cron:`) | Scheduled job — runs at configured expression | | SMTP / SFTP | Referenced in `InitRoute` component registration | | redb.Core (`IRedbService`) | Named-instance CRUD — `DemoItemProps` saved as redb props | --- ## Project Structure ``` redb.Route.Demo/ ├── InitRoute.cs ← Tsak module entry point (discovered by convention) ├── Routes/ ← Routes split by concern, one RouteBuilder per file │ ├── DemoEndpoints.cs ← Central registry of every endpoint URI + shared resources │ ├── DemoHelpers.cs ← Shared helpers for the route builders │ ├── MainPipelineRoutes.cs ← HTTP entry → throttle → dedup → broker RPC → SQL → WireTap │ ├── ErrorHandlingRoutes.cs ← DoTry/DoCatch, CircuitBreaker, Transacted Retry/DeadLetter │ ├── EipRoutes.cs ← Aggregator, Multicast, RecipientList, Loop, Resequencer, … │ ├── TransportRoutes.cs ← Timer, Cron, SEDA, Redis, TCP, WebSocket, MQTT, IBM MQ │ ├── DataObservabilityRoutes.cs ← JSON Schema validation, Marshal, Traced+Metered │ ├── TransactionRoutes.cs ← Transacted() scope │ ├── LifecycleRoutes.cs ← Route policies, cluster-ready checks │ ├── NamedRedbRoutes.cs ← CRUD via named IRedbService from inside a route │ ├── ScopeDiagRoutes.cs ← Exchange introspection / property dump │ ├── DeepDslShowcaseRoutes.cs ← Deep fluent-DSL showcase │ ├── LlmDemoRoutes.cs / LlmHttpRoutes.cs ← LLM connector (stub + live Claude) │ └── EchoRoutes.cs ← Minimal echo routes ├── DemoLifecycle.cs ← IRouteLifecycleListener implementation ├── DemoItemProps.cs ← redb.Core props model ([RedbScheme]) ├── EnvLoader.cs ← Loads .env.local for local runs ├── manifest.json ← Tsak module manifest ├── redb.Route.Demo.config.json ← Module config (loaded by Tsak 5-layer pipeline) └── output/ ← File WireTap writes JSON snapshots here ``` ### Key files explained **`InitRoute.cs`** — the Tsak module entry point. Discovered automatically because the class is named `InitRoute` and contains a static method `main(IRouteContext)`. Registers the transport components, the PostgreSQL data source, the broker connection factories, the lifecycle listener, and every route builder in `Routes/`. **`Routes/*.cs`** — the routes, split by concern, one `RouteBuilder` subclass per file (registered in `InitRoute`). Each overrides `Configure()` and defines its routes with the fluent DSL. **`DemoEndpoints.cs`** is the central registry of every endpoint URI and shared resource — retune the demo for another environment by editing that one file; broker credentials live in the connection factories registered in `InitRoute`, not in the URIs. **`redb.Route.Demo.config.json`** — loaded via the Tsak 5-layer config pipeline. Contains connection strings for Postgres, RabbitMQ, Redis; feature flags; named redb provider configs for both PostgreSQL and MSSQL. --- ## Main Pipeline — How a Message Flows ``` POST /api/demo │ ├─ Throttle (10 req/s) ├─ SetHeader traceId + startedAt ├─ ValidateJsonSchema ├─ IdempotentConsumer (dedup by traceId) │ └─► direct://pipeline │ ├─ Filter (non-empty body) ├─ SetProperty pipelineStartMs ├─ Choice (mode header) → nested Choice (priority) │ ├─ Traced("broker-roundtrips") │ ├─► rabbitmq RPC → stamp.rabbit │ ├─► amqp RPC → stamp.amqp │ ├─► grpc RPC → stamp.grpc │ └─► wmq RPC → stamp.wmq │ ├─► direct-vm://enricher → stamp.vm │ ├─ Metered("sql-operations") │ ├─ BeginTransaction │ ├─► SQL INSERT demo_log │ ├─► SQL SELECT last 5 rows → Split → Log each row │ └─ CommitTransaction │ ├─ WireTap → kafka://demo-audit ├─ WireTap → file://output/{traceId}.json ├─ WireTap → vm://audit-log ├─ WireTap → direct://demo-redis-pub ├─ WireTap → direct://demo-mqtt-pub ├─ WireTap → direct://demo-wmq-pub └─ WireTap → direct://demo-seda-send │ └─ SetBody (JSON response with all stamps + elapsed) ``` --- ## Running the Demo ### Prerequisites The demo expects these services on `localhost`. Start them with Docker: ```bash # PostgreSQL docker run -d --name pg -e POSTGRES_PASSWORD=1 -p 5432:5432 postgres:16 # RabbitMQ docker run -d --name rabbit -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin \ -p 5672:5672 -p 15672:15672 rabbitmq:3-management # Apache Artemis (AMQP 1.0) docker run -d --name artemis -e AMQ_USER=admin -e AMQ_PASSWORD=admin \ -p 5673:5672 -p 8161:8161 apache/activemq-artemis # Kafka docker run -d --name kafka -e KAFKA_PROCESS_ROLES=broker,controller \ -e KAFKA_NODE_ID=1 -e KAFKA_LISTENERS=PLAINTEXT://0.0.0.0:29092,CONTROLLER://0.0.0.0:29093 \ -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:29092 \ -e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:29093 \ -p 29092:29092 apache/kafka:3.7.0 # Redis docker run -d --name redis -p 6379:6379 redis:7 # MQTT (Eclipse Mosquitto) docker run -d --name mosquitto -p 11883:1883 eclipse-mosquitto \ mosquitto -c /mosquitto-no-auth.conf # IBM MQ (optional — comment out wmq routes if not available) docker run -d --name ibmmq -e LICENSE=accept -e MQ_QMGR_NAME=QM1 \ -e MQ_APP_PASSWORD=admin -p 1414:1414 -p 9443:9443 ibmcom/mq ``` ### Option A — run standalone (without Tsak) ```bash # From the project root dotnet run --project redb.Route.Demo ``` The HTTP entry point starts on `http://localhost:5088`. Send a test message: ```bash # Windows (cmd / PowerShell) curl -X POST http://localhost:5088/api/demo ` -H "Content-Type: application/json" ` -H "mode: full" ` -H "priority: high" ` -d "{\"message\":\"hello\"}" # Linux / macOS curl -X POST http://localhost:5088/api/demo \ -H "Content-Type: application/json" \ -H "mode: full" \ -H "priority: high" \ -d '{"message":"hello"}' ``` ### Option B — deploy into redb.Tsak 1. Build the module: ```bash dotnet publish redb.Route.Demo -c Release -o publish/ ``` 2. Copy to Tsak libs directory: ```bash cp -r publish/ $TSAK_HOME/libs/redb.Route.Demo/ ``` 3. Use the Tsak CLI or REST API to start the context: ```bash tsak context start route.demo # or curl -X POST http://localhost:5000/api/contexts/route.demo/start \ -H "X-Api-Key: $TSAK_API_KEY" ``` --- ## Expected Response A successful `POST /api/demo` returns a JSON object with timestamps from every transport in the pipeline: ```json { "traceId": "a1b2c3d4e5f6", "mode": "full", "priority": "high", "fastTrack": "true", "stamps": { "rabbit": "ok:14:32:01.123", "amqp": "ok:14:32:01.234", "grpc": "ok:14:32:01.345", "wmq": "ok:14:32:01.456", "vm": "enriched:14:32:01.567" }, "elapsedMs": 312 } ``` --- ## Configuration Edit `redb.Route.Demo.config.json` to adjust connection strings and feature flags: ```json { "DemoSettings": { "PostgresConnection": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb" }, "RabbitMQ": { "Host": "localhost", "Port": 5672, "Username": "admin", "Password": "admin" }, "Redis": { "Host": "localhost", "Port": 6379 }, "FeatureFlags": { "EnableSqlRoutes": true, "EnableMqttRoutes": true } } ``` When deployed via Tsak, secrets should be injected via environment variables rather than written into `context.json` or an endpoint URI — the worker maps every config key to an env var by replacing `:` with `__`, so nothing sensitive has to live in a file that ships with the module. --- ## Part of [redb.Route](../../README.md) — ESB & EIP Framework for .NET [redb.Tsak](https://github.com/redbase-app/redb-tsak) — Runtime container for redb.Route modules Path: redb-route/demo/redb.Route.Demo/Routes/DataObservabilityRoutes.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/demo/redb.Route.Demo/Routes/DataObservabilityRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; using redb.Route.Serialization; using static redb.Route.Demo.Routes.DemoEndpoints; using static redb.Route.Demo.Routes.DemoHelpers; namespace redb.Route.Demo.Routes; /// /// Data & observability showcase: Validate, Marshal/ConvertBody, Traced/Metered, /// Expression DSL (JPath/XPath/Header/Body/Property/Constant/Expr/Exchange), /// and the Predicate DSL (comparison, string, null, logic, choice, jpath). /// internal sealed class DataObservabilityRoutes : RouteBuilder { private readonly ILogger? _log; public DataObservabilityRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureValidationRoute(); ConfigureMarshalRoute(); ConfigureObservabilityRoute(); ConfigureExpressionShowcase(); ConfigurePredicateShowcase(); } /// /// Validation — JSON Schema + predicate checks. /// Invalid messages get rejected before entering the pipeline. /// private void ConfigureValidationRoute() { From("direct://demo-validation") .RouteId("demo-validation") .Log("[VALID] ▶ Validating message...") // JSON Schema (throws on failure) .ValidateJsonSchema(MessageSchema) .Log("[VALID] ✓ JSON schema OK") // Predicate (custom business rule) .Validate( e => e.In.Body?.ToString()?.Length < 10000, errorMessage: "Body too large (max 10KB)") .Log("[VALID] ✓ Size check OK") .Log("[VALID] ◀ All validations passed"); } /// /// Marshal / ConvertBody — serialization pipeline. /// Object → JSON bytes → string. /// private void ConfigureMarshalRoute() { From("direct://demo-marshal") .RouteId("demo-marshal") .Log("[MARSHAL] ▶ Starting serialization demo...") // Create a typed object .SetBody(e => new { name = "demo", value = 42, ts = DateTime.UtcNow }) .Log("[MARSHAL] Created anonymous object") // Marshal → JSON bytes .Marshal(typeof(JsonMessageSerializer)) .Log("[MARSHAL] After Marshal (JSON): contentType=${contentType}") // ConvertBody → string .ConvertBody() .Log("[MARSHAL] After ConvertBody: ${body}") .Log("[MARSHAL] ◀ Serialization round-trip complete"); } /// /// Traced + Metered blocks — observability without code changes. /// Traced creates spans, Metered records counters/histograms. /// private void ConfigureObservabilityRoute() { From("direct://demo-observability") .RouteId("demo-observability") .Log("[OBS] ▶ Starting observable pipeline...") // Traced block — all steps inside get one span .Traced("demo-traced-block") .Log("[OBS] traced: step 1 — validate") .Validate(e => e.In.Body != null, "Body required") .Log("[OBS] traced: step 2 — transform") .Process(e => e.In.Body = e.In.Body?.ToString()?.ToUpperInvariant()) .EndTraced() // Metered block — records execution time + counter .Metered("demo-metered-block") .Log("[OBS] metered: step 1 — enrich") .SetHeader("obs.enriched", "true") .Log("[OBS] metered: step 2 — delay 10ms") .Delay(TimeSpan.FromMilliseconds(10)) .EndMetered() // Inline traced — single step with action .Traced("final-stamp", e => e.In.Headers["obs.traced"] = "done") // Inline metered — single step with action .Metered("final-count", e => e.In.Headers["obs.metered"] = "done") .Log("[OBS] ◀ Observable pipeline complete"); } /// /// Expression showcase — all the ways to read/write exchange data. /// JPath, XPath, Expr(), Body(), Header(), Property(), Constant(), Exchange(). /// private void ConfigureExpressionShowcase() { From("direct://demo-expressions") .RouteId("demo-expressions") // ── JSON body for JPath ── .SetBody(e => "{\"user\":{\"name\":\"Alice\",\"age\":30},\"items\":[\"a\",\"b\",\"c\"]}") .Log("[EXPR] ▶ JSON body: ${body}") // JPath — extract from JSON body .SetHeader("user.name", JPath("$.user.name")) .SetHeader("user.age", JPath("$.user.age")) .Log("[EXPR] JPath: name=${header.user.name}, age=${header.user.age}") // Property + Constant expressions .SetProperty("origin", Constant("demo-route")) .SetProperty("computed", Exchange(e => $"from-{GetHeader(e, "user.name")}")) .Log("[EXPR] Property: origin=${property.origin}, computed=${property.computed}") // Expr() — template expression as IExpression .SetHeader("greeting", Expr("Hello ${header.user.name}, age ${header.user.age}!")) .Log("[EXPR] Expr: ${header.greeting}") // Header() expression used in Filter predicate. // Closed immediately with EndFilter() so the XML/XPath showcase below // always runs regardless of the user.name value. .Filter(Header("user.name").contains("Alice")) .Log("[EXPR] ✓ User is Alice (Filter + contains)") .EndFilter() // Body() expression snapshot .SetProperty("bodySnapshot", Body()) .Log("[EXPR] Body snapshot saved to property") // ── XML body for XPath ── .SetBody(e => "WidgetGadget") .Log("[EXPR] XML body: ${body}") // XPath — extract from XML body .SetHeader("firstItem", XPath("/order/item[1]")) .Log("[EXPR] XPath: first item = ${header.firstItem}") // RemoveHeader / RemoveProperty cleanup .RemoveHeader("tempData") .RemoveProperty("bodySnapshot") .Log("[EXPR] ◀ Expression showcase complete"); } /// /// Predicate showcase — the entire Expression predicate DSL. /// Each predicate is a fluent method on an Expression: Header("x").isEqualTo("y"). /// Reads like plain English — that's the whole point of the DSL. /// private void ConfigurePredicateShowcase() { // ── Route 1: Comparison predicates ────────────────────────────── // // Each Filter is closed with EndFilter() so the next Filter is a // sibling, not a nested child. Reads top-to-bottom as a flat list // of independent predicate demonstrations. // From("direct://demo-predicates-compare") .RouteId("demo-predicates-compare") .Log("[PRED] ▶ Comparison predicates showcase") // set up test data .SetHeader("score", 85) .SetHeader("grade", "B+") .SetHeader("level", "senior") // isEqualTo — exact match .Filter(Header("grade").isEqualTo("B+")) .Log("[PRED] ✓ Header('grade').isEqualTo('B+') → passed") .EndFilter() // isNotEqualTo — not this value .Filter(Header("level").isNotEqualTo("junior")) .Log("[PRED] ✓ Header('level').isNotEqualTo('junior') → passed") .EndFilter() // isGreaterThan — strictly greater .Filter(Header("score").isGreaterThan(50)) .Log("[PRED] ✓ Header('score').isGreaterThan(50) → passed (score=85)") .EndFilter() // isLessThan — strictly less .Filter(Header("score").isLessThan(100)) .Log("[PRED] ✓ Header('score').isLessThan(100) → passed (score=85)") .EndFilter() // isGreaterThanOrEqualTo — inclusive lower bound .Filter(Header("score").isGreaterThanOrEqualTo(85)) .Log("[PRED] ✓ Header('score').isGreaterThanOrEqualTo(85) → passed") .EndFilter() // isLessThanOrEqualTo — inclusive upper bound .Filter(Header("score").isLessThanOrEqualTo(100)) .Log("[PRED] ✓ Header('score').isLessThanOrEqualTo(100) → passed") .EndFilter() // isBetween — range check (inclusive) .Filter(Header("score").isBetween(70, 90)) .Log("[PRED] ✓ Header('score').isBetween(70, 90) → passed (score=85)") .EndFilter() .Log("[PRED] ◀ Comparison predicates done"); // ── Route 2: String predicates ────────────────────────────────── From("direct://demo-predicates-string") .RouteId("demo-predicates-string") .Log("[PRED] ▶ String predicates showcase") .SetHeader("email", "alice@example.com") .SetHeader("filename", "report-2024.pdf") .SetHeader("tag", "urgent-task-x42") .Filter(Header("email").contains("@example")) .Log("[PRED] ✓ Header('email').contains('@example') → passed") .EndFilter() .Filter(Header("email").startsWith("alice")) .Log("[PRED] ✓ Header('email').startsWith('alice') → passed") .EndFilter() .Filter(Header("filename").endsWith(".pdf")) .Log("[PRED] ✓ Header('filename').endsWith('.pdf') → passed") .EndFilter() .Filter(Header("tag").regex(@"^urgent-.*-x\d+$")) .Log("[PRED] ✓ Header('tag').regex('^urgent-.*-x\\d+$') → passed") .EndFilter() .Filter(Header("filename").In("report-2024.pdf", "summary.pdf", "data.csv")) .Log("[PRED] ✓ Header('filename').In('report-2024.pdf', 'summary.pdf', 'data.csv') → passed") .EndFilter() .Log("[PRED] ◀ String predicates done"); // ── Route 3: Null checks ──────────────────────────────────────── From("direct://demo-predicates-null") .RouteId("demo-predicates-null") .Log("[PRED] ▶ Null-check predicates showcase") .SetHeader("existing", "value") .RemoveHeader("missing") .Filter(Header("existing").isNotNull()) .Log("[PRED] ✓ Header('existing').isNotNull() → passed") .EndFilter() .Filter(Header("missing").isNull()) .Log("[PRED] ✓ Header('missing').isNull() → passed") .EndFilter() .Log("[PRED] ◀ Null-check predicates done"); // ── Route 4: Logical composition — and / or / not ─────────────── // // and() / or() / not() are methods on Expression, not IPredicate. // Left side = Expression (evaluates to bool), right side = IPredicate. // From("direct://demo-predicates-logic") .RouteId("demo-predicates-logic") .Log("[PRED] ▶ Logical composition predicates showcase") .SetHeader("role", "admin") .SetHeader("active", true) .SetHeader("disabled", false) .SetHeader("trust", 9) // and — Expression is truthy AND predicate matches .Filter(Header("active").and(Header("role").isEqualTo("admin"))) .Log("[PRED] ✓ Header('active').and(Header('role').isEqualTo('admin')) → passed") .EndFilter() // or — Expression is truthy OR predicate matches .Filter(Header("disabled").or(Header("role").isEqualTo("admin"))) .Log("[PRED] ✓ Header('disabled').or(Header('role').isEqualTo('admin')) → passed") .EndFilter() // not — negates Expression .Filter(Header("disabled").not()) .Log("[PRED] ✓ Header('disabled').not() → passed (disabled=false)") .EndFilter() // complex: active AND trust >= 5 .Filter(Header("active").and(Header("trust").isGreaterThanOrEqualTo(5))) .Log("[PRED] ✓ Header('active').and(Header('trust').isGreaterThanOrEqualTo(5)) → passed") .EndFilter() .Log("[PRED] ◀ Logical composition done"); // ── Route 5: String expressions — Filter(string) & When(string) ─ // // A condition string ("${header.x}" or "header.x == 'y'") is compiled into a predicate // while the route is built. This is the purely declarative way: no lambdas, just strings. // From("direct://demo-predicates-string-expr") .RouteId("demo-predicates-string-expr") .Log("[PRED] ▶ String expression predicates (condition strings)") .SetHeader("status", "active") .SetHeader("count", "42") // Filter(string) — string expression evaluated as boolean .Filter("${header.status}") .Log("[PRED] ✓ Filter('$${header.status}') → 'active' is truthy") .EndFilter() // Choice + When(string) — declarative branching (nested-lambda DSL) .Choice(choice => choice .When(new StringExpression("${header.status}"), w => w .SetHeader("pred.branch", "status-truthy")) .Otherwise(o => o .SetHeader("pred.branch", "status-falsy"))) .Log("[PRED] ◀ String expression predicates done"); // ── Route 6: Predicates in a Choice (fluent Expression predicates) ─ From("direct://demo-predicates-choice") .RouteId("demo-predicates-choice") .Log("[PRED] ▶ Choice with Expression predicates") .SetHeader("amount", 750) .Choice(choice => choice // When(IPredicate) — expression-based condition .When(Header("amount").isGreaterThanOrEqualTo(1000).Matches, w => w .SetHeader("pred.tier", "premium")) .When(Header("amount").isBetween(500, 999).Matches, w => w .SetHeader("pred.tier", "standard")) .When(Header("amount").isLessThan(500).Matches, w => w .SetHeader("pred.tier", "basic")) .Otherwise(o => o .SetHeader("pred.tier", "fallback"))) .Log("[PRED] ◀ Choice with predicates done"); // ── Route 7: JPath predicates — conditions on JSON body fields ── From("direct://demo-predicates-jpath") .RouteId("demo-predicates-jpath") .Log("[PRED] ▶ JPath predicate showcase") .SetBody(e => "{\"order\":{\"total\":299.99,\"currency\":\"USD\",\"priority\":\"express\"}}") .Log("[PRED] JSON body: ${body}") .Filter(JPath("$.order.currency").isEqualTo("USD")) .Log("[PRED] ✓ JPath('$.order.currency').isEqualTo('USD') → passed") .EndFilter() .Filter(JPath("$.order.priority").In("express", "overnight")) .Log("[PRED] ✓ JPath('$.order.priority').In('express','overnight') → passed") .EndFilter() .Filter(JPath("$.order.priority").startsWith("exp")) .Log("[PRED] ✓ JPath('$.order.priority').startsWith('exp') → passed") .EndFilter() .Log("[PRED] ◀ JPath predicates done"); } } Path: redb-route/demo/redb.Route.Demo/Routes/DeepDslShowcaseRoutes.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/demo/redb.Route.Demo/Routes/DeepDslShowcaseRoutes.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Demo.Routes; /// /// Showcase of the rich, deeply-nested fluent DSL — the same patterns exercised by /// DeepNestedDslTests in the test suite, but assembled into runnable demo routes. /// /// What this file demonstrates: /// • Choice with sibling When() / Otherwise() reachable through /// IRouteDefinition after a sub-scope was just closed (e.g. .EndSplit().When(...)). /// • Rich logging scope (.Log(LogLevel.X)) with multiple static and dynamic /// messages, captured headers, properties and route id rendering. /// • TryCatch around a step that may throw, with a rich log entry inside the /// catch handler that prints the actual exception type via e.Exception. /// • Mixed scope closers: typed EndChoice() / EndSplit() / EndLog() /// and the universal End() that walks the parent chain to the nearest scope. /// • Cascading EndChoice() from deep inside a Split inside a When — closes /// every intermediate scope in one shot and lands back at the route root. /// /// All comments are intentionally English-only since this file is part of the public demo. /// internal sealed class DeepDslShowcaseRoutes : RouteBuilder { private readonly ILogger? _log; /// Creates the showcase builder. The optional logger is used by inline lambdas. public DeepDslShowcaseRoutes(ILogger? log) => _log = log; /// Hook called by to register every showcase route. protected override void Configure() { ConfigureChoiceWithSplitAndRichLog(); ConfigureTryCatchWithRichLogInCatch(); ConfigureCascadingEndChoiceFromDeepInside(); ConfigureUniversalEndChain(); } // ───────────────────────────────────────────────────────────────────────── // Showcase 1 — Choice → When → RichLog → Split → per-item Process + dynamic // Debug log → EndLog → EndSplit, then a sibling When and an // Otherwise reached via the IRouteDefinition extension methods. // // Triggered manually via Direct: send a body of either: // - IEnumerable → list branch (split + upper-case) // - non-empty string → single string branch // - anything else → fallback branch // ───────────────────────────────────────────────────────────────────────── private void ConfigureChoiceWithSplitAndRichLog() { // A simple in-memory sink so the demo can assert what flowed through. var processed = new ConcurrentBag(); From("direct://demo-choice-richlog") .RouteId("demo-choice-richlog") .SetHeader("step", "start") .Choice() // Branch 1: body is a collection of strings (and not a single string). .When(e => e.In.Body is IEnumerable && e.In.Body is not string) .SetHeader("branch", "list") // Rich log: multiple pieces composed into one structured message. // .Header("...") → captures a header value into the output. // .Property("...") → captures an exchange property. // .ShowRouteId(true) → prefixes the log line with [rId:]. .Log(LogLevel.Information) .Message("opening list branch") .Header("branch") .Property("trace") .ShowRouteId(true) .EndLog() // Split fans the items out one-by-one through the inner pipeline. .Split(e => ((IEnumerable)e.In.Body!).Cast()) .Process(e => { // Per-item synchronous transform — uppercase the body string. var s = (string)e.In.Body!; processed.Add(s.ToUpperInvariant()); }) // ── NOTICE THE DIFFERENCE ── // Both .Log(...) calls below produce equivalent output. The string // template is compiled internally into the same kind of lambda via // ExpressionResolver, but it skips formatting entirely when the log // level is disabled — zero allocation on the hot path. // (A) Lambda — arbitrary C# at runtime. .Log(e => $"[lambda] item={e.In.Body} branch={e.In.Headers["branch"]}") // (B) String template — ${body}, ${header.x}, ${property.y}, // ${exception.type|message}, ${routeId} all resolved by the engine. .Log("[tmpl] item=${body} branch=${header.branch} [${routeId}]") // (C) Rich-Log scope — structured, multi-line, with headers and // properties pulled out as separate fields. .Message() itself // accepts BOTH a string template AND a lambda — both are live. .Log(LogLevel.Information) .Message("[rich-tmpl] item=${body}") // string template .Message(e => $"[rich-lambda] upper={((string)e.In.Body!).ToUpperInvariant()}") // lambda .Header("branch") // pulls header.branch .Property("item-index") // pulls property.item-index (if set) .ShowRouteId(true) .EndLog() .EndSplit() // returns IRouteDefinition, but we are still logically inside the When // Sibling-aware: .Log(...) here lives on the When body, not on the Split. .Log("list branch done [${routeId}]") // Branch 2: a non-empty string. Notice that .When() works after .EndSplit() // even though the static type is IRouteDefinition — the extension method // walks up the parent chain and finds the enclosing ChoiceDefinition. .When(e => e.In.Body is string s && s.Length > 0) .SetHeader("branch", "string") .Process(e => processed.Add($"STR:{e.In.Body}")) // Fallback branch — same .Otherwise() extension trick. .Otherwise() .SetHeader("branch", "fallback") .Process(e => processed.Add("FALLBACK")) .EndChoice() // Final summary log lives on the route root, not on any branch. .Log(LogLevel.Information) .Message("route complete") .ShowRouteId(true) .EndLog(); } // ───────────────────────────────────────────────────────────────────────── // Showcase 2 — TryCatch nested inside a When, with a rich log inside the // catch handler that reports the real exception type. // // Triggered manually via Direct: any string body throws inside the try. // ───────────────────────────────────────────────────────────────────────── private void ConfigureTryCatchWithRichLogInCatch() { From("direct://demo-trycatch-richlog") .RouteId("demo-trycatch-richlog") .Choice() .When(e => e.In.Body is string) .TryCatch() // The protected body — always throws for the demo. .Process(e => throw new InvalidOperationException("boom")) .DoCatch() // ── NOTICE THE DIFFERENCE ── // Both lines log the caught exception. The string-template form is // compiled to a similar lambda internally, but stays readable in DSL. // (A) Lambda — explicit access to exchange.Exception. .Log(e => $"[lambda] caught: {e.Exception?.GetType().Name}") // (B) String template — ${exception.type|message} resolve exchange.Exception. .Log("[tmpl] caught: ${exception.type} — ${exception.message} [${routeId}]") // (C) Rich-Log scope — both .Message(string) and .Message(lambda) // execute; ${exception.*} placeholders work inside the template. .Log(LogLevel.Warning) .Message("[rich-tmpl] ${exception.type}: ${exception.message}") // template .Message(e => $"[rich-lambda] stack-top={e.Exception?.StackTrace?.Split('\n').FirstOrDefault()?.Trim()}") // lambda .ShowRouteId(true) .EndLog() .Process(e => e.In.Headers["caught"] = true) .EndTryCatch() .EndChoice(); } // ───────────────────────────────────────────────────────────────────────── // Showcase 3 — Cascading EndChoice() from deep inside a Split inside a When. // // The new End* extensions on IRouteDefinition walk the parent chain looking // for a scope of the requested type and return its parent. Calling // .EndChoice() from inside a Log inside a Split inside a When skips straight // back to the route root in one shot — there is no per-scope finalization // to run, only parent-chain navigation, so this is semantically identical // to chaining .EndLog().EndSplit().EndChoice() but is more concise when // intermediate scopes do not need any extra steps. // ───────────────────────────────────────────────────────────────────────── private void ConfigureCascadingEndChoiceFromDeepInside() { From("direct://demo-cascade-endchoice") .RouteId("demo-cascade-endchoice") .Choice() .When(e => true) .Split(e => new object?[] { 1, 2, 3 }) .Process(e => { /* per-item work */ }) .Log("item=${body}") // .EndChoice() walks the parent chain past Split and When // and lands at the route root — equivalent to the explicit // .EndSplit().EndChoice() chain. .EndChoice() // Back at the route root. Subsequent steps land here. .SetHeader("post-cascade", "ok") .Log("cascade demo done"); } // ───────────────────────────────────────────────────────────────────────── // Showcase 4 — Universal .End() chain. Every scope-class implements // IRouteScope.End(), and there is also an extension End() on // IRouteDefinition that walks up to the nearest scope. Both // compose to produce a clean closing chain. // ───────────────────────────────────────────────────────────────────────── private void ConfigureUniversalEndChain() { From("direct://demo-universal-end") .RouteId("demo-universal-end") .Choice() .When(e => true) .Split(e => new object?[] { "a", "b" }) .Log(LogLevel.Information) .Message("inside") .End() // closes the RichLog scope, returns the Split body .End() // closes the Split scope, returns the When body .EndChoice() // closes the Choice scope, returns the route root .SetHeader("after-close", "ok"); } } Path: redb-route/demo/redb.Route.Demo/Routes/DemoEndpoints.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/demo/redb.Route.Demo/Routes/DemoEndpoints.cs ---- using redb.Route.Processors; namespace redb.Route.Demo.Routes; /// /// Central registry of every endpoint URI and shared resource used by the demo. /// Keeping all of this in one file makes it trivial to retune the demo for /// another environment without touching route code. /// internal static class DemoEndpoints { // ── RabbitMQ ──────────────────────────────────────────────────────────── // Credentials/host live in the "rabbit-demo" connection factory (see InitRoute), not the URI. public const string RabbitConsumer = "rabbitmq://demo-rpc-queue?connectionFactory=rabbit-demo&declare=true"; // RPC timeout=15s for demo; tune per environment for production. public const string RabbitProducer = "rabbitmq://demo-rpc-queue?connectionFactory=rabbit-demo&replyTo=true&timeout=15"; // ── AMQP 1.0 / Artemis ────────────────────────────────────────────────── public const string AmqpConsumer = "amqp://demo-amqp-queue?connectionFactory=amqp-demo"; public const string AmqpProducer = "amqp://demo-amqp-queue?connectionFactory=amqp-demo&replyTo=true&timeout=15"; // ── IBM MQ (RPC queue + topic pub/sub) ────────────────────────────────── // Host/channel/queueManager/credentials live in the "wmq-demo" connection factory (see InitRoute). // waitInterval=100 — короткий цикл MQGET, чтобы worker не дремал лишние ~1.5 с // после простоя очереди (по умолчанию WaitInterval=5000 мс). public const string WmqRpcConsumer = "wmq:DEV.QUEUE.3?connectionFactory=wmq-demo&waitInterval=100"; public const string WmqRpcProducer = "wmq:DEV.QUEUE.3?connectionFactory=wmq-demo&replyTo=true&timeout=15"; // ── gRPC ──────────────────────────────────────────────────────────────── public const string GrpcConsumer = "grpc:0.0.0.0:50051"; public const string GrpcProducer = "grpc:127.0.0.1:50051?plaintext=true"; // ── Kafka (fire-and-forget via WireTap) ───────────────────────────────── public const string KafkaWireTap = "kafka://demo-audit?brokers=localhost:29092"; // ── File (snapshot via WireTap) ───────────────────────────────────────── public const string FileWireTap = "file://output?fileName=${header.traceId}.json&autoCreate=true"; // ── SQL ───────────────────────────────────────────────────────────────── public const string SqlInsert = "sql:INSERT INTO demo_log(exchange_id, message, status) VALUES(:#exchange_id, :#message, :#status)" + "?dataSource=#pg-demo" + "¶m.exchange_id=${header.traceId}" + "¶m.message=${body}" + "¶m.status=${header.mode}"; public const string SqlSelect = "sql:SELECT id, exchange_id, message, status, created_at FROM demo_log ORDER BY id DESC LIMIT 5" + "?dataSource=#pg-demo&outputType=SelectList"; // ── Redis ─────────────────────────────────────────────────────────────── public const string RedisPub = "redis:PUBLISH:demo-events?connectionString=localhost:6379"; public const string RedisSub = "redis:SUBSCRIBE:demo-events?connectionString=localhost:6379"; // ── TCP ───────────────────────────────────────────────────────────────── public const string TcpServer = "tcp://0.0.0.0:9099"; public const string TcpProducer = "tcp://localhost:9099?reconnect=true"; // ── WebSocket ─────────────────────────────────────────────────────────── public const string WsServer = "ws://0.0.0.0:9091/demo"; public const string WsClient = "ws://localhost:9091/demo"; // ── MQTT ──────────────────────────────────────────────────────────────── public const string MqttHost = "localhost"; public const int MqttPort = 11883; public const string MqttTopic = "demo/telemetry"; // ── SEDA dead-letter queue ────────────────────────────────────────────── public const string DeadLetterQueue = "seda://dead-letters?size=1000"; // ── JSON Schema for input validation ──────────────────────────────────── public const string MessageSchema = """ { "type": "object", "required": ["message"], "properties": { "message": { "type": "string", "minLength": 1 } } } """; // ── Shared idempotent repository (dedup) ──────────────────────────────── public static readonly InMemoryIdempotentRepository IdempotentRepo = new(); } Path: redb-route/demo/redb.Route.Demo/Routes/DemoHelpers.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/demo/redb.Route.Demo/Routes/DemoHelpers.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using redb.Route.Abstractions; namespace redb.Route.Demo.Routes; /// /// Pure helpers shared by every demo route builder. /// No state, no DI - just utilities for header access and HTTP response shaping. /// internal static class DemoHelpers { /// Reads a header value as string (null if missing). public static string? GetHeader(IExchange e, string key) => e.In.Headers.TryGetValue(key, out var v) ? v?.ToString() : null; /// Safe substring used by error-handler logging. public static string? Trunc(string? s, int max = 200) => s is null ? null : s[..Math.Min(max, s.Length)]; private static readonly JsonSerializerOptions JsonOpts = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; /// Builds the JSON response returned by the main HTTP pipeline. public static string BuildResponse(IExchange e) { return JsonSerializer.Serialize(new { success = true, traceId = GetHeader(e, "traceId"), mode = GetHeader(e, "mode"), stamps = new { rabbit = GetHeader(e, "stamp.rabbit"), amqp = GetHeader(e, "stamp.amqp"), grpc = GetHeader(e, "stamp.grpc"), wmq = GetHeader(e, "stamp.wmq"), vm = GetHeader(e, "stamp.vm"), // Stamps produced by the new flat fluent DSL (Choice + sibling When/Otherwise, // TryCatch with rich Catch log) configured in MainPipelineRoutes.cs. dsl = new { branch = GetHeader(e, "stamp.dsl"), priority = GetHeader(e, "stamp.dsl.priority"), fastTrack = GetHeader(e, "fastTrack"), catchTriggered = GetHeader(e, "stamp.dsl.caught"), }, }, pipeline = "HTTP -> Direct -> RabbitMQ -> AMQP -> gRPC -> WMQ -> DirectVM -> " + "SQL(tx) -> Kafka(tap) -> File(tap) -> VM(tap) -> WMQ(tap)", startedAt = GetHeader(e, "startedAt"), }, JsonOpts); } } Path: redb-route/demo/redb.Route.Demo/Routes/EchoRoutes.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/demo/redb.Route.Demo/Routes/EchoRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.Demo.Routes; /// /// Echo endpoint — returns the request body straight back to the caller. /// /// Ships with .AutoStart(false): the route stays dormant after the module /// loads and only spins up when started by hand from the Tsak dashboard / CLI /// (tsak route start demo-http-echo). That makes it a tidy probe for the /// start/stop lifecycle API without touching any of the always-on demo routes. /// /// /// Shares the demo's HTTP server on port 5088: /// curl -X POST http://localhost:5088/api/echo -d '{"hello":"world"}' /// → the same payload comes straight back. /// /// internal sealed class EchoRoutes : RouteBuilder { private readonly ILogger? _log; public EchoRoutes(ILogger? log) => _log = log; protected override void Configure() { From("http:0.0.0.0:5088/api/echo?inOut=true") .RouteId("demo-http-echo") .AutoStart(false) // HTTP body arrives as byte[] — surface it as a string for the reply. .ConvertBody() .Log("[ECHO] ▶ Received: body=${body}, contentType=${contentType}") // Mirror the caller's content type back; default to JSON when absent. .SetHeader("Content-Type", e => e.In.Headers.TryGetValue("Content-Type", out var ct) && ct is string s && s.Length > 0 ? s : "application/json") // inOut=true → whatever the body is at the end becomes the HTTP response, // and it is already the (unchanged) request body — a true echo. .Log("[ECHO] ◀ Echoing back: ${body}"); } } Path: redb-route/demo/redb.Route.Demo/Routes/EipRoutes.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/demo/redb.Route.Demo/Routes/EipRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using static redb.Route.Demo.Routes.DemoHelpers; namespace redb.Route.Demo.Routes; /// /// Enterprise Integration Patterns: Aggregator, Multicast, RecipientList, DynamicRouter, /// Loop, Resequencer, Content Enricher, IdempotentConsumer, Throttle. /// internal sealed class EipRoutes : RouteBuilder { private readonly ILogger? _log; public EipRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureAggregatorRoute(); ConfigureMulticastRoute(); ConfigureRecipientListRoute(); ConfigureDynamicRouterRoute(); ConfigureLoopRoute(); ConfigureResequencerRoute(); ConfigureEnrichRoute(); ConfigureIdempotentRoute(); ConfigureThrottleRoute(); } /// /// Aggregator — collects 3 messages with same batchId, merges into one. /// Timer sends events → Aggregate → when 3 collected → emit combined. /// private void ConfigureAggregatorRoute() { From("timer://agg-source?period=2000&repeatCount=9") .RouteId("demo-aggregator") .SetHeader("batchId", e => $"batch-{DateTime.UtcNow.Second % 3}") .SetBody(e => $"event-{DateTime.UtcNow:ss.fff}") .Log("[AGG] ▶ Event: batchId=${header.batchId}, body=${body}") .Aggregate( correlationKey: e => GetHeader(e, "batchId") ?? "default", aggregationStrategy: (oldEx, newEx) => { var oldBody = oldEx.In.Body?.ToString() ?? ""; var newBody = newEx.In.Body?.ToString() ?? ""; oldEx.In.Body = oldBody + " + " + newBody; var count = oldEx.Properties.TryGetValue("agg.count", out var c) ? (int)c! : 1; oldEx.Properties["agg.count"] = count + 1; return oldEx; }, completionPredicate: e => e.Properties.TryGetValue("agg.count", out var c) && (int)c! >= 3) .Log("[AGG] ✔ Aggregated 3 events: ${body}"); } /// /// Multicast — send one message to multiple endpoints in parallel. /// Like a TV broadcast: one input, many outputs. /// private void ConfigureMulticastRoute() { From("direct://demo-multicast") .RouteId("demo-multicast") .Log("[MCAST] ▶ Broadcasting to 3 endpoints...") .Multicast( new[] { "direct://mcast-a", "direct://mcast-b", "direct://mcast-c" }, parallelProcessing: true) .Log("[MCAST] ◀ All endpoints received the message"); From("direct://mcast-a") .RouteId("demo-mcast-a") .Log("[MCAST-A] ▶ Received copy: ${body}") .SetHeader("mcast.a", "done"); From("direct://mcast-b") .RouteId("demo-mcast-b") .Log("[MCAST-B] ▶ Received copy: ${body}") .Delay(TimeSpan.FromMilliseconds(100)) .Log("[MCAST-B] ◀ Done after 100ms delay"); From("direct://mcast-c") .RouteId("demo-mcast-c") .Log("[MCAST-C] ▶ Received copy: ${body}") .SetHeader("mcast.c", "done"); } /// /// RecipientList — dynamically choose endpoints from the exchange. /// Header "targets" = "a,b" → routes to direct://rcpt-a, direct://rcpt-b. /// private void ConfigureRecipientListRoute() { From("direct://demo-recipient-list") .RouteId("demo-recipient-list") .Log("[RCPT] ▶ Routing to dynamic recipients: targets=${header.targets}") .RecipientList( e => { var targets = GetHeader(e, "targets") ?? "a"; return targets.Split(',').Select(t => $"direct://rcpt-{t.Trim()}"); }, parallelProcessing: true) .Log("[RCPT] ◀ All recipients processed"); From("direct://rcpt-a") .RouteId("demo-rcpt-a") .Log("[RCPT-A] ▶ Got message: ${body}"); From("direct://rcpt-b") .RouteId("demo-rcpt-b") .Log("[RCPT-B] ▶ Got message: ${body}"); } /// /// DynamicRouter — state machine routing. The routing function decides /// the next endpoint after each hop. Returns null to stop. /// private void ConfigureDynamicRouterRoute() { From("direct://demo-dynamic-router") .RouteId("demo-dynamic-router") .SetProperty("router.step", 0) .Log("[DROUTER] ▶ Starting dynamic routing...") .DynamicRouter(e => { var step = e.Properties.TryGetValue("router.step", out var s) ? (int)s! : 0; e.Properties["router.step"] = step + 1; return step switch { 0 => "direct://drouter-validate", 1 => "direct://drouter-transform", 2 => "direct://drouter-store", _ => null // null = stop routing }; }) .Log("[DROUTER] ◀ Complete, went through ${property.router.step} hops"); From("direct://drouter-validate") .RouteId("demo-drouter-validate") .Log("[DROUTER] ▸ Step 1: Validate") .SetHeader("validated", "true"); From("direct://drouter-transform") .RouteId("demo-drouter-transform") .Log("[DROUTER] ▸ Step 2: Transform") .Process(e => e.In.Body = e.In.Body?.ToString()?.ToUpperInvariant()); From("direct://drouter-store") .RouteId("demo-drouter-store") .Log("[DROUTER] ▸ Step 3: Store — body=${body}"); } /// /// Loop — repeat a block of processing N times. /// Each iteration appends "→loop" to the body. /// private void ConfigureLoopRoute() { From("direct://demo-loop") .RouteId("demo-loop") .Log("[LOOP] ▶ Looping 3 times...") .Loop(3, body => { body .Log("[LOOP] iteration...") .Process(e => { var current = e.In.Body?.ToString() ?? ""; e.In.Body = current + "→loop"; }); }) .Log("[LOOP] ◀ Result: ${body}"); } /// /// Resequencer — collects messages, sorts by seqNum header, delivers in order. /// Messages arrive 3,1,2 → leave 1,2,3. /// private void ConfigureResequencerRoute() { From("direct://demo-resequencer") .RouteId("demo-resequencer") .Log("[RESEQ] ▶ Received seq=${header.seqNum}: ${body}") .Resequence( e => long.TryParse(GetHeader(e, "seqNum"), out var n) ? n : 0, batchSize: 5, timeout: TimeSpan.FromSeconds(3)) .Log("[RESEQ] ◀ Delivered in order: seq=${header.seqNum}, body=${body}"); } /// /// Content Enricher — call a direct endpoint, merge the result into /// the current message as a header. /// private void ConfigureEnrichRoute() { From("direct://demo-enrich") .RouteId("demo-enrich") .Log("[ENRICH] ▶ Original body: ${body}") .Enrich("direct://enrichment-source", (original, enriched) => { original.In.Headers["enriched.data"] = enriched.In.Body?.ToString(); return original; }) .Log("[ENRICH] ◀ Enriched: body=${body}, enriched.data=${header.enriched.data}"); From("direct://enrichment-source") .RouteId("demo-enrichment-source") .Log("[ENRICH-SRC] ▶ Providing enrichment data") .SetBody(e => $"extra-info-for-{GetHeader(e, "traceId") ?? "unknown"}") .Log("[ENRICH-SRC] ◀ Returning: ${body}"); } /// /// IdempotentConsumer — deduplicates by messageId header. /// Second call with same ID is silently skipped. /// private void ConfigureIdempotentRoute() { From("direct://demo-idempotent") .RouteId("demo-idempotent") .Log("[IDEMP] ▶ messageId=${header.messageId}") .IdempotentConsumer( e => GetHeader(e, "messageId") ?? Guid.NewGuid().ToString(), new InMemoryIdempotentRepository(), skipDuplicate: true) .Log("[IDEMP] ✓ First time seeing this message, processing...") .Process(e => e.In.Headers["idempotent.processed"] = "true") .Log("[IDEMP] ◀ Done"); } /// /// Throttle as standalone route — 5 requests/sec rate limit. /// private void ConfigureThrottleRoute() { From("direct://demo-throttle") .RouteId("demo-throttle") .Log("[THROTTLE] ▶ Incoming request...") .Throttle(5, TimeSpan.FromSeconds(1)) .Log("[THROTTLE] ✓ Passed rate limiter (5/sec)") .Log("[THROTTLE] ◀ Done"); } } Path: redb-route/demo/redb.Route.Demo/Routes/ErrorHandlingRoutes.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/demo/redb.Route.Demo/Routes/ErrorHandlingRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using static redb.Route.Demo.Routes.DemoEndpoints; using static redb.Route.Demo.Routes.DemoHelpers; namespace redb.Route.Demo.Routes; /// /// Error-handling EIPs: DoTry/DoCatch/DoFinally, CircuitBreaker, Retry, DeadLetterChannel. /// internal sealed class ErrorHandlingRoutes : RouteBuilder { private readonly ILogger? _log; public ErrorHandlingRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureTryCatchRoute(); ConfigureCircuitBreakerRoute(); ConfigureRetryRoute(); ConfigureDeadLetterRoute(); } /// /// DoTry / DoCatch / DoFinally — structured error handling inside a route. /// Message flows: try body → catch if error → finally always. /// private void ConfigureTryCatchRoute() { From("direct://demo-try-catch") .RouteId("demo-try-catch") .Log("[TRY-CATCH] ▶ Starting risky operation...") .DoTry() .Log("[TRY-CATCH] try: parsing body...") .Process(e => { var body = e.In.Body?.ToString() ?? ""; if (body.Contains("BOOM")) throw new InvalidOperationException("Body contains BOOM!"); e.In.Headers["parsed"] = "true"; }) .Log("[TRY-CATCH] try: ✓ parsed OK") .DoCatch() .Log("[TRY-CATCH] catch: ✖ InvalidOperation — ${exception.message}") .SetHeader("parsed", "false") .SetHeader("error", e => e.Exception?.Message ?? "unknown") .DoCatch() .Log("[TRY-CATCH] catch: ✖ General error — ${exception.message}") .SetHeader("parsed", "false") .DoFinally() .Log("[TRY-CATCH] finally: cleanup, parsed=${header.parsed}") .RemoveHeader("tempData") .End() .Log("[TRY-CATCH] ◀ Done, parsed=${header.parsed}"); } /// /// CircuitBreaker — protects against cascading failures. /// 3 failures → circuit opens → fallback → auto-recovery after 10s. /// private void ConfigureCircuitBreakerRoute() { From("direct://demo-circuit-breaker") .RouteId("demo-circuit-breaker") .Log("[CB] ▶ Calling unreliable service...") .CircuitBreaker(cb => cb .Threshold(3) .ResetTimeout(TimeSpan.FromSeconds(10)) .HalfOpenMaxCalls(1) .FallBack(fb => fb .Log("[CB] ⚡ FALLBACK: circuit is open, returning cached response") .SetBody(e => "{\"source\":\"cache\",\"note\":\"circuit breaker active\"}") .SetHeader("cb.state", "open"))) .Log("[CB] → calling external API...") .Process(e => { if (GetHeader(e, "fail") == "true") throw new TimeoutException("External API timed out!"); }) .Log("[CB] ◀ Response: ${body}"); } /// /// Retry — automatic retry with exponential backoff. /// Fails twice, succeeds on third attempt. /// private void ConfigureRetryRoute() { From("direct://demo-retry") .RouteId("demo-retry") .Log("[RETRY] ▶ Processing with retry policy...") // NOTE: fluent .Retry(...) DSL is not currently exposed on IRouteDefinition; // retries are configured via OnException(...).MaximumRedeliveries(...) at the route-context level. .Log("[RETRY] → attempt...") .Process(e => { var attempt = e.Properties.TryGetValue("RetryAttempt", out var a) ? (int)a! : 0; e.In.Headers["retry.attempt"] = attempt.ToString(); if (attempt < 2) throw new TimeoutException($"Timeout on attempt {attempt}"); }) .Log("[RETRY] ✓ Succeeded on attempt ${header.retry.attempt}") .Log("[RETRY] ◀ Done"); } /// /// DeadLetterChannel — failed messages go to a dead-letter SEDA queue /// instead of being lost. Separate consumer processes them. /// private void ConfigureDeadLetterRoute() { From("direct://demo-dead-letter") .RouteId("demo-dead-letter") .Log("[DLQ] ▶ Processing message...") // NOTE: fluent .DeadLetterChannel(uri) DSL is not currently exposed on IRouteDefinition; // dead-letter routing is configured via OnException(...).To(DeadLetterQueue).Handled(true) instead. .Process(e => { if (GetHeader(e, "poison") == "true") throw new InvalidOperationException("Poison message detected!"); }) .Log("[DLQ] ✓ Message processed successfully"); // Dead-letter consumer From(DeadLetterQueue) .RouteId("demo-dlq-consumer") .Log("[DLQ-SINK] ▶ Dead letter received: ${body}") .Log("[DLQ-SINK] exception: ${exception.message}") .SetHeader("dlq.receivedAt", e => DateTime.UtcNow.ToString("o")) .Log("[DLQ-SINK] ◀ Archived"); // Poison message sender — cron uses this to exercise the DLQ path From("direct://demo-dead-letter-poison") .RouteId("demo-dead-letter-poison") .SetHeader("poison", "true") .Log("[DLQ-POISON] ▶ Sending poison message to DLQ route...") .To("direct://demo-dead-letter"); } } Path: redb-route/demo/redb.Route.Demo/Routes/LifecycleRoutes.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/demo/redb.Route.Demo/Routes/LifecycleRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Demo.Routes; /// /// Lifecycle showcase: route policy hooks and cluster-ready leader-only routes. /// internal sealed class LifecycleRoutes : RouteBuilder { private readonly ILogger? _log; public LifecycleRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigurePolicyShowcaseRoute(); ConfigureClusterReadyRoute(); } /// /// RoutePolicy — observe start/stop/suspend/resume + before/after exchange. /// Useful for logging, metrics, custom suspend logic. /// private void ConfigurePolicyShowcaseRoute() { From("timer://policy-demo?period=15000") .RouteId("demo-policy-showcase") .RoutePolicy(new DemoRoutePolicy(_log)) .Log("[POLICY] ▶ Tick (RoutePolicy observes this exchange)") .Process(e => e.In.Headers["policy.processed"] = DateTime.UtcNow.ToString("o")) .Log("[POLICY] ◀ Done"); } /// /// ClusterReady() — marks a route as leader-only. In a cluster only one /// node runs the route; others stay idle. Without clustering it always /// runs (the cluster manager defaults to a single-node leader). /// private void ConfigureClusterReadyRoute() { From("timer://leader-only?period=20000") .RouteId("demo-cluster-ready") // NOTE: fluent .ClusterReady() DSL is not currently exposed on IRouteDefinition; // leader-only execution is enabled via a RoutePolicy or the cluster manager configuration. .Log("[CLUSTER] ▶ Leader-only tick fired (single node in cluster)") .Process(e => e.In.Headers["cluster.tick"] = DateTime.UtcNow.ToString("o")) .Log("[CLUSTER] ◀ Done"); } } Path: redb-route/demo/redb.Route.Demo/Routes/LlmDemoRoutes.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/demo/redb.Route.Demo/Routes/LlmDemoRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Extensions; namespace redb.Route.Demo.Routes; /// /// LLM connector showcase. All demos run against the deterministic stub /// provider so they require no API keys and no network. Each route shows a /// different way to wire the connector: /// /// /// llm-inline-demo — .Llm("demo-stub") as an inline step. /// llm-endpoint-demo — .To("llm://demo-stub") through the component. /// llm-tool-demo — .AsLlmTool(...) registers a route as a tool descriptor. /// /// /// Wiring lives in : the LlmComponent is /// added to the context, a stub LlmConnectionFactory is placed in the /// registry, an IAgentEngine and a IToolDescriptorRegistry are /// registered as services so the inline DSL and the producer can resolve them. /// internal sealed class LlmDemoRoutes : RouteBuilder { private readonly ILogger? _log; public LlmDemoRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureInlineCallRoute(); ConfigureEndpointRoute(); ConfigureToolRoute(); } /// /// Inline step — timer ticks, the body becomes a user message, the stub /// provider echoes it back into exchange.Out.Body. Showcases per-call /// configuration via . /// private void ConfigureInlineCallRoute() { From("timer://llm-inline?period=30000&delay=15000") .RouteId("llm-inline-demo") .AutoStart(false) .SetBody(_ => "Summarise: redb.Route is an Apache-Camel-class .NET ESB.") .Log("[LLM-IL] ▶ user=${body}") .Llm("demo-stub", call => call .WithSystemPrompt("Be terse.") .WithMaxIterations(1) .WithTemperature(0.0)) .Log("[LLM-IL] ◀ provider=${header.llm.provider.id} model=${header.llm.model.id}") .Log("[LLM-IL] ◀ tokensIn=${header.llm.tokens.in} tokensOut=${header.llm.tokens.out} stop=${header.llm.stop_reason}") .Log("[LLM-IL] ◀ reply=${body}"); } /// /// Endpoint step — same call, but routed through the LLM component. Endpoint /// options live in the URI: maxIterations, temperature, etc. /// private void ConfigureEndpointRoute() { From("timer://llm-endpoint?period=30000&delay=20000") .RouteId("llm-endpoint-demo") .AutoStart(false) .SetBody(_ => "What is an EIP wire-tap?") .Log("[LLM-EP] ▶ user=${body}") .To("llm://demo-stub?maxIterations=1&temperature=0") .Log("[LLM-EP] ◀ stop=${header.llm.stop_reason} iters=${header.llm.tool.iterations}") .Log("[LLM-EP] ◀ reply=${body}"); } /// /// Tool route — exposes direct:demo-tool as the LLM tool /// echo_tool. With a real provider, the agent could call this via /// .UseTools("echo_tool"); the stub provider never invokes tools, so /// the route just demonstrates the registration shape — calling the /// endpoint directly still works as a normal redb.Route route. /// private void ConfigureToolRoute() { From("direct:demo-tool") .AsLlmTool("echo_tool") .Description("Returns the supplied text unchanged.") .Input("""{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}""") .SideEffect(ToolSideEffect.ReadOnly) .Caching(ToolCachingPolicy.Memoize) .Cost(ToolCostClass.Cheap) .Then() .Log("[LLM-TOOL] ▶ in=${body}") .Process(e => { e.Out ??= e.In.Clone(); e.Out.Body = e.In.Body?.ToString() ?? string.Empty; }) .Log("[LLM-TOOL] ◀ out=${body}"); } } Path: redb-route/demo/redb.Route.Demo/Routes/LlmHttpRoutes.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/demo/redb.Route.Demo/Routes/LlmHttpRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Exec; using redb.Route.Llm; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Extensions; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Demo.Routes; /// /// HTTP showcase for the LLM connector — designed to be the simplest possible /// curl→Claude→reply round-trip, with full technical logging along the way. /// /// Two endpoints, both readable top-down like a Camel example: /// /// /// POST /api/llm/ask — body is the user prompt, route asks Claude Haiku, /// logs token usage + stop reason, returns the model's reply as plain text. /// /// /// POST /api/llm/shell — same flow, but the agent has a shell tool /// wired through . Try: /// curl -d "list the current directory" http://localhost:5088/api/llm/shell. /// /// /// /// Wiring lives in : ExecComponent is added /// to the context and a "haiku" is placed /// in the registry with REDB_LLM_ANT_API03_KEY as its API key. /// internal sealed class LlmHttpRoutes : RouteBuilder { private static bool IsWindows => OperatingSystem.IsWindows(); private readonly ILogger? _log; public LlmHttpRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureAskEndpoint(); ConfigureShellAgentEndpoint(); ConfigureShellTool(); } /// /// Plain chat: prompt in, reply out. No tools, single iteration. The whole /// route is six steps — exactly what a Camel reader expects. Uses the /// llm:// endpoint form so it works in any host without needing /// IRouteContext on the DI container. /// Conversation memory: pass -H "X-Chat-Id: my-chat" with curl /// to keep history across calls; missing header falls back to "default". /// private void ConfigureAskEndpoint() { From("http:0.0.0.0:5088/api/llm/ask?inOut=true") .RouteId("llm-http-ask") .ConvertBody() .Process(e => { e.In.Headers[LlmHeaders.SystemPrompt] = "Reply in one short, friendly sentence."; e.In.Headers[LlmHeaders.ConversationId] = e.In.Headers.TryGetValue("X-Chat-Id", out var v) && v is string s && s.Length > 0 ? s : "default"; }) .Log("[LLM-ASK] ▶ chat=${header.llm.conversation.id} prompt=${body}") .To(LlmDsl.Factory("haiku") .ConversationFromHeader() .MaxIterations(1) .Temperature(0.2) .AsUri()) .Log("[LLM-ASK] ◀ provider=${header.llm.provider.id} model=${header.llm.model.id} " + "tokensIn=${header.llm.tokens.in} tokensOut=${header.llm.tokens.out} stop=${header.llm.stop_reason}") .Log("[LLM-ASK] ◀ reply=${body}"); } /// /// Tool-using agent: Claude can call the shell tool to inspect the host. /// Same compact shape — the only extra knob is .Tools("shell"). Conversation /// memory works the same way: pass -H "X-Chat-Id: my-chat" across calls. /// private void ConfigureShellAgentEndpoint() { var systemPrompt = "You can run small shell commands through the 'shell' tool. " + $"The host is {(IsWindows ? "Windows (use cmd /c)" : "Linux (use sh -c)")}. " + "Use the tool when the user asks about the system, files, or commands; " + "then summarise what you learned in one short sentence."; From("http:0.0.0.0:5088/api/llm/shell?inOut=true") .RouteId("llm-http-shell") .ConvertBody() .Process(e => { e.In.Headers[LlmHeaders.SystemPrompt] = systemPrompt; e.In.Headers[LlmHeaders.ConversationId] = e.In.Headers.TryGetValue("X-Chat-Id", out var v) && v is string s && s.Length > 0 ? s : "default"; }) .Log("[LLM-SHELL] ▶ chat=${header.llm.conversation.id} prompt=${body}") .To(LlmDsl.Factory("haiku") .Tools("shell") .ConversationFromHeader() .MaxIterations(10) .Temperature(0.0) .AsUri()) .Log("[LLM-SHELL] ◀ iters=${header.llm.tool.iterations} stop=${header.llm.stop_reason} " + "tokensIn=${header.llm.tokens.in} tokensOut=${header.llm.tokens.out}") .Log("[LLM-SHELL] ◀ reply=${body}"); } /// /// The shell tool itself — a tiny tool route that just forwards to /// exec://run with a one-command allowlist. The allowlist is the /// security envelope: anything outside it is rejected before a process starts. /// private void ConfigureShellTool() { var allowed = IsWindows ? new[] { "cmd", "pwsh", "powershell" } : new[] { "sh", "bash" }; // Pinned scratch dir so the agent's `Out-File out.html` / `curl -o page.html` // don't pollute the Worker's source tree (its CWD when launched via `dotnet run`). // Persists between iterations so the model can write then re-read on the next call. var scratchDir = Path.Combine(Path.GetTempPath(), "redb-llm-shell"); Directory.CreateDirectory(scratchDir); From("direct:tool-shell") .AsLlmTool("shell") .Description( "Run a small shell command on the host. Input: " + "{\"command\":\"\",\"args\":[\"...\"]}. Output: " + "{\"stdout\":\"...\",\"stderr\":\"...\",\"exitCode\":N}. " + $"Allowed commands: {string.Join(", ", allowed)}. " + $"Working directory is pinned to '{scratchDir}' — relative paths in " + "your commands resolve there, and files written in one call survive to the next. " + (IsWindows ? "Prefer 'pwsh' (PowerShell 7) for anything involving non-ASCII output; " + "start its commands with `[Console]::OutputEncoding=[Text.Encoding]::UTF8; ` " + "so stdout reaches you as UTF-8 instead of cp866." : "Use 'sh -c \"…\"' for pipelines.")) .Input(""" { "type": "object", "properties": { "command": { "type": "string" }, "args": { "type": "array", "items": { "type": "string" } } }, "required": ["command"] } """) .SideEffect(ToolSideEffect.ReadOnly) .Cost(ToolCostClass.Cheap) .Then() .Log("[SHELL-TOOL] ▶ in=${body}") .To(ExecDsl.Run() .AllowedCommands(allowed) .WorkingDirectory(scratchDir) .TimeoutMs(5_000) .MaxStdoutBytes(8_192) .MaxStderrBytes(8_192)) .Log("[SHELL-TOOL] ◀ exit=${header.redbExec.ExitCode} stdoutBytes=${header.redbExec.StdoutBytes}"); } } Path: redb-route/demo/redb.Route.Demo/Routes/MainPipelineRoutes.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/demo/redb.Route.Demo/Routes/MainPipelineRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using static redb.Route.Demo.Routes.DemoEndpoints; using static redb.Route.Demo.Routes.DemoHelpers; namespace redb.Route.Demo.Routes; /// /// Main pipeline: HTTP entry, cross-transport pipeline (RabbitMQ → AMQP → gRPC → /// WMQ → DirectVM → SQL → Kafka/File/VM/Redis/MQTT/SEDA WireTaps) and 6 RPC workers. /// Owns the GLOBAL OnException handler shared by every demo route. /// internal sealed class MainPipelineRoutes : RouteBuilder { private readonly ILogger? _log; public MainPipelineRoutes(ILogger? log) => _log = log; protected override void Configure() { // ── Global error handler ──────────────────────────────────────── // Any unhandled exception in ANY route → retry 2× → log → mark handled OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromSeconds(1)) .UseExponentialBackOff() .BackOffMultiplier(2.0) .Handled(true) .Process(e => { _log?.LogError( "[GLOBAL-ERR] routeId={RouteId}, exType={ExType}, exMsg={ExMsg}, bodyType={BodyType}, body={Body}, headers={Headers}", e.RouteId ?? "(null)", e.Exception?.GetType().Name ?? "(null)", Trunc(e.Exception?.Message), e.In.Body?.GetType().Name ?? "(null)", Trunc(e.In.Body?.ToString()) ?? "(null)", string.Join(", ", e.In.Headers.Select(h => $"{h.Key}={h.Value}"))); }) .Log("[GLOBAL-ERR] ✖ ${exception.message} → handled after retries"); ConfigureHttpEntry(); ConfigurePipeline(); ConfigureRabbitWorker(); ConfigureAmqpWorker(); ConfigureGrpcWorker(); ConfigureWmqWorker(); ConfigureDirectVmEnricher(); ConfigureVmAuditConsumer(); } /// /// Route 1: HTTP entry point. /// POST /api/demo → validate → throttle → dedup → pipeline /// private void ConfigureHttpEntry() { From("http:0.0.0.0:5088/api/demo?inOut=true") .RouteId("demo-http-entry") // HTTP body arrives as byte[] — convert to string first .ConvertBody() // Throttle: max 10 requests per second .Throttle(10) .Log("[1-HTTP] ▶ Received: body=${body}, contentType=${contentType}") // Generate trace ID .SetHeader("traceId", e => Guid.NewGuid().ToString("N")[..12]) .SetHeader("startedAt", e => DateTime.UtcNow.ToString("o")) .Log("[1-HTTP] traceId=${header.traceId}, mode=${header.mode}, priority=${header.priority}") // Validate — body must be JSON with "message" field .ValidateJsonSchema(MessageSchema) .Log("[1-HTTP] ✓ JSON schema valid") // Idempotent Consumer — dedup by traceId (same message won't process twice) .IdempotentConsumer( e => GetHeader(e, "traceId") ?? "", IdempotentRepo) .Log("[1-HTTP] ✓ Not a duplicate") // Forward to pipeline .To("direct://pipeline"); } /// /// Route 2: Main processing pipeline. /// Filter → Choice → Traced(RabbitMQ → AMQP → gRPC RPC) → DirectVM enrich /// → Metered(BeginTx → SQL INSERT → SQL SELECT → CommitTx) /// → WireTap(Kafka, File, VM) → build response /// private void ConfigurePipeline() { From("direct://pipeline") .RouteId("demo-pipeline") .Log("[2-PIPE] ▶ Pipeline started, traceId=${header.traceId}") // ── Filter — drop empty bodies ── .Filter(e => !string.IsNullOrEmpty(e.In.Body?.ToString())) .Log("[2-PIPE] ✓ Body is non-empty") // ── Store processing context in exchange properties ── .SetProperty("pipelineStartMs", e => Environment.TickCount64) .Log("[2-PIPE] pipelineStartMs = ${property.pipelineStartMs}") // ── Choice — flat fluent DSL with sibling When() / Otherwise(). // // This block intentionally uses the new ergonomic style: every branch // returns to IRouteDefinition after EndXxx(), and sibling When() / // Otherwise() are reachable through extension methods that walk the // parent chain back to the enclosing Choice. No nested lambdas needed. // // The "full" branch also showcases TryCatch + RichLog inside the // catch handler — exactly the pattern from DeepNestedDslTests. .Choice() .When(e => GetHeader(e, "mode") == "full") .SetHeader("fastTrack", e => GetHeader(e, "priority") == "high" ? "true" : "false") // Priority normalization that throws on unknown values — proves // the pipeline keeps flowing because the catch sets a sane default. .TryCatch() .Process(e => { var p = GetHeader(e, "priority") ?? ""; if (p is not ("high" or "normal" or "low")) throw new InvalidOperationException($"unknown priority: {p}"); e.In.Headers["stamp.dsl.priority"] = p; }) .DoCatch() // Rich log inside the catch — multi-piece structured entry. .Log(LogLevel.Warning) .Message(e => $"priority normalization failed: {e.Exception?.GetType().Name}") .Header("priority") .ShowRouteId(true) .EndLog() .SetHeader("stamp.dsl.priority", "unknown") .SetHeader("stamp.dsl.caught", "true") .EndTryCatch() .SetHeader("stamp.dsl", "full-branch") .When(e => GetHeader(e, "mode") == "short") .SetHeader("fastTrack", "false") .SetHeader("stamp.dsl", "short-branch") .Otherwise() .SetHeader("mode", "default") .SetHeader("fastTrack", "false") .SetHeader("stamp.dsl", "default-branch") .EndChoice() // ── Rich log scope: one structured line that captures the whole // branching decision plus a property — the route id is rendered // as a [rId:demo-pipeline] prefix thanks to ShowRouteId(true). .Log(LogLevel.Information) .Message("pipeline branch decided") .Header("mode") .Header("priority") .Header("fastTrack") .Header("stamp.dsl") .Header("stamp.dsl.priority") .Property("pipelineStartMs") .ShowRouteId(true) .EndLog() .Log("[2-PIPE] ▸ mode=${header.mode}, fastTrack=${header.fastTrack}") // ── Traced block: wrap broker calls in a single trace span ── .Traced("broker-roundtrips") // RabbitMQ RPC .Log("[3-RABBIT] → Sending to RabbitMQ RPC...") .To(RabbitProducer) .Log("[3-RABBIT] ← stamp.rabbit=${header.stamp.rabbit}") // AMQP RPC .Log("[4-AMQP] → Sending to AMQP/Artemis RPC...") .To(AmqpProducer) .Log("[4-AMQP] ← stamp.amqp=${header.stamp.amqp}") // gRPC .Log("[5-GRPC] → Sending to gRPC server...") .To(GrpcProducer) .Log("[5-GRPC] ← stamp.grpc=${header.stamp.grpc}") // IBM MQ RPC .Log("[6-WMQ] → Sending to IBM MQ RPC...") .To(WmqRpcProducer) .Log("[6-WMQ] ← stamp.wmq=${header.stamp.wmq}") .EndTraced() // ── ConvertBody — gRPC returns byte[], convert to string ── .ConvertBody() .Log("[5-GRPC] ✓ Body converted to string: ${body}") // ── DirectVM enrichment (cross-context sync call) ── .Log("[5b-DVM] → Calling direct-vm://enricher...") .To("direct-vm://enricher") .Log("[5b-DVM] ← stamp.vm=${header.stamp.vm}") // ── Metered block: wrap SQL operations with metrics ── // Save original body — SQL SELECT will replace it with List .SetProperty("originalBody", e => e.In.Body) .Metered("sql-operations") // Begin imperative transaction .BeginTransaction() .Log("[6-TX] ▶ Transaction opened") // SQL INSERT .Log("[6-SQL] → INSERT demo_log: traceId=${header.traceId}, mode=${header.mode}") .To(SqlInsert) .Log("[6-SQL] ← Insert complete") // SQL SELECT — read last 5 rows .Log("[6b-SQL] → SELECT last 5 rows from demo_log") .To(SqlSelect) .Split(Body()) .Log("[6b-SQL] row: id=${body['id']}, msg=${body['message']}, status=${body['status']}") .End() // Commit transaction .CommitTransaction() .Log("[6-TX] ✔ Transaction committed") .EndMetered() // Restore original body after SQL SELECT replaced it .SetBody(e => e.Properties.TryGetValue("originalBody", out var b) ? b : e.In.Body) .Log("[6-RESTORE] Body restored: ${body}") // ── Calculate elapsed ── .SetProperty("pipelineElapsedMs", e => Environment.TickCount64 - (long)(e.Properties.TryGetValue("pipelineStartMs", out var s) ? s! : 0L)) // ── WireTap — async forks ── .WireTap(KafkaWireTap) .Log("[7-TAP] → Kafka: demo-audit topic") .WireTap(FileWireTap, newBodyFactory: e => BuildResponse(e)) .Log("[7-TAP] → File: output/${header.traceId}.json") .WireTap("vm://audit-log") .Log("[7-TAP] → VM: async audit-log queue") // ── Transport showcases — wire standalone routes into the flow ── .WireTap("direct://demo-redis-pub") .Log("[7-TAP] → Redis: demo-events channel") .WireTap("direct://demo-mqtt-pub") .Log("[7-TAP] → MQTT: demo/telemetry topic") .WireTap("direct://demo-wmq-pub") .Log("[7-TAP] → WMQ: demo/telemetry topic") .WireTap("direct://demo-seda-send") .Log("[7-TAP] → SEDA: work-queue") // ── Build HTTP response ── .Log("[8-DONE] ✔ Pipeline complete for traceId=${header.traceId}, elapsed=${property.pipelineElapsedMs}ms") // NOTE: fastTrack header is intentionally kept — BuildResponse exposes it // under stamps.dsl.fastTrack so the curl response shows the new DSL effect. .SetHeader("Content-Type", "application/json") .SetBody(e => BuildResponse(e)); } // ── Workers ───────────────────────────────────────────────────────────── /// Route 3: RabbitMQ echo — stamp and reply. private void ConfigureRabbitWorker() { From(RabbitConsumer) .RouteId("demo-rabbit-worker") .Log("[RABBIT-W] ▶ Received: ${body}") .SetHeader("stamp.rabbit", e => $"ok:{DateTime.UtcNow:HH:mm:ss.fff}") .Log("[RABBIT-W] ◀ Stamped, replying"); } /// Route 4: AMQP echo — stamp and reply. private void ConfigureAmqpWorker() { From(AmqpConsumer) .RouteId("demo-amqp-worker") .Log("[AMQP-W] ▶ Received: ${body}") .SetHeader("stamp.amqp", e => $"ok:{DateTime.UtcNow:HH:mm:ss.fff}") .Log("[AMQP-W] ◀ Stamped, replying"); } /// Route 5: gRPC echo — stamp and reply. private void ConfigureGrpcWorker() { From(GrpcConsumer) .RouteId("demo-grpc-worker") .Log("[GRPC-W] ▶ Received: ${body}") .SetHeader("stamp.grpc", e => $"ok:{DateTime.UtcNow:HH:mm:ss.fff}") .Log("[GRPC-W] ◀ Stamped, replying"); } /// Route 6: IBM MQ echo — stamp and reply (RPC worker). private void ConfigureWmqWorker() { From(WmqRpcConsumer) .RouteId("demo-wmq-worker") .Log("[WMQ-W] ▶ Received: ${body}") .SetHeader("stamp.wmq", e => $"ok:{DateTime.UtcNow:HH:mm:ss.fff}") .Log("[WMQ-W] ◀ Stamped, replying"); } /// Route 7: DirectVM enricher — can live in another module. private void ConfigureDirectVmEnricher() { From("direct-vm://enricher") .RouteId("demo-vm-enricher") .Log("[DVM-W] ▶ Enriching: traceId=${header.traceId}") .SetHeader("stamp.vm", e => $"enriched:{DateTime.UtcNow:HH:mm:ss.fff}") .Log("[DVM-W] ◀ Enriched, returning"); } /// Route 8: VM async audit consumer — processes WireTap events. private void ConfigureVmAuditConsumer() { From("vm://audit-log?concurrentConsumers=2") .RouteId("demo-vm-audit") .Log("[VM-AUDIT] ▶ Audit event: traceId=${header.traceId}, mode=${header.mode}") .Process(e => { var traceId = GetHeader(e, "traceId"); var mode = GetHeader(e, "mode"); e.In.Headers["audit.processed"] = $"{traceId}:{mode}:{DateTime.UtcNow:HH:mm:ss.fff}"; }) .Log("[VM-AUDIT] ◀ Processed: ${header.audit.processed}"); } } Path: redb-route/demo/redb.Route.Demo/Routes/NamedRedbRoutes.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/demo/redb.Route.Demo/Routes/NamedRedbRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Demo.Routes; /// /// Named redb instances showcase — pg-test and mssql-test CRUD via ProcessWithRedb(name, …). /// Named instances are auto-created from the "Redb" section in redb.Route.Demo.config.json. /// internal sealed class NamedRedbRoutes : RouteBuilder { private readonly ILogger? _log; public NamedRedbRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureNamedRedbRoute(); } private void ConfigureNamedRedbRoute() { From("timer://named-redb-check?period=30000&delay=5000") .RouteId("demo-named-redb-pgsql") .AutoStart(false) .Log("[NAMED-REDB] ▶ Checking named IRedbService instances...") // ── DB info ── .ProcessWithRedb("pg-test", (redb, ex) => { ex.In.Headers["pg-db-type"] = redb.dbType ?? "n/a"; ex.In.Headers["pg-db-version"] = redb.dbVersion ?? "n/a"; ex.In.Headers["pg-cache-domain"] = redb.CacheDomain ?? "n/a"; }) .Log("[NAMED-REDB] pg-test: type=${header.pg-db-type}, ver=${header.pg-db-version}, cache=${header.pg-cache-domain}") // ── CRUD: Save ── .ProcessWithRedb("pg-test", async (redb, ex, ct) => { var item = new RedbObject { name = $"Demo-{DateTime.UtcNow:HHmmss}", Props = new DemoItemProps { Title = "Named Redb Demo", Description = $"Created at {DateTime.UtcNow:O}", Priority = Random.Shared.Next(1, 10) } }; var id = await redb.SaveAsync(item); ex.In.Headers["crud-saved-id"] = id.ToString(); }) .Log("[NAMED-REDB] CRUD Save → id=${header.crud-saved-id}") // ── CRUD: Load ── .ProcessWithRedb("pg-test", async (redb, ex, ct) => { var idStr = ex.In.Headers["crud-saved-id"]?.ToString(); if (long.TryParse(idStr, out var id)) { var obj = await redb.LoadAsync(id); ex.In.Headers["crud-loaded"] = obj != null ? $"{obj.name} (priority={obj.Props?.Priority})" : "NOT FOUND"; } }) .Log("[NAMED-REDB] CRUD Load → ${header.crud-loaded}") // ── CRUD: Query ── .ProcessWithRedb("pg-test", async (redb, ex, ct) => { var items = await redb.Query() .Where(p => p.Priority > 3) .Take(5) .ToListAsync(); ex.In.Headers["crud-query-count"] = items.Count.ToString(); }) .Log("[NAMED-REDB] CRUD Query (Priority>3) → ${header.crud-query-count} items") // ── CRUD: Delete ── .ProcessWithRedb("pg-test", async (redb, ex, ct) => { var idStr = ex.In.Headers["crud-saved-id"]?.ToString(); if (long.TryParse(idStr, out var id)) { var deleted = await redb.DeleteAsync(id); ex.In.Headers["crud-deleted"] = deleted.ToString(); } }) .Log("[NAMED-REDB] CRUD Delete id=${header.crud-saved-id} → ${header.crud-deleted}") .Log("[NAMED-REDB] ◀ Done — PG CRUD cycle complete"); // ── MSSql CRUD (same pattern, different named instance) ── From("timer://named-redb-mssql?period=30000&delay=8000") .RouteId("demo-named-redb-mssql") .AutoStart(false) .Log("[NAMED-REDB-MSSQL] ▶ Starting CRUD on mssql-test...") .ProcessWithRedb("mssql-test", (redb, ex) => { ex.In.Headers["ms-db-type"] = redb.dbType ?? "n/a"; ex.In.Headers["ms-db-version"] = redb.dbVersion ?? "n/a"; }) .Log("[NAMED-REDB-MSSQL] info: type=${header.ms-db-type}, ver=${header.ms-db-version}") .ProcessWithRedb("mssql-test", async (redb, ex, ct) => { var item = new RedbObject { name = $"MsDemo-{DateTime.UtcNow:HHmmss}", Props = new DemoItemProps { Title = "MSSql Named Redb", Description = $"Created at {DateTime.UtcNow:O}", Priority = Random.Shared.Next(1, 10) } }; var id = await redb.SaveAsync(item); ex.In.Headers["ms-saved-id"] = id.ToString(); }) .Log("[NAMED-REDB-MSSQL] Save → id=${header.ms-saved-id}") .ProcessWithRedb("mssql-test", async (redb, ex, ct) => { if (long.TryParse(ex.In.Headers["ms-saved-id"]?.ToString(), out var id)) { var obj = await redb.LoadAsync(id); ex.In.Headers["ms-loaded"] = obj != null ? $"{obj.name} (priority={obj.Props?.Priority})" : "NOT FOUND"; } }) .Log("[NAMED-REDB-MSSQL] Load → ${header.ms-loaded}") .ProcessWithRedb("mssql-test", async (redb, ex, ct) => { var items = await redb.Query() .Where(p => p.Priority > 3) .Take(5) .ToListAsync(); ex.In.Headers["ms-query-count"] = items.Count.ToString(); }) .Log("[NAMED-REDB-MSSQL] Query (Priority>3) → ${header.ms-query-count} items") .ProcessWithRedb("mssql-test", async (redb, ex, ct) => { if (long.TryParse(ex.In.Headers["ms-saved-id"]?.ToString(), out var id)) { var deleted = await redb.DeleteAsync(id); ex.In.Headers["ms-deleted"] = deleted.ToString(); } }) .Log("[NAMED-REDB-MSSQL] Delete id=${header.ms-saved-id} → ${header.ms-deleted}") .Log("[NAMED-REDB-MSSQL] ◀ Done — MSSql CRUD cycle complete"); } } Path: redb-route/demo/redb.Route.Demo/Routes/ScopeDiagRoutes.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/demo/redb.Route.Demo/Routes/ScopeDiagRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Demo.Routes; /// /// Scope diagnostics — parallel splitter connection tracking. Verifies that each parallel /// scope gets its own and own DB connection lifecycle. /// internal sealed class ScopeDiagRoutes : RouteBuilder { private readonly ILogger? _log; public ScopeDiagRoutes(ILogger? log) => _log = log; private static int _scopeDiagConcurrent; private static int _scopeDiagPeakConcurrent; private static int _scopeDiagTotalScopes; protected override void Configure() { ConfigureScopeDiagRoute(); } private void ConfigureScopeDiagRoute() { // Timer fires once after 10s, then every 60s (change period as needed) From("timer://scope-diag?period=60000&delay=10000") .RouteId("demo-scope-diag") .AutoStart(false) .Log("[SCOPE-DIAG] ▶ Starting parallel split: 50 items, maxDop=5") // Reset counters .Process(e => { Interlocked.Exchange(ref _scopeDiagConcurrent, 0); Interlocked.Exchange(ref _scopeDiagPeakConcurrent, 0); Interlocked.Exchange(ref _scopeDiagTotalScopes, 0); e.In.Body = Enumerable.Range(1, 50).Cast().ToList(); e.In.Headers["diag-start-ms"] = Environment.TickCount64; }) // Parallel split: 50 items, maxDop=5 — classic Camel fluent chain .Split(Body()) .ParallelProcessing() .MaxParallelism(5) .ProcessWithRedb(async (redb, ex, ct) => { var idx = ex.In.Body; var concurrent = Interlocked.Increment(ref _scopeDiagConcurrent); var total = Interlocked.Increment(ref _scopeDiagTotalScopes); // Track peak int peak; do { peak = Volatile.Read(ref _scopeDiagPeakConcurrent); } while (concurrent > peak && Interlocked.CompareExchange(ref _scopeDiagPeakConcurrent, concurrent, peak) != peak); var scopeHash = ex.ServiceProvider?.GetHashCode().ToString("X8") ?? "NO-SCOPE"; _log?.LogInformation( "[SCOPE-DIAG] item={Item}, concurrent={Concurrent}, total={Total}, scopeHash={ScopeHash}", idx, concurrent, total, scopeHash); try { // Real redb CRUD: Save → Load → Delete var item = new RedbObject { name = $"ScopeDiag-{idx}-{DateTime.UtcNow:HHmmssfff}", Props = new DemoItemProps { Title = $"Scope Diag Item {idx}", Description = $"Parallel split test item {idx}", Priority = (int)idx! } }; var savedId = await redb.SaveAsync(item); var loaded = await redb.LoadAsync(savedId); var loadedName = loaded?.name ?? "NOT FOUND"; await redb.DeleteAsync(savedId); // Raw SQL: actual TCP connections to this DB right now var pgConns = await redb.Context.ExecuteScalarAsync( "SELECT count(*)::int FROM pg_stat_activity WHERE datname = current_database()"); _log?.LogInformation( "[SCOPE-DIAG] item={Item}, savedId={SavedId}, loaded={Loaded}, deleted=true, pg_connections={PgConns}", idx, savedId, loadedName, pgConns); } finally { Interlocked.Decrement(ref _scopeDiagConcurrent); } }) .EndSplit() // Summary — final pg_stat_activity snapshot via raw SQL .ProcessWithRedb(async (redb, e, ct) => { var elapsed = Environment.TickCount64 - (long)(e.In.Headers["diag-start-ms"] ?? 0L); var peak = Volatile.Read(ref _scopeDiagPeakConcurrent); var total = Volatile.Read(ref _scopeDiagTotalScopes); var pgConns = await redb.Context.ExecuteScalarAsync( "SELECT count(*)::int FROM pg_stat_activity WHERE datname = current_database()"); _log?.LogWarning( "[SCOPE-DIAG] ◀ DONE: peak_concurrent={Peak}, total_scopes={Total}, elapsed={Elapsed}ms, pg_connections_after={PgConns}", peak, total, elapsed, pgConns); }); } } Path: redb-route/demo/redb.Route.Demo/Routes/TransactionRoutes.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/demo/redb.Route.Demo/Routes/TransactionRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using static redb.Route.Demo.Routes.DemoEndpoints; namespace redb.Route.Demo.Routes; /// /// Transaction showcase: declarative Transacted() wrapping and /// imperative BeginTransaction/CommitTransaction/RollbackTransaction /// inside DoTry/DoCatch. /// internal sealed class TransactionRoutes : RouteBuilder { private readonly ILogger? _log; public TransactionRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureTransactedRoute(); ConfigureImperativeTxRoute(); } /// /// Transacted() — wraps the entire route in a TransactionScope. /// All SQL operations participate in one distributed transaction. /// private void ConfigureTransactedRoute() { From("direct://demo-transacted") .RouteId("demo-transacted") .Log("[TX-AUTO] ▶ Entering transacted route...") .Transacted() .Log("[TX-AUTO] → SQL INSERT inside auto-transaction...") .To(SqlInsert) .Log("[TX-AUTO] → VM audit inside auto-transaction...") .To("vm://audit-log") .Log("[TX-AUTO] ◀ Route complete → auto-commit"); } /// /// BeginTransaction / CommitTransaction / RollbackTransaction — /// imperative control. You decide when to commit or rollback. /// DoTry/DoCatch wraps the transaction for safety. /// private void ConfigureImperativeTxRoute() { From("direct://demo-imperative-tx") .RouteId("demo-imperative-tx") .Log("[TX-IMP] ▶ Starting imperative transaction...") .BeginTransaction() .Log("[TX-IMP] → Transaction opened") .DoTry() .Log("[TX-IMP] → SQL INSERT #1...") .To(SqlInsert) .Log("[TX-IMP] → SQL INSERT #2...") .To(SqlInsert) .CommitTransaction() .Log("[TX-IMP] ✔ Both inserts committed!") .DoCatch() .Log("[TX-IMP] ✖ Error: ${exception.message}") .RollbackTransaction() .Log("[TX-IMP] ✖ Transaction rolled back") .End() .Log("[TX-IMP] ◀ Done"); } } Path: redb-route/demo/redb.Route.Demo/Routes/TransportRoutes.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/demo/redb.Route.Demo/Routes/TransportRoutes.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.MqttNet; using redb.Route.Processors; using redb.Route.Serialization; using static redb.Route.Demo.Routes.DemoEndpoints; namespace redb.Route.Demo.Routes; /// /// Transport showcase: Timer, Quartz cron, SEDA, Redis Pub/Sub, raw TCP, WebSocket, /// MQTT (fluent DSL), IBM MQ topic pub/sub (fluent DSL) and a slow-process simulator. /// internal sealed class TransportRoutes : RouteBuilder { private readonly ILogger? _log; public TransportRoutes(ILogger? log) => _log = log; protected override void Configure() { ConfigureTimerHeartbeat(); ConfigureCronJob(); ConfigureSedaProcessing(); ConfigureRedisRoutes(); ConfigureTcpEchoServer(); ConfigureWebSocketServer(); ConfigureMqttRoutes(); ConfigureWmqRoutes(); ConfigureSlowProcessRoute(); } /// /// Timer — fires every 10s. Good for heartbeats and health checks. /// private void ConfigureTimerHeartbeat() { From("timer://heartbeat?period=10000") .RouteId("demo-timer-heartbeat") .Log("[TIMER] ♥ Heartbeat at ${header.firedTime}") .SetBody(e => new { alive = true, ts = DateTime.UtcNow }) .Marshal(typeof(JsonMessageSerializer)) .ConvertBody() .Log("[TIMER] ♥ Serialized: ${body}") // TCP roundtrip — send heartbeat JSON to TCP echo, get UPPERCASE back .To(TcpProducer) .Log("[TIMER] → TCP echo: ${body}"); } /// /// Quartz cron — fires every 30 seconds. /// Acts as the self-test driver: exercises all showcase routes so every route /// appears in the logs during normal operation. /// private void ConfigureCronJob() { From("cron://demo-cron?schedule=0/30 * * * * ?") .RouteId("demo-cron-job") .Log("[CRON] ⏰ Cron fired at ${header.firedTime}") // Prepare self-test body and headers for downstream routes .SetBody(e => "{\"message\":\"cron-self-test\"}") .SetHeader("traceId", e => $"cron-{DateTime.UtcNow:HHmmss}") .SetHeader("mode", "cron") .SetHeader("messageId", e => Guid.NewGuid().ToString("N")[..8]) .SetHeader("targets", "a,b") .SetHeader("seqNum", e => (DateTime.UtcNow.Second % 5 + 1).ToString()) .Log("[CRON] ▶ Self-test: exercising all showcase routes...") // ── Section 2: Error handling ── // try-catch catches internally, circuit-breaker has fallback, // DLQ only throws on poison=true (not set by cron), // retry throws 2× then succeeds → 2 WRN lines are expected showcase behavior .WireTap("direct://demo-try-catch") .WireTap("direct://demo-circuit-breaker") .WireTap("direct://demo-retry") .WireTap("direct://demo-dead-letter") .WireTap("direct://demo-dead-letter-poison") .WireTap("direct://demo-ws-ping") .Log("[CRON] ✓ Error handling routes exercised") // ── Section 3: EIP patterns ── .WireTap("direct://demo-multicast") .WireTap("direct://demo-recipient-list") .WireTap("direct://demo-dynamic-router") .WireTap("direct://demo-loop") .WireTap("direct://demo-resequencer") .WireTap("direct://demo-enrich") .WireTap("direct://demo-idempotent") .WireTap("direct://demo-throttle") .Log("[CRON] ✓ EIP pattern routes exercised") // ── Section 5: Data & observability ── .WireTap("direct://demo-validation") .WireTap("direct://demo-marshal") .WireTap("direct://demo-observability") .WireTap("direct://demo-expressions") .Log("[CRON] ✓ Data routes exercised") // ── Section 5b: Predicate showcase ── .WireTap("direct://demo-predicates-compare") .WireTap("direct://demo-predicates-string") .WireTap("direct://demo-predicates-null") .WireTap("direct://demo-predicates-logic") .WireTap("direct://demo-predicates-string-expr") .WireTap("direct://demo-predicates-choice") .WireTap("direct://demo-predicates-jpath") .Log("[CRON] ✓ Predicate routes exercised") // ── Section 6: Transactions ── .WireTap("direct://demo-transacted") .WireTap("direct://demo-imperative-tx") .Log("[CRON] ✓ Transaction routes exercised") // ── Full pipeline — exercises HTTP→RabbitMQ→AMQP→gRPC→SQL→Kafka→File→VM→Redis→MQTT→SEDA ── // curl -X POST http://localhost:5088/api/demo -H "Content-Type: application/json" -H "mode: full" -H "priority: high" -d "{\"message\":\"cron-self-test\"}" .SetHeader("mode", "full") .SetHeader("priority", "high") .WireTap("direct://pipeline") .Log("[CRON] ✓ Full pipeline exercised (RabbitMQ→AMQP→gRPC→WMQ→SQL→Kafka→File→Redis→MQTT→WMQ→SEDA)") .Log("[CRON] ✔ Self-test complete — ALL routes exercised, zero dead ends"); } /// /// SEDA — in-memory async queue. Fire-and-forget between routes. /// Producer queues → consumer picks up asynchronously. /// private void ConfigureSedaProcessing() { From("direct://demo-seda-send") .RouteId("demo-seda-producer") .Log("[SEDA] ▶ Sending to async queue...") .To("seda://work-queue?size=500") .Log("[SEDA] ✓ Queued (fire-and-forget)"); From("seda://work-queue?concurrentConsumers=3") .RouteId("demo-seda-consumer") .Log("[SEDA-W] ▶ Processing from queue: ${body}") .Delay(TimeSpan.FromMilliseconds(50)) .Log("[SEDA-W] ◀ Done"); } /// /// Redis Pub/Sub — publish events, subscribe and process. /// private void ConfigureRedisRoutes() { From("direct://demo-redis-pub") .RouteId("demo-redis-publisher") .Log("[REDIS] ▶ Publishing to channel: ${body}") .To(RedisPub) .Log("[REDIS] ✓ Published"); From(RedisSub) .RouteId("demo-redis-subscriber") .Log("[REDIS-SUB] ▶ Received from channel: ${body}") .SetHeader("redis.receivedAt", e => DateTime.UtcNow.ToString("o")) .Log("[REDIS-SUB] ◀ Processed"); } /// /// TCP echo — raw TCP server. Echoes everything back UPPERCASED. /// private void ConfigureTcpEchoServer() { From(TcpServer) .RouteId("demo-tcp-echo") .ConvertBody() .Log("[TCP] ▶ Received: ${body}") .Process(e => e.In.Body = e.In.Body?.ToString()?.ToUpperInvariant()) .Log("[TCP] ◀ Echoing: ${body}"); } /// /// WebSocket server — listens for WS connections, echoes messages. /// private void ConfigureWebSocketServer() { From(WsServer) .RouteId("demo-websocket") .Log("[WS] ▶ WebSocket message: ${body}") .SetHeader("ws.echo", e => $"echo:{e.In.Body}") .Log("[WS] ◀ Responding: ${header.ws.echo}"); // WS ping — cron sends a message through the WS server as a client From("direct://demo-ws-ping") .RouteId("demo-ws-ping") .SetBody(e => $"{{\"ping\":\"cron\",\"ts\":\"{DateTime.UtcNow:o}\"}}") .Log("[WS-PING] → Sending to WebSocket server...") .To(WsClient) .Log("[WS-PING] ← Response: ${body}"); } /// /// MQTT Pub/Sub — IoT-style telemetry topic. /// Uses the fluent Mqtt.Publish(...)/Mqtt.Subscribe(...) URI builder. /// private void ConfigureMqttRoutes() { From("direct://demo-mqtt-pub") .RouteId("demo-mqtt-publisher") .Log("[MQTT] ▶ Publishing telemetry: ${body}") .To(Mqtt.Publish(MqttTopic).Server(Constant(MqttHost)).Port(MqttPort)) .Log("[MQTT] ✓ Published to topic"); From(Mqtt.Subscribe(MqttTopic).Server(Constant(MqttHost)).Port(MqttPort)) .RouteId("demo-mqtt-subscriber") .Log("[MQTT-SUB] ▶ Telemetry received: ${body}") .SetHeader("mqtt.ts", e => DateTime.UtcNow.ToString("o")) .Log("[MQTT-SUB] ◀ Processed"); } /// /// IBM MQ Topic Pub/Sub — enterprise messaging topic. /// Uses the fluent Wmq.Topic(...) URI builder. /// private void ConfigureWmqRoutes() { // Publisher — triggered via WireTap from the main pipeline From("direct://demo-wmq-pub") .RouteId("demo-wmq-publisher") .Log("[WMQ] ▶ Publishing to topic: ${body}") .To(Wmq.Topic("demo/events") .Host("localhost").Port(1414) .Channel("DEV.APP.SVRCONN").QueueManager("QM1") .User("app").Password("admin")) .Log("[WMQ] ✓ Published to topic"); // Subscriber From(Wmq.Topic("demo/events") .Host("localhost").Port(1414) .Channel("DEV.APP.SVRCONN").QueueManager("QM1") .User("app").Password("admin") .WaitInterval(5000)) .RouteId("demo-wmq-subscriber") .Log("[WMQ-SUB] ▶ Topic event received: ${body}") .SetHeader("wmq.ts", e => DateTime.UtcNow.ToString("o")) .Log("[WMQ-SUB] ◀ Processed"); } /// /// Slow-process route — simulates a long-running exchange for Watchdog testing. /// Timer fires every 30s, each exchange takes 180s → ~6 concurrent exchanges, /// always past the suspected threshold. Suspected after 1 min, Hung after 2 min. /// private void ConfigureSlowProcessRoute() { From("timer://slow-process?period=30000") .RouteId("demo-slow-process") .Log("[SLOW] ▶ Starting long-running operation (180s delay)...") .SetBody(e => new { kind = "slow-task", started = DateTime.UtcNow }) .Delay(TimeSpan.FromSeconds(180)) .Log("[SLOW] ◀ Long-running operation completed"); } } Path: redb-route/demo/redb.Route.Demo/manifest.json 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/demo/redb.Route.Demo/manifest.json ---- { "Name": "redb.Route.Demo", "Version": "1.0.0", "EntryPoints": ["redb.Route.Demo.dll"], "Dependencies": [] } Path: redb-route/demo/redb.Route.Demo/redb.Route.Demo.config.json 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/demo/redb.Route.Demo/redb.Route.Demo.config.json ---- { "ContextName": "route.demo", "AutoStart": true, "DemoSettings": { "PostgresConnection": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb", "HttpPort": 8080, "EnableMetrics": true }, "Redb": { "pg-test": { "Provider": "postgres", "UsePro": true, "ConnectionString": "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=redb;Pooling=true;Include Error Detail=true", "PropsSaveStrategy": "ChangeTracking", "EnsureCreated": true }, "mssql-test": { "Provider": "mssql", "UsePro": false, "ConnectionString": "Server=msdb;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;", "EnsureCreated": true } }, "RabbitMQ": { "Host": "localhost", "Port": 5672, "Username": "admin", "Password": "admin" }, "Redis": { "Host": "localhost", "Port": 6379 }, "FeatureFlags": { "EnableSqlRoutes": true, "EnableMqttRoutes": true } } Path: redb-route/demo/redb.Route.Demo/redb.Route.Demo.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/demo/redb.Route.Demo/redb.Route.Demo.csproj ---- net10.0 enable enable redb.Route.Demo true redb.Route.Demo $(MSBuildThisFileDirectory)..\..\..\redb.Tsak\src\redb.Tsak.Worker\Libs <_TpkgStaging>$(IntermediateOutputPath)tpkg <_TpkgFile>$(MSBuildThisFileDirectory)output\$(TsakModuleName).tpkg