API reference — Event store

Nuvora.Nexus.Relay.EventStore.EfCore

EF Core (PostgreSQL) event store and snapshot store for Nuvora Nexus Relay

dotnet add package Nuvora.Nexus.Relay.EventStore.EfCore

Nuvora.Nexus.Relay.EventStore.EfCore

ArchivedEventRecord

public class ArchivedEventRecord

Persistence row for an archived event in relay_events_archive. Mirrors EventRecord but the original global_position is preserved verbatim (not database-generated), so archived events keep their global ordering.

Properties

DateTimeOffset OccurredAt { get; set; }
Guid AggregateId { get; set; }
Guid EventId { get; set; }
Guid? TenantId { get; set; }
long GlobalPosition { get; set; }
long TxId { get; set; }
long Version { get; set; }
string AggregateType { get; set; }
string EventType { get; set; }
string Payload { get; set; }
string StreamName { get; set; }
string? Metadata { get; set; }

EfCoreEventArchiver<TContext>

public sealed class EfCoreEventArchiver<TContext> : IEventArchiver where TContext : DbContext

Moves a closed stream’s older events out of the hot relay_events table into relay_events_archive (stream compaction). Only valid for streams whose early history is already covered by a snapshot — replay starts after the snapshot, so archiving those events does not affect loading; the archiver verifies that coverage inside the archive transaction and refuses to truncate an uncovered stream (loading such a stream would silently produce wrong state). Runs in one transaction (copy then delete); positions are preserved.

Constructors

EfCoreEventArchiver(IDbContextFactory<TContext> contextFactory)

Methods

Task<int> ArchiveStreamAsync(Guid aggregateId, long upToVersionInclusive, CancellationToken cancellationToken = default(CancellationToken))

Archives events of aggregateId with version ≤ upToVersionInclusive. Returns the number of events moved.

EfCoreEventStore

public sealed class EfCoreEventStore : IEventStore, IEventStoreVisibility

EF Core (PostgreSQL) event store. Appends are staged onto the shared command DbContext (via IRelayDbContextAccessor) and flushed by the unit of work’s commit, so events persist atomically with the aggregate state and the outbox. Optimistic concurrency is enforced by the unique (aggregate_id, version) index; a pre-check against already-committed state surfaces obvious conflicts early, while truly concurrent conflicts are detected as a unique-violation at commit time (translated to ConcurrencyConflictException via PostgresErrorTranslator).

Ordering model (visibility horizon, lock-free appends). global_position is a database identity: values are allocated at INSERT but become visible at COMMIT, and commit order is not allocation order — so a naive high-water-mark reader could advance past a position whose transaction is still in flight and lose that event forever. Instead of serializing appends, every event records its inserting transaction id (tx_id = pg_current_xact_id()) and the catch-up readers (EfCoreEventStore.GetAllEventsAsync and friends) cap each batch at the visibility horizon — the oldest transaction id still running (pg_snapshot_xmin(pg_current_snapshot())). Below the horizon every transaction has either committed (row visible) or aborted (row will never appear), so all remaining gaps are permanent and the high-water-mark checkpoint is safe. Appends therefore run fully concurrently.

Operational note: read visibility lags by at most the duration of the longest in-flight WRITE transaction on the database — a stuck write transaction stalls catch-up readers (projections, subscriptions) until it resolves. EfCoreEventStore.GetVisibilityAsync exposes that lag (committed events above the horizon) and the projection lag monitor publishes/warns on it. Keep command transactions short.

Constructors

EfCoreEventStore(IRelayDbContextAccessor contextAccessor, IOptions<EventStoreOptions>? options = null, IRelayTenantAccessor? tenant = null)

Methods

Task AppendAsync(EventData eventData, long? expectedVersion = null, CancellationToken cancellationToken = default(CancellationToken))

Append a single event to the event store

Task AppendManyAsync(IEnumerable<EventData> events, long? expectedVersion = null, CancellationToken cancellationToken = default(CancellationToken))

Append multiple events to the event store atomically

Task<EventCursor> GetCursorAtAsync(long position, CancellationToken cancellationToken = default(CancellationToken))

Resolves a legacy position-only checkpoint to a conservative resume EventCursor — one that can never skip a committed event, at the cost of possibly re-delivering a few events at or below position (handlers are idempotent by contract, so duplicates are safe; skips are not). Why not the max-position row’s cursor. Resolving to the (tx_id, position) of the newest event at or before position looks natural but is unsafe under the store’s own documented anomaly (EventCursor): a transaction can acquire its id early and commit late, so an event with a lower tx_id and a higher position than that row can exist (or appear later). Under EfCoreEventStore.ReadForwardAsync’s (tx_id, position) ordering such an event sorts before the resolved cursor and would be skipped forever, even though the position checkpoint never covered it. Safe resolution. The checkpoint asserts “everything with position ≤ position has been consumed”; resolution must therefore only guarantee that no event with position > position sorts at or before the cursor. The cursor (txSafe, position) with txSafe = min(min tx_id over rows above the position, visibility horizon − 1) does exactly that: every committed event above the position has tx_id ≥ txSafe (and a greater position when equal), so it sorts after the cursor and is read; every still-in-flight or future transaction has tx_id ≥ horizon > txSafe, so its events sort after the cursor too — read, never skipped. Events at or below the position whose tx_id is ≥ txSafe are re-delivered (bounded overlap around the checkpoint), which is the acceptable duplicate case.

Task<EventCursor> GetReadableHeadCursorAsync(CancellationToken cancellationToken = default(CancellationToken))

The readable head as a EventCursor: the maximum (tx_id, global_position) below the visibility horizon, consistent with the ordering EfCoreEventStore.ReadForwardAsync uses.

Task<EventStoreVisibility> GetVisibilityAsync(CancellationToken cancellationToken = default(CancellationToken))

Reads the current readable/committed head positions.

Task<IReadOnlyList<EventData>> GetAllEventsAsync(long fromPosition = 0, int? maxCount = null, CancellationToken cancellationToken = default(CancellationToken))

Get all events from the global event log

Task<IReadOnlyList<EventData>> GetAllEventsAsync(string aggregateType, long fromPosition = 0, int? maxCount = null, CancellationToken cancellationToken = default(CancellationToken))

Events for aggregates of one type in global order, served by the (aggregate_type, global_position) index.

Task<IReadOnlyList<EventData>> GetEventsAsync(Guid aggregateId, long fromVersion = 0, CancellationToken cancellationToken = default(CancellationToken))

Per-aggregate load: version-ordered, no horizon needed. The caller is rehydrating one aggregate, not advancing a global checkpoint, and per-aggregate versions are contiguous.

Task<IReadOnlyList<EventData>> GetEventsByTypeAsync(string eventType, long fromPosition = 0, int? maxCount = null, CancellationToken cancellationToken = default(CancellationToken))

Get events by event type

Task<IReadOnlyList<EventData>> GetStreamEventsAsync(string streamName, long fromPosition = 0, CancellationToken cancellationToken = default(CancellationToken))

Get all events for a specific stream

Task<IReadOnlyList<EventData>> GetStreamEventsAsync(string streamName, long fromPosition, int? maxCount, CancellationToken cancellationToken = default(CancellationToken))

Get events for a specific stream, bounded to at most maxCount events. Default implementation reads the full stream and truncates client-side; stores should override with a server-side limit (the EF Core store does).

Task<IReadOnlyList<EventData>> ReadForwardAsync(EventCursor from, int? maxCount = null, string? aggregateType = null, string? eventType = null, CancellationToken cancellationToken = default(CancellationToken))

Gap-safe forward read ordered by (tx_id, global_position) and capped at the visibility horizon. Resuming from the last returned event’s EventCursor can never skip a late-committing event: such an event has a transaction id at or above the horizon now, so it is excluded this pass, and once it commits its (strictly greater) transaction id places it after the cursor — it is read, not skipped. This is the query the projection host and subscriptions use; the position-only readers above remain for ad-hoc queries and single-stream rehydration (a single aggregate’s writes are serialized by the version unique index, so its positions are already in commit order).

Task<bool> AggregateExistsAsync(Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Check if an aggregate exists

Task<long> GetAggregateVersionAsync(Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Get the current version of an aggregate

Task<long> GetCurrentPositionAsync(CancellationToken cancellationToken = default(CancellationToken))

The readable head: the highest position SAFE for catch-up readers (capped at the visibility horizon), consistent with what EfCoreEventStore.GetAllEventsAsync returns — so projection lag computed against it never counts events that cannot be read yet.

EfCoreEventStoreSubscription

public sealed class EfCoreEventStoreSubscription : IEventStoreSubscription

Catch-up subscriptions implemented by polling the event store. Each subscription resolves a fresh IEventStore from a new DI scope on every poll, so it never captures the (scoped) command DbContext. Suitable for projections/read-model rebuilds. Errors are logged and retried from the last good position with capped exponential backoff.

Constructors

EfCoreEventStoreSubscription(IServiceScopeFactory scopeFactory, TimeSpan? pollingInterval = null, int batchSize = 500, ILogger<EfCoreEventStoreSubscription>? logger = null, TimeSpan? maxBackoff = null)

Methods

Task<IEventSubscription> SubscribeToAllAsync(Func<EventData, CancellationToken, Task> handler, long fromPosition = 0, Func<EventData, bool>? filter = null, CancellationToken cancellationToken = default(CancellationToken))

Subscribe to all events from the global event log

Task<IEventSubscription> SubscribeToEventTypeAsync(string eventType, Func<EventData, CancellationToken, Task> handler, long fromPosition = 0, CancellationToken cancellationToken = default(CancellationToken))

Subscribe to events by type

Task<IEventSubscription> SubscribeToStreamAsync(string streamName, Func<EventData, CancellationToken, Task> handler, long fromPosition = 0, CancellationToken cancellationToken = default(CancellationToken))

Subscribe to events from a specific stream

EfCoreLeaseStore<TContext>

public sealed class EfCoreLeaseStore<TContext> : ILeaseStore where TContext : DbContext

PostgreSQL-backed ILeaseStore. Each operation opens its own connection from the IDbContextFactory, takes a transaction-scoped advisory lock on the role (so concurrent acquirers across nodes are serialized), then does a simple read-modify-write of the relay_leases row and commits — releasing the advisory lock. This keeps the acquire/renew/ takeover logic identical to InMemoryLeaseStore while being correct across processes, without relying on intricate conditional SQL.

Constructors

EfCoreLeaseStore(IDbContextFactory<TContext> contextFactory, 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.

EfCoreNodeRegistry<TContext>

public sealed class EfCoreNodeRegistry<TContext> : INodeRegistry where TContext : DbContext

PostgreSQL-backed INodeRegistry. Heartbeats upsert the node’s last_seen in one atomic statement (INSERT … ON CONFLICT … DO UPDATE); a node is live while its last heartbeat is within the liveness TTL. Each call uses its own connection from the IDbContextFactory. The clock is injected (TimeProvider) for the liveness window.

Constructors

EfCoreNodeRegistry(IDbContextFactory<TContext> contextFactory, 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.

EfCoreSnapshotStore

public sealed class EfCoreSnapshotStore : ISnapshotStore

EF Core (PostgreSQL) snapshot store. Snapshots are an optimization for load: callers must always be able to fall back to a full event replay if no snapshot exists. Saving a snapshot also prunes older rows for the same aggregate beyond SnapshotOptions.KeepSnapshots, staged on the same context so the new snapshot and the deletes commit atomically.

Constructors

EfCoreSnapshotStore(IRelayDbContextAccessor contextAccessor, IOptions<SnapshotOptions>? options = null, IRelayTenantAccessor? tenant = null)

Methods

Task SaveAsync(SnapshotData snapshot, CancellationToken cancellationToken = default(CancellationToken))

Saves a snapshot.

Task<SnapshotData?> GetLatestAsync(Guid aggregateId, CancellationToken cancellationToken = default(CancellationToken))

Gets the most recent snapshot for an aggregate, or null if none exists.

EfCoreSubscriptionStore<TContext>

public sealed class EfCoreSubscriptionStore<TContext> : ISubscriptionStore where TContext : DbContext

PostgreSQL-backed ISubscriptionStore. EfCoreSubscriptionStore.AdvanceAsync serializes per-name via a transaction-scoped advisory lock and only moves the stored cursor forward, so concurrent acks are safe and the position is monotonic. Each call uses its own connection from the IDbContextFactory.

Constructors

EfCoreSubscriptionStore(IDbContextFactory<TContext> contextFactory)

Methods

Task AdvanceAsync(string subscriptionName, EventCursor cursor, CancellationToken cancellationToken = default(CancellationToken))

Acknowledges the named subscription up to cursor. Monotonic: an attempt to move the position backwards (or to the same place) is ignored.

Task<EventCursor> GetPositionAsync(string subscriptionName, CancellationToken cancellationToken = default(CancellationToken))

The last acknowledged cursor for the named subscription, or EventCursor.Start if none.

EfRelayDbContextAccessor<TContext>

public sealed class EfRelayDbContextAccessor<TContext> : IRelayDbContextAccessor where TContext : DbContext

Exposes the host’s scoped TContext to Relay infrastructure so the event store, outbox and snapshots share the command’s DbContext (and therefore its transaction).

Constructors

EfRelayDbContextAccessor(TContext context)

Properties

object DbContext { get; }

The ambient database context for the current scope.

EventStoreOptions

public sealed class EventStoreOptions

Options for the EF Core event store’s polling catch-up subscriptions (EfCoreEventStoreSubscription).

Properties

TimeSpan SubscriptionMaxBackoff { get; set; }

Upper bound for the exponential backoff applied after consecutive subscription poll/handler failures. Defaults to 30 seconds.

TimeSpan SubscriptionPollingInterval { get; set; }

Delay between polls once a subscription has caught up. Defaults to 500ms.

bool EnableWakeNotifications { get; set; }

Whether the store emits transactional pg_notify wake notifications on append (channel relay_events) and runs the LISTEN listener that converts them into in-process wakes for the projection host and outbox processor. Purely a latency/idle-load optimization — polling remains the correctness mechanism. Defaults to true.

int SubscriptionBatchSize { get; set; }

Maximum number of events read per subscription poll. Defaults to 500.

IEventArchiver

public interface IEventArchiver

Moves a closed stream’s older events out of the hot relay_events table into relay_events_archive (stream compaction). Only valid for streams whose early history is already covered by a snapshot — replay starts after the snapshot, so archiving those events does not affect loading; the archiver verifies that coverage inside the archive transaction and refuses to truncate an uncovered stream (loading such a stream would silently produce wrong state). Runs in one transaction (copy then delete); positions are preserved.

Methods

Task<int> ArchiveStreamAsync(Guid aggregateId, long upToVersionInclusive, CancellationToken cancellationToken = default(CancellationToken))

Archives events of aggregateId with version ≤ upToVersionInclusive. Returns the number of events moved.

LeaseRecord

public class LeaseRecord

Persistence row for a renewable, fenced lease (one per role) — see relay_leases.

Properties

DateTimeOffset ExpiresAt { get; set; }

When the lease lapses unless renewed.

long FencingToken { get; set; }

Monotonic fencing token; bumped on every ownership change, unchanged on renewal.

string OwnerId { get; set; }

The current holder’s opaque owner id.

string Role { get; set; }

The role this lease guards (primary key).

NodeRecord

public class NodeRecord

Persistence row for node-membership heartbeats — see relay_nodes.

Properties

DateTimeOffset LastSeen { get; set; }

Timestamp of the node’s most recent heartbeat.

string NodeId { get; set; }

Opaque node id (primary key).

PostgresDistributedLock<TContext>

public sealed class PostgresDistributedLock<TContext> : IDistributedLock where TContext : DbContext

IDistributedLock backed by PostgreSQL advisory locks, generalizing the technique used by the projection coordinator.

Transaction-scoped methods run on the shared scoped DbContext (via IRelayDbContextAccessor) using pg_*_advisory_xact_lock, so the lock rides the unit-of-work transaction and is released at commit/rollback.

The session-scoped PostgresDistributedLock.TryAcquireAsync opens a dedicated connection from the IDbContextFactory and takes a pg_try_advisory_lock on it. Because the connection is opened explicitly, EF leaves it open after the query, so the session lock persists for the handle’s lifetime; it is released by pg_advisory_unlock on dispose, or automatically by the server when the connection drops (e.g. the holding process crashes).

Constructors

PostgresDistributedLock(IRelayDbContextAccessor accessor, IDbContextFactory<TContext> contextFactory)

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.

PostgresErrorTranslator

public static class PostgresErrorTranslator

Translates a PostgreSQL unique-violation on the event-store concurrency constraints — the events aggregate/version index and the snapshots (aggregate_id, version) primary key — into a ConcurrencyConflictException. Because event appends and snapshot saves are staged and flushed by the unit of work’s SaveChanges, a concurrent conflict surfaces there as a DbUpdateException — the host’s unit of work should route commit failures through PostgresErrorTranslator.ThrowIfConcurrencyConflict.

Methods

static bool IsConcurrencyConflict(DbUpdateException exception)

True when the exception is a unique-violation on one of the event-store concurrency constraints.

static void ThrowIfConcurrencyConflict(DbUpdateException exception)

If exception is a unique-violation on one of the event-store concurrency constraints, throws ConcurrencyConflictException; otherwise does nothing.

Fields

const string AggregateVersionConstraint = "uq_relay_events_aggregate_version"

Unique constraint guarding (aggregate_id, version) on relay_events.

const string SnapshotPrimaryKeyConstraint = "relay_snapshots_pkey"

Primary key guarding (aggregate_id, version) on relay_snapshots. Two writers committing the same aggregate version race on this key exactly as they do on the events index (the snapshot store’s pre-check only filters already-committed duplicates), so a violation here is the same optimistic-concurrency conflict and gets the same typed exception. Postgres’ default name for the table’s unnamed PK; the EF model pins the same name.

PostgresWakeListener

public sealed class PostgresWakeListener : BackgroundService

Hosted service holding one dedicated PostgreSQL connection that LISTENs on the relay notification channels (RelayNotificationChannels) and forwards each notification to the in-process IRelayWakeHub. The write side emits pg_notify transactionally (delivered at commit), so the outbox processor and projection host wake within milliseconds of a commit instead of waiting out a polling interval.

Strictly an optimization: notifications are lossy across reconnects, so the pollers keep their interval as a safety net (relaxed while IRelayWakeHub.HasListener is true — listener registrations are dropped during an outage, which automatically tightens polling back up). Connection loss is retried forever with capped exponential backoff.

Constructors

PostgresWakeListener(IServiceScopeFactory scopeFactory, IRelayWakeHub hub, IOptions<EventStoreOptions> options, ILogger<PostgresWakeListener> 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.

SubscriptionRecord

public class SubscriptionRecord

Persistence row for a durable named subscription position — see relay_subscriptions.

Properties

long CheckpointTxId { get; set; }

Inserting-transaction id of the last acknowledged event (gap-safe cursor component).

long Position { get; set; }

Global position of the last acknowledged event.

string Name { get; set; }

Unique subscription name (primary key).

Nuvora.Nexus.Relay.EventStore.EfCore.DependencyInjection

DistributedLockServiceCollectionExtensions

public static class DistributedLockServiceCollectionExtensions

Registration helper for the PostgreSQL advisory-lock IDistributedLock.

Methods

static IServiceCollection AddRelayDistributedLockPostgres<TContext>(this IServiceCollection services)

Registers PostgresDistributedLock as the scoped IDistributedLock. Requires the event-store accessor (AddRelayEventStoreEfCore) for the transaction-scoped locks and an IDbContextFactory for the session-scoped locks’ dedicated connections.

static IServiceCollection AddRelayFencedLeaderElection(this IServiceCollection services, Action<LeaseLeaderOptions>? configure = null)

Registers the lease-backed IFencedLeaderElector (renewal + fencing tokens, proactive failover). Requires an ILeaseStore (e.g. DistributedLockServiceCollectionExtensions.AddRelayLeaseStorePostgres).

static IServiceCollection AddRelayLeaderElection(this IServiceCollection services)

Registers the session-lock-backed ILeaderElector. Requires an IDistributedLock (e.g. via DistributedLockServiceCollectionExtensions.AddRelayDistributedLockPostgres). Resolve and run it within a DI scope (the elected work owns its own lock connection, so it outlives the scope).

static IServiceCollection AddRelayLeaseStorePostgres<TContext>(this IServiceCollection services)

Registers the PostgreSQL-backed ILeaseStore (renewable, fenced leases). Requires an IDbContextFactory and the relay_leases table — call ApplyRelayLeases() in the host context’s OnModelCreating. Used for leader-lease renewal with proactive failover and fencing tokens.

static IServiceCollection AddRelayNodeRegistryPostgres<TContext>(this IServiceCollection services, TimeSpan livenessTtl)

Registers the PostgreSQL-backed INodeRegistry (heartbeat membership). Requires an IDbContextFactory and the relay_nodes table — call ApplyRelayNodes() in the host context’s OnModelCreating. A node is live while its last heartbeat is within livenessTtl.

EventArchiveServiceCollectionExtensions

public static class EventArchiveServiceCollectionExtensions

Registration helper for the PostgreSQL event archiver (stream compaction).

Methods

static IServiceCollection AddRelayEventArchivePostgres<TContext>(this IServiceCollection services)

Registers the PostgreSQL-backed IEventArchiver. Requires an IDbContextFactory and the relay_events_archive table — call ApplyRelayEventArchive() in the host context’s OnModelCreating.

EventStoreServiceCollectionExtensions

public static class EventStoreServiceCollectionExtensions

Registration helpers for the EF Core (PostgreSQL) event store.

Methods

static IServiceCollection AddRelayEventStoreEfCore<TContext>(this IServiceCollection services)

Registers the EF Core event store, snapshot store and serializer, bound to the host’s TContext so they share the command’s transaction. The host context must call ApplyRelayEventStore()/ApplyRelaySnapshots() in OnModelCreating and be registered separately (e.g. via AddDbContext<TContext>).

static IServiceCollection AddRelayEventStoreEfCore<TContext>(this IServiceCollection services, Action<SnapshotOptions> configureSnapshots, Action<EventStoreOptions>? configureEventStore = null)

As EventStoreServiceCollectionExtensions.AddRelayEventStoreEfCore, additionally configuring automatic snapshotting via SnapshotOptions and (optionally) the catch-up subscription’s polling interval/batch size via EventStoreOptions.

SubscriptionStoreServiceCollectionExtensions

public static class SubscriptionStoreServiceCollectionExtensions

Registration helper for the PostgreSQL-backed durable named-subscription store.

Methods

static IServiceCollection AddRelaySubscriptionStorePostgres<TContext>(this IServiceCollection services)

Registers the PostgreSQL-backed ISubscriptionStore (durable named subscription positions). Requires an IDbContextFactory and the relay_subscriptions table — call ApplyRelaySubscriptions() in the host context’s OnModelCreating.

Nuvora.Nexus.Relay.EventStore.EfCore.Entities

EventRecord

public class EventRecord

Persistence row for a single stored event in the relay_events table.

Properties

DateTimeOffset OccurredAt { get; set; }
Guid AggregateId { get; set; }
Guid EventId { get; set; }
Guid? TenantId { get; set; }

Owning tenant (null = global). Used for tenant isolation (RLS / query filters).

long GlobalPosition { get; set; }

Monotonic global ordering position (database identity). Assigned on insert.

long TxId { get; set; }

Epoch-extended id of the INSERTING transaction (pg_current_xact_id(), stored as bigint; xid8 values are monotonic and never wrap within 2^63). Database-assigned. Catch-up readers use it to cap reads at the visibility horizon — the oldest still-running transaction — so a position allocated by an in-flight transaction can never be skipped past by a high-water-mark checkpoint (positions are assigned at insert but become visible at commit, and commit order is not allocation order).

long Version { get; set; }

Contiguous per-aggregate version (0-based).

string AggregateType { get; set; }
string EventType { get; set; }
string Payload { get; set; }

Serialized event body (stored as jsonb).

string StreamName { get; set; }
string? Metadata { get; set; }

Optional serialized metadata (stored as jsonb).

SnapshotRecord

public class SnapshotRecord

Persistence row for an aggregate snapshot in the relay_snapshots table. Primary key is (SnapshotRecord.AggregateId, SnapshotRecord.Version).

Properties

DateTimeOffset CreatedAt { get; set; }
Guid AggregateId { get; set; }
Guid? TenantId { get; set; }

Owning tenant (null = global). Used for tenant isolation (RLS / query filters).

long Version { get; set; }
string AggregateType { get; set; }
string Payload { get; set; }

Serialized aggregate state (stored as jsonb).

Nuvora.Nexus.Relay.EventStore.EfCore.HealthChecks

RelaySchemaHealthCheck

public sealed class RelaySchemaHealthCheck : IHealthCheck

Validates that every relay table mapped on the host context (relay_*: events, snapshots, outbox, inbox, checkpoints, dead letters, failure tallies — whichever the host applied in OnModelCreating) actually exists in the database, via to_regclass. Catches the classic deployment failure — code shipped without its schema migration — at the readiness probe instead of as runtime errors under load. Also serves as the database connectivity check.

Constructors

RelaySchemaHealthCheck(IServiceScopeFactory scopeFactory)

Methods

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

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

RelaySchemaHealthCheckBuilderExtensions

public static class RelaySchemaHealthCheckBuilderExtensions

Health-check registration for the relay storage schema.

Methods

static IHealthChecksBuilder AddRelaySchema(this IHealthChecksBuilder builder, string name = "relay-schema", IEnumerable<string>? tags = null)

Adds the relay schema/connectivity health check (verifies every mapped relay_* table exists). Wire it into the readiness endpoint: services.AddHealthChecks().AddRelaySchema().

Nuvora.Nexus.Relay.EventStore.EfCore.Persistence

EventArchiveModelBuilderExtensions

public static class EventArchiveModelBuilderExtensions

Maps the relay_events_archive table onto the host’s DbContext. Call from OnModelCreating when using AddRelayEventArchivePostgres. The column layout mirrors relay_events so archived rows are a faithful copy.

Methods

static ModelBuilder ApplyRelayEventArchive(this ModelBuilder modelBuilder)

EventStoreModelBuilderExtensions

public static class EventStoreModelBuilderExtensions

Maps the Relay event-store and snapshot tables onto the host’s DbContext. Call these from the host’s OnModelCreating so the tables live in the same database/context as the aggregate state — that is what lets event-append and state-change commit in one transaction.

Methods

static ModelBuilder ApplyRelayEventStore(this ModelBuilder modelBuilder)
static ModelBuilder ApplyRelaySnapshots(this ModelBuilder modelBuilder)

LeaseModelBuilderExtensions

public static class LeaseModelBuilderExtensions

Maps the relay_leases table (renewable fenced leases) onto the host’s DbContext. Call from OnModelCreating when using AddRelayLeaseStorePostgres.

Methods

static ModelBuilder ApplyRelayLeases(this ModelBuilder modelBuilder)

NodeModelBuilderExtensions

public static class NodeModelBuilderExtensions

Maps the relay_nodes membership table onto the host’s DbContext. Call from OnModelCreating when using AddRelayNodeRegistryPostgres.

Methods

static ModelBuilder ApplyRelayNodes(this ModelBuilder modelBuilder)

SubscriptionModelBuilderExtensions

public static class SubscriptionModelBuilderExtensions

Maps the relay_subscriptions table (durable named subscription positions) onto the host’s DbContext. Call from OnModelCreating when using AddRelaySubscriptionStorePostgres.

Methods

static ModelBuilder ApplyRelaySubscriptions(this ModelBuilder modelBuilder)