Core concepts¶
Mankai adds three features to a Hanami app: background jobs, a cache, and WebSockets. Each feature solves a different problem, and each works on its own. This page explains what each feature does and when to use it. You don't need experience with Rails, Active Job, Action Cable, or the Rails cache.
How a Hanami request works¶
A Hanami app handles each request in one process, from an action to a response. The following diagram shows that path:
Everything inside the action must finish before the browser gets a response. Work that takes a long time, waits on another service, or often fails makes the request slow or unreliable. The three Mankai features move work out of the request, or reuse its result.
Hanami terms used in these docs¶
Mankai builds on a few Hanami ideas. These docs use the following terms:
- Container
- The registry where a Hanami app keeps its components: actions, repositories, jobs, and the objects that Mankai adds.
- Container key
- The name a component is registered under. Hanami derives it from the file path, so
app/jobs/send_welcome.rbis registered as"jobs.send_welcome". A component in a slice has the slice name in front, such as"admin:jobs.import". - Provider
- A file in
config/providers/that sets up a component and registers it in the container. Each Mankai feature has a provider that you register and configure. Deps- The way a component asks for other components by their container keys. For example,
include Deps["cache"]gives the component acachemethod. - Rack app
- An object that takes an HTTP request and returns a response. Rack is the interface that Ruby web
servers, such as Puma, use to talk to apps. Hanami itself is a Rack app, and you can mount other
Rack apps at a path in
config/routes.rb.
Background jobs¶
A background job is a unit of work that you ask the app to run later, outside the request that triggered it. The request stores a small record of the job and returns. A separate process picks up the record and runs the job.
The following diagram shows the path of a job:
The following terms describe jobs:
- Job
- A class with a
#callmethod that does one piece of work. In Hanami, a job is a component inapp/jobs/. - Job key
- The job's container key, such as
"jobs.send_welcome". You enqueue a job by its key. - Enqueue
- Store a request to run a job later. Enqueuing doesn't raise an exception when the job can't be stored. Instead, it returns a result: an object that is either a success, with the stored job, or a failure, with the reason.
- Backend
- Where pending jobs live. The built-in backends keep jobs in memory or run them in the same process. The SQL backend stores jobs in your database, so that separate worker processes can run them.
- Queue
- A named list of jobs inside a backend, such as
"default"or"mailers". Each worker chooses which queues it serves. - Worker
- A process that takes jobs from its queues and runs them.
- Retry
- Running a failed job again, usually after a delay. By default, a failed job isn't retried; you turn on retries for each job.
- At-least-once delivery
- A promise that every stored job runs at least one time, and possibly more. If a worker crashes while it runs a job, the SQL backend runs the job again, so the same job can run twice.
- Idempotent
- Safe to run more than once with the same result. Because delivery is at least once, write jobs so that a second run does no harm.
In Hanami, you inject the enqueuer and call it with the job key and a hash of arguments:
Use a job when the work doesn't need to finish before the response, such as sending email, importing a file, calling a slow API, or rebuilding a report. Don't use a job when the response needs the result, such as validating input or loading the record that the page shows.
For the lifecycle, the backends, and how workers run jobs, see How jobs work.
Cache¶
A cache stores the result of expensive work under a key. On the next request, the app checks the key first. If the key exists, the cache returns the stored value without running the work again. This is a cache hit. If the key is missing or expired, the cache runs the work, stores the result, and returns it. This is a cache miss.
The following diagram shows a cache lookup:
fetch(key) ──► key exists? ──yes──► return stored value
│
no
▼
run the block ──► store the value ──► return it
The following terms describe the cache:
- Key
- The name that identifies an entry, such as
["books", 1]. The cache turns it into a string, such as"books/1". - Value
- The Ruby object that you store. The cache converts it to bytes before it stores it, which is called serializing the value.
- Expiration
- How long an entry stays valid. After it expires, the next lookup is a miss.
- Invalidation
- Deleting or bypassing an entry when the data it came from changes.
- Store
- Where entries live. A memory store belongs to one process, a file store belongs to one machine, and the SQL store is shared by every process and server that uses the database.
In Hanami, you inject the cache component:
include Deps["cache", "repos.book_repo"]
book = cache.fetch(["books", id], expires_in: 600) { book_repo.find(id)&.to_h }
Cache plain data, such as hashes, strings, and numbers. In a view, you can also cache a view fragment: a part of a page's HTML.
Mankai caches the work that produces data or HTML. Browser and proxy caching through HTTP headers is
separate, and stays in Hanami (cache_control, expires, and fresh).
Use a cache when the app computes the same expensive result often, and a slightly old value is acceptable. Don't cache data that must be exact on every request, and don't put one user's private data under a key that other users can read.
For stores, keys, and expiry in more depth, see How the cache works.
WebSockets¶
A WebSocket connection is a long-lived connection between the browser and the server. Unlike a normal HTTP request, either side can send a message at any time. The server can push a change to every subscribed browser without the browser asking for it.
The following diagram shows a broadcast:
browser ──connect──► endpoint ──► channel ──► stream
│
server ──broadcast(stream, data) ─────┘──► every subscribed browser
The following terms describe WebSockets:
- Endpoint
- The URL that the browser connects to. The endpoint is a Rack app that you mount in
config/routes.rb. It runs inside the app's middleware, so your session and security middleware apply to it. - Channel
- A component that decides whether a connection can subscribe, and what to do with the messages that the browser sends. Keep business logic in an operation or a job, not in the channel.
- Subscription
- One connection's membership in a channel, with the parameters that the browser sent.
- Stream
- A named destination for messages, such as the chat room with ID 42. Broadcasts go to a stream.
- Broadcast
- Sending a JSON message to every connection subscribed to a stream.
- Identity
- Who the connection belongs to. An authenticator that you configure reads it from the session or from a signed token. Anonymous connections are allowed only if you turn them on.
In Hanami, channels live in app/channels/. You mount the endpoint in your routes:
Channels aren't found automatically. You list each channel that the browser can use in the
provider's config.channels setting.
Use WebSockets when the server must push updates with low latency, such as for chat, notifications, live dashboards, or collaborative editing. If the browser can ask for updates every few minutes instead, don't use WebSockets. Each WebSocket connection stays open, and you must authenticate it and protect it with origin checks.
For connections, channels, and backends in more depth, see How WebSockets work.
Choose a feature¶
The following table matches common problems to a feature:
| Problem | Feature |
|---|---|
| The request waits on email, a file, or a slow API | Background job |
| The app rebuilds the same expensive query or page part on every request | Cache |
| The browser must see a change without asking for it | WebSockets |
| The response needs the result immediately | None; do the work in the action |
| The data must be exact on every read | None; read the source |
| Updates every few minutes are enough | None; have the browser poll |
What's next¶
- Install Mankai.
- Run your first background job.
- Cache your first view fragment.
- Add your first WebSocket channel.
- Read Design principles for the rules behind the gems' design.