Path: redb-route/redb.Route.Elasticsearch/ElasticsearchConsumer.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.Elasticsearch/ElasticsearchConsumer.cs
----
using ActivityKind = System.Diagnostics.ActivityKind;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Elastic.Clients.Elasticsearch;
using Elastic.Clients.Elasticsearch.Core.Search;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch consumer — polls an index using the Search API (or Scroll API for large result sets).
/// Extends for graceful two-CTS shutdown.
///
/// Supports search_after deep pagination, scroll API (legacy),
/// source filtering, sort ordering, delete-after-read, and query DSL.
///
///
internal sealed class ElasticsearchConsumer : DrainableConsumer
{
private readonly ElasticsearchEndpoint _endpoint;
private readonly ElasticsearchEndpointOptions _options;
private ElasticsearchClient? _client;
// search_after state: sort values from last hit of previous poll
private IReadOnlyCollection? _lastSortValues;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"es://{_endpoint.IndexName}";
internal ElasticsearchConsumer(ElasticsearchEndpoint endpoint, IProcessor processor,
ElasticsearchEndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
}
///
protected override async Task OnStarting(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false);
while (!pollCt.IsCancellationRequested)
{
try
{
if (!string.IsNullOrEmpty(_options.ScrollTimeout))
await PollWithScrollAsync(processingCt).ConfigureAwait(false);
else
await PollWithSearchAsync(processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "Elasticsearch consumer poll error on index {Index}", _endpoint.IndexName);
_endpoint.RecordError(ex);
}
try
{
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
// ═══════════════════════════════════════════════════════════════════
// SEARCH (standard pagination via search_after)
// ═══════════════════════════════════════════════════════════════════
private async Task PollWithSearchAsync(CancellationToken ct)
{
var response = await _client!.SearchAsync(s =>
{
s.Indices(_endpoint.IndexName);
s.Size(_options.Size);
s.TrackTotalHits(new TrackHits(_options.TrackTotalHits));
ConfigureQuery(s);
ConfigureSort(s);
ConfigureSourceFilter(s);
if (_lastSortValues is { Count: > 0 })
s.SearchAfter(_lastSortValues.ToList());
}, ct).ConfigureAwait(false);
if (!response.IsValidResponse)
{
Logger?.LogWarning("Elasticsearch search failed: {Info}", response.DebugInformation);
return;
}
await ProcessHitsAsync(response.Hits, ct).ConfigureAwait(false);
// Update search_after cursor from last hit
if (response.Hits.Count > 0)
{
var lastHit = response.Hits.Last();
_lastSortValues = lastHit.Sort;
}
}
// ═══════════════════════════════════════════════════════════════════
// SCROLL (for large result sets — deprecated in ES 8.x but supported)
// ═══════════════════════════════════════════════════════════════════
private async Task PollWithScrollAsync(CancellationToken ct)
{
// Initial scroll search
var searchResponse = await _client!.SearchAsync(s =>
{
s.Indices(_endpoint.IndexName);
s.Size(_options.Size);
s.Scroll(_options.ScrollTimeout);
s.TrackTotalHits(new TrackHits(_options.TrackTotalHits));
ConfigureQuery(s);
ConfigureSort(s);
ConfigureSourceFilter(s);
}, ct).ConfigureAwait(false);
if (!searchResponse.IsValidResponse)
{
Logger?.LogWarning("Elasticsearch scroll search failed: {Info}", searchResponse.DebugInformation);
return;
}
string? scrollId = searchResponse.ScrollId?.ToString();
try
{
// Process first page
await ProcessHitsAsync(searchResponse.Hits, ct).ConfigureAwait(false);
int lastHitCount = searchResponse.Hits.Count;
// Continue scrolling while there are hits
while (lastHitCount > 0 && !ct.IsCancellationRequested && scrollId is not null)
{
var scrollResponse = await _client.ScrollAsync(s =>
{
s.ScrollId(scrollId);
s.Scroll(_options.ScrollTimeout);
}, ct).ConfigureAwait(false);
if (!scrollResponse.IsValidResponse || scrollResponse.Hits.Count == 0)
break;
scrollId = scrollResponse.ScrollId?.ToString();
await ProcessHitsAsync(scrollResponse.Hits, ct).ConfigureAwait(false);
lastHitCount = scrollResponse.Hits.Count;
}
}
finally
{
// Clear scroll context
if (scrollId is not null)
{
try
{
await _client.ClearScrollAsync(s => s.ScrollId(new[] { scrollId }), ct).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Failed to clear scroll context {ScrollId}", scrollId);
}
}
}
}
// ═══════════════════════════════════════════════════════════════════
// HIT PROCESSING
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessHitsAsync(IReadOnlyCollection> hits, CancellationToken ct)
{
foreach (var hit in hits)
{
if (ct.IsCancellationRequested) break;
// Create exchange with document body
var bodyJson = hit.Source?.ToJsonString() ?? "{}";
var message = new Message { Body = bodyJson, ContentType = "application/json" };
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
// Set headers
var headers = exchange.In.Headers;
headers[ElasticsearchHeaders.IndexName] = hit.Index;
headers[ElasticsearchHeaders.DocumentId] = hit.Id;
if (hit.Version is not null)
headers[ElasticsearchHeaders.Version] = hit.Version;
if (hit.SeqNo is not null)
headers[ElasticsearchHeaders.SequenceNumber] = hit.SeqNo;
if (hit.PrimaryTerm is not null)
headers[ElasticsearchHeaders.PrimaryTerm] = hit.PrimaryTerm;
if (hit.Score is not null)
headers[ElasticsearchHeaders.Score] = hit.Score;
if (hit.Sort is { Count: > 0 })
headers[ElasticsearchHeaders.SortValues] = JsonSerializer.Serialize(hit.Sort);
// Pipeline statistics are the core StatisticsProcessor's (ownership audit).
await ProcessTracedAsync(exchange, ct).ConfigureAwait(false);
// Post-processing: delete after read
if (_options.DeleteAfterRead && hit.Id is not null &&
(exchange.Exception == null || exchange.ExceptionHandled))
{
await _client!.DeleteAsync(_endpoint.IndexName, hit.Id, ct).ConfigureAwait(false);
}
}
}
///
/// inside the span of the hit. A hit 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