Path: redb-route/redb.Route.Exec/ExecConsumer.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.Exec/ExecConsumer.cs ---- using System.Diagnostics; using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Exec; /// /// Scheduled exec consumer. Fires the configured command on a fixed interval (via /// ) and pushes the resulting exchange into the route pipeline. /// /// Supported schedule formats: 500ms, 30s, 5m, 1h. /// Cron expressions are intentionally not handled here — chain /// From("quartz://<cron>").To("exec://run?command=...") when cron is required. /// /// public sealed class ExecConsumer : IConsumer { private static readonly Regex IntervalPattern = new(@"^\s*(\d+)\s*(ms|s|m|h)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private readonly ExecEndpoint _endpoint; private readonly ExecEndpointOptions _options; private readonly IProcessor _processor; private CancellationTokenSource? _cts; private Task? _loop; private ExecProducer? _producer; /// Creates a scheduled exec consumer. public ExecConsumer(ExecEndpoint endpoint, ExecEndpointOptions options, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); } /// public IEndpoint? Endpoint => _endpoint; /// public Task Start(CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(_options.Schedule)) throw new InvalidOperationException( "Consumer mode for 'exec://' requires '?schedule=' (e.g. '30s', '5m', '1h'). " + "For cron expressions chain From(\"quartz://...\").To(\"exec://run?command=...\")."); if (string.IsNullOrWhiteSpace(_options.Command)) throw new InvalidOperationException( "Consumer mode for 'exec://' requires the URI 'command=' option to be set."); var interval = ParseInterval(_options.Schedule) ?? throw new InvalidOperationException( $"Schedule '{_options.Schedule}' is not a valid interval. " + "Accepted formats: '500ms', '30s', '5m', '1h'."); _producer = new ExecProducer(_endpoint, _options); _cts = CancellationTokenSource.CreateLinkedTokenSource(ct); _loop = RunLoopAsync(interval, _cts.Token); return _producer.Start(ct); } /// public async Task Stop(CancellationToken ct = default) { if (_cts is null) return; try { await _cts.CancelAsync().ConfigureAwait(false); } catch { /* idempotent */ } if (_loop is { } loop) { try { await loop.ConfigureAwait(false); } catch (OperationCanceledException) { /* expected */ } } if (_producer is not null) { try { await _producer.Stop(ct).ConfigureAwait(false); } catch { /* best-effort */ } _producer = null; } _cts.Dispose(); _cts = null; _loop = null; } private async Task RunLoopAsync(TimeSpan interval, CancellationToken ct) { using var timer = new PeriodicTimer(interval); while (!ct.IsCancellationRequested) { try { if (!await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) return; } catch (OperationCanceledException) { return; } try { await FireOnceAsync(ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } catch (Exception ex) { // The tick's own span carries the failure. Continue — one failed tick must not kill the consumer. _endpoint.RecordError(ex); } } } private async Task FireOnceAsync(CancellationToken ct) { var ctx = (_endpoint.Component as ComponentBase)?.Context; var scopeFactory = ctx?.GetServiceProvider() ?.GetService(typeof(Microsoft.Extensions.DependencyInjection.IServiceScopeFactory)) as Microsoft.Extensions.DependencyInjection.IServiceScopeFactory; var exchange = Exchange.Create(new Message(string.Empty), scopeFactory); // A tick carries no trace context: its span is a root, never a child of the activity the timer loop holds. The // run of the command (the producer's client span) and the route sit under it. using var span = RouteTelemetryExtensions.StartConsumerSpan( ctx, $"exec {Path.GetFileName(_options.Command ?? string.Empty)} receive", ActivityKind.Consumer, "process.executable.name", Path.GetFileName(_options.Command ?? string.Empty), _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "receive"); // The scheduler owns this exchange for the whole tick: dispose it in finally so its // per-exchange DI scope (and any redb connection resolved downstream) is released every // tick — otherwise each scheduled fire would leak a scope and drain the connection pool. try { if (!string.IsNullOrWhiteSpace(_options.Command)) exchange.In.Headers[ExecHeaders.Command] = _options.Command; if (!string.IsNullOrWhiteSpace(_options.Args)) exchange.In.Headers[ExecHeaders.Args] = _options.Args; await _producer!.Process(exchange, ct).ConfigureAwait(false); await _processor.Process(exchange, ct).ConfigureAwait(false); if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Our own stop is not a failure of the tick; any other cancellation is. span.Activity.RecordFailure(ex); throw; } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } internal static TimeSpan? ParseInterval(string schedule) { var m = IntervalPattern.Match(schedule); if (!m.Success) return null; if (!long.TryParse(m.Groups[1].Value, out var n) || n <= 0) return null; return m.Groups[2].Value.ToLowerInvariant() switch { "ms" => TimeSpan.FromMilliseconds(n), "s" => TimeSpan.FromSeconds(n), "m" => TimeSpan.FromMinutes(n), "h" => TimeSpan.FromHours(n), _ => null }; } }