Defining Operations
Operations register HTTP endpoints for custom logic. When triggered — by a user action, a lifecycle hook, a schedule, or an API call — the platform sends a signed payload to your endpoint and records the result.
Operation Interface
interface ApplyConfigOperationInput {
key: string; // Unique identifier (e.g., 'sync-data')
name: string; // Display name
description?: string; // What this operation does
icon?: string; // Console icon key
category?: string; // Grouping category
endpoint?: string; // HTTP endpoint URL (relative, resolved on push)
isActive?: boolean; // Whether the operation is enabled (default: true)
timeoutMs?: number; // Per-operation timeout in milliseconds
inputSchema?: Record<string, unknown>; // JSON Schema for input
outputSchema?: Record<string, unknown>; // JSON Schema for the operation result
allowedPermissions?: string[]; // Permissions the caller must ALL hold, e.g. 'records:write.all'
retryPolicy?: Record<string, unknown>; // HTTP-dispatch retry policy
precondition?: Precondition; // Gate before execution
quotas?: { rules: QuotaRule[] }; // Usage quotas
/** 'async' lets the operation accept async runs; 'sync' (the default) does not. */
mode?: 'sync' | 'async';
/** TTL the platform waits for an async callback before timing out (clamped 5m–7d, default 24h). */
callbackTtlSeconds?: number;
/** Retry policy applied specifically when the async callback times out. */
callbackTimeoutRetryPolicy?: { maxRetries?: number };
/** What the operation may do when it calls back, as grants (e.g. 'records:read:<model>'). The dispatch token carries them. */
grants?: string[];
/** How the operation surfaces: 'mutation' (default), 'query', or 'field'. See Resolver Operations. */
kind?: 'mutation' | 'query' | 'field';
/** Model the resolver field attaches to (kind 'field' only). */
attachedToModel?: string;
/** Fields of the parent record sent to the resolver as {{parent.X}} (kind 'field' only). */
parentFields?: string[];
/** Result cache-control for resolver operations (kind 'query'/'field'). */
cacheControl?: { scope: 'PUBLIC' | 'PRIVATE' | 'NO_CACHE'; maxAge?: number };
/** Maps {{secret.NAME}} placeholders to project-owned secrets (templated operations). */
secretBindings?: Array<{ name: string; secretRef: string }>;
/** The request Foir makes to a third-party host: resolver operations, and a mutation called SYNC. */
requestTemplate?: {
method?: string;
pathTemplate?: string;
query?: Record<string, string>;
headers?: Record<string, string>;
bodyTemplate?: string;
batchCapable?: boolean;
};
/** jq-style transform of the upstream response (templated operations). */
responseTransform?: string;
}The endpoint field specifies the relative URL path for the operation. When you run foir push, the platform resolves relative endpoints against your deployed service URL — see operationBaseUrl on the top-level config.
Basic Example
import { defineConfig, defineOperation } from '@foir/cli/configs';
export default defineConfig({
key: 'my-app',
name: 'My App',
operations: [
defineOperation({
key: 'sync-to-cdn',
name: 'Sync to CDN',
description: 'Pushes published content to the CDN edge network',
endpoint: '/sync/cdn',
}),
],
});Endpoint URLs
Operation endpoints are relative paths that are resolved against your service’s base URL at push time:
operations: [
{
key: 'generate-pdf',
name: 'Generate PDF',
endpoint: '/generate/pdf',
},
{
key: 'send-notification',
name: 'Send Notification',
endpoint: '/notify',
},
]When the platform triggers an operation, it POSTs a signed payload to the resolved URL. See Operations for details on the request/response contract.
Endpoints must be public
Foir only calls public URLs. The resolved endpoint is checked when you save the operation, and again every time it runs. An address that is not publicly routable is refused, including loopback, private ranges such as 10.0.0.0/8, link-local addresses, cloud metadata addresses, and any .internal hostname.
Public does not mean unprotected. What secures your endpoint is the signed token every dispatch carries in X-Foir-Token, which your handler verifies before doing anything else, so a route that skips that check is open to anyone who finds its URL. See Authentication and Grants for the contract and Building Operations for the one-line SDK path.
The public-address rule is a separate matter from that token check: registering an endpoint directs the platform to make a request on your behalf, and restricting those requests to publicly routable addresses is what keeps that from being turned into a way to reach addresses it shouldn’t.
Saving an operation whose endpoint resolves to one of those fails with a validation error. An endpoint that only starts resolving to one later is refused at the moment it would be called, and the execution is marked failed rather than retried, because no retry can turn a private address into a public one.
In practice this means operationBaseUrl has to point at a deployed service the internet can reach.
While you are developing, you do not need one. foir operations dev holds this project’s dispatches open and forwards them to a server on your own machine:
foir operations dev --port 3000Nothing is exposed to the internet, and the rule above is not being bent: no address is dialled at all. Foir hands the dispatch to the session, and the session POSTs it to your localhost. Your handler receives the same signed envelope at the same path it was registered at, so what runs locally is what runs in production.
Take one operation at a time with --operation <key>, repeated as needed. The operations you do not name keep dispatching to their registered endpoints, so working on one does not take a shared project offline for everybody else.
One session per project. Starting a second replaces the first, which is told it was replaced. If no session is held, a dispatch to a project that expected one fails immediately rather than retrying, so a closed laptop does not fill a dead letter queue overnight.
If you need Foir’s own HTTP dispatch to reach your machine instead, --tunnel is the escape hatch:
foir operations dev --port 3000 --tunnel cloudflared
foir operations dev --port 3000 --tunnel none --url https://your-own-tunnel.example.comThat holds a session naming the tunnel. While it holds, Foir dials the tunnel in place of each operation’s registered endpoint, at that endpoint’s path, under the same address guard and retry classification as any dispatch, which a held session deliberately skips. Your operations are not changed, so there is nothing to put back: when the command exits, or is killed, the session ends and Foir dials the registered endpoints again. An operation whose request is a template is never sent to the tunnel, so its secrets go only where its definition says. It needs cloudflared or ngrok on your PATH unless you bring your own URL.
Prefer the default. The tunnel is a public address for your machine while it is up.
The same rule applies everywhere Foir calls a URL you configure, so it also covers app manifest and middleware URLs, web push endpoints, and the discovery URL of a user identity provider.
Categorizing Operations
Use the category field to group related operations:
operations: [
{
key: 'generate-css',
name: 'Generate Theme CSS',
description: 'Generates Tailwind v4 CSS from design tokens',
endpoint: '/generate-css',
category: 'design-system',
},
{
key: 'generate-tokens',
name: 'Generate Token File',
description: 'Exports design tokens as JSON',
endpoint: '/generate-tokens',
category: 'design-system',
},
]Execution Modes
Declaring mode: 'async' makes an operation accept async runs. A call through the API or CLI runs sync unless it asks for ASYNC; hook and schedule runs dispatch async when the operation declares it.
| Mode | Behaviour | Use For |
|---|---|---|
sync | Foir holds the connection until the endpoint responds. Result returned to the caller inline. | Sub-minute deterministic transforms, validation, lookups. |
async | Foir dispatches and gets 202 Accepted back. Endpoint queues the work, then calls back to the public API to report progress + terminal state. | Long-running work, progress reporting, anything that depends on a slow upstream you don’t want blocking the dispatch. |
defineOperation({
key: 'full-export',
name: 'Full Data Export',
endpoint: '/exports/full',
mode: 'async',
callbackTtlSeconds: 3600, // 1 hour to call back
callbackTimeoutRetryPolicy: { maxRetries: 2 },
})The callbackTtlSeconds field controls how long the platform waits for a callback before marking the execution timed_out. If unset, the platform uses 24 hours. Clamped to [5m, 7d].
callbackTimeoutRetryPolicy is distinct from retryPolicy: retryPolicy governs HTTP dispatch failures (network errors, 5xx); callbackTimeoutRetryPolicy governs callback timeouts. Splitting them lets you retry dispatch failures aggressively while being conservative about callback timeouts — re-running an hour-long job that timed out tends to burn another hour.
See Operations for the full async-callback handshake.
Retrying safely
A call whose response never arrives leaves the caller unable to tell whether the work happened. Both guesses are wrong some of the time: retry and the operation may run twice, do not retry and it may not have run at all. The ambiguity is on the wire, so no amount of care on your side removes it.
A sync call is bounded by the operation’s own timeoutMs, and a caller that
gives up sooner, or loses the connection, still does not know. Send an
idempotencyKey and a retry of the same action adopts the execution the first
attempt started instead of running the operation again:
mutation {
executeSendNotification(
input: { orderId: "ord_4471" }
idempotencyKey: "notify-ord_4471"
) {
execution { id status }
replayed
supersededExecutionId
}
}const payload = await foir.ns.operations['execute.send-notification']({
input: { orderId: 'ord_4471' },
idempotencyKey: 'notify-ord_4471',
});What the retry gets depends on the execution the key last started:
| That execution | The retry |
|---|---|
| still running | adopts it and returns at once with its current state: replayed is true, and a sync call does not wait for it to finish |
| completed | adopts it and returns its result: replayed is true, and the operation does not run again |
| failed, timed out or cancelled | starts a new execution under the same key, and names the failed one in supersededExecutionId |
A failed attempt does not poison the key. A failure is the action not having happened, so the key does not replay it: the retry runs the operation again, and the retry after that adopts the new execution. A deploy that fixes a broken endpoint is reached by the next retry of the same key.
The key has to be stable across the retries of one logical action and different for a genuinely new one, which is why nothing generates it for you: a fresh key per call dedupes nothing. Use something the action already has, such as an order reference or a cart id, rather than a random value you would have to remember.
A key is scoped to the project, the organization and the user the call is made for, so the same key sent for two users names two actions. It is at most 255 printable characters and cannot collide with the ones Foir mints internally for hook redeliveries. A key that cannot be stored is refused rather than trimmed, because a key that arrived altered would deduplicate against something you never sent.
Two keys, two layers
An operation’s idempotencyKey is not the idempotencyKey a record write
takes, and the two do not share keys or rules:
- A record write’s key (
create<Model>,update<Model>and the other record mutations) is scoped to the credential that sent it and committed with the write: the retry answers with the first write’s result, and a write that failed committed nothing, so its key holds nothing. See Update a Record. - An operation’s key is scoped to the project, organization and user the call is made for, and recorded on the execution: it adopts an execution in flight or completed, and a failed one is superseded, as above.
A record write takes an idempotencyKey too (create<Model>, update<Model>,
rename<Model> and updateMany<Model>), and a retry under it returns the first
attempt’s result: the same record with the same data, and nothing written again.
The answer says which it is. replayed is false on a write the call made and
true on a replay, and it is worth checking before acting on the result, because
a replayed record reads exactly like a fresh one: a stock count read back from a
replayed take is the count the first take left. The same key sent with a
different write is refused with INVALID_ARGUMENT.
const { record, replayed } = await foir.pool.update({
where: { naturalKey: { eq: 'dough' } },
data: { sold: { increment: 1 } },
idempotencyKey: `take-${orderId}`,
});
if (replayed) {
// This order's take was already applied by an earlier attempt.
}Resolver Operations
By default an operation is a mutation (kind: 'mutation') — an executeXxx root mutation dispatched through the worker queue. Two other kinds turn an operation into a GraphQL resolver that calls an upstream endpoint and shapes the result inline:
kind | Surfaces as | Resolved |
|---|---|---|
mutation (default) | executeXxx root mutation | Called directly when SYNC, queued when ASYNC |
query | Root Query field | Synchronously, in-process |
field | Resolver field on attachedToModel | Batched per request |
Resolver operations (query / field) use requestTemplate to shape the outbound HTTP request and responseTransform to reshape the upstream response:
defineOperation({
key: 'weather',
name: 'Weather Lookup',
kind: 'field',
attachedToModel: 'city', // attach the resolver field to this model (field only)
parentFields: ['name'], // the city's fields sent as {{parent.X}} (field only)
cacheControl: { scope: 'PUBLIC', maxAge: 300 },
secretBindings: [
{ name: 'WEATHER_KEY', secretRef: 'weather_api_key' },
],
requestTemplate: {
method: 'GET',
pathTemplate: '/v1/forecast?city={{parent.name}}',
headers: { Authorization: 'Bearer {{secret.WEATHER_KEY}}' },
batchCapable: true, // one upstream request for the deduped input set
},
responseTransform: '.current.temp_c', // jq-style transform of the upstream body
grants: ['records:read:city'],
})| Field | Applies to | Description |
|---|---|---|
kind | all | 'mutation' (default), 'query', or 'field'. |
attachedToModel | field | Model key the resolver field attaches to. |
parentFields | field | Fields of the attachedToModel record sent to the resolver, read in the template as {{parent.X}}. Only the fields named here are sent. |
cacheControl | query / field | { scope: 'PUBLIC' | 'PRIVATE' | 'NO_CACHE', maxAge? } — result caching. |
secretBindings | templated | Maps {{secret.NAME}} placeholders to project-owned secrets. |
requestTemplate | query / field, and a SYNC mutation | Shapes the outbound request. Variables: {{input.X}}, {{parent.X}}, {{secret.NAME}}, {{context.X}}. |
responseTransform | templated | jq-style transform applied to the upstream response. |
grants | all | What the operation may do when its endpoint calls back, as grants in the permission catalogue’s names (e.g. records:read:<model>). The dispatch token carries them. See Operation permissions. |
A page inside the Foir console runs a templated operation on its own token, so it can use a secret it never holds. See Your app’s own console, inside Foir.
Pass-through Writes
A mutation with a requestTemplate is a pass-through write. Foir calls the third-party host itself, through the template, while the caller waits, and the host’s answer is the result. Nothing is stored except the execution record, so there is nothing to reconcile: the write succeeds or fails at the host, there and then. There is no service of yours to deploy, and the host’s credential stays in Foir’s vault through secretBindings.
defineOperation({
key: 'cancelPreorder',
name: 'Cancel Preorder',
endpoint: 'https://example-shop.myshopify.com/admin/api/2025-07/graphql.json',
secretBindings: [
{ name: 'SHOPIFY_TOKEN', secretRef: 'shopify_admin_token' },
],
requestTemplate: {
method: 'POST',
headers: { 'X-Shopify-Access-Token': '{{secret.SHOPIFY_TOKEN}}' },
bodyTemplate: '{"query": "mutation Cancel($id: ID!) { orderCancel(orderId: $id, reason: USER, refund: true, restock: true) { userErrors { message } } }", "variables": {"id": "{{input.orderId}}"}}',
},
responseTransform: '{ errors: [.data.orderCancel.userErrors[].message] }',
})Call it SYNC. A templated operation is never queued: an ASYNC call, a hook or a schedule that reaches one is refused with TEMPLATE_NOT_QUEUED, because the queue retries, and a retried write against someone else’s system is a second write.
What the host is sent
Only what the template writes. There is no envelope and no X-Foir-Token or X-Foir-Context: a template calls a host that is not your service, which has no use for a Foir credential. A service of your own that verifies Foir’s token is called without a template. A host that needs proof the call came from Foir is sent a bound secret in a header the template writes.
How values are escaped
Each value is escaped for where it stands, so nothing a caller sends can change the request’s shape:
| Where the token stands | Written as |
|---|---|
In pathTemplate, before any ? | One path segment. A value that is empty, . or .. is refused. |
In pathTemplate after ?, or in query | A query value. |
In a JSON bodyTemplate, inside a string | That string’s content, escaped. |
In a JSON bodyTemplate, as a value | The value’s JSON, so a string arrives quoted and a missing value as null. |
In a form-encoded body (Content-Type: application/x-www-form-urlencoded) | A form value. |
| In a header | As written. A value with a line break is refused. |
A body of any other type may not carry a value. JSON escaping cannot reach a language nested inside a JSON string, so a GraphQL body passes values as variables, as in the example above, never inline in the query.
Retrying a pass-through write
Send an idempotency key and write it where the host reads one. {{context.idempotencyKey}} is the key as the caller sent it:
requestTemplate: {
method: 'POST',
pathTemplate: '/v1/refunds',
headers: {
Authorization: 'Bearer {{secret.STRIPE_KEY}}',
'Content-Type': 'application/x-www-form-urlencoded',
'Idempotency-Key': '{{context.idempotencyKey}}',
},
bodyTemplate: 'payment_intent={{input.paymentIntent}}',
},Foir retries a templated write only when the call carries a key and the template forwards it, because only then can the host tell a retry from a second write. Otherwise the host’s first answer is the call’s answer, and a caller that retries sends its key.
Active/Inactive Toggle
Disable an operation without removing it by setting isActive to false:
{
key: 'legacy-sync',
name: 'Legacy Sync',
description: 'Deprecated sync endpoint',
endpoint: '/sync/legacy',
isActive: false,
}Inactive operations cannot be triggered by hooks, schedules, or API calls. Set isActive back to true (or remove the field) to re-enable.
Real-World Example
From the Cloudflare KV Redirect extension — three operations for syncing, checking status, and tearing down:
operations: [
{
key: 'redirect-sync',
name: 'Sync Redirects to Edge',
description: 'Syncs redirect records to Cloudflare KV',
endpoint: '/sync/all',
},
{
key: 'redirect-sync-status',
name: 'Get Sync Status',
description: 'Returns current sync metadata for display in the editor',
endpoint: '/sync/status',
},
{
key: 'redirect-undeploy',
name: 'Undeploy Edge Redirects',
description: 'Tear down Cloudflare Worker and KV namespace',
endpoint: '/deploy/destroy',
},
]Preconditions
A precondition gates whether an operation can execute at all. It evaluates before execution and returns a FAILED_PRECONDITION error if the check fails. Use preconditions for state-based gating: “is this user allowed to do this?”
There are two precondition shapes:
Segment Precondition
Blocks execution unless the user belongs to a named segment:
defineOperation({
key: 'ai-suggest',
name: 'AI Suggest',
endpoint: '/suggest',
precondition: {
segmentKey: 'pro_users',
message: 'AI suggestions are available on the Pro plan. Upgrade to unlock.',
},
})If the user is not a member of the pro_users segment, the platform returns the message as the error. If message is omitted, a generic “operation precondition not met” error is returned.
Expression Precondition
Blocks execution unless a rule expression evaluates to true against the operation input and context:
defineOperation({
key: 'publish-post',
name: 'Publish Post',
endpoint: '/publish',
precondition: {
type: 'condition',
left: { type: 'field', path: 'status' },
operator: 'equals',
right: { type: 'literal', value: 'draft', valueType: 'string' },
},
})Expression preconditions support the same operators and grouping as segment rules (AND/OR groups, field/context references, etc.). A literal’s value is read as JSON unless valueType names its type, so a string is written with valueType: 'string' (or as value: '"draft"'). Without either, 'draft' reads as nothing and the precondition refuses every call.
Quotas
A quota meters how many times an operation can be executed within a time window. It evaluates after preconditions pass and returns a RATE_LIMITED error when the limit is reached. Use quotas for usage-based metering: “how many times can this user do this?”
defineOperation({
key: 'ai-suggest',
name: 'AI Suggest',
endpoint: '/suggest',
quotas: {
rules: [
{ points: 50, duration: 86400, scope: 'user' },
],
},
})Quota Rule Fields
| Field | Description |
|---|---|
points | Max executions in the window. 0 means unlimited. |
duration | Window length in seconds (86400 = 1 day). |
scope | Whose counter a run is charged to: "user", the person the run is for; "actor", whoever started it; or "tenant", the workspace. |
segmentKey | Target a specific segment. Omit for a fallback rule. |
message | Custom error when quota is exhausted (e.g., an upgrade CTA). |
condition | Optional rule expression to conditionally apply the rule. |
expiresAt | ISO 8601 date after which the rule is ignored. |
failClosed | Refuse the call when this rule’s meter cannot be read, instead of allowing it. Defaults to false. |
When the meter cannot be read
A quota is counted in a store separate from the request. When that store cannot answer, the check has to decide without a count, and by default it allows — an outage of the meter does not take your API down with it.
That default is right for a rate limit and wrong for a paywall: for the duration of the outage, a user who is out of quota gets the action anyway. Set failClosed: true on a rule where serving an unmetered request costs more than refusing a legitimate one:
quotas: {
rules: [
{ segmentKey: 'pro', points: 0, duration: 86400, scope: 'user' },
{
points: 10,
duration: 86400,
scope: 'user',
failClosed: true,
message: "You've used your 10 free AI suggestions today. Upgrade to Pro for unlimited.",
},
],
}A rule that refuses this way reports an internal error rather than RATE_LIMITED, because the caller has not exceeded anything — the meter simply could not say.
Note:
failClosedcovers the rule’s own counter. It does not cover a failure to load the rules at all: with no rules loaded there is no rule whosefailClosedcould be consulted, so that case still allows. Rules default tofailClosed: false, so a rule written before this field existed behaves exactly as it always has.
Rule Ordering
Rules are evaluated top-to-bottom, first match wins. A rule matches if:
- It has not expired
- The user belongs to the rule’s segment (or the rule has no
segmentKey) - The rule’s condition evaluates to true (or the rule has no
condition)
Once a rule matches, it is enforced and no further rules are checked. If no rule matches, execution is allowed.
Tiered Pattern: Pro Unlimited / Free Metered
The most common pattern is a segment-gated unlimited rule followed by a metered fallback. Pro users match the first rule and skip metering entirely; everyone else falls through to the metered rule:
defineOperation({
key: 'ai-suggest',
name: 'AI Suggest',
endpoint: '/suggest',
quotas: {
rules: [
// Rule 0: Pro users — unlimited
{ segmentKey: 'pro', points: 0, duration: 86400, scope: 'user' },
// Rule 1: Everyone else — 10/day with upgrade CTA
{
points: 10,
duration: 86400,
scope: 'user',
message: "You've used your 10 free AI suggestions today. Upgrade to Pro for unlimited.",
},
],
},
})Precondition vs. Quota
| Precondition | Quota | |
|---|---|---|
| Purpose | State-based gating | Usage-based metering |
| Question | “Is this allowed?” | “How many times?” |
| Error code | FAILED_PRECONDITION | RATE_LIMITED |
| Typical use | Paywalls, feature flags, role checks | Rate limits, free-tier caps |
| Evaluation | Before execution | After precondition passes |
You can use both on the same operation. For example, a precondition that requires a logged-in user, plus a quota that meters usage for free-tier users.
What a quota can meter
A quota meters operations, and nothing else. It counts executions of a named operation against the scope you choose, so “ten AI summaries a month” is a quota: the summary is an operation, and each run is one countable thing.
Record reads, media served, search and vector queries are not metered per user. Your own consumption of them is metered for your Foir bill — see Billing — but there is no per-user counter on them, and no upgrade message when one of your users opens their hundredth article.
That boundary is deliberate rather than unfinished. An operation is a discrete, named, expensive thing you chose to expose, and metering it costs one counter on one dispatch. A record read is none of those three: it is not discrete, it is not individually expensive, and metering it per end user would put a counter on the hot path of every read — a different cost profile entirely, paid by every project whether or not it charges for content.
Charging for content
Because metering stops at operations, a content paywall is not a quota. Express it as what a user can see rather than as how many times they have seen it:
| What you want | What to use |
|---|---|
| A free and a paid version of the same page | Variants targeted at a segment |
| Whole records readable only by some users | Per-record visibility |
| One record shared with one named user | Grants |
| A metered action — generate, export, send | A quota on the operation |
A variant already selects what a user sees, so “the free variant” and “the paid variant” needs no counter: the free variant carries the teaser and the upgrade path, the paid variant carries the article, and moving a user between them is a change of segment membership. Nothing has to be counted because nothing is being rationed — the user is being shown a different thing, not the same thing fewer times.
Note: A quota’s
messageis the right place for an upgrade call to action on a metered action, because the user meets it as an error. Content is the opposite case: the user never hits an error, so the upgrade path belongs inside the free variant itself.
Connecting Operations to Other Resources
Operations are referenced by key from other config resources:
- Hooks trigger operations on lifecycle events. See Defining Hooks.
- Schedules trigger operations on a cron schedule. See Defining Schedules.
- Operations can also be triggered manually from the console or via the Operations API.
Next Steps
- Operations Concepts — How operations work, the HTTP contract, and signing
- Building Operations — Step-by-step guide to building an operation endpoint
- Defining Hooks — Trigger operations on content events
- Defining Schedules — Trigger operations on a cron schedule