Module
The FlowCatalyst module is the framework’s only connection to the platform. It holds the
application’s service-account credentials, syncs the application’s definitions (event types,
roles and permissions, connections, dispatch pools, subscriptions, processes, scheduled jobs) to the
platform at deploy time, reports health, and mounts the receivers
through which the platform delivers work back. It is the only framework module that imports a
FlowCatalyst SDK (the Java SDK in Java, github.com/flowcatalyst/go-sdk in Go), and no other module
depends on it.
The platform is not on the request path. If it cannot be reached at start-up the application still
starts, logs the failure, and the flowcatalyst health check reports it.
The normative text is the FlowCatalyst specification. The two languages follow the same rules: settings, defaults, validation and sync order are identical unless a section says otherwise.
What it is not
Section titled “What it is not”| Not built | Notes |
|---|---|
| A framework call that creates a dispatch job outside a use case | Inside a use case, the plan writes one to the outbox (below). Outside one, call the platform endpoint yourself. |
| Per-client sync, principals sync, OpenAPI sync | Not exposed. |
| Wrappers for most platform APIs (events, dispatch jobs, users) | The client wraps what the framework’s own admin pages read. For everything else use the SDK client it exposes (below). |
| Docs sync in Java | Definitions.docs(...) is accepted and skipped with a warning, because the Java SDK cannot sync documentation pages yet. Go sends them. |
Setting it up
Section titled “Setting it up”The module is listed among the application’s modules and configured under flowcatalyst.*.
switch (App.builder() .module(new DatabaseModule()) .module(new OutboxModule()) .module(new UseCaseModule()) .module(new FlowCatalystModule()) .module(new OrdersModule()) .module(new JettyHttpModule()) .shutdownHook(true) .launch(args)) { case Launch.Ran ran -> System.exit(ran.exitCode()); case Launch.Started started -> { }}launch (rather than start) is what lets the module claim the sync command (below).
d := flowcatalyst.Declare(app) // in main: settings, migration set, component claim
fc, err := flowcatalyst.Build(ctx, b, d, // in the build function flowcatalyst.WithDatabases(dbs), flowcatalyst.WithLocks(all))routes, err := fc.Routes() // hand these to httpfw.NewServerDeclare claims the flowcatalyst component, declares the settings and contributes the migration
set that creates fw_dispatch_once (module flowcatalyst). Run database.Migrate before Build.
WithDatabases and WithLocks give the module what it uses when the application has it (the
outbox check, the purge, the scheduled-job lock); both are optional. Build registers the sync
command that app.Launch runs.
Module path: github.com/flowcatalyst/framework/go/flowcatalyst. It requires
github.com/flowcatalyst/go-sdk v0.1.0.
flowcatalyst: base-url: https://platform.example.com application: orders client-id: orders-service # client-secret: from the environment, FLOWCATALYST_CLIENT_SECRET| Key | Type | Default | Meaning |
|---|---|---|---|
flowcatalyst.enabled |
boolean | true |
false makes the module inert: none of the settings below is needed, the catalog is empty, and every client method fails (Java: PlatformClient.isEnabled() is false and the other methods throw; Go: ErrDisabled). |
flowcatalyst.base-url |
URL | required while enabled | Absolute http(s) URL of the platform. |
flowcatalyst.application |
string | required while enabled | This application’s code on the platform, [a-z][a-z0-9-]*. |
flowcatalyst.client-id |
string | required while enabled | OAuth client id of the application’s service account. |
flowcatalyst.client-secret |
secret | required while enabled | Its secret. Use FLOWCATALYST_CLIENT_SECRET or config/secrets.local.yaml (Configuration). |
flowcatalyst.timeout |
duration | 30s |
Timeout of the module’s own calls to the platform. Must be positive. |
flowcatalyst.subscription-target-base-url |
URL | none | What subscription (and scheduled-job) targets given as a path resolve against. |
flowcatalyst.sync.on-boot |
boolean | false |
Also sync definitions in the started phase. Failures are logged, never fatal. |
flowcatalyst.outbox.stale-after |
duration | 5m |
The outbox health check is down when the oldest undelivered row is older than this. Must be positive. |
flowcatalyst.receivers.* |
The receivers’ settings, on the Receivers page. |
The service account (client id and secret) and the application code must already exist on the
platform; the framework does not create them (what the platform needs).
When the module is enabled, missing or malformed settings fail start-up with one error naming every
one. The module claims the flowcatalyst component, so a misspelt key under it
(flowcatalyst.receivers.enabeld) fails start-up too, listing the keys it reads.
Health and readiness
Section titled “Health and readiness”Two checks are added, both informational (see
modules and lifecycle): /health/ready reports them
(top-level DEGRADED, still 200) but they do not make it answer 503, so a platform outage does not
take every replica out of rotation.
| Check | Down when |
|---|---|
flowcatalyst |
Fetching a token with the service-account credentials fails (the platform refuses them or cannot be reached, and the cached token has run out). While a receiver has handlers it is also down when the token does not name the application’s service principal, because then no handler can run (who runs the handler). The SDK caches the token and refreshes it about a minute before expiry, so the check can stay up briefly after the platform goes down. |
outbox |
The oldest undelivered outbox_messages row (status PENDING or IN_PROGRESS; terminal failures are not a backlog) is strictly older than flowcatalyst.outbox.stale-after. Two min(created_at) queries, no writes. Added only when a database module exists and the default database has an outbox_messages table; otherwise there is no check and an INFO line says why. |
To make either decide readiness, list it as critical:
app: health: critical: [flowcatalyst, outbox]The platform client
Section titled “The platform client”The module provides a client acting as the application’s own service account. Failures are the
module’s platform error (Java: unchecked PlatformException; Go: *PlatformError). The messages carry
the status and the platform’s code, never a response body or a credential, because they appear on the
unauthenticated health endpoint.
PlatformClient offers isEnabled(), application(), baseUrl(), verifyCredentials(),
accessToken() (a bearer token cached by the SDK; never log it), clearToken(),
servicePrincipal() (the sub of that token when its type is SERVICE: the principal the
receivers run handlers as; read once per token) and sdk(). The receivers use two more,
completeJobInstance(instanceId, Completion, result) and logJobInstance(instanceId, level, message).
It also has read methods used by the framework’s admin pages (event types, roles, users,
invitations, events, dispatch jobs, platform config). A failed call is a PlatformException whose
kind() says whether the platform refused it (FORBIDDEN) or did not know the record (NOT_FOUND).
Platform.Client() returns a *PlatformClient: AccessToken(ctx) (a config.Secret, cached),
ClearToken(), VerifyCredentials, ServicePrincipal(ctx), CompleteJobInstance, LogJobInstance,
BaseURL() and SDK(). It holds two SDK clients over one token source, because the SDK retries inside
every call and the completion calls have their own bounded retry.
Calling a platform API yourself
Section titled “Calling a platform API yourself”For platform APIs the client has no method for, use the SDK client it exposes, or the framework’s HTTP client authenticated with the application’s token. The platform authorises each call by the service account’s roles.
platformClient.sdk() is the Java SDK’s FlowCatalystClient (io.flowcatalyst:flowcatalyst-sdk, the
version the framework BOM pins), sharing the token cache with accessToken() and clearToken(). On a
401 it drops the cached token, fetches a new one and sends the request once more; it retries 408,
429, 502, 503 and 504 inside each call. Its failures are the SDK’s FlowCatalystException,
not PlatformException.
var roles = platformClient.sdk().roles().list();For a route the pinned SDK has no method for, register a named HTTP client with the application’s
token as bearer credential (from PlatformApiCallTest):
ServiceClient api = app.get(ServiceClients.class) .register( ServiceOptions.builder("platform", app.config().get(FlowCatalystModule.BASE_URL)) .auth(Auth.bearer(platformClient::accessToken, platformClient::clearToken)) .build());After a 401 the client calls clearToken() and sends the request once more with a fresh token.
Timeouts and retries are the HTTP client’s; flowcatalyst.timeout covers only the module’s own calls.
SDK() returns a *client.FlowCatalystClient of github.com/flowcatalyst/go-sdk that calls the
platform as the application’s service account over the token AccessToken caches. A call the platform
answers 401 clears that token and is sent once more with a fresh one (a second 401 is the
answer); the SDK retries 408, 425, 429 and 5xx itself. Its errors are the SDK’s: a *client.APIError
carries the platform’s answer, so log it and never return it to a caller. Both SDK() and BaseURL()
fail with ErrDisabled while the module is disabled. From flowcatalyst/sdk_test.go:
sdk, err := r.fc.Client().SDK()if err != nil { t.Fatal(err)}c, err := sdk.Clients().GetByIdentifier(t.Context(), "acme")AccessToken(ctx) can also be the credential of a named httpclient for routes the SDK does not cover.
Creating a dispatch job
Section titled “Creating a dispatch job”A dispatch job is the platform’s unit of delivery (Dispatch jobs). Most are
made by the platform from an event and a subscription. To create one from your application, add it to a
use case’s plan (Java: plan.andDispatch(DispatchJob)): it is written to the outbox in the same
transaction and the platform’s outbox relay delivers it to POST /api/dispatch-jobs/batch. See the
write path.
- The service account the relay runs with needs
platform:messaging:batch:dispatch-jobs-write, which the platform’sapplication-servicerole grants. - The platform sets
X-Event-Typeto the job’scode, so a dispatch handler registered for that code receives it like any other (Receivers). - A job’s code must start with the application code (
{application}:...).
Outside a use case there is no framework call. Calling the endpoint yourself works: {"items": [...]},
at most 1000 items, answered by {"results": [{"id", "status", "error?"}]} in item order. Send
metadata as an array of {"key", "value"}: the platform refuses the whole batch for an object.
Declaring definitions
Section titled “Declaring definitions”Definitions are the application’s platform-side catalog, written in code next to the code that uses
them. A module contributes them while it is being declared; nothing is checked at that point, because
settings are not readable yet. Everything is validated together at start-up (Go: in Build) and each
problem names the contributing module.
@Overridepublic void register(AppBuilder app) { Definitions.in(app) .eventType("orders:sales:order:placed", "Order placed", "A customer placed an order.") .permission("orders:sales:order:read", "Read orders") .role("order-clerk", "orders:sales:order:read") .connection("main", "Main") .subscription( Definition.Subscription.of( "billing-on-placed", "Bill placed orders", "/webhooks/billing", "orders:sales:order:placed") .viaConnection("main")) .scheduledJob(Definition.ScheduledJob.of("nightly-export", "Nightly export", "0 0 2 * * *").tracking(true));}Methods: eventType, permission, role (a name and permission codes, or a Definition.Role),
subscription, connection, dispatchPool, scheduledJob, process and docs. The Definition
records have of(...) factories and with... copies (for example Subscription.viaConnection,
viaSharedConnection, inPool, withMode, ScheduledJob.tracking, inZone).
A Definition.Role has withDisplayName, withDescription and withClientManaged(). The last marks the role
client-managed (the record component clientManaged, the platform’s flag of that name): a client’s own administrators
may assign it to their users. The sync sends clientManaged: true for such a role and leaves the field off for the
others, which the platform stores as false, so a role marked client-managed on the platform but not in code loses the
flag at the next sync:
.role( Definition.Role.of("operator", "orders:sales:order:read") .withDisplayName("Operator") .withClientManaged() .withDescription("Runs the day's orders."))d := flowcatalyst.Declare(app)d.Definitions("orders"). EventTypeOf(orders.Placed, "Order placed", "A customer placed an order."). Permission("orders:sales:order:read", "Read orders"). Role(flowcatalyst.NewRole("order-clerk", "orders:sales:order:read")). Connection("main", "Main"). Subscription(flowcatalyst.NewSubscription("billing-on-placed", "Bill placed orders", "/webhooks/billing", "orders:sales:order:placed").ViaConnection("main")). ScheduledJob(flowcatalyst.NewScheduledJob("nightly-export", "Nightly export", "0 0 2 * * *").Tracking(true))Declared.Definitions(module) collects event types (EventType, or EventTypeOf for a typed
event.Type), permissions, roles (NewRole), connections, dispatch pools, subscriptions
(NewSubscription(...).ViaConnection(...).InPool(...)), scheduled jobs
(NewScheduledJob(...).Tracking(true).Targeting(url).WithTimeout(n); a job’s target is an absolute
URL), processes and docs (Docs(slug, content)). Optional numbers (MaxRetries, RateLimit, …) are
0 for “the platform’s default”; a negative number is a problem.
A role has WithDisplayName, WithDescription and WithClientManaged copies. WithClientManaged() sets
Role.ClientManaged, the platform’s clientManaged flag: a client’s own administrators may assign the role to their
users. The sync sends clientManaged: true for such a role and leaves the field off for the others, which the platform
stores as false, so a role marked client-managed on the platform but not in code loses the flag at the next sync:
Role(flowcatalyst.NewRole("operator", "orders:sales:order:read"). WithDisplayName("Operator").WithClientManaged().WithDescription("Runs the day's orders.")).Validation is the framework’s and is stricter than the platform’s:
- Segments are lowercase
[a-z0-9][a-z0-9_-]*. - Event type, permission and process codes start with
flowcatalyst.application. - Role names carry no
app:prefix (the platform adds it). - Cron expressions have 6 fields, seconds first.
- A subscription names at least one event type and a target that is an absolute URL, or a path when
subscription-target-base-urlis set (a path target without the base fails start-up). - Codes are unique across modules.
Permissions travel only inside roles: a declared permission that no role grants is logged as a warning.
When the application registers admin sections, their permissions and a role
admin that grants them one by one join the catalog by themselves (Go: Declared.AdminDefinitions(adm)).
Declaring your own role named admin turns that off.
The suggested role can be named or declined, in Go and in Java. In Go AdminDefinitions(adm, flowcatalyst.AdminRoleName("platform-operator"))
declares it under another name, in Java new FlowCatalystModule().adminRoleName("platform-operator"); the display name is
AdminRoleDisplayName("...") / adminRoleDisplayName("...") (otherwise Administrator for admin, and for another name
the name with hyphens as spaces and the first letter upper-case, so platform-operator gives Platform operator);
WithoutAdminRole() / withoutAdminRole() adds the permissions and no role (using it with a name fails start-up; when no
declared role grants {app}:admin:console:view, by its definition or through the permission mapping, start-up logs a
warning, not a failure). An empty or malformed name fails the ordinary role-name check at start-up and never falls back to
admin. Renaming the role creates a new role on the platform: people who held
the old one must be given the new one. Declaring your own role of the chosen name keeps yours and adds nothing.
Client-managed roles and operators-only admin sections. A client-managed role must not carry the permission of an
operators-only admin section (the partitions section is
one: a partition holds every client’s rows; see operators-only sections).
Give the module the application’s permission mapping, the same value the auth module has, and start-up (and the sync)
refuses such a role, naming it and the permission, whether the role’s definition lists the permission or the mapping
grants it (orders:admin:*:* included):
.module(new FlowCatalystModule().withPermissionMapping(MAPPER))The module reads the admin sections from the registry itself. The refusal is made even when flowcatalyst.enabled is
false, and DefinitionSync.run makes it again before it sends anything (an IllegalStateException, “the definitions
are not sent”).
fc.AdminDefinitions(adm) // at declaration time: the registry the check reads...flowcatalyst.Build(ctx, b, fc, flowcatalyst.WithPermissionMapping(mapper))The operators’ role is never client-managed, and neither is the suggested role. The mapping is run for a principal that
holds only the role, so it can be checked only if it depends on the principal’s roles. In an operators-only admin area
console:view is itself an operators-only permission, so a client-managed role that holds it fails start-up.
Removing a definition from code does not delete it on the platform. Deletions are an operator action.
Syncing
Section titled “Syncing”Sync is a deploy-time action, not a start-up one. The module claims the command sync:
app sync --dry-run # validate and report; sends nothing to the platformapp sync # push to the platform(for a Java jar, java -jar app.jar sync).
- Exit codes:
0success,1a category failed,2bad argument or module disabled. --dry-runnever contacts the platform (neither SDK has a preview). It validates and printsWOULD_SYNCwith the codes.- Order: roles, event types, connections, dispatch pools, subscriptions, processes, scheduled jobs,
docs. Each category is its own SDK call, so one failure does not stop the others. It prints one line
per category, for example
ROLES SYNCED sent=2 created=1 updated=1 deleted=0. - Idempotent. Running it again with unchanged definitions changes nothing.
- The command runs after services are built and before any
boothook; no server starts. flowcatalyst.sync.on-boot: truealso syncs in the started phase, logging and continuing on failure.
In Java, building services includes the database module, which connects to the default database and
applies pending migrations. So even a dry run needs database access and can change the schema (a
checksum mismatch fails it). If a deploy step must not touch the schema, set
database.instances.<name>.migrate: false (or DATABASE_INSTANCES_<NAME>_MIGRATE=false) for that run;
the instance must still be reachable.
Programmatically: app.get(DefinitionSync.class).run(DefinitionSync.Mode.APPLY) (or DRY_RUN) returns a
SyncReport of CategoryResults and throws SyncException (carrying the report) if any category
failed, after attempting all of them.
Programmatically: Platform.Sync(ctx, mode) with flowcatalyst.SyncApply or flowcatalyst.SyncDryRun
returns a SyncReport, and a *SyncError carrying it when any category failed. The sync never sets a
remove-unlisted flag.
What the platform needs before the first sync
Section titled “What the platform needs before the first sync”The sync authenticates as the application’s service account (flowcatalyst.client-id), and the
platform refuses it until that account is set up. These came from running a real service against a
real platform:
| Without | The platform answers | Do |
|---|---|---|
The account’s role platform:application-service |
403 PERMISSION_REQUIRED for every category |
PUT /api/service-accounts/{id}/roles, or create the account with POST /api/applications/{id}/provision-service-account |
| The account attached to the application | 400 APPLICATION_SERVICE_ACCOUNT_REQUIRED for connections, then 404 CONNECTION_NOT_FOUND for the subscription that uses it |
POST /api/applications/{id}/service-account (or provision-service-account) |
Anchor reach (a service account created with clientIds is PARTNER, and scope: ANCHOR is ignored while it has any) |
403 ANCHOR_REQUIRED_FOR_PLATFORM_SWEEP for scheduled jobs, which the sync sends platform-scoped |
An account with no clientIds and scope: ANCHOR |
The roles the application declares exist on the platform only after the first successful sync, so
assign them to people after it. A new client’s dispatch queue is picked up by the platform’s router
within 5 minutes, so the first dispatch job for a client created just before may wait that long in
QUEUED.
A scheduled job is delivered to its targetUrl, and the platform has no default for it: a job
without one fails every firing with No target URL configured for job. So, with
flowcatalyst.subscription-target-base-url set, the sync sends this service’s own
{subscription-target-base-url}{flowcatalyst.receivers.path}/scheduled-jobs for a job that declares no
target, as long as a scheduled-job handler is registered and the receivers are enabled. A path target
(/internal/run) resolves against the base like a subscription’s, and an absolute URL is sent as
declared. Without the base nothing is guessed. Java and Go behave the same
(conformance/flowcatalyst/job-targets.json).
The outbox: the platform delivers it
Section titled “The outbox: the platform delivers it”The framework’s write path writes event and audit rows to
outbox_messages in your database. It does not deliver them. Delivery is the platform’s outbox
relay, configured with the application’s own service-account credentials and pointed at your database;
it posts to the platform’s batch endpoints, and the platform fans events out to subscriptions.
Consequently:
- An application that wants events, dispatch jobs, subscriptions or scheduled jobs needs a platform. The framework has no local fan-out, subscription or job dispatch.
- The relay has to be pointed at your database.
fcdev outboxis the standalone poller for an application’s own PostgreSQL; the platform server’s own processor reads only the platform’s database. Both are described, with their flags and environment variables, in The transactional outbox. - The
outboxhealth check (above) watches the backlog.
Minimal use of the standalone poller, run beside the application:
fcdev outbox \ --source-db-url 'postgres://user:pass@db-host:5432/app' \ --target-url https://platform.example.com \ --client-id orders-service --client-secret "$FLOWCATALYST_CLIENT_SECRET"It claims rows with FOR UPDATE SKIP LOCKED, posts by row type (EVENT, DISPATCH_JOB, AUDIT_LOG) and
deletes a row once the platform accepts it. The service account needs the batch-ingest permissions that
the platform’s application-service role carries. Two pollers never take the same row, but a message
group’s order is enforced inside one process, so run one poller per outbox.
Receivers
Section titled “Receivers”The module also mounts the receivers for dispatch jobs and scheduled-job firings
(POST /fc/dispatch, POST /fc/scheduled-jobs) with signature checks and ack, defer and reject
results. They have their own page: Receivers. A receiver with no
registered handler answers 404, and flowcatalyst.receivers.enabled: false removes both routes, for
an application that wants only the token, the sync or the health check.
Testing
Section titled “Testing”Both languages ship an in-process stand-in for the platform that serves a token endpoint and the sync
endpoints and records scheduled-job completion and log calls: FakePlatform in the
framework-flowcatalyst test-jar (Java), package fakeplatform (Go). See
Testing and, for building signed deliveries,
Receivers.