|
| 1 | +import { logger, task, wait } from "@trigger.dev/sdk"; |
| 2 | + |
| 3 | +export const nestedDependencies = task({ |
| 4 | + id: "nested-dependencies", |
| 5 | + run: async ({ |
| 6 | + depth = 0, |
| 7 | + maxDepth = 6, |
| 8 | + batchSize = 4, |
| 9 | + waitSeconds = 1, |
| 10 | + failAttemptChance = 0, |
| 11 | + failParents = false, |
| 12 | + }: { |
| 13 | + depth?: number; |
| 14 | + maxDepth?: number; |
| 15 | + batchSize?: number; |
| 16 | + waitSeconds?: number; |
| 17 | + failAttemptChance?: number; |
| 18 | + failParents?: boolean; |
| 19 | + }) => { |
| 20 | + if (depth >= maxDepth) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + logger.log(`Started ${depth}/${maxDepth} depth`); |
| 25 | + |
| 26 | + const shouldFail = Math.random() < failAttemptChance; |
| 27 | + if (shouldFail) { |
| 28 | + throw new Error(`Failed at ${depth}/${maxDepth} depth`); |
| 29 | + } |
| 30 | + |
| 31 | + await wait.for({ seconds: waitSeconds }); |
| 32 | + |
| 33 | + const triggerOrBatch = depth % 2 === 0; |
| 34 | + |
| 35 | + if (triggerOrBatch) { |
| 36 | + for (let i = 0; i < batchSize; i++) { |
| 37 | + const result = await nestedDependencies.triggerAndWait({ |
| 38 | + depth: depth + 1, |
| 39 | + maxDepth, |
| 40 | + waitSeconds, |
| 41 | + failAttemptChance, |
| 42 | + batchSize, |
| 43 | + }); |
| 44 | + logger.log(`Triggered complete ${i + 1}/${batchSize}`); |
| 45 | + |
| 46 | + if (!result.ok && failParents) { |
| 47 | + throw new Error(`Failed at ${depth}/${maxDepth} depth`); |
| 48 | + } |
| 49 | + } |
| 50 | + } else { |
| 51 | + const results = await nestedDependencies.batchTriggerAndWait( |
| 52 | + Array.from({ length: batchSize }, (_, i) => ({ |
| 53 | + payload: { |
| 54 | + depth: depth + 1, |
| 55 | + maxDepth, |
| 56 | + batchSize, |
| 57 | + waitSeconds, |
| 58 | + failAttemptChance, |
| 59 | + }, |
| 60 | + })) |
| 61 | + ); |
| 62 | + logger.log(`Batch triggered complete`); |
| 63 | + |
| 64 | + if (results.runs.some((r) => !r.ok) && failParents) { |
| 65 | + throw new Error(`Failed at ${depth}/${maxDepth} depth`); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + logger.log(`Sleep for ${waitSeconds} seconds`); |
| 70 | + await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000)); |
| 71 | + |
| 72 | + logger.log(`Finished ${depth}/${maxDepth} depth`); |
| 73 | + }, |
| 74 | +}); |
0 commit comments