Actions
Learn how to define and use actions in Duron
Actions are the core building blocks of Duron. They define what work needs to be done and how it should be executed.
Defining Actions
Actions are defined using the defineAction function. Each action must have:
- name: A unique identifier for the action
- handler: The function that executes the action logic
- input (optional): A Standard Schema validator for validating input (Zod, Valibot, ArkType, etc.)
- output (optional): A Standard Schema validator for validating output
Duron supports any schema library that implements the Standard Schema specification. This includes:
- Zod (v4+)
- Valibot (v1+)
- ArkType
- Effect Schema
import { defineAction } from 'duron/action'
import { z } from 'zod'
const processOrder = defineAction()({
name: 'processOrder',
input: z.object({
orderId: z.string(),
userId: z.string(),
}),
output: z.object({
success: z.boolean(),
orderNumber: z.string(),
}),
handler: async (ctx) => {
// Access input data
const { orderId, userId } = ctx.input
// Use steps to break down work into retryable units
const order = await ctx.step('processOrder', async ({ signal }) => {
// Your business logic here
// The signal can be used to handle cancellation
return await processOrderLogic(orderId, userId, { signal })
})
return {
success: true,
orderNumber: order.number,
}
},
})Action Context
The handler function receives a context object (ctx) with the following properties:
ctx.input
The validated input data based on your input schema.
handler: async (ctx) => {
// Type-safe access to input
const orderId = ctx.input.orderId
const userId = ctx.input.userId
}ctx.jobId
The unique identifier of the job executing this action.
handler: async (ctx) => {
console.log(`Processing job ${ctx.jobId}`)
}ctx.groupKey
The group key for this job, used for concurrency control.
handler: async (ctx) => {
console.log(`Job belongs to group: ${ctx.groupKey}`)
}ctx.var
Variables passed to the Duron client, accessible to all actions.
// When creating the client
const client = duron({
variables: {
apiKey: process.env.API_KEY,
db: myDatabase,
},
// ...
})
// In your action handler
handler: async (ctx) => {
const apiKey = ctx.var.apiKey
const db = ctx.var.db
}ctx.logger
A Pino logger instance for structured logging.
handler: async (ctx) => {
ctx.logger.info({ orderId: ctx.input.orderId }, 'Processing order')
ctx.logger.error({ error }, 'Failed to process order')
}ctx.step
A function to create and execute inline steps within the action. See Steps for more details.
handler: async (ctx) => {
const result = await ctx.step('fetchUser', async ({ signal }) => {
return await fetchUser(ctx.input.userId, { signal })
})
}ctx.run
A function to execute reusable step definitions created with createStep(). See Reusable Step Definitions for more details.
import { createStep } from 'duron'
const sendEmailStep = createStep<typeof variables>()({
name: 'send-email',
input: z.object({ to: z.string().email(), body: z.string() }),
handler: async (ctx) => {
// ctx includes input, signal, var, logger, jobId, etc.
return { success: true }
},
})
handler: async (ctx) => {
// Execute the reusable step
const result = await ctx.run(sendEmailStep, {
to: ctx.input.email,
body: 'Hello World',
})
}ctx.telemetry
Telemetry context for recording custom metrics and span data. Provides access to OpenTelemetry APIs. See Telemetry for more details.
handler: async (ctx) => {
// Record a custom metric
ctx.telemetry.recordMetric('custom.counter', 1)
// Access the active span for attributes and events (undefined without a span)
const span = ctx.telemetry.getActiveSpan()
span?.setAttribute('customKey', 'value')
span?.addEvent('custom.event')
}Action Options
name
Required. A unique string identifier for the action. This is used as the queue name.
{
name: 'sendEmail', // Must be unique across all actions
}version
Optional. A version string for tracking changes to the action. Used in checksum generation.
{
name: 'sendEmail',
version: '1.0.0',
}input
Optional. A Standard Schema validator for validating action input. If provided, input will be validated before the handler is called.
Any schema library that implements the Standard Schema specification works:
// Using Zod
import { z } from 'zod'
{
name: 'sendEmail',
input: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
}// Using Valibot
import * as v from 'valibot'
{
name: 'sendEmail',
input: v.object({
to: v.pipe(v.string(), v.email()),
subject: v.string(),
body: v.string(),
}),
}output
Optional. A Standard Schema validator for validating action output. If provided, output will be validated after the handler completes.
{
name: 'sendEmail',
output: z.object({
success: z.boolean(),
messageId: z.string(),
}),
}handler
Required. The function that executes the action logic. Must return a Promise.
{
name: 'sendEmail',
handler: async (ctx) => {
// Use steps for retryable work
await ctx.step('sendEmail', async ({ signal }) => {
// Your logic here
// The signal can be used to handle cancellation
return await sendEmailLogic(ctx.input, { signal })
})
return { success: true }
},
}expire
Optional. Timeout in milliseconds for the entire action. Defaults to 15 minutes. A job that runs longer fails with an ActionTimeoutError.
{
name: 'sendEmail',
expire: 30 * 60 * 1000, // 30 minutes
}description
Optional. A function that generates a dynamic description for the job at creation time. The description is stored in the database and displayed in the dashboard, providing context about what the specific job instance is doing.
{
name: 'sendEmail',
description: async (ctx) => `Send email to ${ctx.input.to}`,
}The function receives the same context as groupKey with ctx.input and ctx.var:
{
name: 'processOrder',
description: async (ctx) => {
return `Process order #${ctx.input.orderId} for user ${ctx.input.userId}`
},
}concurrency
Optional. The maximum number of jobs of this action that run at the same time across all workers, whatever their group. A positive integer. Without it (the default), the action has no limit of its own.
A job is claimed only when both its group (groups.concurrency) and its action have a free slot. When the action is at its limit, its jobs wait and the jobs of other actions are still claimed. The limit is stored with each job, and the limit of the action's latest unexpired job applies to the whole action, as for groups (see Claim Admission). Each worker also runs at most actionConcurrencyLimit jobs of one action at once.
{
name: 'sendEmail',
concurrency: 50, // at most 50 sendEmail jobs run at once, across all workers
}groups
Optional. Configuration for grouping jobs and controlling concurrency per group.
groups.groupKey
A function that determines the group key for a job. Jobs of this action with the same group key share the group concurrency limit. The key does not deduplicate jobs, and jobs run one at a time only when the limit is 1.
Without groupKey, every job of the action uses the group key @default, so they all share one group: the group limit (groups.concurrency, or the Client's groupConcurrencyLimit, default 10) then caps the running jobs of the whole action across all workers.
{
name: 'processOrder',
groups: {
groupKey: async (ctx) => {
// Group by user ID to prevent concurrent processing for the same user
return `user-${ctx.input.userId}`
},
},
}groups.concurrency
A function that determines the concurrency limit for a job's group, across all workers. Without it, the Client's groupConcurrencyLimit applies (default 10). The limit of the group's latest unexpired job applies to the whole group (see Claim Admission).
{
name: 'processOrder',
groups: {
groupKey: async (ctx) => `user-${ctx.input.userId}`,
concurrency: async (ctx) => {
// Higher concurrency for premium users
return ctx.input.isPremium ? 20 : 5
},
},
}steps
Optional. Configuration for steps within the action.
steps.concurrency
Maximum number of steps of one job that can run concurrently. Defaults to 100.
{
name: 'processOrder',
steps: {
concurrency: 5, // Allow up to 5 concurrent steps
},
}steps.retry
Retry configuration for steps. See Retries for details.
{
name: 'processOrder',
steps: {
retry: {
limit: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 10000,
},
},
}steps.expire
Default timeout in milliseconds for steps. Defaults to 5 minutes.
{
name: 'processOrder',
steps: {
expire: 10 * 60 * 1000, // 10 minutes
},
}Complete Example
Here's a complete example with all options:
import { defineAction } from 'duron/action'
import { z } from 'zod'
const processOrder = defineAction<{ db: Database }>()({
name: 'processOrder',
version: '1.0.0',
input: z.object({
orderId: z.string(),
userId: z.string(),
}),
output: z.object({
success: z.boolean(),
orderNumber: z.string(),
}),
expire: 30 * 60 * 1000, // 30 minutes
concurrency: 50,
groups: {
groupKey: async (ctx) => `user-${ctx.input.userId}`,
concurrency: async (ctx) => 5,
},
description: async (ctx) => `Process order ${ctx.input.orderId} for user ${ctx.input.userId}`,
steps: {
concurrency: 10,
retry: {
limit: 3,
factor: 2,
minTimeout: 1000,
maxTimeout: 10000,
},
expire: 5 * 60 * 1000,
},
handler: async (ctx) => {
ctx.logger.info({ orderId: ctx.input.orderId }, 'Processing order')
// Use variables
const db = ctx.var.db
// Execute steps
const user = await ctx.step('fetchUser', async ({ signal }) => {
return await db.users.findById(ctx.input.userId, { signal })
})
const order = await ctx.step('createOrder', async ({ signal }) => {
return await db.orders.create(
{
orderId: ctx.input.orderId,
userId: ctx.input.userId,
},
{ signal },
)
})
return {
success: true,
orderNumber: order.number,
}
},
})