Skip to content
Edit this page View source of this page

New to WebSockets? Read WebSockets and follow Add your first WebSocket channel before you use this reference.

Mankai

mankai-sockets-sql

mankai-sockets-sql is a backend for mankai-sockets that stores broadcasts in a database table, so that they reach subscribers in other processes. Use it when you run several Puma workers or servers, serve WebSocket connections from a separate process, or broadcast from a job worker or a console.

This page is the reference for installing the backend, its options, its delivery behavior, and its database requirements. For step-by-step instructions, see Broadcast across processes. For the provider settings, see mankai-sockets.

Before you begin

Your app needs the following:

  • mankai-sockets, set up as described in its installation steps.
  • hanami-db with a configured database, for example through DATABASE_URL. hanami-db registers the db.gateway component that the backend uses by default.
  • PostgreSQL, MySQL, MariaDB, or SQLite.

Installation

To install the backend, complete the following steps:

  1. Add both gems to your Gemfile, in the :default and :cli groups. The hanami command loads only the :cli group, so the installer needs the SQL gem there to write the migration:

    # Gemfile
    gem "mankai-sockets", group: [:default, :cli]
    gem "mankai-sockets-sql", group: [:default, :cli]
    
  2. Install the bundle:

    bundle install
    
  3. Generate the migration:

    bundle exec hanami sockets install --backend=sql
    

    The installer writes the create_mankai_sockets_messages migration to config/db/migrate. It also copies the browser client, as described in mankai-sockets. If the migration exists, the installer leaves it alone.

  4. Run the migration:

    bundle exec hanami db migrate
    

    The migration is idempotent: if the table exists, it does nothing. To keep the table in a separate database, set the gateway option to a second gateway.

  5. Require the SQL gem in the provider and set config.backend. Keep the rest of the provider configuration; it still needs allowed_origins, channels, and either an authenticator or allow_anonymous = true:

    # 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 =
          if Hanami.env?(:test)
            :memory
          else
            Mankai::Sockets::SQL.backend(gateway: "db.gateway")
          end
        config.authenticator = lambda do |request, _token_subject|
          user_id = request.session[:user_id]
          user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
        end
        config.allowed_origins = :same_origin
        config.channels = {"chat" => "channels.chat"}
      end
    end
    

    The test environment keeps the memory backend, so specs need neither the table nor a polling thread.

Options

Mankai::Sockets::SQL.backend(**options) returns a backend factory for config.backend. It accepts the following options:

Option Default Description
gateway "db.gateway" The database: a container key, a gateway object that responds to connection, or a Sequel::Database.
table :sockets_messages The name of the messages table, as a Symbol or String.
polling_interval 0.1 The time between polls, in seconds.
batch_size 500 The most rows that one poll reads.
retention 86_400 How long to keep messages, in seconds.
trim_every 100 The number of publishes between trims.
trim_batch_size 200 The most rows that one trim deletes.
trim :thread Where trims run: :thread runs them on a background thread, and :inline runs them inside publish.
silence_polling true If true, the listener polls through a second connection pool without loggers, so polls stay out of the SQL log. If false, it polls through the app's pool.

Every number must be greater than zero. An unknown or invalid option raises Mankai::Sockets::ConfigurationError when the provider starts.

Behavior

Publishing

publish inserts a row through the app's database connection, so it joins the caller's transaction and rolls back with it. Publishing doesn't need a listener, so a job worker or a console can broadcast without serving WebSocket connections.

Each row stores the following data:

  • The stream name, and a signed integer made from the first 8 bytes of the name's SHA-256 digest.
  • The payload, as JSON in a TEXT column. On MySQL and MariaDB, TEXT holds up to 65,535 bytes, which is why mankai-sockets sets max_payload_size to 60,000 by default.
  • The time the row was created.

Listening

A process that serves WebSocket connections starts one listener thread when it accepts its first connection. In :thread trim mode, it also starts one trim thread. A process that only publishes, such as a job worker, starts no listener. In :thread trim mode, it starts a trim thread the first time it trims.

The listener polls the table for rows with higher IDs on the streams that its connections watch. Before it delivers a row, it checks the stored stream name, so a digest collision can't send a message to the wrong stream. If a poll fails, the listener publishes a mankai.sockets.error event and retries with a growing delay of up to 5 seconds.

Delivery guarantees

Delivery is at most once. A process delivers only the messages published after it began to watch a stream. It never replays stored rows, either when its listener starts or when a client subscribes to a stream that no connection in that process was watching. The backend doesn't retry failed deliveries, so don't use it for durable event delivery.

Retention

Every trim_every publishes, the trimmer deletes up to trim_batch_size rows older than retention, oldest first. To trim immediately, call trim on the backend:

Hanami.app["sockets.backend"].trim

Database requirements

A process that serves WebSocket connections needs a pool of at least executor_threads connections for channel code that queries the database, plus one for the listener. With silence_polling, the listener polls through a second pool built from the same settings, which opens one more connection in each process that polls.

When the provider starts, the backend logs a warning for each of the following problems:

Problem Fix
The app's pool is smaller than executor_threads plus one. Raise max_connections on the database URL.
A MySQL or MariaDB connection stores times in whole seconds. Add fractional_seconds=true to the database URL.
A SQLite connection has no busy handler. Add after_connect: ->(conn) { conn.busy_handler_timeout = 5000 } to the connection options.

The backend never changes the app's connection settings. Each warning names the setting to change.

Testing

Use the memory backend in your app's tests, as in the provider example in Installation.