From bbb0fe732514e64c337e7851197ddd98d9e6ef8b Mon Sep 17 00:00:00 2001 From: "agne.statkeviciute" Date: Fri, 27 Nov 2026 10:47:12 +0200 Subject: [PATCH] feat: add async task flow to target commands --- README.md | 20 +++ docs/ARCHITECTURE.md | 8 +- src/cli/services/run-data-action.ts | 12 +- src/cli/services/sort-commands-by-order.ts | 1 + src/cli/types/data-action.ts | 4 + src/platform/services/handle-cli-error.ts | 7 +- src/scrape/commands/attach-async-options.ts | 14 ++ .../commands/attach-task-wait-options.ts | 25 ++++ src/scrape/commands/task.ts | 60 ++++++++ src/scrape/constants.ts | 13 ++ src/scrape/errors/task-failed-error.ts | 11 ++ .../errors/task-results-not-ready-error.ts | 11 ++ src/scrape/register.ts | 2 + src/scrape/services/assert-async-flags.ts | 11 ++ src/scrape/services/assert-task-wait-flags.ts | 15 ++ src/scrape/services/command-builder.ts | 2 + src/scrape/services/get-task-results.ts | 13 ++ src/scrape/services/run-async-scrape.ts | 36 +++++ src/scrape/services/run-target-scrape.ts | 15 ++ src/scrape/services/settle-task.ts | 25 ++++ src/scrape/services/wait-for-task.ts | 34 +++++ src/scrape/types/async-options.ts | 9 ++ src/scrape/types/task-command.ts | 7 + tests/cli/services/run-data-action.test.ts | 19 ++- tests/docs/readme-commands.test.ts | 2 + .../services/handle-cli-error.test.ts | 8 ++ .../commands/attach-async-options.test.ts | 25 ++++ .../commands/attach-task-wait-options.test.ts | 35 +++++ tests/scrape/commands/task.test.ts | 136 ++++++++++++++++++ tests/scrape/errors/task-failed-error.test.ts | 13 ++ .../task-results-not-ready-error.test.ts | 14 ++ .../services/assert-async-flags.test.ts | 37 +++++ .../services/assert-task-wait-flags.test.ts | 24 ++++ tests/scrape/services/command-builder.test.ts | 16 +++ .../scrape/services/get-task-results.test.ts | 26 ++++ .../scrape/services/run-async-scrape.test.ts | 81 +++++++++++ .../scrape/services/run-target-scrape.test.ts | 62 ++++++++ tests/scrape/services/settle-task.test.ts | 24 ++++ tests/scrape/services/wait-for-task.test.ts | 61 ++++++++ 39 files changed, 930 insertions(+), 8 deletions(-) create mode 100644 src/scrape/commands/attach-async-options.ts create mode 100644 src/scrape/commands/attach-task-wait-options.ts create mode 100644 src/scrape/commands/task.ts create mode 100644 src/scrape/errors/task-failed-error.ts create mode 100644 src/scrape/errors/task-results-not-ready-error.ts create mode 100644 src/scrape/services/assert-async-flags.ts create mode 100644 src/scrape/services/assert-task-wait-flags.ts create mode 100644 src/scrape/services/get-task-results.ts create mode 100644 src/scrape/services/run-async-scrape.ts create mode 100644 src/scrape/services/settle-task.ts create mode 100644 src/scrape/services/wait-for-task.ts create mode 100644 src/scrape/types/async-options.ts create mode 100644 src/scrape/types/task-command.ts create mode 100644 tests/scrape/commands/attach-async-options.test.ts create mode 100644 tests/scrape/commands/attach-task-wait-options.test.ts create mode 100644 tests/scrape/commands/task.test.ts create mode 100644 tests/scrape/errors/task-failed-error.test.ts create mode 100644 tests/scrape/errors/task-results-not-ready-error.test.ts create mode 100644 tests/scrape/services/assert-async-flags.test.ts create mode 100644 tests/scrape/services/assert-task-wait-flags.test.ts create mode 100644 tests/scrape/services/get-task-results.test.ts create mode 100644 tests/scrape/services/run-async-scrape.test.ts create mode 100644 tests/scrape/services/settle-task.test.ts create mode 100644 tests/scrape/services/wait-for-task.test.ts diff --git a/README.md b/README.md index 8840995..b58eb06 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ You should see Markdown or parsed JSON within seconds. If you see an auth error, | `decodo map ` | List a site's URLs, one per line (`--limit`, `--sitemap`, `--full`) | | `decodo crawl ` | Start a crawl and print its id; `--wait` prints pages as NDJSON | | `decodo screenshot ` | Capture a PNG screenshot (`-o` file or directory) | +| `decodo task status\|results ` | Check or collect a task started with `--async` | | `decodo targets` | List all scrape targets by group | | `decodo setup` | Save your API key or auth token interactively | | `decodo whoami` | Show configured auth source | @@ -193,6 +194,25 @@ decodo universal --help Use `decodo --help` for target-specific flags (`--parse`, `--geo`, and others from the schema). +### Async tasks + +Add `--async` to any target command to create an async task instead of waiting for the scrape. The command prints the task as JSON, including its `id`, and returns right away: + +```bash +decodo google-search "decodo web data api" --async +decodo task status +decodo task results +decodo task results --wait +``` + +Add `--wait` to create the task and print its result in one command: + +```bash +decodo google-search "decodo web data api" --async --wait +``` + +With `--wait`, the CLI polls every `--poll-interval` seconds (default `5`) and gives up after `--timeout` seconds (default `600`, exit code `6`); the task keeps running. The task id goes to stderr as soon as the task is created. A `faulted` task exits `7`. `task results` without `--wait` exits `1` when the task has no results yet. Task commands accept an API key or a basic auth token. + ## Output modes By default, scrape commands print the first result's `content` (parsed JSON when the target supports `--parse`, Markdown for `decodo scrape`). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8d7016e..66401dd 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -32,8 +32,12 @@ Command assembly is two-layered: dynamically generated scrape commands, then sorts them with `sortCommandsByOrder` so help output has a stable, curated order (`ROOT_COMMAND_ORDER`). - `scrape/register.ts` loads the schema once and builds the scrape-family commands: - `scrape`, `screenshot`, `targets` (list), plus one generated command per API - target from `codegen-target-commands.ts`. + `scrape`, `screenshot`, `targets` (list), `task` (with `task status|results`), plus one + generated command per API target from `codegen-target-commands.ts`. +- Every generated target command takes `--async`, which creates an async task through the + SDK instead of a real-time scrape (`scrape/services/run-async-scrape.ts`); `--wait` polls + the task and prints its result. The `task` commands run through + `cli/services/run-data-action.ts` with `apiKeyOnly: false`, so they accept a basic token too. - The Data API commands `search`, `map`, and `crawl` (with `crawl status|results|cancel`) live in their own modules and are registered directly in `cli/register.ts`. They don't use the schema; each runs through `cli/services/run-data-action.ts`, which requires an diff --git a/src/cli/services/run-data-action.ts b/src/cli/services/run-data-action.ts index 0707845..41a9a0d 100644 --- a/src/cli/services/run-data-action.ts +++ b/src/cli/services/run-data-action.ts @@ -5,11 +5,17 @@ import { AuthRequiredError } from "../../auth/errors/auth-required-error.js"; import { resolveAuthToken } from "../../auth/services/resolve-token.js"; import { handleCliError } from "../../platform/services/handle-cli-error.js"; import { createDecodoClient } from "../../scrape/services/client.js"; -import type { DataActionHandler } from "../types/data-action.js"; +import type { + DataActionConfig, + DataActionHandler, +} from "../types/data-action.js"; import { getRootOpts } from "./global-opts.js"; import { verboseLog } from "./verbose-log.js"; -export function createDataAction(handler: DataActionHandler) { +export function createDataAction( + handler: DataActionHandler, + { apiKeyOnly = true }: DataActionConfig = {} +) { return async ( input: string, _localOptions: unknown, @@ -28,7 +34,7 @@ export function createDataAction(handler: DataActionHandler) { if (!auth.credential) { throw new AuthRequiredError(); } - if (auth.credential.type !== AUTH_TYPE.API_KEY) { + if (apiKeyOnly && auth.credential.type !== AUTH_TYPE.API_KEY) { throw new ApiKeyRequiredError(); } diff --git a/src/cli/services/sort-commands-by-order.ts b/src/cli/services/sort-commands-by-order.ts index d0d98b2..3364315 100644 --- a/src/cli/services/sort-commands-by-order.ts +++ b/src/cli/services/sort-commands-by-order.ts @@ -6,6 +6,7 @@ export const ROOT_COMMAND_ORDER = [ "map", "crawl", "screenshot", + "task", "setup", "reset", "whoami", diff --git a/src/cli/types/data-action.ts b/src/cli/types/data-action.ts index 6b9aa06..8dbcd5c 100644 --- a/src/cli/types/data-action.ts +++ b/src/cli/types/data-action.ts @@ -7,6 +7,10 @@ export interface DataActionContext { verbose: boolean; } +export interface DataActionConfig { + apiKeyOnly?: boolean; +} + export type DataActionHandler = ( context: DataActionContext ) => Promise; diff --git a/src/platform/services/handle-cli-error.ts b/src/platform/services/handle-cli-error.ts index 471271a..007352f 100644 --- a/src/platform/services/handle-cli-error.ts +++ b/src/platform/services/handle-cli-error.ts @@ -10,6 +10,7 @@ import { ApiKeyRequiredError } from "../../auth/errors/api-key-required-error.js import { AuthRequiredError } from "../../auth/errors/auth-required-error.js"; import { CrawlFailedError } from "../../crawl/errors/crawl-failed-error.js"; import { ScrapeFailedError } from "../../output/errors/scrape-failed-error.js"; +import { TaskFailedError } from "../../scrape/errors/task-failed-error.js"; import { EXIT } from "../constants.js"; import { CliUsageError } from "../errors/cli-usage-error.js"; @@ -70,7 +71,11 @@ export function resolveCliExitCode(err: unknown): number { return EXIT.TIMEOUT; } - if (err instanceof ScrapeFailedError || err instanceof CrawlFailedError) { + if ( + err instanceof ScrapeFailedError || + err instanceof CrawlFailedError || + err instanceof TaskFailedError + ) { return EXIT.NETWORK; } diff --git a/src/scrape/commands/attach-async-options.ts b/src/scrape/commands/attach-async-options.ts new file mode 100644 index 0000000..76b675f --- /dev/null +++ b/src/scrape/commands/attach-async-options.ts @@ -0,0 +1,14 @@ +import type { Command } from "commander"; +import { attachTaskWaitOptions } from "./attach-task-wait-options.js"; + +export function attachAsyncOptions(command: Command): Command { + command.option( + "--async", + "Create an async task and print it with its id instead of waiting for the result" + ); + + return attachTaskWaitOptions( + command, + "Wait for the task to finish and print the result (with --async)" + ); +} diff --git a/src/scrape/commands/attach-task-wait-options.ts b/src/scrape/commands/attach-task-wait-options.ts new file mode 100644 index 0000000..20eea12 --- /dev/null +++ b/src/scrape/commands/attach-task-wait-options.ts @@ -0,0 +1,25 @@ +import type { Command } from "commander"; +import { parsePositiveInt } from "../../cli/services/parse-positive-int.js"; +import { parsePollInterval } from "../../crawl/services/parse-poll-interval.js"; +import { + DEFAULT_TASK_POLL_INTERVAL_SECONDS, + DEFAULT_TASK_TIMEOUT_SECONDS, +} from "../constants.js"; + +export function attachTaskWaitOptions( + command: Command, + waitHelp: string +): Command { + return command + .option("--wait", waitHelp) + .option( + "--poll-interval ", + `Seconds between status checks (with --wait, default: ${DEFAULT_TASK_POLL_INTERVAL_SECONDS})`, + parsePollInterval + ) + .option( + "--timeout ", + `Give up waiting after this many seconds (with --wait, default: ${DEFAULT_TASK_TIMEOUT_SECONDS})`, + parsePositiveInt + ); +} diff --git a/src/scrape/commands/task.ts b/src/scrape/commands/task.ts new file mode 100644 index 0000000..4b7a07a --- /dev/null +++ b/src/scrape/commands/task.ts @@ -0,0 +1,60 @@ +import { Command } from "commander"; +import { createDataAction } from "../../cli/services/run-data-action.js"; +import { attachScrapeOutputOptions } from "../../output/commands/attach-output-options.js"; +import { writeJsonOutput } from "../../output/services/write-json-output.js"; +import { writeScrapeResponse } from "../../output/services/write-scrape-response.js"; +import { assertTaskWaitFlags } from "../services/assert-task-wait-flags.js"; +import { getTaskResults } from "../services/get-task-results.js"; +import { settleTask } from "../services/settle-task.js"; +import type { + TaskResultsOptions, + TaskStatusOptions, +} from "../types/task-command.js"; +import { attachTaskWaitOptions } from "./attach-task-wait-options.js"; + +function createTaskStatusCommand(): Command { + return new Command("status") + .description("Show the status of an async task as JSON") + .argument("", "Task id") + .option("--pretty", "Pretty-print JSON on stdout") + .action( + createDataAction( + async ({ api, input, options }) => { + writeJsonOutput(await api.getStatus(input), options); + }, + { apiKeyOnly: false } + ) + ); +} + +function createTaskResultsCommand(): Command { + const command = new Command("results") + .description("Print the result of an async task") + .argument("", "Task id"); + + attachScrapeOutputOptions(command); + + return attachTaskWaitOptions( + command, + "Wait for the task to finish before printing its result" + ).action( + createDataAction( + async ({ api, input, options }) => { + assertTaskWaitFlags(options); + if (options.wait) { + await settleTask(api, input, options); + } + + writeScrapeResponse(await getTaskResults(api, input), { options }); + }, + { apiKeyOnly: false } + ) + ); +} + +export function createTaskCommand(): Command { + return new Command("task") + .description("Check or collect an async task started with --async") + .addCommand(createTaskStatusCommand()) + .addCommand(createTaskResultsCommand()); +} diff --git a/src/scrape/constants.ts b/src/scrape/constants.ts index 5e424a1..181becf 100644 --- a/src/scrape/constants.ts +++ b/src/scrape/constants.ts @@ -2,6 +2,19 @@ export const INTEGRATION_HEADER = "cli"; export const SCHEMA_TTL_MS = 3_600_000; +export const PENDING_TASK_STATUS = "pending"; + +export const DONE_TASK_STATUS = "done"; + +export const DEFAULT_TASK_POLL_INTERVAL_SECONDS = 5; + +export const DEFAULT_TASK_TIMEOUT_SECONDS = 600; + +export const TASK_WAIT_ONLY_FLAGS = { + pollInterval: "--poll-interval", + timeout: "--timeout", +} as const; + export const PRIMARY_INPUT_FIELDS = [ "query", "url", diff --git a/src/scrape/errors/task-failed-error.ts b/src/scrape/errors/task-failed-error.ts new file mode 100644 index 0000000..ed05ca2 --- /dev/null +++ b/src/scrape/errors/task-failed-error.ts @@ -0,0 +1,11 @@ +export class TaskFailedError extends Error { + readonly status: string; + readonly taskId: string; + + constructor(taskId: string, status: string) { + super(`Task ${taskId} ended with status ${status}.`); + this.name = "TaskFailedError"; + this.taskId = taskId; + this.status = status; + } +} diff --git a/src/scrape/errors/task-results-not-ready-error.ts b/src/scrape/errors/task-results-not-ready-error.ts new file mode 100644 index 0000000..1ab93e5 --- /dev/null +++ b/src/scrape/errors/task-results-not-ready-error.ts @@ -0,0 +1,11 @@ +export class TaskResultsNotReadyError extends Error { + readonly taskId: string; + + constructor(taskId: string) { + super( + `Task ${taskId} has no results yet. Run \`decodo task results ${taskId} --wait\` to wait for them.` + ); + this.name = "TaskResultsNotReadyError"; + this.taskId = taskId; + } +} diff --git a/src/scrape/register.ts b/src/scrape/register.ts index 7219eec..d39d675 100644 --- a/src/scrape/register.ts +++ b/src/scrape/register.ts @@ -3,6 +3,7 @@ import { createCodegenTargetCommands } from "./commands/codegen-target-commands. import { createListTargetsCommand } from "./commands/list-targets.js"; import { createScrapeCommand } from "./commands/scrape.js"; import { createScreenshotCommand } from "./commands/screenshot.js"; +import { createTaskCommand } from "./commands/task.js"; import { loadSchema } from "./services/schema-loader.js"; export async function createScrapeCommands(): Promise { @@ -11,6 +12,7 @@ export async function createScrapeCommands(): Promise { return [ createScrapeCommand(schema), createScreenshotCommand(schema), + createTaskCommand(), createListTargetsCommand(schema), ...createCodegenTargetCommands(schema), ]; diff --git a/src/scrape/services/assert-async-flags.ts b/src/scrape/services/assert-async-flags.ts new file mode 100644 index 0000000..0c41385 --- /dev/null +++ b/src/scrape/services/assert-async-flags.ts @@ -0,0 +1,11 @@ +import { CliUsageError } from "../../platform/errors/cli-usage-error.js"; +import type { AsyncOptions } from "../types/async-options.js"; +import { assertTaskWaitFlags } from "./assert-task-wait-flags.js"; + +export function assertAsyncFlags(options: AsyncOptions): void { + if (options.wait && !options.async) { + throw new CliUsageError("--wait requires --async."); + } + + assertTaskWaitFlags(options); +} diff --git a/src/scrape/services/assert-task-wait-flags.ts b/src/scrape/services/assert-task-wait-flags.ts new file mode 100644 index 0000000..ad482d9 --- /dev/null +++ b/src/scrape/services/assert-task-wait-flags.ts @@ -0,0 +1,15 @@ +import { CliUsageError } from "../../platform/errors/cli-usage-error.js"; +import { TASK_WAIT_ONLY_FLAGS } from "../constants.js"; +import type { TaskWaitOptions } from "../types/async-options.js"; + +export function assertTaskWaitFlags(options: TaskWaitOptions): void { + if (options.wait) { + return; + } + + for (const [key, flag] of Object.entries(TASK_WAIT_ONLY_FLAGS)) { + if (options[key as keyof TaskWaitOptions] !== undefined) { + throw new CliUsageError(`${flag} requires --wait.`); + } + } +} diff --git a/src/scrape/services/command-builder.ts b/src/scrape/services/command-builder.ts index a2a7acd..42d91d9 100644 --- a/src/scrape/services/command-builder.ts +++ b/src/scrape/services/command-builder.ts @@ -3,6 +3,7 @@ import { type Command, InvalidArgumentError, Option } from "commander"; import type { JSONSchema4 } from "json-schema"; import { attachScrapeOutputOptions } from "../../output/commands/attach-output-options.js"; import { applyRequestDefaults } from "../../output/services/apply-request-defaults.js"; +import { attachAsyncOptions } from "../commands/attach-async-options.js"; import type { TargetCommandConfig } from "../types/target-command.js"; import { snakeToCamel, snakeToKebab } from "./naming.js"; import { getPrimaryInputField } from "./primary-input.js"; @@ -120,6 +121,7 @@ export function configureTargetCommand( } attachScrapeOutputOptions(command); + attachAsyncOptions(command); return { target, primaryField, optionFields }; } diff --git a/src/scrape/services/get-task-results.ts b/src/scrape/services/get-task-results.ts new file mode 100644 index 0000000..8fb90c6 --- /dev/null +++ b/src/scrape/services/get-task-results.ts @@ -0,0 +1,13 @@ +import type { TaskResultsResponse, WebScrapingApi } from "@decodo/sdk-ts"; +import { TaskResultsNotReadyError } from "../errors/task-results-not-ready-error.js"; + +export async function getTaskResults( + api: WebScrapingApi, + taskId: string +): Promise { + const results = await api.getResults(taskId); + if (results === null) { + throw new TaskResultsNotReadyError(taskId); + } + return results; +} diff --git a/src/scrape/services/run-async-scrape.ts b/src/scrape/services/run-async-scrape.ts new file mode 100644 index 0000000..325de62 --- /dev/null +++ b/src/scrape/services/run-async-scrape.ts @@ -0,0 +1,36 @@ +import type { ScrapeRequest, WebScrapingApi } from "@decodo/sdk-ts"; +import { writeJsonOutput } from "../../output/services/write-json-output.js"; +import { writeScrapeResponse } from "../../output/services/write-scrape-response.js"; +import type { OutputOptions } from "../../output/types/output-options.js"; +import type { WriteScrapeResponseContext } from "../../output/types/write-scrape-response.js"; +import type { AsyncOptions } from "../types/async-options.js"; +import { getTaskResults } from "./get-task-results.js"; +import { settleTask } from "./settle-task.js"; + +export interface RunAsyncScrapeOptions { + body: Record; + input?: string; + options: AsyncOptions & OutputOptions; + outputContext?: Partial; +} + +export async function runAsyncScrape( + api: WebScrapingApi, + { body, input, options, outputContext }: RunAsyncScrapeOptions +): Promise { + const task = await api.scrapeAsync(body as unknown as ScrapeRequest); + + if (!options.wait) { + writeJsonOutput(task, options); + return; + } + + process.stderr.write(`task ${task.id} started\n`); + await settleTask(api, task.id, options); + + writeScrapeResponse(await getTaskResults(api, task.id), { + options, + input, + ...outputContext, + }); +} diff --git a/src/scrape/services/run-target-scrape.ts b/src/scrape/services/run-target-scrape.ts index 177564e..40271fc 100644 --- a/src/scrape/services/run-target-scrape.ts +++ b/src/scrape/services/run-target-scrape.ts @@ -8,14 +8,17 @@ import { writeScrapeResponse } from "../../output/services/write-scrape-response import type { OutputOptions } from "../../output/types/output-options.js"; import type { WriteScrapeResponseContext } from "../../output/types/write-scrape-response.js"; import { handleCliError } from "../../platform/services/handle-cli-error.js"; +import type { AsyncOptions } from "../types/async-options.js"; import type { ExecuteScrapeOptions, OutputContextBuilder, ScrapeBodyBuilder, } from "../types/run-target-scrape.js"; +import { assertAsyncFlags } from "./assert-async-flags.js"; import { createDecodoClient } from "./client.js"; import { buildScrapeBody, getTargetCommandConfig } from "./command-builder.js"; import { formatScrapeRequestLog } from "./format-scrape-request-log.js"; +import { runAsyncScrape } from "./run-async-scrape.js"; async function executeScrape({ credential, @@ -27,6 +30,17 @@ async function executeScrape({ verbose = false, }: ExecuteScrapeOptions): Promise { const client = createDecodoClient(credential, schema); + + if ((options as AsyncOptions).async) { + await runAsyncScrape(client.webScrapingApi, { + body, + input, + options: options as AsyncOptions & OutputOptions, + outputContext, + }); + return; + } + const startedAt = Date.now(); const response = await client.webScrapingApi.scrape( body as unknown as ScrapeRequest @@ -88,6 +102,7 @@ export function createTargetAction( const verbose = rootOpts.verbose === true; try { + assertAsyncFlags(options as AsyncOptions); const auth = await resolveAuthToken({ token: rootOpts.token }); verboseLog( verbose, diff --git a/src/scrape/services/settle-task.ts b/src/scrape/services/settle-task.ts new file mode 100644 index 0000000..05b1c9a --- /dev/null +++ b/src/scrape/services/settle-task.ts @@ -0,0 +1,25 @@ +import type { WebScrapingApi } from "@decodo/sdk-ts"; +import { + DEFAULT_TASK_POLL_INTERVAL_SECONDS, + DEFAULT_TASK_TIMEOUT_SECONDS, + DONE_TASK_STATUS, +} from "../constants.js"; +import { TaskFailedError } from "../errors/task-failed-error.js"; +import type { TaskWaitOptions } from "../types/async-options.js"; +import { waitForTask } from "./wait-for-task.js"; + +export async function settleTask( + api: WebScrapingApi, + taskId: string, + options: TaskWaitOptions +): Promise { + const task = await waitForTask(api, taskId, { + pollIntervalMs: + (options.pollInterval ?? DEFAULT_TASK_POLL_INTERVAL_SECONDS) * 1000, + timeoutMs: (options.timeout ?? DEFAULT_TASK_TIMEOUT_SECONDS) * 1000, + }); + + if (task.status !== DONE_TASK_STATUS) { + throw new TaskFailedError(taskId, task.status); + } +} diff --git a/src/scrape/services/wait-for-task.ts b/src/scrape/services/wait-for-task.ts new file mode 100644 index 0000000..5131116 --- /dev/null +++ b/src/scrape/services/wait-for-task.ts @@ -0,0 +1,34 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { + type TaskMetadata, + TimeoutError, + type WebScrapingApi, +} from "@decodo/sdk-ts"; +import { PENDING_TASK_STATUS } from "../constants.js"; + +export interface WaitForTaskOptions { + pollIntervalMs: number; + timeoutMs: number; +} + +export async function waitForTask( + api: WebScrapingApi, + taskId: string, + { pollIntervalMs, timeoutMs }: WaitForTaskOptions +): Promise { + const deadline = Date.now() + timeoutMs; + let task = await api.getStatus(taskId); + + while (task.status === PENDING_TASK_STATUS) { + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + throw new TimeoutError( + `Task ${taskId} did not finish within ${timeoutMs / 1000}s. It is still running.` + ); + } + await sleep(Math.min(pollIntervalMs, remainingMs)); + task = await api.getStatus(taskId); + } + + return task; +} diff --git a/src/scrape/types/async-options.ts b/src/scrape/types/async-options.ts new file mode 100644 index 0000000..e91bfb6 --- /dev/null +++ b/src/scrape/types/async-options.ts @@ -0,0 +1,9 @@ +export interface TaskWaitOptions { + pollInterval?: number; + timeout?: number; + wait?: boolean; +} + +export interface AsyncOptions extends TaskWaitOptions { + async?: boolean; +} diff --git a/src/scrape/types/task-command.ts b/src/scrape/types/task-command.ts new file mode 100644 index 0000000..72bc3b3 --- /dev/null +++ b/src/scrape/types/task-command.ts @@ -0,0 +1,7 @@ +import type { JsonOutputOptions } from "../../output/types/json-output-options.js"; +import type { OutputOptions } from "../../output/types/output-options.js"; +import type { TaskWaitOptions } from "./async-options.js"; + +export type TaskStatusOptions = JsonOutputOptions; + +export interface TaskResultsOptions extends OutputOptions, TaskWaitOptions {} diff --git a/tests/cli/services/run-data-action.test.ts b/tests/cli/services/run-data-action.test.ts index 1683bb0..b1a5573 100644 --- a/tests/cli/services/run-data-action.test.ts +++ b/tests/cli/services/run-data-action.test.ts @@ -13,7 +13,10 @@ vi.mock("../../../src/scrape/services/client.js", () => ({ createDecodoClient: vi.fn(), })); -function run(handler: Parameters[0]) { +function run( + handler: Parameters[0], + config?: Parameters[1] +) { const program = new Command() .option("--token ") .option("-v, --verbose") @@ -21,7 +24,7 @@ function run(handler: Parameters[0]) { new Command("probe") .argument("") .option("--flag") - .action(createDataAction(handler)) + .action(createDataAction(handler, config)) ); return program.parseAsync(["probe", "value", "--flag", "--token", "key"], { @@ -93,6 +96,18 @@ describe("createDataAction", () => { expect(stderr[0]).toContain("needs a Web Data API key"); }); + it("accepts a basic token when the action is not API key only", async () => { + vi.mocked(resolveAuthToken).mockResolvedValue({ + credential: { type: AUTH_TYPE.TOKEN, value: "dTpw" }, + source: "config", + }); + const handler = vi.fn().mockResolvedValue(undefined); + + await run(handler, { apiKeyOnly: false }); + + expect(handler).toHaveBeenCalledTimes(1); + }); + it("routes handler errors through the CLI error handler", async () => { vi.mocked(resolveAuthToken).mockResolvedValue({ credential: { type: AUTH_TYPE.API_KEY, value: "key" }, diff --git a/tests/docs/readme-commands.test.ts b/tests/docs/readme-commands.test.ts index 379191a..8462d95 100644 --- a/tests/docs/readme-commands.test.ts +++ b/tests/docs/readme-commands.test.ts @@ -12,6 +12,7 @@ import { createCodegenTargetCommands } from "../../src/scrape/commands/codegen-t import { createListTargetsCommand } from "../../src/scrape/commands/list-targets.js"; import { createScrapeCommand } from "../../src/scrape/commands/scrape.js"; import { createScreenshotCommand } from "../../src/scrape/commands/screenshot.js"; +import { createTaskCommand } from "../../src/scrape/commands/task.js"; import { createSearchCommand } from "../../src/search/commands/search.js"; const README_PATH = fileURLToPath(new URL("../../README.md", import.meta.url)); @@ -44,6 +45,7 @@ function buildProgram(): Command { createMapCommand(), createCrawlCommand(), createScreenshotCommand(schema), + createTaskCommand(), createListTargetsCommand(schema), ...createCodegenTargetCommands(schema), ]) { diff --git a/tests/platform/services/handle-cli-error.test.ts b/tests/platform/services/handle-cli-error.test.ts index 04c5c22..709431a 100644 --- a/tests/platform/services/handle-cli-error.test.ts +++ b/tests/platform/services/handle-cli-error.test.ts @@ -12,6 +12,7 @@ import { CrawlFailedError } from "../../../src/crawl/errors/crawl-failed-error.j import { ScrapeFailedError } from "../../../src/output/errors/scrape-failed-error.js"; import { CliUsageError } from "../../../src/platform/errors/cli-usage-error.js"; import { handleCliError } from "../../../src/platform/services/handle-cli-error.js"; +import { TaskFailedError } from "../../../src/scrape/errors/task-failed-error.js"; describe("handleCliError", () => { let exitCode: number | undefined; @@ -130,6 +131,13 @@ describe("handleCliError", () => { expect(stderr.join("\n")).toContain("Crawl abc ended with status faulted."); }); + it("maps task failures to exit code 7", () => { + const err = new TaskFailedError("123", "faulted"); + + expect(() => handleCliError(err)).toThrow("process.exit:7"); + expect(stderr.join("\n")).toContain("Task 123 ended with status faulted."); + }); + it("maps syscall-coded network failures in the cause chain to exit code 7", () => { const cause = Object.assign( new Error("getaddrinfo ENOTFOUND api.decodo.com"), diff --git a/tests/scrape/commands/attach-async-options.test.ts b/tests/scrape/commands/attach-async-options.test.ts new file mode 100644 index 0000000..c396d56 --- /dev/null +++ b/tests/scrape/commands/attach-async-options.test.ts @@ -0,0 +1,25 @@ +import { Command } from "commander"; +import { describe, expect, it } from "vitest"; +import { attachAsyncOptions } from "../../../src/scrape/commands/attach-async-options.js"; + +function parse(args: string[]): Record { + const command = attachAsyncOptions(new Command("target")).exitOverride(); + command.parse(args, { from: "user" }); + return command.opts(); +} + +describe("attachAsyncOptions", () => { + it("leaves the async options unset by default", () => { + expect(parse([])).toEqual({}); + }); + + it("parses --async on its own", () => { + expect(parse(["--async"])).toEqual({ async: true }); + }); + + it("parses --async with the wait options", () => { + expect( + parse(["--async", "--wait", "--poll-interval", "2", "--timeout", "30"]) + ).toEqual({ async: true, wait: true, pollInterval: 2, timeout: 30 }); + }); +}); diff --git a/tests/scrape/commands/attach-task-wait-options.test.ts b/tests/scrape/commands/attach-task-wait-options.test.ts new file mode 100644 index 0000000..c9556a5 --- /dev/null +++ b/tests/scrape/commands/attach-task-wait-options.test.ts @@ -0,0 +1,35 @@ +import { Command } from "commander"; +import { describe, expect, it } from "vitest"; +import { attachTaskWaitOptions } from "../../../src/scrape/commands/attach-task-wait-options.js"; + +const POSITIVE_INTEGER_ERROR = /Must be a positive integer/; + +function parse(args: string[]): Record { + const command = attachTaskWaitOptions( + new Command("target"), + "Wait for the task" + ).exitOverride(); + command.parse(args, { from: "user" }); + return command.opts(); +} + +describe("attachTaskWaitOptions", () => { + it("leaves the wait options unset by default", () => { + expect(parse([])).toEqual({}); + }); + + it("parses --wait with its options", () => { + expect( + parse(["--wait", "--poll-interval", "2", "--timeout", "30"]) + ).toEqual({ wait: true, pollInterval: 2, timeout: 30 }); + }); + + it.each([ + ["--poll-interval", "0"], + ["--timeout", "abc"], + ])("rejects %s %s", (flag, value) => { + expect(() => parse(["--wait", flag, value])).toThrow( + POSITIVE_INTEGER_ERROR + ); + }); +}); diff --git a/tests/scrape/commands/task.test.ts b/tests/scrape/commands/task.test.ts new file mode 100644 index 0000000..9df3226 --- /dev/null +++ b/tests/scrape/commands/task.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AUTH_TYPE } from "../../../src/auth/constants.js"; +import { resolveAuthToken } from "../../../src/auth/services/resolve-token.js"; +import { createTaskCommand } from "../../../src/scrape/commands/task.js"; +import { createDecodoClient } from "../../../src/scrape/services/client.js"; +import { runDataCommand } from "../../cli/helpers/run-data-command.js"; + +vi.mock("../../../src/auth/services/resolve-token.js", () => ({ + resolveAuthToken: vi.fn(), +})); + +vi.mock("../../../src/scrape/services/client.js", () => ({ + createDecodoClient: vi.fn(), +})); + +const RESULTS = { results: [{ content: { ok: true } }] }; + +describe("createTaskCommand", () => { + let exitCode: number | undefined; + let stdout: string[]; + let stderr: string[]; + const api = { + getStatus: vi.fn(), + getResults: vi.fn(), + }; + + beforeEach(() => { + exitCode = undefined; + stdout = []; + stderr = []; + for (const fn of Object.values(api)) { + fn.mockReset(); + } + api.getStatus.mockResolvedValue({ id: "123", status: "done" }); + api.getResults.mockResolvedValue(RESULTS); + Object.defineProperty(process.stdout, "isTTY", { + value: false, + configurable: true, + }); + vi.mocked(resolveAuthToken).mockResolvedValue({ + credential: { type: AUTH_TYPE.TOKEN, value: "dTpw" }, + source: "flag", + }); + vi.mocked(createDecodoClient).mockReturnValue({ + webScrapingApi: api, + } as never); + vi.spyOn(process, "exit").mockImplementation((code) => { + exitCode = code as number; + throw new Error(`process.exit:${code}`); + }); + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + vi.spyOn(console, "error").mockImplementation((message) => { + stderr.push(String(message)); + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("prints the task status as JSON with a basic token", async () => { + await runDataCommand(createTaskCommand(), ["task", "status", "123"]); + + expect(api.getStatus).toHaveBeenCalledWith("123"); + expect(stdout.join("")).toBe('{"id":"123","status":"done"}\n'); + }); + + it("prints the task result without checking the status", async () => { + await runDataCommand(createTaskCommand(), ["task", "results", "123"]); + + expect(api.getStatus).not.toHaveBeenCalled(); + expect(api.getResults).toHaveBeenCalledWith("123"); + expect(stdout.join("")).toBe('{"ok":true}\n'); + }); + + it("waits for the task before printing its result with --wait", async () => { + api.getStatus + .mockResolvedValueOnce({ id: "123", status: "pending" }) + .mockResolvedValueOnce({ id: "123", status: "done" }); + + await runDataCommand(createTaskCommand(), [ + "task", + "results", + "123", + "--wait", + "--poll-interval", + "1", + ]); + + expect(api.getStatus).toHaveBeenCalledTimes(2); + expect(stdout.join("")).toBe('{"ok":true}\n'); + }); + + it("exits 1 with a hint when the task has no results yet", async () => { + api.getResults.mockResolvedValue(null); + + await expect( + runDataCommand(createTaskCommand(), ["task", "results", "123"]) + ).rejects.toThrow("process.exit:1"); + + expect(exitCode).toBe(1); + expect(stderr.join("\n")).toContain("Task 123 has no results yet."); + }); + + it("exits 7 when the waited task is faulted", async () => { + api.getStatus.mockResolvedValue({ id: "123", status: "faulted" }); + + await expect( + runDataCommand(createTaskCommand(), ["task", "results", "123", "--wait"]) + ).rejects.toThrow("process.exit:7"); + + expect(exitCode).toBe(7); + expect(api.getResults).not.toHaveBeenCalled(); + }); + + it("exits 2 when --timeout is set without --wait", async () => { + await expect( + runDataCommand(createTaskCommand(), [ + "task", + "results", + "123", + "--timeout", + "30", + ]) + ).rejects.toThrow("process.exit:2"); + + expect(exitCode).toBe(2); + }); +}); diff --git a/tests/scrape/errors/task-failed-error.test.ts b/tests/scrape/errors/task-failed-error.test.ts new file mode 100644 index 0000000..ed6b403 --- /dev/null +++ b/tests/scrape/errors/task-failed-error.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { TaskFailedError } from "../../../src/scrape/errors/task-failed-error.js"; + +describe("TaskFailedError", () => { + it("names the task and its status", () => { + const err = new TaskFailedError("123", "faulted"); + + expect(err.message).toBe("Task 123 ended with status faulted."); + expect(err.name).toBe("TaskFailedError"); + expect(err.taskId).toBe("123"); + expect(err.status).toBe("faulted"); + }); +}); diff --git a/tests/scrape/errors/task-results-not-ready-error.test.ts b/tests/scrape/errors/task-results-not-ready-error.test.ts new file mode 100644 index 0000000..123a217 --- /dev/null +++ b/tests/scrape/errors/task-results-not-ready-error.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { TaskResultsNotReadyError } from "../../../src/scrape/errors/task-results-not-ready-error.js"; + +describe("TaskResultsNotReadyError", () => { + it("names the task and the command that waits for it", () => { + const err = new TaskResultsNotReadyError("123"); + + expect(err.message).toBe( + "Task 123 has no results yet. Run `decodo task results 123 --wait` to wait for them." + ); + expect(err.name).toBe("TaskResultsNotReadyError"); + expect(err.taskId).toBe("123"); + }); +}); diff --git a/tests/scrape/services/assert-async-flags.test.ts b/tests/scrape/services/assert-async-flags.test.ts new file mode 100644 index 0000000..0fcb094 --- /dev/null +++ b/tests/scrape/services/assert-async-flags.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { CliUsageError } from "../../../src/platform/errors/cli-usage-error.js"; +import { assertAsyncFlags } from "../../../src/scrape/services/assert-async-flags.js"; + +describe("assertAsyncFlags", () => { + it("allows plain scrapes", () => { + expect(() => assertAsyncFlags({})).not.toThrow(); + }); + + it("allows --async on its own", () => { + expect(() => assertAsyncFlags({ async: true })).not.toThrow(); + }); + + it("allows --async with --wait and its options", () => { + expect(() => + assertAsyncFlags({ + async: true, + wait: true, + pollInterval: 2, + timeout: 30, + }) + ).not.toThrow(); + }); + + it("rejects --wait without --async", () => { + expect(() => assertAsyncFlags({ wait: true })).toThrow( + new CliUsageError("--wait requires --async.") + ); + }); + + it.each([ + [{ async: true, pollInterval: 2 }, "--poll-interval requires --wait."], + [{ async: true, timeout: 30 }, "--timeout requires --wait."], + ])("rejects %j without --wait", (options, message) => { + expect(() => assertAsyncFlags(options)).toThrow(new CliUsageError(message)); + }); +}); diff --git a/tests/scrape/services/assert-task-wait-flags.test.ts b/tests/scrape/services/assert-task-wait-flags.test.ts new file mode 100644 index 0000000..252313a --- /dev/null +++ b/tests/scrape/services/assert-task-wait-flags.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { CliUsageError } from "../../../src/platform/errors/cli-usage-error.js"; +import { assertTaskWaitFlags } from "../../../src/scrape/services/assert-task-wait-flags.js"; + +describe("assertTaskWaitFlags", () => { + it("allows the wait options with --wait", () => { + expect(() => + assertTaskWaitFlags({ wait: true, pollInterval: 2, timeout: 30 }) + ).not.toThrow(); + }); + + it("allows no wait options at all", () => { + expect(() => assertTaskWaitFlags({})).not.toThrow(); + }); + + it.each([ + [{ pollInterval: 2 }, "--poll-interval requires --wait."], + [{ timeout: 30 }, "--timeout requires --wait."], + ])("rejects %j without --wait", (options, message) => { + expect(() => assertTaskWaitFlags(options)).toThrow( + new CliUsageError(message) + ); + }); +}); diff --git a/tests/scrape/services/command-builder.test.ts b/tests/scrape/services/command-builder.test.ts index 47e638d..7d76782 100644 --- a/tests/scrape/services/command-builder.test.ts +++ b/tests/scrape/services/command-builder.test.ts @@ -54,6 +54,22 @@ describe("configureTargetCommand", () => { true ); }); + + it("adds the async task options to a target command", () => { + const command = new Command("google-search"); + configureTargetCommand(command, "google_search", schema); + + const flags = command.options.map((opt) => opt.long); + + expect(flags).toEqual( + expect.arrayContaining([ + "--async", + "--wait", + "--poll-interval", + "--timeout", + ]) + ); + }); }); describe("buildScrapeBody", () => { diff --git a/tests/scrape/services/get-task-results.test.ts b/tests/scrape/services/get-task-results.test.ts new file mode 100644 index 0000000..d8d1125 --- /dev/null +++ b/tests/scrape/services/get-task-results.test.ts @@ -0,0 +1,26 @@ +import type { WebScrapingApi } from "@decodo/sdk-ts"; +import { describe, expect, it, vi } from "vitest"; +import { TaskResultsNotReadyError } from "../../../src/scrape/errors/task-results-not-ready-error.js"; +import { getTaskResults } from "../../../src/scrape/services/get-task-results.js"; + +function apiReturning(results: unknown): WebScrapingApi { + return { + getResults: vi.fn().mockResolvedValue(results), + } as unknown as WebScrapingApi; +} + +describe("getTaskResults", () => { + it("returns the results of a finished task", async () => { + const results = { results: [{ content: { ok: true } }] }; + + await expect(getTaskResults(apiReturning(results), "123")).resolves.toBe( + results + ); + }); + + it("throws a TaskResultsNotReadyError when there are no results yet", async () => { + await expect(getTaskResults(apiReturning(null), "123")).rejects.toThrow( + new TaskResultsNotReadyError("123") + ); + }); +}); diff --git a/tests/scrape/services/run-async-scrape.test.ts b/tests/scrape/services/run-async-scrape.test.ts new file mode 100644 index 0000000..fcc52c7 --- /dev/null +++ b/tests/scrape/services/run-async-scrape.test.ts @@ -0,0 +1,81 @@ +import type { WebScrapingApi } from "@decodo/sdk-ts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { TaskFailedError } from "../../../src/scrape/errors/task-failed-error.js"; +import { runAsyncScrape } from "../../../src/scrape/services/run-async-scrape.js"; + +const BODY = { target: "google_search", query: "coffee" }; +const TASK = { id: "123", status: "pending" }; + +function apiWith(overrides: Record = {}): WebScrapingApi { + return { + scrapeAsync: vi.fn().mockResolvedValue(TASK), + getStatus: vi.fn().mockResolvedValue({ id: "123", status: "done" }), + getResults: vi + .fn() + .mockResolvedValue({ results: [{ content: { ok: true } }] }), + ...overrides, + } as unknown as WebScrapingApi; +} + +describe("runAsyncScrape", () => { + let stdout: string[]; + let stderr: string[]; + + beforeEach(() => { + stdout = []; + stderr = []; + + Object.defineProperty(process.stdout, "isTTY", { + value: false, + configurable: true, + }); + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("prints the created task and does not wait without --wait", async () => { + const api = apiWith(); + + await runAsyncScrape(api, { body: BODY, options: { async: true } }); + + expect(api.scrapeAsync).toHaveBeenCalledWith(BODY); + expect(api.getStatus).not.toHaveBeenCalled(); + expect(api.getResults).not.toHaveBeenCalled(); + expect(stdout.join("")).toBe('{"id":"123","status":"pending"}\n'); + }); + + it("waits for the task and prints its result with --wait", async () => { + const api = apiWith(); + + await runAsyncScrape(api, { + body: BODY, + options: { async: true, wait: true }, + }); + + expect(api.getStatus).toHaveBeenCalledWith("123"); + expect(api.getResults).toHaveBeenCalledWith("123"); + expect(stderr.join("")).toBe("task 123 started\n"); + expect(stdout.join("")).toBe('{"ok":true}\n'); + }); + + it("fails without reading results when the task is faulted", async () => { + const api = apiWith({ + getStatus: vi.fn().mockResolvedValue({ id: "123", status: "faulted" }), + }); + + await expect( + runAsyncScrape(api, { body: BODY, options: { async: true, wait: true } }) + ).rejects.toThrow(new TaskFailedError("123", "faulted")); + expect(api.getResults).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/scrape/services/run-target-scrape.test.ts b/tests/scrape/services/run-target-scrape.test.ts index ad79477..f134a54 100644 --- a/tests/scrape/services/run-target-scrape.test.ts +++ b/tests/scrape/services/run-target-scrape.test.ts @@ -6,6 +6,7 @@ import { ConfigParseError } from "../../../src/auth/errors/config-parse-error.js import { resolveAuthToken } from "../../../src/auth/services/resolve-token.js"; import { attachScrapeOutputOptions } from "../../../src/output/commands/attach-output-options.js"; import { writeBinaryOutput } from "../../../src/platform/services/write-binary.js"; +import { attachAsyncOptions } from "../../../src/scrape/commands/attach-async-options.js"; import { createDecodoClient } from "../../../src/scrape/services/client.js"; import { createTargetAction } from "../../../src/scrape/services/run-target-scrape.js"; @@ -261,4 +262,65 @@ describe("createTargetAction", () => { }); expect(stdout).toBe('{"ok":true}\n'); }); + + it("creates a task instead of scraping when --async is set", async () => { + const scrape = vi.fn(); + const scrapeAsync = vi + .fn() + .mockResolvedValue({ id: "123", status: "pending" }); + vi.mocked(createDecodoClient).mockReturnValue({ + webScrapingApi: { scrape, scrapeAsync }, + } as never); + + const googleSearch = new Command("google-search") + .argument("") + .action(createTargetAction("google_search", BundledSchema.shared)); + attachScrapeOutputOptions(googleSearch); + attachAsyncOptions(googleSearch); + + const program = new Command() + .option("--token ") + .addCommand(googleSearch); + + await program.parseAsync( + ["google-search", "coffee", "--async", "--token", "test-token"], + { from: "user" } + ); + + expect(scrape).not.toHaveBeenCalled(); + expect(scrapeAsync).toHaveBeenCalledWith({ + target: "google_search", + query: "coffee", + parse: true, + markdown: false, + }); + expect(stdout).toBe('{"id":"123","status":"pending"}\n'); + }); + + it("exits with a usage error when --wait is set without --async", async () => { + const scrape = vi.fn(); + vi.mocked(createDecodoClient).mockReturnValue({ + webScrapingApi: { scrape }, + } as never); + + const googleSearch = new Command("google-search") + .argument("") + .action(createTargetAction("google_search", BundledSchema.shared)); + attachScrapeOutputOptions(googleSearch); + attachAsyncOptions(googleSearch); + + const program = new Command() + .option("--token ") + .addCommand(googleSearch); + + await expect( + program.parseAsync( + ["google-search", "coffee", "--wait", "--token", "test-token"], + { from: "user" } + ) + ).rejects.toThrow("process.exit:2"); + + expect(exitCode).toBe(2); + expect(scrape).not.toHaveBeenCalled(); + }); }); diff --git a/tests/scrape/services/settle-task.test.ts b/tests/scrape/services/settle-task.test.ts new file mode 100644 index 0000000..5283450 --- /dev/null +++ b/tests/scrape/services/settle-task.test.ts @@ -0,0 +1,24 @@ +import type { WebScrapingApi } from "@decodo/sdk-ts"; +import { describe, expect, it, vi } from "vitest"; +import { TaskFailedError } from "../../../src/scrape/errors/task-failed-error.js"; +import { settleTask } from "../../../src/scrape/services/settle-task.js"; + +function apiWith(status: string): WebScrapingApi { + return { + getStatus: vi.fn().mockResolvedValue({ id: "123", status }), + } as unknown as WebScrapingApi; +} + +describe("settleTask", () => { + it("resolves when the task is done", async () => { + await expect(settleTask(apiWith("done"), "123", {})).resolves.toBe( + undefined + ); + }); + + it("throws a TaskFailedError when the task is faulted", async () => { + await expect(settleTask(apiWith("faulted"), "123", {})).rejects.toThrow( + new TaskFailedError("123", "faulted") + ); + }); +}); diff --git a/tests/scrape/services/wait-for-task.test.ts b/tests/scrape/services/wait-for-task.test.ts new file mode 100644 index 0000000..f46658f --- /dev/null +++ b/tests/scrape/services/wait-for-task.test.ts @@ -0,0 +1,61 @@ +import { TimeoutError, type WebScrapingApi } from "@decodo/sdk-ts"; +import { describe, expect, it, vi } from "vitest"; +import { waitForTask } from "../../../src/scrape/services/wait-for-task.js"; + +function apiReturning(...statuses: string[]): WebScrapingApi { + const getStatus = vi.fn(); + for (const status of statuses) { + getStatus.mockResolvedValueOnce({ id: "123", status }); + } + return { getStatus } as unknown as WebScrapingApi; +} + +describe("waitForTask", () => { + it("polls until the task is no longer pending", async () => { + const api = apiReturning("pending", "pending", "done"); + + const task = await waitForTask(api, "123", { + pollIntervalMs: 1, + timeoutMs: 1000, + }); + + expect(task.status).toBe("done"); + expect(api.getStatus).toHaveBeenCalledTimes(3); + }); + + it("returns a finished task without waiting", async () => { + const api = apiReturning("faulted"); + + const task = await waitForTask(api, "123", { + pollIntervalMs: 1000, + timeoutMs: 1, + }); + + expect(task.status).toBe("faulted"); + expect(api.getStatus).toHaveBeenCalledTimes(1); + }); + + it("uses the time left before the deadline instead of giving up early", async () => { + const api = apiReturning("pending", "done"); + + const task = await waitForTask(api, "123", { + pollIntervalMs: 60_000, + timeoutMs: 20, + }); + + expect(task.status).toBe("done"); + expect(api.getStatus).toHaveBeenCalledTimes(2); + }); + + it("throws a TimeoutError naming the task id", async () => { + const api = apiReturning("pending", "pending"); + + await expect( + waitForTask(api, "123", { pollIntervalMs: 2000, timeoutMs: 1000 }) + ).rejects.toThrow( + new TimeoutError( + "Task 123 did not finish within 1s. It is still running." + ) + ); + }); +});