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.
index.ts
“./outbox.js” (namespace export)
Re-exports all named exports from the “./outbox.js” module.
Signature
export * from "./outbox.js";
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";
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;
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;
}
OutboxTransaction (interface)
Anything with Drizzle’s execute(sql): a Postgres database or transaction.
Signature
export interface OutboxTransaction<Result> {
readonly execute: (query: SQL) => PromiseLike<Result>;
}
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 }>;
}
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;
index.ts
“./providers.types.js” (namespace export)
Re-exports all named exports from the “./providers.types.js” module.
Signature
export * from "./providers.types.js";
PostgresEventAdapter
Events provider adapter selected with postgresEvent().
Signature
type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;
PostgresJobAdapter
Jobs provider adapter selected with postgresJob().
Signature
type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;
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;
}
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;
}
postgresEvent
Signature
declare const postgresEvent: (options?: PostgresEventOptions) => PostgresEventAdapter;
postgresJob
Signature
declare const postgresJob: (options?: PostgresJobOptions) => PostgresJobAdapter;
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";
PostgresEventAdapter (type alias)
Events provider adapter selected with postgresEvent().
Signature
type PostgresEventAdapter = ProviderAdapter<typeof event, "postgres-event">;
PostgresJobAdapter (type alias)
Jobs provider adapter selected with postgresJob().
Signature
type PostgresJobAdapter = ProviderAdapter<typeof job, "postgres-job">;
postgresConnectionContract
Connection fields both adapters accept.
Signature
declare const postgresConnectionContract: ProviderConnectionContract;
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;
postgresIntegration
Integration reference shared by both adapters.
Signature
declare const postgresIntegration: IntegrationReference<"postgres">;
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;
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;
}
PostgresEventOptions (interface)
Options for postgresEvent().
Signature
export interface PostgresEventOptions extends PostgresConnectionOptions {}
PostgresJobOptions (interface)
Options for postgresJob(): connection settings plus the common jobs service options.
Signature
export interface PostgresJobOptions extends PostgresConnectionOptions, JobsServiceOptions {}
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">;
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";
PostgresBackendError (class)
A SQL statement of the Postgres backend failed.
Signature
declare class PostgresBackendError
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>;
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;
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>;
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>;
}
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;
}
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";
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;
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>;
}
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;
}
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>;
}
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;
}
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>;
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>;
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>;
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>;
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;
}
index.ts
“./database.types.js” (namespace export)
Re-exports all named exports from the “./database.types.js” module.
Signature
export * from "./database.types.js";
“./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";
“./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";
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;
}
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[];
}
createPostgresEventProvider
Signature
declare const createPostgresEventProvider: (
options: PostgresEventProviderOptions,
) => PostgresEventProvider;
createPostgresJobsRuntime
Signature
declare const createPostgresJobsRuntime: (
options: PostgresJobsRuntimeOptions,
) => PostgresJobsRuntime;
runtimeIntegration
Signature
declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;
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";
runtimeIntegration
Registrations for the postgres-job and postgres-event adapters.
Signature
declare const runtimeIntegration: RuntimeProviderIntegration<"postgres">;
workerRole
Reads the process role.
Throws
TypeError for any other value.
Example
workerRole("api") === "api";
Signature
declare const workerRole: (value?: string | undefined) => PostgresWorkerRole;
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
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
>;
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
>;
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>;
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";
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>;
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>;
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>;
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>;
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;
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;
loopContext
Builds the operation context used by loops that run outside a request.
Signature
declare const loopContext: (service: string, signal: AbortSignal) => OperationContext;
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>;
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>>;
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;
maxAttempts
Reads the attempt budget declared by the task policy.
Signature
declare const maxAttempts: (policy: JsonValue | undefined) => number;
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;
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";
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;
}
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;
}
TimestampValue
A timestamp column as the driver returns it.
Signature
type TimestampValue = Date | string;
handleOf
Builds the acceptance handle returned by submission and retry.
Signature
declare const handleOf: (row: JobRunRow, duplicate?: boolean) => RunHandle;
isTerminal
Reports whether a stored state can still change.
Signature
declare const isTerminal: (status: JobRunRow["status"]) => boolean;
iso
Normalizes a driver timestamp to ISO-8601 text.
Signature
declare const iso: (value: TimestampValue) => string;
snapshotOf
Projects one row to the public run snapshot.
Signature
declare const snapshotOf: (row: JobRunRow) => RunSnapshot;
statusOf
Derives the public run status from the stored state and eligibility time.
Signature
declare const statusOf: (row: JobRunRow) => RunSnapshot["status"];
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;
}
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;
}
TimestampValue (type alias)
A timestamp column as the driver returns it.
Signature
type TimestampValue = Date | string;
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";
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;
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;
}
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>;
}
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;
}
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;
}
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>;
}
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;
}
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;
}
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;
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
>;
storedRequest
Collects the submission metadata persisted in the request column.
Signature
declare const storedRequest: (
request: NativeSubmission,
context: OperationContext,
) => StoredRequest;
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>;
unknownSubmission
Describes a write whose commit may have happened but whose response was lost.
Signature
declare const unknownSubmission: (request: NativeSubmission) => NativeReceipt;
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;
envelopeOf
Projects a leased row to the executor envelope.
Signature
declare const envelopeOf: (row: JobRunRow) => TaskExecutionEnvelope;
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[];
}
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;
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;
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;
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";
}
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 };
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;
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;
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;
}
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
>;
occurrenceIdentity
Builds the identity that ties a run to its occurrence.
Signature
declare const occurrenceIdentity: (scheduleId: string, occurrenceAt: string) => string;
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>;
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;
}
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;
}
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;
}
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;
}
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[];
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;
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;
}
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;
}