Path: redb-route/redb.Route.Elasticsearch/ElasticsearchComponent.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/ElasticsearchComponent.cs
----
using Elastic.Clients.Elasticsearch;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch transport component for redb.Route.
/// Schemes: elasticsearch, es.
///
/// URI format: elasticsearch://index-name?nodes=http://localhost:9200
///
///
/// Short alias: es://index-name?nodes=http://localhost:9200
///
///
/// With operation: es:Search:index-name?nodes=http://localhost:9200&query={"match_all":{}}
///
///
public sealed class ElasticsearchComponent : ComponentBase
{
///
public override string Scheme => "elasticsearch";
///
public override IReadOnlyList AlternateSchemes => ["es"];
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new ElasticsearchEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new ElasticsearchEndpoint(uri, this, options);
}
}
///
/// Elasticsearch endpoint. Creates either a consumer (polling search)
/// or a producer (index/bulk/search/get/update/delete/count/exists).
///
/// The path part of the URI is parsed as [OPERATION:]index-name.
/// When an operation prefix is present (e.g. es:Search:my-index),
/// the producer dispatches that specific operation.
///
///
public sealed class ElasticsearchEndpoint : EndpointBase
{
private ElasticsearchClient? _client;
private readonly SemaphoreSlim _clientLock = new(1, 1);
/// Parsed operation type (default: Index for producer).
public ElasticsearchOperationType OperationType { get; }
/// Index name parsed from the URI path.
public string IndexName { get; }
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options (exposed for consumer/producer).
internal ElasticsearchEndpointOptions EndpointOptions => Options;
/// Creates an Elasticsearch endpoint.
public ElasticsearchEndpoint(EndpointUri uri, ElasticsearchComponent component, ElasticsearchEndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
(OperationType, IndexName) = ParsePath(uri.Path);
}
///
public override IProducer CreateProducer() => new ElasticsearchProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new ElasticsearchConsumer(this, processor, Options);
}
/// Gets or creates a shared .
internal async Task GetOrCreateClientAsync(CancellationToken ct = default)
{
if (_client is not null)
return _client;
await _clientLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_client is not null)
return _client;
var (client, nodes) = BuildClient();
_client = client;
// The nodes the client was built with: the connection factory's when one is named, not the endpoint's
// default. They may be a comma-separated list of URLs carrying userinfo credentials
// (http://user:pass@host); each is sanitized before logging.
var sanitizedNodes = string.Join(",", nodes.Split(',').Select(EndpointUri.Sanitize));
Logger?.LogInformation("Elasticsearch client created: Nodes={Nodes}, Index={Index}, ConnectionFactory={ConnectionFactory}",
sanitizedNodes, IndexName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory);
return _client;
}
finally
{
_clientLock.Release();
}
}
///
public override Task Stop(CancellationToken ct = default)
{
// ElasticsearchClient uses HttpClient internally — no explicit dispose needed
_client = null;
_clientLock.Dispose();
Logger?.LogInformation("Elasticsearch endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
return base.Stop(ct);
}
// ── Helpers ──
/// The client, and the nodes it connects to (for the log).
private (ElasticsearchClient Client, string Nodes) BuildClient()
{
// 1. Named factory from registry — a set-but-unknown name fails loud, never a
// silent fallback to URI parameters.
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
{
var context = (Component as ElasticsearchComponent)?.Context;
var registryFactory = context.GetRequiredFromRegistry(
Options.ConnectionFactory);
Logger?.LogDebug("Elasticsearch: using ConnectionFactory '{Name}' from registry",
Options.ConnectionFactory);
return (registryFactory.Build(), registryFactory.Nodes);
}
// 2. Build from options
var factory = new ElasticsearchConnectionFactory
{
Nodes = Options.Nodes,
ApiKey = Options.ApiKey,
Username = Options.Username,
Password = Options.Password,
CertificateFingerprint = Options.CertificateFingerprint,
EnableDebugMode = Options.EnableDebugMode,
RequestTimeout = Options.RequestTimeout,
PingTimeout = Options.PingTimeout,
DeadTimeout = Options.DeadTimeout,
MaxDeadTimeout = Options.MaxDeadTimeout,
MaxRetries = Options.MaxRetries,
};
return (factory.Build(), factory.Nodes);
}
private static (ElasticsearchOperationType Operation, string IndexName) ParsePath(string path)
{
// Path may be "OPERATION:index-name" or just "index-name"
var colonIdx = path.IndexOf(':');
if (colonIdx > 0)
{
var opPart = path[..colonIdx];
var indexPart = path[(colonIdx + 1)..];
if (Enum.TryParse(opPart, ignoreCase: true, out var op))
return (op, indexPart);
}
return (ElasticsearchOperationType.Index, path);
}
}