API reference — Scheduling

Nuvora.Nexus.Relay.Scheduling

Scheduled / delayed message abstractions and processor for Nuvora Nexus Relay

dotnet add package Nuvora.Nexus.Relay.Scheduling

Nuvora.Nexus.Relay.Scheduling

IScheduler

public interface IScheduler

Write-side scheduling API. Calls stage a row on the command’s DbContext (via the scoped ISchedulerRepository), so a scheduled message commits atomically with the work that requested it — a rolled-back command schedules nothing. Resolve from a command handler’s scope.

Methods

Task<Guid> ScheduleAsync(ScheduledMessage message, CancellationToken cancellationToken = default(CancellationToken))

Schedule a pre-built message (used for saga timeouts and advanced scenarios).

Task<Guid> ScheduleCommandAsync<TCommand>(TCommand command, DateTimeOffset fireAt, CancellationToken cancellationToken = default(CancellationToken))

Schedule a fire-and-forget command for delivery at fireAt.

Task<Guid> ScheduleCommandAsync<TCommand>(TCommand command, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Schedule a fire-and-forget command for delivery after delay.

Task<int> CancelAsync(Guid scheduledMessageId, CancellationToken cancellationToken = default(CancellationToken))

Cancel a single scheduled message by id.

Task<int> CancelByCorrelationAsync(Guid correlationId, CancellationToken cancellationToken = default(CancellationToken))

Cancel every not-yet-delivered message for a correlation id (e.g. all of one saga’s timeouts).

Task<int> CancelByKeyAsync(string cancellationKey, CancellationToken cancellationToken = default(CancellationToken))

Cancel every not-yet-delivered message for a cancellation key.

Scheduler

public sealed class Scheduler : IScheduler

Default IScheduler. Serializes the payload, stamps the ambient tenant (when tenancy is wired), and stages the row via the scoped ISchedulerRepository so it commits with the caller’s transaction.

Constructors

Scheduler(ISchedulerRepository repository, IScheduledMessageSerializer serializer, IScheduledTenantStamper? tenantStamper = null, TimeProvider? timeProvider = null)

Methods

Task<Guid> ScheduleAsync(ScheduledMessage message, CancellationToken cancellationToken = default(CancellationToken))

Schedule a pre-built message (used for saga timeouts and advanced scenarios).

Task<Guid> ScheduleCommandAsync<TCommand>(TCommand command, DateTimeOffset fireAt, CancellationToken cancellationToken = default(CancellationToken))

Schedule a fire-and-forget command for delivery at fireAt.

Task<Guid> ScheduleCommandAsync<TCommand>(TCommand command, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Schedule a fire-and-forget command for delivery after delay.

Task<int> CancelAsync(Guid scheduledMessageId, CancellationToken cancellationToken = default(CancellationToken))

Cancel a single scheduled message by id.

Task<int> CancelByCorrelationAsync(Guid correlationId, CancellationToken cancellationToken = default(CancellationToken))

Cancel every not-yet-delivered message for a correlation id (e.g. all of one saga’s timeouts).

Task<int> CancelByKeyAsync(string cancellationKey, CancellationToken cancellationToken = default(CancellationToken))

Cancel every not-yet-delivered message for a cancellation key.

ServiceCollectionExtensions

public static class ServiceCollectionExtensions

Registration helpers for the Relay scheduler.

Methods

static IServiceCollection AddRelayScheduling(this IServiceCollection services, Action<SchedulerProcessorOptions>? configure = null)

Registers the scheduler: the write-side IScheduler, the built-in command dispatcher, the processor and backlog monitor. Requires a registered ISchedulerRepository (via AddRelaySchedulerEfCore<TContext>) and the core Relay services (AddRelay, for ICommandBus and the wake hub).

static IServiceCollection AddRelayScheduling(this IServiceCollection services, IConfiguration configuration)

Registers the scheduler, binding options from the "Scheduler" configuration section.

Nuvora.Nexus.Relay.Scheduling.Dispatch

CommandScheduledMessageDispatcher

public sealed class CommandScheduledMessageDispatcher : IScheduledMessageDispatcher

Delivers ScheduledDeliveryKind.Command messages by dispatching the deserialized payload through ICommandBus — so a scheduled command runs the full pipeline (authorization, tenancy enforcement, transaction) exactly like a live one. The scheduled message id is not threaded into the command here; handlers that must be idempotent under at-least-once delivery should rely on their own natural keys (the lease already prevents concurrent double-delivery).

Constructors

CommandScheduledMessageDispatcher(IScheduledMessageSerializer serializer)

Properties

ScheduledDeliveryKind Kind { get; }

The delivery kind this dispatcher handles.

Methods

Task DispatchAsync(ScheduledMessage message, IServiceProvider scope, CancellationToken cancellationToken)

Deliver the message. scope is a fresh per-message DI scope; the ambient tenant (if any) has already been re-established by the processor. Throwing records a delivery failure (retry/backoff/dead-letter); returning normally marks the message executed.

IScheduledMessageDispatcher

public interface IScheduledMessageDispatcher

Delivers a due scheduled message back into the system. One implementation per ScheduledDeliveryKind; the processor routes by IScheduledMessageDispatcher.Kind. The sagas package registers a dispatcher for ScheduledDeliveryKind.SagaTimeout; the command dispatcher is built in.

Properties

ScheduledDeliveryKind Kind { get; }

The delivery kind this dispatcher handles.

Methods

Task DispatchAsync(ScheduledMessage message, IServiceProvider scope, CancellationToken cancellationToken)

Deliver the message. scope is a fresh per-message DI scope; the ambient tenant (if any) has already been re-established by the processor. Throwing records a delivery failure (retry/backoff/dead-letter); returning normally marks the message executed.

Nuvora.Nexus.Relay.Scheduling.Domain

RecurringCatchUpPolicy

public enum RecurringCatchUpPolicy

How to treat occurrences that came due while the processor was down.

Values

  • Skip — Fire only the most recent due occurrence once, then resume from the next future occurrence.
  • Backfill — Fire every missed occurrence in order (bounded by RecurringSchedule.MaxBackfill).

RecurringSchedule

public class RecurringSchedule

A durable recurring schedule. The processor fires it by enqueuing a one-shot ScheduledMessage for each due occurrence, so the existing claim/lease/dispatch/retry and tenancy machinery handles delivery. RecurringSchedule.NextFireAt is the next occurrence to enqueue and is advanced atomically with the enqueue (exactly-once enqueue per occurrence under normal operation; at-least-once across a crash, like the rest of the scheduler).

Properties

DateTimeOffset CreatedAt { get; set; }
DateTimeOffset NextFireAt { get; set; }

The next occurrence instant to enqueue. Due when <= now.

DateTimeOffset UpdatedAt { get; set; }
DateTimeOffset? LastFiredAt { get; set; }
Guid Id { get; set; }
Guid? TenantId { get; set; }

Owning tenant (null = global); re-established on delivery via the tenant stamper.

RecurringCatchUpPolicy CatchUpPolicy { get; set; }

What to do with occurrences missed during downtime.

ScheduledDeliveryKind Kind { get; set; }

How the enqueued occurrence is delivered (command / integration event).

bool Enabled { get; set; }
int MaxBackfill { get; set; }

Maximum number of missed occurrences to enqueue when RecurringSchedule.CatchUpPolicy is Backfill.

string CronExpression { get; set; }

Standard 5-field (or 6-field with seconds) cron expression.

string MessageType { get; set; }

Serialized message type name (assembly-qualified, version-independent).

string Name { get; set; }

Stable unique name (the upsert/identify/cancel key).

string Payload { get; set; }

Serialized message payload (jsonb).

string TimeZoneId { get; set; }

IANA/Windows time-zone id the cron expression is evaluated in (DST-correct). Default UTC.

ScheduledDeliveryKind

public enum ScheduledDeliveryKind

How a due scheduled message re-enters the system (numeric values are persisted).

Values

  • Command — Dispatch the payload as a command through ICommandBus — the full pipeline (authorization, tenancy, transaction) runs, so a scheduled command is indistinguishable from a live one.
  • SagaTimeout — Deliver the payload to a saga as a timeout (correlated by ScheduledMessage.CorrelationId). Handled by the sagas package’s dispatcher; bypasses the command pipeline.
  • IntegrationEvent — Dispatch the payload to local integration-event handlers (deferred publish).
  • Job — Dispatch the payload to its registered IJobHandler<TJob> — a durable background job. Reuses the scheduler’s claim/lease/retry/dead-letter machinery, so a job is delivered at least once across the cluster and retried with backoff on failure.
  • ConsumerRedelivery — Re-publish a broker message back to its queue after a delay — a scheduled (“second-level”) redelivery of a consumed message whose handler asked to retry after a delay (ErrorOutcome.RetryAfter). Handled by the scheduling package’s redelivery dispatcher, which rebuilds the MessageBrokerMessage from its envelope and publishes via IMessageBroker; bypasses the command pipeline.

ScheduledMessage

public class ScheduledMessage

A message persisted in relay_scheduled_messages for future delivery. Staged on the command’s DbContext on the write path (so it commits atomically with the work that requested it) and claimed by the SchedulerProcessor with a FOR UPDATE SKIP LOCKED lease on the poller path (so multiple instances never deliver the same message). Modelled on OutboxMessage with a future-dated ScheduledMessage.ScheduledFor instead of immediate delivery.

Properties

DateTimeOffset CreatedAt { get; set; }

When the row was created.

DateTimeOffset NextAttemptAt { get; set; }

Earliest re-attempt time after a delivery failure (exponential backoff). The due predicate is GREATEST(scheduled_for, next_attempt_at), so backoff never delivers a message before its scheduled time, and a failed message respects both.

DateTimeOffset ScheduledFor { get; set; }

When the message becomes due for delivery.

DateTimeOffset? ClaimedAt { get; set; }

Lease timestamp: when the row was last claimed (null until first claim). A Processing row whose claim is older than the lease is treated as stranded and re-claimed.

DateTimeOffset? ExecutedAt { get; set; }

When the message was delivered (null until executed).

Guid Id { get; set; }

Primary key.

Guid? CorrelationId { get; set; }

Correlation id — the owning saga id for ScheduledDeliveryKind.SagaTimeout, also used for targeted cancellation.

Guid? TenantId { get; set; }

Owning tenant (null = global / not tenant-scoped). Re-established on the ambient context before delivery so a scheduled tenant-scoped command/timeout runs under its tenant.

ScheduledDeliveryKind Kind { get; set; }

How the payload re-enters the system when due.

ScheduledMessageStatus Status { get; set; }

Current lifecycle status.

int RetryCount { get; set; }

Number of delivery attempts that have failed.

string MessageType { get; set; }

Stable type name of the payload (used to resolve the CLR type on delivery).

string Payload { get; set; }

Serialized JSON payload.

string? CancellationKey { get; set; }

Free-form cancellation key (e.g. a saga’s correlation key) for bulk cancellation.

string? ErrorMessage { get; set; }

Last delivery error (for dead-letter inspection).

ScheduledMessageStatus

public enum ScheduledMessageStatus

Lifecycle status of a scheduled message (numeric values are persisted — do not reorder).

Values

  • Pending — Waiting to become due (or rescheduled after a delivery failure’s backoff).
  • Processing — Claimed by a processor and being delivered.
  • Executed — Delivered successfully.
  • Failed — Delivery failed past the retry limit (dead letter).
  • Cancelled — Cancelled before delivery (e.g. a saga cancelled its timeout).

Nuvora.Nexus.Relay.Scheduling.HealthChecks

SchedulerHealthCheck

public sealed class SchedulerHealthCheck : IHealthCheck

Health check over the scheduler: reports Degraded/Unhealthy when due messages age (a stalled processor) or dead letters accumulate. Distinguishes “due but undelivered” (the actionable signal) from “scheduled for the future” (normal).

Constructors

SchedulerHealthCheck(IServiceScopeFactory scopeFactory, IOptions<SchedulerHealthCheckOptions> options)

Methods

Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))

Runs the health check, returning the status of the component being checked.

SchedulerHealthCheckBuilderExtensions

public static class SchedulerHealthCheckBuilderExtensions

Health-check registration for the scheduler.

Methods

static IHealthChecksBuilder AddRelayScheduler(this IHealthChecksBuilder builder, Action<SchedulerHealthCheckOptions>? configure = null, string name = "relay-scheduler", IEnumerable<string>? tags = null)

Adds the scheduler backlog health check (overdue age, dead-letter accumulation).

SchedulerHealthCheckOptions

public sealed class SchedulerHealthCheckOptions

Thresholds for SchedulerHealthCheck.

Properties

TimeSpan DegradedDueAge { get; set; }

Oldest already-due age above which the scheduler is reported Degraded (delivery lagging).

TimeSpan UnhealthyDueAge { get; set; }

Oldest already-due age above which the scheduler is reported Unhealthy (delivery stuck).

long DegradedDeadLettered { get; set; }

Dead-lettered count at or above which the scheduler is reported Degraded.

Nuvora.Nexus.Relay.Scheduling.Infrastructure

ISchedulerRepository

public interface ISchedulerRepository

Repository for scheduled messages. The write path (ISchedulerRepository.ScheduleAsync) enlists in the caller’s ambient transaction (stages on the command’s DbContext); the poller path (ISchedulerRepository.ClaimDueAsync, ISchedulerRepository.MarkExecutedAsync, ISchedulerRepository.RecordFailureAsync) uses its own short transactions and is multi-instance safe (claims lock rows with FOR UPDATE SKIP LOCKED). Mirrors IOutboxRepository.

Methods

Task MarkExecutedAsync(Guid id, CancellationToken cancellationToken = default(CancellationToken))

Mark a claimed message as delivered.

Task ScheduleAsync(ScheduledMessage message, CancellationToken cancellationToken = default(CancellationToken))

Stage a scheduled message on the ambient transaction (not flushed here).

Task<DateTimeOffset?> GetNextDueAtAsync(CancellationToken cancellationToken = default(CancellationToken))

The next time any pending message becomes due, or null when none are pending. Lets the processor sleep exactly until the next due time instead of polling blindly.

Task<IReadOnlyList<ScheduledMessage>> ClaimDueAsync(int batchSize = 100, CancellationToken cancellationToken = default(CancellationToken))

Atomically claim up to batchSize due messages: Pending rows whose GREATEST(scheduled_for, next_attempt_at) is due, plus Processing rows whose claim has expired (stranded by a crash). Claimed rows are marked Processing with a fresh lease.

Task<IReadOnlyList<ScheduledMessage>> GetFailedAsync(int batchSize = 100, CancellationToken cancellationToken = default(CancellationToken))

Dead-lettered rows for inspection.

Task<IReadOnlyList<ScheduledMessage>> GetUpcomingAsync(int batchSize = 100, CancellationToken cancellationToken = default(CancellationToken))

Upcoming (not-yet-delivered) scheduled messages ordered by effective due time, for operator dashboards. Returns Pending rows only (both already-due and future), oldest-due first.

Task<ScheduledFailureOutcome> RecordFailureAsync(Guid id, string errorMessage, int maxRetries, CancellationToken cancellationToken = default(CancellationToken))

Record a delivery failure against the live row (backoff + dead-letter at the cap). A no-op returning ScheduledFailureOutcome.NotFound when the row is no longer Processing — e.g. it was cancelled while in-flight and must not be resurrected.

Task<SchedulerBacklog> GetBacklogAsync(CancellationToken cancellationToken = default(CancellationToken))

Aggregate depth counters for health checks and gauges.

Task<bool> DiscardFailedAsync(Guid id, CancellationToken cancellationToken = default(CancellationToken))

Permanently discard (delete) a dead-lettered scheduled message. False when not found / not failed.

Task<bool> RequeueFailedAsync(Guid id, CancellationToken cancellationToken = default(CancellationToken))

Requeue a dead-lettered message for immediate delivery. False when not found / not failed.

Task<int> CancelAsync(Guid id, CancellationToken cancellationToken = default(CancellationToken))

Cancel a single not-yet-delivered message. Returns rows affected (0 if already terminal).

Task<int> CancelByCorrelationAsync(Guid correlationId, CancellationToken cancellationToken = default(CancellationToken))

Cancel all not-yet-delivered messages for a correlation id (e.g. a saga’s timeouts).

Task<int> CancelByKeyAsync(string cancellationKey, CancellationToken cancellationToken = default(CancellationToken))

Cancel all not-yet-delivered messages for a cancellation key.

Task<int> DeleteCompletedAsync(DateTimeOffset olderThan, CancellationToken cancellationToken = default(CancellationToken))

Delete executed/cancelled rows older than the cut-off (maintenance). Returns rows deleted.

ScheduledFailureOutcome

public enum ScheduledFailureOutcome

Outcome of recording a delivery failure for a scheduled message.

Values

  • ScheduledForRetry — The message will be retried after its backoff delay.
  • DeadLettered — The message exhausted its retries and was dead-lettered.
  • NotFound — No Processing row with the given id exists (pruned, or cancelled while in-flight); nothing was recorded — in particular a cancelled row stays cancelled.

SchedulerBacklog

public sealed record SchedulerBacklog : IEquatable<SchedulerBacklog>

Aggregate scheduler depth counters for health checks and metrics.

Constructors

SchedulerBacklog(long Due, long Pending, long DeadLettered, TimeSpan? OldestDueAge)

Aggregate scheduler depth counters for health checks and metrics.

Properties

TimeSpan? OldestDueAge { get; init; }

Age of the oldest already-due row, or null when none are overdue.

long DeadLettered { get; init; }

Rows that exhausted retries (status Failed).

long Due { get; init; }

Rows already due but not yet delivered.

long Pending { get; init; }

Rows scheduled for the future (not yet due).

Nuvora.Nexus.Relay.Scheduling.Jobs

IJob

public interface IJob

Marker for a durable background-job payload. A job is enqueued via IJobScheduler, persisted by the scheduler, and dispatched to its registered IJobHandler. The payload is JSON-serialized, so it should be a simple data record.

IJobHandler<TJob>

public interface IJobHandler<TJob> where TJob : IJob

Handles a durable background job of type TJob. Resolved from a fresh DI scope per delivery. Throwing records a delivery failure (retry/backoff/dead-letter via the scheduler); returning normally marks the job done. Handlers should be idempotent — delivery is at-least-once.

Methods

Task HandleAsync(TJob job, CancellationToken cancellationToken)

IJobScheduler

public interface IJobScheduler

Write-side API for durable background jobs. Like IScheduler, calls stage a row on the command’s DbContext, so a job commits atomically with the work that enqueued it (a rolled-back command enqueues nothing). Resolve from a command handler’s scope.

Methods

Task<Guid> EnqueueAsync<TJob>(TJob job, CancellationToken cancellationToken = default(CancellationToken))

Enqueue job for processing as soon as possible.

Task<Guid> ScheduleAsync<TJob>(TJob job, DateTimeOffset runAt, CancellationToken cancellationToken = default(CancellationToken))

Schedule job to run at runAt.

Task<Guid> ScheduleAsync<TJob>(TJob job, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Schedule job to run after delay.

JobScheduledMessageDispatcher

public sealed class JobScheduledMessageDispatcher : IScheduledMessageDispatcher

Delivers ScheduledDeliveryKind.Job messages by deserializing the payload and invoking its registered IJobHandler resolved from the per-delivery scope. Mirrors the command/saga-timeout dispatchers.

Constructors

JobScheduledMessageDispatcher(IScheduledMessageSerializer serializer)

Properties

ScheduledDeliveryKind Kind { get; }

The delivery kind this dispatcher handles.

Methods

Task DispatchAsync(ScheduledMessage message, IServiceProvider scope, CancellationToken cancellationToken)

Deliver the message. scope is a fresh per-message DI scope; the ambient tenant (if any) has already been re-established by the processor. Throwing records a delivery failure (retry/backoff/dead-letter); returning normally marks the message executed.

JobScheduler

public sealed class JobScheduler : IJobScheduler

IJobScheduler implemented over the scheduler: stages a ScheduledMessage of kind ScheduledDeliveryKind.Job carrying the serialized job, so jobs inherit the scheduler’s atomic staging, claim/lease, retry/backoff and dead-lettering.

Constructors

JobScheduler(IScheduler scheduler, IScheduledMessageSerializer serializer)

Methods

Task<Guid> EnqueueAsync<TJob>(TJob job, CancellationToken cancellationToken = default(CancellationToken))

Enqueue job for processing as soon as possible.

Task<Guid> ScheduleAsync<TJob>(TJob job, DateTimeOffset runAt, CancellationToken cancellationToken = default(CancellationToken))

Schedule job to run at runAt.

Task<Guid> ScheduleAsync<TJob>(TJob job, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Schedule job to run after delay.

JobsServiceCollectionExtensions

public static class JobsServiceCollectionExtensions

Registration helpers for durable background jobs (built on the scheduler).

Methods

static IServiceCollection AddJobHandler<TJob, THandler>(this IServiceCollection services)

Registers THandler as the handler for job type TJob.

static IServiceCollection AddRelayJobs(this IServiceCollection services)

Registers the durable-job support: the write-side IJobScheduler and the job dispatcher for ScheduledDeliveryKind.Job. Requires the scheduler (AddRelayScheduling plus a repository via AddRelaySchedulerEfCore). Register handlers with JobsServiceCollectionExtensions.AddJobHandler.

Nuvora.Nexus.Relay.Scheduling.Monitoring

SchedulerBacklogMonitor

public sealed class SchedulerBacklogMonitor : BackgroundService

Periodically samples the scheduler backlog into the RelayTelemetry gauges — due depth, dead-letter depth and oldest-due age. One cheap aggregate query per interval; sampling failures are logged and retried, never propagated.

Constructors

SchedulerBacklogMonitor(IServiceScopeFactory scopeFactory, IOptions<SchedulerMonitoringOptions> options, ILogger<SchedulerBacklogMonitor> logger)

Methods

override Task ExecuteAsync(CancellationToken stoppingToken)

This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.

SchedulerMonitoringOptions

public sealed class SchedulerMonitoringOptions

Options for SchedulerBacklogMonitor.

Properties

TimeSpan SamplingInterval { get; set; }

How often the scheduler backlog is sampled into the gauges.

bool Enabled { get; set; }

Whether backlog sampling runs.

Nuvora.Nexus.Relay.Scheduling.Processors

SchedulerProcessor

public sealed class SchedulerProcessor : BackgroundService

Background service that claims due scheduled messages and delivers them. Modelled on the outbox processor (FOR UPDATE SKIP LOCKED claim, bounded delivery concurrency, bookkeeping on CancellationToken.None so shutdown never strands a Processing row), with one difference: work is future-dated, so the idle wait sleeps until the next due time (bounded), woken early by a relay_scheduler notification when an earlier message is staged. The batch is claimed in its own DI scope; each delivery then runs in a fresh per-delivery scope so scoped services (unit of work, DbContext) are never shared across concurrent deliveries.

Constructors

SchedulerProcessor(IServiceScopeFactory scopeFactory, IOptions<SchedulerProcessorOptions> options, ILogger<SchedulerProcessor> logger, IRelayWakeHub? wakeHub = null, TimeProvider? timeProvider = null)

Methods

Task<int> ProcessDueMessagesAsync(CancellationToken cancellationToken)

Claims and delivers one batch of due messages. Public so it can be driven directly from tests and from a manual trigger; the background loop calls it each cycle. Returns the number claimed.

override Task ExecuteAsync(CancellationToken stoppingToken)

This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.

SchedulerProcessorOptions

public sealed class SchedulerProcessorOptions

Configuration for the SchedulerProcessor.

Properties

RetryStrategy RetryStrategy { get; set; }

Backoff strategy applied after a delivery failure. The default RetryStrategy.Exponential reproduces the historical 2s, 4s, 8s, … curve. Ignored when an IRetryPolicy is registered in DI.

bool EnableWakeNotifications { get; set; }

Whether staging emits a transactional pg_notify(relay_scheduler) so the processor re-evaluates its next-due sleep at commit. Latency optimization only; polling is the fallback.

bool Enabled { get; set; }

Whether the processor runs.

double MaxRetryDelaySeconds { get; set; }

Cap (seconds) on the backoff.

double RetryBaseDelaySeconds { get; set; }

Base seconds for backoff after a delivery failure: for exponential backoff the nth retry waits min(MaxRetryDelaySeconds, RetryBaseDelaySeconds * 2^(n-1)).

double RetryIncrementSeconds { get; set; }

Per-attempt increment (seconds) used only by RetryStrategy.Incremental backoff.

int BatchSize { get; set; }

Maximum number of due messages claimed per cycle.

int DeliveryConcurrency { get; set; }

How many claimed messages are delivered concurrently.

int IdlePollingIntervalMilliseconds { get; set; }

Fallback poll interval (ms) when no message is pending and no wake listener is live.

int MaxRetries { get; set; }

Maximum delivery attempts before a message is dead-lettered.

int MaxSleepMilliseconds { get; set; }

Upper bound (ms) on a single sleep, even when the next message is due far in the future, so the processor periodically re-checks (clock skew, externally inserted rows without a wake).

int ProcessingLeaseSeconds { get; set; }

Processing lease (seconds): a Processing row whose claim is older than this is treated as stranded (crashed processor) and re-claimed. A re-delivered timeout/command must be idempotent.

Nuvora.Nexus.Relay.Scheduling.Recurring

CronRecurringOccurrencePlanner

public sealed class CronRecurringOccurrencePlanner : IRecurringOccurrencePlanner

IRecurringOccurrencePlanner backed by Cronos. Supports standard 5-field and 6-field (with-seconds) cron expressions, evaluated in the schedule’s time zone with correct DST handling.

Methods

DateTimeOffset GetFirstOccurrence(string cronExpression, string timeZoneId, DateTimeOffset after)

Validates a cron expression + time zone and returns the first occurrence strictly after after. Throws on an invalid expression/zone (used at upsert for validation).

RecurringPlan Plan(RecurringSchedule schedule, DateTimeOffset now)

Plans a due schedule: which occurrence(s) to enqueue now (honouring the catch-up policy) and the next future occurrence to store on the schedule.

IRecurringOccurrencePlanner

public interface IRecurringOccurrencePlanner

Computes occurrence instants for a recurring schedule from its cron expression and time zone. Kept separate from persistence so the cron engine (Cronos) stays in the core package and the EF Core repository only deals with rows.

Methods

DateTimeOffset GetFirstOccurrence(string cronExpression, string timeZoneId, DateTimeOffset after)

Validates a cron expression + time zone and returns the first occurrence strictly after after. Throws on an invalid expression/zone (used at upsert for validation).

RecurringPlan Plan(RecurringSchedule schedule, DateTimeOffset now)

Plans a due schedule: which occurrence(s) to enqueue now (honouring the catch-up policy) and the next future occurrence to store on the schedule.

IRecurringScheduleRepository

public interface IRecurringScheduleRepository

Persistence for recurring schedules. The processor path (IRecurringScheduleRepository.ProcessDueAsync) claims due rows with FOR UPDATE SKIP LOCKED, enqueues the planned occurrences as one-shot scheduled messages, and advances the row — all in one transaction, so a given occurrence is enqueued once.

Methods

Task UpsertAsync(RecurringSchedule schedule, CancellationToken cancellationToken = default(CancellationToken))

Inserts the schedule, or merges it into the existing row with the same name. On an existing row the persisted RecurringSchedule.NextFireAt and RecurringSchedule.Enabled are preserved unless the cadence (cron expression / time zone) changed: re-registration on redeploy must neither skip occurrences missed during downtime (the catch-up policy handles them) nor re-enable an operator-paused schedule.

Task<Guid?> EnqueueImmediateAsync(string name, DateTimeOffset now, CancellationToken cancellationToken = default(CancellationToken))

Enqueues a single immediate one-shot delivery of the schedule’s message (used by TriggerNowAsync). Returns the new scheduled-message id, or null if the schedule is unknown.

Task<IReadOnlyList<RecurringSchedule>> ListAsync(CancellationToken cancellationToken = default(CancellationToken))
Task<RecurringSchedule?> GetAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> RemoveAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> SetEnabledAsync(string name, bool enabled, CancellationToken cancellationToken = default(CancellationToken))
Task<int> ProcessDueAsync(DateTimeOffset now, int batchSize, Func<RecurringSchedule, RecurringPlan> plan, CancellationToken cancellationToken = default(CancellationToken))

Claims due schedules and, for each, enqueues the occurrences produced by plan and advances RecurringSchedule.NextFireAt atomically. Returns the number of occurrences enqueued.

IRecurringScheduler

public interface IRecurringScheduler

Write-side API for recurring (cron) schedules. Upserting validates the cron expression and time zone and computes the first occurrence; the background processor then enqueues one-shot scheduled messages for each due occurrence.

Methods

Task UpsertRecurringAsync(string name, string cronExpression, object message, Action<RecurringScheduleOptions>? configure = null, CancellationToken cancellationToken = default(CancellationToken))

Creates the schedule, or updates it when one with the same name exists. Re-registering an existing schedule (the normal every-deploy path) is safe: the persisted NextFireAt is kept unless the cadence (cron expression / time zone) changed — so occurrences missed during downtime stay due for the catch-up policy — and a paused schedule is not re-enabled unless the cadence changed.

Task<Guid?> TriggerNowAsync(string name, CancellationToken cancellationToken = default(CancellationToken))

Enqueues an immediate one-shot delivery of the schedule’s message. Returns null if unknown.

Task<IReadOnlyList<RecurringSchedule>> ListRecurringAsync(CancellationToken cancellationToken = default(CancellationToken))
Task<bool> PauseRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> RemoveRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> ResumeRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))

RecurringPlan

public readonly record struct RecurringPlan : IEquatable<RecurringPlan>

The result of planning a due recurring schedule: the occurrence instants to enqueue now and the next occurrence to record on the schedule. RecurringPlan.NextFireAt is always strictly in the future relative to the planning instant so the schedule cannot re-fire in a tight loop.

Constructors

RecurringPlan(IReadOnlyList<DateTimeOffset> Occurrences, DateTimeOffset NextFireAt)

The result of planning a due recurring schedule: the occurrence instants to enqueue now and the next occurrence to record on the schedule. RecurringPlan.NextFireAt is always strictly in the future relative to the planning instant so the schedule cannot re-fire in a tight loop.

Properties

DateTimeOffset NextFireAt { get; init; }
IReadOnlyList<DateTimeOffset> Occurrences { get; init; }

RecurringScheduleMessageFactory

public static class RecurringScheduleMessageFactory

Builds the one-shot ScheduledMessage enqueued for a recurring occurrence. The deterministic ScheduledMessage.CancellationKey (recurring:{name}:{occurrence}) lets operators cancel a specific occurrence and aids tracing.

Methods

static ScheduledMessage Create(RecurringSchedule schedule, DateTimeOffset occurrence, DateTimeOffset now)

RecurringScheduleOptions

public sealed class RecurringScheduleOptions

Per-schedule options supplied to IRecurringScheduler.UpsertRecurringAsync.

Properties

Guid? TenantId { get; set; }

Explicit owning tenant; when null the ambient tenant (if any) is stamped.

RecurringCatchUpPolicy CatchUpPolicy { get; set; }

How to treat occurrences missed during downtime. Default RecurringCatchUpPolicy.Skip.

ScheduledDeliveryKind Kind { get; set; }

Delivery kind for the enqueued occurrence. Default ScheduledDeliveryKind.Command.

bool Enabled { get; set; }

Whether the schedule is active on creation.

int MaxBackfill { get; set; }

Max missed occurrences enqueued on catch-up when RecurringScheduleOptions.CatchUpPolicy is Backfill.

string TimeZoneId { get; set; }

Time zone the cron expression is evaluated in (DST-correct). Default UTC.

RecurringScheduleProcessor

public sealed class RecurringScheduleProcessor : BackgroundService

Background service that scans for due recurring schedules and enqueues their occurrences as one-shot scheduled messages (which the SchedulerProcessor then delivers). A fresh DI scope is created per cycle so the repository’s DbContext is short-lived.

Constructors

RecurringScheduleProcessor(IServiceScopeFactory scopeFactory, IRecurringOccurrencePlanner planner, IOptions<RecurringScheduleProcessorOptions> options, TimeProvider timeProvider, ILogger<RecurringScheduleProcessor> logger)

Methods

override Task ExecuteAsync(CancellationToken stoppingToken)

This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.

RecurringScheduleProcessorOptions

public sealed class RecurringScheduleProcessorOptions

Options for the recurring-schedule processor.

Properties

TimeSpan PollingInterval { get; set; }

How often to scan for due schedules. Cron granularity is at least a minute, so a coarse poll is fine; the enqueued one-shot messages are then handled promptly by the scheduler processor.

bool Enabled { get; set; }
int BatchSize { get; set; }

Maximum due schedules processed per cycle.

RecurringScheduler

public sealed class RecurringScheduler : IRecurringScheduler

Default IRecurringScheduler. Serializes the message, stamps the ambient tenant, and upserts the schedule with a validated first occurrence. The repository applies that first occurrence (and the options’ Enabled) only to new schedules or when the cadence changed; an unchanged re-registration keeps the persisted NextFireAt/Enabled.

Constructors

RecurringScheduler(IRecurringScheduleRepository repository, IScheduledMessageSerializer serializer, IRecurringOccurrencePlanner planner, IScheduledTenantStamper? tenantStamper = null, TimeProvider? timeProvider = null)

Methods

Task UpsertRecurringAsync(string name, string cronExpression, object message, Action<RecurringScheduleOptions>? configure = null, CancellationToken cancellationToken = default(CancellationToken))

Creates the schedule, or updates it when one with the same name exists. Re-registering an existing schedule (the normal every-deploy path) is safe: the persisted NextFireAt is kept unless the cadence (cron expression / time zone) changed — so occurrences missed during downtime stay due for the catch-up policy — and a paused schedule is not re-enabled unless the cadence changed.

Task<Guid?> TriggerNowAsync(string name, CancellationToken cancellationToken = default(CancellationToken))

Enqueues an immediate one-shot delivery of the schedule’s message. Returns null if unknown.

Task<IReadOnlyList<RecurringSchedule>> ListRecurringAsync(CancellationToken cancellationToken = default(CancellationToken))
Task<bool> PauseRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> RemoveRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
Task<bool> ResumeRecurringAsync(string name, CancellationToken cancellationToken = default(CancellationToken))

RecurringSchedulingServiceCollectionExtensions

public static class RecurringSchedulingServiceCollectionExtensions

Registration helpers for recurring (cron) schedules.

Methods

static IServiceCollection AddRelayRecurringScheduling(this IServiceCollection services, Action<RecurringScheduleProcessorOptions>? configure = null)

Registers the recurring scheduler, the cron occurrence planner and the background processor. Additive to AddRelayScheduling (which delivers the enqueued occurrences) and requires a registered IRecurringScheduleRepository (via AddRelayRecurringSchedulingEfCore<TContext>).

Nuvora.Nexus.Relay.Scheduling.Redelivery

ConsumerRedeliveryDispatcher

public sealed class ConsumerRedeliveryDispatcher : IScheduledMessageDispatcher

Delivers ScheduledDeliveryKind.ConsumerRedelivery messages by deserializing the ConsumerRedeliveryEnvelope, rebuilding the MessageBrokerMessage, and re-publishing it through IMessageBroker — so the message re-enters via the normal broker → consumer → inbox flow (and the inbox deduplicates by event id). Mirrors the command/ saga-timeout/job dispatchers.

Constructors

ConsumerRedeliveryDispatcher(IScheduledMessageSerializer serializer)

Properties

ScheduledDeliveryKind Kind { get; }

The delivery kind this dispatcher handles.

Methods

Task DispatchAsync(ScheduledMessage message, IServiceProvider scope, CancellationToken cancellationToken)

Deliver the message. scope is a fresh per-message DI scope; the ambient tenant (if any) has already been re-established by the processor. Throwing records a delivery failure (retry/backoff/dead-letter); returning normally marks the message executed.

ConsumerRedeliveryEnvelope

public sealed class ConsumerRedeliveryEnvelope

Serializable snapshot of a MessageBrokerMessage staged for scheduled redelivery. Holds exactly the fields needed to faithfully rebuild the message on the delivery side (so the inbox deduplicates the redelivered copy by ConsumerRedeliveryEnvelope.EventId), plus the originating queue name for diagnostics. Mirrors the SagaTimeoutEnvelope pattern.

Properties

DateTimeOffset OccurredAt { get; set; }
Dictionary<string, string> Headers { get; set; }
Guid EventId { get; set; }
Guid MessageId { get; set; }
Guid? CausationId { get; set; }
Guid? CorrelationId { get; set; }
string EventType { get; set; }
string Payload { get; set; }
string QueueName { get; set; }

Queue the message was consumed from (diagnostics; routing is by event type).

Methods

MessageBrokerMessage ToMessage()

Rebuilds a MessageBrokerMessage for re-publication. MessageBrokerMessage.Topic is intentionally left unset so routing falls back to ConsumerRedeliveryEnvelope.EventType (and the broker’s topic prefix), re-landing the message on the same queue exactly as the outbox originally published it — reusing the consumed routing key would double-apply a configured prefix.

static ConsumerRedeliveryEnvelope FromMessage(MessageBrokerMessage message, string queueName)

Captures the redelivery-relevant fields of message.

ConsumerRedeliveryScheduler

public sealed class ConsumerRedeliveryScheduler : IConsumerRedeliveryScheduler

Default IConsumerRedeliveryScheduler: stages a future-dated ScheduledDeliveryKind.ConsumerRedelivery row carrying a serialized ConsumerRedeliveryEnvelope. Runs on its own DI scope (the consumer has no ambient command scope) and commits a unit of work so the row is durable before the caller acks the original delivery — the same own-scope/ambient/transaction shape the scheduler processor uses to deliver. The redelivery dispatcher later rebuilds the message and re-publishes it.

Constructors

ConsumerRedeliveryScheduler(IServiceScopeFactory scopeFactory, IRelayScopeAccessor scopeAccessor, IScheduledMessageSerializer serializer, ILogger<ConsumerRedeliveryScheduler> logger, TimeProvider? timeProvider = null)

Methods

Task ScheduleAsync(MessageBrokerMessage message, string queueName, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))

Durably schedule message for re-publication to queueName’s routing after delay. Implementations stage the row inside their own transaction and commit before the caller acks the original delivery (schedule-commit-then-ack), so a crash in the window only causes an at-least-once duplicate the inbox deduplicates.

RedeliveryServiceCollectionExtensions

public static class RedeliveryServiceCollectionExtensions

Registration helpers for scheduled (second-level) consumer redelivery.

Methods

static IServiceCollection AddRelayConsumerRedelivery(this IServiceCollection services)

Registers scheduled consumer redelivery: the IConsumerRedeliveryScheduler the consumer uses to honor ErrorOutcome.RetryAfter durably, and the dispatcher that re-publishes a due redelivery. Requires the scheduler (AddRelayScheduling plus a repository via AddRelaySchedulerEfCore) and a registered IMessageBroker. Without this registration the consumer keeps its default immediate-republish behavior.

Nuvora.Nexus.Relay.Scheduling.Serialization

IScheduledMessageSerializer

public interface IScheduledMessageSerializer

Serializes scheduled-message payloads and resolves their stable type names back to CLR types on delivery. The default implementation uses System.Text.Json and a version-independent “FullName, AssemblyName” type name; replace it via DI to use a custom registry or format.

Methods

object Deserialize(string typeName, string payload)

Deserialize a payload from its stored type name + JSON. Throws if the type cannot be resolved.

string GetTypeName(object payload)

Stable, persistable type name for a payload instance.

string Serialize(object payload)

Serialize a payload to JSON.

SystemTextJsonScheduledMessageSerializer

public sealed class SystemTextJsonScheduledMessageSerializer : IScheduledMessageSerializer

Default IScheduledMessageSerializer: System.Text.Json with a version-independent “Namespace.Type, AssemblyName” type name. Type resolution is cached and falls back to a scan of loaded assemblies by full name, so a scheduled message survives assembly version bumps (unlike a fully assembly-qualified name).

Methods

object Deserialize(string typeName, string payload)

Deserialize a payload from its stored type name + JSON. Throws if the type cannot be resolved.

string GetTypeName(object payload)

Stable, persistable type name for a payload instance.

string Serialize(object payload)

Serialize a payload to JSON.

Nuvora.Nexus.Relay.Scheduling.Tenancy

IScheduledTenantStamper

public interface IScheduledTenantStamper

Soft-dependency bridge to the tenancy ambient context, so the scheduler can stamp the owning tenant at schedule time and re-establish it at delivery time without a compile-time reference to the tenancy package. The tenancy package registers an implementation; when tenancy is not installed this service is absent and the scheduler treats every message as global.

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id at schedule time, or null when none is resolved.

Methods

IDisposable Enter(Guid? tenantId)

Re-establishes the ambient tenant for the duration of the returned scope (used by the processor before delivering a scheduled message so a tenant-scoped command/timeout runs under its tenant).

NullScheduledTenantStamper

public sealed class NullScheduledTenantStamper : IScheduledTenantStamper

Default no-op IScheduledTenantStamper used when the tenancy package is not installed: every scheduled message is global and no ambient tenant is established on delivery. The tenancy package replaces this registration with a real bridge to its ambient context.

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id at schedule time, or null when none is resolved.

Methods

IDisposable Enter(Guid? tenantId)

Re-establishes the ambient tenant for the duration of the returned scope (used by the processor before delivering a scheduled message so a tenant-scoped command/timeout runs under its tenant).