Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Enhance example of using waitForTaskToken to show both state machine and lambda #899

Open
dmeehan1968 opened this issue Oct 23, 2023 · 0 comments

Comments

@dmeehan1968
Copy link

Here is an expanded example for waitForTaskToken, using a lambda as the worker. It simply waits for the specified time or timestamp, then sends the final status to resume the calling state machine.

export const main = asl.deploy.asStateMachine(async (input: any, context: asl.StateMachineContext<any>) => {

    const result = await asl.task<WorkerOutput>({
        resource: 'arn:aws:states:::lambda:invoke.waitForTaskToken',
        parameters: {
            FunctionName: asl.deploy.getLambdaName('workerTask'),
            Payload: {
                seconds: 5,
                taskToken: context.task.token,
            }
        },
        retry: [
            {
                errorEquals: ['States.ALL'],
                maxAttempts: 0,
            },
        ],
        timeoutSeconds: 10,
        heartbeatSeconds: 10,
    })
})

interface WorkerOutput {
    status: 'completed' | 'failed'
}

interface RelativeWait {
    seconds: number
    timestamp?: undefined
}

interface AbsoluteWait {
    seconds?: undefined
    timestamp: string
}

// discriminated union to switch between relative or absolute delays
type WaitInput = (RelativeWait | AbsoluteWait) & { taskToken: string }

export const workerTask = asl.deploy.asLambda(async (input: WaitInput) => {
    if (input.seconds) {
        await new Promise((resolve) => setTimeout(resolve, input.seconds * 1000))
    } else if (input.timestamp) {
        const timeout = Math.max(new Date(input.timestamp).getTime() - Date.now(), 0)
        await new Promise((resolve) => setTimeout(resolve, timeout))
    } else {
        console.error('waitTask: no seconds or timestamp provided')
        await asl.sdk(SFN).sendTaskFailure({
            parameters: {
                error: JSON.stringify({ status: 'failed' }),
                taskToken: input.taskToken,
            }
        })
    }

    await asl.sdk(SFN).sendTaskSuccess({
        parameters: {
            taskToken: input.taskToken,
            output: JSON.stringify({ status: 'completed' }),
        }
    })

    console.log('completed waitTask')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant