class
AsyncLocalIdempotencyContextAccessor
Assembly: EricksonLopez.Idempotencypublic sealed class AsyncLocalIdempotencyContextAccessor : IIdempotencyContextAccessor
Implements: IIdempotencyContextAccessor
Provides access to the ambient `IdempotencyContext` flowed across asynchronous execution contexts.
Members (1)
propertyIdempotencyContext
public IdempotencyContext? IdempotencyContext { get; set; }
Gets or sets the current `IdempotencyContext`.
record
CachedIdempotencyResponse
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record CachedIdempotencyResponse(int StatusCode, IReadOnlyDictionary<string, string[]> Headers, ReadOnlyMemory<byte> Body)
Represents the cached HTTP or application response associated with a completed idempotent operation.
Members (4)
constructorCachedIdempotencyResponse
public CachedIdempotencyResponse(int StatusCode, IReadOnlyDictionary<string, string[]> Headers, ReadOnlyMemory<byte> Body)
Initializes a new instance of CachedIdempotencyResponse.
- StatusCode: int
- The HTTP or logical status code of the response.
- Headers: IReadOnlyDictionary<string, string[]>
- The headers associated with the response.
- Body: ReadOnlyMemory<byte>
- The serialized raw body payload.
propertyBody
public ReadOnlyMemory<byte> Body { get; init; }
The serialized raw body payload.
propertyHeaders
public IReadOnlyDictionary<string, string[]> Headers { get; init; }
The headers associated with the response.
propertyStatusCode
public int StatusCode { get; init; }
The HTTP or logical status code of the response.
enum
ClaimResultStatus
Assembly: EricksonLopez.Idempotency.Abstractionspublic enum ClaimResultStatus : byte
Defines the specific outcome of an attempt to acquire ownership or claim an idempotency key.
Members (5)
fieldAcquiredNew
AcquiredNew = 1
Specifies that the key did not exist previously and ownership was successfully acquired as a new operation.
fieldAcquiredStale
AcquiredStale = 2
Specifies that the key existed but was stale due to an expired lease or failure, and ownership was reclaimed.
fieldCompletedReplay
CompletedReplay = 3
Specifies that the operation was already completed previously and the stored cached response should be replayed.
fieldFingerprintMismatch
FingerprintMismatch = 5
Specifies that the key was previously used with a different request payload or cryptographic fingerprint.
fieldInFlightConflict
InFlightConflict = 4
Specifies that the operation is currently being executed by another concurrent worker under an active lease.
class
DefaultIdempotencyPolicy
Assembly: EricksonLopez.Idempotencypublic sealed class DefaultIdempotencyPolicy : IIdempotencyPolicy
Implements: IIdempotencyPolicy
Provides a default evaluation policy for idempotent operation execution based on configured options.
Members (5)
constructorDefaultIdempotencyPolicy
public DefaultIdempotencyPolicy(IdempotencyOptions options)
Initializes a new instance of the `DefaultIdempotencyPolicy` class with the specified idempotency options.
- options: IdempotencyOptions
- The idempotency configuration options.
methodIsCacheableStatusCode
public bool IsCacheableStatusCode(int statusCode)
Evaluates whether an HTTP or application status code is considered cacheable.
- statusCode: int
- The status code to evaluate.
Returns: `true` if the response should be stored; otherwise, `false`.
propertyAllowRetryOnFailure
public bool AllowRetryOnFailure { get; }
Gets a value indicating whether failed executions can be retried by acquiring a new lease.
propertyLeaseDuration
public TimeSpan LeaseDuration { get; }
Gets the duration an execution lease is granted before it can be stolen by another worker.
propertyRetentionDuration
public TimeSpan RetentionDuration { get; }
Gets the duration for which completed idempotency records are retained before becoming eligible for cleanup.
record
ExecutionResponse
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record ExecutionResponse
Represents the protocol-agnostic response produced by an executed operation, containing the status code, response headers, and raw body payload.
Members (13)
constructorExecutionResponse
public ExecutionResponse()
Initializes a new instance of the `ExecutionResponse` record.
constructorExecutionResponse
public ExecutionResponse(int statusCode, IReadOnlyDictionary<string, string[]>? headers = null, ReadOnlyMemory<byte> body = default)
Initializes a new instance of the `ExecutionResponse` record with the specified status code, headers, and body payload.
- statusCode: int
- The HTTP or logical status code.
- headers: IReadOnlyDictionary<string, string[]>?
- The response headers dictionary, or `null` for empty headers.
- body: ReadOnlyMemory<byte>
- The serialized raw body payload.
propertyBody
public ReadOnlyMemory<byte> Body { get; init; }
Gets the serialized raw response body payload.
propertyBypassCaching
public bool BypassCaching { get; init; }
Gets a value indicating whether response caching in persistence stores should be bypassed (e.g. when payload limits are exceeded).
propertyConnection
public System.Data.IDbConnection? Connection { get; init; }
Gets the active database connection associated with this response, if any.
propertyHandledTransactionally
public bool HandledTransactionally { get; init; }
Gets a value indicating whether transactional completion was already performed by the execution delegate. When `true`, `IdempotencyEngine` skips calling `MarkCompletedAsync`.
propertyHeaders
public IReadOnlyDictionary<string, string[]> Headers { get; init; }
Gets the collection of headers associated with the execution response.
propertyIsSuccess
public bool IsSuccess { get; }
Gets a value indicating whether the status code represents a successful outcome (HTTP 200–299).
propertyStatusCode
public required int StatusCode { get; init; }
Gets the HTTP or logical status code of the execution response.
propertyTransaction
public System.Data.IDbTransaction? Transaction { get; init; }
Gets the active database transaction associated with this response, if any.
propertyTransactionContext
public ITransactionContext? TransactionContext { get; init; }
Gets the transactional context coordinating commit and rollback, if any.
fieldEmptyHeaders
public static readonly IReadOnlyDictionary<string, string[]> EmptyHeaders
Gets a shared empty read-only headers dictionary.
fieldstring
public static readonly IReadOnlyDictionary<string, string[]> string
Gets a shared empty read-only headers dictionary.
record
FallbackCacheEntry
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record FallbackCacheEntry(string Fingerprint, int StatusCode, IReadOnlyDictionary<string, string[]> Headers, ReadOnlyMemory<byte> Body, DateTimeOffset CreatedAtUtc, DateTimeOffset RetentionExpiresAtUtc)
Represents a cached response entry stored within the in-memory fallback cache.
Members (7)
constructorFallbackCacheEntry
public FallbackCacheEntry(string Fingerprint, int StatusCode, IReadOnlyDictionary<string, string[]> Headers, ReadOnlyMemory<byte> Body, DateTimeOffset CreatedAtUtc, DateTimeOffset RetentionExpiresAtUtc)
Initializes a new instance of FallbackCacheEntry.
- Fingerprint: string
- The cryptographic fingerprint of the original request.
- StatusCode: int
- The HTTP or protocol status code.
- Headers: IReadOnlyDictionary<string, string[]>
- The collection of cached response headers.
- Body: ReadOnlyMemory<byte>
- The payload body bytes.
- CreatedAtUtc: DateTimeOffset
- The timestamp when the entry was created.
- RetentionExpiresAtUtc: DateTimeOffset
- The expiration timestamp for retention.
propertyBody
public ReadOnlyMemory<byte> Body { get; init; }
The payload body bytes.
propertyCreatedAtUtc
public DateTimeOffset CreatedAtUtc { get; init; }
The timestamp when the entry was created.
propertyFingerprint
public string Fingerprint { get; init; }
The cryptographic fingerprint of the original request.
propertyHeaders
public IReadOnlyDictionary<string, string[]> Headers { get; init; }
The collection of cached response headers.
propertyRetentionExpiresAtUtc
public DateTimeOffset RetentionExpiresAtUtc { get; init; }
The expiration timestamp for retention.
propertyStatusCode
public int StatusCode { get; init; }
The HTTP or protocol status code.
interface
IFallbackCache
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IFallbackCache
Defines the abstraction for an in-memory fallback cache to provide high-resilience idempotency replay when the primary persistent storage provider is unavailable.
Members (6)
methodClear
void Clear()
Clears all entries from the fallback cache.
methodRelease
void Release(string key, Guid ownerToken)
Releases an acquired in-flight lease if the owner token matches.
- key: string
- The idempotency cache key.
- ownerToken: Guid
- The lease owner token.
methodRemove
void Remove(string key)
Removes an entry from the fallback cache.
- key: string
- The idempotency cache key.
methodSet
void Set(string key, FallbackCacheEntry entry, TimeSpan retentionDuration)
Stores or updates an idempotency response entry in the fallback cache.
- key: string
- The idempotency cache key.
- entry: FallbackCacheEntry
- The response entry to cache.
- retentionDuration: TimeSpan
- The retention duration before eviction.
methodTryAcquire
bool TryAcquire(string key, string fingerprint, TimeSpan leaseDuration, out Guid ownerToken)
Attempts to acquire an in-flight lease in the fallback cache.
- key: string
- The idempotency cache key.
- fingerprint: string
- The cryptographic fingerprint of the request.
- leaseDuration: TimeSpan
- The lease duration.
- ownerToken: out Guid
- When successful, contains the unique token for the lease owner.
Returns: `true` if the lease was acquired; otherwise, `false`.
methodTryGet
bool TryGet(string key, out FallbackCacheEntry? entry)
Attempts to retrieve a completed idempotency response entry from the fallback cache.
- key: string
- The idempotency cache key.
- entry: out FallbackCacheEntry?
- When this method returns, contains the cached entry if found and unexpired; otherwise, null.
Returns: `true` if an unexpired entry was found; otherwise, `false`.
interface
IIdempotencyContextAccessor
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencyContextAccessor
Provides access to the current `IdempotencyContext`.
Members (1)
propertyIdempotencyContext
IdempotencyContext? IdempotencyContext { get; set; }
Gets or sets the current `IdempotencyContext`.
interface
IIdempotencyFingerprintGenerator
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencyFingerprintGenerator
Defines a strategy for computing deterministic fingerprints from request components.
Members (1)
methodGenerateFingerprint
string GenerateFingerprint(string operationName, string scope, string tenantId, string? authenticatedSubject, ReadOnlySpan<byte> payloadBytes)
Computes a deterministic hexadecimal fingerprint string from the specified operation components.
- operationName: string
- The logical operation or endpoint route name.
- scope: string
- The functional partition scope.
- tenantId: string
- The string tenant identifier.
- authenticatedSubject: string?
- The authenticated subject or user identifier if present; otherwise, `null`.
- payloadBytes: ReadOnlySpan<byte>
- The raw payload bytes to hash.
Returns: An uppercase hexadecimal hash string representing the request fingerprint.
interface
IIdempotencyKeyProvider<TContext>
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencyKeyProvider<TContext>
Defines a strategy for resolving an idempotency key from an incoming request or message context.
Members (1)
methodTryGetKeyAsync
ValueTask<IdempotencyKey?> TryGetKeyAsync(TContext context, CancellationToken cancellationToken = default)
Attempts to resolve an idempotency key from the specified context.
- context: TContext
- The execution context.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A value task representing the asynchronous operation. The task result contains the resolved `IdempotencyKey`, or `null` if none was found.
interface
IIdempotencyPolicy
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencyPolicy
Defines policy rules and evaluation criteria for idempotent operation execution.
Members (4)
methodIsCacheableStatusCode
bool IsCacheableStatusCode(int statusCode)
Evaluates whether an HTTP or application status code is considered cacheable.
- statusCode: int
- The status code to evaluate.
Returns: `true` if the response should be stored; otherwise, `false`.
propertyAllowRetryOnFailure
bool AllowRetryOnFailure { get; }
Gets a value indicating whether failed executions can be retried by acquiring a new lease.
propertyLeaseDuration
TimeSpan LeaseDuration { get; }
Gets the duration an execution lease is granted before it can be stolen by another worker.
propertyRetentionDuration
TimeSpan RetentionDuration { get; }
Gets the duration for which completed idempotency records are retained before becoming eligible for cleanup.
interface
IIdempotencySerializer
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencySerializer
Defines a contract for serializing and deserializing response and request payloads for idempotency storage.
Members (2)
methodDeserialize<T>
T? Deserialize<T>(ReadOnlyMemory<byte> bytes)
Deserializes a raw byte payload into an instance of `T`.
- bytes: ReadOnlyMemory<byte>
- The memory buffer containing the serialized payload bytes.
Returns: The deserialized object instance, or `null` if deserialization produces no value.
methodSerialize<T>
byte[] Serialize<T>(T value)
Serializes an object value into a raw UTF-8 byte array.
- value: T
- The value to serialize.
Returns: A byte array containing the serialized representation.
interface
IIdempotencyStore
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface IIdempotencyStore
Defines the persistence contract for atomically recording, updating, and querying idempotency state across distributed instances.
Members (4)
methodCleanupExpiredRecordsAsync
Task<int> CleanupExpiredRecordsAsync(DateTimeOffset utcNow, int batchSize, CancellationToken cancellationToken = default)
Deletes expired completed idempotency records in batches to reclaim storage.
- utcNow: DateTimeOffset
- The current UTC timestamp threshold for expiration.
- batchSize: int
- The maximum number of records to purge per execution batch.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains the number of expired records permanently purged.
methodMarkCompletedAsync
Task<bool> MarkCompletedAsync(Guid tenantId, string scope, IdempotencyKey key, Guid ownerToken, int concurrencyVersion, int statusCode, IReadOnlyDictionary<string, string[]> headers, ReadOnlyMemory<byte> responseBody, TimeSpan retentionDuration, CancellationToken cancellationToken = default)
Atomically marks an in-flight idempotency record as completed, storing the produced response payload.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- ownerToken: Guid
- The ownership token issued during key acquisition.
- concurrencyVersion: int
- The concurrency version issued during key acquisition.
- statusCode: int
- The HTTP or logical status code to cache.
- headers: IReadOnlyDictionary<string, string[]>
- The response headers to cache.
- responseBody: ReadOnlyMemory<byte>
- The serialized response body bytes to cache.
- retentionDuration: TimeSpan
- The retention duration for the completed record.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains `true` if the record was successfully updated with matching fencing tokens; otherwise, `false`.
methodMarkFailedAsync
Task<bool> MarkFailedAsync(Guid tenantId, string scope, IdempotencyKey key, Guid ownerToken, int concurrencyVersion, CancellationToken cancellationToken = default)
Atomically marks an in-flight idempotency record as failed, enabling subsequent retries depending on policy.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- ownerToken: Guid
- The ownership token issued during key acquisition.
- concurrencyVersion: int
- The concurrency version issued during key acquisition.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains `true` if the record was successfully marked as failed; otherwise, `false`.
methodTryAcquireAsync
Task<IdempotencyClaimResult> TryAcquireAsync(Guid tenantId, string scope, IdempotencyKey key, string fingerprint, TimeSpan leaseDuration, TimeSpan retentionDuration, CancellationToken cancellationToken = default)
Attempts to acquire exclusive execution ownership for an idempotency key within the specified tenant and scope.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope or partition of the operation.
- key: IdempotencyKey
- The unique idempotency key.
- fingerprint: string
- The cryptographic fingerprint representing the canonical request.
- leaseDuration: TimeSpan
- The duration for which the ownership lease remains valid before considering it stale.
- retentionDuration: TimeSpan
- The retention period for retaining completed records.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains the `IdempotencyClaimResult` describing the acquisition outcome.
interface
ITransactionContext
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface ITransactionContext
Encapsulates an active database connection and transaction, coordinating atomic commit and rollback operations.
Members (4)
methodCommitAsync
Task CommitAsync(CancellationToken cancellationToken = default)
Asynchronously commits the database transaction.
- cancellationToken: CancellationToken
- A token to monitor for cancellation requests.
methodRollbackAsync
Task RollbackAsync(CancellationToken cancellationToken = default)
Asynchronously rolls back the database transaction.
- cancellationToken: CancellationToken
- A token to monitor for cancellation requests.
propertyConnection
IDbConnection Connection { get; }
Gets the active database connection.
propertyTransaction
IDbTransaction? Transaction { get; }
Gets the active database transaction, or `null` if uncommitted on connection.
interface
ITransactionalIdempotencyStore
Assembly: EricksonLopez.Idempotency.Abstractionspublic interface ITransactionalIdempotencyStore : IIdempotencyStore
Implements: IIdempotencyStore
Extends `IIdempotencyStore` with the ability to participate in an existing database transaction, enabling atomic coordination with domain operations in the Outbox and CQRS transactional patterns.
Members (3)
methodMarkCompletedAsync
Task<bool> MarkCompletedAsync(Guid tenantId, string scope, IdempotencyKey key, Guid ownerToken, int concurrencyVersion, int statusCode, IReadOnlyDictionary<string, string[]> headers, ReadOnlyMemory<byte> responseBody, TimeSpan retentionDuration, IDbConnection connection, IDbTransaction? transaction, CancellationToken cancellationToken = default)
Atomically marks an in-flight idempotency record as completed within the provided database transaction, storing the produced response payload.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- ownerToken: Guid
- The ownership token issued during key acquisition.
- concurrencyVersion: int
- The concurrency version issued during key acquisition.
- statusCode: int
- The HTTP or logical status code to cache.
- headers: IReadOnlyDictionary<string, string[]>
- The response headers to cache.
- responseBody: ReadOnlyMemory<byte>
- The serialized response body bytes to cache.
- retentionDuration: TimeSpan
- The retention duration for the completed record.
- connection: IDbConnection
- An existing open `IDbConnection` to use. Must not be `null`. The store will use this connection without opening a new one.
- transaction: IDbTransaction?
- An optional active `IDbTransaction` the operation should participate in. If `null`, the operation runs without a transaction but still uses the provided connection.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains `true` if the record was successfully updated; otherwise, `false` (fencing token mismatch or owner mismatch).
methodMarkFailedAsync
Task<bool> MarkFailedAsync(Guid tenantId, string scope, IdempotencyKey key, Guid ownerToken, int concurrencyVersion, IDbConnection connection, IDbTransaction? transaction, CancellationToken cancellationToken = default)
Atomically marks an in-flight idempotency record as failed within the provided database transaction, enabling subsequent retries depending on policy.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- ownerToken: Guid
- The ownership token issued during key acquisition.
- concurrencyVersion: int
- The concurrency version issued during key acquisition.
- connection: IDbConnection
- An existing open `IDbConnection` to use. Must not be `null`.
- transaction: IDbTransaction?
- An optional active `IDbTransaction` the operation should participate in. If `null`, the operation runs without a transaction but still uses the provided connection.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains `true` if the record was successfully marked as failed; otherwise, `false`.
methodTryAcquireAsync
Task<IdempotencyClaimResult> TryAcquireAsync(Guid tenantId, string scope, IdempotencyKey key, string fingerprint, TimeSpan leaseDuration, TimeSpan retentionDuration, IDbConnection connection, IDbTransaction? transaction, CancellationToken cancellationToken = default)
Attempts to acquire exclusive execution ownership for an idempotency key within the specified database transaction.
- tenantId: Guid
- The unique identifier of the tenant.
- scope: string
- The functional scope or partition of the operation.
- key: IdempotencyKey
- The unique idempotency key.
- fingerprint: string
- The cryptographic fingerprint representing the canonical request.
- leaseDuration: TimeSpan
- The duration for which the ownership lease remains valid before considering it stale.
- retentionDuration: TimeSpan
- The retention period for retaining completed records.
- connection: IDbConnection
- An existing open database connection to use.
- transaction: IDbTransaction?
- An optional active database transaction to participate in.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains the `IdempotencyClaimResult` indicating whether ownership was acquired, if a cached response is available for replay, or if a conflict occurred.
record
IdempotencyClaimResult
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record IdempotencyClaimResult(ClaimResultStatus Status, Guid? OwnerToken, int? ConcurrencyVersion, CachedIdempotencyResponse? CachedResponse, string? ExistingFingerprint)
Represents the result of an atomic key acquisition attempt against the idempotency store.
Members (8)
constructorIdempotencyClaimResult
public IdempotencyClaimResult(ClaimResultStatus Status, Guid? OwnerToken, int? ConcurrencyVersion, CachedIdempotencyResponse? CachedResponse, string? ExistingFingerprint)
Initializes a new instance of IdempotencyClaimResult.
- Status: ClaimResultStatus
- The specific status outcome of the claim attempt.
- OwnerToken: Guid?
- The unique owner token issued if acquisition succeeded.
- ConcurrencyVersion: int?
- The concurrency version token if acquisition succeeded.
- CachedResponse: CachedIdempotencyResponse?
- The cached response payload if status is `ClaimResultStatus.CompletedReplay`.
- ExistingFingerprint: string?
- The recorded fingerprint on collision or mismatch.
propertyCachedResponse
public CachedIdempotencyResponse? CachedResponse { get; init; }
The cached response payload if status is `ClaimResultStatus.CompletedReplay`.
propertyConcurrencyVersion
public int? ConcurrencyVersion { get; init; }
The concurrency version token if acquisition succeeded.
propertyExistingFingerprint
public string? ExistingFingerprint { get; init; }
The recorded fingerprint on collision or mismatch.
propertyIsAcquired
public bool IsAcquired { get; }
Gets a value indicating whether ownership of the idempotency key was successfully acquired to execute the operation.
propertyIsReplay
public bool IsReplay { get; }
Gets a value indicating whether this claim represents a replay of a previously completed operation.
propertyOwnerToken
public Guid? OwnerToken { get; init; }
The unique owner token issued if acquisition succeeded.
propertyStatus
public ClaimResultStatus Status { get; init; }
The specific status outcome of the claim attempt.
class
IdempotencyCleanupOptions
Assembly: EricksonLopez.Idempotencypublic sealed class IdempotencyCleanupOptions
Encapsulates configuration options for the idempotency cleanup background service.
Members (2)
propertyBatchSize
public int BatchSize { get; set; }
Gets or sets the maximum number of expired records to purge per cleanup cycle.
propertyInterval
public TimeSpan Interval { get; set; }
Gets or sets the interval between consecutive cleanup cycles.
record
IdempotencyContext
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record IdempotencyContext
Encapsulates the execution context of the currently executing idempotent request.
Members (15)
constructorIdempotencyContext
public IdempotencyContext()
Initializes a new instance of the `IdempotencyContext` record with default values.
methodCreateAcquired
public static IdempotencyContext CreateAcquired(Guid tenantId, string scope, IdempotencyKey key, Guid? ownerToken = null, int? concurrencyVersion = null)
Creates a new `IdempotencyContext` representing an actively acquired idempotency lease.
- tenantId: Guid
- The tenant identifier that partitions idempotency records.
- scope: string
- The functional scope or logical partition.
- key: IdempotencyKey
- The unique idempotency key identifying the operation.
- ownerToken: Guid?
- The ownership token issued for this lease.
- concurrencyVersion: int?
- The concurrency version token issued with the lease.
Returns: An immutable `IdempotencyContext` configured for an acquired operation.
methodCreateReplay
public static IdempotencyContext CreateReplay(Guid tenantId, string scope, IdempotencyKey key)
Creates a new `IdempotencyContext` representing a replayed cached execution.
- tenantId: Guid
- The tenant identifier that partitions idempotency records.
- scope: string
- The functional scope or logical partition.
- key: IdempotencyKey
- The unique idempotency key identifying the operation.
Returns: An immutable `IdempotencyContext` configured for a replayed operation.
methodCreateReplayed
public static IdempotencyContext CreateReplayed(Guid tenantId, string scope, IdempotencyKey key)
Creates a new `IdempotencyContext` representing a replayed cached execution.
- tenantId: Guid
- The tenant identifier that partitions idempotency records.
- scope: string
- The functional scope or logical partition.
- key: IdempotencyKey
- The unique idempotency key identifying the operation.
Returns: An immutable `IdempotencyContext` configured for a replayed operation.
methodWithTransaction
public IdempotencyContext WithTransaction(ITransactionContext transactionContext)
Returns a new `IdempotencyContext` with the specified transaction context.
- transactionContext: ITransactionContext
- The transactional context coordinating database interactions.
Returns: A new `IdempotencyContext` with the updated transaction context.
methodWithTransaction
public IdempotencyContext WithTransaction(System.Data.IDbConnection connection, System.Data.IDbTransaction? transaction = null)
Returns a new `IdempotencyContext` with the specified connection and transaction.
- connection: System.Data.IDbConnection
- The database connection participating in the operation.
- transaction: System.Data.IDbTransaction?
- The optional database transaction associated with the connection.
Returns: A new `IdempotencyContext` with the updated connection and transaction.
propertyConcurrencyVersion
public int? ConcurrencyVersion { get; init; }
Gets the fencing token version number issued with the ownership lease to detect zombie workers.
propertyConnection
public System.Data.IDbConnection? Connection { get; init; }
Gets the active database connection associated with this operation, if any.
propertyIsReplay
public bool IsReplay { get; init; }
Gets a value indicating whether the handler is being invoked as part of a cached response replay.
propertyKey
public IdempotencyKey? Key { get; init; }
Gets the unique idempotency key identifying the current operation.
propertyOwnerToken
public Guid? OwnerToken { get; init; }
Gets the ownership token issued when this instance successfully acquired the idempotency lease.
propertyScope
public string Scope { get; init; }
Gets the functional scope or logical partition that isolates this operation's idempotency records.
propertyTenantId
public Guid TenantId { get; init; }
Gets the tenant identifier that partitions idempotency records for the current operation.
propertyTransaction
public System.Data.IDbTransaction? Transaction { get; init; }
Gets the active database transaction associated with this operation, if any.
propertyTransactionContext
public ITransactionContext? TransactionContext { get; init; }
Gets the transactional context coordinating commit and rollback, if any.
class
IdempotencyDiagnostics
Assembly: EricksonLopez.Idempotencypublic static class IdempotencyDiagnostics
Provides unified OpenTelemetry activity tracing and metric meters for the idempotency framework.
Members (18)
methodMaskKey
public static string MaskKey(string? key)
Masks an idempotency key to prevent PII and credential leakage in logs and telemetry traces. Preserves the first 2 and last 2 characters, masking intermediate characters with '****', or fully masking if 4 characters or fewer.
- key: string?
- The raw idempotency key.
Returns: The masked key string, or empty string if `key` is null or empty.
methodRecordCompleted
public static void RecordCompleted(string scope)
Records a successfully completed and cached idempotent operation for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordConflict
public static void RecordConflict(string scope)
Records an in-flight concurrent execution conflict for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordDuplicate
public static void RecordDuplicate(string scope)
Records a detected duplicate request attempt for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordDuration
public static void RecordDuration(double milliseconds, string scope)
Records the total end-to-end execution duration of an idempotent operation.
- milliseconds: double
- The elapsed execution time in milliseconds.
- scope: string
- The functional partition scope of the operation.
methodRecordExecution
public static void RecordExecution(string scope)
Records a newly executed underlying business operation for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordFailed
public static void RecordFailed(string scope)
Records a failed idempotent operation for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordFingerprintMismatch
public static void RecordFingerprintMismatch(string scope)
Records an idempotency key reuse collision with mismatched payload fingerprints.
- scope: string
- The functional partition scope of the operation.
methodRecordLeaseLoss
public static void RecordLeaseLoss(string scope)
Records an idempotency execution lease loss before completion for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordReplayed
public static void RecordReplayed(string scope)
Records a cached response replay served for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordRequest
public static void RecordRequest(string scope)
Records an incoming request attempt for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodRecordStorageLatency
public static void RecordStorageLatency(double milliseconds, string operation)
Records the latency of a storage interaction operation.
- milliseconds: double
- The elapsed storage operation time in milliseconds.
- operation: string
- The storage operation name.
methodRecordStoreOutage
public static void RecordStoreOutage(string scope)
Records an idempotency store outage or infrastructure failure for the specified functional scope.
- scope: string
- The functional partition scope of the operation.
methodSanitizeScope
public static string SanitizeScope(string? scope)
Sanitizes the scope dimension value by replacing dynamic path parameters (GUIDs, numeric identifiers) with generic placeholders to prevent metric cardinality explosion.
- scope: string?
- The raw scope string.
Returns: A bounded, sanitized scope string safe for metric dimension tagging.
fieldActivitySource
public static readonly ActivitySource ActivitySource
Gets the `Diagnostics.ActivitySource` for distributed tracing of idempotency operations.
fieldMeter
public static readonly Meter Meter
Gets the `Metrics.Meter` for exporting operational idempotency metrics.
fieldServiceName
public const string ServiceName
Gets the service name for OpenTelemetry meter and activity source registration.
fieldServiceVersion
public const string ServiceVersion
Gets the version string of the instrumentation library.
class
IdempotencyEngine
Assembly: EricksonLopez.Idempotencypublic sealed partial class IdempotencyEngine
Coordinates the execution workflow and state machine transitions for idempotent operations.
Members (3)
constructorIdempotencyEngine
public IdempotencyEngine(IIdempotencyStore store, IIdempotencyPolicy policy, IIdempotencySerializer serializer, IIdempotencyContextAccessor contextAccessor, ILogger<IdempotencyEngine> logger, IFallbackCache? fallbackCache = null)
Initializes a new instance of the `IdempotencyEngine` class with the specified dependencies.
- store: IIdempotencyStore
- The persistence store for recording idempotency state.
- policy: IIdempotencyPolicy
- The evaluation policy determining lease and retention rules.
- serializer: IIdempotencySerializer
- The serializer used for response caching.
- contextAccessor: IIdempotencyContextAccessor
- The accessor for current idempotency context.
- logger: ILogger<IdempotencyEngine>
- The logger for diagnostics and runtime events.
- fallbackCache: IFallbackCache?
- An optional fallback cache used during primary store outages.
methodExecuteAsync<TResult>
public async Task<TResult> ExecuteAsync<TResult>(Guid tenantId, string scope, IdempotencyKey key, string fingerprint, Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default)
Executes an operation idempotently, ensuring effectively-once execution semantics.
- tenantId: Guid
- The unique tenant identifier.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- fingerprint: string
- The cryptographic fingerprint of the request.
- operation: Func<CancellationToken, Task<TResult>>
- The asynchronous operation delegate to execute.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the asynchronous operation. The task result contains the freshly computed result if ownership was acquired, or the deserialized cached value if the operation was already completed.
methodExecutePipelineAsync
public async Task<IdempotencyPipelineResult> ExecutePipelineAsync(Guid tenantId, string scope, IdempotencyKey key, string fingerprint, TimeSpan leaseDuration, TimeSpan retentionDuration, Func<IdempotencyContext, Task<ExecutionResponse>> executionDelegate, CancellationToken cancellationToken = default)
Executes an operation through the unified idempotency pipeline, returning an `IdempotencyPipelineResult`.
- tenantId: Guid
- The unique tenant identifier.
- scope: string
- The functional scope of the operation.
- key: IdempotencyKey
- The idempotency key.
- fingerprint: string
- The cryptographic fingerprint of the request.
- leaseDuration: TimeSpan
- The duration of the execution lease.
- retentionDuration: TimeSpan
- The retention duration of the completed record.
- executionDelegate: Func<IdempotencyContext, Task<ExecutionResponse>>
- The operation delegate to execute if ownership is acquired.
- cancellationToken: CancellationToken
- A token that can be used to cancel the asynchronous operation.
Returns: A task representing the pipeline result.
class
IdempotencyFingerprintHasher
Assembly: EricksonLopez.Idempotencypublic sealed class IdempotencyFingerprintHasher : IIdempotencyFingerprintGenerator
Implements: IIdempotencyFingerprintGenerator
Provides high-performance, deterministic SHA-256 cryptographic fingerprint generation for idempotent operations.
Members (2)
methodCompute
public static string Compute(string operationName, string scope, string tenantId, string? authenticatedSubject, ReadOnlySpan<byte> payloadBytes)
Computes a deterministic hexadecimal SHA-256 fingerprint from the canonical components of an operation.
- operationName: string
- The logical operation or endpoint route name.
- scope: string
- The functional partition scope.
- tenantId: string
- The string tenant identifier.
- authenticatedSubject: string?
- The authenticated subject or user identifier if present; otherwise, `null`.
- payloadBytes: ReadOnlySpan<byte>
- The raw payload byte content to hash.
Returns: An uppercase hexadecimal SHA-256 hash string uniquely identifying the combination of all provided inputs.
methodGenerateFingerprint
public string GenerateFingerprint(string operationName, string scope, string tenantId, string? authenticatedSubject, ReadOnlySpan<byte> payloadBytes)
Computes a deterministic hexadecimal fingerprint string from the specified operation components.
- operationName: string
- The logical operation or endpoint route name.
- scope: string
- The functional partition scope.
- tenantId: string
- The string tenant identifier.
- authenticatedSubject: string?
- The authenticated subject or user identifier if present; otherwise, `null`.
- payloadBytes: ReadOnlySpan<byte>
- The raw payload bytes to hash.
Returns: An uppercase hexadecimal hash string representing the request fingerprint.
class
IdempotencyJsonContext
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed partial class IdempotencyJsonContext : JsonSerializerContext
Inherits: JsonSerializerContext
Provides source-generated JSON serialization metadata for Native AOT compatibility.
Members (0)
This type declares 0 public members (e.g. marker interface or empty enum/record).
record
IdempotencyKey
Assembly: EricksonLopez.Idempotency.Abstractionspublic readonly record struct IdempotencyKey : IEquatable<IdempotencyKey>, IComparable<IdempotencyKey>, IComparable
Implements: IComparable, IComparable<IdempotencyKey>, IEquatable<IdempotencyKey>
Represents an immutable, strongly-typed idempotency key value object.
Members (17)
constructorIdempotencyKey
public IdempotencyKey(string value)
Initializes a new instance of the `IdempotencyKey` struct.
- value: string
- The unique string key supplied by the client or producer.
methodCompareTo
public int CompareTo(IdempotencyKey other)
Inherits documentation from base type or interface.
- other: IdempotencyKey
methodCompareTo
public int CompareTo(object? obj)
Inherits documentation from base type or interface.
- obj: object?
methodCreate
public static IdempotencyKey Create(Guid identifier)
Creates a new `IdempotencyKey` from the specified `Guid`.
- identifier: Guid
- The unique identifier.
Returns: A new `IdempotencyKey` instance initialized with the hyphenless string representation of the identifier.
methodCreate
public static IdempotencyKey Create(string value)
Creates a new `IdempotencyKey` instance after validating input invariants.
- value: string
- The unique string key.
Returns: A validated `IdempotencyKey` instance.
methodNewKey
public static IdempotencyKey NewKey()
Generates a new random `IdempotencyKey` using a cryptographically unique identifier.
Returns: A new `IdempotencyKey` initialized with a newly generated identifier.
methodToString
public override string ToString()
Inherits documentation from base type or interface.
methodTryParse
public static bool TryParse(string? candidate, out IdempotencyKey key)
Attempts to parse a string into an `IdempotencyKey`.
- candidate: string?
- The string candidate to parse.
- key: out IdempotencyKey
- When this method returns, contains the parsed `IdempotencyKey` if parsing succeeded; otherwise, the default uninitialized value.
Returns: `true` if the string was successfully parsed; otherwise, `false`.
methodexplicit operator IdempotencyKey
public static explicit operator IdempotencyKey(string value)
Converts a `string` to an `IdempotencyKey` instance.
- value: string
- The string value to convert.
Returns: A new `IdempotencyKey` initialized with the specified value.
methodimplicit operator string
public static implicit operator string(IdempotencyKey key)
Converts an `IdempotencyKey` to its underlying `string` representation.
- key: IdempotencyKey
- The `IdempotencyKey` to convert.
Returns: The underlying string representation of the key.
methodoperator <
public static bool operator <(IdempotencyKey left, IdempotencyKey right)
Determines whether a specified `IdempotencyKey` is less than another specified `IdempotencyKey`.
- left: IdempotencyKey
- The first `IdempotencyKey` to compare.
- right: IdempotencyKey
- The second `IdempotencyKey` to compare.
Returns: `true` if `left` is less than `right`; otherwise, `false`.
methodoperator <=
public static bool operator <=(IdempotencyKey left, IdempotencyKey right)
Determines whether a specified `IdempotencyKey` is less than or equal to another specified `IdempotencyKey`.
- left: IdempotencyKey
- The first `IdempotencyKey` to compare.
- right: IdempotencyKey
- The second `IdempotencyKey` to compare.
Returns: `true` if `left` is less than or equal to `right`; otherwise, `false`.
methodoperator >
public static bool operator >(IdempotencyKey left, IdempotencyKey right)
Determines whether a specified `IdempotencyKey` is greater than another specified `IdempotencyKey`.
- left: IdempotencyKey
- The first `IdempotencyKey` to compare.
- right: IdempotencyKey
- The second `IdempotencyKey` to compare.
Returns: `true` if `left` is greater than `right`; otherwise, `false`.
methodoperator >=
public static bool operator >=(IdempotencyKey left, IdempotencyKey right)
Determines whether a specified `IdempotencyKey` is greater than or equal to another specified `IdempotencyKey`.
- left: IdempotencyKey
- The first `IdempotencyKey` to compare.
- right: IdempotencyKey
- The second `IdempotencyKey` to compare.
Returns: `true` if `left` is greater than or equal to `right`; otherwise, `false`.
propertyIsEmpty
public bool IsEmpty { get; }
Gets a value indicating whether this idempotency key is empty or uninitialized.
propertyValue
public string Value { get; }
Gets the string representation of the idempotency key, or an empty string if uninitialized.
fieldEmpty
public static readonly IdempotencyKey Empty
Represents an empty or uninitialized idempotency key.
class
IdempotencyOptions
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed class IdempotencyOptions
Encapsulates configuration options for the idempotency infrastructure.
Members (18)
methodIsHeaderCacheable
public bool IsHeaderCacheable(string headerName)
Determines whether the specified HTTP response header is safe to cache and replay.
- headerName: string
propertyAllowEmptyTenant
public bool AllowEmptyTenant { get; set; }
Gets or sets a value indicating whether empty/null tenant IDs are permitted.
propertyCacheOnlySuccessResponses
public bool CacheOnlySuccessResponses { get; set; }
Gets or sets a value indicating whether only successful responses (HTTP 2xx) are cached.
propertyCommandTimeout
public TimeSpan CommandTimeout { get; set; }
Gets or sets the database command timeout duration.
propertyDefaultLeaseDuration
public TimeSpan DefaultLeaseDuration { get; set; }
Gets or sets the default duration for which an acquired execution lease remains valid before another worker may steal it.
propertyDefaultRetentionDuration
public TimeSpan DefaultRetentionDuration { get; set; }
Gets or sets the default duration for which completed idempotency records are retained before becoming eligible for cleanup.
propertyEnableSensitiveDataLogging
public bool EnableSensitiveDataLogging { get; set; }
Gets or sets a value indicating whether sensitive data logging is enabled.
propertyEnabled
public bool Enabled { get; set; }
Gets or sets a value indicating whether idempotency enforcement is globally active.
propertyHeaderName
public string HeaderName { get; set; }
Gets or sets the header name used to supply the idempotency key.
propertyMaxRequestBodySizeBytes
public long MaxRequestBodySizeBytes { get; set; }
Gets or sets the maximum request payload size in bytes that will be read and buffered for fingerprint computation.
propertyMaxResponseBodySizeBytes
public long MaxResponseBodySizeBytes { get; set; }
Gets or sets the maximum response body size in bytes to buffer and persist.
propertyRequireIdempotencyKey
public bool RequireIdempotencyKey { get; set; }
Gets or sets a value indicating whether an idempotency key header is mandatory on guarded endpoints.
propertyResponseHeadersAllowlist
public System.Collections.Generic.HashSet<string> ResponseHeadersAllowlist { get; }
Gets the collection of explicitly allowed response headers to cache and replay.
propertyResponseHeadersBlocklist
public System.Collections.Generic.HashSet<string> ResponseHeadersBlocklist { get; }
Gets the collection of HTTP response header names that must be excluded from cached idempotency records.
propertyStoreResilience
public StoreResilienceOptions StoreResilience { get; set; }
Gets or sets configuration options for storage resilience policies and outage failover.
propertyStoreResponseBody
public bool StoreResponseBody { get; set; }
Gets or sets a value indicating whether response bodies are included in the cached idempotency record.
propertyTenantIdExtractor
public Func<object, Guid>? TenantIdExtractor { get; set; }
Gets or sets a delegate that extracts the tenant identifier from the ambient execution context.
fieldForbiddenResponseHeaders
public static readonly System.Collections.Generic.HashSet<string> ForbiddenResponseHeaders
Gets the collection of forbidden response headers that are never cached or replayed.
class
IdempotencyOptionsValidator
Assembly: EricksonLopez.Idempotencypublic sealed class IdempotencyOptionsValidator : IValidateOptions<IdempotencyOptions>
Implements: IValidateOptions<IdempotencyOptions>
Validates domain invariants and security guardrails on `IdempotencyOptions` at startup.
Members (1)
methodValidate
public ValidateOptionsResult Validate(string? name, IdempotencyOptions options)
Inherits documentation from base type or interface.
- name: string?
- options: IdempotencyOptions
enum
IdempotencyPipelineOutcome
Assembly: EricksonLopez.Idempotency.Abstractionspublic enum IdempotencyPipelineOutcome
Specifies the execution outcome of an idempotent pipeline run orchestrated by `IdempotencyEngine`.
Members (5)
fieldExecuted
Executed = 0
Indicates that the operation successfully acquired lease ownership, executed the delegate, and marked the completed response in the store.
fieldFingerprintMismatch
FingerprintMismatch = 3
Indicates that the idempotency key exists but was previously recorded with a different request fingerprint.
fieldInFlightConflict
InFlightConflict = 2
Indicates that a concurrent operation with the same idempotency key is currently executing and holds an active lease.
fieldReplayed
Replayed = 1
Indicates that the operation matched an existing completed idempotency record and replayed the previously cached response.
fieldUncachedFailure
UncachedFailure = 4
Indicates that the operation executed the delegate, but the resulting status code was not cacheable under the active policy, causing the execution lease to be marked as failed / released without response caching.
record
IdempotencyPipelineResult
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record IdempotencyPipelineResult
Represents the result of an idempotency pipeline execution, containing the pipeline outcome, status code, response headers, body payload, and contextual metadata.
Members (16)
constructorIdempotencyPipelineResult
public IdempotencyPipelineResult()
Initializes a new instance of the `IdempotencyPipelineResult` record.
constructorIdempotencyPipelineResult
public IdempotencyPipelineResult(IdempotencyPipelineOutcome outcome, int statusCode = 0, IReadOnlyDictionary<string, string[]>? headers = null, ReadOnlyMemory<byte> body = default, IdempotencyKey? key = null, string? existingFingerprint = null, string? incomingFingerprint = null)
Initializes a new instance of the `IdempotencyPipelineResult` record with the specified outcome and response components.
- outcome: IdempotencyPipelineOutcome
- The pipeline execution outcome.
- statusCode: int
- The HTTP or logical status code.
- headers: IReadOnlyDictionary<string, string[]>?
- The response headers dictionary.
- body: ReadOnlyMemory<byte>
- The serialized raw body payload.
- key: IdempotencyKey?
- The optional idempotency key.
- existingFingerprint: string?
- The existing stored fingerprint, if a mismatch occurred.
- incomingFingerprint: string?
- The incoming request fingerprint, if a mismatch occurred.
methodFromConflict
public static IdempotencyPipelineResult FromConflict(IdempotencyKey key)
Creates an `IdempotencyPipelineResult` representing an in-flight conflict.
- key: IdempotencyKey
- The conflicting idempotency key.
Returns: A new `IdempotencyPipelineResult` with `IdempotencyPipelineOutcome.InFlightConflict`.
methodFromExecuted
public static IdempotencyPipelineResult FromExecuted(ExecutionResponse response, IdempotencyKey? key = null)
Creates a successful `IdempotencyPipelineResult` representing a newly executed operation.
- response: ExecutionResponse
- The executed response details.
- key: IdempotencyKey?
- The optional idempotency key.
Returns: A new `IdempotencyPipelineResult` with `IdempotencyPipelineOutcome.Executed`.
methodFromFingerprintMismatch
public static IdempotencyPipelineResult FromFingerprintMismatch(IdempotencyKey key, string? existingFingerprint, string incomingFingerprint)
Creates an `IdempotencyPipelineResult` representing a fingerprint mismatch collision.
- key: IdempotencyKey
- The idempotency key that experienced the collision.
- existingFingerprint: string?
- The previously recorded fingerprint.
- incomingFingerprint: string
- The incoming request fingerprint that differed.
Returns: A new `IdempotencyPipelineResult` with `IdempotencyPipelineOutcome.FingerprintMismatch`.
methodFromReplay
public static IdempotencyPipelineResult FromReplay(CachedIdempotencyResponse? cached, IdempotencyKey? key = null)
Creates an `IdempotencyPipelineResult` representing a replayed cached response.
- cached: CachedIdempotencyResponse?
- The cached response data, or `null` if the cached response carried no payload (e.g., HTTP 204 No Content).
- key: IdempotencyKey?
- The optional idempotency key.
Returns: A new `IdempotencyPipelineResult` with `IdempotencyPipelineOutcome.Replayed`.
methodFromUncached
public static IdempotencyPipelineResult FromUncached(ExecutionResponse response, IdempotencyKey? key = null)
Creates an `IdempotencyPipelineResult` representing an executed operation whose response was not cached under the active policy.
- response: ExecutionResponse
- The executed response details.
- key: IdempotencyKey?
- The optional idempotency key.
Returns: A new `IdempotencyPipelineResult` with `IdempotencyPipelineOutcome.UncachedFailure`.
propertyBody
public ReadOnlyMemory<byte> Body { get; init; }
Gets the serialized raw response body payload.
propertyExistingFingerprint
public string? ExistingFingerprint { get; init; }
Gets the existing recorded fingerprint when `Outcome` is `IdempotencyPipelineOutcome.FingerprintMismatch`.
propertyHeaders
public IReadOnlyDictionary<string, string[]> Headers { get; init; }
Gets the collection of headers associated with the response.
propertyIncomingFingerprint
public string? IncomingFingerprint { get; init; }
Gets the incoming request fingerprint when `Outcome` is `IdempotencyPipelineOutcome.FingerprintMismatch`.
propertyIsReplay
public bool IsReplay { get; }
Gets a value indicating whether this pipeline result represents a replayed cached response.
propertyIsSuccess
public bool IsSuccess { get; }
Gets a value indicating whether the pipeline execution completed successfully (either fresh execution or replay).
propertyKey
public IdempotencyKey? Key { get; init; }
Gets the idempotency key associated with this pipeline execution, if available.
propertyOutcome
public required IdempotencyPipelineOutcome Outcome { get; init; }
Gets the outcome of the pipeline execution.
propertyStatusCode
public int StatusCode { get; init; }
Gets the HTTP or logical status code associated with the response.
record
IdempotencyProblemDetails
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed record IdempotencyProblemDetails(string Type, string Title, int Status, string Detail)
Represents machine-readable problem details for HTTP API error responses according to RFC 9110.
Members (5)
constructorIdempotencyProblemDetails
public IdempotencyProblemDetails(string Type, string Title, int Status, string Detail)
Initializes a new instance of IdempotencyProblemDetails.
- Type: string
- The URI reference identifying the problem type.
- Title: string
- The short, human-readable summary of the problem type.
- Status: int
- The HTTP status code generated for this occurrence.
- Detail: string
- The human-readable explanation specific to this occurrence.
propertyDetail
public string Detail { get; init; }
The human-readable explanation specific to this occurrence.
propertyStatus
public int Status { get; init; }
The HTTP status code generated for this occurrence.
propertyTitle
public string Title { get; init; }
The short, human-readable summary of the problem type.
propertyType
public string Type { get; init; }
The URI reference identifying the problem type.
record
IdempotencyScope
Assembly: EricksonLopez.Idempotency.Abstractionspublic readonly record struct IdempotencyScope : IEquatable<IdempotencyScope>, IComparable<IdempotencyScope>, IComparable
Implements: IComparable, IComparable<IdempotencyScope>, IEquatable<IdempotencyScope>
Represents the logical partition or functional boundary of an idempotent operation (e.g. endpoint route or command type).
Members (14)
constructorIdempotencyScope
public IdempotencyScope(string value)
Initializes a new instance of the `IdempotencyScope` struct.
- value: string
- The scope string identifying the functional partition.
methodCompareTo
public int CompareTo(IdempotencyScope other)
Inherits documentation from base type or interface.
- other: IdempotencyScope
methodCompareTo
public int CompareTo(object? obj)
Inherits documentation from base type or interface.
- obj: object?
methodCreate
public static IdempotencyScope Create(string value)
Creates a new `IdempotencyScope` instance after validating input invariants.
- value: string
- The scope string.
Returns: A validated `IdempotencyScope` instance.
methodCreateNormalized
public static IdempotencyScope CreateNormalized(string value)
Creates a new `IdempotencyScope` instance, deterministically normalizing the input value if it exceeds 64 characters.
- value: string
- The raw scope string.
Returns: A normalized `IdempotencyScope` whose length is guaranteed to be 64 characters or fewer.
methodToString
public override string ToString()
Inherits documentation from base type or interface.
methodexplicit operator IdempotencyScope
public static explicit operator IdempotencyScope(string value)
Converts a `string` to an `IdempotencyScope` instance.
- value: string
- The string value to convert.
Returns: A new `IdempotencyScope` initialized with the specified value.
methodimplicit operator string
public static implicit operator string(IdempotencyScope scope)
Converts an `IdempotencyScope` to its underlying `string` representation.
- scope: IdempotencyScope
- The `IdempotencyScope` to convert.
Returns: The underlying string representation of the scope.
methodoperator <
public static bool operator <(IdempotencyScope left, IdempotencyScope right)
Determines whether a specified `IdempotencyScope` is less than another specified `IdempotencyScope`.
- left: IdempotencyScope
- The first `IdempotencyScope` to compare.
- right: IdempotencyScope
- The second `IdempotencyScope` to compare.
Returns: `true` if `left` is less than `right`; otherwise, `false`.
methodoperator <=
public static bool operator <=(IdempotencyScope left, IdempotencyScope right)
Determines whether a specified `IdempotencyScope` is less than or equal to another specified `IdempotencyScope`.
- left: IdempotencyScope
- The first `IdempotencyScope` to compare.
- right: IdempotencyScope
- The second `IdempotencyScope` to compare.
Returns: `true` if `left` is less than or equal to `right`; otherwise, `false`.
methodoperator >
public static bool operator >(IdempotencyScope left, IdempotencyScope right)
Determines whether a specified `IdempotencyScope` is greater than another specified `IdempotencyScope`.
- left: IdempotencyScope
- The first `IdempotencyScope` to compare.
- right: IdempotencyScope
- The second `IdempotencyScope` to compare.
Returns: `true` if `left` is greater than `right`; otherwise, `false`.
methodoperator >=
public static bool operator >=(IdempotencyScope left, IdempotencyScope right)
Determines whether a specified `IdempotencyScope` is greater than or equal to another specified `IdempotencyScope`.
- left: IdempotencyScope
- The first `IdempotencyScope` to compare.
- right: IdempotencyScope
- The second `IdempotencyScope` to compare.
Returns: `true` if `left` is greater than or equal to `right`; otherwise, `false`.
propertyValue
public string Value { get; }
Gets the underlying string value representing the scope.
fieldDefault
public static readonly IdempotencyScope Default
Gets the default fallback scope used when no specific scope is supplied.
enum
IdempotencyStatus
Assembly: EricksonLopez.Idempotency.Abstractionspublic enum IdempotencyStatus : byte
Defines the lifecycle execution state of an idempotency record.
Members (3)
fieldCompleted
Completed = 2
Specifies that the operation was completed successfully and the result payload is immutable and cached.
fieldFailed
Failed = 3
Specifies that the operation failed during execution and may be eligible for retry depending on policy.
fieldProcessing
Processing = 1
Specifies that the operation is currently being executed under an active lease.
class
MemoryFallbackCache
Assembly: EricksonLopez.Idempotencypublic sealed class MemoryFallbackCache : IFallbackCache
Implements: IFallbackCache
Provides a high-performance, thread-safe, memory-bounded fallback cache implementing `IFallbackCache` using `ConcurrentDictionary<TKey, TValue>` with TTL eviction and capacity controls.
Members (8)
constructorMemoryFallbackCache
public MemoryFallbackCache(IOptions<IdempotencyOptions> options, TimeProvider? timeProvider = null)
Initializes a new instance of the `MemoryFallbackCache` class from configured options.
- options: IOptions<IdempotencyOptions>
- The idempotency options accessor.
- timeProvider: TimeProvider?
- The optional time provider.
constructorMemoryFallbackCache
public MemoryFallbackCache(TimeProvider? timeProvider = null, int maxCapacity = 10_000)
Initializes a new instance of the `MemoryFallbackCache` class with explicit capacity and time provider.
- timeProvider: TimeProvider?
- The time provider for deterministic time computation.
- maxCapacity: int
- The maximum capacity before pruning oldest entries.
methodClear
public void Clear()
Clears all entries from the fallback cache.
methodRelease
public void Release(string key, Guid ownerToken)
Releases an acquired in-flight lease if the owner token matches.
- key: string
- The idempotency cache key.
- ownerToken: Guid
- The lease owner token.
methodRemove
public void Remove(string key)
Removes an entry from the fallback cache.
- key: string
- The idempotency cache key.
methodSet
public void Set(string key, FallbackCacheEntry entry, TimeSpan retentionDuration)
Stores or updates an idempotency response entry in the fallback cache.
- key: string
- The idempotency cache key.
- entry: FallbackCacheEntry
- The response entry to cache.
- retentionDuration: TimeSpan
- The retention duration before eviction.
methodTryAcquire
public bool TryAcquire(string key, string fingerprint, TimeSpan leaseDuration, out Guid ownerToken)
Attempts to acquire an in-flight lease in the fallback cache.
- key: string
- The idempotency cache key.
- fingerprint: string
- The cryptographic fingerprint of the request.
- leaseDuration: TimeSpan
- The lease duration.
- ownerToken: out Guid
- When successful, contains the unique token for the lease owner.
Returns: `true` if the lease was acquired; otherwise, `false`.
methodTryGet
public bool TryGet(string key, out FallbackCacheEntry? entry)
Attempts to retrieve a completed idempotency response entry from the fallback cache.
- key: string
- The idempotency cache key.
- entry: out FallbackCacheEntry?
- When this method returns, contains the cached entry if found and unexpired; otherwise, null.
Returns: `true` if an unexpired entry was found; otherwise, `false`.
class
ScopeHasher
Assembly: EricksonLopez.Idempotency.Abstractionspublic static class ScopeHasher
Provides deterministic hashing and normalization utilities for idempotency scopes.
Members (2)
methodNormalize
public static string Normalize(string rawScope)
Normalizes a scope string, deterministically hashing it with SHA-256 into a lowercase 64-character hexadecimal representation if its length exceeds `MaxScopeLength`.
- rawScope: string
- The raw scope string to normalize.
Returns: The original `rawScope` if its length is less than or equal to 64; otherwise, a deterministic 64-character lowercase hexadecimal SHA-256 hash.
fieldMaxScopeLength
public const int MaxScopeLength
Specifies the maximum allowed character length for an idempotency scope (64 characters).
class
ServiceCollectionExtensions
Assembly: EricksonLopez.Idempotencypublic static class ServiceCollectionExtensions
Provides extension methods for `IServiceCollection` to configure core idempotency services.
Members (2)
methodAddIdempotencyCleanupService
public static IServiceCollection AddIdempotencyCleanupService(this IServiceCollection services, Action<IdempotencyCleanupOptions>? configure = null)
Registers a hosted background service that periodically purges expired idempotency records from the store.
- services: this IServiceCollection
- The `IServiceCollection` to add the service to.
- configure: Action<IdempotencyCleanupOptions>?
- An optional delegate to configure `IdempotencyCleanupOptions`.
Returns: The same service collection instance for method chaining.
methodAddIdempotencyCore
public static IServiceCollection AddIdempotencyCore(this IServiceCollection services, Action<IdempotencyOptions>? configure = null)
Registers core idempotency abstractions, context accessors, serializers, and execution engines in the specified service collection.
- services: this IServiceCollection
- The `IServiceCollection` to add the services to.
- configure: Action<IdempotencyOptions>?
- An optional delegate to configure `IdempotencyOptions`.
Returns: The same service collection instance for method chaining.
enum
StoreFailureMode
Assembly: EricksonLopez.Idempotency.Abstractionspublic enum StoreFailureMode
Specifies the failure handling strategy when the persistent idempotency store encounters an infrastructure failure.
Members (3)
fieldFailClosedGraceful
FailClosedGraceful = 0
Strict financial mode: returns HTTP 503 Service Unavailable with RFC 7807 ProblemDetails and Retry-After. Prevents duplicate execution during database downtime. (Default)
fieldFailOpenWithAudit
FailOpenWithAudit = 1
Permissive mode for non-critical endpoints: bypasses idempotency caching and executes handler unkeyed. Emits OpenTelemetry warnings.
fieldFallbackCache
FallbackCache = 2
High-resilience fallback cache mode: utilizes an in-memory cache to replay responses and maintain idempotency during persistent storage outages.
class
StoreResilienceOptions
Assembly: EricksonLopez.Idempotency.Abstractionspublic sealed class StoreResilienceOptions
Configures resilience policies and failover behaviors for storage operations.
Members (6)
propertyDefaultInFlightRetryAfterSeconds
public int DefaultInFlightRetryAfterSeconds { get; set; }
Gets or sets the base number of seconds for the Retry-After header on 409 in-flight conflicts. Defaults to 2 seconds.
propertyEnableFallbackCache
public bool EnableFallbackCache { get; set; }
Gets or sets a value indicating whether in-memory fallback cache is enabled for resilient replay during store outages. Defaults to `true`.
propertyFallbackCacheRetention
public TimeSpan FallbackCacheRetention { get; set; }
Gets or sets the retention duration for entries stored in the fallback cache. Defaults to 24 hours.
propertyMaxFallbackCacheEntries
public int MaxFallbackCacheEntries { get; set; }
Gets or sets the maximum number of entries maintained in the fallback cache. Defaults to 10,000.
propertyMode
public StoreFailureMode Mode { get; set; }
Gets or sets the failure mode when storage operations fail due to infrastructure errors. Defaults to `StoreFailureMode.FailClosedGraceful`.
propertyStoreUnavailableRetryAfterSeconds
public int StoreUnavailableRetryAfterSeconds { get; set; }
Gets or sets the base number of seconds for the Retry-After header when the store is unavailable. Defaults to 5 seconds.
class
SystemTextJsonIdempotencySerializer
Assembly: EricksonLopez.Idempotencypublic sealed class SystemTextJsonIdempotencySerializer : IIdempotencySerializer
Implements: IIdempotencySerializer
Provides a Native AOT compatible implementation of `IIdempotencySerializer` using `Text.Json`.
Members (4)
constructorSystemTextJsonIdempotencySerializer
public SystemTextJsonIdempotencySerializer()
Initializes a new instance of the `SystemTextJsonIdempotencySerializer` class using default serializer options.
constructorSystemTextJsonIdempotencySerializer
public SystemTextJsonIdempotencySerializer(JsonSerializerOptions options)
Initializes a new instance of the `SystemTextJsonIdempotencySerializer` class with custom options.
- options: JsonSerializerOptions
- The custom serializer options.
methodDeserialize<T>
public T? Deserialize<T>(ReadOnlyMemory<byte> bytes)
Deserializes a raw byte payload into an instance of `T`.
- bytes: ReadOnlyMemory<byte>
- The memory buffer containing the serialized payload bytes.
Returns: The deserialized object instance, or `null` if deserialization produces no value.
methodSerialize<T>
public byte[] Serialize<T>(T value)
Serializes an object value into a raw UTF-8 byte array.
- value: T
- The value to serialize.
Returns: A byte array containing the serialized representation.