7.69.4 • Published 2 days ago

@tsed/temporal v7.69.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 days ago

A package of Ts.ED framework. See website: https://tsed.io

Feature

Temporal lets you write complex asynchronous distributed workflows using easy to read linear code. For more information about Temporal take a look at the documentation here.

The @tsed/temporal module allows you to decorate classes with @Temporal and corresponding methods with @Activity to write and start asynchronous workflows.

Inject the TemporalClient to start/schedule and query workflows or to send signals to them.

Use the bootstrapWorker helper to start a queue that executes your workflows and activities.

Installation

To begin, install the Temporal module for Ts.ED:

npm install --save @tsed/temporal
npm install --save @temporalio/client @temporalio/worker

Configure your server

Import @tsed/temporal in your Server:

import {Configuration} from "@tsed/common";
import "@tsed/temporal"; // import temporal ts.ed module

@Configuration({
  temporal: {
    enabled: true,
    connection: {
      /* optional: see ConnectionOptions of @temporalio/client */
    },
    client: {
      /* optional: see ClientOptions of @temporalio/client */
    }
  }
})
export class Server {}

Create a new Service

Decorate the class with @Temporal.

Use the @Activity decorator to define activities.

import {Temporal, Activity} from "@tsed/temporal";

@Temporal()
export class UserOnboardingActivities {
  constructor(private userService: UserService, private emailService: EmailService) {}

  @Activity()
  async sendVerificationEmail(email: string) {
    return this.emailService.sendVerificationEmail(email);
  }

  @Activity()
  async activateUser(email: string) {
    return this.userService.activateUser(email);
  }

  @Activity()
  async sendWelcomeEmail(email: string) {
    return this.emailService.sendWelcomeEmail(email);
  }

  @Activity()
  async sendFollowUpEmail(email: string) {
    return this.emailService.sendFollowUpEmail(email);
  }

  @Activity()
  async deleteUser(email: string) {
    return this.userService.deleteUser(email);
  }
}

Optional, create an interface for your activities to use it later for your workflows.

interface IUserOnboardingActivities {
  sendVerificationEmail(email: string): Promise<void>;
  activateUser(email: string): Promise<void>;
  sendWelcomeEmail(email: string): Promise<void>;
  sendFollowUpEmail(email: string): Promise<void>;
  deleteUser(email: string): Promise<void>;
}

export type Activities = IGreetingActivity;

Write Workflows

Workflows are regular functions that cannot interact directly with Ts.ED or other packages. Just the earlier created interface is used for type-safety.

::: warning Do not import any non temporal packages here. The workflows are bundled internally by the worker and won't have access to anything else. :::

import {proxyActivities, defineSignal, setHandler, condition, sleep} from "@temporalio/workflow";
import {Activities} from "../activities";

export const isVerifiedSignal = defineSignal("verificationSignal");

export async function onboardUser(email: string): Promise<string> {
  const {sendVerificationEmail, activateUser, sendWelcomeEmail, sendFollowUpEmail, deleteUser} = proxyActivities<Activities>({
    startToCloseTimeout: "1 minute"
  });

  let isVerified = false;
  setHandler(isVerifiedSignal, () => {
    isVerified = true;
  });

  // 1. Send verification email
  await sendVerificationEmail(email);

  // 2. Wait for verification ...
  const verifiedInTime = await condition(() => isVerified, "1w" /* or for a timeout */);
  if (!verifiedInTime) {
    // 3a. If not verified in time, delete user
    await deleteUserAndTenant(email);
    return false;
  }

  // 3b. If verified in time, send welcome email
  await sendWelcomeEmail(email);

  // 4. Send follow up email after one day
  await sleep("1d"); // special sleep function by temporal
  await sendFollowUpEmail(email);
}

Inject TemporalClient

Inject the TemporalClient instance to interact with it directly, e.g. to start a workflow.

import {Service, AfterRoutesInit} from "@tsed/common";
import {TemporalClient} from "@tsed/temporal";
import {onboardUser} from "../workflows";

@Service()
export class UsersService implements AfterRoutesInit {
  @Inject()
  private temporalClient: TemporalClient;

  async create(user: User): Promise<User> {
    // ...
    await this.temporalClient.workflow.start(onboardUser, {
      args: [user.email],
      taskQueue: "onboarding",
      workflowId: `onboarding-${user.id}`
    });
  }
}

Start a worker

The workflows and activities won't get executed until you start a worker. This module provides a helper function to bootstrap a worker based on your Ts.ED server class that is aware of all your activities.

The most tricky part is the workflowsPath parameter. This is the path of the file/folder where the workflows are exported. The file is automatically loaded when the worker is started and internally bundled with webpack. The path is highly dependent on your project structure and build process.

Read more about it here.

import {bootstrapWorker} from "@tsed/temporal";
import {Server} from "./app/Server";

const worker = await bootstrapWorker(Server, {
  worker: {
    taskQueue: "onboarding",
    workflowsPath: require.resolve("./temporal") // other example: path.join(process.cwd(), 'dist/apps/api/temporal/index.ts');
  },
  connection: {
    /* optional: see NativeConnectionOptions of @temporalio/worker */
  },
  platform: {
    /* optional: see PlatformBuilderSettings of @tsed/common */
    componentsScan: false,
    logger: {
      level: "info"
    }
  }
});
await worker.run();

Contributors

Please read contributing guidelines here

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

The MIT License (MIT)

Copyright (c) 2016 - 2021 Romain Lenzotti

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

7.69.4

2 days ago

7.69.3

4 days ago

7.69.2

8 days ago

7.69.1

9 days ago

7.69.0

9 days ago

7.68.6

10 days ago

7.68.4

14 days ago

7.68.5

14 days ago

7.68.3

20 days ago

7.68.2

21 days ago

7.68.0

22 days ago

7.68.1

22 days ago

7.67.8

24 days ago

7.67.7

24 days ago

7.67.6

27 days ago

7.67.5

1 month ago

7.67.4

2 months ago

7.67.3

2 months ago

7.67.1

2 months ago

7.67.2

2 months ago

7.67.0

2 months ago

7.66.0

2 months ago

7.65.0

2 months ago

7.63.3

2 months ago

7.64.0

2 months ago

7.63.2

2 months ago

7.63.1

2 months ago

7.63.0

2 months ago

7.62.3

2 months ago

7.62.2

3 months ago

7.62.1

3 months ago

7.62.0

3 months ago

7.61.2

3 months ago

7.61.1

3 months ago

7.61.0

4 months ago

7.60.1

4 months ago

7.60.0

4 months ago

7.58.0

4 months ago

7.59.0

4 months ago

7.59.1

4 months ago

7.57.1

4 months ago

7.56.0

4 months ago

7.57.0

4 months ago

7.55.0

5 months ago

7.54.0

5 months ago

7.53.0

5 months ago

7.52.0

5 months ago

7.51.2

5 months ago

7.51.1

5 months ago

7.49.0

6 months ago

7.50.0

6 months ago

7.51.0

6 months ago

7.48.0

6 months ago

7.47.1

6 months ago

7.47.0

6 months ago

7.46.0

6 months ago

7.45.0

6 months ago

7.44.1

6 months ago

7.44.0

6 months ago

7.43.2

6 months ago

7.43.1

6 months ago

7.43.0

7 months ago

7.42.0

7 months ago

7.41.2

7 months ago

7.41.1

7 months ago

7.41.0

7 months ago

7.40.0

7 months ago

7.39.1

7 months ago

7.39.0

7 months ago

7.38.1

7 months ago

7.38.0

7 months ago

7.37.0

7 months ago