import { logRaw } from "@cloudflare/cli-shared-helpers"; import { red, white } from "@cloudflare/cli-shared-helpers/colors"; import { retryOnAPIFailure } from "@cloudflare/workers-utils"; import { addMilliseconds, formatDistanceStrict, formatDistanceToNowStrict, } from "date-fns"; import { ms } from "itty-time"; import { fetchResult } from "../../../cfetch"; import { createCommand } from "../../../core/create-command"; import { logger } from "../../../logger"; import { requireAuth } from "../../../user"; import formatLabelledValues from "../../../utils/render-labelled-values"; import { fetchLocalResult, getLocalInstanceIdFromArgs, localWorkflowArgs, } from "../../local"; import { emojifyInstanceStatus, emojifyInstanceTriggerName, emojifyStepType, getInstanceIdFromArgs, getJsonAwareRetryLogger, jsonWorkflowArgs, } from "../../utils"; import type { InstanceSleepLog, InstanceStatusAndLogs, InstanceStepLog, InstanceTerminateLog, InstanceWaitForEventLog, } from "../../types"; export const workflowsInstancesDescribeCommand = createCommand({ metadata: { description: "Describe a workflow instance - see its logs, retries and errors", owner: "Product: Workflows", status: "stable", }, positionalArgs: ["name", "id"], args: { ...localWorkflowArgs, ...jsonWorkflowArgs, name: { describe: "Name of the workflow", type: "string", demandOption: true, }, id: { describe: "ID of the instance - instead of an UUID you can type 'latest' to get the latest instance and describe it", type: "string", demandOption: false, default: "latest", }, "step-output": { describe: "Don't output the step output since it might clutter the terminal", type: "boolean", default: true, }, "truncate-output-limit": { describe: "Truncate step output after x characters", type: "number", default: 5000, }, }, behaviour: { printBanner: (args) => !args.json, }, async handler(args, { config }) { let id: string; let instance: InstanceStatusAndLogs; if (args.local) { id = await getLocalInstanceIdFromArgs(args.port, args, { quiet: args.json, }); instance = await fetchLocalResult( args.port, `/workflows/${encodeURIComponent(args.name)}/instances/${encodeURIComponent(id)}` ); } else { const accountId = await requireAuth(config); id = await getInstanceIdFromArgs(accountId, args, config); instance = await retryOnAPIFailure( () => fetchResult( config, `/accounts/${accountId}/workflows/${args.name}/instances/${id}` ), getJsonAwareRetryLogger(args.json) ); } if (args.json) { // The API payload omits `id`, leaving `--id latest` callers no way to // learn which instance was resolved. `--step-output` and // `--truncate-output-limit` are ignored here because truncating would // hand invalid step output to a machine-readable consumer. logger.json({ id, ...instance }); return; } renderInstanceDetails(args, id, instance); }, }); function renderInstanceDetails( args: typeof workflowsInstancesDescribeCommand.args, id: string, instance: InstanceStatusAndLogs ) { const formattedInstance: Record = { "Workflow Name": args.name, "Instance Id": id, ...(instance.versionId != null ? { "Version Id": instance.versionId } : {}), Status: emojifyInstanceStatus(instance.status), }; if (instance.trigger) { formattedInstance.Trigger = emojifyInstanceTriggerName( instance.trigger.source ); } if (instance.queued) { formattedInstance.Queued = new Date(instance.queued).toLocaleString(); } if (instance.success != null) { formattedInstance.Success = instance.success ? "✅ Yes" : "❌ No"; } // date related stuff, if the workflow is still running assume duration until now if (instance.start != undefined) { formattedInstance.Start = new Date(instance.start).toLocaleString(); } if (instance.end != undefined) { formattedInstance.End = new Date(instance.end).toLocaleString(); } if (instance.start != null && instance.end != null) { formattedInstance.Duration = formatDistanceStrict( new Date(instance.end), new Date(instance.start) ); } else if (instance.start != null) { formattedInstance.Duration = formatDistanceStrict( new Date(instance.start), new Date() ); } const lastSuccessfulStepName = getLastSuccessfulStep(instance); if (lastSuccessfulStepName != null) { formattedInstance["Last Successful Step"] = lastSuccessfulStepName; } // display the error if the instance errored out if (instance.error != null) { formattedInstance.Error = red( `${instance.error.name}: ${instance.error.message}` ); } logRaw("Describing latest instance:"); logRaw(formatLabelledValues(formattedInstance)); logRaw(white("Steps:")); instance.steps.forEach(logStep.bind(false, args)); } function logStep( args: typeof workflowsInstancesDescribeCommand.args, step: | InstanceStepLog | InstanceSleepLog | InstanceTerminateLog | InstanceWaitForEventLog ) { logRaw(""); const formattedStep: Record = {}; if ( step.type == "sleep" || step.type == "step" || step.type == "waitForEvent" ) { formattedStep.Name = step.name; formattedStep.Type = emojifyStepType(step.type); // date related stuff, if the step is still running assume duration until now if (step.start != undefined) { formattedStep.Start = new Date(step.start).toLocaleString(); } if (step.end != undefined) { formattedStep.End = new Date(step.end).toLocaleString(); } if (step.start != null && step.end != null) { formattedStep.Duration = formatDistanceStrict( new Date(step.end), new Date(step.start) ); } else if (step.start != null) { formattedStep.Duration = formatDistanceStrict( new Date(step.start), new Date() ); } } else if (step.type == "termination") { formattedStep.Type = emojifyStepType(step.type); formattedStep.Trigger = step.trigger.source; } if (step.type == "step") { if (step.success !== null) { formattedStep.Success = step.success ? "✅ Yes" : "❌ No"; } else { formattedStep.Success = "▶ Running"; } if (step.success === null) { const latestAttempt = step.attempts.at(-1); if (latestAttempt !== undefined && latestAttempt.success === false) { const retryDelayMs = parseRetryDelayMs(step.config.retries.delay); if (latestAttempt.end == null) { formattedStep["Retries At"] = "unknown"; } else if (retryDelayMs == null) { formattedStep["Retries At"] = "unknown (dynamic delay)"; } else { const retryDate = addMilliseconds( new Date(latestAttempt.end), retryDelayMs ); if (!Number.isNaN(retryDate.getTime())) { formattedStep["Retries At"] = `${retryDate.toLocaleString()} (in ${formatDistanceToNowStrict(retryDate)} from now)`; } } } } } if (step.type == "step" || step.type == "waitForEvent") { if (step.output !== undefined && args.stepOutput) { let output: string; try { output = JSON.stringify(step.output); } catch { output = step.output as string; } formattedStep.Output = output.length > args.truncateOutputLimit ? output.substring(0, args.truncateOutputLimit) + "[...output truncated]" : output; } } logger.log(formatLabelledValues(formattedStep, { indentationCount: 2 })); if (step.type == "step") { const prettyAttempts = step.attempts.map((val) => { const attempt: Record = {}; attempt.Start = new Date(val.start).toLocaleString(); attempt.End = val.end == null ? "" : new Date(val.end).toLocaleString(); if (val.start != null && val.end != null) { attempt.Duration = formatDistanceStrict( new Date(val.end), new Date(val.start) ); } else if (val.start != null) { attempt.Duration = formatDistanceStrict( new Date(val.start), new Date() ); } attempt.State = val.success == null ? "🔄 Working" : val.success ? "✅ Success" : "❌ Error"; // This is actually safe to do while logger.table only considers the first element as keys. // Because if there's an error, the first row will always be an error if (val.error != null) { attempt.Error = red(`${val.error.name}: ${val.error.message}`); } return attempt; }); logger.table(prettyAttempts); } } const DYNAMIC_RETRY_DELAY = "[dynamic]"; function parseRetryDelayMs(delay: unknown): number | null { if (delay === DYNAMIC_RETRY_DELAY) { return null; } if (typeof delay === "number") { return Number.isFinite(delay) ? delay : null; } if (typeof delay === "string") { const parsed = ms(delay); return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : null; } return null; } function getLastSuccessfulStep(logs: InstanceStatusAndLogs): string | null { let lastSuccessfulStepName: string | null = null; for (const step of logs.steps) { switch (step.type) { case "step": if (step.success == true) { lastSuccessfulStepName = step.name; } break; case "sleep": if (step.end != null) { lastSuccessfulStepName = step.name; } break; case "termination": break; } } return lastSuccessfulStepName; }