AppSurface Search
API Reference

PostgreSql

Type

AppSurfaceDurablePostgreSqlServiceCollectionExtensions

Source

Registers the PostgreSQL durable runtime kernel and its separately opt-in host adapter.

Method

AddAppSurfaceDurablePostgreSql

AppSurfaceDurablePostgreSqlBuilder AddAppSurfaceDurablePostgreSql(this IServiceCollection services, NpgsqlDataSource dispatcherDataSource, NpgsqlDataSource runtimeDataSource, PostgreSqlDurableWorkOptions workOptions, PostgreSqlDurableScheduleOptions scheduleOptions, Action<AppSurfaceDurablePostgreSqlOptions>? configure = null) Source

Registers PostgreSQL durable clients, schema validation, health, drain, and the bounded pump without starting a background worker or applying migrations.

Parameters

  • servicesApplication service collection.
  • dispatcherDataSourcePayload-free dispatcher-role data source used for global discovery only.
  • runtimeDataSourceScoped runtime-role data source used for durable mutations and heartbeats.
  • workOptionsValidated active epoch and StoreId. The configure callback selects the metadata-only wake-hint policy.
  • scheduleOptionsValidated exact runtime role and Schedule clock/lease safety settings.
  • configureOptional process-local activation settings.

Returns

A builder that can explicitly add continuous host activation.

Remarks

The supplied data sources must be distinct and configured with roles that are non-owner and free of BYPASSRLS. The identity check prevents reusing one data source for both roles, but cannot validate the database credentials; see the https://github.com/forge-trust/AppSurface/blob/main/Durable/configure-postgresql-roles.sql. This method performs no network I/O or DDL. Apply migrations with a separate migration-owner data source through IDurableRuntimeSchemaManager before a worker is started.

Method

AddAppSurfaceDurableWorkerHost

IServiceCollection AddAppSurfaceDurableWorkerHost(this IServiceCollection services) Source

Adds the one critical continuous worker loop after passive PostgreSQL durable registration.

Remarks

Calling this method never applies migrations. Startup validates compatibility and the active recovery epoch, then fails closed if either is unsuitable. Repeated calls are idempotent.

Method

AddAppSurfaceDurablePostgreSqlFlowRetention

IServiceCollection AddAppSurfaceDurablePostgreSqlFlowRetention(this IServiceCollection services, NpgsqlDataSource retentionOperatorDataSource) Source

Adds the separately authorized verified Flow-retention client after PostgreSQL durable storage registration.

Parameters

  • servicesApplication service registrations.
  • retentionOperatorDataSourceDedicated scope-bound retention-operator data source.

Returns

The original service collection.

Remarks

The retention operator is a fourth database role, distinct from migration owner, dispatcher, and runtime. It must not share a data source with either existing service role. This method performs no network I/O or DDL; use the schema manager to apply the explicit retention migration and authorize callers before invoking the client. See the https://github.com/forge-trust/AppSurface/blob/main/Durable/configure-postgresql-roles.sql.

Type

PostgreSqlDurableRuntimeRegistration

Source

Captures the one immutable PostgreSQL durable runtime configuration for a service provider.

Parameters

  • DispatcherDataSourcePayload-free dispatcher connection used only for global discovery.
  • RuntimeDataSourceScoped runtime connection used for durable mutations and heartbeats.
  • WorkOptionsValidated active Work-store epoch and wake-hint policy.
  • ScheduleOptionsValidated Schedule clock and lease safety configuration.
  • OptionsValidated process-local activation settings.
  • InstanceIdUnique process-instance fence persisted with runtime heartbeats.
Type

PostgreSqlDurableHostedServiceMarker

Source

Marks that worker-host registration has occurred so repeated composition stays idempotent.

Type

PostgreSqlDurableFlowRetentionMarker

Source

Captures the retention-operator data source for duplicate registration detection.

Type

PostgreSqlDurableScheduleWorkProjector

Source

Requeues a QueueOne Schedule when its materialized Work target reaches terminal truth.

Remarks

The Work store invokes this projector in the same transaction that commits terminal Work truth. That makes a coalesced occurrence eligible immediately, without relying on the Schedule's normal interval to wake it.

The definition row is locked before its dispatch row is updated. Schedule processing takes the same definition lock, so a terminal Work transition cannot race a pending occurrence from one active generation into a later generation.

Method

RequeuePendingOccurrenceAsync

ValueTask RequeuePendingOccurrenceAsync(NpgsqlTransaction transaction, DurableScopeId scopeId, DurableWorkId workId, CancellationToken cancellationToken) Source

Requeues a pending coalesced Schedule occurrence after its Work target becomes terminal.

Parameters

  • transactionThe authoritative Work transition transaction.
  • scopeIdThe durable scope containing the completed Work target.
  • workIdThe terminal Work target that may release one QueueOne Schedule slot.
  • cancellationTokenCancels the database operation before it commits.
Type

PostgreSqlDurableControlClient

Source

Implements application-authorized Work inventory, cancellation, and scope fencing over PostgreSQL.

Remarks

This is an internal provider implementation of the public Provider SPI. Applications must authorize an operation before calling it; opaque scope and aggregate identities are not authorization grants.

Enum

DurableRuntimeSchemaCompatibility

Source

Describes whether the installed durable schema can be used by this package.

Type

DurableRuntimeSchemaApplyResult

Source

Describes one explicit migration application.

Property

PreviousVersion

int PreviousVersion { get; } Source

Gets the version before application.

Property

CurrentVersion

int CurrentVersion { get; } Source

Gets the version after application.

Property

AppliedVersions

IReadOnlyList<int> AppliedVersions { get; } Source

Gets the versions applied by this operation.

Type

PostgreSqlDurableRuntimeHealth

Source

Implements low-cardinality PostgreSQL runtime liveness, drain, and worker-generation fencing.

Method

EnsureSessionAsync

ValueTask<bool> EnsureSessionAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) Source

Creates or verifies this process generation while holding the worker row lock.

Returns

Whether the verified generation is currently draining.

Type

PostgreSqlDurableFlowStore

Owns scoped Flow command and query transactions. Processor transactions live in the processing partial.

Type

PostgreSqlDurableFlowProcessorSettings

Source

Internal settings for one-transition Flow processing.

Type

IPostgreSqlDurableFlowBarrierObserver

Source

Observes committed protocol barriers used by subprocess crash certification.

Remarks

Observers run after the named database boundary commits and must preserve that ordering. They must not access the database or initiate another Flow operation, because observers exist only to certify recovery boundaries such as a deterministic subprocess termination.

Method

ObserveAsync

ValueTask ObserveAsync(string barrier, DurableScopeId scopeId, DurableFlowInstanceId instanceId, long revision, PostgreSqlFlowTelemetryEvidence? traceEvidence, CancellationToken cancellationToken) Source

Observes a committed Flow protocol barrier.

Parameters

  • barrierThe stable name of the committed boundary.
  • scopeIdThe scope that owns the committed Flow transition.
  • instanceIdThe Flow instance that crossed the boundary.
  • revisionThe committed aggregate revision.
  • traceEvidenceValue-free in-process activity evidence available at the committed boundary.
  • cancellationTokenCancellation for observer-only work after the commit.

Returns

A task that completes after the observer records the barrier.

Type

NoOpPostgreSqlDurableFlowBarrierObserver

Source

Provides the production barrier observer that preserves ordering without recording a checkpoint.

Type

PostgreSqlFlowDispatchCandidate

Source

Describes one payload-free Flow or timer dispatch candidate discovered by the dispatcher role.

Parameters

  • DispatchIdThe unique dispatch row identity.
  • ScopeIdThe owning durable scope.
  • KindWhether the candidate evaluates a Flow or resolves a timer.
  • InstanceIdThe target Flow instance.
  • TimerIdThe timer identity for PostgreSqlFlowDispatchKind.Timer candidates.
  • DueAtUtcThe time at which the candidate becomes eligible for processing.
  • ExpectedRevisionThe Flow revision that must still match when the candidate is claimed.
  • PriorityThe stable scheduler priority used when candidates share a due time.
Type

PostgreSqlFlowTelemetryEvidence

Source

Value-free in-process Activity evidence passed only to deterministic crash-test barriers.

Type

PostgreSqlFlowProcessingResult

Source

Reports the observable result of processing a single Flow dispatch candidate.

Parameters

  • OutcomeThe applied, terminal, fenced, or competing-transition outcome.
  • ScopeIdThe scope that owns the candidate.
  • InstanceIdThe Flow instance considered for processing.
  • StateThe resulting Flow state when a durable transition was observed.
  • RevisionThe resulting or observed Flow aggregate revision.
  • ChildWorkIdThe child Work accepted by an activity transition, when one was created.
  • ProblemCodeThe durable safety code when the Flow was suspended or rejected.
Type

PostgreSqlDurableFlowProcessor

Source

Discovers payload-free Flow/timer candidates and commits one replay-safe Flow transition at a time.

Remarks

Discovery uses only the dispatcher-role data source. Claim and mutation use only the scoped runtime-role source. Evaluation runs after the claim transaction releases every database resource.

Enum

PostgreSqlFlowDispatchKind

Source

Classifies the payload-free dispatch row that initiated Flow processing.

Enum

PostgreSqlFlowProcessingOutcome

Source

Describes the durable outcome of attempting to process one Flow dispatch candidate.

Type

IDurableRuntimeExecutionBoundary

Source

Owns the per-invocation execution seam that later tracing integration instruments.

Remarks

Slice 6 deliberately makes this a no-op wrapper. Durable Flow trace context, Activities, links, tags, and exports remain #685's responsibility; its narrow integration can replace this implementation without changing claim, permit, completion, or hosted-lifecycle ownership.

Method

InvokeAsync

ValueTask<DurableEncodedPayload> InvokeAsync(DurablePreparedWorkInvocation invocation, CancellationToken cancellationToken) Source

Invokes one prepared provider operation and returns its registered encoded terminal payload.

Remarks

Forwards cancellation to provider execution and owns no claim, permit, completion, or tracing state.

Type

PostgreSqlDurableFlowClient

Source

Persists application-authorized durable Flow commands and payload-free queries in PostgreSQL.

Remarks

This client does not authenticate callers, apply schema migrations, or start a processor. Applications authorize the trusted DurableScopeId before calling it. The data source must use the scoped runtime role.

Type

DurableRuntimeEpochActivationResult

Source

Reports explicit one-time activation of a store recovery epoch.

Parameters

  • ActiveEpochEpoch activated for this store.
  • ActivatedAtUtcAuthoritative PostgreSQL activation timestamp.
Type

PostgreSqlDurableWorkOptions

Source

Controls PostgreSQL Work acceptance for one validated store and runtime epoch.

Property

RuntimeEpoch

Guid RuntimeEpoch { get; } Source

Gets the active out-of-band recovery epoch.

Property

ExpectedStoreId

Guid ExpectedStoreId { get; } Source

Gets the expected physical durable store identity.

Property

WakeNotificationMode

PostgreSqlDurableWakeNotificationMode WakeNotificationMode { get; } Source

Gets whether acceptance emits a metadata-only PostgreSQL wake hint.

Enum

PostgreSqlDurableWakeNotificationMode

Source

Controls advisory PostgreSQL wake notifications after Work acceptance.

Type

PostgreSqlDurableProtocolCodec

Source

Centralizes fail-closed conversion between PostgreSQL protocol values and Durable contract enums.

Method

ParseWorkState

DurableWorkState ParseWorkState(string state) Source

Projects one persisted Work state or rejects an unknown value as corruption.

Method

FormatProviderSafety

string FormatProviderSafety(DurableProviderSafety safety) Source

Formats one supported provider-safety value for persistence.

Method

ParseProviderSafety

DurableProviderSafety ParseProviderSafety(string value) Source

Parses one persisted provider-safety value or rejects corruption.

Method

FormatClassification

string FormatClassification(DurableDataClassification classification) Source

Formats one supported payload classification for persistence.

Method

ParseClassification

DurableDataClassification ParseClassification(string value) Source

Parses one persisted payload classification or rejects corruption.

Type

PostgreSqlDurableFlowTrace

Source

Identifies transaction-local trace evidence before it is attached to its committed Flow lineage.

Type

PostgreSqlDurableFlowStore

Method

InsertTraceContextAsync

ValueTask<PostgreSqlDurableFlowTrace?> InsertTraceContextAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, DurableScopeId scopeId, DurableFlowInstanceId instanceId, DurableTraceContext? context, string causeKind, CancellationToken cancellationToken) Source

Inserts immutable trace evidence into the caller-owned Flow mutation transaction.

Remarks

The caller must set the scoped runtime context and commit or roll back the supplied transaction. A missing context produces no row and returns null. A non-null context must insert exactly one row or the method throws so the enclosing durable mutation cannot commit partial evidence.

Method

AttachTraceContextAsync

ValueTask AttachTraceContextAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, DurableScopeId scopeId, DurableFlowInstanceId instanceId, PostgreSqlDurableFlowTrace? trace, string? commandId, long revision, Guid? waitId, Guid? timerId, DurableWorkId? workId, CancellationToken cancellationToken) Source

Attaches inserted trace evidence to every Flow record created by the same committed transition.

Remarks

The caller must use the transaction that inserted trace. A missing trace is a no-op for an absent context. Otherwise the Flow instance and history pointer, plus every non-null command, wait, timer, or Work pointer, must each update exactly one row; any mismatch throws so the transaction rolls back rather than committing detached causal evidence.

Type

PostgreSqlDurableFlowRetentionClient

Source

Implements the verified, one-Flow retention lifecycle over a scoped PostgreSQL retention-operator connection.

Remarks

The supplied connection must use the dedicated retention-operator role described by the PostgreSQL role recipe. It is not interchangeable with the runtime or dispatcher data source. The application authorizes every caller, stores archive bytes externally, and decides policy cadence; this client proves only protocol correspondence.

Method

MapManifestCreateProcedureOutcome

DurableOperationResult<DurableRetentionManifestCreateResult>? MapManifestCreateProcedureOutcome(DurableRetentionManifestCreateRequest request, string outcome) Source

Maps stable manifest-create procedure rejections before attempting to read a persisted manifest.

Remarks

Returns null for successful and duplicate outcomes that require a manifest read.

Method

MapLifecycleProcedureOutcome

DurableOperationResult<DurableRetentionMutationResult> MapLifecycleProcedureOutcome(DurableRetentionMutationRequest request, string outcome, string? state, long? sequence) Source

Maps one stable lifecycle procedure response into the public retention mutation result.

Type

PostgreSqlDurableFlowActivityProjector

Source

Projects terminal or suspended child Work truth into its retained parent Flow activity wait in the same transaction.

Type

AppSurfaceDurablePostgreSqlOptions

Source

Configures process-local PostgreSQL durable runtime behavior.

Remarks

These options control activation only. They do not apply migrations, alter durable protocol policy, or replace PostgreSQL leases, recovery epochs, and history as the source of truth. Registering PostgreSQL storage remains passive until AppSurfaceDurablePostgreSqlBuilder.AddWorkerHost is called.

Property

WorkerId

string WorkerId { get; set; } Source

Gets or sets the privacy-safe identity written on short-lived claims and runtime heartbeats.

Remarks

Use a unique value for every concurrently live replica. It is not an authorization credential and must not contain connection details, user input, or other secrets.

Property

SendWakeNotifications

bool SendWakeNotifications { get; set; } Source

Gets or sets whether accepted commands emit metadata-only PostgreSQL wake hints.

Remarks

Polling remains authoritative when hints are disabled, lost, duplicated, delayed, or unavailable.

Property

MaximumItemsPerPass

int MaximumItemsPerPass { get; set; } Source

Gets or sets the maximum completed or committed Turns in one hosted pass.

Property

TimeBudgetPerPass

TimeSpan TimeBudgetPerPass { get; set; } Source

Gets or sets the budget for discovering and starting additional Turns in one hosted pass.

Property

HostedSurfaces

DurableRuntimeSurface HostedSurfaces { get; set; } Source

Gets or sets the durable surfaces activated by this worker instance.

Property

IdlePollingInterval

TimeSpan IdlePollingInterval { get; set; } Source

Gets or sets the maximum delay between authoritative polling passes when no work is immediately due.

Property

TransientFailureDelay

TimeSpan TransientFailureDelay { get; set; } Source

Gets or sets the bounded delay before retrying a transient store or listener failure.

Property

HeartbeatStaleAfter

TimeSpan HeartbeatStaleAfter { get; set; } Source

Gets or sets how old a heartbeat may become before health reports the worker as stale.

Property

ShutdownReserve

TimeSpan ShutdownReserve { get; set; } Source

Gets or sets host shutdown time reserved for drain persistence and runtime cleanup.

Remarks

Hosted startup validates this reserve against HostOptions.ShutdownTimeout. A pass admitted by the host receives only the remaining time, while an externally activated pass retains its own caller-supplied budget.

Type

PostgreSqlDurableScheduleProcessRequest

Source

Requests one bounded, manually invoked PostgreSQL Schedule processing pass.

Remarks

This is a passive provider operation. Applications may call it from an external trigger or test, but must not loop it in an ASP.NET request or register hosted work; hosted activation requires the explicit AddWorkerHost() opt-in.

Property

LeaseOwner

string LeaseOwner { get; } Source

Gets the opaque processor identity recorded on a transient dispatch lease.

Property

MaximumSchedules

int MaximumSchedules { get; } Source

Gets the maximum number of Schedule rows the pass may claim.

Type

PostgreSqlDurableScheduleProcessResult

Source

Reports the durable facts produced by one bounded Schedule processing pass.

Property

ClaimedSchedules

int ClaimedSchedules { get; } Source

Gets the number of payload-free dispatch rows claimed by this pass.

Property

RecordedOccurrences

int RecordedOccurrences { get; } Source

Gets the number of new or coalesced Schedule occurrence facts recorded.

Property

MaterializedWorkTargets

int MaterializedWorkTargets { get; } Source

Gets the number of Work target identities materialized by this pass.

Property

SuspendedSchedules

int SuspendedSchedules { get; } Source

Gets the number of Schedules suspended by a safety fence.

Type

PostgreSqlDurableWorkOperatorClient

Source

Implements the internal PostgreSQL operator path over the landed provider contracts.

Remarks

Applications must authorize every request before this client is called.

Type

DurableRuntimeTurnScheduler

Source

Maintains process-local fair selection order for bounded runtime Turns.

Type

PostgreSqlDurableHostedService

Source

Host lifecycle adapter that schedules the one authoritative bounded PostgreSQL runtime pump.

Remarks

This service is registered only by explicit worker-host composition. It does not apply schema migrations and does not own durable correctness: the store still owns claims, leases, permits, fencing, and durable history.

Type

PostgreSqlDurableRuntimeSchemaManager

Source

Implements explicit package-owned durable schema operations for PostgreSQL.

Property

RequiredVersion

int RequiredVersion { get; } Source

Gets the schema version required by this package.

Type

AppSurfaceDurablePostgreSqlBuilder

Source

Continues PostgreSQL durable registration while keeping storage and continuous activation separate.

Method

AddWorkerHost

AppSurfaceDurablePostgreSqlBuilder AddWorkerHost() Source

Adds the single critical host adapter that continuously invokes the bounded runtime pump.

Remarks

Use this only in a continuously live worker process. Query-only hosts, migration tools, tests, and scale-to-zero deployments keep storage registration passive and may invoke IDurableRuntimePump from their own activator instead.

Property

Services

IServiceCollection Services { get; } Source

Gets the application service collection under configuration.

Type

IDurableWorkTransactionWriter

Source

Accepts durable Work through the caller's exact active PostgreSQL transaction.

Remarks

The writer never opens, commits, rolls back, replaces, or disposes the supplied transaction. Domain state and Work acceptance therefore commit or roll back together in the same database.

Method

EnqueueAsync

ValueTask<DurableOperationResult<DurableWorkAcceptance>> EnqueueAsync(NpgsqlTransaction transaction, DurableWorkRequest request, CancellationToken cancellationToken = default) Source

Writes one durable acceptance without taking ownership of the transaction.

Parameters

  • transactionCaller-owned active Npgsql transaction.
  • requestValidated Work request.
  • cancellationTokenCancellation token.

Returns

The stable new or duplicate acceptance, or an actionable domain problem.

Exceptions

  • ArgumentNullExceptionThrown when transaction or request is null.
  • InvalidOperationExceptionThrown when the transaction is disposed, inactive, closed, or targets a different PostgreSQL store.
  • DurableRuntimeSchemaExceptionThrown with safe schema status when the durable schema is absent or incompatible. When a PostgreSQL error exposed the missing schema, Exception.InnerException retains that original failure.
  • NpgsqlExceptionThe original PostgreSQL or transport failure. The caller must roll back the transaction.
Type

PostgreSqlDurableScheduleClient

Source

PostgreSQL implementation of the durable Schedule client.

Remarks

This client persists Schedule command, generation, and occurrence facts but does not start a hosted loop. Use PostgreSqlDurableScheduleProcessor to run one bounded, manually invoked due pass. The initial implementation admits Work targets only because it can atomically compose the existing caller-owned Work writer. Callers must authorize the Schedule scope before invoking this client. Configure distinct non-owner, non- BYPASSRLS dispatcher and runtime login roles with the documented https://github.com/forge-trust/AppSurface/blob/main/Durable/configure-postgresql-roles.sql, and apply schema version 4 before accepting Schedule work. Hosted activation is intentionally deferred; this client and processor never register or start a background loop.

Type

DurableRuntimeSchemaException

Source

Indicates a missing, incompatible, or inconsistent durable PostgreSQL schema.

Property

Status

DurableRuntimeSchemaStatus Status { get; } Source

Gets the incompatible schema status.

Type

PostgreSqlDurableWorkTransactionWriter

Source

Writes durable Work directly into a caller-owned Npgsql transaction.

Type

DurableRuntimeEpochRotationResult

Source

Reports an explicit compare-and-swap recovery-epoch rotation.

Parameters

  • PreviousEpochEpoch active before rotation.
  • ActiveEpochNew epoch fencing prior runtimes.
  • RotatedAtUtcAuthoritative PostgreSQL rotation timestamp.
Type

DurableRuntimeSchemaStatus

Source

Reports the durable PostgreSQL schema identity, version, epoch, and compatibility.

Property

Compatibility

DurableRuntimeSchemaCompatibility Compatibility { get; } Source

Gets the compatibility verdict.

Property

StoreId

Guid StoreId { get; } Source

Gets the immutable store identity, or empty when unavailable.

Property

ActiveRuntimeEpoch

Guid? ActiveRuntimeEpoch { get; } Source

Gets the active recovery epoch, or null before explicit initialization.

Property

InstalledVersion

int InstalledVersion { get; } Source

Gets the highest installed migration version.

Property

RequiredVersion

int RequiredVersion { get; } Source

Gets the schema version required by this package.

Property

MinimumReaderVersion

int MinimumReaderVersion { get; } Source

Gets the oldest runtime protocol allowed to read.

Property

MaximumReaderVersion

int MaximumReaderVersion { get; } Source

Gets the newest runtime protocol allowed to read.

Property

MinimumWriterVersion

int MinimumWriterVersion { get; } Source

Gets the oldest runtime protocol allowed to write.

Property

MaximumWriterVersion

int MaximumWriterVersion { get; } Source

Gets the newest runtime protocol allowed to write.

Property

AppliedVersions

IReadOnlyList<int> AppliedVersions { get; } Source

Gets an immutable copy of ordered applied migration versions.

Property

PendingVersions

IReadOnlyList<int> PendingVersions { get; } Source

Gets an immutable copy of ordered pending migration versions.

Property

Problem

string? Problem { get; } Source

Gets the actionable incompatibility explanation, when present.

Property

IsCompatible

bool IsCompatible { get; } Source

Gets whether schema reads and writes may begin.

Type

PostgreSqlDurableScheduleOptions

Source

Controls the PostgreSQL Schedule processor's runtime-role and temporal safety fences.

Remarks

The role name is checked with current_user before a Schedule processor sets its scoped RLS setting or bridges an occurrence to Work. The safety window limits how far a single database-clock observation may advance an interval cursor; a larger jump suspends rather than consumes future occurrences.

Property

RuntimeRole

string RuntimeRole { get; } Source

Gets the exact role required before Schedule bridge scope is set.

Property

MaximumClockAdvance

TimeSpan MaximumClockAdvance { get; } Source

Gets the maximum safe single-pass database-clock advance beyond a stored cursor.

Property

LeaseDuration

TimeSpan LeaseDuration { get; } Source

Gets the dispatcher-owned Schedule discovery lease duration, capped at ten minutes.

Type

PostgreSqlDurableRuntimePump

Source

Runs one provider-backed PostgreSQL Pass through Work, Flow, and Schedule Turns.

Remarks

One pass is deliberately sequential and process-local. PostgreSQL retains all authoritative discovery, claim, lease, permit, completion, schedule, scope, and epoch decisions. The internal execution boundary is intentionally uninstrumented so #685 can attach Activity and ActivityLink behavior without taking ownership of this lifecycle.

Type

AppSurfaceDurablePostgreSqlModule

Source

Declares the host-neutral durable module dependency for applications configuring PostgreSQL explicitly.

Remarks

This module does not create data sources, choose database credentials, apply migrations, or start a worker. Call AppSurfaceDurablePostgreSqlServiceCollectionExtensions.AddAppSurfaceDurablePostgreSql with the application's reviewed dispatcher and runtime data sources, then opt into AddWorkerHost only where continuous activation is intended.

Type

IDurableRuntimeSchemaManager

Source

Provides explicit deployment operations for the AppSurface durable PostgreSQL schema.

Remarks

Use a migration-owner data source. Runtime registration may validate status but must never apply DDL.

Method

GetStatusAsync

ValueTask<DurableRuntimeSchemaStatus> GetStatusAsync(CancellationToken cancellationToken = default) Source

Reads installed migration metadata without modifying the database.

Parameters

  • cancellationTokenToken that cancels the database read.

Returns

An immutable status snapshot. Missing and incompatible schemas are returned as status, not exceptions.

Exceptions

  • Npgsql.NpgsqlExceptionPostgreSQL rejects the read or the connection fails.
  • OperationCanceledExceptionThe operation is canceled.
Method

GenerateScript

string GenerateScript(int fromVersion = 0) Source

Generates deterministic SQL for migrations newer than the exact reviewed fromVersion.

Parameters

  • fromVersionLast installed migration version, from zero through PostgreSqlDurableRuntimeSchemaManager.RequiredVersion.

Returns

A migration-owner script that acquires and releases the package advisory lock.

Exceptions

  • ArgumentOutOfRangeExceptionfromVersion is outside the supported range.

Remarks

The result is forward-only and is not safe to rerun after any selected migration commits.

Method

ApplyAsync

ValueTask<DurableRuntimeSchemaApplyResult> ApplyAsync(CancellationToken cancellationToken = default) Source

Applies pending migrations while holding the package session advisory lock.

Parameters

  • cancellationTokenToken that cancels lock acquisition or migration application.

Returns

The version range observed before and after application and the ordered versions applied by this call.

Exceptions

  • DurableRuntimeSchemaExceptionThe installed schema is inconsistent or newer than this package.
  • Npgsql.NpgsqlExceptionPostgreSQL rejects a migration or the connection fails.
  • OperationCanceledExceptionThe operation is canceled.
Method

ValidateAsync

ValueTask ValidateAsync(CancellationToken cancellationToken = default) Source

Fails when the installed schema cannot be used without changing it.

Parameters

  • cancellationTokenToken that cancels the database read.

Returns

A task that completes when the installed schema is compatible.

Exceptions

  • DurableRuntimeSchemaExceptionThe schema is not compatible.
  • Npgsql.NpgsqlExceptionPostgreSQL rejects the read or the connection fails.
  • OperationCanceledExceptionThe operation is canceled.
Method

InitializeRuntimeEpochAsync

ValueTask<DurableRuntimeEpochActivationResult> InitializeRuntimeEpochAsync(Guid initialEpoch, string actorId, string reasonCode, CancellationToken cancellationToken = default) Source

Activates the first non-empty store recovery epoch exactly once.

Parameters

  • initialEpochDeployment-selected initial epoch.
  • actorIdPrivacy-safe operator code of 1-200 ASCII letters, digits, -, _, ., or :.
  • reasonCodePrivacy-safe activation code of 1-120 ASCII letters, digits, -, _, ., or :.
  • cancellationTokenToken that cancels lock acquisition or activation.

Returns

The activated epoch and database observation time.

Exceptions

  • ArgumentExceptionThe epoch is empty, or an operator code is empty, too long, or outside the opaque-code grammar.
  • DurableRuntimeSchemaExceptionThe installed schema is not compatible.
  • InvalidOperationExceptionA runtime epoch is already active.
  • Npgsql.NpgsqlExceptionPostgreSQL rejects the mutation or the connection fails.
  • OperationCanceledExceptionThe operation is canceled.
Method

RotateRuntimeEpochAsync

ValueTask<DurableRuntimeEpochRotationResult> RotateRuntimeEpochAsync(Guid expectedActiveEpoch, Guid newActiveEpoch, string actorId, string reasonCode, CancellationToken cancellationToken = default) Source

Atomically rotates the recovery epoch when the expected epoch remains active.

Parameters

  • expectedActiveEpochEpoch that must still be active when the mutation commits.
  • newActiveEpochDistinct, non-empty replacement epoch.
  • actorIdPrivacy-safe operator code of 1-200 ASCII letters, digits, -, _, ., or :.
  • reasonCodePrivacy-safe rotation code of 1-120 ASCII letters, digits, -, _, ., or :.
  • cancellationTokenToken that cancels lock acquisition or rotation.

Returns

The previous and active epochs and database observation time.

Exceptions

  • ArgumentExceptionAn epoch is empty, the epochs match, or an operator code violates its bounds or grammar.
  • DurableRuntimeSchemaExceptionThe installed schema is not compatible.
  • InvalidOperationExceptionexpectedActiveEpoch is no longer active.
  • Npgsql.NpgsqlExceptionPostgreSQL rejects the mutation or the connection fails.
  • OperationCanceledExceptionThe operation is canceled.
Type

PostgreSqlDurableWorkClient

Source

Accepts durable Work in a short provider-owned PostgreSQL transaction.

Type

DurableRuntimeAdmissionGate

Source

Coordinates process-local pass admission with synchronous shutdown initiation.

Method

TryEnter

bool TryEnter() Source

Returns whether a new pass may start without acquiring or reserving any separate release handle.

Remarks

A successful result permits admission only; callers must still serialize active passes independently.

Method

Close

void Close() Source

Rejects future admissions without waiting for or cancelling an in-flight pass.

Method

Reopen

void Reopen() Source

Allows future admissions after a controlled drain rollback or recovery decision.

Type

PostgreSqlDurableScheduleProcessor

Source

Runs one bounded, manually invoked PostgreSQL Schedule due pass.

Remarks

The processor first claims a payload-free dispatch lease through the dispatcher data source, then opens a separate scoped runtime transaction to record and bridge Schedule facts. It does not start a loop, execute Work, invoke a provider, or start Flow targets. Cancellation is observed before each additional lease; work already committed by a prior claim remains durable.

Method

ProcessDueAsync

ValueTask<PostgreSqlDurableScheduleProcessResult> ProcessDueAsync(PostgreSqlDurableScheduleProcessRequest request, CancellationToken cancellationToken = default) Source

Claims and processes up to the requested number of eligible Schedule dispatch rows.

Parameters

  • requestBounded pass identity and maximum claim count.
  • cancellationTokenCancels before the next lease; it never undoes a committed Schedule fact.

Returns

Counts of claimed Schedule rows and resulting durable facts. An empty pass returns zero counts.

Type

PostgreSqlDurableWorkStore

Source

Provides PostgreSQL persistence operations for the durable Work protocol.

Remarks

This internal class supports controlled derived test seams. Overrides must preserve claim identity, runtime epoch and scope-generation fences, lease ownership, dispatch projection, Work history, and transaction guarantees.

Method

AcceptFlowChildAsync

ValueTask<DurableOperationResult<DurableWorkAcceptance>> AcceptFlowChildAsync(NpgsqlTransaction transaction, DurableWorkRequest request, Guid runtimeEpoch, Guid expectedStoreId, bool sendWakeNotification, string derivedActivityId, CancellationToken cancellationToken) Source

Accepts a Flow child Work with an immutable activity identity while retaining the ordinary Work protocol. The caller owns the surrounding transaction and must register the parent wait before commit.

Method

RenewLeaseAsync

ValueTask<PostgreSqlDurableWorkClaim?> RenewLeaseAsync(PostgreSqlDurableWorkClaim claim, CancellationToken cancellationToken = default) Source

Renews the active lease held by a fenced Work claim.

Parameters

  • claimClaim that identifies the active runtime epoch, scope, Work attempt, and lease owner.
  • cancellationTokenToken that cancels database operations.

Returns

The renewed claim with its current revision, expiry, and cancellation state, or null when an epoch, scope, attempt, owner, or lease fence is stale.

Remarks

Overrides must preserve the current-epoch and active-scope checks, lease and dispatch consistency, durable history semantics, and transactional atomicity of the renewal attempt.

Method

ValidateSchemaRemovalForTestingAsync

ValueTask ValidateSchemaRemovalForTestingAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid? expectedStoreId, CancellationToken cancellationToken, Func<ValueTask> afterExistence) Source

Validates schema removal after the successful existence probe without relying on timing.

Parameters

  • connectionOpen connection that owns the caller transaction.
  • transactionCaller-owned transaction used for every validation query.
  • expectedStoreIdExpected durable store identity, or null to omit identity validation.
  • cancellationTokenToken that cancels validation database operations.
  • afterExistenceTest callback invoked after the catalog probe and before metadata is read.

Remarks

This test-only seam preserves the callback-free production validation contract.

Method

CreateMissingSchemaException

DurableRuntimeSchemaException CreateMissingSchemaException(PostgresException innerException) Source

Preserves the PostgreSQL failure that exposed a missing schema without copying its server text.