Install Mankai¶
This page shows you how to add Mankai to an existing Hanami app. You choose the gems for the features you need, prepare the database, register each feature's provider, and check that the components load. If you're new to background jobs, caching, or WebSockets, read Core concepts first.
Mankai's features are independent: installing the jobs gems doesn't add caching or WebSockets. Install only the gems for the features you need.
Before you begin¶
Make sure that you have the following:
- Ruby 3.3 or later.
- A Hanami 3 app that boots with
bin/devandbundle exec hanami console. Hanami 3.1 or later also reloads code in job workers. For tested versions, see Compatibility. - For the SQL gems only: Hanami's database layer (
hanami-db), connected throughDATABASE_URLto PostgreSQL, MySQL, MariaDB, or SQLite. The core gems work without a database. - For WebSockets only: Puma, or another Rack server that supports full hijack.
The samples on this page use Bookshelf as the app's module name, the name that hanami new
bookshelf generates. Replace Bookshelf with your app's module name, and bookshelf with your
database name.
Choose your gems¶
Each feature has a core gem and a SQL gem. The core gem works on its own. The SQL gem adds a backend or store that keeps data in your app's database.
The following table describes each gem and when to use it:
| Gem | Adds | Use it when |
|---|---|---|
mankai-jobs |
Background jobs, with memory, inline, and async backends | You're writing tests, or jobs can run on threads inside the web process |
mankai-jobs-sql |
A SQL backend, plus worker, dispatcher, scheduler, and supervisor processes | Jobs must survive a restart, run in a separate worker process, or run on a schedule |
mankai-cache |
A cache component, with memory, file, and null stores | You want to reuse an expensive result, or cache part of a page |
mankai-cache-sql |
A SQL store | Several processes or servers must share cache entries |
mankai-sockets |
A WebSocket endpoint, channels, and a browser client, with a memory backend | The server must push messages to the browser |
mankai-sockets-sql |
A SQL backend for broadcasts | Broadcasts must cross processes, such as from a job worker or the console |
Start with the core gem. Add the SQL gem for a feature when its data must be shared between processes, or when jobs must run in a separate worker process. Production apps usually need the SQL gems.
Add the gems¶
-
Add the gems for your features to your
Gemfile. The following sample adds all six:# Jobs gem "mankai-jobs", group: [:default, :cli] gem "mankai-jobs-sql", group: [:default, :cli] # Cache gem "mankai-cache" gem "mankai-cache-sql" # WebSockets gem "mankai-sockets", group: [:default, :cli] gem "mankai-sockets-sql", group: [:default, :cli]The
hanamicommand loads only the gems in the:cligroup. If a jobs or sockets gem isn't in that group, itshanami jobsorhanami socketscommands don't exist, and its installer writes no migrations. The command code loads only when you runhanami, so the:cligroup doesn't add anything to your web processes. -
Install the bundle:
Prepare the database¶
If you installed only core gems, skip this section.
The SQL gems use the app's default database gateway ("db.gateway"). Mankai doesn't change your
connection settings. If a setting needs to change, the gems log a warning at boot that says what to
fix.
-
Set the connection options for your database. Do this before you run any migration:
- MySQL and MariaDB: add
fractional_seconds=truetoDATABASE_URL, for examplemysql2://localhost/bookshelf?fractional_seconds=true. Without it, the database stores times in whole seconds. -
SQLite: give the connection a busy handler, so that a thread that waits for a lock doesn't block every other thread in the process. Add the following to
config/providers/db.rb: -
PostgreSQL: no change is needed.
- MySQL and MariaDB: add
-
Make sure that the connection pool is large enough. A jobs worker needs one connection for each worker thread, plus two. The sockets SQL backend needs one connection for each executor thread, plus one. If the gems log a pool warning at boot, raise
max_connectionsinDATABASE_URL. -
Install the tables for the SQL gems that you added:
bundle exec hanami jobs install bundle exec ruby -e 'require "mankai/cache/sql"; Mankai::Cache::SQL::Migration.install(root: ".")' bundle exec hanami sockets install --backend=sqlEach command writes a migration into
config/db/migrate/.hanami sockets installalso copies the browser client into your app. To copy the client without writing a migration, use--backend=memory. -
Run the migrations:
The installers and migrations are idempotent: running one twice does no harm. The migration files belong to your app, and you can edit them.
Register providers¶
Each core gem registers its components through a Hanami provider. The SQL gems plug into those providers as a backend or store. Register a provider for each feature you installed.
Register the jobs provider¶
-
Create a base class for your jobs in
app/job.rb:# app/job.rb # auto_register: false require "mankai/jobs" module Bookshelf class Job < Mankai::Jobs::Job end endThe
auto_register: falsecomment stops Hanami from registering the base class as a component. -
Register the queue provider in
config/providers/queue.rb:# config/providers/queue.rb require "mankai/jobs" require "mankai/jobs/sql" Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do configure do |config| config.backend = Hanami.env?(:test) ? :memory : Mankai::Jobs::SQL.backend end endName the provider
queue, notjobs. Hanami already registers your job classes underjobs., soqueue.enqueuerandqueue.backendcan't clash with them. -
If you use the SQL backend, add a worker to
Procfile.dev. With the SQL backend, jobs run only while a worker runs, and this line makesbin/devstart one next to the web server:
In production, run bundle exec hanami jobs start as its own process. For details, see
Deploy to production.
Register the cache provider¶
-
Register the cache provider in
config/providers/cache.rb:
If you didn't install mankai-cache-sql, remove its require and set config.store to :file.
The file store keeps entries in tmp/cache on one machine. The cache needs no extra process.
Register the WebSockets provider¶
WebSockets need more pieces than the other features: a channel, a route, and a way to know who is connecting. The provider checks at boot that every channel it lists exists, so create a channel before you register the provider.
-
Create a base class for your channels in
app/channel.rb: -
Create a channel in
app/channels/chat.rb: -
Register the sockets provider in
config/providers/sockets.rb:# config/providers/sockets.rb require "mankai/sockets" require "mankai/sockets/sql" Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do configure do |config| config.backend = Hanami.env?(:test) ? :memory : Mankai::Sockets::SQL.backend config.allow_anonymous = true # development only: replace with an authenticator config.allowed_origins = :same_origin config.channels = {"chat" => "channels.chat"} end end -
Mount the endpoint in
config/routes.rb:
allow_anonymous lets anyone connect. Use it only in development. Before you deploy, replace it with
an authenticator that reads the session or a signed token. To set up an authenticator, see
Authenticate connections. To load the browser client on a
page, see Use the browser client.
Verify the installation¶
-
Open a console:
-
Check that the component for each installed feature resolves:
Hanami.app["queue.enqueuer"] # jobs Hanami.app["cache"] # cache Hanami.app["sockets.endpoint"] # WebSocketsEach line returns an object. If a line raises an error, find the error in the following list:
Dry::Core::Container::KeyError: the provider isn't loaded. Check the provider file's name and location, and therequirelines at the top.Mankai::Sockets::ConfigurationErrorwith "channel key ... is not registered": a key inconfig.channelshas no matching class. Check the file path and the module names.Mankai::Sockets::ConfigurationErrorabout the authenticator: setconfig.authenticator, or setconfig.allow_anonymous = truein development.
For more errors and fixes, see Troubleshoot.
What's next¶
- Follow Run your first background job.
- Follow Cache your first view fragment.
- Follow Add your first WebSocket channel.
- Look up every setting and API in the reference:
mankai-jobs,mankai-cache, andmankai-sockets.