Table of Contents

Class PostgresOutboxStore

Namespace
Excalibur.Outbox.Postgres
Assembly
Excalibur.Outbox.Postgres.dll

Postgres implementation of the outbox store for message persistence and processing.

[SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Justification = "Store class coordinates the Dapper request set, outbox message mapping, tenant scoping, and leadership-fencing control-table CAS by design (parity with SqlServerOutboxStore).")]
public sealed class PostgresOutboxStore : IOutboxPayloadTransformStore, IClaimScopedOutboxStore, IClaimScopedDeadLetterableOutboxStore, IFencedClaimScopedOutboxStore, IFencedDeadLetterableOutboxStore, IFencedOutboxStore, IOutboxStore, IServiceProvider, IFencedOutboxStoreDiagnostics, IOutboxStoreCapabilities, IOutboxStoreAdmin, IDeadLetterableOutboxStore, IBackoffSchedulableOutboxStore, ITransactionalOutboxWriter, IDisposable, ITenantPartitionedStore
Inheritance
PostgresOutboxStore
Implements
Inherited Members

Remarks

Tenant isolation is enforced on the write/stage path (each message carries and persists its own tenant_id) and on tenant-facing queries; the drain/mark-by-Id path (mark-sent, increment-attempts, backoff, dead-letter, delete) is cross-tenant infrastructure and stays global (it addresses the globally-unique outbox message_id). The store reads no ambient tenant context — fail-closed enforcement is provided by the multi-tenancy composition.

Properties

SupportsSentTracking

Gets a value indicating whether the store retains a successfully-sent message as a countable, cleanup-eligible Sent row.

public bool SupportsSentTracking { get; }

Property Value

bool

true for a tracking store that keeps the sent row (statistics count it and cleanup removes it); false for a delete-on-sent store that removes the row on mark-sent (no sent row to count, cleanup is a no-op).

Remarks

The Postgres outbox deletes a message the instant it is marked sent (MarkSentAsync(string, CancellationToken) issues a DELETE), so there is no terminal sent row to count and cleanup is a no-op.

Methods

CleanupAllTenantsSentMessagesAsync(DateTimeOffset, int, CancellationToken)

Cleans up sent messages using the standard IOutboxStore interface.

public ValueTask<int> CleanupAllTenantsSentMessagesAsync(DateTimeOffset olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

olderThan DateTimeOffset

Timestamp to filter messages older than this time for cleanup.

batchSize int

Maximum number of messages to clean up in one operation.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<int>

Number of messages cleaned up.

DeleteOutboxRecord(string, CancellationToken)

Deletes a specific outbox record by message ID.

public Task<int> DeleteOutboxRecord(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to delete.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Number of records deleted (0 or 1).

DeleteOutboxRecordsBatchAsync(IEnumerable<string>, CancellationToken)

Deletes multiple outbox records in a batch operation.

public Task<int> DeleteOutboxRecordsBatchAsync(IEnumerable<string> messageIds, CancellationToken cancellationToken)

Parameters

messageIds IEnumerable<string>

Collection of message IDs to delete.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Total number of records deleted.

Dispose()

Disposes the outbox store and releases associated resources.

public void Dispose()

EnqueueAsync(IDispatchMessage, IMessageContext, CancellationToken)

Enqueues a dispatch message for outbound delivery using the standard IOutboxStore interface.

[RequiresUnreferencedCode("JSON serialization of message payload and metadata may reference types not preserved during trimming. Ensure all serialized types are annotated with DynamicallyAccessedMembers.")]
[RequiresDynamicCode("JSON serialization of message payload and metadata requires dynamic code generation for reflection-based property access and value conversion.")]
public ValueTask EnqueueAsync(IDispatchMessage message, IMessageContext context, CancellationToken cancellationToken)

Parameters

message IDispatchMessage

Dispatch message to enqueue.

context IMessageContext

Message context with metadata.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask

A task representing the asynchronous operation.

GetAllTenantsFailedMessagesAsync(int, DateTimeOffset?, int, CancellationToken)

Gets failed messages using the standard IOutboxStore interface.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsFailedMessagesAsync(int maxRetries, DateTimeOffset? olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

maxRetries int

Maximum number of retries to filter by.

olderThan DateTimeOffset?

Optional timestamp to filter messages older than this time.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of failed outbound messages.

GetAllTenantsScheduledMessagesAsync(DateTimeOffset, int, CancellationToken)

Gets scheduled messages using the standard IOutboxStore interface.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsScheduledMessagesAsync(DateTimeOffset scheduledBefore, int batchSize, CancellationToken cancellationToken)

Parameters

scheduledBefore DateTimeOffset

Timestamp to filter messages scheduled before this time.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of scheduled outbound messages.

GetAllTenantsStatisticsAsync(CancellationToken)

Gets outbox statistics using actual database queries against the outbox and dead letter tables.

public ValueTask<OutboxStatistics> GetAllTenantsStatisticsAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<OutboxStatistics>

Statistics about the outbox store including message counts and oldest pending age.

GetFencingHighWaterAsync(CancellationToken)

Reads the store's currently recorded fencing high-water mark.

public Task<long?> GetFencingHighWaterAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

Task<long?>

The recorded high-water mark, or null when no fencing token has ever been presented to this store.

GetUnsentMessagesAsync(int, long, CancellationToken)

Claims a batch of unsent messages on behalf of the leadership tenure identified by fencingToken.

public ValueTask<IEnumerable<OutboundMessage>> GetUnsentMessagesAsync(int batchSize, long fencingToken, CancellationToken cancellationToken)

Parameters

batchSize int

Maximum number of messages to retrieve.

fencingToken long

The fencing token for the caller's current leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of unsent messages ready for delivery.

Remarks

The high-water mark is stored once per outbox SCOPE, not per message row. Implementations MUST claim rows only when fencingToken is greater than or equal to the scope's stored mark, and MUST advance that mark to the maximum of its current value and fencingToken within the same atomic action as the claim. A presented token below the mark identifies a superseded tenure: the claim yields zero rows and MUST NOT throw — this is a set-based operation, not an error.

The mark answers which TENURE may act on this scope. It records nothing about an individual row, and a per-row column does not implement this contract. A per-row mark cannot see a tenure that touched a different row in the same scope, so it admits a superseded leader on every row the current leader has not yet reached — which is most rows, on every handover. It would also pass a single-row test, which is why the distinction is stated here rather than left to the reader.

A token identifies a tenure and cannot discriminate two claim cycles of the same tenure, so this mark is necessary and not sufficient on its own: completing a message additionally requires the claim identity the row carries. See the claim-scoped capability for that half.

Exceptions

ArgumentOutOfRangeException

Thrown when batchSize is less than 1.

GetUnsentMessagesAsync(int, CancellationToken)

Gets unsent messages from the outbox using the standard IOutboxStore interface.

public ValueTask<IEnumerable<OutboundMessage>> GetUnsentMessagesAsync(int batchSize, CancellationToken cancellationToken)

Parameters

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of unsent outbound messages.

IncreaseAttempts(string, CancellationToken)

Increments the attempt count for a specific outbox message.

public Task<int> IncreaseAttempts(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to update.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Number of records updated (0 or 1).

IncreaseAttemptsBatchAsync(IEnumerable<string>, CancellationToken)

Increases attempt counts for multiple outbox messages in a batch operation.

public Task<int> IncreaseAttemptsBatchAsync(IEnumerable<string> messageIds, CancellationToken cancellationToken)

Parameters

messageIds IEnumerable<string>

Collection of message IDs to update.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Total number of records updated.

MarkDeadLetteredAsync(string, string, int, OutboxWriteAuthority, CancellationToken)

Dead-letters a message only while the caller holds both accepted tenure and current claim.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

reason string

The reason for the terminal disposition.

attemptCount int

Nonnegative observed logical attempt count; applied writes retain its maximum.

authority OutboxWriteAuthority

The positive tenure and nonblank acquisition identity captured by the worker.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal mutation.

Remarks

Validate arguments before mutation. For valid authority evaluate the fence before row outcomes; absent/different/released claims return ClaimLost, retained terminal rows AlreadyTerminal and absent rows MessageNotFound. Do not reconstruct outcomes from a later unguarded read.

MarkDeadLetteredAsync(string, string, int, long, CancellationToken)

Moves a message to the dead-letter destination, applying it only if the caller's tenure is still current.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, long fencingToken, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to dead-letter.

reason string

The reason recorded against the dead-lettered message.

attemptCount int

Observed logical delivery attempts. Nonnegative; an applied transition atomically records the maximum of this value and the stored count. Missing, terminal, and refused transitions do not change the count.

fencingToken long

The monotonic token identifying the caller's leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the transition.

Remarks

Implementations MUST evaluate the fence and the transition in ONE atomic action. On a store whose terminal idiom destroys the row, the transition is irreversible: there is no later read that can establish whether the caller was entitled to make it, because the evidence is what was deleted. A fence judged in a separate round trip leaves a window in which a successor advances the mark between the check and the delete.

The refusal is REPORTED, never thrown. The drains reach this member from inside their own exception handlers, where a sibling handler on the same block cannot run, so an exception raised here escapes the cycle and abandons every message the caller still holds. ClaimLost is not reachable from this member — it carries no claim term — and an implementation returning it would be reporting a decision it did not make.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentOutOfRangeException

Thrown before mutation when attemptCount is negative.

MarkDeadLetteredAsync(string, string, int, string, CancellationToken)

Dead-letters a message only while the caller holds its current acquisition.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted identifier captured at acquisition.

reason string

The reason for the terminal disposition.

attemptCount int

Nonnegative logical attempt count; applied transitions retain its maximum.

claimIdentity string

The nonblank identity captured from the acquisition, never a process ID.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded transition.

Remarks

Validate arguments before mutation. Missing/released/different leases return ClaimLost, retained terminal rows AlreadyTerminal and absent rows MessageNotFound. Refusals are returned, not thrown. No completion may classify its outcome by rereading after a separate mutation.

MarkDeadLetteredAsync(string, string, int, CancellationToken)

Durably transitions the specified message to the terminal dead-lettered state.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to dead-letter.

reason string

Human-readable reason the message was dead-lettered.

attemptCount int

Absolute observed send count; the archive preserves the greater stored count.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask<OutboxCompletionOutcome>

A value task representing the asynchronous operation.

Remarks

The Postgres outbox uses a separate dead-letter table as its terminal state rather than a status column. This method moves the message into the dead-letter table with the supplied reason as the error message and deletes it from the main outbox table, making it structurally non-claimable by any delivery predicate.

MarkFailedAsync(string, string, int, DateTimeOffset?, OutboxWriteAuthority, CancellationToken)

Records a delivery failure, applying it only if the caller still holds BOTH the tenure and the claim.

public ValueTask<OutboxCompletionOutcome> MarkFailedAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset? nextAttemptAt, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

nextAttemptAt DateTimeOffset?

The time before which the message must NOT be re-claimed, or null to record the failure without a computed backoff schedule.

authority OutboxWriteAuthority

The tenure and claim the caller is acting under.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

ONE member rather than two, because the backoff schedule is a VALUE the caller already has or does not. The unfenced surface splits the plain and scheduled completions across two members; here the caller has already decided which it wants and holds the computed instant, so a second member would differ only in whether one argument was supplied. The nullable schedule is not the omitted-guard shape that the authority deliberately avoids: "there is no backoff schedule" is a real state with a real meaning to the statement, whereas "there is no tenure" cannot arise on a fenced member at all.

Implementations MUST evaluate the fence, the claim and the mutation in ONE atomic action, and MUST decide the returned outcome from that same action. A store that re-reads the row afterwards to classify what happened compares a value captured outside the window it must describe, which is wrong exactly when the refusal is real.

Implementations MUST persist the high-water mark such that it never decreases across process restart, failover or replica promotion. A store whose high-water is only as durable as an asynchronously-replicated value does not satisfy this and MUST NOT implement this interface.

Atomicity is necessary and not sufficient, and the second half is why this clause exists. A fence is two properties: the comparison and the mutation are one indivisible action, AND the mark is monotone non-decreasing under every fault in the deployment's model. A store can satisfy the first perfectly and still be unsafe — if a failover, an eviction or a restore can roll the mark backwards, a superseded tenure presents a token that is no longer below it and is admitted. A monotonic counter that can decrease is not a fence, and a store providing only the atomicity half satisfies the letter of this interface while breaking the guarantee it exists to give.

The refusals are REPORTED, never thrown. The drains report a delivery failure from inside their own exception handlers, where a sibling handler on the same block cannot run, so an exception raised here escapes the whole cycle and abandons every message the caller still legitimately holds. The two refusals also differ in how much work they cost: FenceRefused means a NEWER TENURE exists and the caller must stop draining entirely, while ClaimLost concerns this one message and the caller continues with the rest.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedAsync(string, string, int, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity.

public ValueTask<OutboxCompletionOutcome> MarkFailedAsync(string messageId, string errorMessage, int retryCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

Implementations MUST evaluate the claim and the mutation in ONE atomic action, and MUST decide whether to refuse from that same action. A store that reconstructs the decision from a separate read compares a value captured before the window it must describe, which is false exactly when the refusal is real.

A refusal is REPORTED, not thrown, and the reason is the caller's control flow rather than style. The drain reports a delivery failure from inside its own exception handler; an exception raised there is not caught by a sibling catch on the same try, so it escapes the whole cycle and abandons every message the caller still holds. The refusal must cost one message, so it travels in the return value where the caller reads it without unwinding.

A refusal here is ROW-LEVEL, and the distinction decides how much work is abandoned. A fence refusal means a NEWER TENURE exists and the whole drain cycle must stop, whereas ClaimLost means only that this message was re-claimed — the caller stops writing for THIS message and continues with the others it still holds. A caller that aborts its cycle on a lost claim abandons messages a live tenure owns.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedAsync(string, string, int, CancellationToken)

Marks a message as failed using the standard IOutboxStore interface.

public ValueTask MarkFailedAsync(string messageId, string errorMessage, int retryCount, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to mark as failed.

errorMessage string

Error message describing the failure.

retryCount int

Current retry count for the message.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask

A task representing the asynchronous operation.

Remarks

The base member cannot verify a claim -- it is handed a message id and nothing else -- so it presents this PROCESS identity, which two cycles of one process share. Callers that hold a claim use the IClaimScopedOutboxStore overload; this one remains for callers that never claimed.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity, applying the per-message backoff schedule.

public ValueTask<OutboxCompletionOutcome> MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

nextAttemptAt DateTimeOffset

The time before which the message must NOT be re-claimed.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

This member exists because the backoff route is the one a genuine delivery failure takes when automatic retry is enabled. Scoping only the plain completion would leave the dominant failure path unscoped while the capability appeared to close it. The same atomicity and reported-refusal requirements as MarkFailedAsync(string, string, int, string, CancellationToken) apply here in full.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, CancellationToken)

Marks a message as failed and records an exponential-backoff schedule so it is not re-claimed for retry until nextAttemptAt has elapsed (the Postgres half of the outbox mark-failed-with-backoff path).

public ValueTask MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message that failed.

errorMessage string

Error message describing the failure.

retryCount int

Current retry attempt count.

nextAttemptAt DateTimeOffset

Absolute time before which the message must not be re-claimed.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask

A task representing the asynchronous operation.

MarkSentAsync(string, OutboxWriteAuthority, CancellationToken)

Marks a message sent only while the caller holds the current tenure and claim.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

authority OutboxWriteAuthority

The immutable acquisition evidence captured before delivery.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal transition.

Remarks

Missing or released leases return ClaimLost. Validate nonblank identifiers before mutation. A fenced authority additionally requires a positive tenure; evaluate its fence before row-level outcomes. Retained terminal rows return AlreadyTerminal. Never infer the outcome from a later read.

MarkSentAsync(string, long, CancellationToken)

Marks a message as successfully sent on behalf of the leadership tenure identified by fencingToken.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, long fencingToken, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to mark as sent.

fencingToken long

The fencing token for the caller's current leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

Implementations MUST apply the mutation as a single atomic compare-and-swap: only apply it when fencingToken is greater than or equal to the stored high-water mark, and atomically advance the stored high-water mark to the maximum of its current value and fencingToken. A presented token below the stored high-water mark identifies a superseded leader attempting to complete work it no longer owns, and the store MUST NOT apply the mutation.

A REFUSAL IS REPORTED IN THE RETURN VALUE, NEVER SMUGGLED THROUGH A SUCCESS OR A FAILURE. This member used to return ValueTask, and a void-returning mutation can express exactly two outcomes: it threw, or it did not. This seam needs three — applied, refused, and an infrastructure fault — so refusal had to travel through an exception, and implementations reached independently for four different wrong encodings of it. One reported a refusal as already-sent; one typed it as a generic failure that a catch-all then dead-lettered; one summed rowcounts across a multi-statement batch so the caller's own refusal test could never fire. A refusal indistinguishable from a failure gets disposed of as a failure, and one indistinguishable from a success gets disposed of as a success — and the second marks a message sent that was never sent. Returning the outcome is what makes both unrepresentable rather than merely unlikely.

ROW-SCOPED AND TENURE-SCOPED REFUSALS DIFFER, and the distinction decides how much work the caller abandons. FenceRefused means a NEWER TENURE exists, so every remaining write this caller would make is unfenced and it must stop draining altogether. ClaimLost, AlreadyTerminal and MessageNotFound concern THIS MESSAGE ONLY: the caller records them and carries on with the rest of its batch. A caller that stands down on a row-scoped refusal strands messages a live tenure still owns; one that carries on after a fence refusal lets a superseded tenure keep writing.

Callers MUST test for Applied BY NAME. Deciding success by excluding the refusals known at compile time makes every value added to the enumeration later begin life as a silent success, which is the way this contract fails open.

Infrastructure faults still throw. A refusal is an expected outcome of losing leadership and is not an error; a connection that dropped is.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkSentAsync(string, string, CancellationToken)

Marks a message sent only while the caller holds the current claim.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

claimIdentity string

The immutable acquisition evidence captured before delivery.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal transition.

Remarks

Missing or released leases return ClaimLost. Validate nonblank identifiers before mutation. A fenced authority additionally requires a positive tenure; evaluate its fence before row-level outcomes. Retained terminal rows return AlreadyTerminal. Never infer the outcome from a later read.

MarkSentAsync(string, CancellationToken)

Marks a message as sent using the standard IOutboxStore interface.

public ValueTask MarkSentAsync(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to mark as sent.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask

A task representing the asynchronous operation.

MoveToDeadLetter(string, CancellationToken)

Moves a specific outbox message to the dead letter table.

public Task<int> MoveToDeadLetter(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

Unique identifier of the message to move.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Number of records moved (0 or 1).

MoveToDeadLetterBatchAsync(IEnumerable<string>, CancellationToken)

Moves multiple outbox messages to the dead letter table in a batch operation.

public Task<int> MoveToDeadLetterBatchAsync(IEnumerable<string> messageIds, CancellationToken cancellationToken)

Parameters

messageIds IEnumerable<string>

Collection of message IDs to move.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Total number of records moved.

ReserveOutboxMessagesAsync(string, int, CancellationToken)

Reserves a batch of outbox messages for processing by a specific dispatcher.

public Task<IEnumerable<IOutboxMessage>> ReserveOutboxMessagesAsync(string dispatcherId, int batchSize, CancellationToken cancellationToken)

Parameters

dispatcherId string

Identifier of the dispatcher reserving messages.

batchSize int

Maximum number of messages to reserve.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<IEnumerable<IOutboxMessage>>

Collection of reserved outbox messages.

ResetFencingHighWaterAsync(long, bool, CancellationToken)

Administratively sets the store's fencing high-water mark.

public Task ResetFencingHighWaterAsync(long newHighWater, bool force, CancellationToken cancellationToken)

Parameters

newHighWater long

The high-water mark to record.

force bool

When false (the default an operator should reach for), the store MUST refuse a newHighWater strictly below the currently recorded value and throw InvalidOperationException without changing anything. When true, the store MUST apply newHighWater unconditionally, including a lowering.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous reset operation.

Remarks

Lowering the high-water is unsafe by design. The high-water exists to refuse a superseded leader; lowering it re-admits one — a leader whose token is now below the (lowered) high-water reads as current again and can claim and complete messages a fresher leader already owns. This is the same split-brain the fence exists to prevent, self-inflicted through the recovery surface meant to fix a stuck fence. force exists for the one case where that risk is understood and accepted (recovering a genuinely poisoned fence, with independent confirmation no live claim conflicts with the new value) — never as a routine unstick button.

Exceptions

InvalidOperationException

newHighWater is below the recorded high-water mark and force is false.

SaveMessagesAsync(ICollection<IOutboxMessage>, CancellationToken)

Saves multiple outbox messages to the database.

public Task<int> SaveMessagesAsync(ICollection<IOutboxMessage> outboxMessages, CancellationToken cancellationToken)

Parameters

outboxMessages ICollection<IOutboxMessage>

Collection of outbox messages to save.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<int>

Number of messages successfully saved.

ScheduleMessageAsync(OutboxMessage, DateTimeOffset, CancellationToken)

Schedules a message for future delivery at the specified time.

public Task ScheduleMessageAsync(OutboxMessage message, DateTimeOffset scheduledAt, CancellationToken cancellationToken)

Parameters

message OutboxMessage

The outbox message to schedule.

scheduledAt DateTimeOffset

The time at which the message should be delivered.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task

A task representing the asynchronous schedule operation.

StageMessageAsync(OutboundMessage, IDbTransaction, CancellationToken)

Stages a message within an externally owned database transaction.

public ValueTask StageMessageAsync(OutboundMessage message, IDbTransaction transaction, CancellationToken cancellationToken)

Parameters

message OutboundMessage

The outbound message to stage. Must not be null.

transaction IDbTransaction

The database transaction to enlist the staging write on. Must not be null. The transaction owner (the transactional event store, in the canonical flow) controls its lifecycle (begin, commit, rollback); this method only stages the message on the supplied transaction.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous staging operation.

Remarks

Stages a message within an externally owned transaction. The caller is responsible for committing or rolling back the transaction. This enables atomic consistency between event store appends and outbox writes in event sourcing scenarios.

Exceptions

ArgumentNullException

Thrown when message or transaction is null.

StageMessageAsync(OutboundMessage, CancellationToken)

Stages a message for outbound delivery using the standard IOutboxStore interface.

public ValueTask StageMessageAsync(OutboundMessage message, CancellationToken cancellationToken)

Parameters

message OutboundMessage

Message to stage for delivery.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

ValueTask

A task representing the asynchronous operation.