Tsumugi Docs
Search

INFO

This page was translated by an LLM. Some details and nuances may differ from the original.

Configuration

defineTsumugi

const tsumugi = defineTsumugi({
  performers,
  flows,
  schedules,
  runs,
  bindings,
  auth,
  ui,
  retention,
  metrics,
  onFailure,
  onSettled,
  onEnqueue,
});

defineTsumugi does not need type arguments.
The payload type for each binding and Env are inferred automatically from the contents of performers.

NameRequiredDescription
performers○Performer modules. The source from which payload and required-key types are derived
flowsMapping of Flow names to definitions. Requires the RUN binding when specified
schedulesDefinitions of scheduled execution. Requires the SCHEDULER binding when specified
runsLimits and retention period for Runs
bindingsPer-binding shard count, execution limits, and retention period
authAuthentication. When unset, all requests to the REST API and the dashboard return 404
uiui() from tsumugi/ui. When omitted, the dashboard bundle is not included
retentionRetention period for lists
metricsSettings for reading metrics. When unset, GET /api/metrics returns 501
onFailureBinding name to notify of failed jobs. When unset, no notification is sent
onSettledBinding name to notify of finished jobs, and the states to notify
onEnqueueFunction that sets default execution options on each enqueue

Return value

NameDescription
fetch, queue, scheduledExportedHandler handlers to include in the default export
jobs(env)Typed enqueue object (JobQueue<M>)
enqueue(env, input)Typed enqueue of one job. Returns the job ID
enqueueMany(env, inputs)Enqueues multiple jobs in the same format as enqueue
shardFor(env, binding, partitionKey?)Stub of the target shard
start(env, flow, input, options?)Starts a Run. Returns the runId
runFor(env, runId)Stub of the Run
runClassRun class to register in wrangler
schedulerClassScheduled-execution class to register in wrangler

Even when flows is not specified, the return value includes start, runFor, and runClass.
Passing a Flow name that is not defined in flows to start throws an exception.
Calling runFor when the RUN binding does not exist also throws an exception.
For the differences between enqueue methods, see Enqueueing jobs.

auth

FunctionDescription
bearerAuthAuthentication with a single token
cloudflareAccessVerification of the Cloudflare Access JWT
unsafeNoAuthNo authentication

You can pass a custom authentication function to auth.
The function takes request and env and returns a Response or undefined.
For details, see Dashboard and authentication.
When auth is not set, all requests to the REST API and the dashboard receive a 404 response.
For the effects of unsafeNoAuth, see Dashboard and authentication.

metrics

const tsumugi = defineTsumugi({
  performers,
  auth: bearerAuth((env: Env) => env.TSUMUGI_TOKEN),
  metrics: (env: Env) =>
    env.CF_ACCOUNT_ID && env.CF_API_TOKEN
      ? { accountId: env.CF_ACCOUNT_ID, apiToken: env.CF_API_TOKEN, dataset: 'tsumugi_jobs' }
      : undefined,
});

metrics configures how the recorded metrics are read from the dashboard and the REST API.
apiToken is an API token with read permission for Account Analytics. Set it as a Secret.
dataset is the dataset name written in analytics_engine_datasets in the wrangler configuration file.
When metrics is not specified, GET /api/metrics responds with 501, and the dashboard sidebar does not show the metrics item.

onFailure

const tsumugi = defineTsumugi({
  performers,
  onFailure: 'NotifyFailure',
});

onFailure is the binding name of the performer that is notified of failed jobs.
The performer that receives the notification must be one that accepts FailureNotice.
For the notification conditions and the contents of FailureNotice, see Failure notifications.

onSettled

const tsumugi = defineTsumugi({
  performers,
  onSettled: { binding: 'NotifySettled', states: ['COMPLETED', 'FAILED'] },
});

onSettled specifies the binding name of the performer that is notified of finished jobs, and the states to notify.
binding must be a performer that accepts SettledNotice.
states is required. Choose from COMPLETED, FAILED, CANCELLED, and STALLED.
Specifying an empty array or an invalid state throws an exception in defineTsumugi.
For the notification conditions and the contents of SettledNotice, see Completion notifications.

onEnqueue

const tsumugi = defineTsumugi({
  performers,
  onEnqueue: (input) => (input.binding === 'SlowJob' ? { timeoutMs: 300_000 } : undefined),
});

onEnqueue is a function that sets default execution options each time a job is enqueued.
Values explicitly specified by the caller always take precedence.
For the enqueue methods it applies to and the options that receive the defaults, see Defaults at enqueue time.

RunSettings

NameDefaultDescription
maxNodes10000Upper limit on the number of nodes in one Run. The Run fails when exceeded
maxDepth3Upper limit on subflow nesting. The Run fails when exceeded
sweepAfterMs5 minutesRetention time for finished Runs
failedRetentionMs7 daysRetention time for FAILED Runs. Runs within this period can be resumed

BindingConfig

NameDefaultDescription
shards1Number of shards. partitionKey is required when this is 2 or more
policySee belowExecution limits and aging
sweepAfterMs5 minutesRetention time for COMPLETED and CANCELLED jobs
failedRetentionMs7 daysRetention time for FAILED and STALLED jobs. Jobs within this period can be retried

Policy

NameDefaultDescription
pausedfalsePauses enqueueing
concurrency100Upper limit on concurrent executions
perKeyConcurrency1Upper limit on concurrent executions per concurrencyKey
ratenull{ tokens, intervalMs }. Runs up to tokens jobs per intervalMs
perKeyRatenull{ tokens, intervalMs }. Runs up to tokens jobs per intervalMs for each key
agingIntervalMs60000Wait time before the effective priority increases by 1. null disables aging
reaperGraceMs30000Grace period after timeoutMs elapses before a job that has reported no result is judged unresponsive

EnqueueInput

NameDefaultDescription
bindingBinding name of the target
payloadValue passed to the performer
priority0Numeric priority. Higher values run first
maxAttempts3Upper limit on the number of attempts
backoffexponentialfixed or exponential
timeoutMs60000Time until timeout
delayMsDelay before execution starts
runAtTime at which execution starts. Cannot be specified together with delayMs
expiresInMsExpiration counted from the enqueue time
expiresAtExpiration time. Takes precedence over expiresInMs
guaranteeat-least-onceat-least-once or at-most-once
concurrencyKeyKey for running jobs with the same key in order
uniqueKeyKey for deduplication
uniqueForMs24 hoursPeriod during which uniqueKey is used to detect duplicates
partitionKeyKey that determines the target when shards are split

For details on the options, see Enqueueing jobs.

enqueue of createClient takes EnqueueInput as its argument.
For the input accepted by enqueue of defineTsumugi, the payload and required-key types are derived for each binding.

Default value of backoff

{ kind: 'exponential', baseMs: 1_000, factor: 2, maxMs: 3_600_000, jitter: true }

SweepOptions

NameDefaultDescription
olderThanMs7 daysHow long finished jobs and Runs remain in lists
limit1000Upper limit on the number of items deleted at once. Applied separately to jobs and Runs

When a cron trigger is configured, jobs and Runs that have finished are deleted from lists after olderThanMs has elapsed.

The period during which a Run can be resumed is set in runs.
A FAILED Run is deleted from lists after the longer of olderThanMs and runs.failedRetentionMs has elapsed.
FAILED and STALLED jobs are also deleted from lists after the longer of olderThanMs and the binding's failedRetentionMs has elapsed.

wrangler bindings

bindingTypeRequiredPurpose
JOB_SHARDDurable Object○Job management
RUNDurable ObjectRun management. Required when using flows
SCHEDULERDurable ObjectScheduled execution. Required when using schedules
TSUMUGI_DBD1○Lists and search
TSUMUGI_QUEUEQueues○Execution of performers
TSUMUGI_METRICSAnalytics EngineRecording metrics

When TSUMUGI_METRICS does not exist, metrics are not recorded.
Nothing else changes.
If other required bindings are missing, the REST API responds with 503, and the response body includes the list of missing bindings.

A performer specified with remote() requires a Service Binding.
Do not use a fixed name for the binding name; use the key in performers as is.

"services": [
  { "binding": "MAIL", "service": "my-mailer", "entrypoint": "SendMail" },
]

A Worker that has no performers and is used only to enqueue jobs needs only the JOB_SHARD binding.

Subpaths

Import fromDescription
tsumugidefineTsumugi, enqueue, bearerAuth, TsumugiJobShard, etc.
tsumugi/performerPerformer
tsumugi/clientcreateClient and related types
tsumugi/uiui()
tsumugi/typesTypes only
tsumugi/testingrunPerformer, createTestContext, simulateFlow, etc.

The published npm package is tsumugi.
Run the setup CLI with npx tsumugi.
For the list of commands, see CLI.

Edit this page

Published: Last updated: