diff --git a/docs/mint.json b/docs/mint.json index 89a2bc8ab..3ae169d16 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -138,7 +138,8 @@ "v3/machines", "v3/idempotency", "v3/reattempting-replaying", - "v3/notifications" + "v3/notifications", + "v3/run-usage" ] }, { diff --git a/docs/v3/run-usage.mdx b/docs/v3/run-usage.mdx new file mode 100644 index 000000000..e99d785e7 --- /dev/null +++ b/docs/v3/run-usage.mdx @@ -0,0 +1,85 @@ +--- +title: "Usage" +description: "Get compute duration and cost from inside a run, or for a specific block of code." +--- + +## Getting the run cost and duration + +You can get the cost and duration of the current including retries of the same run. + +```ts +export const heavyTask = task({ + id: "heavy-task", + machine: { + preset: "medium-2x", + }, + run: async (payload, { ctx }) => { + // Do some compute + const result = await convertVideo(payload.videoUrl); + + // Get the current cost and duration up until this line of code + // This includes the compute time of the previous lines + let currentUsage = usage.getCurrent(); + /* currentUsage = { + compute: { + attempt: { + costInCents: 0.01700, + durationMs: 1000, + }, + total: { + costInCents: 0.0255, + durationMs: 1500, + }, + }, + baseCostInCents: 0.0025, + totalCostInCents: 0.028, + } + */ + + // In the cloud product we do not count waits towards the compute cost or duration. + // We also don't include time between attempts or before the run starts executing your code. + // So this line does not affect the cost or duration. + await wait.for({ seconds: 5 }); + + // This will give the same result as before the wait. + currentUsage = usage.getCurrent(); + + // Do more compute + const result = await convertVideo(payload.videoUrl); + + // This would give a different value + currentUsage = usage.getCurrent(); + }, +}); +``` + + + In Trigger.dev cloud we do not include time between attempts, before your code executes, or waits + towards the compute cost or duration. + + +## Getting the cost and duration of a block of code + +You can also wrap code with `usage.measure` to get the cost and duration of that block of code: + +```ts +// Inside a task run function, or inside a function that's called from there. +const { result, compute } = await usage.measure(async () => { + //...Do something for 1 second + return { + foo: "bar", + }; +}); + +logger.info("Result", { result, compute }); +/* result = { + foo: "bar" + } + compute = { + costInCents: 0.01700, + durationMs: 1000, + } +*/ +``` + +This will work from inside the `run` function, our lifecycle hooks (like `onStart`, `onFailure`, `onSuccess`, etc.), or any function you're calling from the `run` function. It won't work for code that's not executed using Trigger.dev.