Bundle: redb-route / tests/redb.Route.Tests.Cache (tests.redb.Route.Tests.Cache.txt), 14 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.Cache/CacheComponentTests.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.Cache/CacheComponentTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// The cache: component: explicit get / put / remove / clear.
public class CacheComponentTests
{
private static RouteContext Context()
{
var ctx = new RouteContext();
ctx.UseCache();
return ctx;
}
[Fact]
public async Task Get_Miss_Then_Put_Then_Hit_AcrossRoutes()
{
await using var ctx = Context().AddRoutes(b =>
{
b.From("direct://get").To("cache:customers?action=get&key=${header.id}").To("mock://get");
b.From("direct://put").To("cache:customers?action=put&key=${header.id}&ttl=5m");
});
await ctx.Start();
await ctx.SendBodyAndHeader("direct://get", "original", "id", 7);
await ctx.SendBodyAndHeader("direct://put", "cached-7", "id", 7);
await ctx.SendBodyAndHeader("direct://get", "original", "id", 7);
var got = ctx.Mock("mock://get").ReceivedExchanges;
got[0].In.Headers["cache.hit"].Should().Be(false);
got[0].In.Body.Should().Be("original");
got[1].In.Headers["cache.hit"].Should().Be(true);
got[1].In.Body.Should().Be("cached-7");
}
[Fact]
public async Task Remove_And_Clear()
{
await using var ctx = Context().AddRoutes(b =>
{
b.From("direct://put").To("cache:region?action=put&key=${header.id}");
b.From("direct://get").To("cache:region?action=get&key=${header.id}").To("mock://get");
b.From("direct://remove").To("cache:region?action=remove&key=${header.id}");
b.From("direct://clear").To("cache:region?action=clear");
});
await ctx.Start();
await ctx.SendBodyAndHeader("direct://put", "a", "id", "a");
await ctx.SendBodyAndHeader("direct://put", "b", "id", "b");
await ctx.SendBodyAndHeader("direct://remove", "x", "id", "a");
await ctx.SendBodyAndHeader("direct://get", "x", "id", "a");
await ctx.SendBodyAndHeader("direct://get", "x", "id", "b");
await ctx.SendBody("direct://clear", "x");
await ctx.SendBodyAndHeader("direct://get", "x", "id", "b");
ctx.Mock("mock://get").ReceivedExchanges.Select(e => e.In.Headers["cache.hit"]).Should().Equal(false, true, false);
}
[Fact]
public async Task Clear_RemovesAKeyThatWasPutTwice()
{
await using var ctx = Context().AddRoutes(b =>
{
b.From("direct://put2").To("cache:overwrite?action=put&key=k");
b.From("direct://get2").To("cache:overwrite?action=get&key=k").To("mock://get2");
b.From("direct://clear2").To("cache:overwrite?action=clear");
});
await ctx.Start();
await ctx.SendBody("direct://put2", "first");
await ctx.SendBody("direct://put2", "second");
// MemoryCache runs the replaced entry's eviction callback on the thread pool; let it fire before clear.
await Task.Delay(200);
await ctx.SendBody("direct://clear2", "x");
await ctx.SendBody("direct://get2", "x");
ctx.Mock("mock://get2").ReceivedExchanges[0].In.Headers["cache.hit"].Should().Be(false, "clear must remove an overwritten key too");
}
[Fact]
public async Task InvalidOptions_FailLoudly_WhenTheEndpointIsCreated()
{
// A static To's endpoint is created when its route starts, so the option validation stops the start, with the
// reason in the message.
await StartOf("cache:r?action=put").Should().ThrowAsync().WithMessage("*needs key*");
await StartOf("cache:r?action=flush&key=k").Should().ThrowAsync().WithMessage("*unknown action*");
await StartOf("cache:r?action=put&key=k&ttl=soon").Should().ThrowAsync();
}
/// Starting a context with one route that sends to .
private static Func StartOf(string target) => async () =>
{
await using var ctx = Context().AddRoutes(b => b.From("direct://start-of").To(target));
await ctx.Start();
};
[Fact]
public async Task Put_StoresOnlyTheNamedHeaders()
{
await using var ctx = Context().AddRoutes(b =>
{
b.From("direct://put-named").To("cache:named?action=put&key=k&headers=X-Rate,X-Missing");
b.From("direct://get-named").To("cache:named?action=get&key=k").To("mock://get-named");
});
await ctx.Start();
await ctx.SendBodyAndHeaders("direct://put-named", "v", new Dictionary
{
["X-Rate"] = 5, ["Other"] = "first", ["Authorization"] = "Bearer one",
});
await ctx.SendBodyAndHeaders("direct://get-named", "x", new Dictionary
{
["Other"] = "second", ["Authorization"] = "Bearer two",
});
var got = ctx.Mock("mock://get-named").ReceivedExchanges[0].In;
got.Headers["cache.hit"].Should().Be(true);
got.Body.Should().Be("v");
got.Headers["X-Rate"].Should().Be(5);
got.Headers["Other"].Should().Be("second", "a header the put did not name is not stored");
got.Headers["Authorization"].Should().Be("Bearer two");
got.Headers.Should().NotContainKey("X-Missing");
}
[Fact]
public async Task HeaderOptions_AreRefused_WhenTheyCannotBeHonoured()
{
await StartOf("cache:r?action=put&key=k&cacheHeaders=true").Should()
.ThrowAsync("a put cannot tell the value's headers from the request's").WithMessage("*headers=*");
await StartOf("cache:r?action=put&key=k&headers=X-Rate,Authorization").Should()
.ThrowAsync().WithMessage("*Authorization*credential*");
await StartOf("cache:r?action=get&key=k&headers=X-Rate").Should()
.ThrowAsync().WithMessage("*headers=*put*");
}
[Theory]
[InlineData("500ms", 500)]
[InlineData("30s", 30_000)]
[InlineData("5m", 300_000)]
[InlineData("2h", 7_200_000)]
[InlineData("1d", 86_400_000)]
[InlineData("00:00:10", 10_000)]
public void Durations(string text, double milliseconds)
=> CacheDuration.Parse(text)!.Value.TotalMilliseconds.Should().Be(milliseconds);
[Fact]
public async Task ScopeAndComponent_ShareTheStore()
{
await using var ctx = Context().AddRoutes(b =>
{
b.From("direct://scope").Cache("${header.id}").Region("shared").SetBody("from-scope").EndCache();
b.From("direct://get").To("cache:shared?action=get&key=${header.id}").To("mock://get");
});
await ctx.Start();
await ctx.SendBodyAndHeader("direct://scope", "x", "id", 1);
await ctx.SendBodyAndHeader("direct://get", "x", "id", 1);
var got = ctx.Mock("mock://get").ReceivedExchanges[0];
got.In.Headers["cache.hit"].Should().Be(true);
got.In.Body.Should().Be("from-scope");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheHeadersPolicyTests.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.Cache/CacheHeadersPolicyTests.cs
----
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
///
/// Which headers a hit replays with CacheHeaders(): what the miss produced, never what the first
/// caller brought, never a credential. Review 2026-09-29, C1 and C6.
///
public class CacheHeadersPolicyTests
{
[Fact]
public async Task Hit_KeepsTheCurrentCallersHeaders_AndReplaysWhatTheMissProduced()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://creds")
.Cache("k").CacheHeaders().SetHeader("computed", "yes").SetBody("v").EndCache()
.To("mock://creds"));
await ctx.Start();
await ctx.SendBodyAndHeaders("direct://creds", "a", new Dictionary
{
["Authorization"] = "Bearer one", ["Cookie"] = "session=one", ["redbHttp.RemoteAddress"] = "10.0.0.1",
});
await ctx.SendBodyAndHeaders("direct://creds", "a", new Dictionary
{
["Authorization"] = "Bearer two", ["Cookie"] = "session=two", ["redbHttp.RemoteAddress"] = "10.0.0.2",
});
var hit = ctx.Mock("mock://creds").ReceivedExchanges[1].In;
hit.Headers["cache.hit"].Should().Be(true);
hit.Headers["computed"].Should().Be("yes");
hit.Headers["Authorization"].Should().Be("Bearer two", "a hit must not hand the first caller's credential to the current one");
hit.Headers["Cookie"].Should().Be("session=two");
hit.Headers["redbHttp.RemoteAddress"].Should().Be("10.0.0.2", "request metadata belongs to the current exchange");
}
[Fact]
public async Task Hit_RemovesWhatTheMissRemoved()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://removed")
.Cache("k").CacheHeaders().Process(e => e.In.Headers.Remove("temp")).SetBody("v").EndCache()
.To("mock://removed"));
await ctx.Start();
await ctx.SendBodyAndHeader("direct://removed", "a", "temp", "one");
await ctx.SendBodyAndHeader("direct://removed", "a", "temp", "two");
var got = ctx.Mock("mock://removed").ReceivedExchanges;
got[0].In.Headers.Should().NotContainKey("temp");
got[1].In.Headers["cache.hit"].Should().Be(true);
got[1].In.Headers.Should().NotContainKey("temp", "a hit must leave the headers the way the miss did");
}
[Fact]
public async Task Hit_DoesNotReplayACredentialTheMissProduced()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://service-token")
.Cache("k").CacheHeaders().SetHeader("Authorization", "Bearer service").SetHeader("X-Trace", "t").SetBody("v").EndCache()
.To("mock://service-token"));
await ctx.Start();
await ctx.SendBody("direct://service-token", "a");
await ctx.SendBody("direct://service-token", "a");
var got = ctx.Mock("mock://service-token").ReceivedExchanges;
got[0].In.Headers["Authorization"].Should().Be("Bearer service", "the miss itself keeps what its steps set");
got[1].In.Headers["cache.hit"].Should().Be(true);
got[1].In.Headers["X-Trace"].Should().Be("t");
got[1].In.Headers.Should().NotContainKey("Authorization", "a credential is never stored, whoever produced it");
}
[Fact]
public async Task Hit_RestoresInHeaders_WhenTheMissRepliedInOut()
{
// C6: with the reply in Out, what the steps did to In must come back on a hit as well.
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://out-headers")
.Cache("k").CacheHeaders().SetHeader("x", "1").Process(e => e.Out = new Message("reply")).EndCache());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var miss = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://out-headers", miss);
var hit = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://out-headers", hit);
hit.In.Headers["cache.hit"].Should().Be(true);
hit.In.Headers["x"].Should().Be("1", "the miss set it on In");
hit.Out.Should().NotBeNull();
hit.Out!.Body.Should().Be("reply");
}
[Fact]
public async Task Hit_DoesNotReplayRequestHeadersAReplyCopied()
{
// A producer that builds its reply from the request's headers: the copies are the request's, not the reply's own.
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://copied")
.Cache("k").CacheHeaders().Process(e =>
{
var reply = new Message("reply");
foreach (var (name, value) in e.In.Headers)
reply.Headers[name] = value;
reply.Headers["X-Reply"] = "yes";
e.Out = reply;
}).EndCache());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var miss = Exchange.Create(new Message("in") { Headers = { ["X-Tenant"] = "a" } }, null);
await template.SendAsync("direct://copied", miss);
var hit = Exchange.Create(new Message("in") { Headers = { ["X-Tenant"] = "b" } }, null);
await template.SendAsync("direct://copied", hit);
hit.Out.Should().NotBeNull();
hit.Out!.Headers["X-Reply"].Should().Be("yes");
hit.Out.Headers.Should().NotContainKey("X-Tenant", "the first caller's request header must not travel in another caller's reply");
hit.In.Headers["X-Tenant"].Should().Be("b");
}
[Fact]
public async Task Distributed_CarriesTheProducedAndRemovedHeaders_NotTheCallersOwn()
{
await using var ctx = new RouteContext();
ctx.UseCache(o => o.DefaultProvider = CacheProvider.Distributed);
ctx.AddService(typeof(IDistributedCache), new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())));
ctx.AddRoutes(b => b
.From("direct://dist-headers")
.Cache("k").CacheHeaders().SetHeader("computed", "yes").Process(e => e.In.Headers.Remove("temp")).SetBody("v").EndCache()
.To("mock://dist-headers"));
await ctx.Start();
await ctx.SendBodyAndHeaders("direct://dist-headers", "a", new Dictionary { ["Authorization"] = "Bearer one", ["temp"] = "one" });
await ctx.SendBodyAndHeaders("direct://dist-headers", "a", new Dictionary { ["Authorization"] = "Bearer two", ["temp"] = "two" });
var hit = ctx.Mock("mock://dist-headers").ReceivedExchanges[1].In;
hit.Headers["cache.hit"].Should().Be(true);
hit.Headers["computed"].Should().Be("yes");
hit.Headers["Authorization"].Should().Be("Bearer two");
hit.Headers.Should().NotContainKey("temp");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheKeyRuleTests.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.Cache/CacheKeyRuleTests.cs
----
using AwesomeAssertions;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.Tests.Cache;
///
/// The four shapes of a cache key (the cache key rule after findings register row 29): a template with ${...}; a constant
/// that starts with no root of the exchange, kept as written even with a dash, a slash, a colon or a space; an
/// expression over a root, evaluated; broken arithmetic over a root, the row 29 error.
///
public sealed class CacheKeyRuleTests
{
private static Exchange Exchange()
{
var exchange = new Exchange(new Message("x"));
exchange.In.Headers["k"] = "a";
exchange.In.Headers["customerId"] = 42;
return exchange;
}
[Theory]
[InlineData("${header.k}-x", "a-x")]
[InlineData("customer-${header.customerId}", "customer-42")]
public void ATemplate_IsRendered(string key, string expected)
{
CacheDefinition.KeyFromTemplate(key)(Exchange()).Should().Be(expected);
}
[Theory]
[InlineData("orders-all")]
[InlineData("k-out")]
[InlineData("b:c")]
[InlineData("reports/daily")]
[InlineData("plain text")]
[InlineData("2024-11")]
[InlineData("k")]
public void AConstant_IsTheKeyAsWritten(string key)
{
CacheDefinition.KeyFromTemplate(key)(Exchange()).Should().Be(key);
}
[Theory]
[InlineData("header.customerId", "42")]
[InlineData("header.customerId + 1", "43")]
[InlineData("upper(header.k)", "A")]
[InlineData("'quoted'", "quoted")]
public void AnExpressionOverARoot_IsEvaluated(string key, string expected)
{
CacheDefinition.KeyFromTemplate(key)(Exchange()).Should().Be(expected);
}
[Theory]
[InlineData("header.a+b")]
[InlineData("body-cache")]
public void BrokenArithmeticOverARoot_StaysAnError(string key)
{
var act = () => CacheDefinition.KeyFromTemplate(key);
act.Should().Throw().WithMessage("*is not a value*");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheProducerReplyTests.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.Cache/CacheProducerReplyTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
namespace redb.Route.Tests.Cache;
/// The cache: component reading an entry the scope stored as a reply (Out).
public class CacheProducerReplyTests
{
[Fact]
public async Task Get_RestoresAReplyWhereTheScopeLeftIt_InOut()
{
await using var ctx = new RouteContext();
ctx.UseCache();
ctx.AddRoutes(b =>
{
b.From("direct://reply-scope").Cache("k").Region("replies").Process(e => e.Out = new Message("reply")).EndCache();
b.From("direct://reply-get").To("cache:replies?action=get&key=k");
});
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var miss = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://reply-scope", miss);
var read = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://reply-get", read);
read.In.Headers["cache.hit"].Should().Be(true);
read.Out.Should().NotBeNull("the scope cached a reply; the component must hand it back as a reply, not as the request body");
read.Out!.Body.Should().Be("reply");
read.In.Body.Should().Be("in");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheRestartTests.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.Cache/CacheRestartTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
///
/// The cache: component keeps working after Stop() and Start() of the same route context, and the
/// entries put before the restart are still there: the store belongs to the context, not to a run of its routes.
///
public class CacheRestartTests
{
[Fact]
public async Task Get_and_put_work_after_the_context_is_stopped_and_started_again()
{
var ctx = new RouteContext();
ctx.UseCache();
await using var _ = ctx.AddRoutes(b =>
{
b.From("direct://get").To("cache:customers?action=get&key=${header.id}").To("mock://get");
b.From("direct://put").To("cache:customers?action=put&key=${header.id}&ttl=5m");
});
await ctx.Start();
await ctx.SendBodyAndHeader("direct://put", "cached-7", "id", 7);
await ctx.Stop();
await ctx.Start();
await ctx.SendBodyAndHeader("direct://get", "original", "id", 7);
await ctx.SendBodyAndHeader("direct://put", "cached-8", "id", 8);
await ctx.SendBodyAndHeader("direct://get", "original", "id", 8);
var got = ctx.Mock("mock://get").ReceivedExchanges;
got.Should().HaveCount(2);
got[0].In.Body.Should().Be("cached-7", "an entry put before the restart is visible after it");
got[1].In.Body.Should().Be("cached-8", "cache both puts and gets after a restart");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheReviewTests.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.Cache/CacheReviewTests.cs
----
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.Extensions.Caching.Memory;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// Code review 2026-09-01: a host cache with SizeLimit, duration parsing, Out on a hit, and what a hit hands back.
public class CacheReviewTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2);
[Fact]
public async Task HostMemoryCacheWithSizeLimit_IsUsable()
{
var calls = 0;
await using var ctx = new RouteContext();
ctx.AddService(typeof(IMemoryCache), new MemoryCache(new MemoryCacheOptions { SizeLimit = 100 }));
ctx.AddRoutes(b => b.From("direct://sized").Cache("k").Process(_ => Interlocked.Increment(ref calls)).EndCache());
await ctx.Start();
await ctx.SendBody("direct://sized", "x");
await ctx.SendBody("direct://sized", "x");
calls.Should().Be(1, "the second send is a hit; a sized host cache must not reject the entry on every miss");
}
[Theory]
[InlineData("5")]
[InlineData("30")]
public void Duration_BareNumber_IsRejected(string text)
{
var act = () => CacheDuration.Parse(text);
act.Should().Throw("a number without a unit is ambiguous: TimeSpan would read it as days");
}
[Theory]
[InlineData("0s")]
[InlineData("-5m")]
[InlineData("00:00:00")]
public void Duration_NonPositive_IsRejected(string text)
{
var act = () => CacheDuration.Parse(text);
act.Should().Throw();
}
[Theory]
[InlineData("9999999999d")]
[InlineData("1e400ms")]
[InlineData("NaNs")]
[InlineData("Infinityh")]
public void Duration_OutOfRange_IsAFormatError(string text)
{
var act = () => CacheDuration.Parse(text);
act.Should().Throw("an unusable number is a format error like any other typo, not an overflow out of TimeSpan");
}
[Fact]
public async Task Hit_RestoresOut_WhenTheMissProducedOut()
{
// The scope is the route's last step, so its Out reaches the caller the way a reply does (the
// pipeline merges Out into In only between steps); caller-owned exchanges make Out observable.
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://out")
.Cache("k-out").Process(e => e.Out = new Message("out-body")).EndCache());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var miss = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://out", miss);
var hit = Exchange.Create(new Message("in"), null);
await template.SendAsync("direct://out", hit);
miss.Out?.Body.Should().Be("out-body");
hit.Out.Should().NotBeNull("a hit must leave the exchange the way the miss did: a consumer that replies only when Out is present must see one");
hit.Out!.Body.Should().Be("out-body");
}
[Fact]
public async Task StreamBody_IsBufferedOnTheMiss_AndReplayableOnHits()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://stream")
.Cache("k-stream").Process(e => e.In.Body = new MemoryStream("payload"u8.ToArray())).EndCache()
.To("mock://stream"));
await ctx.Start();
await ctx.SendBody("direct://stream", "in");
await ctx.SendBody("direct://stream", "in");
await ctx.Mock("mock://stream").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait);
var bodies = ctx.Mock("mock://stream").ReceivedExchanges.Select(e => e.In.Body).ToList();
bodies.Should().AllBeOfType("a stream can be read once; the cache keeps bytes and hands bytes back");
bodies.Select(body => Encoding.UTF8.GetString((byte[])body!)).Should().Equal("payload", "payload");
}
[Fact]
public async Task JsonNodeBody_IsCopiedIntoAndOutOfTheCache()
{
var seen = new List();
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://node")
.Cache("k-node").Process(e => e.In.Body = JsonNode.Parse("""{"n":1}""")).EndCache()
.Process(e => seen.Add(((JsonObject)e.In.Body!)["n"]!.GetValue()))
.Process(e => ((JsonObject)e.In.Body!)["n"] = 2)); // a later step mutates what it got
await ctx.Start();
await ctx.SendBody("direct://node", "in");
await ctx.SendBody("direct://node", "in");
seen.Should().Equal(1, 1); // neither the miss's later mutation nor a hit's reaches the cached copy
}
// Fourth batch: region keys, and a stampede on one key.
[Fact]
public async Task Regions_DoNotCollideOnTheSeparator_AndClearStaysInItsRegion()
{
await using var ctx = new RouteContext();
ctx.UseCache();
ctx.AddRoutes(b =>
{
b.From("direct://reg-a").Cache("b:c").Region("a").SetBody("from-a").EndCache().To("mock://reg-a");
b.From("direct://reg-ab").Cache("c").Region("a:b").SetBody("from-ab").EndCache().To("mock://reg-ab");
b.From("direct://reg-clear-a").To("cache:a?action=clear");
});
await ctx.Start();
await ctx.SendBody("direct://reg-a", "x");
await ctx.SendBody("direct://reg-ab", "x"); // region "a:b" key "c" must not be region "a" key "b:c"
await ctx.SendBody("direct://reg-clear-a", "x");
await ctx.SendBody("direct://reg-ab", "x"); // clearing "a" must not reach "a:b"
var received = ctx.Mock("mock://reg-ab").ReceivedExchanges;
received.Select(e => e.In.Body).Should().Equal("from-ab", "from-ab");
received[1].In.Headers["cache.hit"].Should().Be(true);
}
[Fact]
public async Task ConcurrentMissesOnOneKey_RunTheInnerStepsOnce()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://stampede")
.Cache("hot", TimeSpan.FromMinutes(1))
.Process(async (e, ct) =>
{
Interlocked.Increment(ref calls);
await Task.Delay(300, ct);
e.In.Body = "computed";
})
.EndCache()
.To("mock://stampede"));
await ctx.Start();
await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => ctx.SendBody("direct://stampede", "in")));
calls.Should().Be(1, "the first miss computes; the other nineteen wait for its result");
var bodies = ctx.Mock("mock://stampede").ReceivedExchanges.Select(e => e.In.Body).ToList();
bodies.Should().HaveCount(20).And.AllBeEquivalentTo("computed");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/CacheScopeTests.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.Cache/CacheScopeTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// The caching scope over the in-process cache.
public class CacheScopeTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2);
[Fact]
public async Task Hit_SkipsInnerSteps_Miss_RunsThem()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://c")
.Cache("customer-${header.id}", TimeSpan.FromMinutes(5))
.Process(e => { Interlocked.Increment(ref calls); e.In.Body = $"loaded {e.In.Headers["id"]}"; })
.EndCache()
.To("mock://c"));
await ctx.Start();
await ctx.SendBodyAndHeader("direct://c", "q", "id", 1);
await ctx.SendBodyAndHeader("direct://c", "q", "id", 1);
await ctx.SendBodyAndHeader("direct://c", "q", "id", 2);
calls.Should().Be(2, "id 1 was a miss then a hit, id 2 a miss");
var mock = ctx.Mock("mock://c");
await mock.ExpectBodies("loaded 1", "loaded 1", "loaded 2").AssertIsSatisfiedAsync(Wait);
mock.ReceivedExchanges.Select(e => e.In.Headers["cache.hit"]).Should().Equal(false, true, false);
}
[Fact]
public async Task Ttl_Expires()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://ttl")
.Cache("k", TimeSpan.FromMilliseconds(200)).Process(_ => Interlocked.Increment(ref calls)).EndCache());
await ctx.Start();
await ctx.SendBody("direct://ttl", "x");
await ctx.SendBody("direct://ttl", "x");
await Task.Delay(400);
await ctx.SendBody("direct://ttl", "x");
calls.Should().Be(2);
}
[Fact]
public async Task CacheHeaders_RestoresHeaders_DefaultDoesNot()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://h").Cache("k").CacheHeaders().SetHeader("computed", "yes").SetBody("v").EndCache().To("mock://h");
b.From("direct://nh").Cache("k2").SetHeader("computed", "yes").SetBody("v").EndCache().To("mock://nh");
});
await ctx.Start();
await ctx.SendBody("direct://h", "a");
await ctx.SendBody("direct://h", "a");
await ctx.SendBody("direct://nh", "a");
await ctx.SendBody("direct://nh", "a");
ctx.Mock("mock://h").ReceivedExchanges[1].In.Headers.Should().ContainKey("computed");
ctx.Mock("mock://nh").ReceivedExchanges[1].In.Headers.Should().NotContainKey("computed");
ctx.Mock("mock://nh").ReceivedExchanges[1].In.Body.Should().Be("v");
}
[Fact]
public async Task KeyFromBody_HashesTheBody()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://kb").Cache("ignored").KeyFromBody().Process(_ => Interlocked.Increment(ref calls)).EndCache());
await ctx.Start();
await ctx.SendBody("direct://kb", "same");
await ctx.SendBody("direct://kb", "same");
await ctx.SendBody("direct://kb", "other");
calls.Should().Be(2);
}
[Fact]
public async Task Regions_Isolate_Keys()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://r1").Cache("k").Region("one").Process(_ => Interlocked.Increment(ref calls)).EndCache();
b.From("direct://r2").Cache("k").Region("two").Process(_ => Interlocked.Increment(ref calls)).EndCache();
});
await ctx.Start();
await ctx.SendBody("direct://r1", "x");
await ctx.SendBody("direct://r2", "x");
calls.Should().Be(2, "same key, different regions");
}
[Fact]
public async Task FailedInner_IsNotCached()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://f")
.Cache("k").Process(_ => { Interlocked.Increment(ref calls); throw new InvalidOperationException("down"); }).EndCache());
await ctx.Start();
for (var i = 0; i < 2; i++)
{
var act = () => ctx.SendBody("direct://f", "x");
await act.Should().ThrowAsync();
}
calls.Should().Be(2);
}
[Fact]
public async Task MaxEntries_Option_BoundsTheCache()
{
var calls = 0;
await using var ctx = new RouteContext();
ctx.UseCache(o => o.MaxEntries = 1);
ctx.AddRoutes(b => b.From("direct://max").Cache("${header.id}").Process(_ => Interlocked.Increment(ref calls)).EndCache());
await ctx.Start();
await ctx.SendBodyAndHeader("direct://max", "x", "id", 1);
await ctx.SendBodyAndHeader("direct://max", "x", "id", 2); // over the limit: MemoryCache rejects the newcomer (or compacts)
await ctx.SendBodyAndHeader("direct://max", "x", "id", 1);
await ctx.SendBodyAndHeader("direct://max", "x", "id", 2);
// Unbounded, the second round would be two hits (calls == 2). With one slot at least one of the
// two keys is a miss again — whether MemoryCache rejected the newcomer (3) or evicted the older (4).
calls.Should().BeInRange(3, 4);
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/ComponentSideTests.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.Cache/ComponentSideTests.cs
----
using redb.Route.Core;
using redb.Route.Cache;
namespace redb.Route.Tests.Cache;
/// The component declares the only side it has ([EndpointRole], Apache Camel's producerOnly / consumerOnly).
public sealed class ComponentSideTests
{
[Fact]
public void The_component_declares_its_only_side()
{
EndpointSides.Declaration(typeof(CacheComponent))!.Role.Should().Be(EndpointRole.Producer);
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/DistributedBodyTypeTests.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.Cache/DistributedBodyTypeTests.cs
----
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// Object bodies through the distributed store: the type name travels with the entry.
public class DistributedBodyTypeTests
{
public sealed class Order
{
public int Id { get; set; }
public string Customer { get; set; } = "";
}
private static RouteContext Context()
{
var ctx = new RouteContext();
ctx.UseCache(o => o.DefaultProvider = CacheProvider.Distributed);
ctx.AddService(typeof(IDistributedCache), new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())));
return ctx;
}
[Fact]
public async Task AnonymousBody_RoundTrips_LikeAnyTypeOfTheWritersAssembly()
{
// Safety net: an anonymous type is a type of the writer's assembly like any other, and comes back
// as itself wherever that assembly is loaded.
var calls = 0;
await using var ctx = Context().AddRoutes(b => b
.From("direct://anon")
.Cache("k").Process(e => { Interlocked.Increment(ref calls); e.In.Body = new { Id = 7, Customer = "acme" }; }).EndCache()
.To("mock://anon"));
await ctx.Start();
await ctx.SendBody("direct://anon", "in");
await ctx.SendBody("direct://anon", "in");
calls.Should().Be(1);
var hit = ctx.Mock("mock://anon").ReceivedExchanges[1].In;
hit.Headers["cache.hit"].Should().Be(true);
hit.Body.Should().BeEquivalentTo(new { Id = 7, Customer = "acme" });
hit.Body!.GetType().Should().Be(new { Id = 0, Customer = "" }.GetType());
}
[Fact]
public async Task ManyHits_OnOnePocoType_ComeBackTyped()
{
// Safety net for the resolved-type and serialize-method caches: the second and later reads take the cached path.
var calls = 0;
await using var ctx = Context().AddRoutes(b => b
.From("direct://typed")
.Cache("${header.id}").Process(e => { Interlocked.Increment(ref calls); e.In.Body = new Order { Id = (int)e.In.Headers["id"]!, Customer = "acme" }; }).EndCache()
.To("mock://typed"));
await ctx.Start();
for (var round = 0; round < 3; round++)
for (var id = 1; id <= 3; id++)
await ctx.SendBodyAndHeader("direct://typed", "in", "id", id);
calls.Should().Be(3, "three keys, each computed once");
ctx.Mock("mock://typed").ReceivedExchanges.Select(e => e.In.Body).Should().AllBeOfType();
ctx.Mock("mock://typed").ReceivedExchanges.Select(e => ((Order)e.In.Body!).Id).Should().Equal(1, 2, 3, 1, 2, 3, 1, 2, 3);
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/DistributedCacheTests.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.Cache/DistributedCacheTests.cs
----
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using Microsoft.Extensions.Options;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// The distributed provider: the reference in-memory implementation and a real Redis (tests/docker: localhost:6379).
public class DistributedCacheTests
{
public sealed class Order
{
public int Id { get; set; }
public string Customer { get; set; } = "";
}
private static RouteContext Context(IDistributedCache cache)
{
var ctx = new RouteContext();
ctx.UseCache(o => o.DefaultProvider = CacheProvider.Distributed);
ctx.AddService(typeof(IDistributedCache), cache);
return ctx;
}
private static IDistributedCache Memory() => new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
private static IDistributedCache Redis() => new RedisCache(Options.Create(new RedisCacheOptions
{
Configuration = "localhost:6379,abortConnect=false",
InstanceName = $"redb-route-cache-tests-{Guid.NewGuid():N}:",
}));
[Fact]
public async Task Poco_KeepsItsType_ThroughTheDistributedCache()
{
var calls = 0;
await using var ctx = Context(Memory()).AddRoutes(b => b
.From("direct://d")
.Cache("${header.id}", TimeSpan.FromMinutes(1))
.Process(e => { Interlocked.Increment(ref calls); e.In.Body = new Order { Id = 7, Customer = "acme" }; })
.EndCache()
.To("mock://d"));
await ctx.Start();
await ctx.SendBodyAndHeader("direct://d", "x", "id", 7);
await ctx.SendBodyAndHeader("direct://d", "x", "id", 7);
calls.Should().Be(1);
var hit = ctx.Mock("mock://d").ReceivedExchanges[1].In;
hit.Headers["cache.hit"].Should().Be(true);
hit.Body.Should().BeOfType().Which.Customer.Should().Be("acme");
hit.ContentType.Should().Be("application/json");
}
[Fact]
public async Task String_Bytes_AndHeaders_RoundTrip()
{
await using var ctx = Context(Memory()).AddRoutes(b =>
{
b.From("direct://put").To("cache:r?action=put&key=${header.id}&headers=n,flag");
b.From("direct://get").To("cache:r?action=get&key=${header.id}").To("mock://get");
});
await ctx.Start();
await ctx.SendBodyAndHeaders("direct://put", "text", new Dictionary { ["id"] = "s", ["n"] = 5, ["flag"] = true });
await ctx.SendBodyAndHeader("direct://put", new byte[] { 1, 2, 3 }, "id", "b");
await ctx.SendBodyAndHeader("direct://get", "x", "id", "s");
await ctx.SendBodyAndHeader("direct://get", "x", "id", "b");
var got = ctx.Mock("mock://get").ReceivedExchanges;
got[0].In.Body.Should().Be("text");
got[0].In.Headers["n"].Should().Be(5L, "JSON numbers come back as Int64");
got[0].In.Headers["flag"].Should().Be(true);
got[1].In.Body.Should().BeEquivalentTo(new byte[] { 1, 2, 3 });
}
[Fact]
public async Task Clear_RemovesASlidingKeyKeptAliveByReads()
{
// The store keeps its own list of written keys (IDistributedCache cannot enumerate) and sweeps the
// expired ones every 256 writes. A sliding entry that is read all the time outlives its write plus
// the window, so the list must follow the reads, or clear skips a live key.
var store = new DistributedCacheStore(Memory(), null);
var key = CacheKeys.For("r", "warm");
// A one-second window read every 100 ms: the margin has to survive a machine busy with other builds.
await store.SetAsync(key, new CacheEntry { Body = "v" }, ttl: null, sliding: TimeSpan.FromSeconds(1), CancellationToken.None);
var until = DateTime.UtcNow.AddMilliseconds(1500);
while (DateTime.UtcNow < until)
{
(await store.GetAsync(key, CancellationToken.None)).Should().NotBeNull("reads renew a sliding entry");
await Task.Delay(100);
}
for (var i = 0; i < 256; i++)
await store.SetAsync(CacheKeys.For("r", $"other-{i}"), new CacheEntry { Body = "x" }, TimeSpan.FromMinutes(1), null, CancellationToken.None);
await store.ClearAsync("r", CancellationToken.None);
(await store.GetAsync(key, CancellationToken.None)).Should().BeNull("clear must remove a key that is still alive");
}
[Fact]
public async Task MissingDistributedCache_FailsStart_WithGuidance()
{
await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://x").Cache("k").Distributed().SetBody("v").EndCache());
var act = () => ctx.Start();
await act.Should().ThrowAsync().WithMessage("*IDistributedCache*");
}
[Fact]
public async Task Redis_RealContainer_RoundTrip()
{
var calls = 0;
await using var ctx = Context(Redis()).AddRoutes(b => b
.From("direct://redis")
.Cache("${header.id}", TimeSpan.FromSeconds(30))
.Process(e => { Interlocked.Increment(ref calls); e.In.Body = new Order { Id = 1, Customer = "redis" }; })
.EndCache()
.To("mock://redis"));
await ctx.Start();
await ctx.SendBodyAndHeader("direct://redis", "x", "id", 1);
await ctx.SendBodyAndHeader("direct://redis", "x", "id", 1);
calls.Should().Be(1, "the second message is served by Redis");
ctx.Mock("mock://redis").ReceivedExchanges[1].In.Body.Should().BeOfType().Which.Customer.Should().Be("redis");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/DistributedEnvelopeTests.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.Cache/DistributedEnvelopeTests.cs
----
using System.Text;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// What the distributed store makes of a value under its key that it did not write.
public class DistributedEnvelopeTests
{
private static IDistributedCache Memory() => new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
private static RouteContext Context(IDistributedCache cache)
{
var ctx = new RouteContext();
ctx.UseCache(o => o.DefaultProvider = CacheProvider.Distributed);
ctx.AddService(typeof(IDistributedCache), cache);
return ctx;
}
[Fact]
public async Task ForeignJson_UnderOurKey_IsAnError_NotAHitWithAnEmptyBody()
{
var cache = Memory();
await cache.SetAsync(CacheKeys.For("default", "k"), Encoding.UTF8.GetBytes("""{"id":1}"""));
var calls = 0;
await using var ctx = Context(cache).AddRoutes(b => b
.From("direct://foreign").Cache("k").Process(e => { calls++; e.In.Body = "computed"; }).EndCache().To("mock://foreign"));
await ctx.Start();
var act = () => ctx.SendBody("direct://foreign", "in");
var failure = await act.Should().ThrowAsync("another writer's value under our key is a shared key space, not a hit and not a miss");
failure.Which.Message.Should().Contain(CacheKeys.For("default", "k")).And.Contain("cache entry");
calls.Should().Be(0, "no silent recompute over somebody else's value");
ctx.Mock("mock://foreign").ReceivedExchanges.Should().BeEmpty("no hit with a null body either");
}
[Fact]
public async Task NonJsonBytes_UnderOurKey_IsAnError_NamingTheKey()
{
var cache = Memory();
await cache.SetAsync(CacheKeys.For("default", "k"), new byte[] { 0x01, 0x02, 0x03 });
await using var ctx = Context(cache).AddRoutes(b => b.From("direct://raw").Cache("k").SetBody("computed").EndCache());
await ctx.Start();
var act = () => ctx.SendBody("direct://raw", "in");
var failure = await act.Should().ThrowAsync();
failure.Which.Message.Should().Contain(CacheKeys.For("default", "k"));
}
[Fact]
public async Task NullBody_IsACachedValue_NotAMiss()
{
// Safety net for the envelope marker: a null body is a legitimate cached value and must stay a hit.
var calls = 0;
await using var ctx = Context(Memory()).AddRoutes(b => b
.From("direct://null").Cache("k").Process(e => { calls++; e.In.Body = null; }).EndCache().To("mock://null"));
await ctx.Start();
await ctx.SendBody("direct://null", "in");
await ctx.SendBody("direct://null", "in");
calls.Should().Be(1);
var hit = ctx.Mock("mock://null").ReceivedExchanges[1].In;
hit.Headers["cache.hit"].Should().Be(true);
hit.Body.Should().BeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/KeyFromBodyTests.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.Cache/KeyFromBodyTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// KeyFromBody(): the key is a hash of the body, whatever the body is.
public class KeyFromBodyTests
{
public sealed class Order
{
public int Id { get; set; }
public string Customer { get; set; } = "";
}
public sealed class Node
{
public Node? Next { get; set; }
}
[Fact]
public async Task StreamBody_IsBufferedAndHashed()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://kb-stream").Cache("ignored").KeyFromBody().Process(_ => Interlocked.Increment(ref calls)).EndCache().To("mock://kb-stream"));
await ctx.Start();
await ctx.SendBody("direct://kb-stream", new MemoryStream("payload"u8.ToArray()));
await ctx.SendBody("direct://kb-stream", new MemoryStream("payload"u8.ToArray()));
await ctx.SendBody("direct://kb-stream", new MemoryStream("other"u8.ToArray()));
calls.Should().Be(2, "two equal payloads share one key");
ctx.Mock("mock://kb-stream").ReceivedExchanges.Select(e => e.In.Body)
.Should().AllBeOfType("a stream is read once to hash it; the steps continue with its bytes");
}
[Fact]
public async Task PocoBody_IsHashedThroughTheContextDataFormat()
{
// Safety net: a POCO hashed the same way the distributed store serializes it.
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://kb-poco").Cache("ignored").KeyFromBody().Process(_ => Interlocked.Increment(ref calls)).EndCache());
await ctx.Start();
await ctx.SendBody("direct://kb-poco", new Order { Id = 1, Customer = "acme" });
await ctx.SendBody("direct://kb-poco", new Order { Id = 1, Customer = "acme" });
await ctx.SendBody("direct://kb-poco", new Order { Id = 2, Customer = "acme" });
calls.Should().Be(2);
}
[Fact]
public async Task UnserializableBody_FailsNamingTheKeyMode()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://kb-cycle").Cache("ignored").KeyFromBody().SetBody("v").EndCache());
await ctx.Start();
var node = new Node();
node.Next = node;
var act = () => ctx.SendBody("direct://kb-cycle", node);
var failure = await act.Should().ThrowAsync();
failure.Which.Message.Should().Contain("KeyFromBody").And.Contain(nameof(Node));
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/SingleFlightTests.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.Cache/SingleFlightTests.cs
----
using redb.Route.Cache;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Cache;
/// One computation per key at a time, across every cache node of the process that shares the store.
public class SingleFlightTests
{
[Fact]
public async Task ConcurrentMisses_OnOneKey_AcrossTwoNodes_RunTheInnerStepsOnce()
{
var calls = 0;
await using var ctx = new RouteContext().AddRoutes(b =>
{
foreach (var name in new[] { "a", "b" })
b.From($"direct://flight-{name}")
.Cache("hot", TimeSpan.FromMinutes(1)).Region("flight")
.Process(async (e, ct) =>
{
Interlocked.Increment(ref calls);
await Task.Delay(300, ct);
e.In.Body = "computed";
})
.EndCache()
.To("mock://flight");
});
await ctx.Start();
await Task.WhenAll(Enumerable.Range(0, 20).Select(i => ctx.SendBody(i % 2 == 0 ? "direct://flight-a" : "direct://flight-b", "in")));
calls.Should().Be(1, "the two nodes share one store, so they share one flight per key");
ctx.Mock("mock://flight").ReceivedExchanges.Select(e => e.In.Body).Should().HaveCount(20).And.AllBeEquivalentTo("computed");
}
}
Path: redb-route/tests/redb.Route.Tests.Cache/redb.Route.Tests.Cache.csproj
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.Cache/redb.Route.Tests.Cache.csproj
----