Bundle: redb-route / tests/redb.Route.Tests.Elasticsearch (tests.redb.Route.Tests.Elasticsearch.txt), 9 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchClientLogTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchClientLogTests.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Elasticsearch;
using redb.Route.Tests.Cluster;
namespace redb.Route.Tests.Elasticsearch;
///
/// The "client created" log names the nodes the client was built with: a connection factory's, not the endpoint's
/// default Nodes (http://localhost:9200), which a user then took for the address in use.
///
public sealed class ElasticsearchClientLogTests
{
[Fact]
public async Task ClientCreated_WithAConnectionFactory_LogsTheFactorysNodes()
{
var capture = new CapturingLoggerProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug));
await using var context = new RouteContext(loggerFactory: loggerFactory);
context.AddComponent(new ElasticsearchComponent());
context.AddToRegistry("cluster", new ElasticsearchConnectionFactory { Nodes = "http://es-a.internal:9201,http://es-b.internal:9201" });
var endpoint = (ElasticsearchEndpoint)context.GetEndpoint("elasticsearch://orders?connectionFactory=cluster");
await endpoint.GetOrCreateClientAsync();
var created = capture.Entries.Single(e => e.Message.StartsWith("Elasticsearch client created", StringComparison.Ordinal)).Message;
created.Should().Contain("http://es-a.internal:9201").And.Contain("http://es-b.internal:9201").And.Contain("cluster");
created.Should().NotContain("localhost:9200", "that is the endpoint's default, not what the client connects to");
}
[Fact]
public async Task ClientCreated_FromTheUri_LogsTheUrisNodes_WithoutCredentials()
{
var capture = new CapturingLoggerProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug));
await using var context = new RouteContext(loggerFactory: loggerFactory);
context.AddComponent(new ElasticsearchComponent());
var endpoint = (ElasticsearchEndpoint)context.GetEndpoint("elasticsearch://orders?nodes=http://user:secret@es-c.internal:9202");
await endpoint.GetOrCreateClientAsync();
var created = capture.Entries.Single(e => e.Message.StartsWith("Elasticsearch client created", StringComparison.Ordinal)).Message;
created.Should().Contain("es-c.internal:9202").And.NotContain("secret");
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchConsumerUnitTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchConsumerUnitTests.cs
----
using System.Reflection;
using System.Text;
using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Elasticsearch;
namespace redb.Route.Tests.Elasticsearch;
///
/// The Elasticsearch consumer against an in-memory transport, no server: a polled hit runs in an exchange with its own
/// DI scope, as every other consumer's message does, and a failed poll is recorded on the endpoint with its text.
///
public sealed class ElasticsearchConsumerUnitTests
{
private const string Uri = "elasticsearch://orders?delay=100&initialDelay=0";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
private const string OneHit =
"{\"took\":1,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1,\"skipped\":0,\"failed\":0}," +
"\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"},\"max_score\":1.0," +
"\"hits\":[{\"_index\":\"orders\",\"_id\":\"1\",\"_score\":1.0,\"_source\":{\"v\":1},\"sort\":[1]}]}}";
private sealed class Marker;
private static Dictionary> ProductHeader() =>
new() { ["x-elastic-product"] = ["Elasticsearch"] };
private static void UseClient(ElasticsearchEndpoint endpoint, ElasticsearchClient client) =>
typeof(ElasticsearchEndpoint).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(endpoint, client);
[Fact]
public async Task A_polled_hit_runs_in_an_exchange_with_its_own_DI_scope()
{
var services = new ServiceCollection().AddScoped().BuildServiceProvider();
await using var context = new RouteContext(services);
context.AddComponent(new ElasticsearchComponent());
var endpoint = (ElasticsearchEndpoint)context.GetEndpoint(Uri);
UseClient(endpoint, new ElasticsearchClient(new ElasticsearchClientSettings(
new InMemoryRequestInvoker(Encoding.UTF8.GetBytes(OneHit), 200, null, "application/vnd.elasticsearch+json; compatible-with=8", ProductHeader()))));
var scoped = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
context.AddRoutes(r => r.From(Uri).Process(e => scoped.TrySetResult(e.ServiceProvider?.GetService() is not null)));
await context.Start();
var hadScope = await scoped.Task.WaitAsync(Wait);
hadScope.Should().BeTrue("the consumer creates the exchange with the endpoint's scope factory");
}
[Fact]
public async Task A_failed_poll_is_recorded_with_its_text()
{
await using var context = new RouteContext();
context.AddComponent(new ElasticsearchComponent());
var endpoint = (ElasticsearchEndpoint)context.GetEndpoint(Uri);
var settings = new ElasticsearchClientSettings(new InMemoryRequestInvoker(
null, 500, new HttpRequestException("search refused by the test"), "application/vnd.elasticsearch+json; compatible-with=8", ProductHeader()))
.ThrowExceptions();
UseClient(endpoint, new ElasticsearchClient(settings));
context.AddRoutes(r => r.From(Uri).Process(_ => { }));
await context.Start();
var deadline = DateTime.UtcNow + Wait;
while (endpoint.Errors == 0 && DateTime.UtcNow < deadline)
await Task.Delay(20);
endpoint.Errors.Should().BeGreaterThan(0, "the failed poll is recorded on the endpoint");
endpoint.LastErrorMessage.Should().NotBeNullOrEmpty("the dashboard shows what failed");
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchDslTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchDslTests.cs
----
using redb.Route.Core;
using redb.Route.Elasticsearch;
using EsDsl = redb.Route.Elasticsearch.Es;
namespace redb.Route.Tests.Elasticsearch;
public sealed class ElasticsearchDslTests
{
[Fact]
public void Index_GeneratesBasicUri()
{
string uri = EsDsl.Index("my-index");
uri.Should().Be("elasticsearch://my-index");
}
[Fact]
public void Index_WithOperation_GeneratesOperationUri()
{
string uri = EsDsl.Index("my-index", ElasticsearchOperationType.Search);
uri.Should().Be("elasticsearch://Search:my-index");
}
[Fact]
public void BuildShort_GeneratesEsScheme()
{
string uri = EsDsl.Index("my-index").BuildShort();
uri.Should().Be("es://my-index");
}
[Fact]
public void Builder_FullConfig_GeneratesCompleteUri()
{
string uri = EsDsl.Index("my-index")
.Nodes("http://localhost:9200")
.ApiKey("base64key")
.Refresh("wait_for")
.Pipeline("my-pipeline")
.Routing("shard-1");
uri.Should().Contain("elasticsearch://my-index?");
uri.Should().Contain("nodes=http");
uri.Should().Contain("apiKey=base64key");
uri.Should().Contain("refresh=wait_for");
uri.Should().Contain("pipeline=my-pipeline");
uri.Should().Contain("routing=shard-1");
}
[Fact]
public void Builder_ConsumerOptions_GeneratesUri()
{
string uri = EsDsl.Index("logs")
.Nodes("http://localhost:9200")
.Query("{\"match_all\":{}}")
.Sort("timestamp:desc")
.Size(50)
.Delay(10_000)
.InitialDelay(2000)
.DeleteAfterRead()
.TrackTotalHits()
.SourceIncludes("title,author")
.SourceExcludes("large_blob");
uri.Should().Contain("query=%7B");
uri.Should().Contain("sort=timestamp%3Adesc");
uri.Should().Contain("size=50");
uri.Should().Contain("delay=10000");
uri.Should().Contain("initialDelay=2000");
uri.Should().Contain("deleteAfterRead=true");
uri.Should().Contain("trackTotalHits=true");
uri.Should().Contain("sourceIncludes=title%2Cauthor");
uri.Should().Contain("sourceExcludes=large_blob");
}
[Fact]
public void Builder_BulkOptions_GeneratesUri()
{
string uri = EsDsl.Index("data", ElasticsearchOperationType.Bulk)
.Nodes("http://localhost:9200")
.BulkSize(500)
.Refresh("wait_for");
uri.Should().Contain("elasticsearch://Bulk:data?");
uri.Should().Contain("bulkSize=500");
uri.Should().Contain("refresh=wait_for");
}
[Fact]
public void Builder_ConnectionOptions_GeneratesUri()
{
string uri = EsDsl.Index("secure")
.Nodes("https://node1:9200,https://node2:9200")
.Username("elastic")
.Password("secret")
.CertificateFingerprint("abc123")
.RequestTimeout(60_000)
.PingTimeout(5000)
.MaxRetries(5)
.DebugMode();
uri.Should().Contain("username=elastic");
uri.Should().Contain("password=secret");
uri.Should().Contain("certificateFingerprint=abc123");
uri.Should().Contain("requestTimeout=60000");
uri.Should().Contain("pingTimeout=5000");
uri.Should().Contain("maxRetries=5");
uri.Should().Contain("enableDebugMode=true");
}
[Fact]
public void Builder_ConnectionFactory_GeneratesUri()
{
string uri = EsDsl.Index("data")
.ConnectionFactory("myEsFactory");
uri.Should().Contain("connectionFactory=myEsFactory");
}
[Fact]
public void Builder_ScrollConfig_GeneratesUri()
{
string uri = EsDsl.Index("data")
.Nodes("http://localhost:9200")
.ScrollTimeout("2m")
.Size(1000);
uri.Should().Contain("scrollTimeout=2m");
uri.Should().Contain("size=1000");
}
[Fact]
public void Builder_ImplicitStringConversion()
{
ElasticsearchBuilder builder = EsDsl.Index("test").Nodes("http://localhost:9200");
string uri = builder;
uri.Should().StartWith("elasticsearch://test?");
}
[Fact]
public void Builder_ToString_EqualsImplicit()
{
var builder = EsDsl.Index("test").Nodes("http://localhost:9200");
builder.ToString().Should().Be((string)builder);
}
[Fact]
public void Builder_DocumentId_SetsParam()
{
string uri = EsDsl.Index("data")
.Nodes("http://localhost:9200")
.DocumentId("${header.id}");
uri.Should().Contain("documentId=");
}
[Fact]
public void Builder_TimeoutOptions_GeneratesUri()
{
string uri = EsDsl.Index("data")
.Nodes("http://localhost:9200")
.DeadTimeout(120_000)
.MaxDeadTimeout(900_000);
uri.Should().Contain("deadTimeout=120000");
uri.Should().Contain("maxDeadTimeout=900000");
}
[Fact]
public void Index_NullIndexName_Throws()
{
var act = () => EsDsl.Index(null!);
act.Should().Throw();
}
[Fact]
public void Index_EmptyIndexName_Throws()
{
var act = () => EsDsl.Index("");
act.Should().Throw();
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchEndpointOptionsTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchEndpointOptionsTests.cs
----
using redb.Route.Elasticsearch;
namespace redb.Route.Tests.Elasticsearch;
public sealed class ElasticsearchEndpointOptionsTests
{
// ═══════════════════════════════════════════════════════════════════
// VALIDATE
// ═══════════════════════════════════════════════════════════════════
[Fact]
public void Validate_MissingNodes_Throws()
{
var opts = new ElasticsearchEndpointOptions { Nodes = "", ConnectionFactory = "" };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*Nodes*");
}
[Fact]
public void Validate_ConnectionFactory_AllowsMissingNodes()
{
var opts = new ElasticsearchEndpointOptions { Nodes = "", ConnectionFactory = "myFactory" };
var act = () => opts.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_WithNodes_DoesNotThrow()
{
var opts = new ElasticsearchEndpointOptions { Nodes = "http://localhost:9200" };
var act = () => opts.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_DelayTooSmall_Throws()
{
var opts = new ElasticsearchEndpointOptions { Delay = 50 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*Delay*");
}
[Fact]
public void Validate_SizeZero_Throws()
{
var opts = new ElasticsearchEndpointOptions { Size = 0 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*Size*");
}
[Fact]
public void Validate_SizeTooLarge_Throws()
{
var opts = new ElasticsearchEndpointOptions { Size = 10_001 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*Size*");
}
[Fact]
public void Validate_BulkSizeZero_Throws()
{
var opts = new ElasticsearchEndpointOptions { BulkSize = 0 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*BulkSize*");
}
[Fact]
public void Validate_RequestTimeoutTooSmall_Throws()
{
var opts = new ElasticsearchEndpointOptions { RequestTimeout = 500 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*RequestTimeout*");
}
[Fact]
public void Validate_MaxRetriesNegative_Throws()
{
var opts = new ElasticsearchEndpointOptions { MaxRetries = -1 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*MaxRetries*");
}
[Fact]
public void Validate_ValidOptions_DoesNotThrow()
{
var opts = new ElasticsearchEndpointOptions
{
Nodes = "http://localhost:9200",
Delay = 1000,
Size = 50,
BulkSize = 200,
RequestTimeout = 5000,
MaxRetries = 5,
};
var act = () => opts.Validate();
act.Should().NotThrow();
}
// ═══════════════════════════════════════════════════════════════════
// BIND FROM URI
// ═══════════════════════════════════════════════════════════════════
[Fact]
public void BindFromUri_AllProperties_Bound()
{
var opts = new ElasticsearchEndpointOptions();
opts.BindFromUri(new Dictionary
{
["nodes"] = "http://node1:9200,http://node2:9200",
["apiKey"] = "base64key",
["username"] = "elastic",
["password"] = "secret",
["certificateFingerprint"] = "abc123",
["connectionFactory"] = "myFactory",
["enableDebugMode"] = "true",
["requestTimeout"] = "60000",
["pingTimeout"] = "5000",
["deadTimeout"] = "120000",
["maxDeadTimeout"] = "900000",
["maxRetries"] = "5",
["operation"] = "Search",
["pipeline"] = "my-pipeline",
["routing"] = "shard-1",
["refresh"] = "wait_for",
["bulkSize"] = "500",
["delay"] = "10000",
["initialDelay"] = "2000",
["query"] = "{\"match_all\":{}}",
["size"] = "50",
["scrollTimeout"] = "2m",
["sort"] = "timestamp:desc",
["deleteAfterRead"] = "true",
["trackTotalHits"] = "false",
["sourceIncludes"] = "title,author",
["sourceExcludes"] = "large_blob",
});
opts.Nodes.Should().Be("http://node1:9200,http://node2:9200");
opts.ApiKey.Should().Be("base64key");
opts.Username.Should().Be("elastic");
opts.Password.Should().Be("secret");
opts.CertificateFingerprint.Should().Be("abc123");
opts.ConnectionFactory.Should().Be("myFactory");
opts.EnableDebugMode.Should().BeTrue();
opts.RequestTimeout.Should().Be(60_000);
opts.PingTimeout.Should().Be(5000);
opts.DeadTimeout.Should().Be(120_000);
opts.MaxDeadTimeout.Should().Be(900_000);
opts.MaxRetries.Should().Be(5);
opts.Operation.Should().Be(ElasticsearchOperationType.Search);
opts.Pipeline.Should().Be("my-pipeline");
opts.Routing.Should().Be("shard-1");
opts.Refresh.Should().Be("wait_for");
opts.BulkSize.Should().Be(500);
opts.Delay.Should().Be(10_000);
opts.InitialDelay.Should().Be(2000);
opts.Query.Should().Be("{\"match_all\":{}}");
opts.Size.Should().Be(50);
opts.ScrollTimeout.Should().Be("2m");
opts.Sort.Should().Be("timestamp:desc");
opts.DeleteAfterRead.Should().BeTrue();
opts.TrackTotalHits.Should().BeFalse();
opts.SourceIncludes.Should().Be("title,author");
opts.SourceExcludes.Should().Be("large_blob");
}
[Fact]
public void BindFromUri_OperationType_Parsed()
{
var opts = new ElasticsearchEndpointOptions();
opts.BindFromUri(new Dictionary { ["operation"] = "Bulk" });
opts.Operation.Should().Be(ElasticsearchOperationType.Bulk);
}
[Fact]
public void Defaults_AreCorrect()
{
var opts = new ElasticsearchEndpointOptions();
opts.Nodes.Should().Be("http://localhost:9200");
opts.Delay.Should().Be(5000);
opts.InitialDelay.Should().Be(1000);
opts.Size.Should().Be(100);
opts.BulkSize.Should().Be(100);
opts.Operation.Should().Be(ElasticsearchOperationType.Index);
opts.RequestTimeout.Should().Be(30_000);
opts.PingTimeout.Should().Be(2000);
opts.DeadTimeout.Should().Be(60_000);
opts.MaxDeadTimeout.Should().Be(600_000);
opts.MaxRetries.Should().Be(3);
opts.DeleteAfterRead.Should().BeFalse();
opts.TrackTotalHits.Should().BeTrue();
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchHeadersTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchHeadersTests.cs
----
using redb.Route.Elasticsearch;
namespace redb.Route.Tests.Elasticsearch;
public sealed class ElasticsearchHeadersTests
{
[Fact]
public void AllHeaders_HaveCorrectPrefix()
{
var fields = typeof(ElasticsearchHeaders)
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
.Where(f => f.FieldType == typeof(string) && f.Name != "Prefix")
.Select(f => (f.Name, Value: (string)f.GetValue(null)!))
.ToList();
fields.Should().NotBeEmpty();
foreach (var (name, value) in fields)
{
value.Should().StartWith("redbEs.", because: $"header {name} must have the ES prefix");
}
}
[Fact]
public void IsRedbHeader_ReturnsTrueForKnownHeaders()
{
ElasticsearchHeaders.IsRedbHeader(ElasticsearchHeaders.IndexName).Should().BeTrue();
ElasticsearchHeaders.IsRedbHeader(ElasticsearchHeaders.DocumentId).Should().BeTrue();
ElasticsearchHeaders.IsRedbHeader(ElasticsearchHeaders.Version).Should().BeTrue();
ElasticsearchHeaders.IsRedbHeader(ElasticsearchHeaders.Score).Should().BeTrue();
}
[Fact]
public void IsRedbHeader_ReturnsFalseForUnknownHeaders()
{
ElasticsearchHeaders.IsRedbHeader("Content-Type").Should().BeFalse();
ElasticsearchHeaders.IsRedbHeader("unknown").Should().BeFalse();
ElasticsearchHeaders.IsRedbHeader("redbS3.Key").Should().BeFalse();
}
[Fact]
public void HeaderValues_AreUnique()
{
var fields = typeof(ElasticsearchHeaders)
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
.Where(f => f.FieldType == typeof(string) && f.Name != "Prefix")
.Select(f => (string)f.GetValue(null)!)
.ToList();
fields.Should().OnlyHaveUniqueItems();
}
[Fact]
public void Prefix_IsRedbEs()
{
ElasticsearchHeaders.Prefix.Should().Be("redbEs.");
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchIntegrationTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Elastic.Clients.Elasticsearch;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Elasticsearch;
using Xunit.Abstractions;
namespace redb.Route.Tests.Elasticsearch;
///
/// Integration tests against Elasticsearch docker container.
/// Expects Elasticsearch at localhost:9200 (no auth, security disabled).
/// Start with: docker compose -f docker-compose.tests.yml up elasticsearch -d
///
[Trait("Category", "Integration")]
public sealed class ElasticsearchIntegrationTests : IAsyncLifetime
{
private const string Nodes = "http://localhost:9200";
private readonly ITestOutputHelper _output;
private ElasticsearchClient? _rawClient;
public ElasticsearchIntegrationTests(ITestOutputHelper output) => _output = output;
public async Task InitializeAsync()
{
_rawClient = new ElasticsearchClient(new ElasticsearchClientSettings(new Uri(Nodes)));
// Verify ES is reachable
var ping = await _rawClient.PingAsync();
if (!ping.IsValidResponse)
throw new InvalidOperationException($"Elasticsearch not reachable at {Nodes}: {ping.DebugInformation}");
}
public async Task DisposeAsync()
{
// Delete the indices this test created, by name: Elasticsearch 8 refuses a wildcard delete
// (action.destructive_requires_name), and the refusal used to go unnoticed, so every run leaked its indices
// until the cluster ran out of shards. A test that never wrote to its index has none to delete.
if (_rawClient is not null && _indices.Count > 0)
{
var deleted = await _rawClient.Indices.DeleteAsync(
Elastic.Clients.Elasticsearch.Indices.Parse(string.Join(",", _indices)),
d => d.IgnoreUnavailable(true));
if (!deleted.IsValidResponse)
throw new InvalidOperationException($"The test's indices were not deleted: {deleted.DebugInformation}");
}
}
// ───── Helpers ─────
private readonly List _indices = [];
private string UniqueIndex()
{
var index = $"test-{Guid.NewGuid():N}";
_indices.Add(index);
return index;
}
private ElasticsearchEndpoint CreateEndpoint(string index, string? extraParams = null)
{
var qs = $"nodes={Nodes}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"elasticsearch://{index}?{qs}");
return (ElasticsearchEndpoint)new ElasticsearchComponent().CreateEndpoint(uri);
}
private ElasticsearchEndpoint CreateEndpointWithOp(ElasticsearchOperationType op, string index, string? extraParams = null)
{
var qs = $"nodes={Nodes}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"elasticsearch://{op}:{index}?{qs}");
return (ElasticsearchEndpoint)new ElasticsearchComponent().CreateEndpoint(uri);
}
private async Task IndexDocument(string index, string id, object doc)
{
var response = await _rawClient!.IndexAsync(doc, i => i.Index(index).Id(id).Refresh(Refresh.WaitFor));
if (!response.IsValidResponse)
throw new InvalidOperationException($"Failed to index doc: {response.DebugInformation}");
}
private async Task IndexDocumentJson(string index, string id, string json)
{
var doc = JsonSerializer.Deserialize(json);
await IndexDocument(index, id, doc!);
}
private async Task RefreshIndex(string index)
{
await _rawClient!.Indices.RefreshAsync(index);
}
private async Task CountDocuments(string index)
{
var response = await _rawClient!.CountAsync(c => c.Indices(index));
return response.IsValidResponse ? response.Count : 0;
}
// ═══════════════════════════════════════════════════════════════════
// INDEX + GET ROUNDTRIP
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Index_Get_Roundtrip()
{
var index = UniqueIndex();
_output.WriteLine($"Index: {index}");
// Index a document
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "Test Doc", ["content"] = "Hello Elasticsearch!" };
var exchange = new Exchange(new Message(body.ToJsonString()));
exchange.In.Headers[ElasticsearchHeaders.DocumentId] = "doc-1";
await producer.Process(exchange);
// Verify index headers
exchange.In.Headers[ElasticsearchHeaders.DocumentId].Should().Be("doc-1");
exchange.In.Headers[ElasticsearchHeaders.Result].Should().NotBeNull();
exchange.In.Headers[ElasticsearchHeaders.Version].Should().NotBeNull();
// Get the document back
var getEp = CreateEndpointWithOp(ElasticsearchOperationType.Get, index);
var getProducer = getEp.CreateProducer();
await getProducer.Start();
var getExchange = new Exchange(new Message());
getExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "doc-1";
await getProducer.Process(getExchange);
getExchange.Pattern.Should().Be(ExchangePattern.InOut);
getExchange.Out.Should().NotBeNull();
var resultBody = getExchange.Out!.Body?.ToString();
resultBody.Should().Contain("Test Doc");
resultBody.Should().Contain("Hello Elasticsearch!");
await getProducer.Stop();
await producer.Stop();
}
[Fact]
public async Task Index_WithAutoId_ReturnsGeneratedId()
{
var index = UniqueIndex();
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "Auto ID Doc" };
var exchange = new Exchange(new Message(body.ToJsonString()));
// No explicit DocumentId header — ES auto-generates
await producer.Process(exchange);
var docId = exchange.In.Headers[ElasticsearchHeaders.DocumentId] as string;
docId.Should().NotBeNullOrEmpty("Elasticsearch should auto-generate an ID");
_output.WriteLine($"Auto-generated ID: {docId}");
await producer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// INDEX + SEARCH ROUNDTRIP
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Index_Search_Roundtrip()
{
var index = UniqueIndex();
// Index multiple documents
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
for (int i = 0; i < 3; i++)
{
var doc = new JsonObject { ["title"] = $"Doc {i}", ["seq"] = i };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"doc-{i}";
await producer.Process(ex);
}
await producer.Stop();
// Search for all documents
var searchEp = CreateEndpointWithOp(ElasticsearchOperationType.Search, index);
var searchProducer = searchEp.CreateProducer();
await searchProducer.Start();
var searchExchange = new Exchange(new Message("{\"match_all\":{}}"));
await searchProducer.Process(searchExchange);
searchExchange.Pattern.Should().Be(ExchangePattern.InOut);
searchExchange.Out.Should().NotBeNull();
var totalHits = searchExchange.Out!.Headers[ElasticsearchHeaders.TotalHits];
totalHits.Should().NotBeNull();
((long)totalHits!).Should().Be(3);
await searchProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// BULK
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Bulk_IndexMultiple_AllIndexed()
{
var index = UniqueIndex();
var ep = CreateEndpointWithOp(ElasticsearchOperationType.Bulk, index, "refresh=wait_for&bulkSize=20");
var producer = ep.CreateProducer();
await producer.Start();
// Create a list of documents
var docs = new JsonArray();
for (int i = 0; i < 50; i++)
{
docs.Add(new JsonObject { ["title"] = $"Bulk Doc {i}", ["seq"] = i });
}
var exchange = new Exchange(new Message(docs.ToJsonString()));
await producer.Process(exchange);
exchange.In.Headers[ElasticsearchHeaders.BulkItemCount].Should().NotBeNull();
((int)exchange.In.Headers[ElasticsearchHeaders.BulkItemCount]!).Should().Be(50);
var hasErrors = exchange.In.Headers[ElasticsearchHeaders.BulkErrors];
((bool)hasErrors!).Should().BeFalse();
// Verify count
await RefreshIndex(index);
var count = await CountDocuments(index);
count.Should().Be(50);
await producer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// UPDATE
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Update_PartialDocument_Merges()
{
var index = UniqueIndex();
// Index a document first
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "Original", ["author"] = "Alice", ["views"] = 0 };
var indexExchange = new Exchange(new Message(body.ToJsonString()));
indexExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "upd-1";
await producer.Process(indexExchange);
await producer.Stop();
// Update only the title and views
var updateEp = CreateEndpointWithOp(ElasticsearchOperationType.Update, index, "refresh=wait_for");
var updateProducer = updateEp.CreateProducer();
await updateProducer.Start();
var updateBody = new JsonObject { ["title"] = "Updated", ["views"] = 42 };
var updateExchange = new Exchange(new Message(updateBody.ToJsonString()));
updateExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "upd-1";
await updateProducer.Process(updateExchange);
updateExchange.In.Headers[ElasticsearchHeaders.Result].Should().NotBeNull();
await updateProducer.Stop();
// Get and verify merge
var getEp = CreateEndpointWithOp(ElasticsearchOperationType.Get, index);
var getProducer = getEp.CreateProducer();
await getProducer.Start();
var getExchange = new Exchange(new Message());
getExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "upd-1";
await getProducer.Process(getExchange);
var result = getExchange.Out!.Body?.ToString();
result.Should().Contain("Updated");
result.Should().Contain("Alice", because: "author should be preserved from original");
result.Should().Contain("42");
await getProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// DELETE
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Delete_RemovesDocument()
{
var index = UniqueIndex();
// Index a document
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "To Delete" };
var indexExchange = new Exchange(new Message(body.ToJsonString()));
indexExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "del-1";
await producer.Process(indexExchange);
await producer.Stop();
// Delete the document
var delEp = CreateEndpointWithOp(ElasticsearchOperationType.Delete, index, "refresh=wait_for");
var delProducer = delEp.CreateProducer();
await delProducer.Start();
var delExchange = new Exchange(new Message());
delExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "del-1";
await delProducer.Process(delExchange);
await delProducer.Stop();
// Verify via Get — should not be found
var getEp = CreateEndpointWithOp(ElasticsearchOperationType.Get, index);
var getProducer = getEp.CreateProducer();
await getProducer.Start();
var getExchange = new Exchange(new Message());
getExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "del-1";
await getProducer.Process(getExchange);
getExchange.Out!.Body.Should().BeNull("document was deleted");
await getProducer.Stop();
}
[Fact]
public async Task Delete_MissingDocument_CompletesWithNotFoundResult()
{
var index = UniqueIndex();
// The index must exist, so the only thing missing is the document.
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var indexExchange = new Exchange(new Message(new JsonObject { ["title"] = "Kept" }.ToJsonString()));
indexExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "kept-1";
await producer.Process(indexExchange);
await producer.Stop();
var delEp = CreateEndpointWithOp(ElasticsearchOperationType.Delete, index, "refresh=wait_for");
var delProducer = delEp.CreateProducer();
await delProducer.Start();
var delExchange = new Exchange(new Message());
delExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "no-such-document";
var act = () => delProducer.Process(delExchange);
// Elastic.Clients.Elasticsearch 8.19.27 takes the 404 of a delete for a valid response:
// the exchange goes on, and the result header is the way to tell the miss.
await act.Should().NotThrowAsync();
delExchange.In.Headers[ElasticsearchHeaders.Result].Should().Be("NotFound");
await delProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// COUNT
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Count_ReturnsCorrectCount()
{
var index = UniqueIndex();
// Index several documents
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
for (int i = 0; i < 7; i++)
{
var doc = new JsonObject { ["seq"] = i };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"cnt-{i}";
await producer.Process(ex);
}
await producer.Stop();
// Count
var countEp = CreateEndpointWithOp(ElasticsearchOperationType.Count, index);
var countProducer = countEp.CreateProducer();
await countProducer.Start();
var countExchange = new Exchange(new Message());
await countProducer.Process(countExchange);
countExchange.Pattern.Should().Be(ExchangePattern.InOut);
((long)countExchange.Out!.Body!).Should().Be(7);
await countProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// EXISTS
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Exists_ReturnsBoolean()
{
var index = UniqueIndex();
// Index a document
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "Exists Test" };
var indexExchange = new Exchange(new Message(body.ToJsonString()));
indexExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "ex-1";
await producer.Process(indexExchange);
await producer.Stop();
// Check exists — should be true
var existsEp = CreateEndpointWithOp(ElasticsearchOperationType.Exists, index);
var existsProducer = existsEp.CreateProducer();
await existsProducer.Start();
var existsExchange = new Exchange(new Message());
existsExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "ex-1";
await existsProducer.Process(existsExchange);
existsExchange.Pattern.Should().Be(ExchangePattern.InOut);
((bool)existsExchange.Out!.Body!).Should().BeTrue();
// Check non-existing
var noExchange = new Exchange(new Message());
noExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "non-existing";
await existsProducer.Process(noExchange);
((bool)noExchange.Out!.Body!).Should().BeFalse();
await existsProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// CONSUMER — Basic Polling
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Consumer_Polls_ProcessesDocuments()
{
var index = UniqueIndex();
_output.WriteLine($"Consumer index: {index}");
// Seed documents via raw client
for (int i = 0; i < 5; i++)
{
await IndexDocumentJson(index, $"poll-{i}", $"{{\"title\":\"Poll Doc {i}\",\"seq\":{i}}}");
}
await RefreshIndex(index);
var ep = CreateEndpoint(index,
"deleteAfterRead=false&delay=500&initialDelay=100&size=10&sort=seq:asc");
var received = new ConcurrentBag();
var counter = 0;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
received.Add(ci.ArgAt(0));
if (Interlocked.Increment(ref counter) >= 5) done.TrySetResult();
return Task.CompletedTask;
});
var consumer = ep.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(done.Task, Task.Delay(30_000));
await consumer.Stop();
received.Should().HaveCountGreaterThanOrEqualTo(5);
// Verify headers set
var first = received.First();
first.In.Headers[ElasticsearchHeaders.IndexName].Should().Be(index);
first.In.Headers[ElasticsearchHeaders.DocumentId].Should().NotBeNull();
}
// ═══════════════════════════════════════════════════════════════════
// CONSUMER — DeleteAfterRead
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Consumer_DeleteAfterRead_CleansIndex()
{
var index = UniqueIndex();
_output.WriteLine($"DeleteAfterRead index: {index}");
// Seed 3 documents
for (int i = 0; i < 3; i++)
{
await IndexDocumentJson(index, $"dar-{i}", $"{{\"title\":\"DAR Doc {i}\"}}");
}
await RefreshIndex(index);
var ep = CreateEndpoint(index,
"deleteAfterRead=true&delay=500&initialDelay=100&size=10&refresh=wait_for");
var counter = 0;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
if (Interlocked.Increment(ref counter) >= 3) done.TrySetResult();
return Task.CompletedTask;
});
var consumer = ep.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(done.Task, Task.Delay(30_000));
await consumer.Stop();
// Index should be empty now
await RefreshIndex(index);
var remaining = await CountDocuments(index);
remaining.Should().Be(0, "all documents should have been deleted after read");
}
// ═══════════════════════════════════════════════════════════════════
// OPERATION OVERRIDE VIA HEADER
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Producer_OperationOverrideViaHeader()
{
var index = UniqueIndex();
// Index a document first
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
var body = new JsonObject { ["title"] = "Override Test" };
var indexExchange = new Exchange(new Message(body.ToJsonString()));
indexExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "ovr-1";
await producer.Process(indexExchange);
// Use same producer (default operation=Index) but override via header to Count
var countExchange = new Exchange(new Message());
countExchange.In.Headers[ElasticsearchHeaders.Operation] = "Count";
await producer.Process(countExchange);
countExchange.Pattern.Should().Be(ExchangePattern.InOut);
((long)countExchange.Out!.Body!).Should().Be(1);
await producer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// GET — Not Found
// ═══════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════
// MULTISEARCH
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task MultiSearch_MultipleQueries_ReturnsResultsPerQuery()
{
var index1 = UniqueIndex();
var index2 = UniqueIndex();
// Seed index1 with 3 docs
var ep1 = CreateEndpoint(index1, "refresh=wait_for");
var p1 = ep1.CreateProducer();
await p1.Start();
for (int i = 0; i < 3; i++)
{
var doc = new JsonObject { ["title"] = $"Alpha {i}", ["category"] = "alpha" };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"a-{i}";
await p1.Process(ex);
}
await p1.Stop();
// Seed index2 with 2 docs
var ep2 = CreateEndpoint(index2, "refresh=wait_for");
var p2 = ep2.CreateProducer();
await p2.Start();
for (int i = 0; i < 2; i++)
{
var doc = new JsonObject { ["title"] = $"Beta {i}", ["category"] = "beta" };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"b-{i}";
await p2.Process(ex);
}
await p2.Stop();
// MultiSearch: two queries against different indices
var msEp = CreateEndpointWithOp(ElasticsearchOperationType.MultiSearch, index1);
var msProducer = msEp.CreateProducer();
await msProducer.Start();
var queries = new JsonArray
{
new JsonObject { ["index"] = index1, ["query"] = new JsonObject { ["match_all"] = new JsonObject() }, ["size"] = 10 },
new JsonObject { ["index"] = index2, ["query"] = new JsonObject { ["match_all"] = new JsonObject() }, ["size"] = 10 },
};
var msExchange = new Exchange(new Message(queries.ToJsonString()));
await msProducer.Process(msExchange);
msExchange.Pattern.Should().Be(ExchangePattern.InOut);
msExchange.Out.Should().NotBeNull();
var results = msExchange.Out!.Body as List>;
results.Should().NotBeNull();
results.Should().HaveCount(2);
results![0].Should().HaveCount(3, "index1 has 3 documents");
results[1].Should().HaveCount(2, "index2 has 2 documents");
// Verify headers
((int)msExchange.Out.Headers[ElasticsearchHeaders.MultiSearchResponseCount]!).Should().Be(2);
((bool)msExchange.Out.Headers[ElasticsearchHeaders.MultiSearchHasErrors]!).Should().BeFalse();
var totalHits = msExchange.Out.Headers[ElasticsearchHeaders.MultiSearchTotalHits] as long[];
totalHits.Should().NotBeNull();
totalHits![0].Should().Be(3);
totalHits[1].Should().Be(2);
await msProducer.Stop();
}
[Fact]
public async Task MultiSearch_WithSizeLimit_RespectsPerQuerySize()
{
var index = UniqueIndex();
// Seed 5 docs
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
for (int i = 0; i < 5; i++)
{
var doc = new JsonObject { ["seq"] = i };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"ms-{i}";
await producer.Process(ex);
}
await producer.Stop();
// MultiSearch: one query with size=2, one without size (defaults)
var msEp = CreateEndpointWithOp(ElasticsearchOperationType.MultiSearch, index);
var msProducer = msEp.CreateProducer();
await msProducer.Start();
var queries = new JsonArray
{
new JsonObject { ["query"] = new JsonObject { ["match_all"] = new JsonObject() }, ["size"] = 2 },
new JsonObject { ["query"] = new JsonObject { ["match_all"] = new JsonObject() } },
};
var msExchange = new Exchange(new Message(queries.ToJsonString()));
await msProducer.Process(msExchange);
var results = msExchange.Out!.Body as List>;
results.Should().NotBeNull();
results![0].Should().HaveCount(2, "size=2 was specified");
results[1].Count.Should().BeGreaterThanOrEqualTo(5, "no size limit, should return all 5");
var totalHits = msExchange.Out.Headers[ElasticsearchHeaders.MultiSearchTotalHits] as long[];
totalHits![0].Should().Be(5, "total hits should reflect all matches, not just returned docs");
totalHits[1].Should().Be(5);
await msProducer.Stop();
}
[Fact]
public async Task MultiSearch_WithSortAndSource_AppliesPerQuery()
{
var index = UniqueIndex();
// Seed 4 docs with seq field
var ep = CreateEndpoint(index, "refresh=wait_for");
var producer = ep.CreateProducer();
await producer.Start();
for (int i = 0; i < 4; i++)
{
var doc = new JsonObject { ["title"] = $"Doc {i}", ["seq"] = i, ["secret"] = "hidden" };
var ex = new Exchange(new Message(doc.ToJsonString()));
ex.In.Headers[ElasticsearchHeaders.DocumentId] = $"ss-{i}";
await producer.Process(ex);
}
await producer.Stop();
var msEp = CreateEndpointWithOp(ElasticsearchOperationType.MultiSearch, index);
var msProducer = msEp.CreateProducer();
await msProducer.Start();
var queries = new JsonArray
{
// Query 1: sorted by seq desc, size 2 — should get docs 3,2
new JsonObject
{
["query"] = new JsonObject { ["match_all"] = new JsonObject() },
["sort"] = "seq:desc",
["size"] = 2,
},
// Query 2: only return title field
new JsonObject
{
["query"] = new JsonObject { ["match_all"] = new JsonObject() },
["_source"] = "title",
},
};
var msExchange = new Exchange(new Message(queries.ToJsonString()));
await msProducer.Process(msExchange);
var results = msExchange.Out!.Body as List>;
results.Should().NotBeNull();
results.Should().HaveCount(2);
// Query 1: sorted desc, size 2 — first doc should have highest seq
results![0].Should().HaveCount(2);
var firstDocSeq = results[0][0]["seq"]!.GetValue();
var secondDocSeq = results[0][1]["seq"]!.GetValue();
firstDocSeq.Should().BeGreaterThan(secondDocSeq, "sort is seq:desc");
// Query 2: _source filtering — docs should have "title" but NOT "secret"
foreach (var doc in results[1])
{
doc.ContainsKey("title").Should().BeTrue();
doc.ContainsKey("secret").Should().BeFalse("source filter excludes it");
}
await msProducer.Stop();
}
// ═══════════════════════════════════════════════════════════════════
// GET — Not Found
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Get_NotFound_ReturnsNullBody()
{
var index = UniqueIndex();
// Create the index by indexing and deleting a dummy doc
await IndexDocumentJson(index, "dummy", "{\"x\":1}");
await RefreshIndex(index);
var getEp = CreateEndpointWithOp(ElasticsearchOperationType.Get, index);
var getProducer = getEp.CreateProducer();
await getProducer.Start();
var getExchange = new Exchange(new Message());
getExchange.In.Headers[ElasticsearchHeaders.DocumentId] = "nonexistent-doc";
await getProducer.Process(getExchange);
getExchange.Out!.Body.Should().BeNull("document does not exist");
await getProducer.Stop();
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchTelemetrySmokeTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchTelemetrySmokeTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Elasticsearch;
using redb.Route.Telemetry;
using redb.Route.Tests.Shared;
using Xunit.Abstractions;
namespace redb.Route.Tests.Elasticsearch;
///
/// Smoke test for the P1 transport span opened by .
/// Requires Elasticsearch docker container on localhost:9200.
///
[Trait("Category", "Integration")]
public sealed class ElasticsearchTelemetrySmokeTests
{
private readonly ITestOutputHelper _output;
public ElasticsearchTelemetrySmokeTests(ITestOutputHelper output) => _output = output;
[Fact]
public async Task ElasticsearchProducer_EmitsTransportSpanWithDbSystemTag()
{
var index = $"smoke-{Guid.NewGuid():N}";
var uri = EndpointUriParser.Parse($"elasticsearch://Index:{index}?nodes=http://localhost:9200");
var endpoint = (ElasticsearchEndpoint)new ElasticsearchComponent().CreateEndpoint(uri);
var producer = endpoint.CreateProducer();
await producer.Start();
using var capture = new SpanCapture(); // this test's spans only
var ex = new Exchange(new Message("""{"title":"smoke"}"""));
try
{
await producer.Process(ex);
}
catch (Exception ioex)
{
_output.WriteLine($"ES Index failed (acceptable for smoke): {ioex.GetType().Name}: {ioex.Message}");
}
finally
{
await producer.Stop();
await DeleteIndex(index);
}
var activities = capture.Spans;
activities.Should().NotBeEmpty();
var activity = activities.First();
activity.Source.Name.Should().Be(RouteActivitySource.SourceName);
activity.Kind.Should().Be(ActivityKind.Client);
activity.GetTagItem("db.system").Should().Be("elasticsearch");
activity.GetTagItem("messaging.destination.name").Should().Be(index);
activity.GetTagItem("redb.route.endpoint").Should().NotBeNull();
}
///
/// Deletes the test's index by name (Elasticsearch 8 refuses a wildcard delete); a failed index attempt leaves none.
///
private static async Task DeleteIndex(string index)
{
var client = new Elastic.Clients.Elasticsearch.ElasticsearchClient(
new Elastic.Clients.Elasticsearch.ElasticsearchClientSettings(new Uri("http://localhost:9200")));
var deleted = await client.Indices.DeleteAsync(index, d => d.IgnoreUnavailable(true));
if (!deleted.IsValidResponse)
throw new InvalidOperationException($"The smoke test's index was not deleted: {deleted.DebugInformation}");
}
}
Path: redb-route/tests/redb.Route.Tests.Elasticsearch/ElasticsearchTraceTests.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/tests/redb.Route.Tests.Elasticsearch/ElasticsearchTraceTests.cs
----
using System.Diagnostics;
using Elastic.Clients.Elasticsearch;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Elasticsearch;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.Elasticsearch;
///
/// A polled document carries no trace context: the consumer opens a root span per routed hit, never a child of the
/// activity the poll loop inherited from whoever started it, and none for an empty poll. A failed route marks it red.
/// The producer marks a failed call red. EnableTelemetry=false opens none of these spans. Each test works on an
/// index of its own, reads only the spans of that endpoint and deletes the index by name.
/// Expects Elasticsearch at localhost:9200.
///
[Trait("Category", "Integration")]
public sealed class ElasticsearchTraceTests : IAsyncLifetime
{
private const string Nodes = "http://localhost:9200";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15);
private readonly string _index = $"trace-{Guid.NewGuid():N}";
private ElasticsearchClient _raw = null!;
public async Task InitializeAsync()
{
_raw = new ElasticsearchClient(new ElasticsearchClientSettings(new Uri(Nodes)));
var created = await _raw.Indices.CreateAsync(_index);
if (!created.IsValidResponse)
throw new InvalidOperationException($"The test index was not created: {created.DebugInformation}");
}
public async Task DisposeAsync()
{
var deleted = await _raw.Indices.DeleteAsync(_index, d => d.IgnoreUnavailable(true));
if (!deleted.IsValidResponse)
throw new InvalidOperationException($"The test index was not deleted: {deleted.DebugInformation}");
}
private string ConsumerUri =>
$"elasticsearch://{_index}?nodes={Nodes}&deleteAfterRead=true&delay=200&initialDelay=50&size=10&refresh=wait_for";
private RouteTelemetryProbe Spans(ActivityKind kind)
=> new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_index, StringComparison.Ordinal) == true);
private async Task Seed(string id)
{
var response = await _raw.IndexAsync(new { v = id }, i => i.Index(_index).Id(id).Refresh(Refresh.WaitFor));
if (!response.IsValidResponse)
throw new InvalidOperationException($"The document was not indexed: {response.DebugInformation}");
}
private async Task StartConsumer(Action step, bool telemetry = true)
{
var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new ElasticsearchComponent());
ctx.AddRoutes(r => r.From(ConsumerUri).Process(step));
using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start())
await ctx.Start();
return ctx;
}
private static async Task Until(Func done)
{
var deadline = DateTime.UtcNow + Wait;
while (!done() && DateTime.UtcNow < deadline)
await Task.Delay(100);
}
[Fact]
public async Task Each_hit_opens_a_root_span_even_under_an_ambient_activity()
{
await Seed("a");
await Seed("b");
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => { }))
await Until(() => probe.Activities.Count >= 2);
probe.Activities.Should().HaveCount(2, "one span per routed hit");
probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId),
"a document carries no context, so its span starts a trace rather than joining the host's");
}
[Fact]
public async Task An_empty_poll_opens_no_span()
{
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => { }))
await Task.Delay(1200); // several polls of an empty index
probe.Activities.Should().BeEmpty();
}
[Fact]
public async Task A_failed_route_marks_the_span_red()
{
await Seed("fail");
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => throw new InvalidOperationException("route failed")))
await Until(() => probe.Activities.Count >= 1);
probe.Activities.Should().NotBeEmpty().And.OnlyContain(a => a.Status == ActivityStatusCode.Error);
}
[Fact]
public async Task A_failure_that_escapes_the_route_keeps_the_document_with_deleteAfterRead()
{
await Seed("kept");
var attempted = new TaskCompletionSource();
await using (var ctx = new RouteContext())
{
ctx.AddComponent(new ElasticsearchComponent());
ctx.AddRoutes(r =>
{
// An error handler passes a cancellation on rather than swallow it, so a timeout inside the route (an
// HttpClient timeout is a TaskCanceledException) escapes the pipeline instead of staying on the exchange.
r.OnException().Handled();
r.From(ConsumerUri).Process(_ =>
{
attempted.TrySetResult();
throw new TaskCanceledException("a call inside the route timed out");
});
});
await ctx.Start();
(await Task.WhenAny(attempted.Task, Task.Delay(Wait))).Should().Be(attempted.Task);
await Task.Delay(500); // past the delete the poll would have issued
}
var got = await _raw.GetAsync