Skip to content
RelKit
Esc
↑↓navigate↵open⌘Jpreview
On this page

Postgres API

Generated public TypeScript reference for @relkit/postgres.

For configuration and examples, read postgres, railway, vercel.

Public imports

  • @relkit/postgres — 10 exports
  • @relkit/postgres/runtime — 18 exports
  • @relkit/postgres/drizzle — 4 exports

All exported APIs

Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API’s inline sample, a maintained repository usage, or the shared module walkthrough.

API Kind Import from Example
BackgroundFiber Type @relkit/postgres/runtime Module example
ClaimedOccurrence Type @relkit/postgres/runtime Module example
createPostgresEventProvider Value @relkit/postgres/runtime API example
createPostgresJobsRuntime Value @relkit/postgres/runtime API example
outbox Value @relkit/postgres/drizzle API example
OutboxOptions Type @relkit/postgres/drizzle Module example
OutboxTransaction Type @relkit/postgres/drizzle Module example
PostgresConnectionOptions Type @relkit/postgres Module example
PostgresDatabase Type @relkit/postgres/runtime Module example
PostgresDatabaseOptions Type @relkit/postgres/runtime Module example
postgresEvent Value @relkit/postgres API example
PostgresEventAdapter Type @relkit/postgres Module example
PostgresEventOptions Type @relkit/postgres Module example
PostgresEventProvider Type @relkit/postgres/runtime Source example
PostgresEventProviderOptions Type @relkit/postgres/runtime Module example
PostgresEventTrigger Type @relkit/postgres/runtime Source example
PostgresFaults Type @relkit/postgres/runtime Module example
postgresJob Value @relkit/postgres API example
PostgresJobAdapter Type @relkit/postgres Module example
PostgresJobOptions Type @relkit/postgres Module example
PostgresJobsRuntime Type @relkit/postgres/runtime Source example
PostgresJobsRuntimeOptions Type @relkit/postgres/runtime Module example
PostgresJobWorker Type @relkit/postgres/runtime Module example
PostgresOutbox Type @relkit/postgres/drizzle Module example
PostgresTableOptions Type @relkit/postgres Module example
PostgresTables Type @relkit/postgres Module example
PostgresTaskDefinition Type @relkit/postgres/runtime Module example
PostgresUrlInput Type @relkit/postgres Module example
PostgresWorkerHandle Type @relkit/postgres/runtime Module example
PostgresWorkerLoopOptions Type @relkit/postgres/runtime Module example
PostgresWorkerRegistration Type @relkit/postgres/runtime Module example
runtimeIntegration Value @relkit/postgres/runtime Source example

index.ts

“./outbox.js” (namespace export)

Re-exports all named exports from the “./outbox.js” module.

Signature

export * from "./outbox.js";

Source

outbox.ts

Transactional outbox for Drizzle. outbox(tx).publish(event, payload) validates the payload against the event contract and writes the envelope and its per-consumer deliveries with one statement on the caller’s Drizzle transaction, so the event commits or rolls back with the transaction’s other writes. Consumers run later from the Postgres event provider’s loops.

“./outbox.types.js” (namespace export)

Re-exports all named exports from the “./outbox.types.js” module.

Signature

export * from "./outbox.types.js";

Source

outbox

Binds the outbox to a Drizzle transaction (or database) on the backend’s Postgres database.

Example

await db.transaction(async (tx) => outbox(tx).publish(orderPlaced, { orderId }));

Signature

declare const outbox: <Result>(
  transaction: OutboxTransaction<Result>,
  options?: OutboxOptions,
) => PostgresOutbox;

Source

outbox.types.ts

Contracts of the Drizzle transactional outbox.

OutboxOptions (interface)

Outbox settings; they must match the event provider’s profile and tables.

Signature

export interface OutboxOptions extends PostgresTableOptions {
  /** Event profile used when the event contract names none; defaults to `default`. */
  readonly profile?: string;
}

Source

OutboxTransaction (interface)

Anything with Drizzle’s execute(sql): a Postgres database or transaction.

Signature

export interface OutboxTransaction<Result> {
  readonly execute: (query: SQL) => PromiseLike<Result>;
}

Source

PostgresOutbox (interface)

The outbox bound to one transaction.

Signature

export interface PostgresOutbox {
  /**
   * Writes one event on the bound transaction.
   * @param event - Event contract; the payload is validated against its schema.
   * @param payload - Event payload.
   * @param options - Optional ordering key and attributes.
   * @returns The persisted envelope; consumers see it only if the transaction commits.
   */
  readonly publish: <Id extends string, Version extends number, Input>(
    event: EventDescriptor<Id, Version, Input>,
    payload: Input,
    options?: EventPublishOptions,
  ) => Promise<UnknownEventEnvelope & { readonly eventId: Id; readonly version: Version }>;
}

Source

events-envelope.ts

Builds the event envelope that publication persists in the outbox. Both the provider’s publish and the Drizzle outbox use it, so an event written inside an application transaction is indistinguishable from one published directly. Pure construction; no connection is opened.

createEventEnvelope

Creates a new envelope for one publication.

Example

createEventEnvelope("orders.placed", 1, { orderId: "o-1" }).instanceId.startsWith("event-");

Signature

declare const createEventEnvelope: (
  eventId: string,
  version: number,
  payload: UnknownEventEnvelope["payload"],
  options?: EventPublishOptions,
  propagation?: TracePropagation,
) => UnknownEventEnvelope;

Source

index.ts

“./providers.types.js” (namespace export)

Re-exports all named exports from the “./providers.types.js” module.

Signature

export * from "./providers.types.js";

Source

PostgresEventAdapter

Events provider adapter selected with postgresEvent().

Signature

type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;

Source

PostgresJobAdapter

Jobs provider adapter selected with postgresJob().

Signature

type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;

Source

PostgresTableOptions

Where the backend’s tables live; both names are validated SQL identifiers.

Signature

export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}

Source

PostgresTables

Fully qualified, quoted table names for one backend namespace.

Signature

export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}

Source

postgresEvent

Signature

declare const postgresEvent: (options?: PostgresEventOptions) => PostgresEventAdapter;

Source

postgresJob

Signature

declare const postgresJob: (options?: PostgresJobOptions) => PostgresJobAdapter;

Source

providers.ts

Authoring entry for the Postgres backend. postgresJob() and postgresEvent() build the provider adapters an application selects in defineApp({ jobs, events }). They validate options and serialize connection and behavior data only; the runtime entry opens connections when the application starts.

“./providers.types.js” (namespace export)

Re-exports all named exports from the “./providers.types.js” module.

Signature

export * from "./providers.types.js";

Source

PostgresEventAdapter (type alias)

Events provider adapter selected with postgresEvent().

Signature

type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;

Source

PostgresJobAdapter (type alias)

Jobs provider adapter selected with postgresJob().

Signature

type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;

Source

postgresConnectionContract

Connection fields both adapters accept.

Signature

declare const postgresConnectionContract: ProviderConnectionContract;

Source

postgresEvent

Selects durable Postgres events with per-consumer delivery for an events profile.

Throws

TypeError for unknown options or an invalid URL, identifier or duration.

Example

const events = postgresEvent({ url: env.secret("DATABASE_URL") });

Signature

declare const postgresEvent: (options?: PostgresEventOptions) => PostgresEventAdapter;

Source

postgresIntegration

Integration reference shared by both adapters.

Signature

declare const postgresIntegration: IntegrationReference<"postgres">;

Source

postgresJob

Selects durable Postgres jobs and schedules for a jobs profile.

Throws

TypeError for unknown options or an invalid URL, identifier or duration.

Example

const jobs = postgresJob({ url: env.secret("DATABASE_URL") });

Signature

declare const postgresJob: (options?: PostgresJobOptions) => PostgresJobAdapter;

Source

providers.types.ts

Authoring contracts for the Postgres jobs and events providers selected in defineApp.

PostgresConnectionOptions (interface)

Connection and table settings shared by the jobs and events providers.

Signature

export interface PostgresConnectionOptions extends PostgresTableOptions {
  /** Postgres connection string; at runtime `RELKIT_POSTGRES_URL` overrides it. */
  readonly url?: PostgresUrlInput;
  /** How long a worker owns a leased run or delivery before another may take it, in ms. */
  readonly leaseMs?: number;
  /** How often idle workers look for due work, in ms. */
  readonly pollIntervalMs?: number;
}

Source

PostgresEventOptions (interface)

Options for postgresEvent().

Signature

export interface PostgresEventOptions extends PostgresConnectionOptions {}

Source

PostgresJobOptions (interface)

Options for postgresJob(): connection settings plus the common jobs service options.

Signature

export interface PostgresJobOptions extends PostgresConnectionOptions, JobsServiceOptions {}

Source

PostgresUrlInput (type alias)

A connection string given inline or as an environment binding.

Signature

type PostgresUrlInput =
  | string
  | BindingValueRef<string, string, "string">
  | BindingValueRef<string, string, "secret-string">;

Source

database.ts

Owns one Postgres connection pool for a backend namespace. The pool is a @effect/sql-pg Layer held by a ManagedRuntime; acquiring it applies the idempotent DDL inside a transaction holding an advisory lock, so instances that start together create the tables once. Background loops are forked into the same runtime and interrupted before the pool closes.

“./database.types.js” (namespace export)

Re-exports all named exports from the “./database.types.js” module.

Signature

export * from "./database.types.js";

Source

PostgresBackendError (class)

A SQL statement of the Postgres backend failed.

Signature

declare class PostgresBackendError

Source

backendOperation

Tags SQL failures of one backend operation.

Signature

declare const backendOperation: (
  operation: string,
) => <A, E, R>(
  effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, Exclude<E, SqlError> | PostgresBackendError, R>;

Source

openPostgresDatabase

Opens the pool lazily; the first run acquires it and creates the schema.

Example

const database = openPostgresDatabase({ url: process.env.DATABASE_URL! });

Signature

declare const openPostgresDatabase: (options: PostgresDatabaseOptions) => PostgresDatabase;

Source

database.types.ts

Contracts for the shared Postgres connection owner used by the jobs and events runtimes.

BackgroundFiber (type alias)

A background loop; it can only fail when the pool or schema cannot be acquired.

Signature

type BackgroundFiber = Fiber.Fiber<void, SqlError>;

Source

PostgresDatabase (interface)

A pooled connection plus the background fibers that depend on it.

Signature

export interface PostgresDatabase {
  /** Quoted table names for this namespace. */
  readonly tables: PostgresTables;
  /**
   * Runs one SQL workflow; the schema is created before the first one runs.
   * @param effect - Workflow requiring the SQL client.
   * @param signal - Optional caller cancellation.
   * @returns The workflow result; failures reject the Promise.
   */
  readonly run: <A, E>(effect: Effect.Effect<A, E, SqlClient>, signal?: AbortSignal) => Promise<A>;
  /**
   * Starts a background workflow that `close()` interrupts before releasing the pool.
   * @param effect - Never-failing loop requiring the SQL client.
   * @returns The running fiber.
   */
  readonly fork: (effect: Effect.Effect<void, never, SqlClient>) => BackgroundFiber;
  /** Interrupts background fibers, then closes the pool. Safe to call twice. */
  readonly close: () => Promise<void>;
}

Source

PostgresDatabaseOptions (interface)

Connection settings for one backend namespace.

Signature

export interface PostgresDatabaseOptions extends PostgresTableOptions {
  /** Postgres connection string. */
  readonly url: string;
  /** Pool size; defaults to 10. */
  readonly maxConnections?: number;
}

Source

events-provider.ts

The Postgres event provider. Registering a durable trigger records its consumer row; publish persists the envelope and one delivery per consumer in a single statement; consumer loops lease due deliveries with FOR UPDATE SKIP LOCKED, invoke the trigger, and complete, retry or dead-letter each delivery on its own under the trigger’s retry policy. Delivery is at least once: a consumer that crashes after its handler succeeded is invoked again when its lease expires.

“./events-provider.types.js” (namespace export)

Re-exports all named exports from the “./events-provider.types.js” module.

Signature

export * from "./events-provider.types.js";

Source

createPostgresEventProvider

Creates the Postgres event provider for one profile.

Throws

TypeError when neither url nor database is given.

Example

const events = createPostgresEventProvider({ url: process.env.DATABASE_URL! });

Signature

declare const createPostgresEventProvider: (
  options: PostgresEventProviderOptions,
) => PostgresEventProvider;

Source

events-provider.types.ts

Contracts of the Postgres event provider: options, trigger bindings and the provider surface.

PostgresEventProvider (interface)

The Postgres event provider.

Signature

export interface PostgresEventProvider extends EventProvider {
  readonly database: PostgresDatabase;
  readonly registerContract: (contract: object) => Promise<void>;
  readonly registerTrigger: (binding: PostgresEventTrigger) => Promise<void>;
  /** Runs at most one due delivery per durable consumer; resolves the number delivered. */
  readonly deliverDue: () => Promise<number>;
  /** Starts the consumer loop; idempotent. */
  readonly startConsumers: () => void;
  readonly close: () => Promise<void>;
}

Source

PostgresEventProviderOptions (interface)

Options for createPostgresEventProvider.

Signature

export interface PostgresEventProviderOptions extends Partial<PostgresDatabaseOptions> {
  /** Shared connection owner; when given, `url` is ignored and `close()` leaves it open. */
  readonly database?: PostgresDatabase;
  /** Event provider profile; consumers and deliveries are namespaced by it. Defaults to `default`. */
  readonly profile?: string;
  /** Delivery lease duration in ms; defaults to 30 000. */
  readonly leaseMs?: number;
  /** Idle polling interval of consumer loops in ms; defaults to 1 000. */
  readonly pollIntervalMs?: number;
  /** Run consumer loops in this instance; false for `api`-role instances. Defaults to true. */
  readonly consumers?: boolean;
  /** Prefix of delivery owner tokens. */
  readonly workerId?: string;
}

Source

PostgresEventTrigger (interface)

The trigger binding the runtime registers for each event-only function.

Signature

export interface PostgresEventTrigger {
  readonly id: string;
  readonly eventId: string;
  readonly eventVersion: number;
  /** `durable` triggers get persisted deliveries; `ephemeral` ones run in-process after publish. */
  readonly delivery: "durable" | "ephemeral";
  /** Retry policy: `maxAttempts`, `initialDelayMs`, `maxDelayMs`, `multiplier`, `jitter`. */
  readonly retry?: JsonValue;
  readonly timeoutMs?: number;
  readonly invoke: (
    envelope: UnknownEventEnvelope,
    options?: { readonly replayed?: boolean; readonly deadlineMs?: number },
  ) => Promise<JsonValue | void | object>;
}

Source

events-store.ts

SQL for durable events. Publication is one statement: it inserts the envelope into the outbox and, from the registered consumers of that event version, one delivery row per consumer, so the event and its deliveries commit or roll back together. Each delivery is leased, retried and dead-lettered on its own, so one failing consumer never re-runs another.

DeliveryRow

A leased delivery joined with its outbox envelope.

Signature

export interface DeliveryRow {
  readonly instance_id: string;
  readonly trigger_id: string;
  /** One-based attempt this lease runs. */
  readonly attempt: number;
  readonly envelope: UnknownEventEnvelope;
}

Source

leaseDelivery

Leases the oldest due delivery of one consumer, including ones whose lease expired.

Signature

declare const leaseDelivery: (
  tables: PostgresTables,
  profile: string,
  triggerId: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<DeliveryRow | undefined, PostgresBackendError, SqlClient.SqlClient>;

Source

publishEvent

Persists an envelope and fans it out to the event’s registered consumers.

Signature

declare const publishEvent: (
  tables: PostgresTables,
  profile: string,
  envelope: UnknownEventEnvelope,
) => Effect.Effect<number, PostgresBackendError, SqlClient.SqlClient>;

Source

registerConsumer

Records a durable consumer so later publications create deliveries for it.

Signature

declare const registerConsumer: (
  tables: PostgresTables,
  profile: string,
  consumer: { readonly triggerId: string; readonly eventId: string; readonly version: number },
) => Effect.Effect<void, PostgresBackendError, SqlClient.SqlClient>;

Source

settleDelivery

Settles a leased delivery, fenced on its owner token.

Signature

declare const settleDelivery: (
  tables: PostgresTables,
  delivery: Pick<DeliveryRow, "instance_id" | "trigger_id">,
  owner: string,
  outcome:
    | { readonly state: "completed" }
    | {
        readonly state: "delayed" | "dead-lettered";
        readonly delayMs: number;
        readonly failure: JobFailureMetadata;
      },
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;

Source

events-store.types.ts

Row shape returned when a consumer leases an event delivery.

DeliveryRow (interface)

A leased delivery joined with its outbox envelope.

Signature

export interface DeliveryRow {
  readonly instance_id: string;
  readonly trigger_id: string;
  /** One-based attempt this lease runs. */
  readonly attempt: number;
  readonly envelope: UnknownEventEnvelope;
}

Source

index.ts

“./database.types.js” (namespace export)

Re-exports all named exports from the “./database.types.js” module.

Signature

export * from "./database.types.js";

Source

“./events-provider.types.js” (namespace export)

Re-exports all named exports from the “./events-provider.types.js” module.

Signature

export * from "./events-provider.types.js";

Source

“./jobs-runtime.types.js” (namespace export)

Re-exports all named exports from the “./jobs-runtime.types.js” module.

Signature

export * from "./jobs-runtime.types.js";

Source

ClaimedOccurrence

One occurrence this pass enqueued (or skipped under overlap: "skip").

Signature

export interface ClaimedOccurrence {
  readonly scheduleId: string;
  readonly occurrenceAt: string;
  /** The enqueued run, or `skipped` when an earlier run of the schedule was still active. */
  readonly runId: string;
}

Source

PostgresJobWorker

Pull worker plus a close operation for its heartbeats.

Signature

export interface PostgresJobWorker extends NativeTaskWorker {
  /** Stops heartbeats without settling held runs; their leases then expire. */
  readonly close: () => Promise<void>;
  /** Runs currently leased by this worker. */
  readonly active: () => readonly string[];
}

Source

createPostgresEventProvider

Signature

declare const createPostgresEventProvider: (
  options: PostgresEventProviderOptions,
) => PostgresEventProvider;

Source

createPostgresJobsRuntime

Signature

declare const createPostgresJobsRuntime: (
  options: PostgresJobsRuntimeOptions,
) => PostgresJobsRuntime;

Source

runtimeIntegration

Signature

declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;

Source

integration.ts

Runtime registrations the generated server uses to build the Postgres jobs and events providers from defineApp profiles. Providers of one process that point at the same database and namespace share one pool. The process role comes from RELKIT_WORKER_ROLE: worker (the default) serves requests and runs job workers, the scheduler and event consumers; api only serves requests, submits jobs and publishes events, leaving the work to separate worker-role instances.

PostgresWorkerRole (type alias)

Whether this process only serves requests (api) or also runs background work (worker).

Signature

type PostgresWorkerRole = "api" | "worker";

Source

runtimeIntegration

Registrations for the postgres-job and postgres-event adapters.

Signature

declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;

Source

workerRole

Reads the process role.

Throws

TypeError for any other value.

Example

workerRole("api") === "api";

Signature

declare const workerRole: (value?: string | undefined) => PostgresWorkerRole;

Source

jobs-controls.ts

Reads, lists and cancels job runs. Cancellation runs in a transaction that locks the row, so the first terminal transition wins: a queued run becomes cancelled at once, a running run records the request and its worker observes it on the next lease heartbeat, and later requests on a terminal run report already-terminal. Each function is a lazy Effect requiring the SQL client.

PostgresRunNotFoundError (class)

No run with this ID exists in the operation’s service.

Signature

declare class PostgresRunNotFoundError

Source

cancelRun

Applies the first cancellation transition under a row lock.

Signature

declare const cancelRun: (
  tables: PostgresTables,
  request: NativeCancelRequest,
  context: OperationContext,
) => Effect.Effect<
  RunCancellationReceipt,
  PostgresBackendError | PostgresRunNotFoundError,
  SqlClient.SqlClient
>;

Source

getRun

Reads one run in the operation’s service.

Signature

declare const getRun: (
  tables: PostgresTables,
  runId: string,
  context: OperationContext,
) => Effect.Effect<
  RunSnapshot,
  PostgresBackendError | PostgresRunNotFoundError,
  SqlClient.SqlClient
>;

Source

listRuns

Lists runs newest first with keyset pagination.

Signature

declare const listRuns: (
  tables: PostgresTables,
  query: RunListQuery,
  context: OperationContext,
) => Effect.Effect<RunPage<RunSnapshot>, PostgresBackendError, SqlClient.SqlClient>;

Source

jobs-lease.ts

Lease protocol for job runs. A worker claims the oldest due run with FOR UPDATE SKIP LOCKED, so concurrent workers never claim the same row; a claim stamps an owner token and an expiry that heartbeats extend. Every settlement is fenced on the owner token, so a worker whose lease expired and was re-claimed cannot overwrite the new attempt. Expired leases are claimable again while attempts remain; exhausted ones end failed and dead-lettered.

HeartbeatOutcome (type alias)

Result of extending a lease.

Signature

type HeartbeatOutcome = "held" | "cancel-requested" | "lost";

Source

completeRun

Records success for a held lease; a run with a pending cancellation ends cancelled.

Signature

declare const completeRun: (
  tables: PostgresTables,
  runId: string,
  owner: string,
  output: JsonValue | undefined,
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;

Source

failRun

Records a failed attempt: schedules the next attempt per policy, or ends the run failed and dead-lettered when the budget is spent or the failure forbids retry.

Signature

declare const failRun: (
  tables: PostgresTables,
  runId: string,
  owner: string | undefined,
  error: object | JsonValue | Error | undefined,
) => Effect.Effect<boolean, PostgresBackendError, SqlClient.SqlClient>;

Source

heartbeatRun

Extends a held lease and reports a pending cancellation.

Signature

declare const heartbeatRun: (
  tables: PostgresTables,
  runId: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<HeartbeatOutcome, PostgresBackendError, SqlClient.SqlClient>;

Source

leaseRun

Ends expired runs that have no attempts left, then claims the next due run.

Signature

declare const leaseRun: (
  tables: PostgresTables,
  service: string,
  owner: string,
  leaseMs: number,
) => Effect.Effect<JobRunRow | undefined, PostgresBackendError, SqlClient.SqlClient>;

Source

jobs-loops.ts

Background loops of the jobs runtime: the scheduler pass and, for processes that run attempts without the generated server’s job loop, worker loops that lease, execute and settle runs. Loops are forked into the connection owner, log and survive transient failures, and stop when the runtime closes.

forkScheduler

Forks the scheduler loop.

Signature

declare const forkScheduler: (
  database: PostgresDatabase,
  service: string,
  claimant: string,
  pollIntervalMs: number,
) => BackgroundFiber;

Source

forkWorkerLoop

Forks one worker loop that keeps executing runs and sleeps when idle.

Signature

declare const forkWorkerLoop: (
  database: PostgresDatabase,
  step: (signal: AbortSignal) => Promise<boolean>,
  pollIntervalMs: number,
) => BackgroundFiber;

Source

loopContext

Builds the operation context used by loops that run outside a request.

Signature

declare const loopContext: (service: string, signal: AbortSignal) => OperationContext;

Source

processNextRun

Leases and executes at most one run, settling it through the worker.

Signature

declare const processNextRun: (
  worker: PostgresJobWorker,
  executor: TaskExecutor,
  context: OperationContext,
) => Promise<boolean>;

Source

jobs-observe.ts

Run observation by polling: an initial snapshot frame, then an update frame whenever the snapshot changes, until the run is terminal or the caller aborts. Polling reads authoritative state, so no notification can be missed.

observeRun

Observes one run.

Signature

declare const observeRun: (
  get: (runId: string, context: OperationContext) => Promise<RunSnapshot>,
  request: NativeWatchRequest,
  context: OperationContext,
  pollIntervalMs: number,
) => AsyncGenerator<RunWatchFrame<RunSnapshot>>;

Source

jobs-retry-policy.ts

Pure retry decisions for failed job attempts. It reads the task’s declared policy.retry (attempt budget, exponential backoff, optional full jitter) from the stored submission and the failure’s own retry/afterMs hints, matching the local provider so a task behaves the same on both backends.

failureOf

Normalizes a thrown task failure into the public error envelope.

Signature

declare const failureOf: (value: Error | JsonValue | object | undefined) => JobErrorEnvelope;

Source

maxAttempts

Reads the attempt budget declared by the task policy.

Signature

declare const maxAttempts: (policy: JsonValue | undefined) => number;

Source

retryDelay

Decides whether a failed attempt runs again and after how long.

Signature

declare const retryDelay: (
  policy: JsonValue | undefined,
  attempt: number,
  failure: JobErrorEnvelope,
  random?: () => number,
) => number | undefined;

Source

jobs-rows.ts

Maps job-run rows to the public jobs contract. The table stores five states; delayed and retrying are derived from the eligibility time and attempt count at read time, and dead-lettered failures carry a diagnostic code. Pure functions only: callers own the SQL that produced the rows.

DEAD_LETTER_CODE

Diagnostic code reported on failed runs that reached the dead-letter state.

Signature

declare const DEAD_LETTER_CODE: "RELKIT_JOB_DEAD_LETTERED";

Source

JobRunRow

One row of the job-runs table.

Signature

export interface JobRunRow {
  readonly run_id: string;
  readonly service: string;
  readonly scope: string;
  readonly job_id: string;
  readonly task_id: string;
  readonly task_version: string;
  readonly build_id: string;
  /** Stored state: queued, running, completed, failed or cancelled. */
  readonly status: "queued" | "running" | "completed" | "failed" | "cancelled";
  /** Attempts started so far; a leased run's current attempt. */
  readonly attempt: number;
  readonly input: JobWireEnvelope;
  readonly request: StoredRequest;
  readonly dedupe_key: string | null;
  readonly operation_id: string;
  readonly retry_of_run_id: string | null;
  readonly run_at: TimestampValue;
  readonly accepted_at: TimestampValue;
  readonly started_at: TimestampValue | null;
  readonly completed_at: TimestampValue | null;
  readonly lease_owner: string | null;
  readonly lease_expires_at: TimestampValue | null;
  readonly output: JsonValue | null;
  readonly error: JobErrorEnvelope | null;
  readonly cancellation: RunCancellationReceipt | null;
  readonly dead_lettered: boolean;
  /** Database time when the row was read, used for derived states such as `delayed`. */
  readonly observed_at: TimestampValue;
}

Source

StoredRequest

Submission metadata kept in the request jsonb column; every field is optional.

Signature

export interface StoredRequest {
  readonly inputHash?: string;
  readonly inputSchemaHash?: string;
  readonly acceptanceIdentity?: string;
  readonly occurrenceIdentity?: string;
  readonly idempotencyKey?: string;
  readonly policy?: JsonValue;
  readonly scheduledFor?: string;
  readonly scheduleId?: string;
  readonly tags?: readonly string[];
  readonly correlationId?: string;
  readonly parentRunId?: string;
  readonly propagation?: TracePropagation;
  readonly serviceGeneration?: string;
}

Source

TimestampValue

A timestamp column as the driver returns it.

Signature

type TimestampValue = Date | string;

Source

handleOf

Builds the acceptance handle returned by submission and retry.

Signature

declare const handleOf: (row: JobRunRow, duplicate?: boolean) => RunHandle;

Source

isTerminal

Reports whether a stored state can still change.

Signature

declare const isTerminal: (status: JobRunRow["status"]) => boolean;

Source

iso

Normalizes a driver timestamp to ISO-8601 text.

Signature

declare const iso: (value: TimestampValue) => string;

Source

snapshotOf

Projects one row to the public run snapshot.

Signature

declare const snapshotOf: (row: JobRunRow) => RunSnapshot;

Source

statusOf

Derives the public run status from the stored state and eligibility time.

Signature

declare const statusOf: (row: JobRunRow) => RunSnapshot["status"];

Source

jobs-rows.types.ts

Row shapes read from the job-runs table and the submission metadata persisted with each run.

JobRunRow (interface)

One row of the job-runs table.

Signature

export interface JobRunRow {
  readonly run_id: string;
  readonly service: string;
  readonly scope: string;
  readonly job_id: string;
  readonly task_id: string;
  readonly task_version: string;
  readonly build_id: string;
  /** Stored state: queued, running, completed, failed or cancelled. */
  readonly status: "queued" | "running" | "completed" | "failed" | "cancelled";
  /** Attempts started so far; a leased run's current attempt. */
  readonly attempt: number;
  readonly input: JobWireEnvelope;
  readonly request: StoredRequest;
  readonly dedupe_key: string | null;
  readonly operation_id: string;
  readonly retry_of_run_id: string | null;
  readonly run_at: TimestampValue;
  readonly accepted_at: TimestampValue;
  readonly started_at: TimestampValue | null;
  readonly completed_at: TimestampValue | null;
  readonly lease_owner: string | null;
  readonly lease_expires_at: TimestampValue | null;
  readonly output: JsonValue | null;
  readonly error: JobErrorEnvelope | null;
  readonly cancellation: RunCancellationReceipt | null;
  readonly dead_lettered: boolean;
  /** Database time when the row was read, used for derived states such as `delayed`. */
  readonly observed_at: TimestampValue;
}

Source

StoredRequest (interface)

Submission metadata kept in the request jsonb column; every field is optional.

Signature

export interface StoredRequest {
  readonly inputHash?: string;
  readonly inputSchemaHash?: string;
  readonly acceptanceIdentity?: string;
  readonly occurrenceIdentity?: string;
  readonly idempotencyKey?: string;
  readonly policy?: JsonValue;
  readonly scheduledFor?: string;
  readonly scheduleId?: string;
  readonly tags?: readonly string[];
  readonly correlationId?: string;
  readonly parentRunId?: string;
  readonly propagation?: TracePropagation;
  readonly serviceGeneration?: string;
}

Source

TimestampValue (type alias)

A timestamp column as the driver returns it.

Signature

type TimestampValue = Date | string;

Source

jobs-runtime.ts

Assembles the Postgres jobs adapter: durable submission, reads, cancellation and retry over the job-runs table, a pull worker with leases, persisted schedules with a once-per-occurrence scheduler, and optional in-process worker loops. The generated server drives worker from its job loop in the worker role and calls registerWorker, which starts the scheduler unless the instance runs in the api role.

“./jobs-runtime.types.js” (namespace export)

Re-exports all named exports from the “./jobs-runtime.types.js” module.

Signature

export * from "./jobs-runtime.types.js";

Source

createPostgresJobsRuntime

Creates the Postgres jobs runtime.

Throws

TypeError when neither url nor database is given.

Example

const jobs = createPostgresJobsRuntime({ url: process.env.DATABASE_URL! });

Signature

declare const createPostgresJobsRuntime: (
  options: PostgresJobsRuntimeOptions,
) => PostgresJobsRuntime;

Source

jobs-runtime.types.ts

Contracts of the Postgres jobs runtime: construction options, worker registration and the runtime surface.

PostgresFaults (interface)

Faults a test can inject at the provider boundary.

Signature

export interface PostgresFaults {
  /** Commit submissions but report their outcome as unknown, as after a lost response. */
  readonly loseSubmitResponse?: boolean;
}

Source

PostgresJobsRuntime (interface)

The Postgres jobs adapter plus its worker, scheduler and loop controls.

Signature

export interface PostgresJobsRuntime extends JobsAdapterRuntime {
  readonly database: PostgresDatabase;
  readonly worker: PostgresJobWorker;
  readonly schedules: NativeScheduleOperations;
  readonly registerWorker: (options: PostgresWorkerRegistration) => PostgresWorkerHandle;
  /** Runs one scheduler pass now. */
  readonly tickSchedules: () => Promise<readonly ClaimedOccurrence[]>;
  /** Starts the background scheduler loop; idempotent. */
  readonly startScheduler: () => void;
  /** Starts background loops that lease and execute runs in this process. */
  readonly startWorkers: (options: PostgresWorkerLoopOptions) => void;
  /** Leases and executes at most one run; resolves true when one ran. */
  readonly processNext: (executor: TaskExecutor) => Promise<boolean>;
}

Source

PostgresJobsRuntimeOptions (interface)

Options for createPostgresJobsRuntime.

Signature

export interface PostgresJobsRuntimeOptions extends Partial<PostgresDatabaseOptions> {
  /** Shared connection owner; when given, `url` is ignored and `close()` leaves it open. */
  readonly database?: PostgresDatabase;
  /** Jobs service (profile) name; defaults to `postgres`. */
  readonly service?: string;
  /** Lease duration in ms; defaults to 30 000. */
  readonly leaseMs?: number;
  /** Idle polling interval for the scheduler and worker loops in ms; defaults to 1 000. */
  readonly pollIntervalMs?: number;
  /** Prefix of owner tokens and occurrence claims; defaults to a random instance ID. */
  readonly workerId?: string;
  /** Test-only fault injection. */
  readonly faults?: PostgresFaults;
}

Source

PostgresTaskDefinition (interface)

A task binding the generated server registers for each job.

Signature

export interface PostgresTaskDefinition {
  readonly jobId: string;
  readonly taskId: string;
  readonly taskVersion?: string;
  readonly version?: string;
  readonly buildId: string;
  readonly policy?: JsonValue;
}

Source

PostgresWorkerHandle (interface)

Handle the generated server awaits and closes.

Signature

export interface PostgresWorkerHandle {
  readonly definitions: readonly PostgresTaskDefinition[];
  readonly ready: () => Promise<void>;
  readonly close: () => Promise<void>;
}

Source

PostgresWorkerLoopOptions (interface)

Options for running task attempts in this process without the generated server.

Signature

export interface PostgresWorkerLoopOptions {
  /** Executes one envelope; the generated server passes its task executor. */
  readonly executor: TaskExecutor;
  /** Concurrent attempts; defaults to 1. */
  readonly concurrency?: number;
}

Source

PostgresWorkerRegistration (interface)

Arguments of registerWorker, matching what the generated server passes.

Signature

export interface PostgresWorkerRegistration {
  readonly definitions: readonly PostgresTaskDefinition[];
  readonly executor: TaskExecutor;
  /** False in the `api` role: this instance only submits, and runs no scheduler. */
  readonly startWorker?: boolean;
}

Source

jobs-submit.ts

Durable submission and retry for the job-runs table. A submission is one INSERT whose dedupe key (job, idempotency key, occurrence) is unique per service and scope, so concurrent duplicates resolve to the first run. A retry copies a terminal run into a new run linked by retry_of_run_id; the retry identity is unique per original run, so repeating a retry returns the same new run. Each function is a lazy Effect requiring the SQL client.

dedupeKey

Builds the submission dedupe key; runs without an idempotency key or occurrence never deduplicate.

Signature

declare const dedupeKey: (request: NativeSubmission) => string | null;

Source

retryRun

Creates (or returns) the new run for one retry of a terminal run.

Signature

declare const retryRun: (
  tables: PostgresTables,
  request: NativeRetryRequest,
  context: OperationContext,
) => Effect.Effect<
  {
    retryOfRunId: string;
    accepted: true;
    runId: string;
    jobId: string;
    taskId: string;
    taskVersion: string;
    acceptedAt: string;
    duplicate?: boolean;
    idempotencyExpiresAt?: string;
  },
  PostgresBackendError,
  SqlClient.SqlClient
>;

Source

storedRequest

Collects the submission metadata persisted in the request column.

Signature

declare const storedRequest: (
  request: NativeSubmission,
  context: OperationContext,
) => StoredRequest;

Source

submitRun

Inserts a run, or returns the run that already owns its dedupe key.

Signature

declare const submitRun: (
  tables: PostgresTables,
  request: NativeSubmission,
  context: OperationContext,
) => Effect.Effect<RunHandle, PostgresBackendError, SqlClient.SqlClient>;

Source

unknownSubmission

Describes a write whose commit may have happened but whose response was lost.

Signature

declare const unknownSubmission: (request: NativeSubmission) => NativeReceipt;

Source

jobs-work.ts

Builds the execution envelope and binding the task executor receives for a leased run. The binding’s signal belongs to the lease: the worker aborts it when a cancellation is requested or the lease is lost. Pure construction; the worker owns the controller and heartbeat.

bindingOf

Builds the binding for one attempt.

Signature

declare const bindingOf: (
  row: JobRunRow,
  signal: AbortSignal,
  context: OperationContext,
) => TaskExecutionBinding;

Source

envelopeOf

Projects a leased row to the executor envelope.

Signature

declare const envelopeOf: (row: JobRunRow) => TaskExecutionEnvelope;

Source

jobs-worker.ts

Pull worker for the Postgres jobs backend. next claims one due run with a fresh owner token and starts a heartbeat fiber that extends the lease every third of its duration; the heartbeat aborts the attempt’s signal when a cancellation is requested or the lease is lost. complete and fail stop the heartbeat and settle fenced on the owner token. Closing the worker stops heartbeats without settling, which is exactly what a crash looks like to the database: the lease expires and another worker retries the run.

PostgresJobWorker (interface)

Pull worker plus a close operation for its heartbeats.

Signature

export interface PostgresJobWorker extends NativeTaskWorker {
  /** Stops heartbeats without settling held runs; their leases then expire. */
  readonly close: () => Promise<void>;
  /** Runs currently leased by this worker. */
  readonly active: () => readonly string[];
}

Source

createPostgresJobWorker

Creates the pull worker for one jobs service.

Signature

declare const createPostgresJobWorker: (
  database: PostgresDatabase,
  options: { readonly service: string; readonly leaseMs: number; readonly workerId: string },
) => PostgresJobWorker;

Source

schedule-time.ts

Pure occurrence arithmetic for persisted schedules. Cron schedules use Effect’s Cron with the schedule’s IANA timezone; interval schedules advance from the previous occurrence so they do not drift with polling. The misfire policy decides which due occurrences are enqueued after downtime.

MAX_CATCH_UP

Upper bound of occurrences enqueued in one pass for misfire: "all".

Signature

declare const MAX_CATCH_UP: 100;

Source

ON_TIME_MS

How far behind an occurrence may be and still count as on time for misfire: "skip".

Signature

declare const ON_TIME_MS: 60000;

Source

ScheduleTiming (interface)

Timing fields of a stored schedule definition.

Signature

export interface ScheduleTiming {
  readonly cron?: string;
  readonly timezone?: string;
  readonly every?: JsonValue;
  readonly misfire?: "skip" | "latest" | "all";
}

Source

dueOccurrences

Selects the occurrences to enqueue now and the next pending occurrence.

Signature

declare const dueOccurrences: (
  timing: ScheduleTiming,
  nextAt: Date,
  now: Date,
) => { readonly due: readonly Date[]; readonly next: Date };

Source

nextOccurrence

Computes the first occurrence strictly after an instant.

Throws

TypeError when the timing is neither a valid cron nor a positive interval.

Signature

declare const nextOccurrence: (timing: ScheduleTiming, after: Date) => Date;

Source

schedules-store.ts

Persisted schedule definitions behind the native schedule operations that schedule reconciliation and the admin API call. Each row keeps the authored definition (with its ownership metadata), the submission template the scheduler uses to enqueue runs, and the next pending occurrence. Upserting a definition with unchanged timing keeps its pending occurrence, so restarts and redeploys neither skip nor repeat one.

createScheduleOperations

Builds the native schedule operations for one jobs service.

Signature

declare const createScheduleOperations: (
  database: PostgresDatabase,
  service: string,
  template: (jobId: string) => Omit<ScheduleSubmission, "scope"> | undefined,
) => NativeScheduleOperations;

Source

schedules-tick.ts

Enqueues schedule occurrences exactly once across instances. One pass locks due schedule rows with FOR UPDATE SKIP LOCKED, claims each occurrence by inserting into the occurrences table, whose primary key is (service, schedule, occurrence time), enqueues the run in the same transaction, and advances the pending occurrence. A contender that reads a stale pending occurrence loses on the primary key, so it never enqueues a second run.

ClaimedOccurrence (interface)

One occurrence this pass enqueued (or skipped under overlap: "skip").

Signature

export interface ClaimedOccurrence {
  readonly scheduleId: string;
  readonly occurrenceAt: string;
  /** The enqueued run, or `skipped` when an earlier run of the schedule was still active. */
  readonly runId: string;
}

Source

claimOccurrence

Claims one occurrence and enqueues its run; a lost race on the primary key claims nothing.

Signature

declare const claimOccurrence: (
  tables: PostgresTables,
  row: ScheduleRow,
  occurrenceAt: string,
  claimant: string,
) => Effect.Effect<
  { scheduleId: string; occurrenceAt: string; runId: string } | undefined,
  PostgresBackendError,
  SqlClient.SqlClient
>;

Source

occurrenceIdentity

Builds the identity that ties a run to its occurrence.

Signature

declare const occurrenceIdentity: (scheduleId: string, occurrenceAt: string) => string;

Source

tickSchedules

Runs one scheduler pass for a jobs service.

Signature

declare const tickSchedules: (
  tables: PostgresTables,
  service: string,
  claimant: string,
) => Effect.Effect<Array<ClaimedOccurrence>, PostgresBackendError, SqlClient.SqlClient>;

Source

schedules.types.ts

Row and template shapes for persisted schedules and their claimed occurrences.

ScheduleRow (interface)

One row of the schedules table.

Signature

export interface ScheduleRow {
  readonly service: string;
  readonly schedule_id: string;
  readonly job_id: string;
  /** Authored definition including reconciliation ownership metadata. */
  readonly definition: JsonValue;
  readonly submission: ScheduleSubmission;
  readonly state: "active" | "paused" | "deleted";
  /** Earliest occurrence not yet claimed. */
  readonly next_at: TimestampValue;
}

Source

ScheduleSubmission (interface)

The task binding a scheduler needs to enqueue a run without the application code.

Signature

export interface ScheduleSubmission {
  readonly jobId: string;
  readonly taskId: string;
  readonly taskVersion: string;
  readonly buildId: string;
  readonly scope: string;
  readonly policy?: JsonValue;
}

Source

schema.ts

Owns the Postgres backend’s table layout: identifier validation, quoted table names, and the idempotent DDL that the runtime applies at startup under an advisory lock. Applications that own their migrations can apply the same statements from postgresBackendSql. Nothing here opens a connection.

PostgresTableOptions

Where the backend’s tables live; both names are validated SQL identifiers.

Signature

export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}

Source

PostgresTables

Fully qualified, quoted table names for one backend namespace.

Signature

export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}

Source

postgresBackendSql

Lists the idempotent DDL statements for one backend namespace, in apply order.

Example

postgresBackendSql().length > 0;

Signature

declare const postgresBackendSql: (options?: PostgresTableOptions) => readonly string[];

Source

postgresTables

Resolves quoted table names for one backend namespace.

Throws

TypeError when a name is not a lowercase identifier of at most 41 characters.

Example

postgresTables({ tablePrefix: "app" }).jobRuns === '"public"."app_job_runs"';

Signature

declare const postgresTables: (options?: PostgresTableOptions) => PostgresTables;

Source

schema.types.ts

Where the backend’s tables live; both names are validated SQL identifiers.

PostgresTableOptions (interface)

Where the backend’s tables live; both names are validated SQL identifiers.

Signature

export interface PostgresTableOptions {
  /** Postgres schema holding the tables; defaults to `public`. */
  readonly schema?: string;
  /** Prefix for every table name; defaults to `relkit`. */
  readonly tablePrefix?: string;
}

Source

PostgresTables (interface)

Fully qualified, quoted table names for one backend namespace.

Signature

export interface PostgresTables {
  /** Quoted schema name. */
  readonly schema: string;
  /** Job runs, leased with `FOR UPDATE SKIP LOCKED`. */
  readonly jobRuns: string;
  /** Persisted schedule definitions keyed by service and schedule ID. */
  readonly schedules: string;
  /** One row per claimed schedule occurrence, unique on (service, schedule, occurrence). */
  readonly scheduleOccurrences: string;
  /** Event outbox written by publishers, inside the caller's transaction when given one. */
  readonly eventOutbox: string;
  /** Registered event consumers that publication fans out to. */
  readonly eventConsumers: string;
  /** One delivery per (event instance, consumer), retried independently. */
  readonly eventDeliveries: string;
  /** Advisory-lock key that serializes schema creation across instances. */
  readonly lockKey: number;
}

Source