Jobs
A job is work that runs on the server after the write that asked for it, like sending an email, building a report or calling another service. It's stored in the database, so it survives a restart, runs again if it fails, and needs no other service to run.
Defining a Job
A job type is a module that starts with use Hologram.Job, and its run/1 function does the work:
defmodule MyApp.Jobs.ExportTasks do
use Hologram.Job
alias MyApp.Project
relationship :project, Project
def run(%{project_id: project_id}) do
MyApp.Reports.export_tasks(project_id)
end
end
run/1 runs only on the server, so it can call anything server code can, like a mailer, another service's API or a secret from the app's config.
A job type is an entity type, so everything Entities covers works for it, except for the options on the use line. Its attributes and relationships hold what the job needs. You can query jobs, show them on a page and write access rules for them.
run/1 gets the job and returns :ok when the work is done. It may also return {:ok, value}, so it can end with a call like DB.create/2 that returns one. Hologram drops the value. {:error, reason} means the attempt failed, and so does any other return value, an exception, a throw or an exit. Here, MyApp.Reports.export_tasks returns one of these.
A job that reads or writes data in run/1 starts with use Hologram.DB too. A relationship gives the job its access rules, queries and foreign key, but run/1 gets only the ID, so read the entity it needs:
defmodule MyApp.Jobs.NotifyMembers do
use Hologram.Job
use Hologram.DB
alias MyApp.Project
relationship :project, Project
def run(%{project_id: project_id}) do
case DB.read(Project, project_id) do
nil -> :ok
project -> MyApp.Mailer.notify_members(project)
end
end
end
The user can lose access to the project before the job runs, and DB.read then returns nil. There's nothing left to do in that case, so the job returns :ok. If it failed instead, Hologram would try it again.
Creating Jobs
Job.create takes the job type and its values. It works in actions, commands, init/3, seeds and other jobs. use Hologram.DB gives you the Job alias. An action creates a job like this:
def action(:export_tasks, %{project_id: project_id}, component) do
case Job.create(ExportTasks, project_id: project_id) do
{:ok, _job} -> put_state(component, :message, "Your export is on its way")
{:error, _violations} -> put_state(component, :message, "The export couldn't be started")
end
end
In an action, the browser shows the job at once and sends it to the server in the action's batch, with the action's other writes. A server runs it once the batch commits. While the browser is offline, the job waits with the rest of the batch. Writing Data covers batches and what happens when the server refuses one.
On the server, the job is part of the transaction it's created in:
def command(:archive_project, %{project_id: project_id}, server) do
result =
DB.transaction(fn ->
with :ok <- DB.update(Project, project_id, archived: true) do
Job.create(NotifyMembers, project_id: project_id)
end
end)
case result do
{:ok, _job} -> put_action(server, :project_archived)
{:error, violations} -> put_action(server, :show_errors, violations: violations)
end
end
A job runs only after its transaction commits. If the transaction is undone, or the server refuses the batch, there's no job and nothing runs. So NotifyMembers runs only if the project was archived. Its rules have to let the user create it.
Job.create returns {:ok, job} or {:error, violations}, like DB.create, and Job.create! returns the job or raises a Hologram.WriteError. DB.create doesn't take jobs and raises a Hologram.MisuseError.
A job starts as soon as it can. There's no way to schedule one for later, or to repeat it on a schedule, yet.
Who Can Create Jobs
In an action, a command or any other code that runs for a user, the allow :create rules decide who can create a job. This rule on ExportTasks lets anyone who may read a project export its tasks:
allow :create, via: {:read, project}
A job type with no rules can't be created by any user or visitor, and Job.create raises a Hologram.AccessDeniedError on the server. Access Control covers the rules.
To create a job no user may create on their own, claim trust, which only server code can do:
Job.create(SyncInvoices, [account_id: account_id], trust: true)
Seeds, Mix tasks, the console and your own plugs have no user, so they create jobs past the rules and don't need trust.
Who a Job Runs As
A job runs as whoever created it:
- A job created for a signed-in user runs as that user.
- A job created for a signed-out visitor runs as a visitor.
- A job created by code with no user, like a seed, runs as the server, past the access rules. So does one created with
trust: truewhen no one is signed in.
So run/1 reads only what the user may read, and the rules check what it writes. They apply as they stand when the job runs. If the user lost access to the project after creating the job, its reads leave the project out, and a write the rules refuse raises a Hologram.AccessDeniedError, which fails the attempt.
trust: true is about creating the job. For a signed-in user, run/1 still runs as that user. When it has to go past the rules, mark its queries and writes with trust(), as Writing Data shows.
Each job says who it runs as. actor_kind is :user, :visitor or :server, and actor is a relationship to the user, with the ID in actor_id. Both work in queries and rules. This rule on ExportTasks lets users see the exports they asked for:
allow :read, when: actor_id == user_id()
Visitors and the server have no actor, so actor_id is nil for them.
An app with no user entity type has no actor. Its queries and rules can't use actor or actor_id, and the jobs its users create run as a visitor.
Retries and Backoff
A job that fails runs again, up to 10 attempts. Hologram waits about 30 seconds before the second attempt, then 2 minutes, 8 minutes, 32 minutes and 2 hours, and then 6 hours between the rest. The 10 attempts take a bit over a day. A job out of attempts becomes :failed and keeps its last error.
Set another limit on the use line:
use Hologram.Job, max_attempts: 3
A run can also be cut short, when its server stops, its process is killed or it loses the database. Another server, or the same one after a restart, notices and counts it as a failed attempt. A deploy that stops a server during a run uses up an attempt too.
So a job can run more than once, and a run cut short may have done part of its work. Write run/1 so that running it again is safe, for example by checking whether the email was already sent. For work that must never run twice, set max_attempts: 1.
Hologram checks max_attempts only when an attempt fails. So when you lower it, a job already waiting for a retry still gets its next run, even if it has used up the new limit. If that run fails too, the job ends as failed. To stop such jobs before they run, cancel them. With a new limit of 3, they're the queued jobs that have had 3 or more attempts: status == :queued and attempt >= 3.
Hologram doesn't log failed attempts, so look at the jobs themselves, as Ended Jobs below shows. A failed job can't be run again yet, so create a new one with the same values.
Timeouts
A run can take up to 1 hour. After that Hologram kills it and counts it as a failed attempt, so a stuck job can't block the others for good. Set another limit in milliseconds:
use Hologram.Job, timeout: 60_000
The limit can't be turned off, but it can go up to 4,294,967,295 ms, about 49 days, so a job that needs longer than an hour sets a bigger number. It covers the whole run, including the work Hologram does to start it and record how it ended, so leave some room.
Hologram can't stop native code that's still running. A call stuck in a native library holds its job until it returns. A file read on a network drive that stopped answering keeps going after Hologram has given up on the run, so it can overlap the next attempt. Give calls that can hang a timeout of their own, like an HTTP client's receive_timeout. For file reads on network drives, set a timeout in the mount's options.
Concurrency
Each server runs up to 10 jobs of a type at once. Set another number for a job type that should run fewer at once, or more:
use Hologram.Job, max_concurrency: 2
The limit is per server, so with 3 servers up to 6 of these jobs run at once. It's also per job type, so a type at its limit doesn't hold up the others. The job that has waited longest runs first.
Every server that runs the app runs jobs, and the servers don't need to be connected in a cluster. They use the app's own database connections. A run holds one only while it's querying or writing, not while it waits for another service. If you raise the limit for jobs that write a lot, raise pool_size too, as Database Setup shows.
Tracking Jobs
Hologram keeps these fields on every job. You can read and query them, but only Hologram writes them, and a job type can't declare fields with these names:
status-:queued,:running,:done,:failedor:cancelled. A new job is:queueduntil a server picks it up. A job waiting for a retry is:queuedtoo.attempt- how many runs have started, 0 at first.scheduled_at- when the next run is due.started_at- when the latest run started,nilbefore the first one.ended_at- when the job ended, which is when it became:done,:failedor:cancelled. It'sniluntil then, also while the job waits for a retry.node- the name of the Erlang node that ran the latest attempt,nilbefore the first one. It's a server-only attribute, so browsers never get it.error- why the latest failed attempt failed, cleared when the job is done. It's server-only too.actor_kind,actorandactor_id- who the job runs as.
Jobs sync to browsers like other entities, so a live read shows each status as it changes:
derived :exports, [ExportTasks], fn project_id ->
ExportTasks
|> filter(project_id == ^project_id)
|> sort(created_at: :desc)
end
def template do
~HOLO"""
<ul>
{%for export <- @exports}
<li>{export.status}</li>
{/for}
</ul>
"""
end
The allow :read rule from above still applies, so users see only their own exports.
A job can also report its own progress. Give it an attribute like progress, update it in run/1 with DB.update, and allow that with an allow :update rule.
Ended Jobs
Hologram keeps jobs that have ended, whether they're done, failed or cancelled, until you delete them. To look through the failed ones, query them in the console, where the query reads past the rules and shows error:
ExportTasks
|> filter(status == :failed)
|> sort(ended_at: :desc)
|> DB.read()
Cancelling Jobs
Job.cancel takes a job, or a job type and an ID. It works in actions and in server code:
Job.cancel(export)
Job.cancel(ExportTasks, export_id)
What it does depends on the job's status:
- A
:queuedjob becomes:cancelledand never runs again, whether it was waiting for its first run or for a retry. - A
:runningjob becomes:cancelledtoo, and Hologram kills its run, whichever server it's on. It isn't retried. - A job that has ended stays as it is.
Job.cancel returns :ok in all three cases. On the server, it also returns :ok when there's no job with that ID.
Who Can Cancel Jobs
The allow :cancel rules decide who can cancel a job. This rule on ExportTasks lets users cancel the exports they asked for:
allow :cancel, when: actor_id == user_id()
Without such a rule, no user or visitor can cancel the job. On the server, a refused cancel raises a Hologram.AccessDeniedError. Code with no user, like a Mix task or the console, cancels past the rules. To go past them in a command, pass the job through trust() first, as in export |> trust() |> Job.cancel().
Don't check the status in this rule. With status == :queued in it, cancelling a job that has just started or ended is refused. Without it, a running job is stopped and an ended one stays as it is.
To decide whether to show a cancel button, ask can?(@current_user, :cancel, export). The rule above still holds once the job has ended, so check in the template that the status is :queued or :running too.
Cancelling in an Action
An action can cancel a job the browser holds. The page shows it as :cancelled at once, and ended_at stays nil until the server answers. The server checks the rules, and if it refuses the cancel, the browser undoes the action's whole batch.
It works offline too. The cancel waits with the user's other writes, so the job can end before the cancel reaches the server. The job then stays as it ended, and the page changes from :cancelled to :done or :failed.
What Cancelling Can't Undo
:cancelled means the job won't run again, not that its run has stopped. Hologram usually kills the run within moments. It can take up to 5 seconds when PostgreSQL's notifications don't reach the server, as behind some connection poolers. Native code can go on for longer, as with Timeouts above.
A cancelled run may have done all, part or none of its work, and what it wrote stays. It can also still write for a moment after the cancel, so code that cleans up right after Job.cancel can miss what the run writes last.
Deleting a job that's waiting keeps it from running too, but deleting one that's running doesn't stop its run.