Bundle: redb-route / tests/redb.Route.Tests.Quartz (tests.redb.Route.Tests.Quartz.txt), 16 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.Quartz/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.Quartz/ComponentSideTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// 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(CronComponent))!.Role.Should().Be(EndpointRole.Consumer); EndpointSides.Declaration(typeof(QuartzTimerComponent))!.Role.Should().Be(EndpointRole.Consumer); } } Path: redb-route/tests/redb.Route.Tests.Quartz/CronComponentTests.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.Quartz/CronComponentTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Tests for CronComponent, CronEndpoint, CronEndpointOptions, and CronConsumer. /// public class CronComponentTests { // ── Component ── [Fact] public void Scheme_IsCron() { var component = new CronComponent(); component.Scheme.Should().Be("cron"); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new CronComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_ValidUri_ReturnsCronEndpoint() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_MissingSchedule_Throws() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob"); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*schedule*"); } [Fact] public void CreateEndpoint_InvalidCronExpression_Throws() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=not-a-cron"); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*Invalid cron*"); } // ── Options ── [Fact] public void Options_DefaultValues() { var opts = new CronEndpointOptions(); opts.Schedule.Should().BeEmpty(); opts.Threads.Should().Be(1); } [Fact] public void Options_Validate_MissingSchedule_Throws() { var opts = new CronEndpointOptions(); var act = () => opts.Validate(); act.Should().Throw().WithMessage("*schedule*"); } [Fact] public void Options_Validate_InvalidSchedule_Throws() { var opts = new CronEndpointOptions { Schedule = "invalid" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Invalid cron*"); } [Fact] public void Options_Validate_ZeroThreads_Throws() { var opts = new CronEndpointOptions { Schedule = "0/5 * * * * ?", Threads = 0 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_ValidSchedule_Passes() { var opts = new CronEndpointOptions { Schedule = "0 0 12 * * ?" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Options_BindFromUri_ParsesScheduleAndThreads() { var uri = EndpointUriParser.Parse("cron://job1?schedule=0/10 * * * * ?&threads=4"); var opts = new CronEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Schedule.Should().Be("0/10 * * * * ?"); opts.Threads.Should().Be(4); } // ── Endpoint ── [Fact] public void Endpoint_CreateProducer_ThrowsNotSupported() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?"); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateProducer(); act.Should().Throw(); } [Fact] public void Endpoint_CreateConsumer_NullProcessor_Throws() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?"); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } [Fact] public void Endpoint_CreateConsumer_ReturnsCronConsumer() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } // ── Consumer lifecycle with real Quartz scheduler ── [Fact] public async Task Consumer_StartStop_Lifecycle() { var component = new CronComponent(); var context = new RouteContext("cron-test-1"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("cron://tick?schedule=0/1 * * * * ?"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = endpoint.CreateConsumer(processor); // Start should not throw await consumer.Start(); // Consumer should be registered under the job it claimed on the context's scheduler var scheduler = context.GetService()!; var jobKey = new global::Quartz.JobKey("tick", "redb"); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().NotBeNull(); // Stop should not throw await consumer.Stop(); // Consumer should be unregistered QuartzConsumerRegistry.Get(scheduler, jobKey).Should().BeNull(); context.Dispose(); } [Fact] public async Task Consumer_RequiresRouteContext() { // Component without Context → Start should throw var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://tick?schedule=0/1 * * * * ?"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*RouteContext*"); } [Fact] public async Task Consumer_FiresProcessor_OnCronSchedule() { var component = new CronComponent(); var context = new RouteContext("cron-fire-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler // Every second var uri = EndpointUriParser.Parse("cron://rapid?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); var fireCount = 0; Abstractions.IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { Interlocked.Increment(ref fireCount); capturedExchange = ci.Arg(); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // Wait up to 5 seconds for at least one fire for (var i = 0; i < 50 && fireCount == 0; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); fireCount.Should().BeGreaterThan(0, "cron should have fired at least once"); capturedExchange.Should().NotBeNull(); capturedExchange!.Properties.Should().ContainKey("CamelCronSchedule"); capturedExchange.Properties["CamelCronSchedule"].Should().Be("* * * * * ?"); capturedExchange.Properties.Should().ContainKey("CamelCronName"); capturedExchange.Properties["CamelCronName"].Should().Be("rapid"); capturedExchange.Properties.Should().ContainKey("CamelQuartzFireTime"); capturedExchange.Properties.Should().ContainKey("CamelQuartzScheduledFireTime"); } [Fact] public async Task Consumer_ExchangePattern_IsInOnly() { var component = new CronComponent(); var context = new RouteContext("cron-pattern-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("cron://check?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Pattern.Should().Be(Abstractions.ExchangePattern.InOnly); } [Fact] public async Task Consumer_SharedScheduler_BetweenMultipleConsumers() { var component = new CronComponent(); var context = new RouteContext("cron-shared-scheduler"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri1 = EndpointUriParser.Parse("cron://job1?schedule=* * * * * ?"); var uri2 = EndpointUriParser.Parse("cron://job2?schedule=* * * * * ?"); var ep1 = component.CreateEndpoint(uri1); var ep2 = component.CreateEndpoint(uri2); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var c1 = ep1.CreateConsumer(processor); var c2 = ep2.CreateConsumer(processor); await c1.Start(); await c2.Start(); // Both should share the same IScheduler via RouteContext service var scheduler = context.GetService(); scheduler.Should().NotBeNull("scheduler should be registered in context"); await c1.Stop(); await c2.Stop(); context.Dispose(); } [Fact] public async Task Consumer_StopIdempotent() { var component = new CronComponent(); var context = new RouteContext("cron-stop-idem"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("cron://idem?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // Double stop should not throw await consumer.Stop(); var act = () => consumer.Stop(); await act.Should().NotThrowAsync(); context.Dispose(); } [Fact] public async Task Consumer_ExceptionInProcessor_HandledViaRouteContext() { var component = new CronComponent(); var context = new RouteContext("cron-error-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("cron://errJob?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); var errorThrown = false; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { errorThrown = true; throw new InvalidOperationException("Test error in cron processor"); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // Wait for at least one fire for (var i = 0; i < 50 && !errorThrown; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); errorThrown.Should().BeTrue("processor should have been called"); // Exception is handled by routeContext.HandleException — no unhandled crash } // ── Cron expression validation variants ── [Theory] [InlineData("0 0 12 * * ?", "every day at noon")] [InlineData("0 15 10 ? * MON-FRI", "weekdays at 10:15")] [InlineData("0/5 * * * * ?", "every 5 seconds")] [InlineData("0 0 0 1 1 ?", "midnight Jan 1")] public void Options_Validate_VariousCronExpressions_Passes(string expression, string _) { var opts = new CronEndpointOptions { Schedule = expression }; var act = () => opts.Validate(); act.Should().NotThrow(); } // ── New Camel-compatible options ── [Fact] public void Options_DefaultGroupName_IsRedb() { var opts = new CronEndpointOptions(); opts.GroupName.Should().Be("redb"); } [Fact] public void Options_DefaultDeleteJob_IsTrue() { var opts = new CronEndpointOptions(); opts.DeleteJob.Should().BeTrue(); } [Fact] public void Options_DefaultTriggerStartDelay_Is500() { var opts = new CronEndpointOptions(); opts.TriggerStartDelay.Should().Be(500); } [Fact] public void Options_DeleteJobAndPauseJob_BothTrue_Throws() { var opts = new CronEndpointOptions { Schedule = "0/5 * * * * ?", DeleteJob = true, PauseJob = true }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*deleteJob*pauseJob*"); } [Fact] public void Options_BindFromUri_ParsesNewParams() { var uri = EndpointUriParser.Parse("cron://job1?schedule=0/10 * * * * ?&stateful=true&recoverableJob=true&timeZone=Europe/Moscow&misfireInstruction=CronDoNothing"); var opts = new CronEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Schedule.Should().Be("0/10 * * * * ?"); opts.Stateful.Should().BeTrue(); opts.RecoverableJob.Should().BeTrue(); opts.TimeZone.Should().Be("Europe/Moscow"); opts.MisfireInstruction.Should().Be(QuartzMisfirePolicy.CronDoNothing); } [Fact] public void CreateEndpoint_WithGroupInPath_ParsesGroupAndJob() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://billing/invoice?schedule=0 0 2 * * ?"); var endpoint = (CronEndpoint)component.CreateEndpoint(uri); endpoint.GroupName.Should().Be("billing"); endpoint.JobName.Should().Be("invoice"); } [Fact] public void CreateEndpoint_SingleName_DefaultGroup() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?"); var endpoint = (CronEndpoint)component.CreateEndpoint(uri); endpoint.GroupName.Should().Be("redb"); endpoint.JobName.Should().Be("myJob"); } [Fact] public void CreateEndpoint_Stateful_PropagatedToEndpoint() { var component = new CronComponent(); var uri = EndpointUriParser.Parse("cron://myJob?schedule=0/5 * * * * ?&stateful=true&recoverableJob=true"); var endpoint = (CronEndpoint)component.CreateEndpoint(uri); endpoint.Stateful.Should().BeTrue(); endpoint.RecoverableJob.Should().BeTrue(); } [Fact] public async Task Consumer_FiresWithGroupProperties() { var component = new CronComponent(); var context = new RouteContext("cron-group-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("cron://billing/invoice?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Properties["CamelCronName"].Should().Be("invoice"); captured.Properties["CamelCronGroup"].Should().Be("billing"); } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzBuilderTests.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.Quartz/QuartzBuilderTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; public class CronBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Schedule_StartsWithCronScheme() { var uri = Cron.Schedule("job1", "0/5 * * * * ?").Build(); uri.Should().StartWith("cron:job1?"); } [Fact] public void Schedule_ContainsEncodedExpression() { var uri = Cron.Schedule("job1", "0/5 * * * * ?").Build(); uri.Should().Contain("schedule="); } [Fact] public void NullName_Throws() { var act = () => Cron.Schedule(null!, "0/5 * * * * ?"); act.Should().Throw(); } [Fact] public void NullSchedule_Throws() { var act = () => Cron.Schedule("job1", null!); act.Should().Throw(); } [Fact] public void EmptyName_Throws() { var act = () => Cron.Schedule("", "0/5 * * * * ?"); act.Should().Throw(); } // ── Round-trip guard ───────────────────────────────────────────── // Build() must survive EndpointUriParser (the ecosystem reader). Regression: HttpUtility.UrlEncode // wrote a space as '+', but the parser's Uri.UnescapeDataString leaves '+' as-is — so every // space-bearing cron expression came back corrupted and CronEndpointOptions.Validate() threw inside // context.Start(), taking down the whole module. Uri.EscapeDataString writes %20, which round-trips. [Theory] [InlineData("0 */5 * * * ?")] [InlineData("0/30 * * * * ?")] [InlineData("0 0 12 ? * MON-FRI")] [InlineData("0 15 10 ? * 6L")] public void Build_ScheduleRoundTripsThroughParser(string schedule) { var parsed = EndpointUriParser.Parse(Cron.Schedule("job1", schedule).Build()); parsed.RawParameters["schedule"].Should().Be(schedule); } // ── Params ────────────────────────────────────────────────────── [Fact] public void Threads_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").Threads(4).Build(); uri.Should().Contain("threads=4"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = Cron.Schedule("job1", "0/5 * * * * ?").Threads(2); uri.Should().StartWith("cron:job1?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = Cron.Schedule("j", "0/5 * * * * ?").Threads(2); builder.ToString().Should().Be(builder.Build()); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = Cron.Schedule("job1", "0/5 * * * * ?").Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("cron"); parsed.Path.Should().Be("job1"); parsed.RawParameters.Should().ContainKey("schedule"); } // ── Group/name in path ────────────────────────────────────────── [Fact] public void GroupAndName_EncodesInPath() { var uri = Cron.Schedule("billing/invoice", "0 0 2 * * ?").Build(); uri.Should().StartWith("cron:billing/invoice?"); } // ── Job lifecycle params ──────────────────────────────────────── [Fact] public void DeleteJob_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").DeleteJob(false).Build(); uri.Should().Contain("deleteJob=false"); } [Fact] public void PauseJob_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").PauseJob().Build(); uri.Should().Contain("pauseJob=true"); } [Fact] public void DurableJob_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").DurableJob().Build(); uri.Should().Contain("durableJob=true"); } [Fact] public void Stateful_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").Stateful().Build(); uri.Should().Contain("stateful=true"); } [Fact] public void Recoverable_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").Recoverable().Build(); uri.Should().Contain("recoverableJob=true"); } [Fact] public void PrefixJobNameWithEndpointId_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").PrefixJobNameWithEndpointId().Build(); uri.Should().Contain("prefixJobNameWithEndpointId=true"); } // ── Trigger timing params ─────────────────────────────────────── [Fact] public void MisfireInstruction_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?") .MisfireInstruction(QuartzMisfirePolicy.CronDoNothing).Build(); uri.Should().Contain("misfireInstruction=CronDoNothing"); } [Fact] public void TimeZone_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").TimeZone("Europe/Moscow").Build(); uri.Should().Contain("timeZone=Europe/Moscow"); } [Fact] public void StartAt_String_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").StartAt("2025-01-01T00:00:00Z").Build(); uri.Should().Contain("startAt="); } [Fact] public void EndAt_String_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").EndAt("2025-12-31T23:59:59Z").Build(); uri.Should().Contain("endAt="); } [Fact] public void CustomCalendar_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").CustomCalendar("holidays").Build(); uri.Should().Contain("customCalendar=holidays"); } [Fact] public void TriggerStartDelay_SetsParam() { var uri = Cron.Schedule("j", "0/5 * * * * ?").TriggerStartDelay(2000).Build(); uri.Should().Contain("triggerStartDelay=2000"); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_AllParams() { var uri = Cron.Schedule("billing/invoice", "0 0 2 * * ?") .Threads(4) .DeleteJob(false) .DurableJob() .Stateful() .Recoverable() .MisfireInstruction(QuartzMisfirePolicy.CronFireOnceNow) .TimeZone("Europe/Moscow") .CustomCalendar("holidays") .TriggerStartDelay(1000) .Build(); uri.Should().StartWith("cron:billing/invoice?"); uri.Should().Contain("threads=4"); uri.Should().Contain("deleteJob=false"); uri.Should().Contain("durableJob=true"); uri.Should().Contain("stateful=true"); uri.Should().Contain("recoverableJob=true"); uri.Should().Contain("misfireInstruction=CronFireOnceNow"); uri.Should().Contain("timeZone=Europe/Moscow"); uri.Should().Contain("customCalendar=holidays"); uri.Should().Contain("triggerStartDelay=1000"); } // ── Round-trip with new params ────────────────────────────────── [Fact] public void RoundTrip_GroupName_ParsedCorrectly() { var original = Cron.Schedule("billing/invoice", "0 0 2 * * ?") .Stateful().Recoverable().Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("cron"); parsed.Path.Should().Be("billing/invoice"); parsed.RawParameters["stateful"].Should().Be("true"); parsed.RawParameters["recoverableJob"].Should().Be("true"); } } public class QTimerBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Every_StartsWithQTimerScheme() { var uri = QTimer.Every("heartbeat").Build(); uri.Should().StartWith("qtimer:heartbeat"); } [Fact] public void NullName_Throws() { var act = () => QTimer.Every(null!); act.Should().Throw(); } [Fact] public void EmptyName_Throws() { var act = () => QTimer.Every(""); act.Should().Throw(); } // ── Params ────────────────────────────────────────────────────── [Fact] public void Period_SetsParam() { var uri = QTimer.Every("hb").Period(5000).Build(); uri.Should().Contain("period=5000"); } [Fact] public void Delay_SetsParam() { var uri = QTimer.Every("hb").Delay(1000).Build(); uri.Should().Contain("delay=1000"); } [Fact] public void FixedRate_SetsParam() { var uri = QTimer.Every("hb").FixedRate().Build(); uri.Should().Contain("fixedRate=true"); } [Fact] public void Threads_SetsParam() { var uri = QTimer.Every("hb").Threads(3).Build(); uri.Should().Contain("threads=3"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = QTimer.Every("hb").Period(5000).Delay(1000); uri.Should().StartWith("qtimer:hb?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = QTimer.Every("hb").Period(5000).FixedRate(); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_BuildsCorrectUri() { var uri = QTimer.Every("heartbeat") .Period(5000) .Delay(1000) .FixedRate() .Threads(2) .Build(); uri.Should().StartWith("qtimer:heartbeat?"); uri.Should().Contain("period=5000"); uri.Should().Contain("delay=1000"); uri.Should().Contain("fixedRate=true"); uri.Should().Contain("threads=2"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = QTimer.Every("hb").Period(5000).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("qtimer"); parsed.Path.Should().Be("hb"); parsed.RawParameters["period"].Should().Be("5000"); } // ── Group/name in path ────────────────────────────────────────── [Fact] public void GroupAndName_EncodesInPath() { var uri = QTimer.Every("monitoring/heartbeat").Build(); uri.Should().StartWith("qtimer:monitoring/heartbeat"); } // ── Job lifecycle params ──────────────────────────────────────── [Fact] public void DeleteJob_SetsParam() { var uri = QTimer.Every("hb").DeleteJob(false).Build(); uri.Should().Contain("deleteJob=false"); } [Fact] public void PauseJob_SetsParam() { var uri = QTimer.Every("hb").PauseJob().Build(); uri.Should().Contain("pauseJob=true"); } [Fact] public void DurableJob_SetsParam() { var uri = QTimer.Every("hb").DurableJob().Build(); uri.Should().Contain("durableJob=true"); } [Fact] public void Stateful_SetsParam() { var uri = QTimer.Every("hb").Stateful().Build(); uri.Should().Contain("stateful=true"); } [Fact] public void Recoverable_SetsParam() { var uri = QTimer.Every("hb").Recoverable().Build(); uri.Should().Contain("recoverableJob=true"); } [Fact] public void PrefixJobNameWithEndpointId_SetsParam() { var uri = QTimer.Every("hb").PrefixJobNameWithEndpointId().Build(); uri.Should().Contain("prefixJobNameWithEndpointId=true"); } // ── Trigger timing params ─────────────────────────────────────── [Fact] public void MisfireInstruction_SetsParam() { var uri = QTimer.Every("hb") .MisfireInstruction(QuartzMisfirePolicy.SimpleFireNow).Build(); uri.Should().Contain("misfireInstruction=SimpleFireNow"); } [Fact] public void RepeatCount_SetsParam() { var uri = QTimer.Every("hb").RepeatCount(10).Build(); uri.Should().Contain("repeatCount=10"); } [Fact] public void StartAt_SetsParam() { var uri = QTimer.Every("hb").StartAt("2025-06-01T00:00:00Z").Build(); uri.Should().Contain("startAt="); } [Fact] public void EndAt_SetsParam() { var uri = QTimer.Every("hb").EndAt("2025-12-31T23:59:59Z").Build(); uri.Should().Contain("endAt="); } [Fact] public void CustomCalendar_SetsParam() { var uri = QTimer.Every("hb").CustomCalendar("businessDays").Build(); uri.Should().Contain("customCalendar=businessDays"); } // ── Full chain with all params ────────────────────────────────── [Fact] public void FullChain_AllNewParams() { var uri = QTimer.Every("monitoring/heartbeat") .Period(5000) .Delay(1000) .FixedRate() .Threads(2) .DeleteJob(false) .DurableJob() .Stateful() .Recoverable() .MisfireInstruction(QuartzMisfirePolicy.SimpleFireNow) .RepeatCount(100) .CustomCalendar("holidays") .Build(); uri.Should().StartWith("qtimer:monitoring/heartbeat?"); uri.Should().Contain("period=5000"); uri.Should().Contain("delay=1000"); uri.Should().Contain("fixedRate=true"); uri.Should().Contain("threads=2"); uri.Should().Contain("deleteJob=false"); uri.Should().Contain("durableJob=true"); uri.Should().Contain("stateful=true"); uri.Should().Contain("recoverableJob=true"); uri.Should().Contain("misfireInstruction=SimpleFireNow"); uri.Should().Contain("repeatCount=100"); uri.Should().Contain("customCalendar=holidays"); } // ── Round-trip with new params ────────────────────────────────── [Fact] public void RoundTrip_GroupName_ParsedCorrectly() { var original = QTimer.Every("monitoring/heartbeat") .Period(5000).Stateful().Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("qtimer"); parsed.Path.Should().Be("monitoring/heartbeat"); parsed.RawParameters["stateful"].Should().Be("true"); } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzConsumerRegistryTests.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.Quartz/QuartzConsumerRegistryTests.cs ---- using System.Collections.Specialized; using Quartz; using Quartz.Impl; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Tests for QuartzConsumerRegistry — the running consumers of the process by the job they claimed on their scheduler. /// One job key, one consumer per scheduler: a second claimant is refused, never silently put in the first one's place. /// public class QuartzConsumerRegistryTests { [Fact] public async Task Get_Unregistered_ReturnsNull() { var scheduler = await NewScheduler(); QuartzConsumerRegistry.Get(scheduler, new JobKey("nonexistent", "redb")).Should().BeNull(); } [Fact] public async Task RegisterAndGet_ReturnsConsumer() { var scheduler = await NewScheduler(); var jobKey = new JobKey("ep1", "redb"); var key = QuartzConsumerRegistry.KeyOf(scheduler, jobKey); var consumer = CreateMockConsumer(); try { QuartzConsumerRegistry.TryRegister(key, consumer, out _).Should().BeTrue(); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().BeSameAs(consumer); } finally { QuartzConsumerRegistry.Unregister(key, consumer); } } [Fact] public async Task Unregister_RemovesConsumer() { var scheduler = await NewScheduler(); var jobKey = new JobKey("ep2", "redb"); var key = QuartzConsumerRegistry.KeyOf(scheduler, jobKey); var consumer = CreateMockConsumer(); QuartzConsumerRegistry.TryRegister(key, consumer, out _); QuartzConsumerRegistry.Unregister(key, consumer); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().BeNull(); } [Fact] public void Unregister_NonExistent_DoesNotThrow() { var act = () => QuartzConsumerRegistry.Unregister("does-not-exist", CreateMockConsumer()); act.Should().NotThrow(); } [Fact] public async Task ASecondClaimant_IsRefused_AndTheFirstStays() { var scheduler = await NewScheduler(); var jobKey = new JobKey("ep3", "redb"); var key = QuartzConsumerRegistry.KeyOf(scheduler, jobKey); var first = CreateMockConsumer(); var second = CreateMockConsumer(); try { QuartzConsumerRegistry.TryRegister(key, first, out _).Should().BeTrue(); QuartzConsumerRegistry.TryRegister(key, second, out var owner).Should().BeFalse(); owner.Should().BeSameAs(first); // The refused one cannot release what it does not hold. QuartzConsumerRegistry.Unregister(key, second); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().BeSameAs(first); } finally { QuartzConsumerRegistry.Unregister(key, first); } } [Fact] public async Task TheSameJobKey_OnAnotherScheduler_IsAnotherClaim() { var a = await NewScheduler(); var b = await NewScheduler(); var jobKey = new JobKey("ep4", "redb"); var c1 = CreateMockConsumer(); var c2 = CreateMockConsumer(); try { QuartzConsumerRegistry.TryRegister(QuartzConsumerRegistry.KeyOf(a, jobKey), c1, out _).Should().BeTrue(); QuartzConsumerRegistry.TryRegister(QuartzConsumerRegistry.KeyOf(b, jobKey), c2, out _).Should().BeTrue( "a scheduler per context: two contexts may both say cron://ep4"); QuartzConsumerRegistry.Get(a, jobKey).Should().BeSameAs(c1); QuartzConsumerRegistry.Get(b, jobKey).Should().BeSameAs(c2); } finally { QuartzConsumerRegistry.Unregister(QuartzConsumerRegistry.KeyOf(a, jobKey), c1); QuartzConsumerRegistry.Unregister(QuartzConsumerRegistry.KeyOf(b, jobKey), c2); } } private static Task NewScheduler() => new StdSchedulerFactory(new NameValueCollection { ["quartz.scheduler.instanceName"] = "registry-test-" + Guid.NewGuid().ToString("N"), }).GetScheduler(); private static QuartzConsumerBase CreateMockConsumer() { return Substitute.ForPartsOf( Substitute.For(), Substitute.For(), 1, // maxThreads (string?)null, // groupName (string?)null, // jobName true, // deleteJob false, // pauseJob false, // durableJob false, // stateful false, // recoverableJob false, // prefixJobNameWithEndpointId (string?)null); // customCalendar } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzErrorHandlingTests.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.Quartz/QuartzErrorHandlingTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// A failed fire goes through the route's own error handling once — inside the pipeline, as every other consumer — /// and the consumer only records the outcome. It used to hand an unhandled failure to /// IRouteContext.HandleException as well, so an OnException without Handled() ran twice and a /// route-level one ended in "No exception handler found". /// public class QuartzErrorHandlingTests { [Fact] public async Task UnhandledFailure_RunsTheBuildersOnExceptionOnce() { var hits = 0; await using var context = new RouteContext(); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => { r.OnException().Process(_ => Interlocked.Increment(ref hits)); r.From("qtimer://builder-once?period=50&repeatCount=0") .Process(_ => throw new InvalidOperationException("boom")); }); await context.Start(); await WaitFor(() => Volatile.Read(ref hits) >= 1); await Task.Delay(300); Volatile.Read(ref hits).Should().Be(1, "the handler runs inside the route, the consumer does not run it again"); } [Fact] public async Task UnhandledFailure_RunsTheRoutesOnExceptionOnce() { var hits = 0; await using var context = new RouteContext(); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r .From("qtimer://route-once?period=50&repeatCount=0") .OnException() .Process(_ => Interlocked.Increment(ref hits)) .End() .Process(_ => throw new InvalidOperationException("boom"))); await context.Start(); await WaitFor(() => Volatile.Read(ref hits) >= 1); await Task.Delay(300); Volatile.Read(ref hits).Should().Be(1); } [Fact] public async Task UnhandledFailure_ReachesTheContextErrorHandlerOnce() { // The dead letter queue of a host (Tsak's checkpoint DLQ) is the context's ErrorHandler: a failed fire no // OnException took reaches it exactly once. var calls = 0; await using var context = new RouteContext { ErrorHandler = new CountingErrorHandler(() => Interlocked.Increment(ref calls)) }; context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r .From("qtimer://errorhandler-once?period=50&repeatCount=0") .Process(_ => throw new InvalidOperationException("boom"))); await context.Start(); await WaitFor(() => Volatile.Read(ref calls) >= 1); await Task.Delay(300); Volatile.Read(ref calls).Should().Be(1); } private sealed class CountingErrorHandler(Action onCall) : redb.Route.Abstractions.IErrorHandler { public Task HandleError(redb.Route.Abstractions.IExchange exchange, Exception exception, CancellationToken ct = default) { onCall(); return Task.CompletedTask; } } private static async Task WaitFor(Func condition) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); while (!condition()) { cts.Token.ThrowIfCancellationRequested(); await Task.Delay(10, cts.Token); } } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzIntegrationTests.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.Quartz/QuartzIntegrationTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// End-to-end integration tests for Quartz connectors: /// multiple consumers on shared schedulers, cross-component interaction, /// pipeline processing, and concurrent lifecycle management. /// public class QuartzIntegrationTests : IAsyncLifetime { private RouteContext? _context; private readonly List _consumers = []; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var c in _consumers) { try { await c.Stop(); } catch { } } _context?.Dispose(); } private RouteContext CreateContext(string name) { _context = new RouteContext(name); return _context; } private void TrackConsumer(IConsumer consumer) => _consumers.Add(consumer); // ── Multi-consumer on shared scheduler ────────────────────────── [Fact] public async Task SharedScheduler_MultipleTimers_AllFireIndependently() { var context = CreateContext("multi-timer"); var component = new QuartzTimerComponent(); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var counts = new ConcurrentDictionary(); counts["fast"] = 0; counts["slow"] = 0; var fastConsumer = CreateTimerConsumer(component, "fast", period: 100, counts); var slowConsumer = CreateTimerConsumer(component, "slow", period: 300, counts); TrackConsumer(fastConsumer); TrackConsumer(slowConsumer); await fastConsumer.Start(); await slowConsumer.Start(); // Wait enough for both to fire await WaitForCondition(() => counts["fast"] >= 3 && counts["slow"] >= 2, 5000); await fastConsumer.Stop(); await slowConsumer.Stop(); counts["fast"].Should().BeGreaterThanOrEqualTo(3, "fast timer should fire frequently"); counts["slow"].Should().BeGreaterThanOrEqualTo(2, "slow timer should fire at its own rate"); counts["fast"].Should().BeGreaterThan(counts["slow"], "fast timer should fire more than slow"); } [Fact] public async Task SharedScheduler_CronAndTimer_CoexistOnSameContext() { var context = CreateContext("cron-timer-mixed"); var cronComponent = new CronComponent(); var timerComponent = new QuartzTimerComponent(); context.AddComponent(cronComponent); context.AddComponent(timerComponent); await context.Start(); // the context runs: a consumer started now starts the scheduler var cronExchanges = new ConcurrentBag(); var timerExchanges = new ConcurrentBag(); // Cron: every second var cronConsumer = CreateCronConsumer(cronComponent, "cronJob", "* * * * * ?", cronExchanges); // Timer: every 200ms var timerConsumer = CreateTimerConsumerCapture(timerComponent, "timerJob", 200, timerExchanges); TrackConsumer(cronConsumer); TrackConsumer(timerConsumer); await cronConsumer.Start(); await timerConsumer.Start(); await WaitForCondition(() => cronExchanges.Count >= 1 && timerExchanges.Count >= 2, 5000); await cronConsumer.Stop(); await timerConsumer.Stop(); cronExchanges.Should().NotBeEmpty(); timerExchanges.Should().NotBeEmpty(); // Validate cron exchange properties var cronEx = cronExchanges.First(); cronEx.Properties.Should().ContainKey("CamelCronSchedule"); cronEx.Properties.Should().ContainKey("CamelCronName"); cronEx.Properties["CamelCronName"].Should().Be("cronJob"); // Validate timer exchange properties var timerEx = timerExchanges.First(); timerEx.Properties.Should().ContainKey("CamelTimerName"); timerEx.Properties["CamelTimerName"].Should().Be("timerJob"); } // ── Stop one, other continues ─────────────────────────────────── [Fact] public async Task StopOneConsumer_OtherContinuesFiring() { var context = CreateContext("stop-one"); var component = new QuartzTimerComponent(); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var counts = new ConcurrentDictionary(); counts["a"] = 0; counts["b"] = 0; var consumerA = CreateTimerConsumer(component, "a", 100, counts); var consumerB = CreateTimerConsumer(component, "b", 100, counts); TrackConsumer(consumerA); TrackConsumer(consumerB); await consumerA.Start(); await consumerB.Start(); await WaitForCondition(() => counts["a"] >= 2 && counts["b"] >= 2, 5000); // Stop A, B should keep firing await consumerA.Stop(); var bCountAtStop = counts["b"]; await WaitForCondition(() => counts["b"] >= bCountAtStop + 3, 5000); await consumerB.Stop(); counts["b"].Should().BeGreaterThan(bCountAtStop, "consumer B should continue after A stopped"); } // ── Processing pipeline ───────────────────────────────────────── [Fact] public async Task CronConsumer_ProcessorTransformsData_OutputAccumulated() { var context = CreateContext("pipeline"); var component = new CronComponent(); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var results = new ConcurrentBag(); var uri = EndpointUriParser.Parse("cron://transform?schedule=* * * * * ?"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { var ex = ci.Arg(); var fireTime = ex.Properties["CamelQuartzFireTime"]; results.Add($"fired-at-{fireTime}"); }); var consumer = endpoint.CreateConsumer(processor); TrackConsumer(consumer); await consumer.Start(); await WaitForCondition(() => results.Count >= 2, 5000); await consumer.Stop(); results.Should().HaveCountGreaterThanOrEqualTo(2); results.Should().AllSatisfy(r => r.Should().StartWith("fired-at-")); } // ── Restart ───────────────────────────────────────────────────── [Fact] public async Task Consumer_StopAndRestart_ContinuesProcessing() { var context = CreateContext("restart"); var component = new QuartzTimerComponent(); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var fireCount = 0; var uri = EndpointUriParser.Parse("qtimer://restartable?period=100"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref fireCount)); var consumer = endpoint.CreateConsumer(processor); TrackConsumer(consumer); // First run await consumer.Start(); await WaitForCondition(() => fireCount >= 2, 10_000); await consumer.Stop(); var countAfterFirstRun = fireCount; countAfterFirstRun.Should().BeGreaterThanOrEqualTo(2); // Restart await consumer.Start(); await WaitForCondition(() => fireCount >= countAfterFirstRun + 2, 10_000); await consumer.Stop(); fireCount.Should().BeGreaterThan(countAfterFirstRun, "fires should resume after restart"); } // ── Separate contexts have separate schedulers ────────────────── [Fact] public async Task SeparateContexts_HaveSeparateSchedulers() { var context1 = new RouteContext("ctx1"); var context2 = new RouteContext("ctx2"); var comp1 = new QuartzTimerComponent(); var comp2 = new QuartzTimerComponent(); context1.AddComponent(comp1); await context1.Start(); // the context runs: a consumer started now starts the scheduler context2.AddComponent(comp2); await context2.Start(); // the context runs: a consumer started now starts the scheduler var count1 = 0; var count2 = 0; var uri1 = EndpointUriParser.Parse("qtimer://isolated1?period=100"); var ep1 = comp1.CreateEndpoint(uri1); var p1 = Substitute.For(); p1.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref count1)); var c1 = ep1.CreateConsumer(p1); _consumers.Add(c1); var uri2 = EndpointUriParser.Parse("qtimer://isolated2?period=100"); var ep2 = comp2.CreateEndpoint(uri2); var p2 = Substitute.For(); p2.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref count2)); var c2 = ep2.CreateConsumer(p2); _consumers.Add(c2); await c1.Start(); await c2.Start(); await WaitForCondition(() => count1 >= 2 && count2 >= 2, 5000); // Stop only context1's consumer await c1.Stop(); context1.Dispose(); var count2AtStop = count2; await WaitForCondition(() => count2 >= count2AtStop + 2, 5000); await c2.Stop(); context2.Dispose(); count2.Should().BeGreaterThan(count2AtStop, "context2's scheduler should be unaffected by context1 disposal"); } // ── Processor exception does not stop other consumers ─────────── [Fact] public async Task ProcessorException_DoesNotAffectOtherConsumers() { var context = CreateContext("error-isolation"); var component = new QuartzTimerComponent(); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var errorCount = 0; var successCount = 0; // Failing consumer var failUri = EndpointUriParser.Parse("qtimer://failing?period=100"); var failEp = component.CreateEndpoint(failUri); var failProc = Substitute.For(); failProc.Process(Arg.Any(), Arg.Any()) .Returns(_ => { Interlocked.Increment(ref errorCount); throw new InvalidOperationException("Intentional test error"); }); var failConsumer = failEp.CreateConsumer(failProc); TrackConsumer(failConsumer); // Healthy consumer var okUri = EndpointUriParser.Parse("qtimer://healthy?period=100"); var okEp = component.CreateEndpoint(okUri); var okProc = Substitute.For(); okProc.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref successCount)); var okConsumer = okEp.CreateConsumer(okProc); TrackConsumer(okConsumer); await failConsumer.Start(); await okConsumer.Start(); await WaitForCondition(() => errorCount >= 2 && successCount >= 2, 5000); await failConsumer.Stop(); await okConsumer.Stop(); errorCount.Should().BeGreaterThanOrEqualTo(2, "failing consumer should keep firing despite errors"); successCount.Should().BeGreaterThanOrEqualTo(2, "healthy consumer unaffected by sibling errors"); } // ── Helpers ────────────────────────────────────────────────────── private static IConsumer CreateTimerConsumer( QuartzTimerComponent component, string name, int period, ConcurrentDictionary counts) { var uri = EndpointUriParser.Parse($"qtimer://{name}?period={period}"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => counts.AddOrUpdate(name, 1, (_, v) => v + 1)); return endpoint.CreateConsumer(processor); } private static IConsumer CreateTimerConsumerCapture( QuartzTimerComponent component, string name, int period, ConcurrentBag bag) { var uri = EndpointUriParser.Parse($"qtimer://{name}?period={period}"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => bag.Add(ci.Arg())); return endpoint.CreateConsumer(processor); } private static IConsumer CreateCronConsumer( CronComponent component, string name, string schedule, ConcurrentBag bag) { var uri = EndpointUriParser.Parse($"cron://{name}?schedule={schedule}"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => bag.Add(ci.Arg())); return endpoint.CreateConsumer(processor); } private static async Task WaitForCondition(Func condition, int timeoutMs) { var sw = System.Diagnostics.Stopwatch.StartNew(); while (!condition() && sw.ElapsedMilliseconds < timeoutMs) { await Task.Delay(50); } } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzOperatorPauseTests.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.Quartz/QuartzOperatorPauseTests.cs ---- using System.Collections.Specialized; using Quartz; using Quartz.Impl; using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// A job an operator paused on the scheduler (a host's panel, CLI or API) stays paused when its route starts again, on /// the in-memory store: the start replaces the trigger with the route's definition, and the replacement keeps the pause. /// That holds when the stop removed the job (deleteJob=true, the default) or paused it itself /// (pauseJob=true): the stop notes the operator's pause on the scheduler, and the next start pauses again. A /// pause the route set itself at its stop is the route's, and its start lifts it. /// public class QuartzOperatorPauseTests { [Theory] [InlineData("qtimer", "qtimer://held-timer?period=200&deleteJob=false")] [InlineData("cron", "cron://held-cron?schedule=0/1 * * * * ?&deleteJob=false")] public async Task An_operators_pause_survives_a_restart_of_the_route(string scheme, string uri) { var scheduler = await NewScheduler(); try { var fired = 0; await using var context = new RouteContext(); context.AddService(typeof(IScheduler), scheduler); context.AddComponent(scheme == "cron" ? new CronComponent() : new QuartzTimerComponent()); context.AddRoutes(r => r.From(uri).RouteId("held").Process(_ => Interlocked.Increment(ref fired))); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) >= 1, "the job fires before the pause"); var job = new JobKey(scheme == "cron" ? "held-cron" : "held-timer", "redb"); await scheduler.PauseJob(job); await context.StopRoute("held"); await context.StartRoute("held"); var trigger = (await scheduler.GetTriggersOfJob(job)).Single().Key; (await scheduler.GetTriggerState(trigger)).Should().Be(TriggerState.Paused, "the operator paused the job; a restart of its route is not a decision to resume it"); var before = Volatile.Read(ref fired); await Task.Delay(1500); Volatile.Read(ref fired).Should().Be(before, "a paused job does not fire"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Theory] [InlineData("qtimer://gone-timer?period=200")] [InlineData("qtimer://gone-paused?period=200&pauseJob=true&deleteJob=false")] public async Task An_operators_pause_survives_a_restart_of_the_route_that_removes_or_pauses_its_job_at_the_stop(string uri) { // deleteJob=true (the default) removes the job, pause included, at the stop; pauseJob=true pauses it there, and // its start lifts its own pause. Neither may take the operator's pause with it. var scheduler = await NewScheduler(); try { var fired = 0; await using var context = new RouteContext(); context.AddService(typeof(IScheduler), scheduler); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r.From(uri).RouteId("gone").Process(_ => Interlocked.Increment(ref fired))); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) >= 1, "the job fires before the pause"); var name = new Uri(uri).Host; await scheduler.PauseJob(new JobKey(name, "redb")); await context.StopRoute("gone"); await context.StartRoute("gone"); (await scheduler.GetTriggerState(new TriggerKey(name, "redb"))).Should().Be(TriggerState.Paused, "the operator paused the job; what the route does with it at its stop is not the operator's decision"); var before = Volatile.Read(ref fired); await Task.Delay(1500); Volatile.Read(ref fired).Should().Be(before, "a paused job does not fire"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task A_job_the_operator_resumed_while_its_route_was_stopped_fires_after_the_start() { var scheduler = await NewScheduler(); try { var fired = 0; await using var context = new RouteContext(); context.AddService(typeof(IScheduler), scheduler); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r.From("qtimer://back?period=200&pauseJob=true&deleteJob=false").RouteId("back") .Process(_ => Interlocked.Increment(ref fired))); await context.Start(); var job = new JobKey("back", "redb"); await scheduler.PauseJob(job); await context.StopRoute("back"); await scheduler.ResumeJob(job); await context.StartRoute("back"); var before = Volatile.Read(ref fired); (await scheduler.GetTriggerState(new TriggerKey("back", "redb"))).Should().Be(TriggerState.Normal, "the operator resumed the job; the pause seen at the stop is no longer theirs"); await WaitForAsync(() => Volatile.Read(ref fired) > before, "the job fires again"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task A_job_kept_paused_over_a_restart_fires_again_once_the_operator_resumes_it() { var scheduler = await NewScheduler(); try { var fired = 0; await using var context = new RouteContext(); context.AddService(typeof(IScheduler), scheduler); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r.From("qtimer://resumed?period=200&deleteJob=false").RouteId("resumed") .Process(_ => Interlocked.Increment(ref fired))); await context.Start(); var job = new JobKey("resumed", "redb"); await scheduler.PauseJob(job); await context.StopRoute("resumed"); await context.StartRoute("resumed"); var before = Volatile.Read(ref fired); await scheduler.ResumeJob(job); await WaitForAsync(() => Volatile.Read(ref fired) > before, "the resumed job fires on the route's schedule"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task The_routes_own_pause_at_its_stop_is_lifted_at_its_start() { var scheduler = await NewScheduler(); try { var fired = 0; await using var context = new RouteContext(); context.AddService(typeof(IScheduler), scheduler); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r.From("qtimer://own-pause?period=200&pauseJob=true&deleteJob=false").RouteId("own") .Process(_ => Interlocked.Increment(ref fired))); await context.Start(); var trigger = new TriggerKey("own-pause", "redb"); await context.StopRoute("own"); (await scheduler.GetTriggerState(trigger)).Should().Be(TriggerState.Paused, "pauseJob=true pauses at the stop"); await context.StartRoute("own"); var before = Volatile.Read(ref fired); (await scheduler.GetTriggerState(trigger)).Should().Be(TriggerState.Normal, "the route lifts its own pause"); await WaitForAsync(() => Volatile.Read(ref fired) > before, "the job fires again"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } private static async Task WaitForAsync(Func condition, string because) { var deadline = DateTime.UtcNow.AddSeconds(20); while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(50); condition().Should().BeTrue(because); } private static Task NewScheduler() => new StdSchedulerFactory(new NameValueCollection { ["quartz.scheduler.instanceName"] = "redb-route-pause-" + Guid.NewGuid().ToString("N"), }).GetScheduler(); } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzPersistentStoreTests.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.Quartz/QuartzPersistentStoreTests.cs ---- using System.Collections.Concurrent; using System.Collections.Specialized; using Microsoft.Extensions.Logging; using Npgsql; using Quartz; using Quartz.Impl; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// A database the job store shares — between the nodes of a cluster, or with the node's next start — is the /// schedule's home, not the node's: a node never deletes or pauses what it holds as a side effect. Stopping a route /// stops this node's consumer only; a fire with no consumer on the node that took it is skipped and logged, not /// "cleaned up" out of the database. Runs on the pgdb container of docker-compose.tests.yml: the standard /// Quartz tables in a schema of their own, a clustered AdoJobStore as redb.Tsak configures it. /// public sealed class QuartzPersistentStoreTests : IClassFixture { private readonly PostgresQuartzStore _store; public QuartzPersistentStoreTests(PostgresQuartzStore store) => _store = store; [Fact] public async Task StoppingTheRoute_KeepsTheJobInTheDatabase() { var scheduler = await _store.NewScheduler(); try { await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From("qtimer://pg-stop?period=60000").RouteId("pg-stop").Process(_ => { })); await ctx.Start(); (await scheduler.CheckExists(new JobKey("pg-stop", "redb"))).Should().BeTrue(); await ctx.StopRoute("pg-stop"); (await scheduler.CheckExists(new JobKey("pg-stop", "redb"))).Should().BeTrue( "this node stopped; the schedule belongs to the database (deleteJob=true by default)"); (await scheduler.CheckExists(new TriggerKey("pg-stop", "redb"))).Should().BeTrue(); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task StoppingTheRoute_WithPauseJob_DoesNotPauseTheSharedTrigger() { var scheduler = await _store.NewScheduler(); try { await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From("qtimer://pg-pause?period=60000&pauseJob=true&deleteJob=false").RouteId("pg-pause") .Process(_ => { })); await ctx.Start(); await ctx.StopRoute("pg-pause"); (await scheduler.GetTriggerState(new TriggerKey("pg-pause", "redb"))).Should().NotBe(TriggerState.Paused, "pausing the shared trigger would stop the schedule on every node"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task AnOperatorsPause_SurvivesARestartOfTheRoute() { var scheduler = await _store.NewScheduler(); try { var fires = 0; await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From("qtimer://pg-held?period=200").RouteId("pg-held") .Process(_ => Interlocked.Increment(ref fires))); await ctx.Start(); await WaitFor(() => Volatile.Read(ref fires) >= 1); // The operator pauses the job on the shared store (a host's panel, CLI or API); the route restarts. await scheduler.PauseJob(new JobKey("pg-held", "redb")); await ctx.StopRoute("pg-held"); await ctx.StartRoute("pg-held"); (await scheduler.GetTriggerState(new TriggerKey("pg-held", "redb"))).Should().Be(TriggerState.Paused, "a restart of the route on a node is not a decision to resume the schedule the store shares"); var before = Volatile.Read(ref fires); await Task.Delay(1500); Volatile.Read(ref fires).Should().Be(before, "a paused job does not fire"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task AFireWithoutItsConsumerOnThisNode_IsSkipped_NotDeleted() { var scheduler = await _store.NewScheduler(); try { var fires = 0; await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From("qtimer://pg-orphan?period=200&deleteJob=false").RouteId("pg-orphan") .Process(_ => Interlocked.Increment(ref fires))); await ctx.Start(); await WaitFor(() => Volatile.Read(ref fires) >= 1); // The route stops on this node: its consumer leaves; the trigger keeps firing on the scheduler. await ctx.StopRoute("pg-orphan"); await Task.Delay(1000); (await scheduler.CheckExists(new JobKey("pg-orphan", "redb"))).Should().BeTrue( "a node without the consumer — a rolling upgrade, a route stopped on one node — must not delete the shared job"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task ALeaderPolicyOnAQuartzRoute_OverAClusteredStore_IsAWarning() { var warnings = await WarningsOfAClusterRoute("pg-leader", new LeaderPolicyFactory()); warnings.Should().Contain(m => m.Contains("Route 'pg-leader'") && m.Contains("Drop .Cluster(true)"), "Quartz already fires the job on one node; on the leader only, the fires other nodes take are lost"); } [Fact] public async Task AClusterRouteTheFactoryDeclined_IsNoWarning() { // Tsak's policy factory leaves Quartz routes on every node: the clustered store gives one fire per cluster. var warnings = await WarningsOfAClusterRoute("pg-declined", new DecliningPolicyFactory()); warnings.Should().NotContain(m => m.Contains("Drop .Cluster(true)")); } private async Task WarningsOfAClusterRoute(string name, IRoutePolicyFactory factory) { var scheduler = await _store.NewScheduler(); var log = new WarningLog(); try { using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(log)); await using var ctx = new RouteContext(loggerFactory: loggerFactory); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddRoutePolicyFactory(factory); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From($"qtimer://{name}?period=60000").RouteId(name).Cluster(true).Process(_ => { })); await ctx.Start(); return log.Warnings.ToArray(); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } private sealed class LeaderPolicyFactory : IRoutePolicyFactory { public IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition) => definition.GetCluster() ? new LeaderPolicy() : null; } private sealed class DecliningPolicyFactory : IRoutePolicyFactory { public IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition) => null; } private sealed class LeaderPolicy : IRoutePolicy { } private sealed class WarningLog : ILoggerProvider, ILogger { public ConcurrentQueue Warnings { get; } = new(); public ILogger CreateLogger(string categoryName) => this; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (logLevel >= LogLevel.Warning) Warnings.Enqueue(formatter(state, exception)); } public void Dispose() { } } private static async Task WaitFor(Func condition) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); while (!condition()) { cts.Token.ThrowIfCancellationRequested(); await Task.Delay(20, cts.Token); } } } /// /// The standard Quartz tables in a schema of their own on the pgdb container, dropped afterwards; a scheduler /// factory configured as redb.Tsak configures a clustered AdoJobStore. /// public sealed class PostgresQuartzStore : IAsyncLifetime { private static readonly string Server = global::redb.Route.Tests.Shared.TestDatabases.Postgres("Host=localhost;Port=5432;Username=postgres;Password=1;Database=postgres"); private readonly string _schema = "qrtz_" + Guid.NewGuid().ToString("N")[..12]; private string ConnectionString => $"{Server};Search Path={_schema}"; public async Task InitializeAsync() { await using var connection = new NpgsqlConnection(Server); await connection.OpenAsync(); await using (var create = new NpgsqlCommand($"CREATE SCHEMA {_schema}", connection)) await create.ExecuteNonQueryAsync(); await using var script = typeof(PostgresQuartzStore).Assembly.GetManifestResourceStream("QuartzSchema.Postgres")!; using var reader = new StreamReader(script); await using var apply = new NpgsqlCommand($"SET search_path TO {_schema};\n" + await reader.ReadToEndAsync(), connection); await apply.ExecuteNonQueryAsync(); } public async Task DisposeAsync() { await using var connection = new NpgsqlConnection(Server); await connection.OpenAsync(); await using var drop = new NpgsqlCommand($"DROP SCHEMA IF EXISTS {_schema} CASCADE", connection); await drop.ExecuteNonQueryAsync(); } /// A clustered scheduler on the store, not started; each one is a cluster of its own (its own name). public Task NewScheduler() => new StdSchedulerFactory(new NameValueCollection { ["quartz.scheduler.instanceName"] = "redb-route-pg-" + Guid.NewGuid().ToString("N"), ["quartz.scheduler.instanceId"] = "AUTO", ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz", ["quartz.jobStore.dataSource"] = "default", ["quartz.jobStore.tablePrefix"] = "QRTZ_", ["quartz.jobStore.clustered"] = "true", ["quartz.dataSource.default.provider"] = "Npgsql", ["quartz.dataSource.default.connectionString"] = ConnectionString, ["quartz.serializer.type"] = "newtonsoft", ["quartz.threadPool.maxConcurrency"] = "4", }).GetScheduler(); } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzRestartTests.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.Quartz/QuartzRestartTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Quartz timers keep firing after Stop() and Start() of the same route context: the stop removes the /// jobs of the cached endpoints from the scheduler, the start schedules them again. /// public class QuartzRestartTests { private static async Task WaitForAsync(Func condition, string because) { var deadline = DateTime.UtcNow.AddSeconds(15); while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(50); condition().Should().BeTrue(because); } [Fact] public async Task Qtimer_fires_after_the_context_is_stopped_and_started_again() { var fired = 0; await using var context = new RouteContext(); context.AddComponent(new QuartzTimerComponent()); context.AddRoutes(r => r.From("qtimer://restart?period=100").Process(_ => Interlocked.Increment(ref fired))); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) >= 1, "qtimer fires"); await context.Stop(); var before = Volatile.Read(ref fired); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) > before, "qtimer fires again after a restart"); } [Fact] public async Task Cron_fires_after_the_context_is_stopped_and_started_again() { var fired = 0; await using var context = new RouteContext(); context.AddComponent(new CronComponent()); context.AddRoutes(r => r.From("cron://restart?schedule=0/1 * * * * ?").Process(_ => Interlocked.Increment(ref fired))); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) >= 1, "cron fires"); await context.Stop(); var before = Volatile.Read(ref fired); await context.Start(); await WaitForAsync(() => Volatile.Read(ref fired) > before, "cron fires again after a restart"); } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzRouteJobTests.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.Quartz/QuartzRouteJobTests.cs ---- using Quartz; using Quartz.Impl; using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Tests for QuartzRouteJob — the universal Quartz IJob that bridges to consumers. /// public class QuartzRouteJobTests { [Fact] public async Task Execute_NoConsumerRegistered_CleansUpOrphan() { var job = new QuartzRouteJob(); var scheduler = await StdSchedulerFactory.GetDefaultScheduler(); await scheduler.Start(); try { var jobDetail = JobBuilder.Create() .UsingJobData("endpointUri", "orphan://test") .UsingJobData("contextId", "orphan-ctx") .Build(); var trigger = TriggerBuilder.Create().StartNow().Build(); var context = new TestJobExecutionContext(scheduler, jobDetail, trigger); // No consumer registered, no context — should not throw, just clean up var act = () => job.Execute(context); await act.Should().NotThrowAsync(); } finally { await scheduler.Shutdown(); } } /// /// Minimal IJobExecutionContext implementation for testing QuartzRouteJob.Execute() directly. /// private sealed class TestJobExecutionContext : IJobExecutionContext { public TestJobExecutionContext(IScheduler scheduler, IJobDetail jobDetail, ITrigger trigger) { Scheduler = scheduler; JobDetail = jobDetail; Trigger = trigger; FireTimeUtc = DateTimeOffset.UtcNow; ScheduledFireTimeUtc = DateTimeOffset.UtcNow; } public IScheduler Scheduler { get; } public ITrigger Trigger { get; } public ICalendar? Calendar => null; public bool Recovering => false; public TriggerKey RecoveringTriggerKey => null!; public int RefireCount => 0; public JobDataMap MergedJobDataMap => JobDetail.JobDataMap; public IJobDetail JobDetail { get; } public IJob JobInstance => null!; public DateTimeOffset FireTimeUtc { get; } public DateTimeOffset? ScheduledFireTimeUtc { get; } public DateTimeOffset? PreviousFireTimeUtc => null; public DateTimeOffset? NextFireTimeUtc => null; public string FireInstanceId => "test-fire-id"; public object? Result { get; set; } public TimeSpan JobRunTime => TimeSpan.Zero; public CancellationToken CancellationToken => CancellationToken.None; public void Put(object key, object objectValue) { } public object? Get(object key) => null; } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzSchedulingTests.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.Quartz/QuartzSchedulingTests.cs ---- using System.Collections.Specialized; using Quartz; using Quartz.Impl; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// How a Quartz consumer claims its job and when the scheduler starts, on the in-memory store. One job key, one /// consumer per scheduler: a second claimant — the same path with another schedule, another component with the same /// path, another context on the same scheduler — fails at its start instead of silently replacing the first schedule. /// The scheduler, the context's own or one handed to it, starts once the context has started (camel-quartz /// autoStartScheduler), so a fire never finds a consumer not yet registered. /// public class QuartzSchedulingTests { [Fact] public async Task SamePath_TwoSchedules_InOneContext_TheSecondFails_TheFirstKeepsItsSchedule() { await using var ctx = new RouteContext(); ctx.AddComponent(new CronComponent()); ctx.AddRoutes(r => { r.From("cron://key-nightly?schedule=0 0 3 * * ?").RouteId("report-3am").Process(_ => { }); r.From("cron://key-nightly?schedule=0 0 4 * * ?").RouteId("report-4am").Process(_ => { }); }); await ctx.Start(); var started = ctx.Routes.Where(r => r.Status == RouteStatus.Started).Select(r => r.RouteId).ToList(); started.Should().ContainSingle("one job key, one schedule — the second claimant does not start"); var scheduler = ctx.GetService()!; var trigger = (ICronTrigger)(await scheduler.GetTrigger(new TriggerKey("key-nightly", "redb")))!; trigger.CronExpressionString.Should().Be(started[0] == "report-3am" ? "0 0 3 * * ?" : "0 0 4 * * ?", "the schedule of the route that started is not replaced by the one that did not"); } [Fact] public async Task SamePath_CronAndQtimer_InOneContext_TheSecondFails() { await using var ctx = new RouteContext(); ctx.AddComponent(new CronComponent()); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => { r.From("cron://key-shared?schedule=0 0 3 * * ?").Process(_ => { }); r.From("qtimer://key-shared?period=60000").Process(_ => { }); }); await ctx.Start(); ctx.Routes.Count(r => r.Status == RouteStatus.Started).Should().Be(1); } [Fact] public async Task SameUri_TwoContexts_OnOneScheduler_TheSecondFails() { var scheduler = await NewScheduler(); try { await using var first = new RouteContext(contextId: "key-ctx-a"); first.AddService(typeof(IScheduler), scheduler); first.AddComponent(new CronComponent()); first.AddRoutes(r => r.From("cron://key-module?schedule=0 0 3 * * ?").Process(_ => { })); await first.Start(); await using var second = new RouteContext(contextId: "key-ctx-b"); second.AddService(typeof(IScheduler), scheduler); second.AddComponent(new CronComponent()); second.AddRoutes(r => r.From("cron://key-module?schedule=0 0 3 * * ?").Process(_ => { })); await second.Start(); first.Routes.Single().Status.Should().Be(RouteStatus.Started); second.Routes.Single().Status.Should().NotBe(RouteStatus.Started, "two contexts of one process cannot share one job of one scheduler"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task AHandedInScheduler_StartsOnlyOnceTheContextHasStarted() { var scheduler = await NewScheduler(); try { var probe = new StartedAtRouteStart(scheduler); await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddLifecycleListener(probe); ctx.AddRoutes(r => r.From("qtimer://start-order?period=60000").Process(_ => { })); await ctx.Start(); probe.SchedulerStartedWhenTheRouteStarted.Should().BeFalse( "a consumer registers; the scheduler starts after the whole context has started"); scheduler.IsStarted.Should().BeTrue("auto-start, as camel-quartz autoStartScheduler"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } [Fact] public async Task ARouteStartedLater_StartsTheSchedulerItself() { var scheduler = await NewScheduler(); try { await using var ctx = new RouteContext(); ctx.AddService(typeof(IScheduler), scheduler); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From("qtimer://started-later?period=60000").RouteId("started-later").AutoStart(false) .Process(_ => { })); await ctx.Start(); scheduler.IsStarted.Should().BeFalse("no Quartz consumer started with the context"); await ctx.StartRoute("started-later"); scheduler.IsStarted.Should().BeTrue("the context is already running"); } finally { await scheduler.Shutdown(waitForJobsToComplete: false); } } private static Task NewScheduler() => new StdSchedulerFactory(new NameValueCollection { ["quartz.scheduler.instanceName"] = "redb-route-test-" + Guid.NewGuid().ToString("N"), }).GetScheduler(); private sealed class StartedAtRouteStart(IScheduler scheduler) : IRouteLifecycleListener { public bool? SchedulerStartedWhenTheRouteStarted { get; private set; } public Task OnRouteStarted(string routeId, CancellationToken ct) { SchedulerStartedWhenTheRouteStarted ??= scheduler.IsStarted; return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzTimerComponentTests.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.Quartz/QuartzTimerComponentTests.cs ---- using redb.Route.Core; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Tests for QuartzTimerComponent, QuartzTimerEndpoint, QuartzTimerEndpointOptions, and QuartzTimerConsumer. /// public class QuartzTimerComponentTests { // ── Component ── [Fact] public void Scheme_IsQtimer() { var component = new QuartzTimerComponent(); component.Scheme.Should().Be("qtimer"); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new QuartzTimerComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_ValidUri_ReturnsQuartzTimerEndpoint() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://heartbeat?period=500"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_DefaultPeriod() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://heartbeat"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_ZeroPeriod_Throws() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://broken?period=0"); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } [Fact] public void CreateEndpoint_NegativePeriod_Throws() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://broken?period=-100"); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } // ── Options ── [Fact] public void Options_DefaultValues() { var opts = new QuartzTimerEndpointOptions(); opts.Period.Should().Be(1000); opts.Delay.Should().Be(0); opts.FixedRate.Should().BeFalse(); opts.Threads.Should().Be(1); } [Fact] public void Options_Validate_ZeroPeriod_Throws() { var opts = new QuartzTimerEndpointOptions { Period = 0 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_NegativeThreads_Throws() { var opts = new QuartzTimerEndpointOptions { Threads = -1 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_ValidOptions_Passes() { var opts = new QuartzTimerEndpointOptions { Period = 500, Threads = 3, FixedRate = true, Delay = 100 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Options_BindFromUri_ParsesAllParameters() { var uri = EndpointUriParser.Parse("qtimer://tick?period=250&delay=100&fixedRate=true&threads=2"); var opts = new QuartzTimerEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Period.Should().Be(250); opts.Delay.Should().Be(100); opts.FixedRate.Should().BeTrue(); opts.Threads.Should().Be(2); } // ── Endpoint ── [Fact] public void Endpoint_CreateProducer_ThrowsNotSupported() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://tick?period=500"); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateProducer(); act.Should().Throw(); } [Fact] public void Endpoint_CreateConsumer_NullProcessor_Throws() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://tick?period=500"); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } [Fact] public void Endpoint_CreateConsumer_ReturnsQuartzTimerConsumer() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://tick?period=500"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } // ── Consumer lifecycle ── [Fact] public async Task Consumer_StartStop_Lifecycle() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-test-1"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://tick?period=200"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var scheduler = context.GetService()!; var jobKey = new global::Quartz.JobKey("tick", "redb"); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().NotBeNull(); await consumer.Stop(); QuartzConsumerRegistry.Get(scheduler, jobKey).Should().BeNull(); context.Dispose(); } [Fact] public async Task Consumer_RequiresRouteContext() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://tick?period=200"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*RouteContext*"); } [Fact] public async Task Consumer_FiresProcessor_Periodically() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-fire-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://rapid?period=200"); var endpoint = component.CreateEndpoint(uri); var fireCount = 0; Abstractions.IExchange? capturedExchange = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { Interlocked.Increment(ref fireCount); capturedExchange = ci.Arg(); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // Wait for at least 2 fires (period=200ms, so ~1s should be enough) for (var i = 0; i < 50 && fireCount < 2; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); fireCount.Should().BeGreaterThanOrEqualTo(2, "timer should have fired at least twice"); capturedExchange.Should().NotBeNull(); capturedExchange!.Properties.Should().ContainKey("CamelTimerName"); capturedExchange.Properties["CamelTimerName"].Should().Be("rapid"); capturedExchange.Properties.Should().ContainKey("CamelTimerPeriod"); capturedExchange.Properties["CamelTimerPeriod"].Should().Be(200); capturedExchange.Properties.Should().ContainKey("CamelTimerFixedRate"); capturedExchange.Properties["CamelTimerFixedRate"].Should().Be(false); } [Fact] public async Task Consumer_FixedRate_SetsProperty() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-fixedrate"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://fr?period=200&fixedRate=true"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Properties["CamelTimerFixedRate"].Should().Be(true); } [Fact] public async Task Consumer_Delay_DelaysFirstFire() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-delay"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://delayed?period=100&delay=2000"); var endpoint = component.CreateEndpoint(uri); var fireCount = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref fireCount)); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); // After 500ms with 2000ms delay, should NOT have fired yet await Task.Delay(500); var countBeforeDelay = fireCount; await consumer.Stop(); context.Dispose(); countBeforeDelay.Should().Be(0, "with 2000ms delay, no fires should occur within 500ms"); } [Fact] public async Task Consumer_ExchangePattern_IsInOnly() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-pattern"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://chk?period=200"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Pattern.Should().Be(Abstractions.ExchangePattern.InOnly); } [Fact] public async Task Consumer_QuartzFireTimeProperties_Present() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-firetime"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://ft?period=200"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Properties.Should().ContainKey("CamelQuartzFireTime"); captured.Properties.Should().ContainKey("CamelQuartzScheduledFireTime"); // NextFireTime should exist for a repeating timer captured.Properties.Should().ContainKey("CamelQuartzNextFireTime"); } [Fact] public async Task Consumer_StopIdempotent() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-idem"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://idem?period=500"); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await consumer.Stop(); // Double stop var act = () => consumer.Stop(); await act.Should().NotThrowAsync(); context.Dispose(); } [Fact] public async Task Consumer_SharedScheduler_WithCron() { // Verify that CronComponent and QuartzTimerComponent share the same scheduler var cronComponent = new CronComponent(); var timerComponent = new QuartzTimerComponent(); var context = new RouteContext("shared-scheduler-test"); context.AddComponent(cronComponent); context.AddComponent(timerComponent); await context.Start(); // the context runs: a consumer started now starts the scheduler var cronUri = EndpointUriParser.Parse("cron://cJob?schedule=* * * * * ?"); var timerUri = EndpointUriParser.Parse("qtimer://tJob?period=200"); var cronEp = cronComponent.CreateEndpoint(cronUri); var timerEp = timerComponent.CreateEndpoint(timerUri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var cronConsumer = cronEp.CreateConsumer(processor); var timerConsumer = timerEp.CreateConsumer(processor); await cronConsumer.Start(); await timerConsumer.Start(); // Both should share one scheduler var scheduler = context.GetService(); scheduler.Should().NotBeNull(); await cronConsumer.Stop(); await timerConsumer.Stop(); context.Dispose(); } [Fact] public async Task Consumer_ErrorInProcessor_DoesNotCrash() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-error"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://err?period=200"); var endpoint = component.CreateEndpoint(uri); var errorThrown = false; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { errorThrown = true; throw new InvalidOperationException("Boom"); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && !errorThrown; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); errorThrown.Should().BeTrue(); } // ── New Camel-compatible options ── [Fact] public void Options_DefaultGroupName_IsRedb() { var opts = new QuartzTimerEndpointOptions(); opts.GroupName.Should().Be("redb"); } [Fact] public void Options_DefaultDeleteJob_IsTrue() { var opts = new QuartzTimerEndpointOptions(); opts.DeleteJob.Should().BeTrue(); } [Fact] public void Options_DefaultRepeatCount_IsMinusOne() { var opts = new QuartzTimerEndpointOptions(); opts.RepeatCount.Should().Be(-1); } [Fact] public void Options_DeleteJobAndPauseJob_BothTrue_Throws() { var opts = new QuartzTimerEndpointOptions { DeleteJob = true, PauseJob = true }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*deleteJob*pauseJob*"); } [Fact] public void Options_BindFromUri_ParsesNewParams() { var uri = EndpointUriParser.Parse("qtimer://hb?period=500&stateful=true&recoverableJob=true&misfireInstruction=SimpleFireNow&repeatCount=10"); var opts = new QuartzTimerEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Period.Should().Be(500); opts.Stateful.Should().BeTrue(); opts.RecoverableJob.Should().BeTrue(); opts.MisfireInstruction.Should().Be(QuartzMisfirePolicy.SimpleFireNow); opts.RepeatCount.Should().Be(10); } [Fact] public void CreateEndpoint_WithGroupInPath_ParsesGroupAndJob() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://monitoring/heartbeat?period=500"); var endpoint = (QuartzTimerEndpoint)component.CreateEndpoint(uri); endpoint.GroupName.Should().Be("monitoring"); endpoint.JobName.Should().Be("heartbeat"); } [Fact] public void CreateEndpoint_SingleName_DefaultGroup() { var component = new QuartzTimerComponent(); var uri = EndpointUriParser.Parse("qtimer://heartbeat?period=500"); var endpoint = (QuartzTimerEndpoint)component.CreateEndpoint(uri); endpoint.GroupName.Should().Be("redb"); endpoint.JobName.Should().Be("heartbeat"); } [Fact] public async Task Consumer_FiresWithGroupProperties() { var component = new QuartzTimerComponent(); var context = new RouteContext("qtimer-group-test"); context.AddComponent(component); await context.Start(); // the context runs: a consumer started now starts the scheduler var uri = EndpointUriParser.Parse("qtimer://monitoring/heartbeat?period=200"); var endpoint = component.CreateEndpoint(uri); Abstractions.IExchange? captured = null; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); for (var i = 0; i < 50 && captured == null; i++) await Task.Delay(100); await consumer.Stop(); context.Dispose(); captured.Should().NotBeNull(); captured!.Properties["CamelTimerName"].Should().Be("heartbeat"); captured.Properties["CamelTimerGroup"].Should().Be("monitoring"); } } Path: redb-route/tests/redb.Route.Tests.Quartz/QuartzTraceTests.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.Quartz/QuartzTraceTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Quartz; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Quartz; /// /// A scheduler fire carries no trace context: the consumer opens a root span per fire, never a child of the activity /// the scheduler thread holds or the host started the routes under, with the route under it; a failed route marks it /// red, our own stop does not. EnableTelemetry=false opens none. Each test schedules a job of its own. /// public sealed class QuartzTraceTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private readonly string _job = $"trace{Guid.NewGuid():N}"; private RouteTelemetryProbe Fires() => new(a => a.Kind == ActivityKind.Consumer && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_job, StringComparison.Ordinal) == true); private async Task StartTimer(Action step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new QuartzTimerComponent()); ctx.AddRoutes(r => r.From($"qtimer://{_job}?period=100").RouteId(_job).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(50); } [Fact] public async Task Each_fire_opens_a_root_span_with_the_route_under_it() { using var fires = Fires(); using var routes = RouteTelemetryProbe.ForRouteIdPrefix(_job); IReadOnlyList ended; await using (await StartTimer(_ => { })) { await Until(() => fires.Activities.Count >= 2); ended = fires.Activities; } ended.Should().HaveCountGreaterThanOrEqualTo(2); ended.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a fire carries no context, so its span starts a trace rather than joining the host's"); routes.Activities.Should().Contain(a => a.ParentSpanId == ended[0].SpanId, "the route runs inside the fire"); } [Fact] public async Task A_failed_route_marks_the_fire_span_red() { using var fires = Fires(); IReadOnlyList ended; await using (await StartTimer(_ => throw new InvalidOperationException("route failed"))) { await Until(() => fires.Activities.Count >= 1); ended = fires.Activities; // before the stop: a fire the stop interrupts is not a failure } ended.Should().NotBeEmpty().And.OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span() { using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_job, StringComparison.Ordinal) == true || RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) == _job); var fired = new TaskCompletionSource(); await using (await StartTimer(_ => fired.TrySetResult(), telemetry: false)) (await Task.WhenAny(fired.Task, Task.Delay(Wait))).Should().Be(fired.Task); probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Quartz/Resources/quartz_tables_postgres.sql 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.Quartz/Resources/quartz_tables_postgres.sql ---- -- Quartz.NET schema for PostgreSQL (the standard Quartz.NET tables, as redb.Tsak applies them). -- Test resource of redb.Route.Tests.Quartz: applied into a schema of its own per test run. -- Idempotent: uses CREATE TABLE IF NOT EXISTS. CREATE TABLE IF NOT EXISTS qrtz_job_details ( sched_name TEXT NOT NULL, job_name TEXT NOT NULL, job_group TEXT NOT NULL, description TEXT NULL, job_class_name TEXT NOT NULL, is_durable BOOL NOT NULL, is_nonconcurrent BOOL NOT NULL, is_update_data BOOL NOT NULL, requests_recovery BOOL NOT NULL, job_data BYTEA NULL, PRIMARY KEY (sched_name, job_name, job_group) ); CREATE TABLE IF NOT EXISTS qrtz_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, job_name TEXT NOT NULL, job_group TEXT NOT NULL, description TEXT NULL, next_fire_time BIGINT NULL, prev_fire_time BIGINT NULL, priority INTEGER NULL, trigger_state TEXT NOT NULL, trigger_type TEXT NOT NULL, start_time BIGINT NOT NULL, end_time BIGINT NULL, calendar_name TEXT NULL, misfire_instr SMALLINT NULL, job_data BYTEA NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, job_name, job_group) REFERENCES qrtz_job_details (sched_name, job_name, job_group) ); CREATE TABLE IF NOT EXISTS qrtz_simple_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, repeat_count BIGINT NOT NULL, repeat_interval BIGINT NOT NULL, times_triggered BIGINT NOT NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_simprop_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, str_prop_1 TEXT NULL, str_prop_2 TEXT NULL, str_prop_3 TEXT NULL, int_prop_1 INTEGER NULL, int_prop_2 INTEGER NULL, long_prop_1 BIGINT NULL, long_prop_2 BIGINT NULL, dec_prop_1 NUMERIC NULL, dec_prop_2 NUMERIC NULL, bool_prop_1 BOOL NULL, bool_prop_2 BOOL NULL, time_zone_id TEXT NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_cron_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, cron_expression TEXT NOT NULL, time_zone_id TEXT, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_blob_triggers ( sched_name TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, blob_data BYTEA NULL, PRIMARY KEY (sched_name, trigger_name, trigger_group), FOREIGN KEY (sched_name, trigger_name, trigger_group) REFERENCES qrtz_triggers (sched_name, trigger_name, trigger_group) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS qrtz_calendars ( sched_name TEXT NOT NULL, calendar_name TEXT NOT NULL, calendar BYTEA NOT NULL, PRIMARY KEY (sched_name, calendar_name) ); CREATE TABLE IF NOT EXISTS qrtz_paused_trigger_grps ( sched_name TEXT NOT NULL, trigger_group TEXT NOT NULL, PRIMARY KEY (sched_name, trigger_group) ); CREATE TABLE IF NOT EXISTS qrtz_fired_triggers ( sched_name TEXT NOT NULL, entry_id TEXT NOT NULL, trigger_name TEXT NOT NULL, trigger_group TEXT NOT NULL, instance_name TEXT NOT NULL, fired_time BIGINT NOT NULL, sched_time BIGINT NOT NULL, priority INTEGER NOT NULL, state TEXT NOT NULL, job_name TEXT NULL, job_group TEXT NULL, is_nonconcurrent BOOL NOT NULL, requests_recovery BOOL NULL, PRIMARY KEY (sched_name, entry_id) ); CREATE TABLE IF NOT EXISTS qrtz_scheduler_state ( sched_name TEXT NOT NULL, instance_name TEXT NOT NULL, last_checkin_time BIGINT NOT NULL, checkin_interval BIGINT NOT NULL, PRIMARY KEY (sched_name, instance_name) ); CREATE TABLE IF NOT EXISTS qrtz_locks ( sched_name TEXT NOT NULL, lock_name TEXT NOT NULL, PRIMARY KEY (sched_name, lock_name) ); -- Indexes CREATE INDEX IF NOT EXISTS idx_qrtz_j_req_recovery ON qrtz_job_details (requests_recovery); CREATE INDEX IF NOT EXISTS idx_qrtz_t_next_fire_time ON qrtz_triggers (next_fire_time); CREATE INDEX IF NOT EXISTS idx_qrtz_t_state ON qrtz_triggers (trigger_state); CREATE INDEX IF NOT EXISTS idx_qrtz_t_nft_st ON qrtz_triggers (next_fire_time, trigger_state); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_name ON qrtz_fired_triggers (trigger_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_group ON qrtz_fired_triggers (trigger_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_nm_gp ON qrtz_fired_triggers (sched_name, trigger_name, trigger_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_trig_inst_name ON qrtz_fired_triggers (instance_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_name ON qrtz_fired_triggers (job_name); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_group ON qrtz_fired_triggers (job_group); CREATE INDEX IF NOT EXISTS idx_qrtz_ft_job_req_recovery ON qrtz_fired_triggers (requests_recovery); Path: redb-route/tests/redb.Route.Tests.Quartz/ServiceCollectionExtensionsTests.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.Quartz/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Quartz; namespace redb.Route.Tests.Quartz; /// /// Tests for ServiceCollectionExtensions — DI registration methods. /// public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteQuartz_RegistersBothComponents() { var services = new ServiceCollection(); services.AddRedbRouteQuartz(); var provider = services.BuildServiceProvider(); provider.GetService().Should().NotBeNull(); provider.GetService().Should().NotBeNull(); } [Fact] public void AddRedbRouteCron_RegistersCronOnly() { var services = new ServiceCollection(); services.AddRedbRouteCron(); var provider = services.BuildServiceProvider(); provider.GetService().Should().NotBeNull(); provider.GetService().Should().BeNull(); } [Fact] public void AddRedbRouteQuartzTimer_RegistersTimerOnly() { var services = new ServiceCollection(); services.AddRedbRouteQuartzTimer(); var provider = services.BuildServiceProvider(); provider.GetService().Should().NotBeNull("AddRedbRouteQuartzTimer should register QuartzTimerComponent"); provider.GetService().Should().BeNull("AddRedbRouteQuartzTimer should NOT register CronComponent"); } [Fact] public void AddRedbRouteQuartz_ComponentsSingleton() { var services = new ServiceCollection(); services.AddRedbRouteQuartz(); var provider = services.BuildServiceProvider(); var cron1 = provider.GetService(); var cron2 = provider.GetService(); cron1.Should().BeSameAs(cron2, "CronComponent should be singleton"); var timer1 = provider.GetService(); var timer2 = provider.GetService(); timer1.Should().BeSameAs(timer2, "QuartzTimerComponent should be singleton"); } } Path: redb-route/tests/redb.Route.Tests.Quartz/redb.Route.Tests.Quartz.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.Quartz/redb.Route.Tests.Quartz.csproj ----