# x-contextual Specification

These instructions apply to the current Admin Console.

{% hint style="info" %}
Contextual Workers are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that Workers be enabled for your tenant.
{% endhint %}

Contextual Workers are powered by [Compose](https://compose-spec.io), a developer-focused standard for defining cloud- and platform-agnostic container-based applications. `x-contextual` is a Compose [Extension](https://github.com/compose-spec/compose-spec/blob/main/11-extension.md) that tells Contextual how to run a Compose file as a Worker. It appears once at the top of a Contextual Worker Compose file, and again throughout the file where Contextual-specific configuration is needed. Everything outside of an `x-contextual` section is standard Compose, limited to the subset described by [`v1/compose.schema.json`](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md#compose-schema).

**Format version:** 1 · **Status:** draft

```yaml
x-contextual:
  version: 1
services:
  web:
    image: images.acme.my.contextual.io/web:1.0.0
    depends_on:
      migrate: { condition: service_completed_successfully }
    x-contextual:
      public: true
      http_healthcheck: { path: /ready, port: 8081 }
      features: [native-object-api]
  migrate:
    image: images.acme.my.contextual.io/migrate:1.0.0
```

In the above example, `web` is marked as public, so it receives the Worker's HTTP traffic on the port its image exposes, or on 8080 if the image exposes none. It has a `depends_on` condition for the `migrate` service reporting `service_completed_successfully`, which configures the Worker to run `migrate` as an init container. `web` is never started unless `migrate` has succeeded.

## Conformance

The key words MUST, MUST NOT and MAY are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119).

[`v1/compose.schema.json`](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md#compose-schema) and [`v1/managed-definition.schema.json`](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md#managed-definition-schema) describe each file's structure as JSON Schema. The [rules](#rules) apply as well; JSON Schema can't express them, so the schemas accept some files the rules reject.

## The Document Block

The top-level `x-contextual` object. Three kinds of document carry it: a Worker's own Compose file, a managed definition that Contextual publishes, and a template that an organization publishes for its own Workers. Managed definitions and templates share one format, [`v1/managed-definition.schema.json`](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md#managed-definition-schema). A Worker that uses a managed definition or template can also send a Compose file of its own, which is added to that file before it runs ([how it combines](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md#add-services-with-a-compose-file)). It is a Worker's own Compose file, so it carries the block and follows the same rules, but the whole-file rules apply to the combined file.

| Field | Type | Required | Meaning |
| --- | --- | --- | --- |
| `version` | integer | yes | The format version the file is written in. This spec defines version `1`. |
| `options` | object | no | Managed definitions and templates only: the options a Worker can set. See [Options](#options). |

### Versioning

- A file MUST declare `version`. A reader MUST reject a file without it, or with a version the reader doesn't support.
- The version covers every `x-contextual` field in the file, and the [defaults](#defaults) that apply when a field is absent. Standard Compose keys follow the Compose Specification and aren't versioned.
- Each document declares its own version. A managed definition, a template and a Worker's own Compose file are each read at the version they declare.
- The version is a whole number. It changes only when a file that's valid today would be read differently or rejected; adding an optional field doesn't change it.
- A file that uses a field or feature added within its version needs a reader that knows it. An older reader rejects the file rather than ignoring what it doesn't know.

### Options

`options` maps each option name to `{ "description"?: string, "required"?: boolean, "native_object"?: string }`. An option is a Compose variable the definition uses, such as `${IMAGE}` or `${MAX_REPLICAS:-4}`. Definitions use Compose's braced forms: `${NAME}`, `${NAME:-default}`, `${NAME-default}`, `${NAME:+value}`, `${NAME+value}`, `${NAME:?error}` and `${NAME?error}`.

- A Worker sets option values as strings of at most 4096 characters. The platform substitutes them into the definition using Compose interpolation, exactly as written: a `$` in a value stays a `$`. Where a field expects a number or a boolean, a whole number, `true` or `false` is converted.
- An option name is letters, digits and underscores, and doesn't start with a digit.
- A Worker MUST NOT set an option the definition doesn't declare, and MUST set every option marked `required` to a non-empty value.
- An option used as a service's image MUST be the whole image value in its plain form, as in `image: ${IMAGE}`, with no default, alternative or error. The platform pins it to a digest when the Worker is saved.
- An option with `native_object` names a record of that Native Object type in the Worker's organization. Its value MUST be the record's ID, optionally followed by `#<version>` to pin one of the record's revisions; the record, and the revision if pinned, MUST exist when the Worker is saved. The value reaches services as written.
- A revision number in `#<version>` MUST be a positive whole number with no leading zero. For example, `profile-a#3` pins revision 3.
- A `native_object` type is a Native Object type ID: lowercase letters, digits, dashes and underscores, such as `site` or `orders_api`. A record ID in an option's value is a letter or digit followed by letters, digits, dashes and underscores, at most 128 characters, so a record whose ID uses any other character can't be named.
- A definition MUST use a `native_object` option in its plain form, as in `SITE_ID: ${SITE}`, with no default, alternative or error, so every record a service sees is one the Worker set.
- A value without `#<version>` isn't pinned: it's only the record's ID. The platform doesn't follow the record's revisions or restart the Worker when it changes; a service decides when to read it, so one that reads it as it starts sees changes only after a restart. A service given `<id>#<version>` MUST read that revision.
- The platform also sets `CONTEXTUAL_WORKER_ID`, the Worker's ID, and in managed definitions `CONTEXTUAL_WORKER_IMAGES`, where its own images are. They win over an option of the same name.

## The Service Block

`services.<name>.x-contextual`. A reader MUST reject fields not listed here, except fields whose names start with `x-`, which it ignores.

| Field | Type | Default | Meaning |
| --- | --- | --- | --- |
| `public` | boolean, or a port from 1 to 65535 | see [Defaults](#defaults) | `true` marks the service that receives the Worker's HTTP traffic. A port marks it and chooses the port. `false` or no value: not public. |
| `container_type` | `primary`, `sidecar` or `init` | see [Defaults](#defaults) | How the service runs in each replica. `primary` services start last and run for the life of the replica. `sidecar` services run alongside primaries for the life of the replica. `init` services run to completion before the services that depend on them are allowed to start. |
| `http_healthcheck` | `{ "path", "port" }` | none | An HTTP readiness check on `port` (1024–65535) at `path` (starting with `/`, at most 2048 characters). It replaces the service's Compose `healthcheck` command; that healthcheck's `interval`, `timeout`, `retries`, `start_period` and `start_interval` still apply. |
| `features` | list of `messaging`, `messaging-producer`, `native-object-api`, `logging`, `platform-services`, `keda` | none | Platform features the service uses. See [Features](#features). |
| `scaling` | object | see [Scaling](#scaling) | Backlog scaling for the service that uses `keda`. |

### Features

A feature applies to the service that lists it, and the environment variables below go only to that service.

| Feature | What the Service Gets |
| --- | --- |
| `messaging` | The Worker's own topic and subscription, and the settings to connect to the organization's messaging (`CONTEXTUAL_MESSAGING_*`). The platform creates the topic. |
| `messaging-producer` | The same settings, for sending messages. The platform doesn't create a topic for the Worker. |
| `native-object-api` | The Native Object API's address, the organization's ID, and OAuth client credentials for the API (`CONTEXTUAL_NATIVE_OBJECT_*`, `CONTEXTUAL_ORG_ID`). |
| `logging` | When the organization has its own log topic, the settings to publish the service's logs to it (`WORKER_LOG_TRANSPORT`, `LOGS_MESSAGING_TOPIC`, `CONTEXTUAL_LOGS_*`). Without one, nothing. |
| `platform-services` | The addresses of Contextual's platform services, such as Files, Connections, Logs and Notifications, as a JSON object in `CONTEXTUAL_PLATFORM_SERVICES`. These are addresses only; they grant no access. |
| `keda` | Nothing in its environment: the Worker scales on the backlog of the subscription `messaging` gives this service. See [Scaling](#scaling). |

`messaging` and `messaging-producer` need the organization's messaging to be Pulsar.

### Scaling

A reader MUST reject fields not listed here.

| Field | Type | Default | Meaning |
| --- | --- | --- | --- |
| `minReplicas` | integer, 0–100 | `0` | The fewest replicas. |
| `maxReplicas` | integer, 1–100 | `1` | The most replicas; at least `minReplicas`. |
| `pollingInterval` | integer, at least 5 | `20` | Seconds between backlog checks. |
| `cooldownPeriod` | number, at least 0 | `5` | Seconds to wait after the backlog was last active before scaling to zero. |
| `lagThreshold` | number, at least 2 | `100` | The backlog each replica should handle. |

## Defaults

When a field is absent, the platform reads the file this way.

- **Single image.** A Worker given one image instead of a Compose file is read as a file with one service, `worker`, that runs the image.
- **Public service.** The public service is the one service whose `public` is `true` or a port; a single-image Worker's service is always public. More than one is an error; none means the Worker has no public service. A scheduled Worker never has a public service.
- **Public port.** The port `public` gives, otherwise the `target` of the public service's first `ports` entry, otherwise the one port the service's image exposes, otherwise 8080. An image that exposes several ports needs `public` or `ports` to choose one. The platform sets the public service's `PORT` to this port, replacing any `PORT` in its `environment`.
- **Container type.** The public service, or the only service, is `primary`. A service another service waits for with `condition: service_completed_successfully` is `init`. Every other service is a `sidecar`.

## Rules

A **packaged application** is an application image produced by a runtime adapter's package command. A **managed host** is the service that runs beside that application, holds the platform credentials, and makes platform calls on its behalf.

- A reader MUST reject unknown fields in any Compose object, `x-contextual` included, unless their names start with `x-`.
- The public service MUST NOT publish several `ports` unless `public` chooses one, and can't be an `init` service.
- At least one service MUST be `primary`.
- Nothing can depend on a `primary` service. A service that waits for an `init` service MUST use `condition: service_completed_successfully`, and nothing can wait for a `sidecar` to complete. `condition: service_healthy` needs a check on the dependency that isn't disabled: a Compose `healthcheck`, the image's `HEALTHCHECK`, or an `http_healthcheck`. `depends_on` can't form a cycle.
- No two services can declare the same port in `ports`, `expose`, `public` or `http_healthcheck`; they share one network.
- `scaling` requires the `keda` feature, and `keda` requires `messaging` on the same service. Only one service can use `keda`, it can't be an `init` service, and a Worker with a public service MUST keep `minReplicas` at 1 or more.
- A Worker whose file uses `keda` can't have a schedule, and its own replica settings stay at 1; the service's `scaling` sets its replicas.
- Before a Worker with a public service runs, the platform also checks that its port is from 1024 to 65535 and that it has a readiness check: an `http_healthcheck`, a Compose `healthcheck`, or the image's `HEALTHCHECK`.
- A Worker using `managed-event-worker`, `managed-http-worker`, or `managed-scheduled-worker` MUST set `IMAGE` to an application image produced by the runtime adapter's [package command](https://docs.contextual.io/build/contextual-workers/managed-workers/get-started.md#3-package-the-release). Its `CONNECTION_BINDINGS` option MUST bind exactly the connection aliases declared in that application's `worker.json`. See [The Release Manifest](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md#the-release-manifest).
- Each managed host MUST be associated with exactly one packaged application. A packaged application that declares connection aliases MUST have a managed host that supplies their bindings. The runtime-adapter templates provide this host and its association with the application.

### Standard Compose Keys

The platform limits standard Compose keys too, beyond the subset in [`v1/compose.schema.json`](https://docs.contextual.io/build/contextual-workers/x-contextual-specification/json-schemas.md#compose-schema).

- A file has from 1 to 50 services.
- Each image has a tag or a digest, is built for linux/amd64, and is one of the organization's own Worker images (`images.acme.my.contextual.io/…` in the example above) or one of Contextual's platform images (`images.contextual.io/worker/platform/…`). The platform pins tags to digests when the Worker is saved.
- A Worker's own file can't use variables such as `$NAME` or `${NAME}`, in its services or in config content; write `$$` for a literal `$`. Managed definitions and templates use variables for their options, which are substituted first.
- Environment names starting with `CONTEXTUAL_` are reserved.
- Every service receives the Worker's environment variables, except those a mounted secret names. A service's own `environment` reaches only that service, and wins over a Worker variable of the same name.
- The platform upper-cases the names of the Worker's environment variables. A name is letters, digits and underscores and doesn't start with a digit, and two names that differ only in case are an error.
- Only the default network exists. The top-level `networks` and a service's `networks` can name only `default`.
- `command`, `entrypoint` and a healthcheck's `test` take Compose's list form. A `test` starts with `CMD`, `CMD-SHELL` or `NONE`.
- A healthcheck's `interval`, `timeout`, `start_period` and `start_interval` are positive durations of at most one hour, and its `retries` is from 1 to 120.
- Each volume a service mounts MUST be declared under the top-level `volumes`, and each config or secret under the top-level `configs` or `secrets`.
- No volume, config or secret can be mounted at `/` or `/tmp`, or at `/proc`, `/sys`, `/dev` or a path under them, and no two mounts in one service can share a path. A config or secret's target is a file path, so it can't end in `/`.
- A service's root filesystem is read-only. Its `/tmp` and the named volumes it mounts are scratch space, empty in each new replica, and all of a replica's scratch together is 1 GiB, split evenly across each service's `/tmp` and each named volume. Each replica has 2 GiB of ephemeral storage in all, scratch and container logs included, split evenly across its `primary` and `sidecar` services; an `init` service gets what the `sidecar` services started before it leave.
- A top-level config holds the file's text in `content`. `file` and `environment` sources aren't supported, and all configs together are at most 64 KiB. A service mounts a config at `/<name>` by default; a relative `target` is under `/`, and the default mode is `0444`.
- A top-level secret names one of the Worker's environment variables, in upper case, in `environment`; the variable's value is the file. `file` sources aren't supported. A service mounts a secret at `/run/secrets/<name>` by default; a relative `target` is under `/run/secrets/`, and the default mode is `0440`.
- The Worker MUST have each variable a mounted secret names. That variable reaches services only as the file, and only the services that mount the secret.

### Runtime

How the platform runs each replica, whatever the file or its images declare.

- Every container runs as user and group `10001`, not the image's `USER`, with all Linux capabilities dropped.
- A service reaches the others in its replica by service name.
- On shutdown, each container gets `SIGTERM` and at least 30 seconds to exit.
- The public service's requests are limited to a 1 MB body and 30 seconds by default. The Worker environment variables `BODY_SIZE_LIMIT` (such as `10mb`) and `HTTP_TIMEOUT_MS` change them.
- A scheduled Worker starts one run per tick of its UTC cron schedule, and every service gets the schedule in `CONTEXTUAL_SCHEDULE`. A run is stopped after 30 minutes, a failed run isn't retried, and a tick is skipped while the previous run is still going.
