Files
triggerdotdev--trigger.dev/CONTRIBUTING.md
T
nicktrn e97704d904 Run Engine 2.0 (WIP) (#1575)
* bump worker version

* Suggested glossary for the RunEngine, TBC

* Removed BatchTaskRun changes from this branch, they were done in main

* Set the BatchTaskRun status to completed when all runs are completed

* When dequeuing respect passed in maxResources

* Ported over the new run props: idempotencyKeyExpiresAt, versions, oneTimeUseToken, maxDurationInSeconds

* Didn’t hit save… the new props when triggering tasks passed through

* Idempotency expiration + waitpoint edge case

* WIP on creating checkpoint, parking for now

* fix worker routes

* upgrade webapp node types to support generic event emitter

* separate event bus handler singleton and run failure alerts

* duration waits

* fix execution snapshot debug spans

* task waits

* fix event bus types

* temporary fix for react hook run handle type

* disable run notifications for now

* convert any typecasts to expect errors to more easily fix later

* fix webapp types after node types upgrade

* updateEnvConcurrencyLimits across marqs and the runqueue

* Pass proper values into the run engine

* RunQueue settings and removed unused rebalancing workers

* Remove rebalancing prop

* Tidied more things up

* Update/remove queue limits for MARQS and RunQueue

* taskQueue/concurrencyLimit changes ported back into the RunEngine

* Reworked completing waitpoints to improve performance and reduce race conditions

* Improved test robustness

* Down to a single run lock only when a run is totally unblocked and ready to continue

* warm starts, worker notifications, wait fixes

* Fix for Run Engine poll interval env var

* Expect the waitpoint to be completed quickly

* If a run is locked then it’s too late to expire it

* Added VALKEY_ env vars and plugged them into the run engine

* Extracted and updated the guard queue function so it can be used when batching

* Added logging and universal concurrency changes to trigger task v1

* Added notes back in

* Bump @trigger.dev/worker to 3.3.7

* reportInvocationUsage for the runAttemptStarted event

* improve execution snapshot span debug span start times

* Unfriendly IDs

* update lockfile

* Created a shared determineEngineVersion function

* disable unfinished commands

* save new cli config to different location, misc fixes

* add basic engine version check via current deploy

* new run engine will default to node 22 runtime

* block some actions for projects on previous run engine

* fix worker group tests

* fix triggerAndWait test

* one typescript version to rule them all

* redlock type patch

* fix type issues caused by ts-reset

* improve cleanup scripts

* add missing socket.io dep

* fix run notification handler type

* fix worker group test again

* generate prisma client for e2e tests

* remove worker group tests for now

* prevent image pull rate limits during unit tests

* increase timeout for queue concurrency limit test

* generate prisma client for preview release

* same node types everywhere

* Updated engine readme, removed legacy system notes

* use default machine preset from platform package

* worker instances plural in schema

* disable pnpm update notifications

* return worker group details from connect call

* add workers admin route

* fix heartbeat route return type

* move deployment labels to core apps

* refactor run controller env schema

* Add firstAttemptStartedAt to TaskRun

* RunEngine 2.0 batch trigger support (#1581)

* Make it clear when BatchTriggerV2Service is used

* Copy of BatchTriggerV2Service

* WIP batch triggering

* Allow blocking a run with multiple waitpoints at once. Made it atomic

* Removed unused param

* New batch service

* Pass through the parentRunId and resumeParentOnCompletion

* Use the new batch service, and correct trigger task version

* Force V1 engine if using BatchTriggerV2Service, we’ve already done the check at this point

* Removed the $transaction and early exit if nothing changed

* Adedd a simple batch task to the hello world reference catalog

* Fix for batch waits not working

* Added parentRunId in a couple more places

* Removed waitForBatch log

* Added another parentRunId

* Expanded the example to include all the different triggers

* More changes to blocking to support continuing after idempotent completed runs

* Fix for the wrong type when blocking a run

* remove @map

* optimise worker auth query

* add engine version header to core api client requests

* remove unique constraint for default group id

* consolidate migrations

* the first managed worker becomes the global default

* Debug events off by default, added an admin toggle to show them

* worker group name can't be an empty string

* add exec helper to core

* move machine resources to core

* add pre-dequeue callback to determine max resources

* optionally skip dequeue

* bump worker package

* move worker to core

* fix ReadableStream type error

* fix another type issue

* update a few more tsconfigs

* add metadata changes introduced in #1563

* Run Engine 2.0 trigger idempotency (#1613)

* Return isCached from the trigger API endpoint

* Fix for the wrong type when blocking a run

* Render the idempotent run in the inspector

* Event repository for idempotency

* Debug events off by default, added an admin toggle to show them

* triggerAndWait idempotency span

* Some improvements to the reference idempotency task

* Removed the cached tracing from the SDK

* Server-side creating cached span

* Improved idempotency test task

* Create cached task spans in a better way

* Idempotency span support inc batch trigger

* Simplified how the spans are done, using more of the existing code

* Improved the idempotency test task

* Added Waitpoint Batch type, add to TaskRunWaitpoint with order

* Pass batch ids through to the run engine when triggering

* Added batchIndex

* Better batch support in the run engine

* Added settings to batch trigger service, before major overhaul

* Allow the longer run/batch ids in the filters

* Changed how batching works, includes breaking changes in CLI

* Removed batch idempotency because it gets put on the runs instead

* Added `runs` to the batch.retrieve call/API

* Set firstAttemptStartedAt when creating the first attempt

* Do nothing when receiving a BATCH waitpoint

* Some fixes in the new batch trigger service… mostly just passing missing optional params through

* Tweaked the idempotency test task for more situations

* Only block with a batch if it’s a batchTriggerAndWait… 🤦‍♂️

* Added another case to the idempotency test task: multiple of the same idempotencyKey in a single batch

* Support for the same run multiple times in the same batch

* Small tweaks

* Make sure to complete batches, even if they’re not andWait ones

* Export RunDuplicateIdempotencyKeyError from the run engine

* Latest lockfile

* Trigger with a machine (old run engine)

* RE2, allow setting machine when triggering

* Fix for new glob patterns

* add max run count to dequeue from version route

* add worker instance name env var and header

* queue consumer pre skip callback

* poll for more runs after final execution errors

* fix dequeue search param schema

* add shortcut to debug switch

* expose run engine timeouts as env vars

* make warm start durations configurable

* add optional status to json reply helper

* fix preSkip hook, add debug logs

* BLOCKED_BY_WAITPOINTS -> SUSPENDED

* exit controller when run suspended

* check if already replied before http reply

* run controller will wait for next run after the current one is suspended

* cancel run button shortcut

* minimal event repository environment type

* fix update metadata call

* run suspension and misc fixes wip

* change debug shortcut to shift + D

* Started work on the Dev supervisor

* Formatting

* Fix for bad imports

* Before rebuilding SSE

* Presence updating from the CLI working via SSE

* add worker notification debug logs

* send run:stop when exiting run phase

* skip current snapshot poll on worker notification

* add more logs and route to submit run debug logs

* add worker and runner ids to snapshots

* improve run notification debug logs

* add workload debug log route

* misc run controller fixes and refactor

* prevent parallel execution of critical functions

* update bun to 1.2.1

* WIP with dev dequeuing

* Method to convert friendlyIds to non-friendly, do nothing with actual ids

* Set the engine on BackgroundWorker, lazily upgrade projects to engine V2

* Runs with ttls were getting immediately expired… oops.

* Pass the Waiting for deploy reason through, so we have it on the execution snapshots

* Fixed the logic for getting the right background worker for a run

* Use the correct ID when dequeuing…

* determineEngineVersion is now fully functional

* Rate limiter ignores the dev endpoints

* Retrieving a batch gives you the runIds

* Set a unique version for the RE2 BatchTaskRun

* add provisional changeset

* The start of dev run execution is working

* First dev run working

* Moved the dev run controller closer to what Nick did with the managed one

* export exec output type

* Heartbeat fix: don’t heartbeat if _isHeartbeating == false

* Dev runs get notifications, some dev bug fixes

* Improved logging or dequeuing

* We need to dequeue runs from the latest version too, for triggerAndWait

* Ported Eric’s validateWorkerManifest with nicer errors

* When flattening an idempotency key if part is undefined, return undefined

* Dev logging fixes

* Remove sigterm listener

* Deprecating workers. Don’t specify a BackgroundWorker when dequeuing an environment

* Deleted some old files. Renamed “managed” to “deploy”

* When a build finishes, always copy the build dir (otherwise the first one gets trampled on by the 2nd)

* Dev master queues should work differently

* Deleting old workers

* Added debounce function to core

* Improvement to canceling

* WIP on debounce canceling on socket disconnection

* Added environment data to execution snapshots

* Dev runs that have stalled get “Canceled” with a reason explaining why

* Show CLI messaged when a connection to the platform is lost/restored

* Fix TriggerTask after merge

* Add trigger task v2 max attempts, replace some findUniques

* Port the new queue logic to the run engine

* More fixes post-merge

* We weren’t setting a `retryConfig` up for the tests… it’s now required

* Start the Redis worker inside the Run Engine… 🤦‍♂️

* Trying to make the testcontainers more reliable

* Added keyPrefix: "engine:”

* Badly placed bracket in trigger task

* Better Redis namespacing

* Fix for expired run not getting removed from the queue

* Don’t create a redis client in the testcontainers, return the redisOptions instead

* Cleanup redis client in the run lock tests

* Fix for the RunQueue not supporting keyPrefix

* Updated more of the RunQueue scripts rebalancing

* Trying to make Redis more robust in the tests…

* Improved test resiliciency more

* Fix for delays (checkpoint check)

* Increase the timeout slightly to fix ttl test

* Added priority support when triggering

* More wip trying to make test containers more reliable

* batchTriggerAndWait test is still failing… some wip to try fix it

* Fixed redis tests now we’re not providing a client

* Separate Redis clients for the run engine worker/queue/runlock

* Made the wait for duration test more resilient

* Added idempotencyKeyExpiresAt to Waitpoints

* Waitpoint timeouts and idempotency expiry

* Use finishWaitpoint, removed extra worker job

* Added waitpoint idempotency tests

* Creating resume tokens is working

* Some improvements to the resume tokens

* Moved resumeTokens to just be wait functions 🥳

* Delete old RuntimeManagers

* Wait for token is working

* Better test for the wait tokens

* Improved the test task some more

* Hide the accessories in the span inspector

* WIP on waitpoint inspector

* WIP on complete waitpoint form

* Span overview panel can be changed based on the entity type

* Improved the waitpoint display

* WIP on completing waitpoint form

* Use the existing CodeBlock for the tip

* Style improvements

* Complete waitpoint

* All waitpoint sidebar variants

* Waits now use a pause icon

* Durations waits use the API to create/block with a waitpoint, not the runtime

* Fix for engine.blockRunWithWaitpoint required org id

* Removed old wait code from the run controllers/task run process

* Form action for skipping a datetime waitpoint

* Move testDockerCheckpoint to a separate core package export (it can’t be bundled on the client)

* Fix for glitchy hourglass animation

* Completed waitpoints display better

* Increase Redis maxRetriesPerRequest to 20 (default)

* Completing and skipping waitpoints is working

* Remove the database prisma dev command, since we need to use create only now. Updated docs

* Added skip timeout, reworked the UI

* Tweaked spacing

* Added payload limit to waitpoint token completion from dashboard

* Test idempotency works on wait.for and wait.until

* Moved the worker-actions to /engine/ from /api/

* Moved dev engine endpoints to /engine/ from /api/

* Separate /engine/ rate limiter

* Added parallel wait prevention, it’s working for duration waits but not well for triggerAndWait yet

* WIP post-merge conflicts

* Set taskEventStore column in the new engine

* Remove duplicate keys

* Post-merge fixes

* Fix for span merge layout

* Use executedAt instead of firstAttemptStartedAt

---------

Co-authored-by: Matt Aitken <matt@mattaitken.com>
2025-03-05 14:40:14 +00:00

12 KiB

Contributing to Trigger.dev

Thank you for taking the time to contribute to Trigger.dev. Your involvement is not just welcomed, but we encourage it! 🚀

Please take some time to read this guide to understand contributing best practices for Trigger.dev.

Thank you for helping us make Trigger.dev even better! 🤩

Developing

The development branch is main. This is the branch that all pull requests should be made against. The changes on the main branch are tagged into a release periodically.

Prerequisites

Setup

  1. Clone the repo into a public GitHub repository or fork the repo. If you plan to distribute the code, keep the source code public to comply with the Apache Licence 2.0.

    git clone https://github.com/<github_username>/trigger.dev.git
    

    If you are on windows, run the following command on gitbash with admin privileges: git clone -c core.symlinks=true https://github.com/<github_username>/trigger.dev.git

  2. Navigate to the project folder

    cd trigger.dev
    
  3. Ensure you are on the correct version of Node.js (20.11.1). If you are using nvm, there is an .nvmrc file that will automatically select the correct version of Node.js when you navigate to the repository.

  4. Run corepack enable to use the correct version of pnpm (8.15.5) as specified in the root package.json file.

  5. Install the required packages using pnpm.

    pnpm i
    
  6. Create your .env file

    cp .env.example .env
    
  7. Open it and generate a new value for ENCRYPTION_KEY:

    ENCRYPTION_KEY is used to two-way encrypt OAuth access tokens and so you'll probably want to actually generate a unique value, and it must be a random 16 byte hex string. You can generate one with the following command:

    openssl rand -hex 16
    

    Feel free to update SESSION_SECRET and MAGIC_LINK_SECRET as well using the same method.

  8. Start Docker. This starts the required services like Postgres & Redis. If this is your first time using Docker, consider going through this guide

    pnpm run docker
    

    This will also start and run a local instance of pgAdmin on localhost:5480, preconfigured with email admin@example.com and pwd admin. Then use postgres as the password to the Trigger.dev server.

  9. Migrate the database

    pnpm run db:migrate
    
  10. Build the server app

    pnpm run build --filter webapp
    
  11. Run the app. See the section below.

Running

  1. You can run the app with:

    pnpm run dev --filter webapp
    

    It should run on port 3030: http://localhost:3030

  2. Once the app is running click the magic link button and enter your email. You will automatically be logged in, since you are running locally. Create an Org and your first project in the dashboard.

Manual testing using v3-catalog

We use the <root>/references/v3-catalog subdirectory as a staging ground for testing changes to the SDK (@trigger.dev/sdk at <root>/packages/trigger-sdk), the Core package (@trigger.dev/core at <root>packages/core), the CLI (trigger.dev at <root>/packages/cli-v3) and the platform (The remix app at <root>/apps/webapp). The instructions below will get you started on using the v3-catalog for local development of Trigger.dev (v3).

First-time setup

First, make sure you are running the webapp according to the instructions above. Then:

  1. In Postgres go to the "Organizations" table and on your org set the v3Enabled column to true.

  2. Visit http://localhost:3030 in your browser and create a new V3 project called "v3-catalog". If you don't see an option for V3, you haven't set the v3Enabled flag to true.

  3. In Postgres go to the "Projects" table and for the project you create change the externalRef to yubjwjsfkxnylobaqvqz.

  4. Build the CLI

# Build the CLI
pnpm run build --filter trigger.dev
# Make it accessible to `pnpm exec`
pnpm i
  1. Change into the <root>/references/v3-catalog directory and authorize the CLI to the local server:
cd references/v3-catalog
cp .env.example .env
pnpm exec trigger login -a http://localhost:3030

This will open a new browser window and authorize the CLI against your local user account.

You can optionally pass a --profile flag to the login command, which will allow you to use the CLI with separate accounts/servers. We suggest using a profile called local for your local development:

cd references/v3-catalog
pnpm exec trigger login -a http://localhost:3030 --profile local
# later when you run the dev or deploy command:
pnpm exec trigger dev --profile local
pnpm exec trigger deploy --profile local

Running

The following steps should be followed any time you start working on a new feature you want to test in v3:

  1. Make sure the webapp is running on localhost:3030

  2. Open a terminal window and build the CLI and watch for changes

pnpm run dev --filter trigger.dev
  1. Open a new terminal window, and anytime changes are made to the @trigger.dev/core package, you'll need to manually rebuild the CLI:
pnpm run build --filter trigger.dev

Note: You do not need to do the same for @trigger.dev/sdk, just core.

  1. Open another terminal window, and change into the <root>/references/v3-catalog directory.

  2. Run the dev command, which will register all the local tasks with the platform and allow you to start testing task execution:

# in <root>/references/v3-catalog
pnpm exec trigger dev

If you want additional debug logging, you can use the --log-level debug flag:

# in <root>/references/v3-catalog
pnpm exec trigger dev --log-level debug
  1. If you make any changes in the CLI/Core/SDK, you'll need to CTRL+C to exit the dev command and restart it to pickup changes. Any changes to the files inside of the v3-catalog/src/trigger dir will automatically be rebuilt by the dev command.

  2. Navigate to the v3-catalog project in your local dashboard at localhost:3030 and you should see the list of tasks.

  3. Go to the "Test" page in the sidebar and select a task. Then enter a payload and click "Run test". You can tell what the payloads should be by looking at the relevant task file inside the /references/v3-catalog/src/trigger folder. Many of them accept an empty payload.

  4. Feel free to add additional files in v3-catalog/src/trigger to test out specific aspects of the system, or add in edge cases.

Running end-to-end webapp tests (deprecated)

To run the end-to-end tests, follow the steps below:

  1. Set up environment variables (copy example envs into the correct place)
cp ./.env.example ./.env
cp ./references/nextjs-test/.env.example ./references/nextjs-test/.env.local
  1. Set up dependencies
# Build packages
pnpm run build --filter @references/nextjs-test^...
pnpm --filter @trigger.dev/database generate

# Move trigger-cli bin to correct place
pnpm install --frozen-lockfile

# Install playwrite browsers (ONE TIME ONLY)
npx playwright install
  1. Set up the database
pnpm run docker
pnpm run db:migrate
pnpm run db:seed
  1. Run the end-to-end tests
pnpm run test:e2e

Cleanup

The end-to-end tests use a setup and teardown script to seed the database with test data. If the test runner doesn't exit cleanly, then the database can be left in a state where the tests can't run because the setup script will try to create data that already exists. If this happens, you can manually delete the users and organizations from the database using prisma studio:

# With the database running (i.e. pnpm run docker)
pnpm run db:studio

Adding and running migrations

  1. Modify internal-packages/database/prisma/schema.prisma file

  2. Change directory to the packages/database folder

    cd packages/database
    
  3. Create a migration

    pnpm run db:migrate:dev:create
    

    This creates a migration file. Check the migration file does only what you want. If you're adding any database indexes they must use CONCURRENTLY, otherwise they'll lock the table when executed.

  4. Run the migration.

pnpm run db:migrate:deploy
pnpm run generate

This executes the migrations against your database and applies changes to the database schema(s), and then regenerates the Prisma client.

  1. Commit generated migrations as well as changes to the schema.prisma file
  2. If you're using VSCode you may need to restart the Typescript server in the webapp to get updated type inference. Open a TypeScript file, then open the Command Palette (View > Command Palette) and run TypeScript: Restart TS server.

Add sample jobs

The references/job-catalog project defines simple jobs you can get started with.

  1. cd into references/job-catalog
  2. Create a .env file with the following content, replacing <TRIGGER_DEV_API_KEY> with an actual key:
TRIGGER_API_KEY=[TRIGGER_DEV_API_KEY]
TRIGGER_API_URL=http://localhost:3030

TRIGGER_API_URL is used to configure the URL for your Trigger.dev instance, where the jobs will be registered.

  1. Run one of the the job-catalog files:
pnpm run events

This will open up a local server using express on port 8080. Then in a new terminal window you can run the trigger-cli dev command:

pnpm run dev:trigger

See the Job Catalog file for more.

  1. Navigate to your trigger.dev instance (http://localhost:3030), to see the jobs. You can use the test feature to trigger them.

Making a pull request

If you get errors, be sure to fix them before committing.

Adding changesets

We use changesets to manage our package versions and changelogs. If you've never used changesets before, first read their guide here.

If you are contributing a change to any packages in this monorepo (anything in either the /packages or /integrations directories), then you will need to add a changeset to your Pull Requests before they can be merged.

To add a changeset, run the following command in the root of the repo

pnpm run changeset:add

Here's an example of creating a patch changeset for the @trigger.dev/github and @trigger.dev/slack packages (click to view):

asciicast

You will be prompted to select which packages to include in the changeset. Only select the packages that you have made changes for.

Most of the time the changes you'll make are likely to be categorized as patch releases. If you feel like there is the need for a minor or major release of the package based on the changes being made, add the changeset as such and it will be discussed during PR review.

Troubleshooting

EADDRINUSE: address already in use :::3030

When receiving the following error message:

webapp:dev: Error: listen EADDRINUSE: address already in use :::3030

The process running on port 3030 should be destroyed.

  1. Get the PID of the process running on PORT 3030
    lsof -i :3030
    
  2. Kill the process
    sudo kill -9 <PID>