Skip to content

sleep() fails successfully #27

@adomaitisc

Description

@adomaitisc

Isn't there a more graceful way of sleeping?

I was trying to figure out why the sleep function is erroing (but working).
Just to read the stdlib and figure that this happens by design...

//stdlib.js
export async function sleep(param) {
    'use step';
    const { stepStartedAt } = getStepMetadata();
    const durationMs = typeof param === 'string'
        ? ms(param)
        : param.getTime() - Number(stepStartedAt);
    if (typeof durationMs !== 'number' || durationMs < 0) {
        const message = param instanceof Date
            ? `Invalid sleep date: "${param}". Expected a future date.`
            : `Invalid sleep duration: "${param}". Expected a valid duration string like "1s", "1m", "1h", etc.`;
        throw new Error(message);
    }
    const endAt = +stepStartedAt + durationMs;
    const now = Date.now();
    if (now < endAt) {
        const remainingSeconds = (endAt - now) / 1000;
        const retryAfter = Math.min(remainingSeconds, MAX_SLEEP_DURATION_SECONDS);
        // 😮
        throw new RetryableError(`Sleeping for ${ms(retryAfter * 1000, { long: true })}`, {
            retryAfter,
        });
    }
}
//my-workflow.ts
export async function myWorkflow({ name }: { name: string }) {
  "use workflow";

  await greet(name);
  await sleep("20s");
  await bye(name);
}
Hello, James Webb!, 2025-10-24T15:21:39.466Z
[Workflows] "wrun_01K8BCZA88RHM7TKWPVKTXMDK1" - Encountered `RetryableError` while executing step "step//node_modules/workflow/dist/stdlib.js//sleep" (attempt 1):
  > Sleeping for 20 seconds

  This step has failed but will be retried
[Workflows] "wrun_01K8BCZA88RHM7TKWPVKTXMDK1" - Encountered `RetryableError` while executing step "step//node_modules/workflow/dist/stdlib.js//sleep" (attempt 2):
  > Sleeping for 987 ms

  This step has failed but will be retried
Goodbye, James Webb!, 2025-10-24T15:21:59.529Z

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions