Modules and lifecycle
An application is a set of capabilities (database, locks, HTTP, the platform client) plus your own code, wired in a defined order. Both implementations follow the same specification (Core contract) and the same start-up and shutdown sequence, but the shape of the code differs because the languages do.
| Java | Go | |
|---|---|---|
| Unit of assembly | a Module, listed in code on App.builder() |
a capability package with a Declare function, called on an fw.App |
| How services find each other | typed lookup (app.get(Locks.class)), with providers run in dependency order |
none; you build services in one function and pass each its dependencies, so a missing one is a compile error |
| Configuration problems | all reported together | all reported together |
| Problems while building (a database that does not answer) | collected where possible | stop at the first failing component |
| Replacing a service in a test | AppBuilder.override(type, instance) when APP_ENV=test |
the build function takes the collaborators a test replaces as parameters |
The sequence
Section titled “The sequence”- Declare. Every module or package says what it needs: settings, instance sections, migration sets, commands, the configuration components it claims.
- Configure. Configuration is loaded and every declared setting is validated. Every problem is reported at once, naming the key.
- Build. Services are constructed.
- Boot. Each module reads its configuration, registers health checks, routes and background loops.
- Started. Work that needs every module booted (the HTTP server compiles its route table and starts listening).
- Run until the process is signalled or the server returns.
- Shutdown, in the reverse of start-up.
A command (sync, openapi, migrate) stops after step 3: no boot, no routes, no server.
The Module interface
Section titled “The Module interface”public interface Module { String id(); default void register(AppBuilder app) throws Exception {} default void boot(App app) throws Exception {} default void started(App app) throws Exception {} default void shutdown(App app) throws Exception {}}The id matches [a-z][a-z0-9-]* and must be unique. core is taken by the framework’s own module,
which is added for you.
| Hook | Use it to | Do not |
|---|---|---|
register(AppBuilder) |
declare settings, provide services, claim configuration components, contribute migrations and definitions, claim commands | build services, read config values, start threads |
boot(App) |
read config, look up services, add health checks, register routes and background loops (loops start only after every started hook has run) |
provide new services |
started(App) |
work that needs every module booted | provide new services |
shutdown(App) |
stop what you started |
App.builder().module(a).module(b)...start() does this, in order:
- Calls every module’s
register, in the order listed. - Loads and validates configuration. Any problem fails here.
- Builds every provided service, eagerly. A provider asks for what it needs and that is built first.
- Calls every module’s
boot, in order. - Calls every module’s
started, in order, after everybootfinished. If anybootfailed, nostartedruns. - Returns the running
App.
Failures are thrown from start() as StartupException, collected so one start reports every
problem: a duplicate module id, two providers for one type, a lookup of a type nobody provides, a
dependency cycle, any config error, an unknown driver, an exception from a provider or hook. Services
already built are closed before it is thrown; StartupException.problems() lists them.
Services
Section titled “Services”A module provides a service by type during register. The lambda is a Provider<T>
(T create(Lookup lookup) throws Exception); Lookup offers get(Class), contributions(Class)
and moduleId().
app.provide( OrderUseCases.class, lookup -> new OrderUseCases( new OrderRepository(), lookup.get(Databases.class).defaultInstance(), lookup.get(Events.class), lookup.get(Ids.class), OrderUseCases.Policies.defaults()));- One provider per type. A second
providefor a type fails start-up, naming both modules. - Providers run once, at start-up, in dependency order. A provider that asks for a type nobody provides fails start-up and names the asking module.
- The framework provides
Config,InstantSource,Ids,MonotonicClock,HealthandEnvironmentVariables, plusMetricsandBackground; a module cannot provide these.Ids.generate("ord")givesord_plus 13 characters. Use the injectedInstantSource, notInstant.now(), so tests can fix the clock. - A service that is
AutoCloseableis closed at shutdown.
After start-up, App is a typed map: app.get(Locks.class) throws IllegalArgumentException if
absent, app.find(ContextResolver.class) returns an Optional. App also has config(),
health(), moduleIds(), buildOrder() and shutdownDrain().
Contributions
Section titled “Contributions”A module can hand a value to another module that collects them. This is how migrations work:
MigrationSet.contribute(app, OrdersModule.class, "db/migration/orders");The class passed is used only for its class loader: it says which jar holds the SQL directory. Call
it from register, because the contributing module’s id is taken from the module being registered.
The raw form is app.contribute(Class<T>, T). The FlowCatalyst module’s Definitions.in(app) uses
the same mechanism.
Builder options
Section titled “Builder options”| Method | Meaning |
|---|---|
module(Module) |
add a module; order matters (register, boot, started, migrations) |
configDirectory(Path) |
where application.yaml lives; default config under the working directory |
environment(Map<String,String>) |
the environment to read instead of System.getenv(); tests use this |
instantSource(InstantSource) |
the wall clock |
monotonicClock(MonotonicClock) |
the clock used by locks and timeouts |
shutdownHook(boolean) |
close from a JVM shutdown hook; default off |
override(Class<T>, T) |
replace a provided service; only when APP_ENV is test, otherwise start-up fails |
A builder starts once; reusing it throws IllegalStateException.
A complete small module
Section titled “A complete small module”static final class MailModule implements Module { static final Setting<String> HOST = Setting.string("mail.host").asRequired().describedAs("SMTP host."); static final Setting<Secret> PASSWORD = Setting.secret("mail.password");
@Override public String id() { return "mail"; }
@Override public void register(AppBuilder app) { app.declare(HOST); app.declare(PASSWORD); app.provide( Mailer.class, lookup -> { Config config = lookup.get(Config.class); return new Mailer(config.get(HOST), config.find(PASSWORD).orElse(Secret.of(""))); }); }
@Override public void boot(App app) { app.health().add("mail", () -> { if (app.get(Mailer.class).host.isEmpty()) { throw new IllegalStateException("no host"); } }); }}Declare, then build
Section titled “Declare, then build”There is no service container and no lookup by type. Each capability package has a Declare
function that registers its settings, instance sections and migration sets on the fw.App and
returns a typed handle. You then build the services in one function, passing each its dependencies
(from go/examples/locks-demo):
func declare(app *fw.App) declared { d := declared{ db: database.Declare(app), redis: redisfw.Declare(app), locks: locks.Declare(app), } dblock.Declare(app) // the fw_lock migration return d}dbs, err := database.Connect(ctx, b, d.db)if err != nil { return nil, err}if err := database.Migrate(ctx, b, dbs); err != nil { return nil, err}clients, err := redisfw.Connect(ctx, b, d.redis)if err != nil { return nil, err}all, err := locks.Build(ctx, b, d.locks, locks.WithStore("main", dblock.Store(dbs)), locks.WithStore("shared", redislock.Store(clients)), locks.DefaultStore("main"))Within a package, Declarer gives you DeclareSetting, Instances(path, capability, keys...)
(and InstancesWithoutDefault), ClaimComponent, Migrations(fs.FS) and DeclarationCommand.
App.Launch(ctx, args, build) returns the process exit code:
- configure: every declared setting and instance section is checked, as are removed keys and
claimed components; every problem is reported at once as a
*fw.StartupError(exit 1); - build: your
BuildFuncconstructs the services and registers lifecycle work on the*fw.Boot(Health,Loop,OnStarted,OnShutdown,Command), then returns what to serve (fw.Serve, usually the HTTP server, or afw.ServeFunc); - a first argument claimed with
Boot.Commandruns that command after build, with no started actions, loops or serving, then shuts down; - start: the started actions in registration order, then the loops, then serve;
- it runs until SIGTERM or SIGINT, or until serve returns;
- shutdown: not ready from then on; loops stop first; serve is cancelled and waited for; then
the shutdown actions run in reverse registration order, each bounded by
app.shutdown.drain.
Boot also gives you AppName, Environment, LookupEnv, Clock, Ids, Metrics,
Logger(module), Ready and HealthReport.
Tests use App.Start(ctx, build), which returns a *fw.Running (Health, Ready, Done,
Shutdown). A build that fails runs the shutdown actions registered so far. A panic in build, a
started action, a command or serve is recovered and treated as a failure. Declaring after Launch or
Start began panics. Options for fw.New: WithEnvironment, WithClock, WithConfigDir,
WithLogger, WithOutput.
Shutdown
Section titled “Shutdown”Shutdown is idempotent and runs in a fixed order: not ready first, then the
background loops stop, then each module’s shutdown work
runs in reverse order, then built services are closed in reverse build order. A failure in one step
is logged and does not stop the rest. Each step gets app.shutdown.drain (default 10s). A step
still running after that is logged as an overrun, interrupted (Java) or abandoned (Go), and shutdown
moves on without waiting, so write shutdown work that stops promptly.
App.close() is idempotent and AutoCloseable, so use try-with-resources in tests.
builder.shutdownHook(true) also closes the app from a JVM shutdown hook; the default is off so tests
leave no hooks behind. The steps run on virtual threads.
Loops stop first, then serve is cancelled and waited for, then shutdown actions run in reverse registration order. An overrun is logged and abandoned.
Databases and migrations
Section titled “Databases and migrations”The database capability provides one pooled connection per configured instance, each with a
database:<name> health check. Instances, pools and migrate are configuration
(Configuration); see Database and
Redis for the keys.
Migrations are plain SQL files, forward only, named V<version>__<description>.sql with a positive
integer version (for example V0001__create_orders.sql). Each module contributes at most one set (a
module id plus a location), and your application contributes its own the same way. Sets are applied
to the default database instance, in module registration order and by version within a set, only
when that instance’s migrate is true (the default). Each file runs in its own transaction together
with its row in fw_schema_history, under a PostgreSQL advisory lock so instances starting together
apply each file once. A changed checksum of an applied file, a missing applied file or a skipped lower
version fails start-up.
Registration order is migration order: list the module whose tables you depend on (the outbox module, for example) before your own.
Health checks
Section titled “Health checks”A check returns normally for up and fails for down; the message becomes the reason. All checks run in
parallel, each limited by app.health.timeout (default 2s), and report Up, Down(reason) or
TimedOut. With the HTTP server, /health/ready serves the report (HTTP).
app.health().add("mail", () -> { if (app.get(Mailer.class).host.isEmpty()) { throw new IllegalStateException("no host"); }});// a dependency you can serve requests withoutapp.health().add("flowcatalyst", client::verifyCredentials, Criticality.INFORMATIONAL);app.health().check() returns a HealthReport: isUp() is true when every check is up,
isReady() when every critical one is, criticality(name) says how a check ran.
b.Health("mail", fw.Informational, func(ctx context.Context) error { return mailer.Ping(ctx)})b.Health(name, fw.Critical | fw.Informational, check). IsReady looks at the critical checks only.
database:<name> and redis:<name> are critical; background:<name> is informational unless the
loop’s Options.Critical is set.
A check is critical (the default) or informational. A critical check that is not up makes the application not ready; an informational one is reported but never decides readiness. Configuration overrides a module’s choice by name:
app: health: critical: [flowcatalyst] # the platform decides readiness again informational: ["database:reporting"]A name in both lists fails start-up. A name that matches no check is logged at WARN once start-up
finishes, not refused, because some checks exist only in some deployments. The core claims the app
component, so a misspelt key under it (app.helth.critical) fails start-up as unknown.
Commands
Section titled “Commands”A module can claim a command name, which is how java -jar app.jar sync or app sync works.
Command names match [a-z][a-z0-9-]*; two claims for one name fail start-up. A command runs after
configuration and building and before boot, so it has no routes, no health checks and no server.
Anything not claimed starts the application normally; an unknown argument is not an error.
app.command( new Command() { @Override public String name() { return "mail-test"; } @Override public int run(App app, List<String> args, PrintStream out) { out.println("host " + app.get(Mailer.class).host); return 0; } });AppBuilder.launch(String... args) returns Launch.Ran(exitCode) when a command ran (the
application is closed first) or Launch.Started(app):
switch (App.builder().module(/* ... */).launch(args)) { case Launch.Ran ran -> System.exit(ran.exitCode()); case Launch.Started started -> { } // running; the server threads keep the JVM alive}Anything thrown out of a command, an Error included, is logged and launch returns
Launch.Ran(1) after closing the application, so non-daemon threads end and the JVM exits. An
Error from a provider, boot or started closes the services built so far and propagates.
b.Command("mail-test", func(ctx context.Context, args []string, out io.Writer) int { fmt.Fprintln(out, "host", host) return 0})A first argument claimed with Boot.Command runs that command after build; Launch returns its
exit code. A panic in a command is recovered and treated as a failure.
Declaration-phase commands need only what modules declared, not configuration or services. Writing
the OpenAPI document is the first (app openapi, see Typed operations and
OpenAPI). They run after declaration and stop there:
no configuration file is read, no provider runs, nothing connects, so they work in a build without a
database. In Java a module claims one with the app.command(DeclarationCommand) overload (its
run(Declarations, args, out) gets a read-only view with moduleIds(), settings() and
contributions(Type.class)); in Go with Declarer.DeclarationCommand.
Drivers and named instances
Section titled “Drivers and named instances”Things an application can have many of are code: lock stores, secret stores, HTTP clients and
rate limiters are named in a builder with a factory that names the driver, for example
LocksModule.builder().store("main", DatabaseLockStores.database()). No configuration key chooses a
driver (Configuration).
Connections are named instances in configuration. Database and Redis build every instance under
<section>.instances. A key that an instance factory did not read fails start-up as unknown, so a
typo cannot pass silently; with exactly one instance default may be omitted, with several it must
name one; a capability with no configured instances is valid.
An InstanceFactory<T> receives the instance name, its InstanceConfig section, a Lookup and the
instances built so far, and reads its keys through typed getters (string, integer, bool,
duration, secret, findString, section). Instances.build(Database.class, "database", lookup, factory) returns a registry with get(name), defaultInstance(), names() and all(). The shipped
registries (Locks, Databases, RedisConnections) have package-private constructors; a capability
of your own writes a registry around Instances.
A capability declares the keys of its instances once with Declarer.Instances (there is no driver
registry: one schema for every instance), so unknown or malformed keys are reported with the other
configuration problems at configure time. An instance exists only when a file names it; its values may
then come from the environment (DATABASE_INSTANCES_MAIN_URL).
The specification is the Core contract. Configuration is covered next in Configuration.