npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@convex-dev/workflow

v0.1.3

Published

Convex component for durably executing workflows.

Downloads

717

Readme

Convex Workflow

npm version

Note: Convex Components are currently in beta.

Have you ever wanted to sleep for 7 days within a Convex function? Find yourself in callback hell chaining together function calls through queues? Sick of manual state management and scheduling in long-lived workflows? Convex workflows might just be what you're looking for.

import { WorkflowManager } from "@convex-dev/workflow";
import { components } from "./_generated/server";

export const workflow = new WorkflowManager(components.workflow);

export const exampleWorkflow = workflow.define({
  args: {
    storageId: v.id("_storage"),
  },
  handler: async (step, args) => {
    const transcription = await step.runAction(
      internal.index.computeTranscription,
      { storageId: args.storageId },
    );

    // Sleep for a month after computing the transcription.
    await step.sleep(30 * 24 * 60 * 60 * 1000);

    const embedding = await step.runAction(internal.index.computeEmbedding, {
      transcription,
    });
    console.log(embedding);
  },
});

This component adds durably executed workflows to Convex. Combine Convex queries, mutations, and actions into long-lived workflows, and the system will always fully execute a workflow to completion.

This component is currently in beta and may have some rough edges. Open a GitHub issue with any feedback or bugs you find.

Installation

First, add @convex-dev/workflow to your Convex project:

npm install @convex-dev/workflow

Then, install the component within your convex/convex.config.ts file:

// convex/convex.config.ts
import workflow from "@convex-dev/workflow/convex.config";
import { defineApp } from "convex/server";

const app = defineApp();
app.use(workflow);
export default app;

Finally, create a workflow manager within your convex/ folder, and point it to the installed component:

// convex/index.ts
import { WorkflowManager } from "@convex-dev/workflow";
import { components } from "./_generated/server";

export const workflow = new WorkflowManager(components.workflow);

Usage

The first step is to define a workflow using workflow.define(). This function is designed to feel like a Convex action but with a few restrictions:

  1. The workflow runs in the background, so it can't return a value.
  2. The workflow must be deterministic, so it should implement most of its logic by calling out to other Convex functions. We will be lifting some of these restrictions over time by implementing Math.random(), Date.now(), and fetch within our workflow environment.
export const exampleWorkflow = workflow.define({
  args: { name: v.string() },
  handler: async (step, args) => {
    const queryResult = await step.runQuery(
      internal.example.exampleQuery,
      args,
    );
    const actionResult = await step.runAction(
      internal.example.exampleAction,
      args,
    );
    console.log(queryResult, actionResult);
  },
});

export const exampleQuery = internalQuery({
  args: { name: v.string() },
  handler: async (ctx, args) => {
    return `The query says... Hi ${args.name}!`;
  },
});

export const exampleAction = internalAction({
  args: { name: v.string() },
  handler: async (ctx, args) => {
    return `The action says... Hi ${args.name}!`;
  },
});

Once you've defined a workflow, you can start it from a mutation or action using workflow.start().

export const kickoffWorkflow = mutation({
  handler: async (ctx) => {
    const workflowId = await workflow.start(
      ctx,
      internal.example.exampleWorkflow,
      {
        name: "James",
      },
    );
  },
});

The workflow.start() method returns a WorkflowId, which can then be used for querying a workflow's status.

export const kickoffWorkflow = action({
  handler: async (ctx) => {
    const workflowId = await workflow.start(
      ctx,
      internal.example.exampleWorkflow,
      {
        name: "James",
      },
    );
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const status = await workflow.status(ctx, workflowId);
    console.log("Workflow status after 1s", status);
  },
});

You can also cancel a workflow with workflow.cancel(), halting the workflow's execution immmediately. In-progress calls to step.runAction(), however, only have best-effort cancelation.

export const kickoffWorkflow = action({
  handler: async (ctx) => {
    const workflowId = await workflow.start(
      ctx,
      internal.example.exampleWorkflow,
      {
        name: "James",
      },
    );
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // Cancel the workflow after 1 second.
    await workflow.cancel(ctx, workflowId);
  },
});

After a workflow has completed, you can clean up its storage with workflow.cleanup(). Completed workflows are not automatically cleaned up by the system.

export const kickoffWorkflow = action({
  handler: async (ctx) => {
    const workflowId = await workflow.start(
      ctx,
      internal.example.exampleWorkflow,
      {
        name: "James",
      },
    );
    try {
      while (true) {
        const status = await workflow.status(ctx, workflowId);
        if (status.type === "inProgress") {
          await new Promise((resolve) => setTimeout(resolve, 1000));
          continue;
        }
        console.log("Workflow completed with status:", status);
        break;
      }
    } finally {
      await workflow.cleanup(ctx, workflowId);
    }
  },
});

Limitations

Convex workflows is a beta product currently under active development. Here are a few limitations to keep in mind:

  • Steps can only take in and return a total of 1 MiB of data within a single workflow execution. If you run into journal size limits, you can work around this by storing results within your worker functions and then passing IDs around within the the workflow.
  • console.log() isn't currently captured, so you may see duplicate log lines within your Convex dashboard.
  • We currently do not collect backtraces from within function calls from workflows.
  • If you need to use side effects like fetch, Math.random(), or Date.now(), you'll need to define a separate Convex action, perform the side effects there, and then call that action from the workflow with step.runAction().
  • If the implementation of the workflow meaningfully changes (steps added, removed, or reordered) then it will fail with a determinism violation. The implementation should stay stable for the lifetime of active workflows.