Path: redb-route/redb.Route.Ldap/LdapConsumer.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.Ldap/LdapConsumer.cs
----
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Novell.Directory.Ldap;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using NovellEntry = Novell.Directory.Ldap.LdapEntry;
namespace redb.Route.Ldap;
///
/// LDAP consumer. Polls the directory for changes using configurable change tracking.
/// Supports ModifyTimestamp (universal) and USN (Active Directory) modes.
/// Optionally detects deletions by comparing known DNs with current results.
///
internal sealed class LdapConsumer : DrainableConsumer
{
private readonly LdapEndpoint _endpoint;
private readonly LdapEndpointOptions _options;
private readonly HashSet _knownDns = new(StringComparer.OrdinalIgnoreCase);
private readonly string _baseFilter;
private int _pollsSinceFullSync;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"ldap:WATCH:{_endpoint.BaseDn}";
/// Number of change events delivered.
public long ProcessedCount { get; private set; }
/// Creates an LDAP consumer.
public LdapConsumer(LdapEndpoint endpoint, IProcessor processor, LdapEndpointOptions options)
: base(processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_baseFilter = _options.Filter?.Resolve(new Exchange()) ?? "(objectClass=*)";
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
var mode = _options.ParseChangeTrackingMode();
if (mode == LdapChangeTrackingMode.Persistent)
throw new NotSupportedException(
"Persistent Search is not yet implemented. Use ModifyTimestamp or Usn mode.");
string? marker = _options.InitialLoad ? null : await GetInitialMarkerAsync(mode, processingCt).ConfigureAwait(false);
Logger?.LogInformation("LDAP consumer started: baseDn={BaseDn}, mode={Mode}, initialLoad={InitialLoad}, detectDeletions={DetectDeletions}",
_endpoint.BaseDn, mode, _options.InitialLoad, _options.DetectDeletions);
while (!pollCt.IsCancellationRequested)
{
try
{
var (entries, newMarker) = await PollChangesAsync(mode, marker, processingCt)
.ConfigureAwait(false);
foreach (var entry in entries)
{
var exchange = CreateExchange(entry);
await ProcessTracedAsync(exchange, processingCt).ConfigureAwait(false);
ProcessedCount++;
}
// Detect deletions if enabled
if (_options.DetectDeletions)
await DetectDeletionsAsync(entries, processingCt).ConfigureAwait(false);
if (newMarker != null)
marker = newMarker;
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "LDAP poll failed for {BaseDn}", _endpoint.BaseDn);
_endpoint.RecordError(ex);
}
try
{
await Task.Delay(_options.PollInterval, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
Logger?.LogInformation("LDAP consumer stopped: baseDn={BaseDn}, processed={Count}",
_endpoint.BaseDn, ProcessedCount);
}
///
/// inside the span of the entry. A directory entry carries no
/// trace context, so the span is a root, never a child of the activity the poll loop holds. A failed route marks it,
/// whether the failure stays on the exchange or escapes the pipeline; our own stop does not.
///
private async Task ProcessTracedAsync(IExchange exchange, CancellationToken ct)
{
using var span = RouteTelemetryExtensions.StartConsumerSpan