|
| 1 | +import { Or } from '@hatchet-dev/typescript-sdk/v1/conditions'; |
| 2 | +import { durationToMs } from '@hatchet-dev/typescript-sdk/v1/client/duration'; |
| 3 | +import { hatchet } from '../hatchet-client'; |
| 4 | + |
| 5 | +export const ONBOARDING_EVENT_KEY = 'user:onboarding-completed'; |
| 6 | +const TIMEOUT_SECONDS = 5; |
| 7 | +const LOOKBACK_WINDOW = '5m' as const; |
| 8 | + |
| 9 | +// > Models |
| 10 | +export type SignupInput = { |
| 11 | + email: string; |
| 12 | + user_id: string; |
| 13 | +}; |
| 14 | + |
| 15 | +export type WelcomeEmailResult = { |
| 16 | + userId: string; |
| 17 | + welcomeSent: boolean; |
| 18 | + followUpSent: boolean; |
| 19 | +}; |
| 20 | + |
| 21 | +// > Welcome email task |
| 22 | +export const welcomeEmail = hatchet.durableTask<SignupInput, WelcomeEmailResult>({ |
| 23 | + name: 'welcome-email', |
| 24 | + onEvents: ['user:signup'], |
| 25 | + executionTimeout: '5m', |
| 26 | + fn: async (input, ctx) => { |
| 27 | + // Step 1: Send the welcome email |
| 28 | + console.log(`Sending welcome email to ${input.email}: finish your first onboarding step`); |
| 29 | + |
| 30 | + // Step 2: Wait for the user to complete onboarding, or time out |
| 31 | + // (use a longer duration for a more realistic workflow) |
| 32 | + const now = await ctx.now(); |
| 33 | + const considerEventsSince = new Date( |
| 34 | + now.getTime() - durationToMs(LOOKBACK_WINDOW) |
| 35 | + ).toISOString(); |
| 36 | + |
| 37 | + const waitResult = await ctx.waitFor( |
| 38 | + Or( |
| 39 | + { sleepFor: `${TIMEOUT_SECONDS}s` }, |
| 40 | + // Scope the event condition to this user so that another user's |
| 41 | + // onboarding-completed event does not resolve this wait. |
| 42 | + { eventKey: ONBOARDING_EVENT_KEY, scope: input.user_id, considerEventsSince } |
| 43 | + ) |
| 44 | + ); |
| 45 | + |
| 46 | + // The or-group result is { CREATE: { <condition_key>: ... } }. |
| 47 | + // Check whether the onboarding event was the one that resolved. |
| 48 | + const create = (waitResult as Record<string, Record<string, unknown>>)['CREATE'] ?? waitResult; |
| 49 | + const resolvedKey = Object.keys(create as Record<string, unknown>)[0] ?? ''; |
| 50 | + const onboardingCompleted = resolvedKey === ONBOARDING_EVENT_KEY; |
| 51 | + |
| 52 | + if (onboardingCompleted) { |
| 53 | + // Step 3a: User completed onboarding -> skip follow-up |
| 54 | + console.log(`User ${input.user_id} completed onboarding, skipping follow-up`); |
| 55 | + return { userId: input.user_id, welcomeSent: true, followUpSent: false }; |
| 56 | + } |
| 57 | + |
| 58 | + // Step 3b: Timeout -> send follow-up email |
| 59 | + console.log(`Sending follow-up email to ${input.email}: need help finishing onboarding?`); |
| 60 | + return { userId: input.user_id, welcomeSent: true, followUpSent: true }; |
| 61 | + }, |
| 62 | +}); |
0 commit comments