API reference — Entry point

Nuvora.Nexus.Relay.Core

Core abstractions for Nuvora Nexus Relay

dotnet add package Nuvora.Nexus.Relay.Core

Nuvora.Nexus.Relay.Core

IBaseMessage

public interface IBaseMessage

IMessage

public interface IMessage : IBaseMessage

IMessage<TReply>

public interface IMessage<TReply> : IBaseMessage

IMessageHandler<TMessage, TResponse>

public interface IMessageHandler<TMessage, TResponse> where TMessage : IMessage<TResponse>

Methods

Task<TResponse> Handle(TMessage message, CancellationToken cancellationToken)

IMessageHandler<TMessage>

public interface IMessageHandler<TMessage> where TMessage : IMessage

Methods

Task Handle(TMessage message, CancellationToken cancellationToken)

Nuvora.Nexus.Relay.Core.Application.Commands

ICommand

public interface ICommand : IMessage

ICommand<TResponse>

public interface ICommand<TResponse> : IMessage<TResponse>

ICommandHandler<TCommand, TResponse>

public interface ICommandHandler<TCommand, TResponse> : IMessageHandler<TCommand, TResponse> where TCommand : ICommand<TResponse>

Handler for commands that return a result

Methods

Task<TResponse> Handle(TCommand command, CancellationToken cancellationToken)

ICommandHandler<TCommand>

public interface ICommandHandler<TCommand> : IMessageHandler<TCommand> where TCommand : ICommand

Handler for commands with no return value

Methods

Task Handle(TCommand command, CancellationToken cancellationToken)

ICommandPipelineBehavior<TCommand, TResponse>

public interface ICommandPipelineBehavior<TCommand, TResponse> where TCommand : ICommand<TResponse>

Methods

Task<TResponse> Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task<TResponse>> next)

ICommandPipelineBehavior<TCommand>

public interface ICommandPipelineBehavior<TCommand> where TCommand : ICommand

Methods

Task Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task> next)

ICommandValidator<TCommand, TResponse>

public interface ICommandValidator<TCommand, TResponse> where TCommand : ICommand<TResponse>

Methods

Task<ValidationResult> ValidateAsync(TCommand command, CancellationToken cancellationToken)

ICommandValidator<TCommand>

public interface ICommandValidator<TCommand> where TCommand : ICommand

Methods

Task<ValidationResult> ValidateAsync(TCommand command, CancellationToken cancellationToken)

SkipTransactionAttribute

public sealed class SkipTransactionAttribute : Attribute

Opts a command out of the automatic transactional pipeline (TransactionBehavior). Use it for commands that perform no persistence work (or manage their own transaction), e.g. commands that only call external services. The behavior then passes straight through to the handler and does not require an IUnitOfWork/event store to be registered.

Nuvora.Nexus.Relay.Core.Application.Events

AccessEvent

public abstract record AccessEvent : IAccessEvent, IEquatable<AccessEvent>

Base class for access events

Properties

DateTimeOffset OccurredAt { get; init; }
Guid EventId { get; init; }
Guid? CausationId { get; init; }
Guid? CorrelationId { get; init; }
virtual Guid UserId { get; init; }

The acting user. Defaults to Guid.Empty (unknown) — callers must set it explicitly; fabricating a random id here would silently corrupt audit data.

IAccessEvent

public interface IAccessEvent : IMessage

Marker interface for access events

Properties

DateTimeOffset OccurredAt { get; }
Guid EventId { get; }
Guid UserId { get; }
Guid? CausationId { get; }
Guid? CorrelationId { get; }

IAccessEventHandler<TEvent>

public interface IAccessEventHandler<TEvent> : IMessageHandler<TEvent> where TEvent : IAccessEvent

Handler for access event notifications

IIntegrationEvent

public interface IIntegrationEvent : IMessage

Marker interface for integration events

Properties

DateTimeOffset OccurredAt { get; }
Guid EventId { get; }
Guid? CausationId { get; }
Guid? CorrelationId { get; }

IIntegrationEventHandler<TEvent>

public interface IIntegrationEventHandler<TEvent> : IMessageHandler<TEvent> where TEvent : IIntegrationEvent

Handler for integration event notifications

IntegrationEvent

public abstract record IntegrationEvent : IIntegrationEvent, IEquatable<IntegrationEvent>

Base class for integration events

Properties

DateTimeOffset OccurredAt { get; init; }
Guid EventId { get; init; }
Guid? CausationId { get; init; }
Guid? CorrelationId { get; init; }

Nuvora.Nexus.Relay.Core.Application.Queries

IQuery

public interface IQuery : IMessage

IQuery<TResponse>

public interface IQuery<TResponse> : IMessage<TResponse>

IQueryHandler<TQuery, TResponse>

public interface IQueryHandler<TQuery, TResponse> : IMessageHandler<TQuery, TResponse> where TQuery : IQuery<TResponse>

Handler for queries that return a result

Methods

Task<TResponse> Handle(TQuery query, CancellationToken cancellationToken)

IQueryPipelineBehavior<TQuery, TResponse>

public interface IQueryPipelineBehavior<TQuery, TResponse> where TQuery : IQuery<TResponse>

Methods

Task<TResponse> Handle(TQuery query, CancellationToken cancellationToken, Func<TQuery, CancellationToken, Task<TResponse>> next)

IQueryResult

public interface IQueryResult

IQueryResult<TResponse>

public interface IQueryResult<TResponse>

IQueryValidator<TQuery, TResponse>

public interface IQueryValidator<TQuery, TResponse> where TQuery : IQuery<TResponse>

Methods

Task<ValidationResult> ValidateAsync(TQuery query, CancellationToken cancellationToken)

IQueryValidator<TQuery>

public interface IQueryValidator<TQuery> where TQuery : IQuery

Methods

Task<ValidationResult> ValidateAsync(TQuery query, CancellationToken cancellationToken)

Nuvora.Nexus.Relay.Core.Coordination

DistributedAggregateWriteLock

public sealed class DistributedAggregateWriteLock : IAggregateWriteLock

IAggregateWriteLock over an IDistributedLock, using a transaction-scoped lock on a stable per-aggregate resource key (relay:aggregate:{type}:{id}). The lock therefore rides the command’s unit-of-work transaction and is released when it commits or rolls back, and on the PostgreSQL backend is enforced by a Postgres advisory lock.

Constructors

DistributedAggregateWriteLock(IDistributedLock distributedLock)

Methods

Task AcquireAsync(string aggregateType, Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Blocks until the per-aggregate write lock is held for the current transaction.

Task<bool> TryAcquireAsync(string aggregateType, Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Tries to take the per-aggregate write lock without waiting; false if another writer holds it.

DistributedLockLeaderElector

public sealed class DistributedLockLeaderElector : ILeaderElector

ILeaderElector over a session-scoped IDistributedLock: whoever holds the leader:<role> lock runs the work; others retry acquisition on an interval until they win it or are cancelled. A fault while contending for the lock is logged and retried on the same interval — a transient store error must not end this node’s participation in the election.

Constructors

DistributedLockLeaderElector(IDistributedLock distributedLock, TimeSpan? retryInterval = null, ILogger<DistributedLockLeaderElector>? logger = null)

Methods

Task RunAsync(string role, Func<CancellationToken, Task> onElected, CancellationToken cancellationToken)

Contends for leadership of role and invokes onElected while this instance holds it, re-contending after a back-off when it does not. Runs until cancellationToken is cancelled. Leadership is held until this instance releases it (work returns / shutdown) or its process dies (the lock’s connection drops, releasing it server-side). There is no lease renewal, so for strict at-most-one-active semantics across network partitions the elected work should also be idempotent.

IAggregateWriteLock

public interface IAggregateWriteLock

Pessimistic, cluster-wide write lock for a single event-sourced aggregate. Taken on the ambient unit-of-work transaction and released automatically at commit/rollback. Acquire it inside a command (before loading the aggregate for write) to serialize concurrent writers to the same aggregate instance — the alternative to optimistic concurrency’s load → fail → retry loop, useful for hot aggregates where conflicts are frequent. Other aggregates are unaffected (the lock is per aggregate id). Implementations are thread-safe.

Methods

Task AcquireAsync(string aggregateType, Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Blocks until the per-aggregate write lock is held for the current transaction.

Task<bool> TryAcquireAsync(string aggregateType, Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Tries to take the per-aggregate write lock without waiting; false if another writer holds it.

IDistributedLock

public interface IDistributedLock

A cluster-wide mutual-exclusion lock keyed by an arbitrary resource name. Two flavors:

Implementations are thread-safe.

Methods

Task AcquireForCurrentTransactionAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))

Blocks until the transaction-scoped lock is acquired.

Task<IDistributedLockHandle?> TryAcquireAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))

Tries to take the session-scoped lock without waiting. Returns a handle to hold (and dispose to release), or null if another holder owns it.

Task<bool> TryAcquireForCurrentTransactionAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))

Tries to take the transaction-scoped lock without waiting; false if held elsewhere.

IDistributedLockHandle

public interface IDistributedLockHandle : IAsyncDisposable

A held session-scoped distributed lock; dispose to release it (idempotent).

Properties

string Resource { get; }

The resource this lock guards.

IFencedLeaderElector

public interface IFencedLeaderElector

Leader elector backed by a renewable ILeaseStore. Unlike a connection-bound lock, it renews the lease on an interval and surfaces a fencing token, giving proactive failover: an alive-but-stalled leader fails to renew and is taken over, and the new leader’s higher token lets downstream writers fence the old one out.

Methods

Task RunAsync(string role, Func<long, CancellationToken, Task> onLeadership, CancellationToken cancellationToken)

Contends for leadership of role. When elected, invokes onLeadership with the current fencing token and a token that is cancelled when leadership is lost (renewal failed / fenced) or cancellationToken is cancelled. Renews while the work runs and re-contends after losing, until cancellationToken is cancelled.

ILeaderElector

public interface ILeaderElector

Runs work on exactly one instance of a cluster at a time (“the leader”) for a named role — e.g. a singleton recurring job or a process that must not run in parallel. Built on a session-scoped IDistributedLock: the holder of the lock is the leader.

Methods

Task RunAsync(string role, Func<CancellationToken, Task> onElected, CancellationToken cancellationToken)

Contends for leadership of role and invokes onElected while this instance holds it, re-contending after a back-off when it does not. Runs until cancellationToken is cancelled. Leadership is held until this instance releases it (work returns / shutdown) or its process dies (the lock’s connection drops, releasing it server-side). There is no lease renewal, so for strict at-most-one-active semantics across network partitions the elected work should also be idempotent.

ILeaseStore

public interface ILeaseStore

A renewable, time-bounded lease keyed by role, used for leader election and single-active-owner work with proactive failover. Unlike a connection-bound distributed lock (which only releases when the holder’s connection drops), a lease must be renewed before ttl elapses or another node may take it over — which detects an alive-but-stalled holder. Each ownership change increments a LeaseResult.FencingToken so a delayed old holder can be rejected. Implementations are thread-safe.

Methods

Task ReleaseAsync(string role, string ownerId, CancellationToken cancellationToken = default(CancellationToken))

Releases the lease if ownerId holds it (best-effort; expiry covers crashes).

Task<LeaseResult> TryAcquireOrRenewAsync(string role, string ownerId, TimeSpan ttl, CancellationToken cancellationToken = default(CancellationToken))

Acquires the lease for ownerId if it is free or expired, or renews it if ownerId already holds it. Returns LeaseResult.NotAcquired if a different, non-expired owner holds it.

INodeRegistry

public interface INodeRegistry

Tracks the live nodes of a deployment by heartbeat, giving the database-centric coordination plane a membership view (for observability and smarter work rebalancing) without a peer-to-peer gossip protocol. A node calls INodeRegistry.HeartbeatAsync periodically; INodeRegistry.GetLiveNodesAsync returns the nodes whose last heartbeat is within the liveness window. Implementations are thread-safe.

Methods

Task HeartbeatAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))

Records that nodeId is alive as of now.

Task RemoveAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))

Removes nodeId from the registry (e.g. on graceful shutdown).

Task<IReadOnlyList<string>> GetLiveNodesAsync(CancellationToken cancellationToken = default(CancellationToken))

Returns the node ids whose most recent heartbeat is within the liveness window.

IRelayWakeHub

public interface IRelayWakeHub

In-process wake hub: producers (a notification listener, tests, local writes) signal a channel and pollers wait for “a wake or the fallback interval, whichever first”. Wakes are coalescing and lossy-by-design — a missed wake only delays work until the next poll, never loses it — which keeps the polling loop the single source of truth for correctness.

Methods

IDisposable RegisterListener(string channel)

Registers a live listener for the channel; dispose the handle when the listener stops.

Task<bool> WaitAsync(string channel, TimeSpan maxWait, CancellationToken cancellationToken = default(CancellationToken))

Waits until the channel is signaled or maxWait elapses, whichever comes first. Returns true when woken by a signal, false on timeout.

bool HasListener(string channel)

Whether an external notification listener is currently feeding this channel. Pollers use this to relax their fallback interval when wakes are available and keep the tight interval when polling is the only signal.

void Wake(string channel)

Signals the channel, releasing all current waiters (no-op when none are waiting).

InMemoryLeaseStore

public sealed class InMemoryLeaseStore : ILeaseStore

In-process ILeaseStore for single-node use and testing. Thread-safe; the clock is injected (TimeProvider) so expiry is deterministic in tests. This is not a cross-process lease — multi-node leadership needs a durable, shared store (e.g. a PostgreSQL-backed one).

Constructors

InMemoryLeaseStore(TimeProvider? timeProvider = null)

Methods

Task ReleaseAsync(string role, string ownerId, CancellationToken cancellationToken = default(CancellationToken))

Releases the lease if ownerId holds it (best-effort; expiry covers crashes).

Task<LeaseResult> TryAcquireOrRenewAsync(string role, string ownerId, TimeSpan ttl, CancellationToken cancellationToken = default(CancellationToken))

Acquires the lease for ownerId if it is free or expired, or renews it if ownerId already holds it. Returns LeaseResult.NotAcquired if a different, non-expired owner holds it.

InMemoryNodeRegistry

public sealed class InMemoryNodeRegistry : INodeRegistry

In-process INodeRegistry for single-node use and testing. A node is “live” while its last heartbeat is within livenessTtl. Thread-safe; the clock is injected (TimeProvider) so liveness is deterministic in tests. Multi-node membership needs a durable, shared registry (e.g. a PostgreSQL-backed one).

Constructors

InMemoryNodeRegistry(TimeSpan livenessTtl, TimeProvider? timeProvider = null)

Methods

Task HeartbeatAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))

Records that nodeId is alive as of now.

Task RemoveAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))

Removes nodeId from the registry (e.g. on graceful shutdown).

Task<IReadOnlyList<string>> GetLiveNodesAsync(CancellationToken cancellationToken = default(CancellationToken))

Returns the node ids whose most recent heartbeat is within the liveness window.

LeaseLeaderElector

public sealed class LeaseLeaderElector : IFencedLeaderElector

IFencedLeaderElector over an ILeaseStore. While elected it renews the lease every LeaseLeaderOptions.RenewInterval; if a renewal fails, throws or returns a different fencing token (someone else took over), it cancels the leadership token so the work stops, then re-contends. A store fault while merely contending is logged and retried after LeaseLeaderOptions.RetryInterval — a transient error must not end this node’s participation in the election. The clock is injected (TimeProvider) so the delays are testable.

Constructors

LeaseLeaderElector(ILeaseStore leases, LeaseLeaderOptions? options = null, TimeProvider? timeProvider = null, ILogger<LeaseLeaderElector>? logger = null)

Methods

Task RunAsync(string role, Func<long, CancellationToken, Task> onLeadership, CancellationToken cancellationToken)

Contends for leadership of role. When elected, invokes onLeadership with the current fencing token and a token that is cancelled when leadership is lost (renewal failed / fenced) or cancellationToken is cancelled. Renews while the work runs and re-contends after losing, until cancellationToken is cancelled.

LeaseLeaderOptions

public sealed class LeaseLeaderOptions

Tuning for LeaseLeaderElector.

Properties

TimeSpan LeaseTtl { get; set; }

Lease lifetime; leadership lapses this long after the last successful renewal.

TimeSpan RenewInterval { get; set; }

How often the lease is renewed while leading (should be well below LeaseLeaderOptions.LeaseTtl).

TimeSpan RetryInterval { get; set; }

How long to wait before re-contending after failing to acquire or losing leadership.

string OwnerId { get; set; }

Stable identity of this node/instance (defaults to a per-process random id).

LeaseResult

public readonly record struct LeaseResult : IEquatable<LeaseResult>

Outcome of an acquire-or-renew attempt on a ILeaseStore.

Constructors

LeaseResult(bool Acquired, long FencingToken, DateTimeOffset ExpiresAt)

Outcome of an acquire-or-renew attempt on a ILeaseStore.

Properties

DateTimeOffset ExpiresAt { get; init; }

When the lease lapses unless renewed.

bool Acquired { get; init; }

Whether the caller now holds (or still holds) the lease.

long FencingToken { get; init; }

Monotonically increasing token for the current holder. It increases every time the lease changes hands, never on a renewal by the same holder, so a stalled-then-resumed old leader can be fenced out: downstream writers reject any token lower than the highest they have seen.

static LeaseResult NotAcquired { get; }

A failed attempt (the lease is held by someone else and is not yet expired).

RelayNotificationChannels

public static class RelayNotificationChannels

Well-known notification channels connecting the write side to the polling background services. The PostgreSQL implementations NOTIFY these channels transactionally (delivered at commit), and a listener wakes the corresponding pollers, cutting idle latency from a polling interval to near-zero without giving up the polling fallback.

Fields

const string Events = "relay_events"

Signaled when new events are appended to the event store (wakes projections/subscriptions).

const string Outbox = "relay_outbox"

Signaled when new outbox messages are staged (wakes the outbox processor).

const string Scheduler = "relay_scheduler"

Signaled when a scheduled message is staged (wakes the scheduler processor so it re-evaluates its next-due sleep — a newly scheduled message may be due sooner than the current wait).

RelayWakeHub

public sealed class RelayWakeHub : IRelayWakeHub

Default IRelayWakeHub; register as a singleton.

Methods

IDisposable RegisterListener(string channel)

Registers a live listener for the channel; dispose the handle when the listener stops.

Task<bool> WaitAsync(string channel, TimeSpan maxWait, CancellationToken cancellationToken = default(CancellationToken))

Waits until the channel is signaled or maxWait elapses, whichever comes first. Returns true when woken by a signal, false on timeout.

bool HasListener(string channel)

Whether an external notification listener is currently feeding this channel. Pollers use this to relax their fallback interval when wakes are available and keep the tight interval when polling is the only signal.

void Wake(string channel)

Signals the channel, releasing all current waiters (no-op when none are waiting).

Nuvora.Nexus.Relay.Core.Diagnostics

MetricTagAttribute

public sealed class MetricTagAttribute : Attribute

Marks a command/query property as a telemetry dimension: its value is added as a tag to the dispatch counter, the duration histogram, and the trace span (e.g. region, plan_tier, channel). This lets callers segment Relay’s built-in metrics by a business dimension without forking the framework’s instrumentation.

Metric tags are multiplicative cardinality: every distinct value creates a new time series. Only annotate bounded categorical fields — never per-entity identifiers (order id, user id) or other high-cardinality values, which belong on spans/logs, not metric dimensions.

Mirrors the attribute-driven convention used elsewhere in Relay (e.g. CacheableAttribute). On positional records, apply it with the property: target — record GetOrders(Guid TenantId, [property: MetricTag("region")] string Region) : IQuery<...>;

Constructors

MetricTagAttribute(string name)

Properties

string Name { get; }

The tag key emitted on the metric/span (e.g. region). Keep it bounded and stable.

RelayTelemetry

public static class RelayTelemetry

OpenTelemetry-native instrumentation for the framework: a single ActivitySource for distributed traces and a Meter for metrics, emitted across the command → event-append → outbox → broker → projection → inbox flow. Apps light these up by adding RelayTelemetry.SourceName/RelayTelemetry.MeterName to their OpenTelemetry tracer/meter providers (or via the AddRelayInstrumentation helpers in Nuvora.Nexus.Relay.Diagnostics).

Methods

static void RecordEventVisibilityLag(long lag)

Publishes a fresh visibility-lag sample (called by the projection monitoring service).

static void RecordOutboxBacklog(long pending, long deadLettered, TimeSpan? oldestPendingAge)

Publishes a fresh outbox backlog sample (called by the outbox monitoring service).

static void RecordPartitionsOwned(long owned)

Publishes the current owned-partition count (called by the partition coordinator).

static void RecordProjectionMaxLag(long maxLag)

Publishes a fresh projection-lag sample (called by the projection monitoring service).

static void RecordSchedulerBacklog(long due, long deadLettered, TimeSpan? oldestDueAge)

Publishes a fresh scheduler backlog sample (called by the scheduler monitoring service).

Fields

const string MeterName = "Nuvora.Nexus.Relay"
const string SourceName = "Nuvora.Nexus.Relay"
static readonly ActivitySource ActivitySource
static readonly Counter<long> CacheEvictions

Cache entries evicted by explicit invalidation (tagged by query name).

static readonly Counter<long> CacheHits

Query cache hits (tagged by query name).

static readonly Counter<long> CacheMisses

Query cache misses, i.e. executions that fell through to the backend (tagged by query name).

static readonly Counter<long> CacheStampedeWaits

Query executions that waited on the cache stampede stripe lock and then found the value already cached (double-check hit) — i.e. requests whose backend work was coalesced into another in-flight execution (tagged by query name).

static readonly Counter<long> CacheWriteFailures

Cache writes that failed and were swallowed by the caching behavior — the query result was still returned to the caller, but not cached (tagged by query name).

static readonly Counter<long> CircuitBreakerTrips

Circuit breaker trips (closed/half-open → open transitions).

static readonly Counter<long> ClaimCheckOffloads

Messages whose oversized payload was offloaded to the claim-check store before publish.

static readonly Counter<long> ClaimCheckRehydrations

Messages whose payload was rehydrated from the claim-check store before dispatch.

static readonly Counter<long> CommandsExecuted

Command executions (tagged by command name and success).

static readonly Counter<long> ConsumeBackpressure

Deliveries short-circuited by a built-in consume filter applying backpressure (rate limiter, circuit breaker, concurrency limiter or kill switch) before the handler ran — the message was requeued/redelivered later rather than processed now (tagged by filter).

static readonly Counter<long> ConsumeErrorsRouted

Failed deliveries routed by a per-exception IMessageErrorPolicy (tagged by disposition — retry/requeue/dead_letter/ignore — and exception type). Not emitted when no policy matches and the transport’s default handling applies.

static readonly Counter<long> ConsumerChannels

Consumer channels opened when a subscription is (re)established — the configured per-subscription channel fan-out for concurrent processing (tagged by queue).

static readonly Counter<long> ConsumerRedeliveriesScheduled

Scheduled (“second-level”) consumer redeliveries staged — a consumed message whose handler asked to retry after a delay (ErrorOutcome.RetryAfter) was durably re-armed for delayed re-publication instead of being requeued immediately (tagged by event_type). Delivery of the redelivered copy is counted by the scheduler counters under kind=ConsumerRedelivery.

static readonly Counter<long> EventsAppended

Domain events appended to the event store.

static readonly Counter<long> EventsProjected

Events applied by projections.

static readonly Counter<long> InboxDeduplicated

Inbound messages skipped as duplicates by the inbox.

static readonly Counter<long> InboxProcessed

Inbound messages processed by the inbox.

static readonly Counter<long> JobsEnqueued

Durable background jobs enqueued (tagged by job type). Delivery/dead-letter is counted by the scheduler counters under kind=Job.

static readonly Counter<long> LeaderElectionsWon

Leadership acquisitions won by this instance (tagged by role).

static readonly Counter<long> OutboxDeadLettered

Outbox messages dead-lettered after exhausting retries.

static readonly Counter<long> OutboxPublished

Integration events successfully published from the outbox to the broker.

static readonly Counter<long> PartitionRebalances

Partition ownership changes — a partition acquired or released by this node (tagged by group).

static readonly Counter<long> ProjectionRebuildsCompleted

Projection rebuilds completed (caught back up to the head captured at start).

static readonly Counter<long> ProjectionRebuildsStarted

Projection rebuilds started.

static readonly Counter<long> QueriesExecuted

Query executions (tagged by query name and success).

static readonly Counter<long> RateLimitRejections

Operations rejected by a rate limiter because the budget was exhausted.

static readonly Counter<long> RetriesScheduled

Durable retries scheduled — a failed outbox/scheduler row re-armed for a later attempt (its backoff next_attempt_at pushed out) rather than dead-lettered. Tagged by component (outbox/scheduler) and strategy.

static readonly Counter<long> RoutingSlipCompensations

Routing-slip compensations replayed on rollback (tagged by saga type).

static readonly Counter<long> RoutingSlipFaulted

Routing slips rolled back / faulted (tagged by saga type).

static readonly Counter<long> RoutingSlipLegsCompleted

Routing-slip forward legs whose compensation was recorded onto the itinerary (tagged by saga type).

static readonly Counter<long> SagaConcurrencyRetries

Saga reactions that lost the optimistic-concurrency race and were retried (tagged by saga type).

static readonly Counter<long> SagaReactions

Saga reactions applied (tagged by saga type and trigger message type).

static readonly Counter<long> SagaTimeoutsScheduled

Saga timeouts requested (tagged by saga type).

static readonly Counter<long> SagasCompleted

Saga instances completed (tagged by saga type).

static readonly Counter<long> SagasStarted

Saga instances started (tagged by saga type).

static readonly Counter<long> SchedulerDeadLettered

Scheduled messages dead-lettered after exhausting retries (tagged by kind).

static readonly Counter<long> SchedulerDelivered

Scheduled messages delivered (tagged by kind).

static readonly Histogram<double> CommandDuration

Command pipeline duration in milliseconds.

static readonly Histogram<double> QueryDuration

Query pipeline duration in milliseconds.

static readonly ObservableGauge<double> OutboxOldestPendingAge

Age of the oldest pending outbox row in seconds (0 when the outbox is drained).

static readonly ObservableGauge<double> SchedulerOldestDueAge

Age in seconds of the oldest already-due scheduled row (0 when none are overdue).

static readonly ObservableGauge<long> EventVisibilityLag

Committed events not yet visible to catch-up readers (held back by the oldest in-flight write transaction; −1 until first sampled). Persistently non-zero = a stuck transaction is stalling every projection and subscription.

static readonly ObservableGauge<long> OutboxDeadLetteredDepth

Outbox rows dead-lettered and awaiting operator action (−1 until first sampled).

static readonly ObservableGauge<long> OutboxPendingDepth

Outbox rows waiting to be published (−1 until first sampled).

static readonly ObservableGauge<long> PartitionsOwned

Partitions currently owned by this node (−1 until first sampled).

static readonly ObservableGauge<long> ProjectionMaxLag

Maximum projection lag (event-store head position minus checkpoint) across all registered projections (−1 until first sampled).

static readonly ObservableGauge<long> SchedulerDeadLetteredDepth

Scheduled rows dead-lettered and awaiting operator action (−1 until first sampled).

static readonly ObservableGauge<long> SchedulerDueDepth

Scheduled rows already due but not yet delivered (−1 until first sampled).

RelayTelemetryOptions

public sealed class RelayTelemetryOptions

Opt-in knobs for Relay’s command/query telemetry segmentation. Bind with the standard options pattern, e.g. services.Configure<RelayTelemetryOptions>(o => o.TagTenant = true). All flags default to the pre-existing behaviour, so existing dashboards/series are unchanged unless a flag is turned on (or a message carries MetricTagAttribute).

Properties

bool TagTenant { get; set; }

When true, the ambient tenant id (from IRelayTenantAccessor.CurrentTenantId) is added as a tenant tag to the command/query counter, duration histogram, and trace span. Opt-in (default false) because tenant cardinality is multiplicative: enable it only when the tenant set is small/known. For large tenant fleets prefer per-tenant spans (always safe) over per-tenant metrics.

RelayTelemetryTagBuilder

public static class RelayTelemetryTagBuilder

Builds the caller-defined telemetry dimensions for a dispatched command/query: the values of its MetricTagAttribute-marked properties plus, optionally, the ambient tenant. The per-type set of property accessors is reflected once and cached as compiled delegates, so dispatch never pays a reflection cost. The bus calls this to enrich both metrics and the trace span.

Methods

static void AppendDynamicTags(ref TagList tags, object? message, Guid? tenantId)

Appends the message’s MetricTagAttribute dimensions, then the optional tenant tag, to tags (which already carries the bus’s base tags).

static void ApplyToSpan(Activity? activity, object? message, Guid? tenantId)

Mirrors the same dimensions onto the trace span. Spans tolerate higher cardinality than metrics, so this is always applied when a span is recording.

Fields

const string TenantTagKey = "tenant"

The tag key used for the ambient tenant dimension when tenant tagging is enabled.

Nuvora.Nexus.Relay.Core.Domain

AggregateReplayVerifier

public static class AggregateReplayVerifier

Test helper that proves an aggregate’s live state and its event-replayed state agree — the invariant event sourcing depends on. Because AggregateRoot.ApplyEvent (replay) and command methods (live execution) can be written as two separate mutation paths, they can silently diverge; call AggregateReplayVerifier.VerifyReplayEquivalence from unit tests after exercising command methods to catch that divergence at build time instead of in production.

Methods

static void VerifyReplayEquivalence<TAggregate>(TAggregate live, IEnumerable<IDomainEvent>? committedHistory = null)

Rehydrates a fresh TAggregate from live’s committed + uncommitted event history and asserts every public state property (deep-compared via JSON) matches the live instance. committedHistory supplies the already-persisted events when the live instance was loaded rather than newly created; for a brand-new aggregate the uncommitted events alone are replayed.

AggregateRoot<TId>

public abstract class AggregateRoot<TId> : Entity<TId>, IEventSourcedAggregate where TId : notnull

Base class for aggregate roots with domain event support

Constructors

AggregateRoot()
AggregateRoot(TId id)

Properties

Guid AggregateIdValue { get; }

The aggregate identity as a Guid. Event-sourced aggregates must be keyed by Guid; throws a clear error otherwise.

IReadOnlyCollection<IDomainEvent> DomainEvents { get; }

Domain events raised by this aggregate

bool HasDomainEvents { get; }

Check if the aggregate has any pending domain events

int DomainEventCount { get; }

Get the count of pending domain events

long ExpectedVersion { get; }

The version the event store is expected to find already persisted for this aggregate when appending the current uncommitted events (optimistic concurrency check). Equals AggregateRoot.Version: the last committed event version, or -1 for a new stream.

long Version { get; protected set; }

Version of the last committed/applied event for this aggregate (0-based). -1 means the aggregate has no persisted events yet (a brand-new stream).

string AggregateTypeName { get; }

Stable type name used for event-store aggregate_type metadata and stream naming. Resolves AggregateTypeAttribute when present, else the CLR FullName. Prefer the attribute: with the FullName fallback, renaming or moving the class changes the stream name for NEW events while historical rows keep the old one, silently fragmenting the aggregate’s stream (reads by aggregate id are unaffected, but stream/aggregate-type reads are).

virtual bool ApplyEventsOnRaise { get; }

When true, AggregateRoot.RaiseEvent also runs AggregateRoot.ApplyEvent on the freshly raised event, making AggregateRoot.ApplyEvent the single state-mutation path for both live execution and replay (the canonical event-sourcing style, immune to raise/replay divergence). Defaults to false for backward compatibility with aggregates whose command methods mutate state imperatively — for those, enabling this would double-apply. Use AggregateReplayVerifier in tests to prove raise/replay equivalence either way.

Methods

IReadOnlyCollection<IDomainEvent> GetUncommittedChanges()

Get uncommitted changes (events that haven’t been persisted yet)

virtual void ApplyEvent(IDomainEvent domainEvent)

Apply a domain event to the aggregate (override in derived classes)

virtual void LoadFromHistory(IEnumerable<IDomainEvent> events)

Load aggregate from event history (event sourcing)

void ClearDomainEvents()

Clear all domain events (called after persistence)

void MarkChangesAsCommitted()

Mark all changes as committed (called after successful persistence)

void RaiseEvent(IDomainEvent domainEvent)

Raise a domain event, stamping it with the next contiguous per-aggregate version.

void RaiseEvents(IEnumerable<IDomainEvent> domainEvents)

Raise multiple domain events from a collection, each stamped with the next contiguous version.

void RaiseEvents(params IDomainEvent[] domainEvents)

Raise multiple domain events, each stamped with the next contiguous version.

AggregateTypeAttribute

public sealed class AggregateTypeAttribute : Attribute

Declares the stable name stored as the event-store aggregate_type and used in stream names for an aggregate, decoupling persisted identity from the CLR type name. Without it the CLR FullName is used, which means renaming or moving the class fragments the aggregate’s stream: new events get the new stream name while history keeps the old one. Apply this attribute (or keep it when renaming, set to the historical name) to make refactors safe.

Constructors

AggregateTypeAttribute(string name)

Properties

string Name { get; }

The stable, persisted aggregate type name.

DomainEvent

public abstract record DomainEvent : IDomainEvent, IEquatable<DomainEvent>

Base class for domain events

Properties

DateTimeOffset OccurredAt { get; init; }
Guid EventId { get; init; }
Guid? CausationId { get; init; }
Guid? CorrelationId { get; init; }
abstract Guid AggregateId { get; }
long Version { get; init; }

DomainException

public class DomainException : Exception

Exception thrown when domain invariants are violated

Constructors

DomainException(string message)
DomainException(string message, Exception innerException)

Entity<TId>

public abstract class Entity<TId> where TId : notnull

Base class for all entities with strongly-typed ID

Constructors

Entity()
Entity(TId id)

Properties

DateTimeOffset CreatedAt { get; protected set; }
DateTimeOffset UpdatedAt { get; protected set; }
TId Id { get; protected set; }
string? CreatedBy { get; protected set; }
string? UpdatedBy { get; protected set; }

Methods

override bool Equals(object? obj)

Determines whether the specified object is equal to the current object.

override int GetHashCode()

Serves as the default hash function.

void SetCreatedBy(string? createdBy)

Set audit information for entity creation

void SetId(TId id)

Set the ID of the entity (protected for derived classes)

void SetUpdatedBy(string? updatedBy)

Set audit information for entity updates

void SetUpdatedBy(string? updatedBy, DateTimeOffset updatedAt)

Set audit information for entity updates with custom timestamp

Operators

static bool operator !=(Entity<TId>? a, Entity<TId>? b)
static bool operator ==(Entity<TId>? a, Entity<TId>? b)

Guard

public static class Guard

Guard clauses for domain invariant validation. Argument guards (null/empty/whitespace checks) throw ArgumentException-family exceptions; domain-rule guards (ranges, dates, business conditions) throw DomainException.

Methods

static void Against(bool condition, string message)

Guards against custom conditions

static void Against<TException>(bool condition, string message)

Guards against custom conditions with parameterized message

static void AgainstEmptyGuid(Guid value, string parameterName, string? message = null)

Guards against empty GUIDs

static void AgainstFutureDate(DateTime value, string parameterName, string? message = null)

Guards against dates in the future

static void AgainstFutureDate(DateTimeOffset value, string parameterName, string? message = null)

Guards against dates in the future (DateTimeOffset)

static void AgainstInvalidEmail(string? value, string parameterName, string? message = null)

Guards against invalid email addresses

static void AgainstLengthExceeded(string? value, int maxLength, string parameterName, string? message = null)

Guards against strings that exceed maximum length

static void AgainstLengthTooShort(string? value, int minLength, string parameterName, string? message = null)

Guards against strings that are shorter than minimum length

static void AgainstNegative(decimal value, string parameterName, string? message = null)

Guards against negative decimals

static void AgainstNegative(int value, string parameterName, string? message = null)

Guards against negative numbers

static void AgainstNegativeOrZero(decimal value, string parameterName, string? message = null)

Guards against negative or zero decimals

static void AgainstNegativeOrZero(int value, string parameterName, string? message = null)

Guards against negative or zero numbers

static void AgainstNull<T>(T value, string parameterName, string? message = null)

Guards against null values

static void AgainstNullOrEmpty(string? value, string parameterName, string? message = null)

Guards against null or empty strings

static void AgainstNullOrEmptyCollection<T>(IEnumerable<T>? value, string parameterName, string? message = null)

Guards against null or empty collections

static void AgainstNullOrWhiteSpace(string? value, string parameterName, string? message = null)

Guards against null or whitespace strings

static void AgainstOutOfRange<T>(T value, T min, T max, string parameterName, string? message = null)

Guards against values outside a valid range

static void AgainstPastDate(DateTime value, string parameterName, string? message = null)

Guards against dates in the past

static void AgainstPastDate(DateTimeOffset value, string parameterName, string? message = null)

Guards against dates in the past (DateTimeOffset)

IDomainEvent

public interface IDomainEvent : IMessage

Marker interface for domain events

Properties

DateTimeOffset OccurredAt { get; }
Guid AggregateId { get; }
Guid EventId { get; }
Guid? CausationId { get; }
Guid? CorrelationId { get; }
long Version { get; }

IDomainEventHandler<TEvent>

public interface IDomainEventHandler<TEvent> : IMessageHandler<TEvent> where TEvent : IDomainEvent

Handler for domain event notifications

IEventSourcedAggregate

public interface IEventSourcedAggregate

Non-generic projection of an event-sourced aggregate, exposing exactly what the write pipeline (transaction behavior, event-sourced repository) needs to persist and dispatch events without reflecting over the closed AggregateRoot type on every command.

Properties

Guid AggregateIdValue { get; }

The aggregate identity as a Guid. Event-sourced aggregates must be keyed by Guid (the event store, domain-event metadata and stream identifiers are all Guid-based). Throws if the concrete aggregate uses a non-Guid key.

long ExpectedVersion { get; }

The version the event store is expected to already hold for this aggregate when appending the current uncommitted events (optimistic concurrency). -1 for a brand-new stream.

string AggregateTypeName { get; }

Stable type name used for the aggregate_type metadata column.

Methods

IReadOnlyCollection<IDomainEvent> GetUncommittedChanges()

Events raised but not yet persisted.

void MarkChangesAsCommitted()

Advance the committed version and clear uncommitted events after a successful persist.

ValueObject

public abstract class ValueObject

Base class for Value Objects

Methods

abstract IEnumerable<object?> GetEqualityComponents()
override bool Equals(object? obj)

Determines whether the specified object is equal to the current object.

override int GetHashCode()

Serves as the default hash function.

static T Create<T>()

Create a value object with validation

static T Create<T>(Action<T> initialize)

Create a value object with validation and custom initialization

virtual void Validate()

Validate the value object’s invariants Override this method in derived classes to add custom validation

Operators

static bool operator !=(ValueObject? left, ValueObject? right)
static bool operator ==(ValueObject? left, ValueObject? right)

Nuvora.Nexus.Relay.Core.Messaging

RelayMessageHeaders

public static class RelayMessageHeaders

Well-known message-header names propagated across the broker so cross-cutting ambient context survives a publish → broker → consume hop. Kept in Core so producers (outbox/scheduler), the broker transport and consumers (inbox) all agree on the wire name without referencing each other’s packages.

Fields

const string ClaimCheck = "x-relay-claim-check"

Pointer to an offloaded (“claim-check”) payload held in an external store. Present when the message body exceeded the configured threshold and was replaced with a stub; the consumer rehydrates the original payload from the store before dispatch.

const string PartitionKey = "x-relay-partition-key"

Partition key for sticky (ordered, single-owner-per-partition) processing. Messages sharing a key hash to the same partition queue, owned by one node at a time, so they are processed in order. Absent for non-partitioned messages.

const string TenantId = "tenant-id"

The owning tenant id (a Guid string, or absent for a global message). Stamped onto outgoing messages from the ambient tenant and re-established on the consumer before dedup and dispatch so a tenant-scoped reaction runs under its tenant.

Nuvora.Nexus.Relay.Core.Partitioning

ConsistentHashPartitioner

public sealed class ConsistentHashPartitioner : IPartitioner

IPartitioner using consistent hashing: each partition is placed at many points (“virtual nodes”) on a hash ring, and a key maps to the first partition point at or after the key’s hash. Unlike DefaultPartitioner’s hash-modulo — which remaps almost every key when partitionCount changes — resizing a ring only moves the keys in the arcs owned by the added/removed partition (≈1/N of keys), greatly reducing rebalancing churn.

The mapping is stable across processes and restarts (FNV-1a over UTF-8; no randomized hash codes), so every node agrees on ownership. Thread-safe: the ring for a given partition count is built once and cached.

Constructors

ConsistentHashPartitioner(int virtualNodesPerPartition = 100)

Methods

int GetPartition(string partitionKey, int partitionCount)

Returns the partition index in [0, partitionCount) for partitionKey.

Fields

const int DefaultVirtualNodesPerPartition = 100

Default virtual nodes per partition — enough to keep arc sizes (and thus load) even.

DefaultPartitioner

public sealed class DefaultPartitioner : IPartitioner

Default IPartitioner: a stable FNV-1a hash of the key’s UTF-8 bytes, modulo the partition count. Hashing in-process (rather than using String.GetHashCode, which is randomized per run) keeps the mapping identical across processes and restarts, so every node agrees on which partition owns a key.

Methods

int GetPartition(string partitionKey, int partitionCount)

Returns the partition index in [0, partitionCount) for partitionKey.

IPartitioner

public interface IPartitioner

Maps a partition key to one of partitionCount partitions. The mapping must be stable (the same key always maps to the same partition for a given count) so that all messages for a key are processed by the single node that owns that partition, in order. Implementations are thread-safe.

Methods

int GetPartition(string partitionKey, int partitionCount)

Returns the partition index in [0, partitionCount) for partitionKey.

PartitionOptions

public sealed class PartitionOptions

Configuration for sticky (partitioned) processing: a logical PartitionOptions.GroupName and a fixed PartitionOptions.PartitionCount. Each partition has its own queue ({group}.p{n}) owned by a single node at a time (via a distributed lock), so messages for a partition key are processed in order with failover when the owner dies.

Properties

bool UseConsistentHashing { get; set; }

When true, use a ConsistentHashPartitioner instead of the default hash-modulo DefaultPartitioner. Consistent hashing remaps only ≈1/N of keys when PartitionOptions.PartitionCount changes (vs. nearly all keys with modulo), cutting rebalancing churn when the topology is resized. Defaults to false to preserve existing key→partition mappings. Ignored if an IPartitioner is already registered.

int PartitionCount { get; set; }

Number of partitions. Fixed for the life of the group (changing it reshuffles key ownership).

int VirtualNodesPerPartition { get; set; }

Virtual nodes per partition for PartitionOptions.UseConsistentHashing (more = more even load).

string GroupName { get; set; }

Logical name of the partition group (used for the queues, routing keys and ownership locks).

Nuvora.Nexus.Relay.Core.Resiliency

CircuitBreaker

public sealed class CircuitBreaker : ICircuitBreaker

In-memory ICircuitBreaker with a rolling-window trip rule and a half-open probe. Closed → Open when the window breaches CircuitBreakerOptions.FailureThreshold or CircuitBreakerOptions.FailureRatio; Open → HalfOpen after CircuitBreakerOptions.BreakDuration; the half-open probe closes the circuit on success or re-opens it on failure. A probe that ends without an outcome should release its slot via CircuitBreaker.AbandonProbe; as a backstop, a probe older than CircuitBreakerOptions.BreakDuration is presumed abandoned and a new probe is allowed, so a caller that never reports back cannot wedge the circuit in a probe-forever-in-flight state. The clock is injected (TimeProvider) so the transitions are deterministically testable.

Constructors

CircuitBreaker(CircuitBreakerOptions options, TimeProvider? timeProvider = null)

Properties

CircuitState State { get; }

Current state (evaluated against the clock, so an expired open circuit reads as half-open).

Methods

bool TryEnter()

Returns true if the call may proceed (closed, or the single allowed half-open probe); false if the circuit is open and the call should be short-circuited.

void AbandonProbe()

Reports that a call admitted by ICircuitBreaker.TryEnter ended without a success/failure verdict (e.g. it was shed as backpressure before reaching the downstream). Releases the half-open probe slot without deciding the circuit’s fate, so an abandoned probe cannot wedge the circuit. Default no-op for implementations that admit more than one half-open call.

void RecordFailure()

Reports a failed call. A failure while half-open re-opens the circuit; otherwise it may trip a closed circuit.

void RecordSuccess()

Reports a successful call. A success while half-open closes the circuit.

CircuitBreakerOptions

public sealed class CircuitBreakerOptions

Tuning for CircuitBreaker. The breaker trips when, within CircuitBreakerOptions.SamplingWindow, either the absolute failure count reaches CircuitBreakerOptions.FailureThreshold or — once at least CircuitBreakerOptions.MinimumThroughput outcomes have been observed — the failure ratio reaches CircuitBreakerOptions.FailureRatio.

Properties

TimeSpan BreakDuration { get; set; }

How long the circuit stays open before allowing a half-open probe.

TimeSpan SamplingWindow { get; set; }

Rolling window over which outcomes are counted.

double FailureRatio { get; set; }

Failure ratio in (0,1] that trips the circuit once CircuitBreakerOptions.MinimumThroughput is met. Set ≤ 0 to disable the ratio rule.

int FailureThreshold { get; set; }

Absolute number of failures within the window that trips the circuit. Set ≤ 0 to disable the count rule.

int MinimumThroughput { get; set; }

Minimum number of outcomes in the window before the CircuitBreakerOptions.FailureRatio rule applies.

CircuitState

public enum CircuitState

State of an ICircuitBreaker.

Values

  • Closed — Calls flow normally; failures are counted toward tripping.
  • Open — Tripped: calls are short-circuited until the break duration elapses.
  • HalfOpen — Probing recovery: a single trial call is allowed to decide whether to close or re-open.

ConcurrencyLimiter

public sealed class ConcurrencyLimiter : IConcurrencyLimiter

IConcurrencyLimiter backed by a SemaphoreSlim. Each acquired lease takes a permit and releases it exactly once on dispose (double-dispose is a no-op, so it can’t over-release).

Constructors

ConcurrencyLimiter(int maxConcurrency)

Properties

int InUse { get; }

Leases currently held (live concurrency).

int MaxConcurrency { get; }

Maximum number of leases that can be held at once.

Methods

Task<IConcurrencyLease> AcquireAsync(CancellationToken cancellationToken = default(CancellationToken))

Waits until a lease is available, then acquires it.

Task<IConcurrencyLease?> TryAcquireAsync(CancellationToken cancellationToken = default(CancellationToken))

Acquires a lease without waiting; returns null if the limit is already reached.

ConfigurableRetryPolicy

public sealed class ConfigurableRetryPolicy : IRetryPolicy

The built-in IRetryPolicy: Immediate / Interval / Exponential / Incremental backoff driven by RetryPolicyOptions. Inputs are sanitized at construction so a misconfigured (non-finite or negative) option can never produce a non-finite delay or throw out of TimeSpan.FromSeconds.

Constructors

ConfigurableRetryPolicy(RetryPolicyOptions options)

Methods

RetryDecision Evaluate(int attemptNumber, int maxAttempts, RetryContext context)

Evaluates attempt attemptNumber (1-based: 1 is the first retry after the initial failure) against maxAttempts (0 or negative means unbounded).

double[] BuildDelaySchedule(int count)

Materializes the deterministic (jitter-free) delay schedule, in seconds, for attempts 1..count. Drives the SQL-side outbox/scheduler backoff via an indexed Postgres array so the whole schedule is computed once and the database simply indexes it by the live retry count.

ICircuitBreaker

public interface ICircuitBreaker

A circuit breaker: short-circuits calls to a failing dependency so it can recover, instead of piling on requests that will fail. Usage: call ICircuitBreaker.TryEnter before the work; if it returns false the circuit is open — skip the call (or shed load). After the work, report the outcome with ICircuitBreaker.RecordSuccess or ICircuitBreaker.RecordFailure. Implementations are thread-safe.

Properties

CircuitState State { get; }

Current state (evaluated against the clock, so an expired open circuit reads as half-open).

Methods

bool TryEnter()

Returns true if the call may proceed (closed, or the single allowed half-open probe); false if the circuit is open and the call should be short-circuited.

void AbandonProbe()

Reports that a call admitted by ICircuitBreaker.TryEnter ended without a success/failure verdict (e.g. it was shed as backpressure before reaching the downstream). Releases the half-open probe slot without deciding the circuit’s fate, so an abandoned probe cannot wedge the circuit. Default no-op for implementations that admit more than one half-open call.

void RecordFailure()

Reports a failed call. A failure while half-open re-opens the circuit; otherwise it may trip a closed circuit.

void RecordSuccess()

Reports a successful call. A success while half-open closes the circuit.

IConcurrencyLease

public interface IConcurrencyLease : IDisposable

A held concurrency permit; dispose to release it (idempotent).

IConcurrencyLimiter

public interface IConcurrencyLimiter

Caps the number of operations running concurrently. Acquire a lease before the work and dispose it after; the lease count is the live concurrency. Protects a downstream that must not be overwhelmed even when the transport could deliver faster. Implementations are thread-safe.

Properties

int InUse { get; }

Leases currently held (live concurrency).

int MaxConcurrency { get; }

Maximum number of leases that can be held at once.

Methods

Task<IConcurrencyLease> AcquireAsync(CancellationToken cancellationToken = default(CancellationToken))

Waits until a lease is available, then acquires it.

Task<IConcurrencyLease?> TryAcquireAsync(CancellationToken cancellationToken = default(CancellationToken))

Acquires a lease without waiting; returns null if the limit is already reached.

IKeyedConcurrencyLimiter

public interface IKeyedConcurrencyLimiter

A bulkhead: caps concurrency per key rather than globally, so saturation of one key (e.g. a partition, consumer, or tenant) cannot starve the others. Each key has its own independent pool of IKeyedConcurrencyLimiter.MaxConcurrencyPerKey permits. Acquire a lease before the work and dispose it after. Keys are expected to be bounded (their gates are cached for the limiter’s lifetime). Implementations are thread-safe.

Properties

int MaxConcurrencyPerKey { get; }

Maximum leases that can be held at once for any single key.

Methods

Task<IConcurrencyLease> AcquireAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Waits until a lease is available for key, then acquires it.

Task<IConcurrencyLease?> TryAcquireAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Acquires a lease for key without waiting; returns null if that key’s limit is reached.

int InUse(string key)

Leases currently held for key (0 if the key has never been used).

IRateLimiter

public interface IRateLimiter

Throttles the rate of operations. Call IRateLimiter.TryAcquire before the work; false means the rate budget is exhausted and the caller should shed/defer. Implementations are thread-safe.

Methods

bool TryAcquire(int permits = 1)

Tries to take permits from the budget without waiting. Returns true if granted (or if rate limiting is disabled); false if the budget is currently exhausted.

IRetryPolicy

public interface IRetryPolicy

Decides whether a failed operation should be retried and how long to wait before the next attempt. Relay resolves an IRetryPolicy for the durable outbox and scheduler backoff when the application registers one in DI; when none is registered each component builds a ConfigurableRetryPolicy from its own options, so behavior is unchanged out of the box. Implementations must be thread-safe and free of observable side effects.

Methods

RetryDecision Evaluate(int attemptNumber, int maxAttempts, RetryContext context)

Evaluates attempt attemptNumber (1-based: 1 is the first retry after the initial failure) against maxAttempts (0 or negative means unbounded).

ITimeoutPolicy

public interface ITimeoutPolicy

Bounds the duration of an asynchronous operation. The operation is run under a linked CancellationToken that is cancelled once ITimeoutPolicy.Timeout elapses; if the operation has not completed by then it is signalled to cancel and a TimeoutRejectedException is thrown. This is a cooperative (optimistic) timeout — it bounds work that honours its cancellation token. Implementations are thread-safe and reusable.

Properties

TimeSpan Timeout { get; }

The maximum time each execution is allowed before it is cancelled.

Methods

Task ExecuteAsync(Func<CancellationToken, Task> operation, CancellationToken cancellationToken = default(CancellationToken))

Runs operation bounded by ITimeoutPolicy.Timeout.

Task<TResult> ExecuteAsync<TResult>(Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default(CancellationToken))

Runs operation bounded by ITimeoutPolicy.Timeout and returns its result. The token passed to operation is cancelled when either the timeout elapses or cancellationToken is cancelled.

KeyedConcurrencyLimiter

public sealed class KeyedConcurrencyLimiter : IKeyedConcurrencyLimiter

IKeyedConcurrencyLimiter backed by one SemaphoreSlim per key. Each key’s gate is created on first use and cached; a lease takes a permit on its key’s gate and releases it exactly once on dispose (double-dispose is a no-op). Because gates are cached for the lifetime of the limiter, use it with a bounded key space (partitions, consumers, tenants) rather than unbounded keys.

Constructors

KeyedConcurrencyLimiter(int maxConcurrencyPerKey)

Properties

int MaxConcurrencyPerKey { get; }

Maximum leases that can be held at once for any single key.

Methods

Task<IConcurrencyLease> AcquireAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Waits until a lease is available for key, then acquires it.

Task<IConcurrencyLease?> TryAcquireAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Acquires a lease for key without waiting; returns null if that key’s limit is reached.

int InUse(string key)

Leases currently held for key (0 if the key has never been used).

RateLimiterOptions

public sealed class RateLimiterOptions

Tuning for TokenBucketRateLimiter. Tokens refill continuously at RateLimiterOptions.PermitsPerWindow per RateLimiterOptions.Window, up to RateLimiterOptions.BurstCapacity.

Properties

TimeSpan Window { get; set; }

The refill window.

int PermitsPerWindow { get; set; }

Permits replenished per RateLimiterOptions.Window. 0 (the default) disables rate limiting — every acquire is granted.

int? BurstCapacity { get; set; }

Maximum tokens that can accumulate (the burst allowance). Defaults to RateLimiterOptions.PermitsPerWindow when unset.

RetryContext

public readonly record struct RetryContext : IEquatable<RetryContext>

Ambient information available to an IRetryPolicy when it decides whether and how long to wait before the next attempt. The built-in ConfigurableRetryPolicy derives its delay purely from the attempt number; richer custom policies can branch on the last error.

Constructors

RetryContext(int AttemptNumber, Exception? LastError, DateTimeOffset NowUtc)

Ambient information available to an IRetryPolicy when it decides whether and how long to wait before the next attempt. The built-in ConfigurableRetryPolicy derives its delay purely from the attempt number; richer custom policies can branch on the last error.

Properties

DateTimeOffset NowUtc { get; init; }
Exception? LastError { get; init; }
int AttemptNumber { get; init; }

Methods

static RetryContext ForAttempt(int attemptNumber, Exception? lastError = null)

A context for attemptNumber with the current UTC clock.

RetryDecision

public readonly record struct RetryDecision : IEquatable<RetryDecision>

Outcome of an IRetryPolicy evaluation: whether to retry and, if so, how long to wait.

Constructors

RetryDecision(bool ShouldRetry, TimeSpan Delay)

Outcome of an IRetryPolicy evaluation: whether to retry and, if so, how long to wait.

Properties

TimeSpan Delay { get; init; }
bool ShouldRetry { get; init; }

Methods

static RetryDecision After(TimeSpan delay)

Retry after delay (clamped to non-negative).

Fields

static readonly RetryDecision Stop

Do not retry — the caller should fail / dead-letter.

RetryPolicyExtensions

public static class RetryPolicyExtensions

Helpers for driving SQL-side backoff from an IRetryPolicy.

Methods

static double[] BuildDelaySchedule(this IRetryPolicy policy, int count, int maxAttempts)

Builds the per-attempt delay schedule (seconds, for 1-based attempts 1..count) so the durable outbox/scheduler UPDATE can keep the retry-vs-dead-letter decision in SQL (on the live retry_count) while sourcing the delay shape from the policy: the SQL indexes the returned array by retry_count + 1. The built-in ConfigurableRetryPolicy contributes its deterministic schedule (no jitter, so a whole claimed batch is not given an identical random offset); any other policy is sampled via IRetryPolicy.Evaluate. A non-retry decision contributes 0s; that slot is never reached because SQL dead-letters the row at that attempt.

RetryPolicyOptions

public sealed class RetryPolicyOptions

Parameters for ConfigurableRetryPolicy. The defaults reproduce the framework’s historical behavior: exponential backoff (2s, 4s, 8s, …) capped at 300s, no jitter.

Properties

RetryStrategy Strategy { get; set; }

Backoff shape. Default RetryStrategy.Exponential.

double BaseDelaySeconds { get; set; }

Base wait in seconds: the wait for the first retry and the multiplicand for exponential growth.

double IncrementSeconds { get; set; }

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

double JitterFraction { get; set; }

Fractional jitter in [0,1] applied as a symmetric multiplier (delay × (1 ± fraction·rand)); 0 disables it. Jitter is applied only to in-process waits via IRetryPolicy.Evaluate; the SQL-driven outbox and scheduler backoff use the deterministic schedule, so a whole claimed batch is never given an identical random offset.

double MaxDelaySeconds { get; set; }

Upper bound (seconds) the computed delay is capped at.

RetryStrategy

public enum RetryStrategy

Shape of the delay between retry attempts produced by an IRetryPolicy.

Values

  • Immediate — No wait — retry immediately (delay is always TimeSpan.Zero).
  • Interval — Constant wait of BaseDelaySeconds before every attempt.
  • Exponential — Exponential backoff: BaseDelaySeconds * 2^(attempt-1), capped at MaxDelaySeconds. The default; reproduces the framework’s historical outbox/scheduler backoff.
  • Incremental — Linear backoff: BaseDelaySeconds + IncrementSeconds * (attempt-1), capped at MaxDelaySeconds.

TimeoutPolicy

public sealed class TimeoutPolicy : ITimeoutPolicy

ITimeoutPolicy implemented with a linked CancellationTokenSource whose CancellationTokenSource.CancelAfter fires the timeout. A timeout is surfaced as TimeoutRejectedException; cancellation originating from the caller’s token is surfaced as OperationCanceledException. Stateless and safe to share as a singleton.

Constructors

TimeoutPolicy(TimeSpan timeout)

Properties

TimeSpan Timeout { get; }

The maximum time each execution is allowed before it is cancelled.

Methods

Task ExecuteAsync(Func<CancellationToken, Task> operation, CancellationToken cancellationToken = default(CancellationToken))

Runs operation bounded by ITimeoutPolicy.Timeout.

Task<TResult> ExecuteAsync<TResult>(Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default(CancellationToken))

Runs operation bounded by ITimeoutPolicy.Timeout and returns its result. The token passed to operation is cancelled when either the timeout elapses or cancellationToken is cancelled.

TimeoutRejectedException

public sealed class TimeoutRejectedException : Exception

Thrown by ITimeoutPolicy when an operation does not complete within its allotted TimeoutRejectedException.Timeout. Distinct from OperationCanceledException (which signals that the caller’s token was cancelled) so callers can tell a timeout apart from a normal cancellation.

Constructors

TimeoutRejectedException(TimeSpan timeout)

Properties

TimeSpan Timeout { get; }

The timeout that was exceeded.

TokenBucketRateLimiter

public sealed class TokenBucketRateLimiter : IRateLimiter

In-memory token-bucket IRateLimiter. Tokens accrue continuously based on elapsed time (no background timer) and are capped at the burst capacity. The clock is injected via TimeProvider so refill is deterministically testable. Disabled (always grants) when RateLimiterOptions.PermitsPerWindow is not positive.

Constructors

TokenBucketRateLimiter(RateLimiterOptions options, TimeProvider? timeProvider = null)

Methods

bool TryAcquire(int permits = 1)

Tries to take permits from the budget without waiting. Returns true if granted (or if rate limiting is disabled); false if the budget is currently exhausted.

Nuvora.Nexus.Relay.Core.Security

CryptoShredder

public sealed class CryptoShredder : ICryptoShredder

AES-GCM ICryptoShredder over an ICryptoKeyStore. Each value is packed as nonce | tag | ciphertext and Base64-encoded; decryption is authenticated (tampering throws).

Constructors

CryptoShredder(ICryptoKeyStore keyStore)

Methods

Task<string> EncryptAsync(string subjectId, string plaintext, CancellationToken cancellationToken = default(CancellationToken))

Encrypts plaintext under subjectId’s key (created if needed).

Task<string?> TryDecryptAsync(string subjectId, string ciphertext, CancellationToken cancellationToken = default(CancellationToken))

Decrypts a value produced by ICryptoShredder.EncryptAsync, or returns null if the subject’s key has been shredded (erased).

ICryptoKeyStore

public interface ICryptoKeyStore

Stores a per-subject encryption key for crypto-shredding: GDPR “right to erasure” for an append-only event store. Instead of rewriting immutable events, PII is encrypted under a key bound to the data subject; destroying that key (ICryptoKeyStore.ShredAsync) renders every event encrypted under it permanently unreadable, satisfying erasure while leaving the event stream intact. Implementations are thread-safe.

Methods

Task ShredAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Destroys the subject’s key (erasure). Data encrypted under it becomes undecryptable.

Task<byte[]> GetOrCreateKeyAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Returns the subject’s key, creating a fresh random one on first use.

Task<byte[]?> FindKeyAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Returns the subject’s key, or null if it was never created or has been shredded.

ICryptoShredder

public interface ICryptoShredder

Encrypts and decrypts payloads under a data subject’s key for crypto-shredding. Once the subject’s key is shredded (ICryptoKeyStore.ShredAsync), ICryptoShredder.TryDecryptAsync returns null — the data is irrecoverable, which is how erasure is achieved over an append-only store.

Methods

Task<string> EncryptAsync(string subjectId, string plaintext, CancellationToken cancellationToken = default(CancellationToken))

Encrypts plaintext under subjectId’s key (created if needed).

Task<string?> TryDecryptAsync(string subjectId, string ciphertext, CancellationToken cancellationToken = default(CancellationToken))

Decrypts a value produced by ICryptoShredder.EncryptAsync, or returns null if the subject’s key has been shredded (erased).

InMemoryCryptoKeyStore

public sealed class InMemoryCryptoKeyStore : ICryptoKeyStore

In-process ICryptoKeyStore for single-node use and testing (AES-256 keys). A durable, shared key store is needed for multi-node erasure.

Methods

Task ShredAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Destroys the subject’s key (erasure). Data encrypted under it becomes undecryptable.

Task<byte[]> GetOrCreateKeyAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Returns the subject’s key, creating a fresh random one on first use.

Task<byte[]?> FindKeyAsync(string subjectId, CancellationToken cancellationToken = default(CancellationToken))

Returns the subject’s key, or null if it was never created or has been shredded.

Nuvora.Nexus.Relay.Core.Tenancy

IRelayTenantAccessor

public interface IRelayTenantAccessor

Soft-dependency read of (and scoped entry into) the ambient tenant, so framework internals that live below the tenancy package — the integration-event bus (stamps the outbox) and the inbox processor (re-establishes the tenant before dedup/dispatch) — can be tenant-aware without a compile edge to Relay.Tenancy. The tenancy package replaces the default; absent tenancy everything is global.

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id, or null when none is in scope (global).

Methods

IDisposable EnterTenant(Guid? tenantId)

Re-establishes tenantId as the ambient tenant for the lifetime of the returned scope (restoring the prior tenant on dispose). Used by the inbox to run a delivered message under its owning tenant.

NullRelayTenantAccessor

public sealed class NullRelayTenantAccessor : IRelayTenantAccessor

Default no-op accessor: everything is global and no tenant is established.

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id, or null when none is in scope (global).

Methods

IDisposable EnterTenant(Guid? tenantId)

Re-establishes tenantId as the ambient tenant for the lifetime of the returned scope (restoring the prior tenant on dispose). Used by the inbox to run a delivered message under its owning tenant.

Nuvora.Nexus.Relay.UnitOfWork

IUnitOfWork

public interface IUnitOfWork

Unit of Work pattern for managing database transactions

Properties

bool HasActiveTransaction { get; }

Check if a transaction is active

Methods

IEnumerable<object> GetTrackedAggregates()

Get all tracked aggregates

Task BeginTransactionAsync(CancellationToken cancellationToken = default(CancellationToken))

Begin a new transaction

Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken))

Commit the current transaction and save changes

Task RollbackAsync(CancellationToken cancellationToken = default(CancellationToken))

Rollback the current transaction

Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))

Save changes without committing transaction

void TrackAggregate<TId>(AggregateRoot<TId> aggregate)

Track an aggregate for event persistence and dispatch