Skip to content
Edit this page View source of this page

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/dev and bundle 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 through DATABASE_URL to 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

  1. 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 hanami command loads only the gems in the :cli group. If a jobs or sockets gem isn't in that group, its hanami jobs or hanami sockets commands don't exist, and its installer writes no migrations. The command code loads only when you run hanami, so the :cli group doesn't add anything to your web processes.

  2. Install the bundle:

    bundle install
    

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.

  1. Set the connection options for your database. Do this before you run any migration:

    • MySQL and MariaDB: add fractional_seconds=true to DATABASE_URL, for example mysql2://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:

      # config/providers/db.rb
      Hanami.app.configure_provider :db do
        config.gateway :default do |gw|
          gw.connection_options after_connect: ->(conn) { conn.busy_handler_timeout = 5000 }
        end
      end
      
    • PostgreSQL: no change is needed.

  2. 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_connections in DATABASE_URL.

  3. 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=sql
    

    Each command writes a migration into config/db/migrate/. hanami sockets install also copies the browser client into your app. To copy the client without writing a migration, use --backend=memory.

  4. Run the migrations:

    bundle exec hanami db migrate
    

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

  1. 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
    end
    

    The auto_register: false comment stops Hanami from registering the base class as a component.

  2. 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
    end
    

    Name the provider queue, not jobs. Hanami already registers your job classes under jobs., so queue.enqueuer and queue.backend can't clash with them.

  3. 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 makes bin/dev start one next to the web server:

    web: bundle exec hanami server
    worker: bundle exec hanami jobs start
    

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:

    # config/providers/cache.rb
    require "mankai/cache"
    require "mankai/cache/sql"
    
    Hanami.app.register_provider(:cache, from: :mankai_cache) do
      configure do |config|
        config.store = Hanami.env?(:test) ? :memory : Mankai::Cache::SQL.store
        config.expires_in = 3600
      end
    end
    

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.

  1. Create a base class for your channels in app/channel.rb:

    # app/channel.rb
    # auto_register: false
    require "mankai/sockets"
    
    module Bookshelf
      class Channel < Mankai::Sockets::Channel
      end
    end
    
  2. Create a channel in app/channels/chat.rb:

    # app/channels/chat.rb
    module Bookshelf
      module Channels
        class Chat < Bookshelf::Channel
          def subscribe(_subscription)
            Success(streams: [Mankai::Sockets::Stream.of("chat")])
          end
        end
      end
    end
    
  3. 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
    
  4. Mount the endpoint in config/routes.rb:

    # config/routes.rb
    mount Hanami.app["sockets.endpoint"], at: "/sockets"
    

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

  1. Open a console:

    bundle exec hanami console
    
  2. Check that the component for each installed feature resolves:

    Hanami.app["queue.enqueuer"]   # jobs
    Hanami.app["cache"]            # cache
    Hanami.app["sockets.endpoint"] # WebSockets
    

    Each 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 the require lines at the top.
    • Mankai::Sockets::ConfigurationError with "channel key ... is not registered": a key in config.channels has no matching class. Check the file path and the module names.
    • Mankai::Sockets::ConfigurationError about the authenticator: set config.authenticator, or set config.allow_anonymous = true in development.

For more errors and fixes, see Troubleshoot.

What's next