# `Typsty.Pool`
[🔗](https://github.com/akoutmos/typsty/blob/0.1.0/lib/typsty/pool.ex#L1)

A pool of worker processes that render documents outside of the BEAM.

By default, Typsty renders inside your VM. That's the fastest way to render, and the
right one for well validated data (see
[What a template can do](Typsty.html#module-what-a-template-can-do)). A template is code,
though, and a template that loops for a long time or allocates without bound, as data
can make it do, can only be stopped by ending the process it runs in. Favor a pool for
input from untrusted users that isn't well validated, and for files they upload. The
pool runs renders in separate OS processes, so that it can:

- **stop a render at its timeout**, whatever it's doing, by ending its worker
- **limit the memory** a render can use, ending its worker when it goes over
- **contain crashes**: a worker that dies takes nothing else down

A worker that's ended is replaced with a new one. Documents rendered in a pool can also
read PDF files, which renders inside the VM refuse.

## Usage

Add a pool to your supervision tree:

```elixir
children = [
  {Typsty.Pool, name: MyApp.TypstPool, size: 4, memory_limit: 1_000_000_000}
]
```

and render with it, per render or for every render:

```elixir
MyApp.Invoice.to_pdf(assigns, pool: MyApp.TypstPool, timeout: 10_000)

config :typsty, pool: MyApp.TypstPool
```

Renders return what they return without a pool: the same output, warnings and errors,
pointing at the same lines. They can also read PDF files, and SVG images that contain
other SVG images, which renders inside the VM refuse. As inside the VM, a render that runs
past its timeout fails with `:timeout`, and one that waits past it for a free worker with
`:busy` (see `Typsty.RenderError`). A render that goes over the memory limit fails with
`:memory_limit`, and one whose worker crashes, or whose pool stops, before or during the
render with `:crashed`. A render can take up to a second longer than its timeout, while
its worker is stopped.

A pool serves the processes on its own node. A render's template, assigns and files
(with its components and their files) may be at most 4 GiB together.

## Options

* `:name` (`t:GenServer.name/0`) - The name to register the pool under, to pass as the `:pool` option.

* `:size` (`t:pos_integer/0`) - The number of workers, which is how many renders can run at once. Defaults to the
  number of CPU cores (`System.schedulers_online/0`). A render waits for a free worker,
  within its timeout.

* `:memory_limit` (`t:pos_integer/0` or `nil`) - The most memory, in bytes, each worker may use. A render that goes over it fails, and
  its worker is replaced. `nil` is no limit. See [Memory](#module-memory). The default value is `nil`.

* `:max_renders` (`t:pos_integer/0` or `nil`) - Replaces each worker after this many renders, which bounds the memory a long-running
  worker holds on to, and gives it a fresh table of file paths (see
  [Files](Typsty.html#module-files)). `nil` keeps workers for as long as they work. The default value is `nil`.

## Memory

The memory limit counts what a worker allocates: the document being rendered, Typst's
caches, and the fonts it has loaded, which it keeps (system fonts can be large: an emoji
font can take 200 MB). Allow for those, and for the files a render is given (its
components' files too), which the worker holds twice while it reads the request; a render
whose template, assigns and files are larger than the limit fails without being sent.
Each worker keeps its own fonts and caches, so a pool uses up to `size` times as much.
The limit doesn't count thread stacks or the allocator's overhead, so the operating
system sees somewhat more.

A worker drops Typst's caches once they take half of the room left under the limit.

Without a memory limit, a render that allocates without bound grows its worker until
the operating system runs out of memory, and the system may then end another process
than the worker (the BEAM, say). Set a limit when rendering templates or files you don't
trust.

## How it works

Each worker runs `typsty_worker`, a program built from the same code as the NIF, which
Typsty installs next to it. The pool talks to it through a port. A worker renders one
document at a time, and keeps Typst's caches and its fonts between renders, like the
NIF does. When the pool starts, it checks that the program runs, and then starts its
workers, which load the fonts that renders use by default (as configured). The pool is
started once they have, so renders never wait for that, even the first ones: in a
supervision tree, the children after the pool start once it's ready. A worker that
replaces one that ended starts in the background, and joins the pool once it has loaded
the fonts. A worker that fails to start is logged, and retried a second later, while the
pool runs with the others.

A worker exits as soon as its port closes, even in the middle of a render. That happens
when a render times out, when the process that asked for the render exits, when the pool
stops, and when the VM exits, so workers never outlive what they're working for. A render
that runs past its timeout ends its worker itself, too. A worker also retires itself after
Typst panicked in it, and when its table of file paths is nearly full, and is replaced.

Rendering in a worker costs a little more than in the NIF: the template, the assigns,
the files and the output are copied between processes, and a worker that replaces one
that was ended starts with empty caches.

# `option`

```elixir
@type option() ::
  {:name, GenServer.name()}
  | {:size, pos_integer()}
  | {:memory_limit, pos_integer() | nil}
  | {:max_renders, pos_integer() | nil}
```

An option for `start_link/1`. See [Options](#module-options).

# `start_link`

```elixir
@spec start_link([option()]) :: GenServer.on_start()
```

Starts a pool. See [Options](#module-options) for the options.

Returns once the pool's workers have started and loaded the fonts that renders use by
default, all at once, which takes about as long as one worker does. A worker that
doesn't start within a minute is left to start in the background.

Raises `ArgumentError` for invalid options, and raises if the worker program can't run,
before starting any workers. With a `:memory_limit`, it also starts a worker to check
that the limit leaves room for the fonts renders use by default.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
