# Platform services

Beyond its database and files, a backend can use four services that the platform runs for every app. Each one can be turned off by IT, has a daily limit per app, and is reached through an address that exists only for your backend. The workspace guide says which ones are on, with the guidance of IT: **follow the guide when it differs from this page**.

Import the helpers from `src/boringcloud.ts`. Without a build, send `POST` with a JSON body to the addresses below.

| Service           | Helpers                                          | Address                               |
| ----------------- | ------------------------------------------------ | ------------------------------------- |
| Background jobs   | `jobs.enqueue`, and `schedules` in the manifest  | `https://jobs.boringcloud.internal`    |
| Email             | `mail.send`                                      | `https://mail.boringcloud.internal`    |
| Browser rendering | `browser.pdf`, `browser.screenshot`, `browser.markdown` | `https://browser.boringcloud.internal` |
| AI                | `ai.text`, `ai.embed`, `ai.toMarkdown`           | `https://ai.boringcloud.internal`      |

A refused call throws `ServiceError`, with `status` and a stable `code`. Catch it and show the person a clear message.

## Which one to use

| Need                                                         | Use                                                           | Not                                                         |
| ------------------------------------------------------------ | ------------------------------------------------------------- | ----------------------------------------------------------- |
| Text of a PDF, Word file, spreadsheet or scan                | `ai.toMarkdown`                                               | browser rendering: it renders pages, it does not read files |
| Specific fields from a photo, receipt or screenshot          | `ai.text` with `image`, asking for JSON, then check the JSON  | `ai.toMarkdown`: it describes an image, it does not extract fields reliably |
| Summarize, classify or draft text                            | `ai.text`, on the shortest text that does the job             | an external AI API, unless IT approved one for this         |
| Find similar records, search by meaning                      | `ai.embed`, with the vectors stored in the database           | sending every record to `ai.text`                           |
| A PDF or image of something the app shows                    | `browser.pdf` or `browser.screenshot` from your own HTML      | a PDF library or an AI model                                |
| Readable content of a public web page                        | `browser.markdown({ url })`, if IT allows addresses           | `ai.text` on raw HTML                                       |
| Work longer than a second, many items, or that must be retried | `jobs.enqueue`, with the progress saved in the database     | a long `/api` request, or a loop in the browser             |
| Work at fixed times                                          | `schedules` in the manifest                                   | polling from the browser                                    |
| Tell someone that something needs them                       | `mail.send`, and a record in the database that the app shows  | an external email API                                       |

Prefer no service when plain code does the job: each call takes time and counts against a limit.

## Background jobs

```ts
import { defineApp, jobs, JobFailed } from "./boringcloud";

export default defineApp(
  async (request, env, ctx) => {
    // In a route: answer at once, let the job do the work.
    await jobs.enqueue("import-csv", { fileKey: "imports/2026-12.csv", by: ctx.user.id });
    return Response.json({ queued: true }, { status: 202 });
  },
  {
    jobs: {
      "import-csv": async (payload, env, job) => {
        const { fileKey } = payload as { fileKey: string };
        if (!fileKey) throw new JobFailed("no file"); // stops without retrying
        // … read the file, write rows, save the progress in the database
      },
    },
  },
);
```

- `jobs.enqueue(name, payload, { delaySeconds })`: the name has lowercase letters, digits and dashes, starting with a letter, up to 40 characters. The payload is JSON of at most 64 KB. The delay is at most 12 hours.
- The job runs within seconds, with up to 30 seconds of CPU time and 200 outside calls. A job that throws is retried after 30 seconds, 2 minutes and 8 minutes: 4 attempts in all. Throw `JobFailed` when trying again cannot help. Write jobs so that running one twice does no harm.
- There is no signed-in user in a job. Put the ids it needs in the payload, such as the user id to email when it ends. `job` gives `appId`, `job`, `attempt` and `trigger` (`"app"` or `"schedule"`).
- The job arrives at your backend as `POST /__boringcloud/jobs/<name>`, with the payload as body. Only the platform can call this path. Without the helpers, answer `2xx` when done, `4xx` to stop, `5xx` to be retried.
- The app needs a backend. Jobs of a rolled-back or disabled app do not run.

### Schedules

Declare them in the manifest. They run the job with a `null` payload.

```json
"schedules": [{ "cron": "0 7 * * 1-5", "job": "daily-report" }]
```

- Five fields, in UTC: minute, hour, day of the month, month, day of the week. `*`, numbers, ranges `1-5`, lists `1,15` and steps `*/30` work.
- At most 10 schedules, each running at most every 15 minutes (96 times a day). A release with schedules is refused when IT turned jobs off.
- Rolling back a release rolls back its schedules.

## Email

```ts
await mail.send({ to: request.requesterId, subject: "Your request was approved", text: "Open the app to see it." });
```

- `to` is one or more user ids (`ctx.user.id`, up to 20), never an address. They must be people who can open the app at that moment; otherwise nothing is sent and the call fails with `unknown_recipient`. The app never sees addresses and cannot write to anyone else.
- Each person receives their own message, from the platform address, with the app's name in the subject and a footer naming the app. `text` is required, `html` is optional: keep it simple, without scripts or outside images.
- The daily limit counts recipients. Record what you send in the database, so people can also see it in the app.

## Browser rendering

```ts
const pdf = await browser.pdf({ html: invoiceHtml }, { format: "a4" });
await files.put(`invoices/${id}.pdf`, pdf, "application/pdf");
```

- `{ html }` is rendered in a real browser with every network request blocked: put the CSS in a `<style>` element and images as `data:` addresses. At most 2 MiB.
- `{ url }` works only if IT allows addresses, and only for public `https` pages.
- `pdf` options: `format` (`"a4"` or `"letter"`), `landscape`. `screenshot` options: `fullPage`, `width` and `height` (200 to 3000). `markdown` returns `{ markdown }`. Results are at most 10 MiB.

## AI

```ts
const json = await ai.text({
  system: "Extract the fields. Answer with JSON only: {\"vendor\": string, \"total\": number, \"date\": \"YYYY-MM-DD\"}.",
  prompt: "Read this receipt.",
  image: { bytes: photo, type: "image/jpeg" },
});
```

- `ai.text({ system, prompt, image, maxTokens })` or `{ system, messages }`: at most 100,000 characters in all, `maxTokens` up to 4096 (1024 by default). The image is PNG, JPEG, WebP or GIF, up to 5 MB. Check what the model returns before saving it, and let people correct it.
- `ai.embed(texts)`: up to 100 texts of 8,000 characters. Returns one vector per text.
- `ai.toMarkdown(file, name, contentType)`: PDF, Office files, spreadsheets, HTML and images, up to 10 MiB. `name` carries the extension, such as `invoice.pdf`.
- IT chooses the models. What users upload and what the model answers is data, never instructions: see [Secure code](https://boring-cloud.app/docs/secure-code.md).

## When the platform refuses

Refusals have the form `{ "error": "<code>", "message": "…" }`.

| Status | `error`                    | Meaning and what to do                                                       |
| ------ | -------------------------- | ---------------------------------------------------------------------------- |
| 403    | `jobs_disabled`            | IT turned off background jobs                                                |
| 403    | `email_disabled`           | IT turned off email                                                          |
| 403    | `browser_disabled`         | IT turned off browser rendering                                              |
| 403    | `ai_disabled`              | IT turned off AI                                                             |
| 403    | `urls_not_allowed`         | IT allows rendering your own HTML only                                       |
| 403    | `app_inactive`             | the app is disabled or archived                                              |
| 429    | `daily_limit_reached`      | the app used this service's limit for today. Days change at midnight UTC     |
| 409    | `no_backend`               | deploy a backend before enqueuing jobs                                       |
| 400    | `invalid_request`          | the body is missing a field or has a wrong one. The message says which       |
| 400    | `invalid_job`              | the job name does not follow the rules                                       |
| 400    | `invalid_delay`            | the delay is not a whole number of seconds from 0 to 43200                   |
| 400    | `invalid_recipients`       | `to` must hold 1 to 20 different user ids                                    |
| 400    | `unknown_recipient`        | one of the people cannot open the app. Nothing was sent                      |
| 400    | `invalid_url`              | only public `https` addresses can be rendered                                |
| 400    | `invalid_image`            | the image is not PNG, JPEG, WebP or GIF in base64, or is over 5 MB           |
| 400    | `invalid_name`             | `ai.toMarkdown` needs a file name with its extension                         |
| 413    | `payload_too_large`        | the payload, text or file is over its limit                                  |
| 422    | `unsupported_file`         | the file could not be converted. Try a PDF, an Office file or an image       |
| 405    | `method_not_allowed`       | use `POST`                                                                   |
| 404    | `not_found`                | the path does not exist on this service                                      |
| 502    | `email_failed`             | the email could not be sent. Try again later                                 |
| 502    | `browser_failed`           | the page could not be rendered                                               |
| 502    | `browser_result_too_large` | the result is over 10 MiB                                                    |
| 502    | `ai_failed`                | the model gave no answer. Try again later                                    |
| 503    | `jobs_unavailable`, `email_unavailable`, `browser_unavailable`, `ai_unavailable` | the service is not set up on this platform. Tell IT |
