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 => "- Widget
- Gadget
")
.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