# Functions and public HTTP endpoints

The backend is a set of Cloud Functions (Node.js, Firebase Functions v2)
deployed from `firebase/functions/`. Every function exported from
`firebase/functions/src/index.ts` is deployed with the environment; an
HTTP function gets a public HTTPS URL, which is how you serve webhooks and
other public endpoints.

## Add an HTTP endpoint

```ts
// firebase/functions/src/CloudFunctions/Hooks.ts
import express from "express"
import { onRequest } from "firebase-functions/v2/https"

const app = express()

// Webhook senders sign the raw body: keep it raw and verify before acting.
app.post("/github", express.raw({ type: "*/*", limit: "1mb" }), async (request, response) => {
    const secret = process.env.GITHUB_WEBHOOK_SECRET // set with: spaceboy secrets set GITHUB_WEBHOOK_SECRET
    // verify request.header("x-hub-signature-256") against secret here
    response.json({ received: true })
})

app.get("/health", (_request, response) => {
    response.json({ ok: true })
})

export const hooks__request__api = onRequest({ cors: true }, app)
```

```ts
// firebase/functions/src/index.ts
export { hooks__request__api } from "./CloudFunctions/Hooks.js"
```

- Names follow `<domain>__request__<name>` for HTTP and
  `<domain>__message__<event>` for Pub/Sub handlers, and must be at most 30
  characters: deploys prefix each name, and Google caps the total at 62.
- HTTP functions are public: anyone with the URL can call them. Check
  signatures or tokens yourself. The GraphQL API
  (`graphql__request__api`) is the one that requires a signed-in user.
- The starter's own HTTP functions are examples to copy:
  `payments__request__api` (Stripe webhook with signature checking),
  `storage__request__api`, `jobs__request__api`, `auth__request__api`.

## Find an endpoint's URL

A deployed function's URL is
`https://<region>-<gcp project>.cloudfunctions.net/<prefix>__<export name>`.
Every succeeded `spaceboy deploy` or `spaceboy push` prints the base
(`Functions: .../<prefix>__<export name>`); under `--json` it is
`endpoints.functionsBaseUrl`:

```bash
BASE=$(spaceboy deploy --target production --json | jq -r .endpoints.functionsBaseUrl)
echo "${BASE}hooks__request__api/github"
```

For a stable hostname, serve the function from your own domain:

```bash
spaceboy domains add hooks.example.com --project prj_... --target production --function hooks__request__api
spaceboy domains check hooks.example.com --wait
```

`domains add` prints the DNS records to create; custom domains come with a
paid project.

## Per-page link previews (document routes)

A single-page app's links all preview with the site's one generic card:
chat apps and social sites read the page's `<meta>` tags without running
its JavaScript. To give `/v/<id>` its own title, description and image,
let one of your HTTP functions answer page requests for that path:

```json
// repobot.deploy.json
{ "documentRoutes": [{ "path": "/v/*", "function": "share__request__api" }] }
```

```ts
// firebase/functions/src/CloudFunctions/Share.ts
import express from "express"
import { onRequest } from "firebase-functions/v2/https"

const escape = (text: string) =>
    text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)

const app = express()
app.get("/v/:id", async (request, response) => {
    const video = await findPublicVideo(request.params.id) // your own lookup
    if (!video) {
        response.status(404).end() // the site's normal page answers instead
        return
    }
    // The app's built shell, with this page's tags in <head>.
    const shell = await fetch(`${process.env.APP_BASE_URL}/index.html`).then((r) => r.text())
    const tags = `<title>${escape(video.title)}</title>
<meta property="og:title" content="${escape(video.title)}">
<meta property="og:description" content="${escape(video.summary)}">
<meta property="og:image" content="${escape(video.posterUrl)}">
<meta name="twitter:card" content="summary_large_image">`
    response.type("html").send(shell.replace(/<title>[^<]*<\/title>/, tags))
})

export const share__request__api = onRequest(app)
```

How it behaves:

- `path` is literal segments ending in `*` (exactly one more segment) or
  `**` (one or more): `/v/*`, `/gift/**`, `/about`. It cannot cover the
  whole site (`/*`), start with `/assets` or `/auth`, or name a file. At
  most 20 routes. A declaration that breaks a rule fails the deploy with
  the reason.
- One host only: `hostDocumentRoutes` takes the same entries plus
  `hosts` (exact hostnames, at most 10), and only it may take the home
  page `/`. Use it when one site serves several domains and one domain's
  home needs its own card; every other host keeps the static page with no
  function call:
  `{ "hostDocumentRoutes": [{ "hosts": ["example.com", "www.example.com"], "path": "/", "function": "share__request__api" }] }`
- Only page requests use the route: `GET` or `HEAD` on a path whose last
  segment has no file extension. Images, scripts, `/v/abc.png` and every
  other method are served from the site as before.
- The function gets the same path and query (`/v/abc?x=1`), the visitor's
  `User-Agent`, `Accept` and `Accept-Language`, and `X-Forwarded-Host`.
  It never gets cookies or an `Authorization` header, and a `Set-Cookie`
  it sends is dropped: answer the public page only, the same for everyone.
- A `2xx` or `3xx` answer is served. A `4xx` or `5xx`, an error, an
  answer not complete within 10 seconds, or a body over 1 MiB serves the
  site's normal page instead, so a broken function never breaks the link.
  A served `2xx` page counts once in the site's analytics, as its path.
- Caching: the answer is always revalidated, like the app's HTML
  (`Cache-Control: public, max-age=0, must-revalidate`), or `no-store` if
  your function says `no-store`. Your site's declared security headers
  (`firebase.json` `hosting.headers`) apply as on its other pages.
- The function must be one of the app's own HTTP exports
  (`<domain>__request__<name>`, not `auth__request__api` or
  `jobs__request__api`); it runs in the same environment as the site.
- Escape everything you put into the tags (titles come from your users).
- Served on the platform's sites (`*.sites.spaceboy.ai` and custom domains
  linked to the site); environments on the older per-site hosting ignore
  the declaration.

## Background work

- Scheduled jobs: the `JOBS` capability gives the starter's jobs kernel a
  platform scheduler that calls it every 5 minutes (starter doc
  `docs/jobs.md`).
- Pub/Sub: functions named `<domain>__message__<event>` subscribe to topics;
  `repobot.deploy.json` `pubsub` configures retries and dead letters (starter
  doc `docs/pubsub-events.md`).

## Cold starts and keep-warm

Functions and the GraphQL API scale to zero when idle. The first request
after a quiet spell (about 15 minutes or more) starts an instance: measured
at 5 to 11 seconds for the starter's GraphQL API, and a few seconds before a
streaming endpoint sends its first byte. Later requests take well under a
second. Static pages are not affected.

On a published project's production environment an organization owner or
admin can keep up to two functions at one running instance (always-on):

```bash
spaceboy environments keep-warm production                    # the setting and the price
spaceboy environments keep-warm production --functions graphql__request__api --confirm-charge <amount quoted>
spaceboy environments keep-warm production --off              # back to scale-to-zero, rest of the period credited
```

The change is applied to the deployed functions at once; no deploy is
needed. Billing starts only once the function is warm: if the platform
cannot update it, nothing is charged; if the charge fails, the function goes
back to zero. `--off` returns it to zero first, then credits.

- Price: always-on is billed per kept-warm function a month (1 vCPU), on
  the organization's subscription next to its published projects. The
  command states the amount (`CHARGE_CONFIRMATION_REQUIRED`, exit 4,
  `amountUsd` and the full `nextCommand`) and charges nothing until
  `--confirm-charge` equals it; then the card on file is charged for the
  rest of the billing period and a receipt line is printed. `spaceboy
  billing show` lists it. The kept-warm instance does not use the
  project's included backend time (it is paid by this line); when traffic
  needs more instances than the warm one, their time counts as usual.
  Turning it off counts every instance again from that moment. A minimum
  instance count set any other way (not through this command) counts in
  full.
- No card on the subscription: the command prints the one card-portal link
  and waits (heartbeat every 30 s); once a person saves a card it continues
  by itself. `--no-wait` exits 4 (`PAYMENT_METHOD_REQUIRED`) instead.
- Refusals: `NOT_PUBLISHED` (publish first), `ALWAYS_ON_LIMIT` (more than
  two functions), `BILLING_UNAVAILABLE` (always-on cannot be priced right
  now; nothing charged), `PAYMENT_PAST_DUE`, `CHARGE_APPROVAL_REQUIRED`
  (over the agent charge limit).
- Unpublishing the project, or a payment pause, turns it off. If the add-on
  is ever unpaid while functions are kept warm, the owners are emailed the
  command that pays for them (with its amount), and keep-warm is turned off
  for those functions a day later if it is still unpaid.
- The amount stated is computed from what the subscription pays for now, so
  it includes any kept-warm function not yet paid for; what is charged is
  always that amount (otherwise the command is refused with the new amount).
- Off for every project until you turn it on. Development environments
  always scale to zero (refused there with `FAILED_PRECONDITION`).
- Use the exported function name (`graphql__request__api` is the API). A
  name the production deploy does not have is refused (`INVALID_ARGUMENT`)
  with the list of its functions, before anything is charged. `--json` returns
  `functions`, `billing`, `monthlyPriceUsd`, `monthlyTotalUsd`,
  `chargedMonthlyUsd`, `receipt`, `note` and `nextCommand`.
- Without keep-warm: make the first screen useful before the API answers
  (static content, a loading state), and retry a streaming connection that
  has not sent a byte within a few seconds.

## Reading configuration in a function

Platform values (`DATABASE_URL`, `AUTH_*`, `APP_BASE_URL`, ...) and your
custom secrets are plain environment variables: `process.env.NAME`. See
[Secrets and settings](https://spaceboy.ai/docs/agents/secrets-and-settings.md).

## Not available

- No CLI command that lists an environment's deployed functions by name.
- Function runtime options other than what the code declares (memory,
  regions) are not configurable from the CLI.
