Path: redb-route/redb.Route/ControlBus/ControlBusComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/ControlBus/ControlBusComponent.cs ---- using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.ControlBus; /// The control-bus command family. public enum ControlBusCommand { /// controlbus:route — act on a route by id (Apache Camel parity). Route, /// controlbus:language:<lang> — evaluate an expression against the context (Camel parity). Language, /// controlbus:notify — consume route/context lifecycle events as messages (redb extension beyond Camel). Notify } /// Exchange header keys set by the controlbus:notify event consumer. public static class ControlBusHeaders { /// Event name: RouteStarted / RouteStopped / RouteSuspending / RouteErrored / ContextStarting / ContextStarted / ContextStopping / ContextStopped / ExchangeTimedOut / ConnectionLost / ReconnectFailed / ConnectionRestored. public const string Event = "controlbus.event"; /// Affected route id (route/exchange events; connection events of a route's consumer endpoint). public const string RouteId = "controlbus.routeId"; /// Event timestamp (UTC). public const string Timestamp = "controlbus.timestamp"; /// Error message (RouteErrored; on connection events the masked failure, absent on ConnectionRestored). public const string Error = "controlbus.error"; /// Exchange id (ExchangeTimedOut only). public const string ExchangeId = "controlbus.exchangeId"; /// Elapsed milliseconds (ExchangeTimedOut only). public const string ElapsedMs = "controlbus.elapsedMs"; /// Connection events: the endpoint whose connection changed, short form, secrets masked. public const string Endpoint = "controlbus.endpoint"; /// Connection events: which connection of the endpoint (the supervisor's name). public const string Connection = "controlbus.connection"; /// Connection events: Connected, Recovering or Disconnected after the change. public const string ConnectionState = "controlbus.connectionState"; /// Connection events: failed reconnect attempts since the loss (0 on ConnectionLost). public const string Attempt = "controlbus.attempt"; /// Connection events: milliseconds until the next attempt; absent on ConnectionRestored. public const string NextDelayMs = "controlbus.nextDelayMs"; /// Connection events: milliseconds the connection has been lost; on ConnectionRestored, how long it was. public const string OutageMs = "controlbus.outageMs"; /// Connection events: how many times this connection was restored since it started. public const string Reconnects = "controlbus.reconnects"; } /// Actions for the route command (Apache Camel parity). public enum ControlBusAction { /// Start the route. Start, /// Stop the route (consumer removed; route stays registered). Stop, /// Suspend the route. Same effect as in redb (route stays registered). Suspend, /// Resume a stopped/suspended route (policy-aware). Resume, /// Stop then start after restartDelay. Restart, /// Return the route status on the message body. Status, /// Return route statistics (all routes when routeId is omitted) on the message body. Stats, /// Stop the route and mark it failed (Errored). Fail } // ── Component ──────────────────────────────────────────────────────────────── /// /// Control Bus EIP component (Apache Camel controlbus: parity). Producer-only — you send to it /// to manage routes at runtime. Modelled on the . /// /// URI forms: /// /// controlbus:route?routeId=foo&action=start — act on a route. /// controlbus:language:simple — evaluate the message body as an expression. /// /// Parameters: routeId (or current = the sending route), action /// (start|stop|suspend|resume|restart|status|stats|fail), async (default false), restartDelay /// (ms, default 1000), loggingLevel. Registered out of the box under the controlbus scheme. /// Per-context, like Camel: for cross-context control, send over direct-vm/vm to the target /// context and run controlbus: there. /// /// public sealed class ControlBusComponent : ComponentBase { /// public override string Scheme => "controlbus"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new ControlBusEndpointOptions(); options.BindFromUri(uri.RawParameters); // Command from the URI path: "route" (default), "language[:lang]", or "notify" / "event". var path = uri.Path ?? string.Empty; if (path.StartsWith("language", StringComparison.OrdinalIgnoreCase)) { options.Command = ControlBusCommand.Language; var colon = path.IndexOf(':'); options.Language = colon >= 0 && colon + 1 < path.Length ? path[(colon + 1)..] : "simple"; } else if (path.StartsWith("notify", StringComparison.OrdinalIgnoreCase) || path.StartsWith("event", StringComparison.OrdinalIgnoreCase)) { options.Command = ControlBusCommand.Notify; } else { options.Command = ControlBusCommand.Route; } options.Validate(); return new ControlBusEndpoint(uri, this, options); } } // ── Options ────────────────────────────────────────────────────────────────── /// Options for the control-bus endpoint. public sealed class ControlBusEndpointOptions : EndpointOptions { /// Command family (set from the URI path). public ControlBusCommand Command { get; set; } = ControlBusCommand.Route; /// Target route id. current resolves to the sending route. Optional for stats. public string? RouteId { get; set; } /// Action for the route command. public ControlBusAction? Action { get; set; } /// Perform the action asynchronously (fire-and-forget). Default: false. public bool Async { get; set; } /// Delay in ms between stop and start on restart. Default: 1000. public int RestartDelay { get; set; } = 1000; /// Logging level for the action. Default: Info. public string LoggingLevel { get; set; } = "Info"; /// Expression language name for the language command (e.g. simple). public string? Language { get; set; } /// /// notify command only: comma-separated event-name filter (e.g. RouteStarted,RouteStopped). /// Empty = all events. Combine with to filter to one route. /// public string? Events { get; set; } /// public override void Validate() { switch (Command) { case ControlBusCommand.Route: if (Action is null) throw new ArgumentException("controlbus:route requires an 'action' (start|stop|suspend|resume|restart|status|stats|fail)."); // routeId is required for everything except stats (stats without routeId = whole context). if (Action != ControlBusAction.Stats && string.IsNullOrWhiteSpace(RouteId)) throw new ArgumentException($"controlbus:route action '{Action}' requires a 'routeId' (or 'current')."); break; case ControlBusCommand.Language: if (string.IsNullOrWhiteSpace(Language)) throw new ArgumentException("controlbus:language requires a language name, e.g. controlbus:language:simple."); break; case ControlBusCommand.Notify: // No required options — routeId and events are optional filters. break; } } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// Endpoint that runs a control-bus action when the route sends to it. public sealed class ControlBusEndpoint : EndpointBase { private readonly ControlBusEndpointOptions _options; internal ControlBusEndpoint(EndpointUri uri, ControlBusComponent component, ControlBusEndpointOptions options) : base(uri, component, options) => _options = options; internal ControlBusEndpointOptions ControlOptions => _options; /// public override IProducer CreateProducer() => _options.Command == ControlBusCommand.Notify ? throw new NotSupportedException( "controlbus:notify is a consumer (from) — it emits lifecycle events. Use From(\"controlbus:notify\").") : new ControlBusProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => _options.Command == ControlBusCommand.Notify ? new ControlBusEventConsumer(this, processor) : throw new NotSupportedException( "controlbus:route / controlbus:language are producer-only. Use .To(\"controlbus:...\") or .ControlBus(...); " + "to consume lifecycle events use From(\"controlbus:notify\")."); } // ── Producer ───────────────────────────────────────────────────────────────── /// Producer that dispatches the control-bus action against the route context. public sealed class ControlBusProducer : IProducer { private readonly ControlBusEndpoint _endpoint; internal ControlBusProducer(ControlBusEndpoint endpoint) => _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var context = (_endpoint.Component as ComponentBase)?.Context as RouteContext ?? throw new InvalidOperationException("Control Bus requires a RouteContext."); var o = _endpoint.ControlOptions; using var span = RouteTelemetryExtensions.StartTransportSpan( $"controlbus {o.Command}:{o.Action?.ToString() ?? o.Language}", ActivityKind.Client, "messaging.system", "controlbus", _endpoint.Uri.NormalizedKey, o.RouteId, o.Action?.ToString()); if (o.Command == ControlBusCommand.Language) { // Evaluate a ${...} template against the exchange and return the result. // Boundary vs Camel: our engine is a template evaluator, not an OGNL that can invoke // context methods; lifecycle control is done via the 'route' command above. var template = exchange.In.Body?.ToString() ?? string.Empty; exchange.In.Body = ((EndpointOptions)o).ResolveOption(template, exchange); return; } var routeId = o.RouteId; if (string.Equals(routeId, "current", StringComparison.OrdinalIgnoreCase)) routeId = exchange.RouteId; switch (o.Action) { case ControlBusAction.Status: exchange.In.Body = context.GetRoute(routeId!)?.Status.ToString() ?? "NotFound"; return; case ControlBusAction.Stats: exchange.In.Body = BuildStats(context, routeId); return; } Func op = o.Action switch { ControlBusAction.Start => () => context.StartRoute(routeId!, ct), ControlBusAction.Stop or ControlBusAction.Suspend => () => context.StopRoute(routeId!, ct), ControlBusAction.Resume => () => context.ResumeRoute(routeId!, ct), ControlBusAction.Restart => async () => { await context.StopRoute(routeId!).ConfigureAwait(false); if (o.RestartDelay > 0) await Task.Delay(o.RestartDelay).ConfigureAwait(false); await context.StartRoute(routeId!).ConfigureAwait(false); }, ControlBusAction.Fail => async () => { await context.StopRoute(routeId!).ConfigureAwait(false); if (context.GetRoute(routeId!) is { } r) r.Status = RouteStatus.Errored; }, _ => throw new InvalidOperationException($"Unsupported control-bus action '{o.Action}'.") }; // Stopping the current route synchronously would deadlock (this exchange is in-flight on it), // so self-targeting stop-like actions are always deferred, matching Camel's async guidance. var stopsRoute = o.Action is ControlBusAction.Stop or ControlBusAction.Suspend or ControlBusAction.Restart or ControlBusAction.Fail; var selfTarget = string.Equals(routeId, exchange.RouteId, StringComparison.OrdinalIgnoreCase); if (o.Async || (stopsRoute && selfTarget)) _ = Task.Run(op, CancellationToken.None); else await op().ConfigureAwait(false); } private static string BuildStats(RouteContext context, string? routeId) { var routes = routeId is null ? context.Routes : context.GetRoute(routeId) is { } one ? new[] { one } : System.Array.Empty(); var sb = new StringBuilder(); sb.Append(""); foreach (var r in routes) { sb.Append(" 0 } lastError) sb.Append(" lastError=\"").Append(Escape(lastError)).Append('"'); if (s.LastRefusalMessage is { Length: > 0 } lastRefusal) sb.Append(" lastRefusal=\"").Append(Escape(lastRefusal)).Append('"'); } sb.Append("/>"); } sb.Append(""); return sb.ToString(); } /// /// Attribute-escapes free text. Route ids and error messages are arbitrary strings; a quote or /// an angle bracket appended raw would corrupt the document for whoever parses it downstream. /// private static string Escape(string value) => System.Security.SecurityElement.Escape(value); /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } // ── Event consumer (redb extension beyond Camel) ───────────────────────────── /// /// Consumer for controlbus:notify: emits route/context lifecycle events as exchanges into the route, /// so you can react to them with the full EIP pipeline (filter, route, alert) instead of a callback. /// Backed by (redb's equivalent of Camel's EventNotifier SPI); Camel /// has no such consumer, so this goes beyond parity. Optional filters: routeId (one route) and /// events (comma-separated event names). Events are dispatched off the lifecycle-notification thread /// so a slow reaction never stalls route start/stop. /// public sealed class ControlBusEventConsumer : IConsumer, IRouteLifecycleListener { private readonly ControlBusEndpoint _endpoint; private readonly IProcessor _processor; private readonly string? _routeFilter; private readonly HashSet? _eventFilter; private readonly Microsoft.Extensions.Logging.ILogger? _logger; private int _registered; private volatile bool _active; internal ControlBusEventConsumer(ControlBusEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); var o = endpoint.ControlOptions; _routeFilter = string.IsNullOrWhiteSpace(o.RouteId) ? null : o.RouteId; _eventFilter = string.IsNullOrWhiteSpace(o.Events) ? null : new HashSet(o.Events!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public IEndpoint Endpoint => _endpoint; /// public Task Start(CancellationToken ct = default) { // Register with the context once (no RemoveLifecycleListener API); toggle emission with _active // so a restart does not double-register and a stop simply goes quiet. if (Interlocked.Exchange(ref _registered, 1) == 0) (_endpoint.Component as ComponentBase)?.Context?.AddLifecycleListener(this); _active = true; return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _active = false; return Task.CompletedTask; } // ── IRouteLifecycleListener → exchanges ── Task IRouteLifecycleListener.OnRouteStarted(string routeId, CancellationToken ct) { Emit("RouteStarted", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteStopped(string routeId, CancellationToken ct) { Emit("RouteStopped", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteSuspending(string routeId, CancellationToken ct) { Emit("RouteSuspending", routeId); return Task.CompletedTask; } Task IRouteLifecycleListener.OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { Emit("RouteErrored", routeId, m => m.Headers[ControlBusHeaders.Error] = ex.Message); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStarting(IRouteContext context, CancellationToken ct) { Emit("ContextStarting", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStarted(IRouteContext context, CancellationToken ct) { Emit("ContextStarted", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStopping(IRouteContext context, CancellationToken ct) { Emit("ContextStopping", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnContextStopped(IRouteContext context, CancellationToken ct) { Emit("ContextStopped", null); return Task.CompletedTask; } Task IRouteLifecycleListener.OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { Emit("ExchangeTimedOut", routeId, m => { m.Headers[ControlBusHeaders.ExchangeId] = exchangeId; m.Headers[ControlBusHeaders.ElapsedMs] = elapsed.TotalMilliseconds; }); return Task.CompletedTask; } Task IRouteLifecycleListener.OnConnectionEvent(ConnectionEvent e, CancellationToken ct) { var eventName = e.Kind switch { ConnectionEventKind.Lost => "ConnectionLost", ConnectionEventKind.AttemptFailed => "ReconnectFailed", _ => "ConnectionRestored", }; Emit(eventName, e.RouteId, m => { m.Headers[ControlBusHeaders.Timestamp] = e.Time; m.Headers[ControlBusHeaders.Endpoint] = e.Endpoint; m.Headers[ControlBusHeaders.Connection] = e.Connection; m.Headers[ControlBusHeaders.ConnectionState] = e.State.ToString(); m.Headers[ControlBusHeaders.Attempt] = e.Attempt; m.Headers[ControlBusHeaders.OutageMs] = e.Outage.TotalMilliseconds; m.Headers[ControlBusHeaders.Reconnects] = e.Reconnects; if (e.NextDelay is { } next) m.Headers[ControlBusHeaders.NextDelayMs] = next.TotalMilliseconds; if (e.ErrorMessage is { } error) m.Headers[ControlBusHeaders.Error] = error; }); return Task.CompletedTask; } private void Emit(string eventName, string? routeId, Action? decorate = null) { if (!_active) return; if (_eventFilter is not null && !_eventFilter.Contains(eventName)) return; // Route filter: when set, route-scoped events must match; context events (no routeId) are skipped. if (_routeFilter is not null && !string.Equals(routeId, _routeFilter, StringComparison.OrdinalIgnoreCase)) return; var message = new Message(eventName); message.Headers[ControlBusHeaders.Event] = eventName; if (routeId is not null) message.Headers[ControlBusHeaders.RouteId] = routeId; message.Headers[ControlBusHeaders.Timestamp] = DateTimeOffset.UtcNow; decorate?.Invoke(message); var exchange = Exchange.Create(message, _endpoint.ScopeFactory); // Off the lifecycle-notification thread: a slow reaction must not stall route start/stop, // and running the route pipeline reentrantly inside Start()/Stop() would be unsafe. _ = Task.Run(async () => { try { await _processor.Process(exchange).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "controlbus:notify handler failed for event {Event}", eventName); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } }); } }