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