Scheduling infrastructure for absolutely everyone.
feat: Tasker (#14180)
Omar López5695ba7c1354
diff --git a/.env.example b/.env.exampleindex a01ef6cc4d5..644c8b24621 100644--- a/.env.example+++ b/.env.example@@ -240,7 +240,7 @@ CSP_POLICY=# Vercel Edge ConfigEDGE_CONFIG=-NEXT_PUBLIC_MINUTES_TO_BOOK=5 # Minutes+NEXT_PUBLIC_MINUTES_TO_BOOK=5 # MinutesNEXT_PUBLIC_BOOKER_NUMBER_OF_DAYS_TO_LOAD=0 # Override the booker to only load X number of days worth of data# Control time intervals on a user's Schedule availability@@ -347,6 +347,10 @@ SENTRY_DISABLE_SERVER_WEBPACK_PLUGIN=1# api v2NEXT_PUBLIC_API_V2_URL="http://localhost:5555/api/v2"+# Tasker features+TASKER_ENABLE_WEBHOOKS=0+TASKER_ENABLE_EMAILS=0+# Ratelimiting via unkeyUNKEY_ROOT_KEY=diff --git a/apps/api/v1/test/lib/bookings/_post.test.ts b/apps/api/v1/test/lib/bookings/_post.test.tsindex e34defc601f..93f0076c713 100644--- a/apps/api/v1/test/lib/bookings/_post.test.ts+++ b/apps/api/v1/test/lib/bookings/_post.test.ts@@ -7,7 +7,7 @@ import { createMocks } from "node-mocks-http";import { describe, expect, test, vi } from "vitest";import dayjs from "@calcom/dayjs";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import { ErrorCode } from "@calcom/lib/errorCodes";import { buildBooking, buildEventType, buildWebhook } from "@calcom/lib/test/builder";import prisma from "@calcom/prisma";diff --git a/apps/web/app/api/tasks/cleanup/route.ts b/apps/web/app/api/tasks/cleanup/route.tsnew file mode 100644index 00000000000..c7dfb287bef--- /dev/null+++ b/apps/web/app/api/tasks/cleanup/route.ts@@ -0,0 +1 @@+export { GET } from "@calcom/features/tasker/api/cleanup";diff --git a/apps/web/app/api/tasks/cron/route.ts b/apps/web/app/api/tasks/cron/route.tsnew file mode 100644index 00000000000..ca83c5331db--- /dev/null+++ b/apps/web/app/api/tasks/cron/route.ts@@ -0,0 +1 @@+export { GET } from "@calcom/features/tasker/api/cron";diff --git a/apps/web/pages/api/recorded-daily-video.ts b/apps/web/pages/api/recorded-daily-video.tsindex c1f4a980eef..bab8ed64df0 100644--- a/apps/web/pages/api/recorded-daily-video.ts+++ b/apps/web/pages/api/recorded-daily-video.ts@@ -6,7 +6,7 @@ import { z } from "zod";import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/core/videoClient";import { sendDailyVideoRecordingEmails } from "@calcom/emails";import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";import logger from "@calcom/lib/logger";import { safeStringify } from "@calcom/lib/safeStringify";diff --git a/apps/web/playwright/webhook.e2e.ts b/apps/web/playwright/webhook.e2e.tsindex 23d051c4db9..62c82182300 100644--- a/apps/web/playwright/webhook.e2e.ts+++ b/apps/web/playwright/webhook.e2e.ts@@ -8,16 +8,20 @@ import { BookingStatus } from "@calcom/prisma/client";import { test } from "./lib/fixtures";import {bookOptinEvent,+ bookTimeSlot,createHttpServer,- selectFirstAvailableTimeSlotNextMonth,- gotoRoutingLink,createUserWithSeatedEventAndAttendees,+ gotoRoutingLink,+ selectFirstAvailableTimeSlotNextMonth,} from "./lib/testUtils";// remove dynamic properties that differs depending on where you run the testsconst dynamic = "[redacted/dynamic]";-test.afterEach(({ users }) => users.deleteAll());+test.afterEach(async ({ users }) => {+ // This also delete forms on cascade+ await users.deleteAll();+});async function createWebhookReceiver(page: Page) {const webhookReceiver = createHttpServer();@@ -71,11 +75,7 @@ test.describe("BOOKING_CREATED", async () => {// --- Book the first available day next month in the pro user's "30min"-eventawait page.goto(`/${user.username}/${eventType.slug}`);await selectFirstAvailableTimeSlotNextMonth(page);-- // --- fill form- await page.fill('[name="name"]', "Test Testson");- await page.fill('[name="email"]', "[email protected]");- await page.press('[name="email"]', "Enter");+ await bookTimeSlot(page);await webhookReceiver.waitForRequestCount(1);diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 6f4decb2eec..df63e6dbb77 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -3,6 +3,14 @@{"path": "/api/cron/calendar-cache-cleanup","schedule": "0 5 * * *"+ },+ {+ "path": "/api/tasks/cron",+ "schedule": "* * * * *"+ },+ {+ "path": "/api/tasks/cleanup",+ "schedule": "0 0 * * *"}],"functions": {diff --git a/packages/features/bookings/lib/handleBookingRequested.ts b/packages/features/bookings/lib/handleBookingRequested.tsindex 579b2fd2373..0798191fe6e 100644--- a/packages/features/bookings/lib/handleBookingRequested.ts+++ b/packages/features/bookings/lib/handleBookingRequested.ts@@ -1,7 +1,7 @@import { sendAttendeeRequestEmail, sendOrganizerRequestEmail } from "@calcom/emails";import { getWebhookPayloadForBooking } from "@calcom/features/bookings/lib/getWebhookPayloadForBooking";import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import logger from "@calcom/lib/logger";import { safeStringify } from "@calcom/lib/safeStringify";import { WebhookTriggerEvents } from "@calcom/prisma/enums";diff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.tsindex 68fbad39466..9e66aa57cfe 100644--- a/packages/features/bookings/lib/handleCancelBooking.ts+++ b/packages/features/bookings/lib/handleCancelBooking.ts@@ -14,8 +14,8 @@ import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reimport { deleteScheduledWhatsappReminder } from "@calcom/features/ee/workflows/lib/reminders/whatsappReminderManager";import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";import { cancelScheduledJobs } from "@calcom/features/webhooks/lib/scheduleTrigger";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";import { HttpError } from "@calcom/lib/http-error";diff --git a/packages/features/bookings/lib/handleConfirmation.ts b/packages/features/bookings/lib/handleConfirmation.tsindex 748773613cb..d2c0f394a3a 100644--- a/packages/features/bookings/lib/handleConfirmation.ts+++ b/packages/features/bookings/lib/handleConfirmation.ts@@ -7,8 +7,8 @@ import { sendScheduledEmails } from "@calcom/emails";import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";import { scheduleTrigger } from "@calcom/features/webhooks/lib/scheduleTrigger";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";import logger from "@calcom/lib/logger";diff --git a/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.tsindex 667c5bbe4a8..91fe47308e0 100644--- a/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts+++ b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts@@ -4,8 +4,8 @@ import { sendCancelledSeatEmails } from "@calcom/emails";import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager";import { deleteScheduledWhatsappReminder } from "@calcom/features/ee/workflows/lib/reminders/whatsappReminderManager";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";import { HttpError } from "@calcom/lib/http-error";import { getTranslation } from "@calcom/lib/server/i18n";import prisma from "@calcom/prisma";diff --git a/packages/features/bookings/lib/handleWebhookTrigger.ts b/packages/features/bookings/lib/handleWebhookTrigger.tsindex 7b510c820ae..dbbcaaf75f9 100644--- a/packages/features/bookings/lib/handleWebhookTrigger.ts+++ b/packages/features/bookings/lib/handleWebhookTrigger.ts@@ -1,7 +1,7 @@import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import type { WebhookDataType } from "@calcom/features/webhooks/lib/sendPayload";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";import logger from "@calcom/lib/logger";export async function handleWebhookTrigger(args: {diff --git a/packages/features/tasker/README.md b/packages/features/tasker/README.mdnew file mode 100644index 00000000000..91f31d6b3ce--- /dev/null+++ b/packages/features/tasker/README.md@@ -0,0 +1,91 @@+# Tasker++Tasker: "One who performs a task, as a day-laborer."++Task: "A function to be performed; an objective."++## What is it?++Introduces a new pattern called Tasker which may be switched out in the future for other third party services.++Also introduces a base `InternalTasker` which doesn't require third party dependencies and should work out of the box (by configuring a proper cron).++## Why is this needed?++The Tasker pattern is needed to streamline the execution of non-critical tasks in an application, providing a structured approach to task scheduling, execution, retrying, and cancellation. Here's why it's necessary:++1. **Offloading non-critical tasks**: There are tasks that don't need to be executed immediately on the main thread, such as sending emails, generating reports, or performing periodic maintenance tasks. Offloading these tasks to a separate queue or thread improves the responsiveness and efficiency of the main application.++2. **Retry mechanism**: Not all tasks succeed on the first attempt due to errors or external dependencies. This pattern incorporates a retry mechanism, which allows failed tasks to be retried automatically for a specified number of attempts. This improves the robustness of the system by handling temporary failures gracefully.++3. **Scheduled task execution**: Some tasks need to be executed at a specific time or after a certain delay. The Tasker pattern facilitates scheduling tasks for future execution, ensuring they are performed at the designated time without manual intervention.++4. **Task cancellation**: Occasionally, it's necessary to cancel a scheduled task due to changing requirements or user actions. The Tasker pattern supports task cancellation, enabling previously scheduled tasks to be revoked or removed from the queue before execution.++5. **Flexible implementation**: The Tasker pattern allows for flexibility in implementation by providing a base structure (`InternalTasker`) that can be extended or replaced with third-party services (`TriggerDevTasker`, `AwsSqsTasker`, etc.). This modularity ensures that the task execution mechanism can be adapted to suit different application requirements or environments.++Overall, the Tasker pattern enhances the reliability, performance, and maintainability by managing non-critical tasks in a systematic and efficient manner. It abstracts away the complexities of task execution, allowing developers to focus on core application logic while ensuring timely and reliable execution of background tasks.++## How does it work?++Since the Tasker is a pattern on itself, it will depend on the actual implementation. For example, a `TriggerDevTasker` will work very differently from an `AwsSqsTasker`.++For simplicity sake will explain how the `InternalTasker` works:++- Instead of running a non-critical task you schedule using the tasker:++ ```diff+ const examplePayload = { example: "payload" };+ - await sendWebhook(examplePayload);+ + await tasker.create("sendWebhook", JSON.stringify(examplePayload));+ ```++- This will create a new task to be run on the next processing of the task queue.+- Then on the next cron run it will be picked up and executed:++ ```ts+ // /app/api/tasks/cron/route.ts+ import tasker from "@calcom/features/tasker";++ export async function GET() {+ // authenticate the call...+ await tasker.processQueue();+ return Response.json({ success: true });+ }+ ```++- By default, the cron will run each minute and will pick the next 100 tasks to be executed.+- If the tasks succeeds, it will be marked as `suceededAt: new Date()`. If if fails, the `attempts` prop will increase by 1 and will be retried on the next cron run.+- If `attempts` reaches `maxAttemps`, it will be considered a failed and won't be retried again.+- By default, tasks will be attempted up to 3 times. This can be overridden when creating a task.+- From here we can either keep a record of executed tasks, or we can setup another cron to cleanup all successful and failed tasks:++ ```ts+ // /app/api/tasks/cleanup/route.ts+ import tasker from "@calcom/features/tasker";++ export async function GET() {+ // authenticate the call...+ await tasker.cleanup();+ return Response.json({ success: true });+ }+ ```++- This will delete all failed and successful tasks.+- A task is just a simple function receives a payload:++ ```ts+ type TaskHandler = (payload: string) => Promise<void>;+ ```++## How to contribute?++You can contribute by either expanding the `InternalTasker` or creating new Taskers. To see how to add new Taskers, see the `tasker-factory.ts` file.++You can also take some inspiration by looking into previous attempts to add various Message Queue pull requests:++- [feat: Messaging Bus Implementation using AWS SQS OSSHack Challenge](https://github.com/calcom/cal.com/pull/12663)+- [feat: add opt-in ready-to-deploy message queue (QStash+Next.js functions)](https://github.com/calcom/cal.com/pull/12658)+- [feat: Implement A Message Queuing System](https://github.com/calcom/cal.com/pull/12655)+- [Message Queuing System](https://github.com/calcom/cal.com/pull/12654)+- [feat: Message Queuing System using Trigger.dev](https://github.com/calcom/cal.com/pull/12641)diff --git a/packages/features/tasker/api/cleanup.ts b/packages/features/tasker/api/cleanup.tsnew file mode 100644index 00000000000..c0a5d2fe904--- /dev/null+++ b/packages/features/tasker/api/cleanup.ts@@ -0,0 +1,13 @@+import type { NextRequest } from "next/server";+import { NextResponse } from "next/server";++import tasker from "..";++export async function GET(request: NextRequest) {+ const authHeader = request.headers.get("authorization");+ if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {+ return new Response("Unauthorized", { status: 401 });+ }+ await tasker.cleanup();+ return NextResponse.json({ success: true });+}diff --git a/packages/features/tasker/api/cron.ts b/packages/features/tasker/api/cron.tsnew file mode 100644index 00000000000..f0f28296985--- /dev/null+++ b/packages/features/tasker/api/cron.ts@@ -0,0 +1,13 @@+import type { NextRequest } from "next/server";+import { NextResponse } from "next/server";++import tasker from "..";++export async function GET(request: NextRequest) {+ const authHeader = request.headers.get("authorization");+ if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {+ return new Response("Unauthorized", { status: 401 });+ }+ await tasker.processQueue();+ return NextResponse.json({ success: true });+}diff --git a/packages/features/tasker/index.ts b/packages/features/tasker/index.tsnew file mode 100644index 00000000000..364fee22afc--- /dev/null+++ b/packages/features/tasker/index.ts@@ -0,0 +1,14 @@+import type { Tasker } from "./tasker";+import { getTasker } from "./tasker-factory";++const globalForTasker = global as unknown as {+ tasker: Tasker;+};++export const tasker = globalForTasker.tasker || getTasker();++if (process.env.NODE_ENV !== "production") {+ globalForTasker.tasker = tasker;+}++export default tasker;diff --git a/packages/features/tasker/internal-tasker.ts b/packages/features/tasker/internal-tasker.tsnew file mode 100644index 00000000000..3e18193070a--- /dev/null+++ b/packages/features/tasker/internal-tasker.ts@@ -0,0 +1,38 @@+import { Task } from "./repository";+import { type Tasker, type TaskTypes } from "./tasker";+import tasksMap from "./tasks";++/**+ * This is the default internal Tasker that uses the Task repository to create tasks.+ * It doens't have any external dependencies and is suitable for most use cases.+ * To use a different Tasker, you can create a new class that implements the Tasker interface.+ * Then, you can use the TaskerFactory to select the new Tasker.+ */+export class InternalTasker implements Tasker {+ async create(type: TaskTypes, payload: string): Promise<string> {+ return Task.create(type, payload);+ }+ async processQueue(): Promise<void> {+ const tasks = await Task.getNextBatch();+ const tasksPromises = tasks.map(async (task) => {+ const taskHandlerGetter = tasksMap[task.type as keyof typeof tasksMap];+ if (!taskHandlerGetter) throw new Error(`Task handler not found for type ${task.type}`);+ const taskHandler = await taskHandlerGetter();+ return taskHandler(task.payload)+ .then(async () => {+ await Task.succeed(task.id);+ })+ .catch(async (error) => {+ await Task.retry(task.id, error instanceof Error ? error.message : "Unknown error");+ });+ });+ const settled = await Promise.allSettled(tasksPromises);+ const failed = settled.filter((result) => result.status === "rejected");+ const succeded = settled.filter((result) => result.status === "fulfilled");+ console.info({ failed, succeded });+ }+ async cleanup(): Promise<void> {+ const count = await Task.cleanup();+ console.info(`Cleaned up ${count} tasks`);+ }+}diff --git a/packages/features/tasker/redis-tasker.ts b/packages/features/tasker/redis-tasker.tsnew file mode 100644index 00000000000..a9e29a41dfc--- /dev/null+++ b/packages/features/tasker/redis-tasker.ts@@ -0,0 +1,19 @@+import { type Tasker, type TaskTypes } from "./tasker";++/**+ * RedisTasker is a tasker that uses Redis as a backend.+ * WIP: This is a work in progress and is not fully implemented yet.+ **/+export class RedisTasker implements Tasker {+ async create(type: TaskTypes, payload: string): Promise<string> {+ throw new Error("Method not implemented.");+ }++ processQueue(): Promise<void> {+ throw new Error("Method not implemented.");+ }++ cleanup(): Promise<void> {+ throw new Error("Method not implemented.");+ }+}diff --git a/packages/features/tasker/repository.ts b/packages/features/tasker/repository.tsnew file mode 100644index 00000000000..687eaa29cfc--- /dev/null+++ b/packages/features/tasker/repository.ts@@ -0,0 +1,148 @@+import { type Prisma } from "@prisma/client";++import db from "@calcom/prisma";++import { type TaskTypes } from "./tasker";++const whereSucceeded: Prisma.TaskWhereInput = {+ succeededAt: { not: null },+};++const whereMaxAttemptsReached: Prisma.TaskWhereInput = {+ attempts: {+ equals: {+ // @ts-expect-error prisma is tripping: '_ref' does not exist in type 'FieldRef<"Task", "Int">'+ _ref: "maxAttempts",+ _container: "Task",+ },+ },+};++const whereUpcomingTasks: Prisma.TaskWhereInput = {+ // Get only tasks that have not succeeded yet+ succeededAt: null,+ // Get only tasks that are scheduled to run now or in the past+ scheduledAt: {+ lt: new Date(),+ },+ // Get only tasks where maxAttemps has not been reached+ attempts: {+ lt: {+ // @ts-expect-error prisma is tripping: '_ref' does not exist in type 'FieldRef<"Task", "Int">'+ _ref: "maxAttempts",+ _container: "Task",+ },+ },+};++export class Task {+ static async create(+ type: TaskTypes,+ payload: string,+ options: { scheduledAt?: Date; maxAttempts?: number } = {}+ ) {+ const { scheduledAt, maxAttempts } = options;+ const newTask = await db.task.create({+ data: {+ payload,+ type,+ scheduledAt,+ maxAttempts,+ },+ });+ return newTask.id;+ }++ static async getNextBatch() {+ return db.task.findMany({+ where: whereUpcomingTasks,+ orderBy: {+ scheduledAt: "asc",+ },+ take: 100,+ });+ }++ static async getAll() {+ return db.task.findMany();+ }++ static async getFailed() {+ return db.task.findMany({+ where: whereMaxAttemptsReached,+ });+ }++ static async getSucceeded() {+ return db.task.findMany({+ where: whereSucceeded,+ });+ }++ static async count() {+ return db.task.count();+ }++ static async countUpcoming() {+ return db.task.count({+ where: whereUpcomingTasks,+ });+ }++ static async countFailed() {+ return db.task.count({+ where: whereMaxAttemptsReached,+ });+ }++ static async countSucceeded() {+ return db.task.count({+ where: whereSucceeded,+ });+ }++ static async retry(taskId: string, lastError?: string) {+ return db.task.update({+ where: {+ id: taskId,+ },+ data: {+ attempts: { increment: 1 },+ lastError,+ },+ });+ }++ static async succeed(taskId: string) {+ return db.task.update({+ where: {+ id: taskId,+ },+ data: {+ attempts: { increment: 1 },+ succeededAt: new Date(),+ },+ });+ }++ static async cancel(taskId: string) {+ return db.task.delete({+ where: {+ id: taskId,+ },+ });+ }++ static async cleanup() {+ return db.task.deleteMany({+ where: {+ OR: [+ // Get tasks that have succeeded+ whereSucceeded,+ // Get tasks where maxAttemps has been reached+ whereMaxAttemptsReached,+ ],+ },+ });+ }+}diff --git a/packages/features/tasker/tasker-factory.ts b/packages/features/tasker/tasker-factory.tsnew file mode 100644index 00000000000..c023c88312f--- /dev/null+++ b/packages/features/tasker/tasker-factory.ts@@ -0,0 +1,27 @@+import { InternalTasker } from "./internal-tasker";+// import { RedisTasker } from "./redis-tasker";+import { type Tasker, type TaskerTypes } from "./tasker";++/**+ * This is a factory class that creates Taskers.+ * The TaskerFactory is useful when you want to use a different Tasker in different environments.+ * For example, you can use the InternalTasker in development and the AWSSQSTasker in production.+ */+export class TaskerFactory {+ createTasker(type?: TaskerTypes): Tasker {+ // TODO: Add more alternative Taskers in the future:+ // RedisTasker, TriggerDevTasker, TemporalIOTasker, AWSSQSTasker, etc.+ // TODO: Uncomment the following line when RedisTasker is implemented.+ // if (type === "redis") return new RedisTasker();+ // For now, we only have the InternalTasker.+ if (type === "internal") return new InternalTasker();+ // Default to InternalTasker+ return new InternalTasker();+ }+}++/** Shorthand for getting the default Tasker */+export function getTasker() {+ const taskerFactory = new TaskerFactory();+ return taskerFactory.createTasker();+}diff --git a/packages/features/tasker/tasker.ts b/packages/features/tasker/tasker.tsnew file mode 100644index 00000000000..9659632a4b3--- /dev/null+++ b/packages/features/tasker/tasker.ts@@ -0,0 +1,9 @@+export type TaskerTypes = "internal" | "redis";+export type TaskTypes = "sendEmail" | "sendWebhook" | "sendSms";+export type TaskHandler = (payload: string) => Promise<void>;+export interface Tasker {+ /** Create a new task with the given type and payload. */+ create(type: TaskTypes, payload: string): Promise<string>;+ processQueue(): Promise<void>;+ cleanup(): Promise<void>;+}diff --git a/packages/features/tasker/tasks/index.ts b/packages/features/tasker/tasks/index.tsnew file mode 100644index 00000000000..2e688090e72--- /dev/null+++ b/packages/features/tasker/tasks/index.ts@@ -0,0 +1,14 @@+import type { TaskHandler, TaskTypes } from "../tasker";++/**+ * This is a map of all the tasks that the Tasker can handle.+ * The keys are the TaskTypes and the values are the task handlers.+ * The task handlers are imported dynamically to avoid circular dependencies.+ */+const tasks: Record<TaskTypes, () => Promise<TaskHandler>> = {+ sendEmail: () => import("./sendEmail").then((module) => module.sendEmail),+ sendWebhook: () => import("./sendWebook").then((module) => module.sendWebhook),+ sendSms: () => Promise.resolve(() => Promise.reject(new Error("Not implemented"))),+};++export default tasks;diff --git a/packages/features/tasker/tasks/sendEmail.ts b/packages/features/tasker/tasks/sendEmail.tsnew file mode 100644index 00000000000..1634411d470--- /dev/null+++ b/packages/features/tasker/tasks/sendEmail.ts@@ -0,0 +1,25 @@+import { z } from "zod";++const sendEmailPayloadSchema = z.object({+ /** */+ to: z.string(),+ /** The email template to send */+ template: z.string(),+ payload: z.string(),+});++export async function sendEmail(payload: string): Promise<void> {+ try {+ const parsedPayload = sendEmailPayloadSchema.parse(JSON.parse(payload));+ console.log(parsedPayload);+ const emails = await import("@calcom/emails");+ const email = emails[parsedPayload.template as keyof typeof emails];+ if (!email) throw new Error("Invalid email template");+ // @ts-expect-error - TODO bring back email type safety+ await email(parsedPayload.to);+ } catch (error) {+ // ... handle error+ console.error(error);+ throw error;+ }+}diff --git a/packages/features/tasker/tasks/sendWebook.ts b/packages/features/tasker/tasks/sendWebook.tsnew file mode 100644index 00000000000..b8bdb699548--- /dev/null+++ b/packages/features/tasker/tasks/sendWebook.ts@@ -0,0 +1,29 @@+import { z } from "zod";++import sendPayload from "@calcom/features/webhooks/lib/sendPayload";++const sendWebhookPayloadSchema = z.object({+ secretKey: z.string().nullable(),+ triggerEvent: z.string(),+ createdAt: z.string(),+ webhook: z.object({+ subscriberUrl: z.string().url(),+ appId: z.string().nullable(),+ payloadTemplate: z.string().nullable(),+ }),+ // TODO: Define the data schema+ data: z.any(),+});++export async function sendWebhook(payload: string): Promise<void> {+ try {+ const { secretKey, triggerEvent, createdAt, webhook, data } = sendWebhookPayloadSchema.parse(+ JSON.parse(payload)+ );+ await sendPayload(secretKey, triggerEvent, createdAt, webhook, data);+ } catch (error) {+ // ... handle error+ console.error(error);+ throw error;+ }+}diff --git a/packages/features/webhooks/lib/schedulePayload.ts b/packages/features/webhooks/lib/schedulePayload.tsnew file mode 100644index 00000000000..d36a304f89b--- /dev/null+++ b/packages/features/webhooks/lib/schedulePayload.ts@@ -0,0 +1,16 @@+import tasker from "@calcom/features/tasker";++import type sendPayload from "./sendPayload";++type SchedulePayload = typeof sendPayload;++const schedulePayload: SchedulePayload = async (secretKey, triggerEvent, createdAt, webhook, data) => {+ await tasker.create("sendWebhook", JSON.stringify({ secretKey, triggerEvent, createdAt, webhook, data }));+ return {+ ok: true,+ status: 200,+ message: "Webhook scheduled successfully",+ };+};++export default schedulePayload;diff --git a/packages/features/webhooks/lib/sendOrSchedulePayload.ts b/packages/features/webhooks/lib/sendOrSchedulePayload.tsnew file mode 100644index 00000000000..a8928311b0d--- /dev/null+++ b/packages/features/webhooks/lib/sendOrSchedulePayload.ts@@ -0,0 +1,12 @@+import schedulePayload from "./schedulePayload";+import sendPayload from "./sendPayload";++type SendOrSchedulePayload = typeof sendPayload;++const sendOrSchedulePayload: SendOrSchedulePayload = async (...args) => {+ // If Tasker is enabled, schedule the payload instead of sending it immediately+ if (process.env.TASKER_ENABLE_WEBHOOKS === "1") return schedulePayload(...args);+ return sendPayload(...args);+};++export default sendOrSchedulePayload;diff --git a/packages/prisma/migrations/20240327153218_adds_tasker_feature/migration.sql b/packages/prisma/migrations/20240327153218_adds_tasker_feature/migration.sqlnew file mode 100644index 00000000000..be8f3b8ed3d--- /dev/null+++ b/packages/prisma/migrations/20240327153218_adds_tasker_feature/migration.sql@@ -0,0 +1,18 @@+-- CreateTable+CREATE TABLE "Task" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,+ "scheduledAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "succeededAt" TIMESTAMP(3),+ "type" TEXT NOT NULL,+ "payload" TEXT NOT NULL,+ "attempts" INTEGER NOT NULL DEFAULT 0,+ "maxAttempts" INTEGER NOT NULL DEFAULT 3,+ "lastError" TEXT,++ CONSTRAINT "Task_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "Task_id_key" ON "Task"("id");diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 7b4a84f15e8..2c1c38d0108 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -1326,3 +1326,23 @@ model SecondaryEmail {@@unique([userId, email])@@index([userId])}++// Needed to store tasks that need to be processed by a background worker or Tasker+model Task {+ id String @id @unique @default(uuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ // The time at which the task should be executed+ scheduledAt DateTime @default(now())+ // The time at which the task was successfully executed+ succeededAt DateTime?+ // The task type to be executed. Left it as a freeform string to avoid more migrations for now. Will be enforced at type level.+ type String+ // Generic payload for the task+ payload String+ // The number of times the task has been attempted+ attempts Int @default(0)+ // The maximum number of times the task can be attempted+ maxAttempts Int @default(3)+ lastError String?+}diff --git a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.tsindex a0bf49a47d8..2de95d325da 100644--- a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts+++ b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts@@ -13,7 +13,7 @@ import { sendRequestRescheduleEmail } from "@calcom/emails";import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";import { cancelScheduledJobs } from "@calcom/features/webhooks/lib/scheduleTrigger";-import sendPayload from "@calcom/features/webhooks/lib/sendPayload";+import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";import { isPrismaObjOrUndefined } from "@calcom/lib";import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";diff --git a/turbo.json b/turbo.jsonindex 199880e8a57..91293f7a400 100644--- a/turbo.json+++ b/turbo.json@@ -250,6 +250,7 @@"CI","CLOSECOM_API_KEY","CRON_API_KEY",+ "CRON_SECRET","CRON_ENABLE_APP_SYNC","CLOUDFLARE_TURNSTILE_SECRET","DAILY_API_KEY",@@ -368,6 +369,7 @@"TANDEM_BASE_URL","TANDEM_CLIENT_ID","TANDEM_CLIENT_SECRET",+ "TASKER_ENABLE_WEBHOOKS","TEAM_ID_VERCEL","TELEMETRY_DEBUG","TWILIO_MESSAGING_SID",diff --git a/yarn.lock b/yarn.lockindex 7519f408640..f85fd061062 100644--- a/yarn.lock+++ b/yarn.lock@@ -32976,6 +32976,15 @@ __metadata:languageName: nodelinkType: hard+"lucide-react@npm:^0.363.0":+ version: 0.363.0+ resolution: "lucide-react@npm:0.363.0"+ peerDependencies:+ react: ^16.5.1 || ^17.0.0 || ^18.0.0+ checksum: abe8fad469a2f14181eca6f3682403c5d53a4a354f333b0f7d3b575471d451c6f3fd36f59d96745a5a823e4cc55eeb2dcda70774a6fe438834ea3fb6fa5b75af+ languageName: node+ linkType: hard+"luxon@npm:3.3.0":version: 3.3.0resolution: "luxon@npm:3.3.0"