Skip to content
Edit this page View source of this page

Mankai

Design principles

Mankai's gems plug into Hanami apps, so they follow the principles that Hanami and the dry-rb libraries are built on. This page states those principles, explains what each one means for Mankai's code, and ends with a checklist for reviewing changes. It's for contributors, and for app developers who want to know why the gems work the way they do.

These principles are Mankai's reading of Hanami's guides and of how Hanami, dry-rb, and ROM are written. They aren't an official statement from the Hanami team.

Contents

  1. Explicit over implicit
  2. Dependency injection through the container
  3. Small, stateless, thread-safe components
  4. Value objects for data
  5. Results as values
  6. Separation of layers
  7. Slices as boundaries
  8. Settings from the environment
  9. Cheap, lazy boot
  10. Code reloading in development
  11. Rack and middleware
  12. Independence from Hanami
  13. Observability through notifications
  14. No monkey patching
  15. A clear, carefully versioned public API
  16. Isolated testing
  17. Secure defaults
  18. Small, focused gems

1. Explicit over implicit

Nothing happens unless the app's code says so. By reading the app, you can find everything that runs and why.

  • Mankai has no hidden naming conventions. When a client or a setting refers to a component by name, the app lists that name explicitly, the way routes list actions.
  • Mankai never calls a method because of its name, and never chooses a method from incoming data (public_send(params[:action])).
  • Mankai has no globals, such as Mankai.cache or Mankai::Jobs.enqueue. Everything is reached through the container.
  • No default quietly weakens security. Settings such as allowed origins are required, and the app opts out of a protection in writing.
  • Where a default exists, the docs show it written out.

Hanami does use one convention: a component's container key comes from its file path (app/repos/book_repo.rb becomes "repos.book_repo"). That convention is uniform and documented, so it isn't hidden behavior. Mankai avoids letting a convention decide what outside callers can reach or what runs.

For example, the app lists the channels that clients can subscribe to:

# Explicit: the channels clients can subscribe to are listed.
config.channels = {"chat" => "channels.chat"}

# Not: any class under app/channels/ becomes reachable because of its name.

In Mankai:

  • Job keys are explicit strings: enqueuer.call("jobs.import", ...).
  • Cache keys must be convertible to strings. The cache raises InvalidKeyError instead of falling back to to_s.
  • When a SQLite connection lacks a busy handler, the gems log a warning that tells you how to add one. They don't change your connection themselves.

2. Dependency injection through the container

Objects get their collaborators through Deps[...], never by reaching for them.

For example, an action asks for the cache and a repository:

class Books::Show < Hanami::Action
  include Deps["cache", "repos.book_repo"]
end
  • Every Mankai service is a container component, such as "cache", "queue.enqueuer", or "sockets.broadcaster".
  • Mankai has no class-level state, singletons, @@variables, or Mankai::Something.instance.
  • Gems register components through provider sources (register_provider(:cache, from: :mankai_cache)), so the app decides the name, the configuration, and when the component starts.
  • Optional collaborators, such as "logger" and "notifications", are looked up by the container key named in the provider's settings.

3. Small, stateless, thread-safe components

A component is built once and shared by every thread, so it holds no state for any one request.

  • Hanami apps run threaded (Puma), so a component's instance variables don't change after it's built.
  • Per-request or per-connection state lives in objects passed in, such as a Subscription, an Envelope, or a request.
  • Each component does one job, ideally behind one method (#call).
  • Where state must be shared, such as a connection table or a memory store, a Mutex or Monitor guards it, and it's kept in one place.

For example, a channel receives everything about the connection as arguments:

# Stateless: everything about this connection arrives as an argument.
def receive(subscription, message)
  ...
end

4. Value objects for data

Data travels as small, immutable value objects, not as loose hashes or mutable objects.

  • Records such as Envelope, Outcome, Entry, Stream, and Message use Data.define.
  • Code replaces objects instead of changing them: entry.with(expires_at: ...).
  • Hashes are for the edges, such as JSON and database rows. Code turns them into value objects as soon as they come in.

For example, a cache entry is a value object:

Entry = Data.define(:value, :expires_at, :version) do
  def expired?(now) = !expires_at.nil? && expires_at <= now
end

5. Results as values

Expected outcomes are returned; only bugs raise.

  • Expected outcomes use dry-monads: Success(value) and Failure(reason). An enqueue that a middleware refuses, a job that fails, and a channel that rejects a subscription each return a Failure.
  • Callers pattern match on the result instead of rescuing.
  • Programming and configuration errors raise, such as ConfigurationError and InvalidKeyError, with messages that say how to fix them.
  • Every error class inherits from the gem's own Error, so apps can rescue one family.

For example, a caller matches on the result of an enqueue:

case enqueuer.call("jobs.import", {file: path})
in Success(envelope) then ...
in Failure(reason) then ...
end

6. Separation of layers

Each layer has one job. Actions handle HTTP, operations hold business logic, repositories handle storage, and views render.

  • Jobs and channels are thin, like actions: they check their input, call an operation, and return a result.
  • Business rules never live inside a job, channel, or provider.
  • Mankai's docs and demo app show logic in operations (Dry::Operation) and repositories, called from jobs and channels.

For example, a channel passes a message to an operation:

def receive(subscription, message)
  case message.name
  when "speak"
    post_message.call(room: subscription.params[:room], body: message.data["body"])
  else Failure(:unknown_action)
  end
end

7. Slices as boundaries

A slice has its own container, components, and providers. It reaches the app only through what it imports.

  • Each slice registers its own Mankai providers. Slices usually share the app's backend or store (config.backend = Hanami.app["queue.backend"]).
  • Keys from slices carry the slice name ("admin:jobs.import"), so they never collide.
  • A slice's jobs or channels can reach only that slice's components.

8. Settings from the environment

Secrets and per-environment values go through Hanami::Settings, which types them and reads them from the environment.

  • Providers never contain secrets, URLs, or origins; they read them from settings.
  • Installers never edit the app's settings, providers, or routes. They write migrations or copy files, and print what you need to add yourself. Each gem's README lists the settings it needs.

For example, an app declares the token secret as a setting:

class Settings < Hanami::Settings
  setting :sockets_token_secret, constructor: Types::String
end

9. Cheap, lazy boot

Preparing the app (prepare) loads only what's used, and a provider's start step does no heavy work.

  • start builds objects. It doesn't start threads, open connections, or run queries.
  • Threads, such as workers, listeners, and expiry, start when they're first needed, and again after a fork.
  • Requiring a gem defines constants and registers provider sources, and does nothing else.
  • Every provider has a stop step that releases what start and later use acquired.

10. Code reloading in development

On Hanami 3.1 or later, changed code reloads without a restart, so long-lived objects don't hold on to app code.

  • Components are looked up in the container when they're needed, such as for each job run or each socket message, not once at boot.
  • Workers reload between jobs, never while a job runs.
  • Anything that outlives a request, such as a thread or a socket, keeps container keys, not component instances.

11. Rack and middleware

Endpoints are plain Rack apps inside the app's middleware stack.

  • Endpoints are mounted in routes (mount Hanami.app["sockets.endpoint"], at: "/sockets"), so sessions, logging, and security middleware run for them too.
  • Endpoints never bypass the stack or require a particular server, beyond documented requirements, such as Rack full hijack for WebSockets.

12. Independence from Hanami

The core of each gem runs in any Ruby app; Hanami is one integration.

  • Core classes take their collaborators as constructor arguments and need no Hanami constants.
  • The provider source is plain dry-system, so it works with any dry-system container.
  • Hanami-only parts, such as CLI commands, view helpers, and Hanami.app lookups, are a thin layer that loads only when Hanami is present.

For example, you can build a cache without Hanami:

# No Hanami needed:
cache = Mankai::Cache.new(store: Mankai::Cache::Stores::Memory.new, expires_in: 300)

13. Observability through notifications

Events go on the app's notifications bus (dry-monitor), not into custom logging hooks.

  • Events are named mankai.<gem>.<event>, such as mankai.jobs.perform and mankai.cache.fetch.
  • Every event is registered up front, so apps can subscribe before the first one fires.
  • Payloads carry what a subscriber needs, such as keys, IDs, outcomes, and timings. They never carry secrets, tokens, or message bodies.
  • When no bus is registered, events cost nothing.

14. No monkey patching

Gems never change core, framework, or third-party classes. Mankai adds no refinements on String, doesn't reopen Hanami::Action, doesn't patch Puma, Rack, or Sequel, and adds no JavaScript globals. If something needs a hook, Mankai uses a documented extension point or asks the upstream project for one.

15. A clear, carefully versioned public API

Every class and method says whether apps can rely on it.

  • Everything is marked with YARD @api public or @api private, and @since.
  • Only @api public is a promise; private code can change in any release.
  • Versions follow Break Versioning, and each gem keeps a Keep a Changelog CHANGELOG.md.
  • Code is checked with Hanakai's shared RuboCop config, copied into each gem.

16. Isolated testing

Components can be tested without booting the app, opening sockets, or running servers.

  • Because collaborators are injected, specs pass fakes, such as FakeClock, a memory backend, or a null store.
  • Each gem ships test helpers for apps: RSpec matchers and Minitest assertions for jobs, shared examples for store and backend authors, and helpers that call a channel's subscribe and receive directly.
  • Each gem's suite runs on its own (make test/GEM, for example make test/jobs-sql). The SQL gems run on every supported database.

17. Secure defaults

The safe choice is the default; the unsafe choice must be written down.

  • Security settings, such as allowed origins and token secrets, have no default. If a feature needs one and it's missing, the app fails to boot.
  • Everything that comes from outside is validated with dry-schema before it reaches app code.
  • What runs, and what's reachable, is never derived from incoming data.
  • Clients get generic error messages; the details go to logs and events.
  • Database access uses only Sequel's bound parameters.

18. Small, focused gems

Each gem does one thing, and apps install only what they use.

  • Each feature has a core gem (mankai-jobs, mankai-cache), with adapters as separate gems (mankai-jobs-sql, mankai-cache-sql).
  • Optional integrations, such as view helpers and CLI commands, load only when their framework is present.
  • Gems depend on each other only when they must. Shared code is copied before it's extracted, and it's extracted only into a gem with a clear job of its own.

Review checklist

Before you merge a change, check that:

  • Everything that runs is visible in app code or written-out configuration; nothing is reachable by naming convention or chosen from incoming data.
  • New services are container components injected with Deps, with no class-level state.
  • Components keep no per-request state; shared state is guarded and kept in one place.
  • New data types are Data.define value objects.
  • Expected failures return Failure; raised errors inherit from the gem's Error and say how to fix the problem.
  • Business logic lives in operations and repositories, not in jobs, channels, or providers.
  • The change works inside a slice, with slice-prefixed keys.
  • Secrets and per-environment values come from settings.
  • Provider start only builds objects; threads and connections start on first use and after a fork.
  • Long-lived threads look up app code in the container each time.
  • Endpoints are Rack apps mounted in routes.
  • The core works without Hanami loaded.
  • New events are named mankai.<gem>.<event>, registered up front, and carry no secrets.
  • Nothing outside the gem is patched.
  • Every class and method has @api and @since, and the changelog is updated.
  • Specs need no booted app or open sockets, and SQL changes pass on every database.
  • Unsafe options are opt-in, and outside input is validated.
  • The gem still does one thing, and new dependencies are necessary.