Workers
When a calculation is slow enough that typing or clicking stutters, or a file is too large to bring into the page, do the work in a worker. A worker is a Web Worker running a second copy of your app’s compiled module. You declare a task, a named Roc function. The page asks for a job of it with an input and goes on handling events, and the job’s answer comes back as an ordinary effect result. You write no JavaScript and no serialisation code.
The samples on this page come from www/samples/workers/, a text box whose
analysis runs in workers; www/samples/files/ and www/samples/tasks/,
which read and convert a file; www/samples/prepared/, a notes explorer;
www/samples/line-index/, which indexes a large file’s lines;
and www/samples/worker-lifetimes/, a list of documents. All of them have
specs that run natively and in Chrome.
A task
A task is a name and a function, run!, from an input to a Try: the
job’s output, or the task’s own error.
## The words of a text that differ, and the one used most.
Summary : { distinct : U64, top : Str }
## How often a word is used.
Frequency : { word : Str, count : U64 }
## A task that cannot fail: its error is `Worker.Never`, and `run!` is a
## plain calculation that always answers `Ok`.
summary : Worker.Task(Str, Summary, Worker.Never)
summary = Worker.task({ name: "example.org/words/summary", run!: |text| Ok(Words.summarise(text)) })
## The numbers of the lines, from 1, that contain `word`.
find : Worker.Task({ text : Str, word : Str }, List(U64), Worker.Never)
find = Worker.task({
name: "example.org/words/find",
run!: |{ text, word }| Ok(Words.lines_with(text, word)),
})
Worker.tasktakes a props record.nameandrun!are required;timeout,on_disposeandon_cancelare optional (see Lifetimes).- Its type is
Worker.Task(input, output, error). The types ofrun!are the task’s types, so a request can only send the input the task expects, and its answer already has the output type. run!always answers aTry. A calculation that cannot fail answersOk(...)and names its errorWorker.Never, a type with no values. (The empty union[]would say the same, but it cannot cross to a worker, so a task’s error is never[].) A task with an error of its own is under Failures.run!is an effectful field (=>), because a job may call the platform’s effects on files (see What a task may do). A plain calculation is written as a lambda, which the compiler accepts there whatever its body:run!: |text| Ok(Words.summarise(text)). A named pure function cannot fill the field directly; that is a type mismatch on the props record.- A task needs an annotation only when its
run!is a lambda that never says what its error is: one that only answersOk. A top-level value needs a concrete type, and without the annotation the compiler reports that the type never resolved. A task whoserun!is a named, annotated function (run!: ConverterApp.convert!), or a lambda whose error type is known, compiles without one; the function’s annotation already gives the task’s types. - A timeout that varies (one the user picks, say) belongs to the task, so
make the task with a function of the timeout,
primes : [Unlimited, Ms(U32)] -> Worker.Task(...), register each task that can be asked for, and ask for the one with the timeout wanted, as the Worker Lab does.
Names are namespaced and unversioned, like "example.org/words/summary".
The page and every worker run the same compiled module, so a name always
means the same function; there is nothing to keep in step between versions.
Registering it
Declare tasks wherever they belong, as in the Words module above, and
register each one once in the program your app binds as main, with
Program.with_workers and the task’s registration():
## The program both platforms run, with every worker task it asks for.
program : Engine.Program
program =
Engine.program(|| Engine.state(Editor.initial, Editor.view))
.with_workers([
Words.summary.registration(),
Words.find.registration(),
Words.frequencies.registration(),
Words.total.registration(),
])
Use the same Worker.Task value for the registration and for every
request, so the two cannot disagree. An app registers at most 64 names; a
task, a preparation and each of a
preparation’s tasks count one each.
Mistakes in the catalogue stop the app with a contract error, the way a duplicate list key does (see Reference):
- Registering two tasks with one name, when the app mounts:
contract: worker task "example.org/words/summary" is registered twice in with_workers. - Registering more than 64 names, when the app mounts:
contract: with_workers registers more than 64 worker tasks (task "…" is over the bound). - Asking for a job of a task that is not registered, when the site asks:
contract: worker task "example.org/words/summary" is not registered; add its registration to with_workers (site /3/0), naming the site that asked.
Showing its answer
Worker.resource(task, input, body) holds a task’s asynchronous answer
as a signal. Engine.derive computes a signal synchronously in the turn.
It gives body a value of type Engine.Remote(output, Worker.Error(error)):
## The summary of the text, computed in a worker.
summary : Signal(Ctx, S) -> Elem(Ctx)
summary = |v|
Worker.resource(
Words.summary,
v.map(|s| s.text),
|remote| Html.p_s(remote.map(Editor.show_summary), [Engine.test_id("summary")]),
)
## While a job is wanted, the previous answer stays and says it is being
## updated.
show_summary : Engine.Remote(Words.Summary, Worker.Error(Worker.Never)) -> Str
show_summary = |{ request, answer }|
match answer {
Unanswered => if (request == Pending) "Analysing…" else ""
Answered({ distinct, top }) => {
shown = "${distinct.to_str()} different words; most used: ${top}"
if (request == Pending) "${shown} (analysing…)" else shown
}
Failed(error) => Editor.problem(error)
}
## What to tell the user when a job produced no answer. These tasks
## cannot fail, so there is no `Failed` to match.
problem : Worker.Error(Worker.Never) -> Str
problem = |error|
match error {
Timeout => "This took too long."
Refused => "Too much is running; edit the text to try again."
TooDeep | NanKeys | TooManyFiles => "The answer could not be sent."
Lost(_) => "The analysis failed."
}
requestisPendingwhile the answer for the current input is still wanted, andIdleotherwise.answerisUnansweredbefore the first answer,Answered(output)once there is one, orFailed(error)when the job gave no output. The error is aWorker.Error(error)(see Failures). These tasks cannot fail, soproblemmatches aWorker.Error(Worker.Never)and has no arm for a failure of the task’s own.remote.answered()is the latest answer as aTry, kept while a newer job works:remote.answered() ?? defaultshows a fallback, and.map_ok(f)picks from it.Worker.status(remote)is the whole resource as one union,Unasked,Working,Answered(output), the task’s ownFailed(error),Timeout,Refused,TooDeep,NanKeys,TooManyFilesorLost(fault), for a view that says something different in each case (see Failures).- To show an answer beside state the resource does not hold (the page of
results the user is on, say), lift the state in and combine the two:
v.lift().map2(remote, |s, r| ...). The task then need not echo its input in its answer.
What you see:
- The job for the first input starts when the site mounts.
- When the input changes to an unequal value,
requestbecomesPendingin the same turn andanswerkeeps the previous answer, so the view can go on showing it, asshow_summarydoes. As the user types, the summary keeps showing the last answer, marked as being updated, until the answer for the new text arrives. - A newer input stops the job for the older one before it starts its own. An answer for an old input is never shown, and you keep no request number in your state.
- An equal input asks nothing.
The input is a snapshot: it is encoded when the job is asked for, and later
changes reach only the next job. The input, the output and the task’s error
need equality, like the value of any derive.
A job reports nothing until it answers: there is no progress. Stopping a job that has started ends its worker, and the next job starts a new one (unless the task says otherwise; see Lifetimes).
An input that is sometimes not a question
Worker.resource_when(task, input, body) takes an input of type
[Run(i), Skip]. Run(i) asks for a job on i; Skip stops any job and
clears the answer, so answer is Unanswered and request is Idle. Use
it for an empty search box or a form that is not valid yet:
## Search the text for a word. An empty box asks nothing.
find : State(Ctx, S) -> Elem(Ctx)
find = |st| {
v = st.signal()
Html.div(
"find",
[
Html.text_input(Engine.const("Find"), "search", v.map(|s| s.query), [], st.set_value(|s, query| { ..s, query })),
Worker.resource_when(
Words.find,
v.map(|s| if (s.query == "") Skip else Run({ text: s.text, word: s.query })),
Editor.found,
),
],
)
}
## The body of the search's resource, as a named function. Its context is
## left generic: inside the resource it is
## `In(Ctx, Engine.Remote(List(U64), Worker.Error(Worker.Never)))`, which
## a named body has no need to spell out.
found : Signal(ctx, Engine.Remote(List(U64), Worker.Error(Worker.Never))) -> Elem(ctx)
found = |remote| Html.p_s(remote.map(Editor.show_lines), [Engine.test_id("found")])
show_lines : Engine.Remote(List(U64), Worker.Error(Worker.Never)) -> Str
show_lines = |{ request, answer }|
match answer {
Unanswered => if (request == Pending) "Searching…" else ""
Answered([]) => "Not found"
Answered(lines) => "Lines ${Str.join_with(lines.map(|n| n.to_str()), ", ")}"
Failed(error) => Editor.problem(error)
}
The search’s input includes the text, so editing the text while a word is in the box searches again.
A resource’s body can be a named function, as found is. Give it a generic
context, Signal(ctx, Engine.Remote(…)) -> Elem(ctx), and it fits any site:
inside the resource the context is In(Ctx, Engine.Remote(…)), and a named
body never needs to write that out.
Starting and cancelling from a button
When the user decides when a job runs, keep the request in state and use
Engine.watch_latest (see
Effects and the Browser).
task.ask(input) is the ask for its plan, and its reaction receives the
job’s result as Try(output, Worker.Error(error)):
## What the "Count words" button last asked for. `press` numbers the
## presses, so pressing it again for the same text counts again.
Ask : [Idle, Count({ press : U64, text : Str })]
## What the count shows.
Counted : [NotCounted, Counting, Cancelled, Counted(List(Words.Frequency)), CountFailed(Worker.Error(Worker.Never))]
S : { text : Str, query : Str, numbers : Str, presses : U64, ask : Ask, counted : Counted }
Ctx : In(Root, S)
## Count the most used words when asked. "Cancel" stops a count that is
## still running; editing the text starts nothing.
count : State(Ctx, S) -> Elem(Ctx)
count = |st| {
v = st.signal()
Html.div(
"count",
[
Html.button("Count words", [], st.update(|s| { ..s, presses: s.presses + 1, ask: Count({ press: s.presses + 1, text: s.text }), counted: Counting })),
Html.button("Cancel", [], st.update(|s| { ..s, ask: Idle, counted: Editor.cancelled(s.counted) })),
Engine.watch_latest(
v.map(|s| s.ask),
|ask|
match ask {
Idle => []
Count({ text, .. }) => [Words.frequencies.ask(text)]
},
st.on_result(|s, _, res| { ..s, counted: Editor.counted(res) }),
),
Html.p_s(v.map(|s| Editor.show_counted(s.counted)), [Engine.test_id("counted")]),
],
)
}
counted : Try(List(Words.Frequency), Worker.Error(Worker.Never)) -> Counted
counted = |outcome|
match outcome {
Ok(top) => Counted(top)
Err(error) => CountFailed(error)
}
- “Count words” puts a new
Countin state, andwatch_latestasks for a job on it. The press number makes each press a new value, so pressing again for the same text counts again. (A request that must never be cancelled by a later press, a save say, is posted to an outbox and sent withEngine.on_postinstead; see Effects and the Browser.) - Pressing it while a count runs stops that job and starts a new one.
- “Cancel” puts
Idlein state. Its plan is[], so the change only stops the job that is in flight. - Editing the text starts nothing: the site watches only
ask. - The answer is written to state by the reaction, so it stays after the job
is over.
watch_latestnever delivers an answer for a request it has stopped, so the reaction does not need to check which press it belongs to.
One question, several jobs
A question that splits into independent parts (the shards of a range, the
files of a batch) can be asked as one job per part, which the pool spreads
over its workers. Worker.gather(task, inputs, body) asks one job per
input and gives body an Engine.Gathered(output, Worker.Error(error)):
## One shard of the question: the numbers from `start` up to `end`.
Shard : { start : U64, end : U64 }
## How many primes a shard holds.
count : Worker.Task(Shard, U64, Worker.Never)
count = Worker.task({ name: "example.org/primes/count", run!: |shard| Ok(Primes.primes_in(shard)) })
## The question split into `shards` equal ranges below `limit`, the
## last taking the remainder. Keep `shards` within the in-flight bound
## (32 by default): a job beyond it is refused.
split : { limit : U64, shards : U64 } -> List(Shard)
split = |{ limit, shards }| {
size = limit // shards
var $out = []
for i in 0..<shards {
$out = $out.append({ start: i * size, end: if (i + 1 == shards) limit else (i + 1) * size })
}
$out
}
## One job per shard. `jobs` shows each shard as it settles; `all`
## answers once every shard has, and keeps the previous total while a
## new question works.
view : State(Ctx, S) -> Elem(Ctx)
view = |st| {
v = st.signal()
Html.div(
"primes",
[
Html.number_input(Engine.const("Shards"), v.map(|s| s.shards.to_str()), [], st.set_value(|s, text| { ..s, shards: U64.from_str(text) ?? s.shards })),
Worker.gather(
Primes.count,
v.map(|s| Primes.split(s)),
|gathered| Html.div(
"result",
[
Html.p_s(gathered.map(|g| Str.join_with(g.jobs.map(Primes.show_job), " ")), [Engine.test_id("shards")]),
Html.p_s(gathered.map(|g| Primes.show_total(g.all)), [Engine.test_id("total")]),
],
),
),
],
)
}
show_job : Engine.JobState(U64, Worker.Error(Worker.Never)) -> Str
show_job = |job|
match job {
Working => "…"
Answered(n) => n.to_str()
Failed(_) => "failed"
}
## The whole answer as one flat match, and the previous total while a
## new question works.
show_total : Engine.Remote(List(U64), Worker.Error(Worker.Never)) -> Str
show_total = |all|
match Worker.status(all) {
Unasked => ""
Working => all.answered().map_ok(|counts| "${counts.sum().to_str()} (counting…)") ?? "Counting…"
Answered(counts) => "${counts.sum().to_str()} primes"
Timeout | Refused | TooDeep | NanKeys | TooManyFiles | Lost(_) => "The count failed."
}
jobsholds each input’s job, in input order, asWorking,Answered(output)orFailed(error), so the view can show each part as it arrives, in whatever order the workers finish.allis anEngine.Remoteof the whole list:Pendingwhile any job works,Answered(outputs)in input order once every job has answered, or the first failure in input order once none works. It keeps the previous question’s answer while a new one works, soall.answered()still gives the last total.- A new, unequal list of inputs stops every job of the old question and
asks again, as
resourcedoes; an equal list asks nothing. Withon_cancel: Finisha stopped job runs to its end, so a worker keeps its prepared state. - Each job takes a slot of the in-flight bound (32 by default), and a job
beyond it is refused: its part shows
Failed(Refused)and the whole answer fails. Split a question into no more parts than the bound allows. The pool runs at mostmaxWorkersjobs at once and queues the rest in order, so more parts than workers costs nothing but the queue. - An empty list is answered at once with
[]. all.answered()keeps the last answer only while the next question works: once a question fails it isErr(NoAnswer), so say in the view what is shown until the next question is answered.
The parts can be a preparation’s task, one input per shard of a dataset
the workers keep: each job’s input names its shard (a seed and a size, say,
or a file and a range), the pool runs each shard’s jobs on the worker that
prepared it, and only the small answers cross to the page. Keep one shard
per worker of the pool: a worker keeps one state, so with more shards than
workers every question prepares shards again. The
Million-Row Explorer asks four shards
of two million generated orders this way, with on_cancel: Finish so a
superseded question never ends a worker and its shard.
A question that changes faster than it is answered, such as a slider being
dragged, shows nothing until it stops changing: each new question stops the
previous one’s answer from being shown. Ask such a question at most every
so often instead: keep what the control shows and what was asked apart in
the state, and copy one to the other when a Timer(ms) request fires (the
explorer samples its sliders every 100 ms, so each question is answered
while the drag goes on).
Engine.gather is the same for anything with request and result, a
port call per item for instance. A question with more parts than the
in-flight bound, or one whose parts may each be asked again (a part that
was lost, retried on its own), does not fit a gather: changing the list
asks every part again. Keep one site per part instead, each in a row
with its own watch_latest, and admit parts from the page’s state as earlier
ones finish, as the Worker Lab does for the
strips of its picture: its jobs are a table, and each row of the view that
draws every one of them owns its job’s request. Count every request the
parts lead to: a drawn strip’s object URL and an interval take slots of the
same bound as the jobs.
What a task may do
Most tasks only calculate. A job receives its input and nothing else: it cannot read the page’s state, write it, or ask for the page’s effects, and it keeps nothing between jobs, so a job that runs in a worker that ran other jobs before sees nothing of them.
What a job may also do is act on files. A File in a job’s input is a
handle, not the file’s bytes (see Files), and the job
calls the platform’s effects on it to read as much as it needs:
## A file's line and word counts, read in a worker. The task receives the
## file's handle, and its job reads the bytes as text with the effect
## `contents_utf8!` (`contents!` gives the bytes, `read!` a range); a file
## that is not text, or that the browser can no longer read, is the
## task's error.
Counts : { name : Str, lines : U64, words : U64 }
count : Worker.Task(File, Counts, Engine.FileError)
count = Worker.task({
name: "example.org/upload/count",
run!: |file| {
text = file.contents_utf8!()?
lines = text.split_on("\n").len()
words = text.split_on("\n").map(|l| l.split_on(" ").keep_if(|w| w != "").len()).sum()
Ok({ name: file.name(), lines, words })
},
})
file.contents_utf8!() brings the whole file into the job’s memory as
text; file.contents!() gives its bytes and file.read!({ start, len }) a
range of them. A read can fail, because the user may have changed or
deleted the file since choosing it, so each effect answers a Try, and ?
passes its error on as the task’s own. A read fails only with
Unreadable (OutsideFile too for a range, and InvalidUtf8 when text
was asked for), so the task’s error can be any union that has those tags;
here it is Engine.FileError.
A job can also write. Files.build! (from import pf.Files) opens a builder, append! copies bytes
into it, and finish! turns it into a new, immutable File that the
answer may hold. This task converts a CSV file to TSV, 64 KiB at a time, so
the job’s memory holds one chunk, never the whole file:
## Convert a CSV file to TSV in a worker, 64 KiB at a time: the job's
## memory holds a chunk, never the file.
to_tsv : Worker.Task(File, File, Engine.FileError)
to_tsv = Worker.task({ name: "example.org/convert/tsv", run!: Convert.to_tsv! })
to_tsv! : File => Try(File, Engine.FileError)
to_tsv! = |source| {
out = Files.build!({ name: "${source.name()}.tsv", mime: Mime("text/tab-separated-values") })
chunk = 65536
var $at = 0
while $at < source.size() {
len = if (source.size() - $at < chunk) source.size() - $at else chunk
bytes = source.read!({ start: $at, len })?
out.append!(bytes.map(|b| if (b == ',') '\t' else b))?
$at = $at + len
}
Ok(out.finish!())
}
The file in the answer reaches the page as a handle the page holds, which the app can show, save, upload or send to another job. No file’s bytes pass through the page’s memory on the way. Files in Tasks covers every effect, appending to a file across jobs, saving, and downloading into a file.
Write a run! like to_tsv! as a named function annotated with =>, as
the sample does. With the current compiler, a lambda written in the props
record is rejected when its body uses ? on a method of its own parameter
(source.read!(...)?) and then uses ? again: the error is a type
mismatch on that method, as if it had to be pure and could not fail
(roc-lang/roc#12951). The
same body as an annotated function compiles. A lambda with one ?, like
Upload.count’s, is fine.
Effects exist only inside a job. Page code cannot call one, because the compiler refuses an effect in a pure function, and the platform refuses one anywhere else with a contract error.
A job’s effects are synchronous: the job blocks inside each one until it
returns (a read waits for the browser to read the file), and otherwise runs
from start to answer without pausing. So a task cannot await anything: no
timer, page event or HTTP response reaches a running job. The platform
has no effect yet that makes an HTTP request from inside a job: download on
the page with File.fetch and send the file to the task instead.
A preparation and its tasks
Some apps ask several questions of one expensive intermediate result: an
explorer parses a document and then shows its outline, its search results
and its statistics. With separate tasks, each job parses the document
again. A preparation names that first step once. Worker.preparation
declares it: a function prepare! from its input to a Try of a state.
The state can be any type, since it never leaves the worker, and
prepare! may read the files its input holds:
## The expensive step: read the file and split it into lines, once per
## file in a worker that keeps the result. A file that is not text is the
## preparation's error, which every task of it shares.
document : Worker.Preparation(File, List(Str), Engine.FileError)
document = Worker.preparation({
name: "example.org/notes/document",
prepare!: |file| {
text = file.contents_utf8!()?
Ok(text.split_on("\n"))
},
})
Each question is a task of the preparation, made with the preparation’s
task. Its run! receives the state beside the job’s own input, and it
has its own name, input type and output type:
## Three typed questions over the same lines, each with its own input and
## output type. A preparation's task reads the state beside its own input.
summary : Worker.PreparedTask(File, List(Str), {}, { lines : U64, chars : U64 }, Engine.FileError)
summary = Notes.document.task({
name: "example.org/notes/summary",
run!: |lines, {}| Ok({ lines: lines.len(), chars: lines.fold(0, |n, l| n + l.count_utf8_bytes()) }),
})
search : Worker.PreparedTask(File, List(Str), Str, List(U64), Engine.FileError)
search = Notes.document.task({
name: "example.org/notes/search",
run!: |lines, word| {
var $found = []
var $at = 1.U64
for line in lines {
if word != "" and line.contains(word) {
$found = $found.append($at)
}
$at = $at + 1
}
Ok($found)
},
})
## A cancelled job of this task finishes, its answer dropped, so the
## worker keeps the lines for the next question.
longest : Worker.PreparedTask(File, List(Str), {}, Str, Engine.FileError)
longest = Notes.document.task({
name: "example.org/notes/longest",
run!: |lines, {}| Ok(lines.fold("", |best, l| if (l.count_utf8_bytes() > best.count_utf8_bytes()) l else best)),
on_cancel: Finish,
})
A preparation’s tasks share its error type, the third parameter of
Worker.Preparation(init, state, error). When prepare! answers
Err(error), each job of its tasks answers Failed(error), which the app
matches like any task’s failure. Here a file that is not text fails every
tab with Failed(InvalidUtf8).
The preparation is registered once, listing the registrations of its tasks:
program : Engine.Program
program =
Engine.program(|| Engine.state({ doc: None, tab: Summary, word: "" }, Notes.view))
.with_workers([Notes.document.registration([Notes.summary.registration(), Notes.search.registration(), Notes.longest.registration()])])
A preparation’s task is used like any task: Worker.resource,
Worker.resource_when, or request and result in an Engine.watch_latest site,
with the same timeout, on_dispose and on_cancel. What it is asked is
a Worker.Question(init, input): its init field is the preparation’s
input, and its input field is the task’s own input:
## The question for the current file, or none before a file is chosen.
asked : S, q -> [Run(Worker.Question(File, q)), Skip]
asked = |s, input| match s.doc {
Loaded(doc) => Run({ init: doc, input })
None => Skip
}
Answers never depend on whether the state was kept. A job’s answer is exactly what preparing afresh and running the task would give. A worker that prepared a state keeps it, and a later job over the same input runs on that worker and costs the task instead of the preparation; the monitor shows which jobs prepared and which reused (see Monitoring Workers). But keeping it is an optimisation the platform may or may not achieve, never a promise: specs see only answers, and the native spec runner prepares for every job.
- The same input is the same bytes. A worker reuses a state only for an
input whose encoding is identical. Comparing costs the page time in
proportion to the input on every job, so pass a large input as a
File(or a slice of one): a file’s identity is its handle and range, which cost nothing to compare, andprepare!reads its bytes once. A changed input prepares again, on another worker if one is free, so going back to an earlier input can still find its state. - One state per worker. The pool’s workers each keep at most one. A job
waits for the worker that holds its state if that worker is busy; a new
input prepares on a worker holding nothing, a new worker, or the idle one
used least recently, whose state it replaces. A worker whose memory has
grown past the
maxWorkerBytesmount option (128 MiB by default) is ended after its job, its state with it. - Leave the state’s type to inference if you like. A task’s type names
the state and the error
(
Worker.PreparedTask(File, List(Str), Str, List(U64), Engine.FileError)), butWorker.PreparedTask(File, _, Str, List(U64), _)works too, and a preparation with several tasks reads best with a local alias for the parts they share:LogTask(query, output) : Worker.PreparedTask(File, Prepared, query, output, Problem), thensearch : LogTask(Log.Search, Log.Found). Listing a task in another preparation’s registration is a type error when the states’ types differ (Worker.PreparedTaskEntry(List(Str))againstWorker.PreparedTaskEntry(U64)). When they are the same type it compiles, and every job of that task is a contract error in its worker, given the resultLost(Contract). - A file’s state goes with the file. When the app lets go of a file, every state prepared from it is let go too.
- Tasks only read the state. A task cannot change it, so an answer never
depends on which jobs ran before it on that worker, and a lost worker
loses nothing an answer needs. A finished file may be kept in the state.
A builder may not: one that
prepare!opened is closed whenprepare!returns, and a job that uses it is a contract error, answeredLost(Contract). - A lost worker costs a preparation, never an answer. A crash in
prepare!or in a task ends that worker: the job has resultLost(fault), the state is gone, and the next job prepares again elsewhere. A timeout counts the preparation’s time. - A failed preparation is kept like any other. When
prepare!answersErr(error), the worker keeps that answer for the input, and the next job over the same input answers the sameFailed(error)without preparing again. Trying again needs a new input: for a file the browser could not read, the user choosing the file again.
Tabs. The sample’s tasks live inside their tabs, so switching away disposes a tab’s site and coming back asks again. With separate tasks every revisit pays the whole calculation; with a preparation it pays one task, because the worker kept the lines:
## Each tab's site lives in its branch: a revisit asks again, and the
## worker that kept the lines runs only the task, not a new split.
panel : State(Ctx, S), Tab -> Elem(Ctx)
panel = |st, tab| {
v = st.signal()
match tab {
Summary => Worker.resource_when(Notes.summary, v.map(|s| Notes.asked(s, {})), |r| Html.p_s(r.map(|x| Notes.show(x, |a| "${a.lines.to_str()} lines, ${a.chars.to_str()} characters")), [Engine.test_id("summary")]))
Search =>
Html.div(
"search",
[
Html.text_input(Engine.const("Word"), "search", v.map(|s| s.word), [], st.set_value(|s, word| { ..s, word })),
Worker.resource_when(Notes.search, v.map(|s| Notes.asked(s, s.word)), |r| Html.p_s(r.map(|x| Notes.show(x, |found| "lines ${Str.join_with(found.map(|n| n.to_str()), ", ")}")), [Engine.test_id("found")])),
],
)
Longest => Worker.resource_when(Notes.longest, v.map(|s| Notes.asked(s, {})), |r| Html.p_s(r.map(|x| Notes.show(x, |line| line)), [Engine.test_id("longest")]))
}
}
That is usually enough. Hoist a site out of the tab, next to the state its answer belongs with, when even the task is slow or the answer must survive the tab: a hoisted site asks once per input and keeps its answer, but it runs while its tab is hidden.
Keep the handle, not the text
A preparation’s tasks are given its state and their own query, not the
preparation’s input. When a task needs to read the file again, keep the
File in the state: it is a handle, which costs the worker nothing to
hold, and a task reads from it with read! as prepare! did. The state
can then be an index of the file rather than its text. Here prepare!
reads the file 64 KiB at a time and keeps only where each line starts, and
a task reads one line back with a single read of its bytes:
## What the preparation keeps: the file's handle, to read from later,
## and where each line starts. Not the text.
Indexed : { file : File, starts : List(U64) }
## Read the file 64 KiB at a time, so the worker holds one chunk and the
## index, never the whole file.
index! : File => Try(Indexed, Engine.FileError)
index! = |file| {
var $starts = if (file.size() == 0) [] else [0]
var $at = 0
while $at < file.size() {
len = if (file.size() - $at < 65536) file.size() - $at else 65536
chunk = file.read!({ start: $at, len })?
var $i = 0
for b in chunk {
if b == '\n' and $at + $i + 1 < file.size() {
$starts = $starts.append($at + $i + 1)
}
$i = $i + 1
}
$at = $at + len
}
Ok({ file, starts: $starts })
}
lines : Worker.Preparation(File, Indexed, Engine.FileError)
lines = Worker.preparation({ name: "example.org/lines/index", prepare!: Lines.index! })
## How many lines there are, from the index alone.
count : Worker.PreparedTask(File, Indexed, {}, U64, Engine.FileError)
count = Lines.lines.task({ name: "example.org/lines/count", run!: |indexed, {}| Ok(indexed.starts.len()) })
## One line (from 1), read from the kept handle: just its bytes.
line : Worker.PreparedTask(File, Indexed, U64, [Text(Str), PastTheEnd], Engine.FileError)
line = Lines.lines.task({ name: "example.org/lines/line", run!: Lines.line! })
line! : Indexed, U64 => Try([Text(Str), PastTheEnd], Engine.FileError)
line! = |{ file, starts }, number| {
if number == 0 {
return Ok(PastTheEnd)
}
match starts.get(number - 1) {
Ok(start) => {
end = starts.get(number) ?? file.size()
bytes = file.read!({ start, len: end - start })?
Ok(Text(Str.from_utf8_lossy(if (bytes.last() == Ok('\n')) bytes.drop_last(1) else bytes)))
}
Err(OutOfBounds) => Ok(PastTheEnd)
}
}
The worker holds the index and one chunk, never the whole file, so it can prepare a file far larger than you would read whole, let alone bring into the page. The Log Explorer is a whole app in this shape: its state is a log’s handle and an index of its lines, levels, sources and a timeline of entries a minute; its overview and its chart are answered from the index alone, and its search and its viewer read only the lines they need.
The viewer follows its native scrollbar, asking the worker for only the
fixed-height lines that fit. Its spacer is capped at 8,000,000 pixels; for a
taller log the scroll map is proportional, while paging and “Go to line”
keep fine movement available. Jumps scroll instantly, and their scroll
echoes write nothing, so one jump asks for one window. Superseded window
jobs use on_cancel: Finish to keep the worker’s prepared index for the
next question.
Two costs come with a state like this:
- A question about the whole text, such as a search for a word, reads the file again, a chunk at a time. That is the price of not keeping the text. It is still only the task’s cost: the index tells the search where lines start and which lines a filter keeps, so it never parses the file again.
- The state counts toward
maxWorkerBytes. A worker grown past it is ended after its job, its state with it, so a state too large for the bound is prepared again for every question; the console says so once for each preparation it happens to. Keep the state compact (positions and small tags rather than strings), or raise the bound. Give anything that grows with something other than the file’s size a bound of its own: the Log Explorer’s timeline counts a minute a bucket only while the log spans at most 1,500 minutes, and widens its buckets past that (half an hour for a month, six hours for a year), so it never holds more than 1,500 however long the log runs.
Lifetimes
A job belongs to the site that asked for it, and what you see follows from
that. Three props of a task say how long its jobs live: on_dispose,
timeout and on_cancel.
Leaving the screen stops the job. When a site is disposed (its when
branch switched, its row left the list, its panel closed), its job is
stopped, and no answer arrives. That is on_dispose: Stop, the default: a
job nobody will read is only cost. The panel below shows its totals in a
resource that lives inside the panel, so closing the panel stops the
totals’ job:
## The panel's totals belong to the panel: closing it stops their job.
## The export it starts is a job of a kept task: closing the panel leaves
## it running, and its answer is written to the page's state, which
## outlives the panel.
panel : State(Ctx, S) -> Elem(Ctx)
panel = |st| {
v = st.signal()
Engine.when(
v.map(|s| s.panel),
||
Html.section(
"Statistics",
"panel",
[
Worker.resource(
Documents.tally,
v.map(|s| s.docs.map(|d| d.text)),
|remote| Html.p_s(remote.map(Documents.show_totals), [Engine.test_id("totals")]),
),
Html.button(
"Export",
[],
st.update(
|s| {
..s,
presses: s.presses + 1,
ask: Export({ press: s.presses + 1, docs: s.docs }),
report: "Exporting…",
},
),
),
# Asks for a report each time "Export" is pressed,
# never for the value the panel was opened with.
Engine.watch_changes(
v.map(|s| s.ask),
|ask|
match ask {
Idle => []
Export({ docs, .. }) => [Documents.report.ask(docs)]
},
st.on_result(
|s, _, res|
match res {
Ok(text) => { ..s, report: text }
Err(error) => { ..s, report: Documents.problem(error) }
},
),
),
],
),
|| Engine.text(""),
)
}
A job that must outlive its site says so. The panel’s “Export” button
asks for a report, and the site that issues it is inside the panel too. Its
task is declared on_dispose: Keep:
## A report on every document. The user asked for it, so its job is kept
## when the site that asked for it is disposed, and it gives up after a
## minute.
report : Worker.Task(List(Doc), Str, Worker.Never)
report = Worker.task({
name: "example.org/documents/report",
run!: |docs| Ok(Str.join_with(docs.map(|d| "${d.id}: ${Documents.word_count(d.text).to_str()} words"), "; ")),
timeout: Ms(60000),
on_dispose: Keep,
})
Closing the panel while an export runs leaves the job running. When it
answers, the reaction its request was made with still runs, and its write
to the page’s state shows the report. Write a kept job’s answer into state
that outlives the site, as here: a write to a state that was disposed with
the site is skipped, and a worker resource goes with its site, so ask
for a kept job with request and result. The other way to let work
outlive a panel is to mount its site outside the panel, in the scope that
should own the work.
Each row can have its own job. A resource in an each row runs for that
row’s value. Jobs finish in any order, and each row shows its own answer.
Removing a row stops its job:
## Each row runs its own count. Removing a row stops its job.
rows : State(Ctx, S) -> Elem(Ctx)
rows = |st|
Html.ul(
[],
[Engine.each(st.signal().map(|s| s.docs), |d| d.id, |row_ref| Documents.row(st, row_ref))],
)
row : State(Ctx, S), RowRef(Ctx, Doc) -> Elem(Line)
row = |st0, row_ref| {
st = st0.lift_row()
id = row_ref.key()
Html.li(
[],
[
Html.span_s(row_ref.field(|d| d.text), []),
Worker.resource(
Documents.count,
row_ref.field(|d| d.text),
|remote| Html.p_s(remote.map(Documents.show_count), [Engine.test_id_s(id.map(|k| "words-${k}").lift())]),
),
Html.button_s(id.map(|k| "Remove ${k}"), [], st.update_by(id, |s, k| { ..s, docs: s.docs.keep_if(|d| d.id != k) })),
],
)
}
Jobs share the in-flight bound. Worker jobs count against the same bound
as HTTP requests and timers: 32 awaited requests by default, set with
max_inflight in Engine.program_boot. A job beyond the bound is not
started; its result is Refused straight away, and the others go on. The
sample sets a bound of three so its spec can reach it:
## At most three jobs are in flight at once, kept low here so the specs
## can reach the bound; the default is 32.
program : Engine.Program
program =
Engine.program_boot({ storage_keys: [], max_inflight: 3 }, |_| Engine.state(Documents.initial, Documents.view))
.with_workers([Documents.count.registration(), Documents.tally.registration(), Documents.report.registration()])
A refused job is not retried. A resource asks again only when its input
changes, so tell the user, as the rows do, or ask again from a button.
Jobs beyond the number of workers wait for a free one. The pool’s size is
the page’s maxWorkers option (see Serving the app).
Task and prepared-task timeouts use Unlimited for none, or Ms(ms) with
at least one millisecond. Ms(0) is a contract error when Worker.task or
the preparation’s task constructor is called. A bad top-level constant
fails while compiling; a computed bad timeout faults when constructed.
A timeout stops a job that takes too long. timeout: Ms(ms) stops a
job that has not answered ms milliseconds after it was asked for, and
delivers the result Timeout:
## The three most used words. A job that has not answered five seconds
## after it was asked for is stopped and answers `Timeout`.
frequencies : Worker.Task(Str, List(Frequency), Worker.Never)
frequencies = Worker.task({
name: "example.org/words/frequencies",
run!: |text| Ok(Words.most_used(text, 3)),
timeout: Ms(5000),
})
- The time counts from when the job is asked for, so time spent waiting for a free worker and starting one counts too, and so does a preparation.
- Expiry stops the job: a job still waiting for a worker is dropped, and a running one ends its worker. The work does not finish in the background.
Unlimited, the default, means no timeout. The longest timeout is ten minutes.
A job that never finishes holds its worker until its site stops it, or,
when its task says on_cancel: Finish (below), until its timeout, and at
most ten minutes after it was asked for when it has none. Give a task a
timeout when its input can make it run for an unreasonable time.
A cancelled job can be allowed to finish. A job is cancelled when its
site is disposed (unless its task says Keep) or when a watch_latest or
resource site moves on to a newer input. By default, on_cancel: Stop, a
cancelled job that is running ends its worker, and anything that worker
held goes with it, a prepared state included. A task declared
on_cancel: Finish, as longest is in the notes sample above, lets a
cancelled job complete and drops its answer, so its worker, and the state
it holds, is kept for the next job; the cost is a worker busy for the rest
of that job. Either way the app never sees a cancelled job’s answer.
Finish suits a tab whose task the user often leaves mid-job, so the
worker is still warm when they come back, and a task asked again as the
user types, such as a search over a prepared file: a search the user has
typed past runs to its end, and the next one waits for the worker that
holds the state rather than preparing it again on another. A timeout
always ends the worker, a cancelled job’s included: a job that is still
finishing when its timeout expires has its worker ended there, and one
whose task has no timeout is ended ten minutes after it was asked for, so
a job that never ends cannot hold a worker for good.
Whatever stops a job, nothing it wrote can be seen: only a delivered answer puts a file on the page.
Failures
A job that gives no output has failed in one of two ways: the task chose
to answer an error, or there was no answer at all. Worker.Error(error)
tells them apart:
| Error | Cause |
|---|---|
Failed(error) | The task answered Err(error): a failure of its own, which it chose |
Timeout | The job’s timeout expired, and it was stopped |
Refused | Too many requests were in flight; the job was never started |
TooDeep | The input or the answer nested more than 128 levels of lists, sets, dictionaries, records, tuples, tags with a payload and files; nothing was sent or answered, and the worker was kept |
NanKeys | The input or the answer held a dictionary with more than one NaN key, which a payload cannot tell apart; nothing was sent or answered, and the worker was kept |
TooManyFiles | The answer held more than 16 files; nothing was answered, and the worker was kept |
Lost(fault) | The job crashed, or no worker could run it |
The task’s own error. A calculation that can fail on its input (text
that is not a number, a file that cannot be read) answers Err with an
error type of its choosing:
## The sum of the numbers in a text, or the first word that is not one:
## a task's own error, which reaches the page as `Failed(NotANumber(word))`.
total : Worker.Task(Str, U64, [NotANumber(Str)])
total = Worker.task({ name: "example.org/words/total", run!: |text| Words.add_up(text) })
add_up : Str -> Try(U64, [NotANumber(Str)])
add_up = |text|
Words.split(text).fold_try(
0,
|sum, word|
match U64.from_str(word) {
Ok(n) => Ok(sum + n)
Err(_) => Err(NotANumber(word))
},
)
In the resource, that error is Failed(Failed(NotANumber(word))): the
resource’s Failed, holding the Worker.Error’s. Worker.status flattens
the two into one union, so a view matches each case once:
## Add up the numbers in a box, in a worker.
total : State(Ctx, S) -> Elem(Ctx)
total = |st| {
v = st.signal()
Html.div(
"total",
[
Html.text_input(Engine.const("Numbers"), "text", v.map(|s| s.numbers), [], st.set_value(|s, numbers| { ..s, numbers })),
Worker.resource(Words.total, v.map(|s| s.numbers), |sum| Html.p_s(sum.map(Editor.show_total), [Engine.test_id("total")])),
],
)
}
## `Worker.status` reads the resource as one union: the task's own error
## (`Failed`) beside the ways a job can produce no answer at all,
## including the payload's refusals (`TooDeep`, `NanKeys`,
## `TooManyFiles`), which leave the worker as it was.
show_total : Engine.Remote(U64, Worker.Error([NotANumber(Str)])) -> Str
show_total = |remote|
match Worker.status(remote) {
Unasked | Working => "Adding…"
Answered(sum) => "Total ${sum.to_str()}"
Failed(NotANumber(word)) => "\"${word}\" is not a number"
Timeout => "Adding took too long."
Refused => "Too much is running; edit the numbers to try again."
TooDeep => "The answer was nested too deeply to send."
NanKeys => "The answer held two NaN keys in one dictionary."
TooManyFiles => "The answer held more files than a job may return."
Lost(_) => "Adding failed."
}
With request and result, the same cases are Ok(value),
Err(Failed(error)), Err(Timeout), Err(Refused), Err(TooDeep),
Err(NanKeys), Err(TooManyFiles) and Err(Lost(fault)).
A long job. A job cannot be stopped from inside: there are no
checkpoints, and stopping one ends its worker. Split long work into
shorter jobs (see One question, several jobs)
and give a task a timeout, so a job that runs too long is stopped and
has result Timeout.
A lost job. Use the task’s own error for failures you expect. A
crash in a job is not an error you chose: it is Lost. A job that fails
badly (a crash, running out of memory, a failed expect in a development
build) ends only its worker. The job has result Lost(fault) with the fault’s
class, the diagnostic goes to the browser console, and the page keeps
working. The next job starts a new worker.
| Fault | Cause |
|---|---|
AppCrash, OutOfMemory, ExpectFailed | The job crashed, ran out of memory, or failed an expect |
Contract | The job broke a rule of the API: a builder used after finish! |
ResourceLimit | The job held more than 64 files and builders at once, or the page had no room for the files of its answer |
Unavailable | No worker could run the job (below) |
Executor | The worker script itself failed |
Lost(Unavailable) has two causes. In a browser without workers, every job
answers it. And with the workers: "inline" mount option jobs run on the
page’s thread, where the effects on files do not exist: a job that reaches
none of them answers as it would in a worker, and a job that reaches one
has result Lost(Unavailable), while the page and later jobs keep working.
The workers sample’s specs show both kinds: a total whose own error reaches the view, and a total whose job is lost (see Testing).
What can cross
A task’s input, output and error must be Wire.Sendable. Most types are,
with no code from you: numbers, Bool, Str, lists, sets, dictionaries,
records, tuples and tag unions of those, and File, which crosses as a
handle. A dictionary key must be a number, Bool, Str or a tag union
without payloads. A key that is a tuple, a record or a nominal type is a
compile error at the task’s declaration, naming the missing method
encode_key_start: its equality is its type’s own, which the format
cannot see, so two keys the type equates would silently become one entry
(roc#13057), and the
compiler cannot yet build such a key’s codec
(roc#12919). Use a
Dict(Str, v) or a list of pairs instead.
## Records, tag unions, lists, numbers and strings cross as they are.
Shape : [Circle({ radius : F64 }), Rect({ width : F64, height : F64 })]
area : Worker.Task(List(Shape), F64, Worker.Never)
area = Worker.task({
name: "example.org/shapes/area",
run!: |shapes|
Ok(
shapes
.map(
|shape|
match shape {
Circle({ radius }) => 3.141592653589793 * radius * radius
Rect({ width, height }) => width * height
},
)
.sum(),
),
})
A nominal type crosses once it declares the codec hooks parser_for : _ and
encoder_for : _. It is sent as the value it wraps:
## A nominal type crosses once it declares the two codec hooks. It is then
## sent as the value it wraps.
Celsius := { degrees : F64 }.{
is_eq : _
parser_for : _
encoder_for : _
## The reading in degrees.
degrees : Celsius -> F64
degrees = |c| c.degrees
}
## Its error, `[Empty]`, crosses as any tag union does.
warmest : Worker.Task(List(Celsius), Celsius, [Empty])
warmest = Worker.task({
name: "example.org/weather/warmest",
run!: |readings|
readings.fold(
Err(Empty),
|best, reading|
match best {
Ok(b) => if (reading.degrees() > b.degrees()) Ok(reading) else Ok(b)
Err(Empty) => Ok(reading)
},
),
})
Functions, State values, Signals, builders and nominal types without the
hooks do not cross. Using one is a compile error at the task’s declaration,
naming the type that lacks the hooks. Here Celsius declares only is_eq:
── ✗ missing method ────────────────────────────────────────────── main.roc:17:8
A where clause requires the encoder_for method here, but the type being used
doesn't have that method.
warm = Worker.task({ name: "example.org/weather/warm", run!: |c| Ok(c.degrees > 20) })
^^^^^^^^^^^
The value's type, which does not have a method named encoder_for, is:
Celsius
Hint: For this to work, the type would need to have a method named encoder_for
associated with it in the type's declaration.
A second error says the same of parser_for.
The Try a job answers is the platform’s to send. A Try inside a
payload does not cross: the compiler reports Try(U64, [NotANumber])
without encoder_for in the same way. (The one exception is a record field
of type Try(a, [Missing]), which the derivation treats as an optional
field.) Inside a payload, use a tag union of your own, such as
[Parsed(U64), NotANumber(Str)].
For bulk bytes the page already holds, wrap the List(U8) in Wire.Bytes.
It is encoded and read as one CBOR byte string rather than item by item.
An empty Bytes is an empty byte string, while an ordinary empty derived
list is an empty array, and the strict reader reads each only as its own
type. Both ends of a job always have the same types, so this never refuses
a payload one instance sends another:
## Bulk bytes cross as one block when wrapped in `Wire.Bytes`.
checksum : Worker.Task(Wire.Bytes, U32, Worker.Never)
checksum = Worker.task({
name: "example.org/files/checksum",
run!: |bytes| Ok(Wire.Bytes.to_list(bytes).fold(0, |sum, byte| sum + byte.to_u32())),
})
## A request for a checksum of bytes the page holds, wrapped for sending.
## (A file the page holds is sent as its handle instead, and read in the
## job.)
check_bytes : List(U8) -> Engine.Request
check_bytes = |contents| checksum.request(Wire.Bytes.from_list(contents))
Payloads use the pinned roc-cbor format. Records carry field names, dictionaries
have sorted keys, and every number uses the writer’s preferred representation.
The two instances are the same compiled module; payload bytes are not a format
for an app to persist across releases. A float keeps its zero sign, while all
NaN payloads become one canonical NaN. A dictionary with F32 or F64 keys
cannot hold both 0.0 and -0.0, which float equality makes one key, so a
payload holding both is refused rather than read as one entry. NaN is not
equal to itself, so such a dictionary can hold several NaN keys, but a
payload writes every NaN alike: one NaN key crosses, and a dictionary with
two is not sent. Its job’s result is NanKeys, as TooDeep below.
A handwritten codec is generic over its format and names only the hooks it
calls: an encoder_for of type format -> (T, enc -> Try(enc, [])) whose
where clause lists, say, format.encode_list and format.encode_str, and
which calls them through a local alias of format. It never names the
platform’s format or its states, which are not public: pass each supplied
state through the hooks, as a derived codec does. A list, tuple or tag’s
accumulator is distinct from the writer its add callback supplies for each
item. A handwritten parser that opens a dictionary with parse_dict_start
calls parse_dict_after_key after each key, as a derived one does.
Wire encodes and decodes only the payloads the platform carries between
instances; it offers no encode or decode of its own. An app that needs CBOR
bytes of its own depends on roc-cbor and chooses its own schema and
persistence contract. A worker task’s types derive their codecs through
Wire.Sendable, so a task’s source calls no encoder or decoder.
Every payload is decoded strictly. A value crosses only if it nests at
most 128 levels: each list, set, dictionary, record, tuple, tag with a
payload and file is one level of the path down to it. A deeper input is
not sent and its job’s result is TooDeep at once; a deeper answer is not
sent either, and the job’s result is TooDeep. Either way the worker and
its prepared state are kept, and nothing is lost. The bound is what a
browser worker can encode safely on every build; a handwritten codec that
recurses without the container hooks is not counted. Keep payloads plain: each payload
type adds code to the module.
When a worker is worth it
A worker is not free. Starting one loads the worker script and instantiates the module in a new thread, and every job encodes its input on the page, copies it to the worker, and copies and decodes the answer on the way back. A job is also asynchronous: its answer arrives in a later turn, so the view has to say what it shows meanwhile.
So keep cheap work on the page. Counting the words of a text box is quick, and
a derive gives its answer in the same turn as the keystroke:
## Counting words is quick, so it stays on the page in a `derive`.
length : Signal(Ctx, S) -> Elem(Ctx)
length = |v|
Engine.derive(
v.map(|s| Words.split(s.text).len()),
|n| Html.p_s(n.map(|words| "${words.to_str()} words"), [Engine.test_id("length")]),
)
Move a calculation to a worker when you can feel it: when a keystroke or a click visibly waits for it. To see where a job’s time goes (waiting for a worker, starting one, computing, copying), read the runtime’s monitor; see Monitoring Workers. A job whose time is mostly copying and starting is better done on the page.
A job receives only its input, so data it needs every time, such as the text it searches, is sent and copied with every job. When the cost is not sending the data but preparing it (parsing a document, building an index), a preparation lets a worker keep the prepared state between jobs without changing any answer. When the data is a file, send its handle: nothing is copied until the job reads it.
The page and its workers run one module, so a task’s code is part of the module the page downloads and compiles, although the page never runs it. A task that brings in a large library makes the app’s module larger by about that library’s size, and its build longer. The types a task sends and returns add code too, usually far less than the task itself.
Serving the app
The runtime starts its workers from worker.mjs, beside runtime.mjs.
It also imports environment.mjs for browser facts. Serve all three together,
from the same origin as the page. roc signals.roc serve does this, and roc signals.roc build puts
the runtime files beside the app’s module in dist/ (see
Getting Started).
Serving the files yourself, copy all three from the release, or from platform/
in a checkout:
cp platform/runtime.mjs platform/environment.mjs platform/worker.mjs my-site/
A worker receives the module the page already compiled, so app.wasm is not
fetched again. Your page only calls mountRocEngineApp; it never sees the
worker protocol. Its options for workers:
await mountRocEngineApp({
wasmUrl: "app.wasm",
root: document.getElementById("app"),
maxWorkers: 4, // most workers at once; default min(cores, 8)
workerUrl: "/js/worker.mjs", // when worker.mjs is not beside runtime.mjs
workers: "inline", // run jobs on the page's thread instead (below)
maxWorkerBytes: 64 << 20, // retire a worker grown past this; default 128 MiB
maxOutputBytes: 64 << 20, // most bytes a job appends to builders; default 256 MiB
onWorkerFault: (f) => console.warn(f.task, f.class, f.message),
});
maxWorkersbounds the workers alive at once. Each runs one job at a time; further jobs wait in order.workerUrllocatesworker.mjswhen you serve it elsewhere.workers: "inline"runs every job in a second instance of the module on the page’s own thread, one at a time. A job that only calculates gives the same answer; a job that reads or builds a file answersLost(Unavailable)(see Failures). The page waits while a job runs, and a timeout can only stop a job that has not started. It gives up what a worker is for; use it to measure or debug.maxWorkerBytesends a worker whose memory has grown past it, after its job, since a worker’s memory never shrinks.maxOutputBytesbounds what one job copies into its builders (see Files in Tasks).onWorkerFaultreceives{ id, task, class, message }when a job isLost, in addition to the console message;taskis the task’s name. The diagnostic never reaches the app.
Testing
Worker jobs are effects, and specs control them like HTTP requests and timers (see Testing):
- A job waits until
(run-effect N)runs it,Nbeing its place among the document’s HTTP requests, timers and jobs in the order they were asked for. In Chrome it runs in a real worker; natively it runs in a child process of the spec runner, which serves the job’s effects from the spec’s files. The step waits for the answer. A task that crashes isLostin both, and the next job works. (expect-pending-effects N)counts jobs still waiting, so a spec can see that a job was stopped.(expect-pending-work "name" N)counts only the jobs of one task, by its name.- A job finishes when the spec runs it, so the order of
run-effectsteps is the order jobs finish. Running a later job first checks the app against an earlier, slower one.
(test "Words — the search runs only while there is a word to find"
(steps
(run-effect 1)
(run-effect 2)
; An empty box is Skip: nothing runs and nothing is shown.
(expect-pending-effects 0)
(expect-text (test-id "found") "")
(fill (label "Text") "the cat\nsaw\nthe hat")
(run-effect 3)
(fill (label "Find") "the")
(expect-text (test-id "found") "Searching…")
(expect-pending-effects 1)
(run-effect 4)
(expect-text (test-id "found") "Lines 1, 3")
; Changing the text is a new question for the search too.
(fill (label "Text") "the cat\nsaw a hat")
(expect-pending-effects 2)
(run-effect 6)
(expect-text (test-id "found") "Lines 1")
(run-effect 5)
(fill (label "Find") "dog")
(run-effect 7)
(expect-text (test-id "found") "Not found")
; Clearing the box stops a job that is still wanted and clears the answer.
(fill (label "Find") "cat")
(expect-pending-effects 1)
(fill (label "Find") "")
(expect-pending-effects 0)
(expect-text (test-id "found") "")
)
)
Here the text and the word are both in the box, so editing the text asks for the summary (job 5) and the search (job 6); the spec answers the search first.
A spec’s time only moves when the spec says so, so a timeout never expires by itself, however long the job takes. Two steps answer a waiting job without running it:
(time-out-work N)expires its timeout: the job has resultTimeout. A job of a task without a timeout cannot time out, and the step fails.(lose-work N FAULT)deliversLost(fault), as if its worker had crashed (app_crash), run out of memory (out_of_memory), or there were no worker at all (unavailable). See Testing for every fault.
So the failure branches of a view have specs too:
(test "Words — a job that times out or is lost says so, and the page keeps working"
(steps
(run-effect 1)
(run-effect 2)
(click (role button :name "Count words"))
(expect-pending-work "example.org/words/frequencies" 1)
; The count has a five-second timeout. A spec's time only moves when it
; says so: here the timeout expires before the job answers.
(mark-metrics)
(time-out-work 3)
(expect-text (test-id "counted") "This took too long.")
(expect-metric-delta effects_delivered 1)
(expect-pending-effects 0)
; A job can also be lost: its worker crashed, ran out of memory, or there
; is none. The view shows the same failure for every cause.
(fill (label "Numbers") "1 2")
(lose-work 4 out_of_memory)
(expect-text (test-id "total") "Adding failed.")
; Nothing else broke: the next jobs answer as usual.
(fill (label "Numbers") "1 2 3")
(run-effect 5)
(expect-text (test-id "total") "Total 6")
(click (role button :name "Count words"))
(run-effect 6)
(expect-text (test-id "counted") "the 2, cat 1, saw 1")
(expect-metric-delta effects_cancelled 0)
)
)
A kept job is still pending after its site is gone, so a spec can close the panel and then run it:
(test "Documents — closing the panel stops its job, but not the kept export it started"
(steps
(run-effect 1)
(run-effect 2)
(click (role button :name "Statistics"))
(expect-text (test-id "totals") "Counting…")
(expect-pending-effects 1)
; Closing the panel disposes its site, and that stops its job.
(click (role button :name "Statistics"))
(expect-absent (test-id "totals"))
(expect-pending-effects 0)
(click (role button :name "Statistics"))
(run-effect 4)
(expect-text (test-id "totals") "8 words in 2 documents")
(click (role button :name "Export"))
(expect-text (test-id "report") "Exporting…")
(expect-pending-work "example.org/documents/report" 1)
; The export site is inside the panel, but its task says on_dispose: Keep,
; so its job survives the panel and its answer still reaches the page.
(click (role button :name "Statistics"))
(expect-pending-work "example.org/documents/report" 1)
(run-effect 5)
(expect-text (test-id "report") "doc-1: 3 words; doc-2: 5 words")
; Opening the panel again asks for nothing new.
(click (role button :name "Statistics"))
(expect-pending-work "example.org/documents/report" 0)
)
)
The work metrics count jobs with the other effects: effects_issued for
each job asked for, effects_cancelled for each one stopped,
effects_delivered for each answer, and effects_refused for each one
the in-flight bound turned away (see
Work assertions).
Which tool
| You want | Use |
|---|---|
| A cheap value computed from state | Engine.derive |
| A slow value that follows its input | Worker.resource with a task |
| The same, when some inputs ask nothing | Worker.resource_when |
| A job the user starts and cancels, with its answer kept in state | Engine.watch_latest with request and result |
| A task that cannot fail | Worker.Never as its error |
| A task that fails on some inputs | An error type of its own, answered Err(error) and read as Failed(error) |
| A job that reads a file, or part of one | file.read!, file.contents!, file.contents_utf8! in run! |
| A job that writes a new file | Files.build! and a builder; see Files in Tasks |
| Several tasks over one slow preparation | Worker.preparation and its task |
| A job that must not take too long | timeout: Ms(ms) |
| A job that must finish although its panel closed | on_dispose: Keep, and a reaction that writes to state outside the panel |
| A cancelled job that should keep its worker’s prepared state | on_cancel: Finish |
| Bulk bytes in a payload | Wire.Bytes |
| Where a job’s time goes | Monitoring Workers |
Compared with roc-gui
roc-gui’s Action.task({ pending, run, resolve }) takes run as a closure
written where the action is, which a thread sharing the UI’s memory then
runs. Here a job runs in another instance of the module with memory of its
own, and a closure cannot cross to it. So a task is a named, registered
function whose context is its input, and its pending and resolve are
the sites that issue it and react to its answer (Worker.resource, watch_latest,
Engine.resource). The handles are the same idea, and so are the !
effects on them; what is different is that a job’s effects cannot wait, and
that a handle crosses to the job by token rather than being shared.
Debugging a task
A job’s dbg lines appear on the page console with [dbg task "name"] when
its answer or fault arrives. Preparation output precedes task output; a kept
preparation prints only when it actually runs. A cancelled job allowed to
finish still prints, while a stopped, timed-out or lost worker loses its
buffer with its memory. While investigating that job, lengthen its timeout
or call its function from an expect. dbg: "off" applies to jobs too.
See Debugging before deploying debug statements.