How Behemoth fits together
This page gives you the big picture of Behemoth: the parts it is made of, how an application starts, and what happens when a request arrives. Read it after the Quick Start and before the pages on individual parts.
The parts #
Behemoth is a library that you add to your Go application. It connects to your database and your router, and it does not run as a separate service. The following table lists its parts and where you meet each one:
| Part | What it does | Where you meet it |
|---|---|---|
| Plugins | Add an authentication method or a behavior. A plugin declares the tables, routes, hooks, and rate limits it needs. | The plugin list you pass to Prepare |
| Database and migrations | Store users, sessions, and tokens in your database. Behemoth generates migrations from the tables that plugins and your application declare. | A database adapter and the behemoth command |
| Sessions and tokens | Create a session at sign-in, deliver its token by cookie or header, and issue single-use tokens for flows such as password reset. | SessionConfig and RouterConfig.Carrier |
| Hooks | Run your code before or after an operation, or when it fails. | BootConfig.Hooks |
| Routes and routers | Serve the plugins' routes on your framework, with rate limits and consistent error responses. | A router adapter in BootConfig.HTTP |
| Mail and SMS | Hand messages to the sender you provide, so you keep your own delivery service and templates. | BootConfig.Mail and BootConfig.SMS |
| Telemetry | Record logs, audit events, metrics, and traces. | BootConfig.Telemetry |
Two phases: Prepare and Boot #
Behemoth starts in two phases. The split exists so that tools such as the migration command can read your declarations without a database connection.
1. Prepare
Needs no database or router
- Orders the plugins by their dependencies
- Collects tables, hook points, token kinds, and rate-limit rules
- Adds your application's own tables
- Fixes the declarations
2. Boot
Needs a database, optionally a router
- Checks that the database is set up correctly
- Registers hook handlers and starts the plugins
- Builds the session, token, and mail services
- Mounts the routes on your router
AuthContext
What you keep
- Holds the services Behemoth built
- Gives your code the session manager, the store, and telemetry
- Is what plugins receive when they start
The following example shows both phases. The Quick Start explains each line in detail.
// Phase 1: collect the declarations. No database is needed.
app, err := engine.Prepare(
[]core.Plugin{emailpassword.New(emailpassword.Options{})},
engine.PrepareConfig{},
)
if err != nil {
log.Fatal(err)
}
// Phase 2: connect to the database and the router.
db := postgres.NewPostgresAdapter(sqlDB, app.Resolver)
router := gin.New()
secrets := crypto.StaticSecretSource{
Secrets: map[int]string{1: os.Getenv("BEHEMOTH_SECRET")},
Current: 1,
}
ac, err := engine.Boot(
ctx,
app,
db,
engine.BootConfig{
Crypto: crypto.Config{
Secrets: secrets,
},
HTTP: ginadapter.New(router),
},
)
if err != nil {
log.Fatal(err)
}In this example, sqlDB is your open *sql.DB connection and ctx is a context that lives as long as the application. Pass app.Resolver to the database adapter so that your queries and your migrations agree on table and column names.
What Boot checks #
Boot reports a setup problem at startup, not on the first sign-up. It returns an error in these cases:
- The database does not support transactions, as on a standalone MongoDB server.
- The database does not enforce foreign keys, as on a SQLite connection opened without them. Set
BootConfig.AllowUnenforcedForeignKeysto start anyway with a logged warning. - A plugin needs a mail or SMS sender and you did not configure one.
- The router or session configuration is invalid, for example a cookie domain that does not cover your base URL.
What a plugin contributes #
Everything Behemoth does for a user comes from a plugin. A plugin takes part in both phases:
| Phase | What the plugin does |
|---|---|
Prepare | Declares its tables, hook points, token kinds, permissions, and rate-limit rules. |
Boot | Registers its hook handlers, receives the services it works with, and supplies its routes. |
A plugin lists the plugins it depends on. Prepare orders them so that each plugin comes after its dependencies. It returns an error if a required plugin is missing or if the dependencies form a cycle. For example, username builds on emailpassword, so it can only be used with it.
Your application takes part in the same way as a plugin, under the name app unless you set PrepareConfig.AppName:
PrepareConfig.Schemadeclares your tables after every plugin has declared, so it can also add a column to a plugin's table such asusers.BootConfig.Hooksregisters your hook handlers after every plugin's handlers.
The AuthContext #
Boot returns an *core.AuthContext. It is one value that holds the services Behemoth built from your configuration. Behemoth passes it to every plugin when the plugin starts, and you receive the same value as ac.
Most of its fields are for plugins. The following table lists the ones you are most likely to use in your own code:
| Field | What it gives you | Use it to |
|---|---|---|
Store | Behemoth's data layer for its own tables | Look up a user, for example with ac.Store.FindUserByEmail, or query audit events |
SessionManager | Create, validate, and look up sessions | Pass it to httpapi.RequireFreshSession, or manage sessions in a route of your own |
Public | The columns of a row that are safe to send to a client | Answer a request with ac.Public.Of(user) instead of the model |
DB | The root database adapter | Read and write your own tables |
Mailer and SMS | The senders behind BootConfig.Mail and BootConfig.SMS | Wait for queued messages at shutdown |
Telemetry | The logger, audit recorder, and metrics | Log from your own code with the same setup as Behemoth |
HTTPClient | The client Behemoth uses for calls to other services | Make outbound calls with the same timeout and tracing. See Outbound calls. |
The other fields hold services that plugins build on, such as the token manager, the rate limiter, and the cryptography services. The generated reference lists all of them.
Use ac.Store for Behemoth's tables, not ac.DB. The database adapter skips the hooks, ids, timestamps, normalization, and token sealing that the store adds. Use ac.DB for tables that your application or a plugin declared itself.
Shut down cleanly #
Behemoth sends mail and text messages in the background. When your application stops, call Close on both senders so that messages still in the queue are sent first:
shutdownCtx, cancel := context.WithTimeout(
context.Background(),
10*time.Second,
)
defer cancel()
err := errors.Join(
ac.Mailer.Close(shutdownCtx),
ac.SMS.Close(shutdownCtx),
)
if err != nil {
log.Println("shutdown:", err)
}Use a context that is not already cancelled, because the context of a stopping server usually is.
The life of a request #
The following steps describe a request to a route that Behemoth mounted, such as a sign-in:
- Your framework receives the request and passes it to the route through the router adapter.
- If the session token travels in a cookie, Behemoth checks the
Originof the request and refuses form content types. A bearer token needs neither check, because a browser never sends it on its own. - The route's rate limit runs first, so a refused request costs no session lookup.
- Behemoth resolves the session token, if there is one, to a session.
- The plugin's flow runs. Before hooks run first and can change the data or stop the operation. After hooks run when the operation succeeds, and failed hooks run when it does not.
- Writes go through the store. The store seals sensitive values before they reach the database, and it runs data hooks in the same transaction as the write.
- A sign-in creates a session and returns its token by cookie or header.
Telemetry records logs and audit events along the way. A failed request returns a JSON body with an error message and, for most errors, a code that your client can match on.
Where your code fits #
The following table maps common tasks to the place where you do them:
| If You want to | Use |
|---|---|
| Add a sign-in method or a reusable behavior | A plugin that you pass to Prepare |
| Store your own data next to Behemoth's tables | PrepareConfig.Schema, then behemoth generate for the migration |
| Run code around sign-up, sign-in, or a data write | BootConfig.Hooks |
| Send email or text messages | BootConfig.Mail and BootConfig.SMS |
| Use a framework other than the supported ones | Your own implementation of FrameworkDriver |
| Require a signed-in user on your own routes | The httpapi.RequireSession middleware. See Protect your own routes. |
| Call a flow such as sign-in from your own code | The plugin's own methods, such as plugin.SignIn, which work without a router |
Run without a router #
Leave BootConfig.HTTP unset to boot Behemoth without serving any routes. Behemoth still builds and checks the route table, so a misconfiguration surfaces the same way in every process. Use this in a worker or a command-line tool, and call the flows from code.
The examples/init directory in the repository shows these parts together: PostgreSQL, Gin, migrations, a custom plugin, hooks, and telemetry.
Next steps #
To go deeper into a part, read the following pages:
- Quick Start: Build your first authentication flow.
- Hooks: Run your code at fixed points.
- Sessions: Configure how the session token is delivered.
- Routers: Mount the routes on your framework.
- Core tables: See the tables Behemoth creates.
- Migration CLI: Generate migrations from your declarations.