Skip to content
View as Markdown

Executor ​

Executors are event-driven handlers that automatically trigger in response to data changes, schedules, or external events.

Overview ​

Executors provide:

  • Automatic triggers on record changes (create, update, delete)
  • Scheduled execution via cron expressions
  • Incoming webhook handlers
  • Post-resolver execution hooks
  • Multiple operation types (functions, webhooks, GraphQL, workflows)

For the official Tailor Platform documentation, see Executor Guide.

Creating an Executor ​

Define executors in files matching glob patterns specified in tailor.config.ts.

Definition Rules:

  • One executor per file: Each file must contain exactly one executor definition
  • Export method: Must use export default
  • Uniqueness: Executor names must be unique globally across your entire application
typescript
import { createExecutor, recordCreatedTrigger, t } from "@tailor-platform/sdk";
import { user } from "../tailordb/user";

export default createExecutor({
  name: "user-welcome",
  description: "Send welcome email to new users",
  trigger: recordCreatedTrigger({
    type: user,
    condition: ({ newRecord }) => !!newRecord.email && newRecord.isActive,
  }),
  operation: {
    kind: "function",
    body: async ({ newRecord }) => {
      // Send welcome email logic here
    },
  },
});

Disabling an Executor ​

Set disabled: true to deploy an executor without letting it run. The definition stays deployed, and the platform skips dispatching jobs to it.

typescript
export default createExecutor({
  name: "user-welcome-paused",
  disabled: true,
  trigger: recordCreatedTrigger({ type: user }),
  operation: { kind: "function", body: async () => {} },
});

A disabled executor does not count as a subscriber when deploy resolves publishEvents on the resource its trigger names. Publishing is not enabled on that resource's behalf, and an explicit publishEvents: false on it is not rejected. If the resource was publishing only for this executor, the next deploy turns publishing back off — so disabling the last subscriber of a shared table changes that table for every config that reads its events.

The trigger is still deployed, so it must still name a resource the deploy declares; a disabled executor whose trigger names nothing fails the deploy exactly as an enabled one does. For the same reason, deploy and remove of another application stop with SERVICE_IN_USE instead of deleting a resource that a disabled executor's trigger names.

Trigger Types ​

Record Triggers ​

Fire when records are created, updated, or deleted:

  • recordCreatedTrigger(): Fires when a new record is created
  • recordUpdatedTrigger(): Fires when a record is updated
  • recordDeletedTrigger(): Fires when a record is deleted

Each trigger can include an optional filter function:

typescript
recordUpdatedTrigger({
  type: order,
  condition: ({ newRecord, oldRecord }) =>
    newRecord.status === "completed" && oldRecord.status !== "completed",
});

Schedule Trigger ​

Fires on a cron schedule:

typescript
scheduleTrigger({ cron: "*/5 * * * *" }); // Every 5 minutes
scheduleTrigger({ cron: "0 9 * * 1" }); // Every Monday at 9am
scheduleTrigger({ cron: "0 0 1 * *" }); // First day of every month
scheduleTrigger({ cron: "0 * * * *", timezone: "Asia/Tokyo" });

Incoming Webhook Trigger ​

Fires when an external webhook is received:

typescript
type WebhookRequest = {
  body: WebhookPayload;
  headers: Record<string, string>;
};

incomingWebhookTrigger<WebhookRequest>();

Name only what you want to change in the type argument. The body type and the type of each header you name are replaced, and the others keep their defaults. For example, incomingWebhookTrigger<{ headers: { "x-request-id": string[] } }>() types x-request-id as string[]. Because one header is an array, the headers you do not name may then be arrays as well.

You can customize the HTTP response returned to the webhook caller:

typescript
// Response body only (shorthand)
incomingWebhookTrigger<WebhookRequest>({
  response: (args) => ({ challenge: args.body.challenge }),
});

// Response body with custom status code
incomingWebhookTrigger<WebhookRequest>({
  response: {
    body: (args) => ({ challenge: args.body.challenge }),
    statusCode: 201,
  },
});

If body is set without statusCode, the platform uses 200. If neither is set, the platform returns 204.

Resolver Executed Trigger ​

Fires when a resolver is executed:

typescript
resolverExecutedTrigger({
  resolver: createOrderResolver,
  condition: (args) => args.success && !!args.result.order,
});

IdP User Triggers ​

Fire when IdP users are created, updated, or deleted:

  • idpUserCreatedTrigger(): Fires when a new IdP user is created
  • idpUserUpdatedTrigger(): Fires when an IdP user is updated
  • idpUserDeletedTrigger(): Fires when an IdP user is deleted
typescript
idpUserCreatedTrigger();

When the project defines multiple IdPs, pass idp to target a specific one. The name is type-narrowed via the generated IdpName type:

typescript
idpUserCreatedTrigger({ idp: "my-idp" });

Omitting idp is allowed only when the project has exactly one IdP; otherwise deploy fails with an error listing the configured IdPs.

When you deploy several configs together with tailor deploy -c shop,backoffice, idp can also name an IdP that another config in the same run owns, without declaring that IdP in the subscribing config's defineConfig({ idp }). deploy fails if no config in the run owns an IdP with that name. An executor that omits idp still considers only the IdPs its own config declares.

The generated IdpName type lists only the IdPs the config declares, so a config that declares an IdP of its own reports another config's IdP name as a type error. Pass external: true with the name to allow it:

typescript
idpUserCreatedTrigger({ idp: "backoffice-idp", external: true });

The option only relaxes the type check; deploy resolves the name the same way with or without it.

These triggers require the IdP to publish user lifecycle events. deploy enables publishEvents automatically on each IdP targeted by an idpUser trigger taking part in the same run, and turns it back off once no such trigger remains; set the value explicitly on defineIdp() to pin it. See IdP service - publishEvents.

Auth Access Token Triggers ​

Fire on auth access token lifecycle events:

  • authAccessTokenIssuedTrigger(): Fires when a new access token is issued
  • authAccessTokenRefreshedTrigger(): Fires when an access token is refreshed
  • authAccessTokenRevokedTrigger(): Fires when an access token is revoked
typescript
authAccessTokenIssuedTrigger();

Workflow Execution Triggers ​

Fire when a workflow execution changes state. Use the single-event helpers or workflowExecutionTrigger() for multiple events:

typescript
import { createExecutor, workflowExecutionTrigger } from "@tailor-platform/sdk";
import orderWorkflow from "../workflows/order";

export default createExecutor({
  name: "order-workflow-finished",
  trigger: workflowExecutionTrigger({
    workflow: orderWorkflow,
    events: ["completed", "retried"],
  }),
  operation: {
    kind: "function",
    body: async (args) => {
      if (args.event === "completed" && !args.success) {
        console.error(args.error);
      }
    },
  },
});

The available workflow events are started, completed, retried, resumed, wait_started, and wait_resolved; their single-event helpers are workflowExecutionStartedTrigger(), workflowExecutionCompletedTrigger(), workflowExecutionRetriedTrigger(), workflowExecutionResumedTrigger(), workflowExecutionWaitStartedTrigger(), and workflowExecutionWaitResolvedTrigger(). To observe job-level events, use workflowJobExecutionStartedTrigger(), workflowJobExecutionCompletedTrigger(), workflowJobExecutionWaitStartedTrigger(), workflowJobExecutionWaitResolvedTrigger(), or workflowJobExecutionTrigger().

completed events include success; when it is false, error contains the failure message. A job released from a wait point emits wait_resolved instead of completed.

These triggers require the workflow to publish execution events. deploy enables publishEvents automatically on each targeted workflow, and on every job of a workflow targeted by a workflowJobExecution* trigger, and turns it back off once no such trigger remains; set the value explicitly to pin it. See Workflow service - Execution Events.

Multi-Event Triggers ​

Handle multiple event types in a single executor using multi-event trigger factories. These accept an events array of short event names:

recordTrigger() ​

typescript
import { createExecutor, recordTrigger } from "@tailor-platform/sdk";
import { user } from "../tailordb/user";

export default createExecutor({
  name: "user-changed",
  trigger: recordTrigger({
    type: user,
    events: ["created", "updated"],
  }),
  operation: {
    kind: "function",
    body: async (args) => {
      if (args.event === "created") {
        console.log("User created:", args.newRecord.name);
      }
      if (args.event === "updated") {
        console.log("User updated:", args.oldRecord.name, "->", args.newRecord.name);
      }
    },
  },
});

idpUserTrigger() ​

typescript
idpUserTrigger({ events: ["created", "deleted"] });

In multi-IdP projects, add idp to target a specific IdP:

typescript
idpUserTrigger({ events: ["created", "deleted"], idp: "my-idp" });

authAccessTokenTrigger() ​

typescript
authAccessTokenTrigger({ events: ["issued", "revoked"] });

workflowExecutionTrigger() and workflowJobExecutionTrigger() ​

typescript
workflowExecutionTrigger({ workflow: orderWorkflow, events: ["started", "completed"] });
workflowJobExecutionTrigger({ workflow: orderWorkflow, events: ["started", "wait_resolved"] });

The event field on args matches the short event name, enabling type narrowing. Record triggers use names such as "created", auth token triggers use "issued", and workflow triggers use "started", "completed", and "wait_resolved". The rawEvent field contains the full event type string (e.g., "tailordb.type_record.created").

Operation Types ​

Function Operation ​

Execute JavaScript/TypeScript functions:

typescript
createExecutor({
  operation: {
    kind: "function",
    body: async ({ newRecord, env }) => {
      console.log(`New record created in ${env.bar}:`, newRecord);
    },
  },
});

Executor callbacks receive the trigger args, including env from defineConfig({ env }). function and jobFunction body args also include an invoker field: the principal running this function, or the machine user configured through the operation invoker option; null for anonymous calls. Other operation kinds (graphql, webhook, workflow) receive env through their callback args but do not pass invoker into those callbacks.

Job Function Operation ​

For work that needs more than the 60-second function limit, use jobFunction, which can run for up to 5 minutes. See Job Function Operation for details.

typescript
import { createExecutor, scheduleTrigger } from "@tailor-platform/sdk";
import { getDB } from "../generated/tailordb";

export default createExecutor({
  name: "daily-report-generator",
  description: "Generate daily reports",
  trigger: scheduleTrigger({ cron: "0 0 * * *" }),
  operation: {
    kind: "jobFunction",
    body: async () => {
      const db = getDB("tailordb");
      // Report generation logic (runs up to 5 minutes)
      const records = await db.selectFrom("Order").selectAll().execute();
      // Process records...
    },
  },
});

Webhook Operation ​

Call external webhooks with dynamic data:

typescript
createExecutor({
  operation: {
    kind: "webhook",
    url: ({ typeName }) => `https://api.example.com/webhooks/${typeName}`,
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": { vault: "api-keys", key: "external-api" },
    },
    requestBody: ({ newRecord }) => ({
      id: newRecord.id,
      timestamp: new Date(),
      data: newRecord,
    }),
  },
});

GraphQL Operation ​

Execute GraphQL queries and mutations:

typescript
createExecutor({
  operation: {
    kind: "graphql",
    appName: "my-app",
    query: `
      mutation UpdateUserStatus($id: ID!, $status: String!) {
        updateUser(id: $id, input: { status: $status }) {
          id
          status
          updatedAt
        }
      }
    `,
    variables: ({ newRecord }) => ({
      id: newRecord.userId,
      status: "active",
    }),
  },
});

Workflow Operation ​

Trigger workflows from executors. See Workflow documentation for how to define workflows.

typescript
import { createExecutor, recordCreatedTrigger } from "@tailor-platform/sdk";
import { order } from "../tailordb/order";
import processOrderWorkflow from "../workflows/process-order";

export default createExecutor({
  name: "order-processor",
  description: "Process new orders via workflow",
  trigger: recordCreatedTrigger({ type: order }),
  operation: {
    kind: "workflow",
    workflow: processOrderWorkflow,
    args: ({ newRecord }) => ({
      orderId: newRecord.id,
      customerId: newRecord.customerId,
    }),
  },
});

You can also pass static arguments:

typescript
createExecutor({
  operation: {
    kind: "workflow",
    workflow: dailyReportWorkflow,
    args: { reportType: "summary" },
  },
});

args must match the workflow's main job input. It is required when that input is required and can be omitted when the workflow has no input. Static arguments can be JSON-compatible primitives, arrays, or plain objects; top-level null is not supported. An argument callback must return the same input type.

Authentication for Operations ​

graphql, function, jobFunction, and workflow operations can specify an invoker to execute with machine user credentials. Pass the machine user name as a plain string — it is type-narrowed to the names defined in your auth config:

typescript
import { createExecutor, scheduleTrigger } from "@tailor-platform/sdk";

export default createExecutor({
  name: "scheduled-cleanup",
  trigger: scheduleTrigger({ cron: "0 0 * * *" }),
  operation: {
    kind: "graphql",
    query: `mutation { cleanupOldRecords { count } }`,
    invoker: "batch-processor",
  },
});

The machine user is resolved in your application's auth namespace — the name of your Auth service, local or external. webhook is the only operation kind that does not accept invoker, since it calls an external URL rather than acting inside your workspace.

Without an invoker, the operation runs as whoever raised the trigger event, or anonymously when there is no such principal — as with a schedule trigger. Declare an invoker whenever the operation needs an identity of its own.

Event Payloads ​

The SDK exports the args type of each single-event trigger under the trigger's name in PascalCase with Trigger replaced by Args, such as RecordCreatedArgs for recordCreatedTrigger(); a multi-event trigger's callbacks receive the union of the args of the events it lists. Editor autocompletion lists each type's fields. actor, where present, is the principal that raised the event, or null when there is none.

Record Event Payloads ​

newRecord holds the record after a create or update, and oldRecord holds it before an update or delete.

Usage Example:

typescript
import { createExecutor, recordUpdatedTrigger, t } from "@tailor-platform/sdk";
import { order } from "../tailordb/order";

export default createExecutor({
  name: "order-status-changed",
  trigger: recordUpdatedTrigger({
    type: order,
    condition: ({ oldRecord, newRecord }) => oldRecord.status !== newRecord.status,
  }),
  operation: {
    kind: "function",
    body: async ({ oldRecord, newRecord, typeName }) => {
      console.log(`${typeName} status changed:`);
      console.log(`  From: ${oldRecord.status}`);
      console.log(`  To: ${newRecord.status}`);
    },
  },
});

Schedule Event Payload ​

ScheduleArgs holds only env.

Incoming Webhook Payload ​

IncomingWebhookArgs types body and headers from the type argument of incomingWebhookTrigger(). Header names are in lower case. accept, via and the other headers a client may send on several lines are string | string[]; any other header is a string.

Usage Example:

typescript
import { createExecutor, incomingWebhookTrigger } from "@tailor-platform/sdk";
import { secretmanager } from "@tailor-platform/sdk/runtime";

type StripeWebhook = {
  type: string;
  data: { object: { id: string; amount: number } };
};

export default createExecutor({
  name: "stripe-webhook",
  trigger: incomingWebhookTrigger<{
    body: StripeWebhook;
    headers: { "stripe-signature": string };
  }>(),
  operation: {
    kind: "function",
    body: async ({ body, headers, rawBody }) => {
      const secret = await secretmanager.getSecret("api-keys", "stripe-webhook-secret");
      // Implement verifyStripeSignature following https://docs.stripe.com/webhooks?verify=verify-manually#verify-manually
      if (!(await verifyStripeSignature(headers["stripe-signature"], rawBody, secret))) {
        throw new Error("Invalid Stripe signature");
      }
      console.log(`Received ${body.type} event`);
      // Process webhook...
    },
  },
});

The webhook URL is public, so verify the signature over the unparsed request body before trusting body. rawBody is delivered base64-encoded; decode it to the original bytes before computing the signature.

A header sent on one line is a string, and a header sent on more than one line is an array of strings.

When an executor is triggered manually with tailor executor trigger or triggerExecutor from @tailor-platform/sdk/cli, it receives the headers passed with --header or the headers option, and no rawBody. A header passed once is a string, and a header passed more than once is an array. To test an executor that verifies a signature over rawBody, send a request to its webhook URL, which tailor executor webhook list shows.

With custom response:

typescript
export default createExecutor({
  name: "slack-challenge",
  trigger: incomingWebhookTrigger<{
    body: { challenge: string; type: string };
    headers: Record<string, string>;
  }>({
    response: (args) => ({ challenge: args.body.challenge }),
  }),
  operation: {
    kind: "function",
    body: async ({ body }) => {
      console.log(`Received ${body.type} event`);
    },
  },
});

This example omits signature verification. To handle real Slack events, verify the request in the operation before trusting body, as the Stripe example above does. Verifying requests from Slack describes how to compute Slack's signature.

Resolver Executed Payload ​

Narrow ResolverExecutedArgs on success: result holds the resolver's output when it is true, and error holds the error message when it is false.

Usage Example:

typescript
import { createExecutor, resolverExecutedTrigger } from "@tailor-platform/sdk";
import { createOrderResolver } from "../resolvers/create-order";

export default createExecutor({
  name: "order-created-notification",
  trigger: resolverExecutedTrigger({
    resolver: createOrderResolver,
    condition: (args) => args.success && !!args.result.order,
  }),
  operation: {
    kind: "function",
    body: async (args) => {
      if (!args.success) return;
      console.log(`${args.resolverName} completed successfully`);
      console.log(`Order ID: ${args.result.order.id}`);
    },
  },
});

IdP User Event Payload ​

namespaceName names the IdP namespace, and userId the affected user.

Auth Access Token Event Payload ​

namespaceName names the Auth namespace, and userId the user the token belongs to.

Workflow Execution Event Payloads ​

See Workflow Execution Triggers for narrowing workflow and job execution args on event and success.