Client, outbox and runtime helpers
This page covers the parts of the SDK that talk to the platform or to your own database: the API client, the outbox writer, the use-case envelope, and the helpers for receiving deliveries.
FlowCatalystClient
Section titled “FlowCatalystClient”import { FlowCatalystClient } from '@flowcatalyst/sdk';
const client = new FlowCatalystClient({ baseUrl: 'https://platform.example.com', clientId: process.env.FLOWCATALYST_CLIENT_ID!, clientSecret: process.env.FLOWCATALYST_CLIENT_SECRET!,});Configuration
Section titled “Configuration”There are two authentication modes. The constructor picks the mode by whether the config has an
accessToken property.
| Option | Mode | Default | Meaning |
|---|---|---|---|
baseUrl |
both | required | Platform base URL. A trailing / is removed. |
clientId, clientSecret |
client credentials | required | An OAuth client (usually a service account). The SDK runs the client_credentials grant and caches the token. |
tokenUrl |
client credentials | {baseUrl}/oauth/token |
Token endpoint override. |
accessToken |
user token | required | A token string, or a sync or async function returning the current token. Use a function if your app refreshes tokens. |
timeout |
both | 30000 |
Timeout of each attempt, in ms. The timer aborts the in-flight request. |
retryAttempts |
both | 3 |
Retries for transient failures. |
retryDelay |
both | 100 |
Base delay in ms; the wait doubles each attempt (retryDelay * 2^attempt). |
routerBaseUrl |
both | baseUrl |
Host of the message router, used only by client.router(). |
Use client credentials for backend services. Use accessToken when you already hold a user’s token
and want to act as that user. See Tokens and Call the API.
Token handling and retries
Section titled “Token handling and retries”In client-credentials mode OidcTokenManager fetches a token, caches it until 60 seconds before
expiry, and shares a single in-flight fetch between concurrent callers. A 401 makes the client
refresh the token and retry once. In user-token mode there is no refresh: a 401 is returned as an
error.
A request is repeatable when its method is GET, HEAD, OPTIONS, PUT or DELETE, or when
the call passes { repeatable: true } to client.request() (the SDK does this for the declarative
syncs and other POSTs the platform applies once however often they arrive). Retries use exponential
backoff, up to retryAttempts times, and follow one rule:
408and429, and a connection that could not be made (DNS failure, refused, connect timeout), are retried for every request.502,503and504, and a connection failure or timeout after the request was sent, are retried only for a repeatable request. For any other request (a plainPOST) the call ends at once with anoutcome_unknownerror: the platform may have applied it, and the SDK did not send it again. Read the state before sending it again.- A
DELETEthat answers404after an attempt whose outcome was unknown succeeds. 500and every other error status are returned immediately as an error value.
Resource accessors
Section titled “Resource accessors”Each accessor returns a cached resource object. Every method returns a neverthrow ResultAsync.
| Accessor | Operations (as implemented) |
|---|---|
eventTypes() |
list, get, create, update, addSchemaVersion, archive, sync |
subscriptions() |
list, get, create, update, delete, pause, resume, sync |
connections() |
list, get, create, update, delete, pause, activate |
dispatchPools() |
list, get, create, update, delete, suspend, activate, sync |
processes() |
list, get, getByCode, create, update, archive, delete, sync |
roles() |
list, get, getByCode, create, update, delete, listForApplication, grantPermission, revokePermission, sync |
permissions() |
list, get |
applications() |
list, get, getByCode, create, update, delete, activate, deactivate, provisionServiceAccount, getServiceAccount, listRoles, listClients, enableForClient, disableForClient |
clients() |
list, get, getByIdentifier, create, update, activate, deactivate, suspend, getApplications, updateApplications, enableApplication, disableApplication, search, addNote |
principals() |
list, get, findByEmail, createUser, update, activate, deactivate, resetPassword, getRoles, addRole, removeRole, setRoles, getClientAccessGrants, grantClientAccess, revokeClientAccess, sync, syncUsers |
me() |
getClients, getClient, getClientApplications |
scheduledJobs() |
create, list, get, getByCode, update, pause, resume, archive, delete, fire, listInstances, getInstance, listInstanceLogs, logForInstance, completeInstance |
auditLogs() |
list, get, recent, forEntity, forPrincipal |
ingestions() |
CRUD, pause, resume, listVersions, saveVersion, makeVersionLive, getDefinition, listHistory, listFailures, dismissFailure, listSecrets, listSourceKinds, testConnection, getTest, listSets, applySet, listSetApplies, getSetApply, reapplySet, releaseSet |
platformConfig() |
list, get, set, delete, revealSecret |
fieldWorkers(), fieldDevices(), fieldPolicies(), fieldTokens() |
See Field |
router() |
inPipeline, inPipelineBatch (see below) |
definitions() |
The definition synchroniser; see Sync |
applications().provisionServiceAccount(id) answers { message, serviceAccount }, where
serviceAccount is { name, principalId, oauthClient: { id, clientId, clientSecret? }, webhook? } and
webhook is { authToken, signingSecret }: the token the platform sends on its deliveries and the
secret it signs them with. Every secret is in plaintext and shown once. An application that already has
a service account is refused with 409 ALREADY_PROVISIONED; read it with getServiceAccount(id), which
never returns a secret. If the call ends in outcome_unknown, call getServiceAccount(id) before you
retry: a second provision is refused and the secrets from the first are lost.
Two accessors are not plain resources:
client.router()calls the message router’s monitoring endpoints (/monitoring/in-flight-messages/checkand/check-batch) onrouterBaseUrl. Those calls are plainfetchcalls with noAuthorizationheader and no retry.client.scheduledJobRunner(options)builds a runner.
An example
Section titled “An example”const created = await client.eventTypes().create({ code: 'orders:fulfillment:order:created', name: 'Order Created', description: 'Fired when a new order is placed',});
const subscription = await client.subscriptions().create({ code: 'notify-warehouse', name: 'Notify Warehouse', eventTypes: [{ eventTypeCode: 'orders:fulfillment:order:created' }], endpoint: 'https://myapp.example.com/webhooks',});
if (subscription.isErr()) { console.error(subscription.error.type, subscription.error.message);}For anything declarative (the same set every deploy), prefer Sync to creating rows one by one. Request and response shapes are the platform’s wire types; see the HTTP API reference.
Anything without a resource class
Section titled “Anything without a resource class”The whole generated API is available as the api namespace. Pass a generated function through
client.request() to get the same authentication, retry and error mapping:
import { api } from '@flowcatalyst/sdk';
const jobs = await client.request((httpClient, headers) => api.listDispatchJobs({ client: httpClient, headers, query: { status: 'FAILED' } }),);client.getHttpClient() and client.getTokenManager() expose the internals for advanced use (the
token manager is null in user-token mode).
Platform config and secrets
Section titled “Platform config and secrets”platformConfig().list() and .get() return the literal "***" as the value of a SECRET
property for every caller. The audited reveal call is the only way to read the plaintext:
const r = await client.platformConfig().revealSecret('my-app', 'smtp', 'password');if (r.isOk()) { useSecret(r.value.value);}Reveal needs the platform:admin:config:reveal permission (a platform administrator) or
platform:application-service:config:reveal (an application’s own service account, which the
platform:application-service role carries). The returned value is a non-enumerable property, so
it does not appear in console.log, object spreads or JSON.stringify (those show [REDACTED]).
The call is never cached. Setting a secret to "***" or to an empty string is refused (400 SECRET_VALUE_MASKED, 400 SECRET_VALUE_REQUIRED). A service account acting for a signed-in person
passes { onBehalfOf: 'alice@example.com' } to set, delete or revealSecret; it is sent as
X-On-Behalf-Of and recorded in the audit row. See Platform config.
Ingestions
Section titled “Ingestions”Without the promote permission, create, update and saveVersion save a draft: the answer’s
save.outcome is DRAFT and save.awaitingPromote is true until someone with promote calls
makeVersionLive. Refused records appear as failures of category rejected:
const open = await client.ingestions().listFailures(id, { category: 'rejected', undismissed: true });await client.ingestions().dismissFailure(id, failureId);listSecrets(id) returns secret names the live definition binds, with fetch counts and times;
no call returns a secret value. The runtime API for ingestions is not part of this SDK. See
Ingestion definitions and sets.
The outbox writer
Section titled “The outbox writer”To publish an event, write a row to outbox_messages in the same database transaction as your
business change. The platform’s relay forwards the row. See
The transactional outbox for the mechanism; this section is the TypeScript API.
import pg from 'pg';import { OutboxManager, PgOutboxDriver } from '@flowcatalyst/sdk';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });const outbox = new OutboxManager(new PgOutboxDriver(pool), process.env.FC_CLIENT_ID!);OutboxManager(driver, clientId, options?) takes the outbox row’s client_id as its second argument
and throws on every write if it is empty. options.clientCode is the default client code of a push.
The bundled driver is PgOutboxDriver, which accepts any node-postgres-compatible pool or client
(PgQueryable). It is the only driver shipped. Another database needs your own implementation of the
OutboxDriver interface (insert, insertBatch, optional withTransaction). The table definition
is in migrations/postgresql/001_create_outbox_messages.sql in the package (a MySQL variant is under
migrations/mysql/), and fcdev outbox creates the Postgres table on first run
(fcdev outbox).
Writing in a transaction
Section titled “Writing in a transaction”Pass the same transaction handle to your own writes and to the outbox call. With PgOutboxDriver,
that handle is a pg client:
import { CreateEventDto } from '@flowcatalyst/sdk';
const client = await pool.connect();try { await client.query('BEGIN'); await client.query('INSERT INTO orders (id, total) VALUES ($1, $2)', [order.id, order.total]); await outbox.createEvent( CreateEventDto.create('shop:orders:order:placed', { orderId: order.id }) .withSubject(`shop.order.${order.id}`) .withMessageGroup(`shop:order:${order.id}`), client, // joins the transaction ); await client.query('COMMIT');} catch (e) { await client.query('ROLLBACK'); throw e;} finally { client.release();}Without a tx argument the row is written on the driver’s own executor, outside any transaction of
yours; you lose the guarantee that makes the pattern worthwhile. driver.withTransaction(cb) opens a
transaction for you when you construct the driver with a pool.
Methods
Section titled “Methods”| Method | Writes | Returns |
|---|---|---|
createEvent(dto, tx?), createEvents(dtos, tx?) |
EVENT rows |
row id(s), TSIDs |
createDispatchJob(dto, tx?), createDispatchJobs(dtos, tx?) |
DISPATCH_JOB rows |
row id(s) |
createAuditLog(dto, tx?), createAuditLogs(dtos, tx?) |
AUDIT_LOG rows |
row id(s) |
createPush(dto, tx?), createPushes(dtos, tx?) |
PUSH rows |
row id(s) (the pushId) |
Batch methods return [] for an empty input and write all rows in one driver call. Rows are written
with status PENDING (0); every other status is set by the relay (OutboxStatus lists them).
DTOs are immutable: each with* returns a new object.
CreateEventDto.create(type, data) requires a four-segment type. Builders: withSource,
withSubject, withCorrelationId, withCausationId, withDeduplicationId, withMessageGroup,
withClientCode, withHeaders, withContextData. If you set no deduplicationId, the outbox row’s
own id is used, so a batch the relay resends after a lost response never produces a second event.
CreateDispatchJobDto.create(source, code, targetUrl, payload, dispatchPoolId) requires a
four-segment code; payload is a string or an object (which is JSON-stringified). Builders include
withSubject, withCorrelationId, withEventId, withMetadata, withHeaders,
withPayloadContentType, withDataOnly, withMessageGroup, withMode
(IMMEDIATE, NEXT_ON_ERROR or BLOCK_ON_ERROR), withSequence, withTimeoutSeconds (default 30),
withMaxRetries (default 5), withRetryStrategy, withScheduledFor, withExpiresAt,
withIdempotencyKey, withExternalId, withConnectionId and withQueue. withHeaders,
withRetryStrategy, withScheduledFor and withExpiresAt are accepted but not sent. The platform
now accepts scheduledFor and expiresAt on a dispatch job, but this SDK does not send them yet (the
Laravel SDK does). See
Dispatch jobs for what the platform does with each field, and
Ordering for modes.
CreateAuditLogDto.create(entityType, entityId, operation) with withOperationData,
withPrincipalId, withPerformedAt, withSource, withCorrelationId, withApplicationCode,
withClientCode, withMetadata, withHeaders.
CreatePushDto is covered under Push.
Push to clients
Section titled “Push to clients”A push tells people looking at a screen that something changed. The application writes a PUSH row
in the same transaction as the change; the platform’s outbox processor hands it to the push gateway,
which fans it out over server-sent events. See Push and
Publish and subscribe. The gateway is a separate opt-in service
on the platform side.
import { OutboxManager, PgOutboxDriver, CreatePushDto } from '@flowcatalyst/sdk';
const outbox = new OutboxManager(new PgOutboxDriver(pool), clientId, { clientCode: 'acme', // default client of a push; '_platform' leaves it out});
await outbox.createPush( CreatePushDto.create('shop:orders:ord_2', 'order.updated', { status: 'shipped' }), tx,);topicis{application}:{segment}(:{segment})*;typematches[a-z][a-z0-9-]*(.[a-z][a-z0-9-]*)*(reset,auth-expired,subscribedandfw.*are reserved);datais a JSON object, 16 KiB by default and up to 64 KiB with.withMaxDataBytes(n).createPushvalidates first and throwsPushErrorwith acodeofTOPIC_INVALID,TYPE_INVALID,TYPE_RESERVED,DATA_INVALID,DATA_NOT_OBJECT,DATA_TOO_LARGE,PUSH_ID_INVALIDorCLIENT_INVALID, so a push the platform would refuse is never stored.- The message group is the topic, so pushes of one topic arrive in order.
.withUngrouped()opts out (batched, concurrent, unordered);.withMessageGroup(g)names another group..withId(id)sets thepushId(a TSID otherwise, at most 26 characters)..withClientCode(code)overrides the client. - With
PgOutboxDriverthe insert also runspg_notify('fc_outbox_push', '')in the same statement, so the processor wakes when your transaction commits. Other drivers write a plain row and the processor’s poll picks it up. A custom Postgres driver should run the exportedPUSH_INSERT_SQLforPUSHrows.
Who may listen to a topic (rules, ticket keys, minting) is declared with the other definitions; see Sync.
The use-case envelope
Section titled “The use-case envelope”The usecase namespace implements one business operation as named phases and applies the result
in one transaction: aggregate write, event, and optional audit log. It is the same shape as the Go
SDK’s operation and plan. See The write path: use cases
for the thinking, and Effect for the variant with compile-time guarantees.
An Operation has validate (optional, no I/O), authorize (required; use
usecase.publicAuthorize to declare an operation deliberately open) and execute, which loads and
checks invariants and returns a Plan, or a UseCaseError. A Plan is built only by
Plan.save(aggregate, repo, event), Plan.delete(...) or Plan.emit(event); an operation cannot
reach the database any other way. usecase.run(uow, operation, command, context) runs the phases
in order, short-circuiting on the first error, then applies the plan.
import type pg from 'pg';import { usecase, PgOutboxDriver } from '@flowcatalyst/sdk';
interface Order extends usecase.Aggregate { readonly id: string; readonly totalCents: number }
class OrderRepo implements usecase.Repo<Order> { async persist(order: Order, tx: unknown) { await (tx as pg.PoolClient).query('INSERT INTO orders (id, total_cents) VALUES ($1, $2)', [order.id, order.totalCents]); } async delete(order: Order, tx: unknown) { await (tx as pg.PoolClient).query('DELETE FROM orders WHERE id = $1', [order.id]); }}
class OrderPlaced extends usecase.BaseDomainEvent<{ orderId: string; totalCents: number }> { constructor(ctx: usecase.ExecutionContext, data: { orderId: string; totalCents: number }) { super( { eventType: 'shop:orders:order:placed', specVersion: '1.0', source: 'shop:orders', subject: usecase.DomainEvent.subject('orders', 'order', data.orderId), messageGroup: usecase.DomainEvent.messageGroup('orders', 'order', data.orderId), }, ctx, data, ); }}
interface PlaceOrder extends usecase.Command { totalCents: number }
const placeOrder = (repo: OrderRepo): usecase.Operation<PlaceOrder, OrderPlaced> => ({ name: 'PlaceOrder', validate: (cmd) => cmd.totalCents > 0 ? null : usecase.UseCaseError.validation('TOTAL_INVALID', 'totalCents must be positive'), authorize: usecase.publicAuthorize, async execute(cmd, ctx) { const order: Order = { id: crypto.randomUUID(), totalCents: cmd.totalCents }; return usecase.Plan.save(order, repo, new OrderPlaced(ctx, { orderId: order.id, totalCents: order.totalCents })); },});
const uow = usecase.OutboxUnitOfWork.fromDriver(new PgOutboxDriver(pool), clientId);const result = await usecase.run(uow, placeOrder(new OrderRepo()), { totalCents: 1500 }, usecase.ExecutionContext.create('prn_123'));
if (usecase.Result.isSuccess(result)) { console.log('committed', result.value.eventType);} else { console.log(result.error.code, usecase.UseCaseError.httpStatus(result.error));}Points to know:
usecase.Resultis{ _tag: 'success', value }or{ _tag: 'failure', error }; success can only be created by a unit of work, so an operation cannot fake it.UseCaseErrorhas six kinds, built withvalidation,notFound,businessRule,concurrency,authorizationandinfrastructure.UseCaseError.httpStatusmaps them to 400, 404, 409, 409, 403 and 500. A thrown non-UseCaseErrorbecomes aninfrastructureerror with codeEXECUTE_FAILED.OutboxUnitOfWorktakes{ outboxManager, options }orOutboxUnitOfWork.fromDriver(driver, clientId, options). Options:auditEnabled(write an audit log with every event, default false),fallbackPrincipalId(default"system"),applicationCode,clientCode.runneeds a driver withwithTransaction; otherwise it fails withDRIVER_NOT_TX_AWARE.Plan.andPush(plan, ...pushes)addsCreatePushDtos (or functions of the committed event) written in the plan’s transaction after the event. An invalid push fails the plan and rolls back.- The older
uow.commit(event, command, persist)path exists and writes the identical outbox payload, butpersistis not wrapped in a transaction for you. Preferrun.
Scheduled-job runner
Section titled “Scheduled-job runner”The platform fires a scheduled job by POSTing an envelope to the job’s target URL. Mount the runner on any HTTP framework at that URL. See Scheduled jobs and the guide.
import { PgLockProvider, initLockSchema, verifyDeliverySignature } from '@flowcatalyst/sdk';
await initLockSchema(pool);
const runner = client.scheduledJobRunner({ lockProvider: new PgLockProvider(pool), onError: (err, envelope) => console.error('job failed', envelope.jobCode, err),});
runner.handler('shop:reports:daily:build', async (ctx) => { await ctx.log('starting', { level: 'INFO' }); return { rows: await buildReport() };});
// in your route handler (raw body in hand):verifyDeliverySignature({ rawBody, signature, timestamp, secret });const out = await runner.process(JSON.parse(rawBody));reply.code(out.status).send(out.bodyJson);process(envelope) validates the envelope, answers 202 immediately and runs the handler in the
background, or answers 400 for a bad envelope and 404 when no handler is registered for the
jobCode. A resolved handler is success; a thrown error is failure, reported through the completion
callback when the job tracksCompletion. ctx.log(message, { level, metadata }) appends a log line
to the instance.
Options: lockProvider (default NoOpLockProvider, which blocks nothing), lockKey (default
scheduled-job:{jobCode}), enforceLock (default: follow the envelope’s concurrent flag, locking
when it is false), lockTtlMs (default 10 minutes), onError. The platform fires once per tick;
whether overlapping runs are allowed is the receiver’s decision, which is what the lock is for. A
runner without a real lock provider logs a warning the first time a non-concurrent job fires.
Lock providers: PgLockProvider(executor, { table }) (table fc_locks, create it with
initLockSchema or initLockSchemaWithTable), RedisLockProvider(client, { prefix }) (prefix
fc:lock), InMemoryLockProvider for tests, NoOpLockProvider.
Verifying signed deliveries
Section titled “Verifying signed deliveries”Dispatch webhooks and scheduled-job firings carry X-FlowCatalyst-Signature (hex HMAC-SHA256 of the
timestamp header plus the raw body) and X-FlowCatalyst-Timestamp. verifyDeliverySignature
checks both and throws WebhookSignatureError with a code on any failure:
import { verifyDeliverySignature, WebhookSignatureError } from '@flowcatalyst/sdk';
try { verifyDeliverySignature({ rawBody, // the bytes as received, not re-serialised JSON signature: req.headers['x-flowcatalyst-signature'], timestamp: req.headers['x-flowcatalyst-timestamp'], secret: process.env.FLOWCATALYST_SIGNING_SECRET!, // toleranceSeconds: 300, // default // expectedBearerToken, authorization: // optional second gate, ANDed with the signature });} catch (e) { if (e instanceof WebhookSignatureError) return reply.code(401).send({ error: e.code }); throw e;}Codes: missing_secret, missing_signature, missing_timestamp, invalid_timestamp,
timestamp_expired, timestamp_in_future (more than 60 seconds ahead), invalid_signature,
missing_bearer, invalid_bearer. An empty secret is an error, not a bypass. See
Webhook signatures and Receive webhooks.
A small key-value cache with a required TTL, shared in shape with the other SDKs:
MemoryCacheStore, PgCacheStore (create the table with initCacheSchema) and RedisCacheStore
(ioredis-compatible). The CacheStore interface has get, set(key, value, ttlMs), delete and
getOrSet. get returns null for a miss or an expired entry. A zero or negative TTL throws
CacheError. getOrSet is not atomic across replicas; layer a lock around it if the supplier must
run once.
Testing
Section titled “Testing”- Outbox and use cases. Implement
OutboxDriverin memory (insert,insertBatch,withTransaction) and assert on the rows it received.tests/usecase-envelope.test.tsin the SDK does exactly this: a transaction is a buffer of deferred writes that is flushed on success and discarded on a throw, which models rollback without a database. - Client calls. Point
baseUrlat a local stub server, or useaccessToken: 'test'against a stub. For an end-to-end check, runfcdev(Install fcdev). - Signatures. Compute the HMAC yourself with
node:cryptoand the same timestamp, then callverifyDeliverySignature; the SDK’sdelivery-signature.test.tscovers each failure code. - Run the SDK’s own tests:
pnpm testinclients/typescript-sdk(Node’s built-in runner throughtsx).