From bbb0fe732514e64c337e7851197ddd98d9e6ef8b Mon Sep 17 00:00:00 2001 From: "agne.statkeviciute" Date: Fri, 27 Nov 2026 10:47:12 +0200 Subject: [PATCH 1/3] 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." + ) + ); + }); +}); From db16909025af3917116f4002a787879ea9e761d0 Mon Sep 17 00:00:00 2001 From: "agne.statkeviciute" Date: Fri, 27 Nov 2026 14:03:43 +0200 Subject: [PATCH 2/3] feat: add async task flow to target commands --- README.md | 4 +- docs/ARCHITECTURE.md | 7 ++- src/cli/services/run-data-action.ts | 12 +--- src/cli/types/data-action.ts | 4 -- .../commands/attach-task-wait-options.ts | 7 +-- src/scrape/commands/task.ts | 27 ++++---- src/scrape/constants.ts | 6 +- src/scrape/services/get-task-results.ts | 11 ++-- src/scrape/services/run-async-scrape.ts | 12 ++-- src/scrape/services/run-target-scrape.ts | 5 ++ src/scrape/services/settle-task.ts | 24 ++++---- src/scrape/services/wait-for-task.ts | 34 ----------- tests/cli/services/run-data-action.test.ts | 19 +----- tests/scrape/commands/task.test.ts | 60 ++++++++++++------ .../scrape/services/get-task-results.test.ts | 8 +-- .../scrape/services/run-async-scrape.test.ts | 36 +++++------ .../scrape/services/run-target-scrape.test.ts | 39 ++++++++++-- tests/scrape/services/settle-task.test.ts | 40 +++++++++--- tests/scrape/services/wait-for-task.test.ts | 61 ------------------- 19 files changed, 180 insertions(+), 236 deletions(-) delete mode 100644 src/scrape/services/wait-for-task.ts delete mode 100644 tests/scrape/services/wait-for-task.test.ts diff --git a/README.md b/README.md index b58eb06..0d28d38 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ decodo crawl results --wait -o pages.ndjson decodo crawl cancel ``` -`crawl results --wait` lets an agent start a crawl, keep working, and collect the pages later. With `--wait`, the CLI polls every `--poll-interval` seconds (default `5`) and gives up after `--timeout` seconds (default `3600`, exit code `6`); the crawl keeps running until you cancel it. The crawl id goes to stderr as soon as the crawl starts. A `truncated` or `cancelled` crawl prints a warning; a `faulted` crawl still prints its pages, then exits `7`. +`crawl results --wait` lets an agent start a crawl, keep working, and collect the pages later. With `--wait`, the CLI polls every `--poll-interval` seconds and gives up after `--timeout` seconds (default `3600`, exit code `6`); the crawl keeps running until you cancel it. The crawl id goes to stderr as soon as the crawl starts. A `truncated` or `cancelled` crawl prints a warning; a `faulted` crawl still prints its pages, then exits `7`. > **Upgrading from 1.x:** `decodo search` used the `google_search` scrape target. Use `decodo google-search` or `decodo bing-search` for the previous behaviour. @@ -211,7 +211,7 @@ Add `--wait` to create the task and print its result in one command: 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. +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. `--async` and the `task` commands need an API key; a basic auth token cannot use them. ## Output modes diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 66401dd..bd86e7c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,9 +35,10 @@ Command assembly is two-layered: `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. + SDK's `task` flow instead of a real-time scrape (`scrape/services/run-async-scrape.ts`); + `--wait` polls the task and prints its result. Endpoints, statuses and the poll interval + come from the schema through `webScrapingApi.flows`. Like the `task` commands, which run + through `cli/services/run-data-action.ts`, `--async` requires an API key. - 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 41a9a0d..0707845 100644 --- a/src/cli/services/run-data-action.ts +++ b/src/cli/services/run-data-action.ts @@ -5,17 +5,11 @@ 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 { - DataActionConfig, - DataActionHandler, -} from "../types/data-action.js"; +import type { DataActionHandler } from "../types/data-action.js"; import { getRootOpts } from "./global-opts.js"; import { verboseLog } from "./verbose-log.js"; -export function createDataAction( - handler: DataActionHandler, - { apiKeyOnly = true }: DataActionConfig = {} -) { +export function createDataAction(handler: DataActionHandler) { return async ( input: string, _localOptions: unknown, @@ -34,7 +28,7 @@ export function createDataAction( if (!auth.credential) { throw new AuthRequiredError(); } - if (apiKeyOnly && auth.credential.type !== AUTH_TYPE.API_KEY) { + if (auth.credential.type !== AUTH_TYPE.API_KEY) { throw new ApiKeyRequiredError(); } diff --git a/src/cli/types/data-action.ts b/src/cli/types/data-action.ts index 8dbcd5c..6b9aa06 100644 --- a/src/cli/types/data-action.ts +++ b/src/cli/types/data-action.ts @@ -7,10 +7,6 @@ export interface DataActionContext { verbose: boolean; } -export interface DataActionConfig { - apiKeyOnly?: boolean; -} - export type DataActionHandler = ( context: DataActionContext ) => Promise; diff --git a/src/scrape/commands/attach-task-wait-options.ts b/src/scrape/commands/attach-task-wait-options.ts index 20eea12..9affcb2 100644 --- a/src/scrape/commands/attach-task-wait-options.ts +++ b/src/scrape/commands/attach-task-wait-options.ts @@ -1,10 +1,7 @@ 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"; +import { DEFAULT_TASK_TIMEOUT_SECONDS } from "../constants.js"; export function attachTaskWaitOptions( command: Command, @@ -14,7 +11,7 @@ export function attachTaskWaitOptions( .option("--wait", waitHelp) .option( "--poll-interval ", - `Seconds between status checks (with --wait, default: ${DEFAULT_TASK_POLL_INTERVAL_SECONDS})`, + "Seconds between status checks (with --wait)", parsePollInterval ) .option( diff --git a/src/scrape/commands/task.ts b/src/scrape/commands/task.ts index 4b7a07a..391c9bf 100644 --- a/src/scrape/commands/task.ts +++ b/src/scrape/commands/task.ts @@ -3,6 +3,7 @@ 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 { TASK_FLOW } from "../constants.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"; @@ -18,12 +19,9 @@ function createTaskStatusCommand(): Command { .argument("", "Task id") .option("--pretty", "Pretty-print JSON on stdout") .action( - createDataAction( - async ({ api, input, options }) => { - writeJsonOutput(await api.getStatus(input), options); - }, - { apiKeyOnly: false } - ) + createDataAction(async ({ api, input, options }) => { + writeJsonOutput(await api.flows.status(TASK_FLOW, input), options); + }) ); } @@ -38,17 +36,14 @@ function createTaskResultsCommand(): Command { 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); - } + createDataAction(async ({ api, input, options }) => { + assertTaskWaitFlags(options); + if (options.wait) { + await settleTask(api, input, options); + } - writeScrapeResponse(await getTaskResults(api, input), { options }); - }, - { apiKeyOnly: false } - ) + writeScrapeResponse(await getTaskResults(api, input), { options }); + }) ); } diff --git a/src/scrape/constants.ts b/src/scrape/constants.ts index 181becf..dc449f1 100644 --- a/src/scrape/constants.ts +++ b/src/scrape/constants.ts @@ -2,11 +2,7 @@ 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 TASK_FLOW = "task"; export const DEFAULT_TASK_TIMEOUT_SECONDS = 600; diff --git a/src/scrape/services/get-task-results.ts b/src/scrape/services/get-task-results.ts index 8fb90c6..8afe71d 100644 --- a/src/scrape/services/get-task-results.ts +++ b/src/scrape/services/get-task-results.ts @@ -1,13 +1,14 @@ -import type { TaskResultsResponse, WebScrapingApi } from "@decodo/sdk-ts"; +import type { SyncResponse, WebScrapingApi } from "@decodo/sdk-ts"; +import { TASK_FLOW } from "../constants.js"; 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) { +): Promise { + const results = await api.flows.results(TASK_FLOW, taskId); + if (results === undefined || results === null) { throw new TaskResultsNotReadyError(taskId); } - return results; + return results as SyncResponse; } diff --git a/src/scrape/services/run-async-scrape.ts b/src/scrape/services/run-async-scrape.ts index 325de62..26da41b 100644 --- a/src/scrape/services/run-async-scrape.ts +++ b/src/scrape/services/run-async-scrape.ts @@ -1,8 +1,9 @@ -import type { ScrapeRequest, WebScrapingApi } from "@decodo/sdk-ts"; +import type { 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 { TASK_FLOW } from "../constants.js"; import type { AsyncOptions } from "../types/async-options.js"; import { getTaskResults } from "./get-task-results.js"; import { settleTask } from "./settle-task.js"; @@ -18,17 +19,18 @@ export async function runAsyncScrape( api: WebScrapingApi, { body, input, options, outputContext }: RunAsyncScrapeOptions ): Promise { - const task = await api.scrapeAsync(body as unknown as ScrapeRequest); + const task = await api.flows.start(TASK_FLOW, body); if (!options.wait) { writeJsonOutput(task, options); return; } - process.stderr.write(`task ${task.id} started\n`); - await settleTask(api, task.id, options); + const taskId = String(task[api.flows.describe(TASK_FLOW, "job").idField]); + process.stderr.write(`task ${taskId} started\n`); + await settleTask(api, taskId, options); - writeScrapeResponse(await getTaskResults(api, task.id), { + writeScrapeResponse(await getTaskResults(api, taskId), { options, input, ...outputContext, diff --git a/src/scrape/services/run-target-scrape.ts b/src/scrape/services/run-target-scrape.ts index 40271fc..ea179c3 100644 --- a/src/scrape/services/run-target-scrape.ts +++ b/src/scrape/services/run-target-scrape.ts @@ -1,5 +1,7 @@ import type { DecodoSchema, ScrapeRequest } from "@decodo/sdk-ts"; import type { Command } from "commander"; +import { AUTH_TYPE } from "../../auth/constants.js"; +import { ApiKeyRequiredError } from "../../auth/errors/api-key-required-error.js"; import { AuthRequiredError } from "../../auth/errors/auth-required-error.js"; import { resolveAuthToken } from "../../auth/services/resolve-token.js"; import { getRootOpts } from "../../cli/services/global-opts.js"; @@ -32,6 +34,9 @@ async function executeScrape({ const client = createDecodoClient(credential, schema); if ((options as AsyncOptions).async) { + if (credential.type !== AUTH_TYPE.API_KEY) { + throw new ApiKeyRequiredError(); + } await runAsyncScrape(client.webScrapingApi, { body, input, diff --git a/src/scrape/services/settle-task.ts b/src/scrape/services/settle-task.ts index 05b1c9a..ba56765 100644 --- a/src/scrape/services/settle-task.ts +++ b/src/scrape/services/settle-task.ts @@ -1,25 +1,23 @@ import type { WebScrapingApi } from "@decodo/sdk-ts"; -import { - DEFAULT_TASK_POLL_INTERVAL_SECONDS, - DEFAULT_TASK_TIMEOUT_SECONDS, - DONE_TASK_STATUS, -} from "../constants.js"; +import { DEFAULT_TASK_TIMEOUT_SECONDS, TASK_FLOW } 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, + { flows }: 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, + const task = await flows.wait(TASK_FLOW, taskId, { + pollInterval: + options.pollInterval === undefined + ? undefined + : options.pollInterval * 1000, + timeout: (options.timeout ?? DEFAULT_TASK_TIMEOUT_SECONDS) * 1000, }); - if (task.status !== DONE_TASK_STATUS) { - throw new TaskFailedError(taskId, task.status); + if (flows.hasFailed(TASK_FLOW, task)) { + const { statusField } = flows.describe(TASK_FLOW, "job"); + throw new TaskFailedError(taskId, String(task[statusField])); } } diff --git a/src/scrape/services/wait-for-task.ts b/src/scrape/services/wait-for-task.ts deleted file mode 100644 index 5131116..0000000 --- a/src/scrape/services/wait-for-task.ts +++ /dev/null @@ -1,34 +0,0 @@ -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/tests/cli/services/run-data-action.test.ts b/tests/cli/services/run-data-action.test.ts index b1a5573..1683bb0 100644 --- a/tests/cli/services/run-data-action.test.ts +++ b/tests/cli/services/run-data-action.test.ts @@ -13,10 +13,7 @@ vi.mock("../../../src/scrape/services/client.js", () => ({ createDecodoClient: vi.fn(), })); -function run( - handler: Parameters[0], - config?: Parameters[1] -) { +function run(handler: Parameters[0]) { const program = new Command() .option("--token ") .option("-v, --verbose") @@ -24,7 +21,7 @@ function run( new Command("probe") .argument("") .option("--flag") - .action(createDataAction(handler, config)) + .action(createDataAction(handler)) ); return program.parseAsync(["probe", "value", "--flag", "--token", "key"], { @@ -96,18 +93,6 @@ 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/scrape/commands/task.test.ts b/tests/scrape/commands/task.test.ts index 9df3226..1b09c35 100644 --- a/tests/scrape/commands/task.test.ts +++ b/tests/scrape/commands/task.test.ts @@ -19,30 +19,36 @@ describe("createTaskCommand", () => { let exitCode: number | undefined; let stdout: string[]; let stderr: string[]; - const api = { - getStatus: vi.fn(), - getResults: vi.fn(), + const flows = { + status: vi.fn(), + wait: vi.fn(), + hasFailed: vi.fn(), + describe: vi.fn(), + results: vi.fn(), }; beforeEach(() => { exitCode = undefined; stdout = []; stderr = []; - for (const fn of Object.values(api)) { + for (const fn of Object.values(flows)) { fn.mockReset(); } - api.getStatus.mockResolvedValue({ id: "123", status: "done" }); - api.getResults.mockResolvedValue(RESULTS); + flows.status.mockResolvedValue({ id: "123", status: "done" }); + flows.wait.mockResolvedValue({ id: "123", status: "done" }); + flows.hasFailed.mockReturnValue(false); + flows.describe.mockReturnValue({ statusField: "status" }); + flows.results.mockResolvedValue(RESULTS); Object.defineProperty(process.stdout, "isTTY", { value: false, configurable: true, }); vi.mocked(resolveAuthToken).mockResolvedValue({ - credential: { type: AUTH_TYPE.TOKEN, value: "dTpw" }, + credential: { type: AUTH_TYPE.API_KEY, value: "key" }, source: "flag", }); vi.mocked(createDecodoClient).mockReturnValue({ - webScrapingApi: api, + webScrapingApi: { flows }, } as never); vi.spyOn(process, "exit").mockImplementation((code) => { exitCode = code as number; @@ -65,26 +71,22 @@ describe("createTaskCommand", () => { vi.restoreAllMocks(); }); - it("prints the task status as JSON with a basic token", async () => { + it("prints the task status as JSON", async () => { await runDataCommand(createTaskCommand(), ["task", "status", "123"]); - expect(api.getStatus).toHaveBeenCalledWith("123"); + expect(flows.status).toHaveBeenCalledWith("task", "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(flows.wait).not.toHaveBeenCalled(); + expect(flows.results).toHaveBeenCalledWith("task", "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", @@ -94,12 +96,15 @@ describe("createTaskCommand", () => { "1", ]); - expect(api.getStatus).toHaveBeenCalledTimes(2); + expect(flows.wait).toHaveBeenCalledWith("task", "123", { + pollInterval: 1000, + timeout: 600_000, + }); 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); + flows.results.mockResolvedValue(undefined); await expect( runDataCommand(createTaskCommand(), ["task", "results", "123"]) @@ -110,14 +115,29 @@ describe("createTaskCommand", () => { }); it("exits 7 when the waited task is faulted", async () => { - api.getStatus.mockResolvedValue({ id: "123", status: "faulted" }); + flows.wait.mockResolvedValue({ id: "123", status: "faulted" }); + flows.hasFailed.mockReturnValue(true); await expect( runDataCommand(createTaskCommand(), ["task", "results", "123", "--wait"]) ).rejects.toThrow("process.exit:7"); expect(exitCode).toBe(7); - expect(api.getResults).not.toHaveBeenCalled(); + expect(flows.results).not.toHaveBeenCalled(); + }); + + it("exits 3 with a basic token", async () => { + vi.mocked(resolveAuthToken).mockResolvedValue({ + credential: { type: AUTH_TYPE.TOKEN, value: "dTpw" }, + source: "flag", + }); + + await expect( + runDataCommand(createTaskCommand(), ["task", "status", "123"]) + ).rejects.toThrow("process.exit:3"); + + expect(exitCode).toBe(3); + expect(flows.status).not.toHaveBeenCalled(); }); it("exits 2 when --timeout is set without --wait", async () => { diff --git a/tests/scrape/services/get-task-results.test.ts b/tests/scrape/services/get-task-results.test.ts index d8d1125..3be14ae 100644 --- a/tests/scrape/services/get-task-results.test.ts +++ b/tests/scrape/services/get-task-results.test.ts @@ -5,7 +5,7 @@ import { getTaskResults } from "../../../src/scrape/services/get-task-results.js function apiReturning(results: unknown): WebScrapingApi { return { - getResults: vi.fn().mockResolvedValue(results), + flows: { results: vi.fn().mockResolvedValue(results) }, } as unknown as WebScrapingApi; } @@ -19,8 +19,8 @@ describe("getTaskResults", () => { }); it("throws a TaskResultsNotReadyError when there are no results yet", async () => { - await expect(getTaskResults(apiReturning(null), "123")).rejects.toThrow( - new TaskResultsNotReadyError("123") - ); + await expect( + getTaskResults(apiReturning(undefined), "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 index fcc52c7..1f3d919 100644 --- a/tests/scrape/services/run-async-scrape.test.ts +++ b/tests/scrape/services/run-async-scrape.test.ts @@ -6,15 +6,17 @@ 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 +function apiWith(status = "done") { + const flows = { + start: vi.fn().mockResolvedValue(TASK), + wait: vi.fn().mockResolvedValue({ id: "123", status }), + hasFailed: vi.fn().mockReturnValue(status === "faulted"), + describe: vi.fn().mockReturnValue({ idField: "id", statusField: "status" }), + results: vi .fn() .mockResolvedValue({ results: [{ content: { ok: true } }] }), - ...overrides, - } as unknown as WebScrapingApi; + }; + return { api: { flows } as unknown as WebScrapingApi, flows }; } describe("runAsyncScrape", () => { @@ -44,38 +46,36 @@ describe("runAsyncScrape", () => { }); it("prints the created task and does not wait without --wait", async () => { - const api = apiWith(); + const { api, flows } = 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(flows.start).toHaveBeenCalledWith("task", BODY); + expect(flows.wait).not.toHaveBeenCalled(); + expect(flows.results).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(); + const { api, flows } = apiWith(); await runAsyncScrape(api, { body: BODY, options: { async: true, wait: true }, }); - expect(api.getStatus).toHaveBeenCalledWith("123"); - expect(api.getResults).toHaveBeenCalledWith("123"); + expect(flows.wait).toHaveBeenCalledWith("task", "123", expect.anything()); + expect(flows.results).toHaveBeenCalledWith("task", "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" }), - }); + const { api, flows } = apiWith("faulted"); await expect( runAsyncScrape(api, { body: BODY, options: { async: true, wait: true } }) ).rejects.toThrow(new TaskFailedError("123", "faulted")); - expect(api.getResults).not.toHaveBeenCalled(); + expect(flows.results).not.toHaveBeenCalled(); }); }); diff --git a/tests/scrape/services/run-target-scrape.test.ts b/tests/scrape/services/run-target-scrape.test.ts index f134a54..4de5a52 100644 --- a/tests/scrape/services/run-target-scrape.test.ts +++ b/tests/scrape/services/run-target-scrape.test.ts @@ -265,11 +265,13 @@ describe("createTargetAction", () => { 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" }); + const start = vi.fn().mockResolvedValue({ id: "123", status: "pending" }); + vi.mocked(resolveAuthToken).mockResolvedValue({ + credential: { type: AUTH_TYPE.API_KEY, value: "key" }, + source: "flag", + }); vi.mocked(createDecodoClient).mockReturnValue({ - webScrapingApi: { scrape, scrapeAsync }, + webScrapingApi: { scrape, flows: { start } }, } as never); const googleSearch = new Command("google-search") @@ -288,7 +290,7 @@ describe("createTargetAction", () => { ); expect(scrape).not.toHaveBeenCalled(); - expect(scrapeAsync).toHaveBeenCalledWith({ + expect(start).toHaveBeenCalledWith("task", { target: "google_search", query: "coffee", parse: true, @@ -297,6 +299,33 @@ describe("createTargetAction", () => { expect(stdout).toBe('{"id":"123","status":"pending"}\n'); }); + it("exits 3 when --async is used with a basic token", async () => { + const start = vi.fn(); + vi.mocked(createDecodoClient).mockReturnValue({ + webScrapingApi: { flows: { start } }, + } 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", "--async", "--token", "test-token"], + { from: "user" } + ) + ).rejects.toThrow("process.exit:3"); + + expect(exitCode).toBe(3); + expect(start).not.toHaveBeenCalled(); + }); + it("exits with a usage error when --wait is set without --async", async () => { const scrape = vi.fn(); vi.mocked(createDecodoClient).mockReturnValue({ diff --git a/tests/scrape/services/settle-task.test.ts b/tests/scrape/services/settle-task.test.ts index 5283450..7bd5b1e 100644 --- a/tests/scrape/services/settle-task.test.ts +++ b/tests/scrape/services/settle-task.test.ts @@ -3,21 +3,41 @@ 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; +function apiWith(status: string) { + const flows = { + wait: vi.fn().mockResolvedValue({ id: "123", status }), + hasFailed: vi.fn().mockReturnValue(status === "faulted"), + describe: vi.fn().mockReturnValue({ statusField: "status" }), + }; + return { api: { flows } as unknown as WebScrapingApi, flows }; } describe("settleTask", () => { - it("resolves when the task is done", async () => { - await expect(settleTask(apiWith("done"), "123", {})).resolves.toBe( - undefined - ); + it("waits on the task flow with the default timeout", async () => { + const { api, flows } = apiWith("done"); + + await expect(settleTask(api, "123", {})).resolves.toBe(undefined); + expect(flows.wait).toHaveBeenCalledWith("task", "123", { + pollInterval: undefined, + timeout: 600_000, + }); }); - it("throws a TaskFailedError when the task is faulted", async () => { - await expect(settleTask(apiWith("faulted"), "123", {})).rejects.toThrow( + it("passes the poll interval and timeout in milliseconds", async () => { + const { api, flows } = apiWith("done"); + + await settleTask(api, "123", { pollInterval: 2, timeout: 30 }); + + expect(flows.wait).toHaveBeenCalledWith("task", "123", { + pollInterval: 2000, + timeout: 30_000, + }); + }); + + it("throws a TaskFailedError when the flow reports a failed task", async () => { + const { api } = apiWith("faulted"); + + await expect(settleTask(api, "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 deleted file mode 100644 index f46658f..0000000 --- a/tests/scrape/services/wait-for-task.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -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." - ) - ); - }); -}); From b8333082c2b31533bf229aa5485718febbd497f7 Mon Sep 17 00:00:00 2001 From: "agne.statkeviciute" Date: Fri, 27 Nov 2026 14:24:56 +0200 Subject: [PATCH 3/3] feat: add async task flow to target commands --- docs/ARCHITECTURE.md | 10 +- src/cli/services/run-data-action.ts | 8 +- src/scrape/commands/codegen-job-commands.ts | 92 +++++++++++++++++++ src/scrape/commands/task.ts | 55 ----------- src/scrape/errors/task-failed-error.ts | 6 +- .../errors/task-results-not-ready-error.ts | 6 +- src/scrape/register.ts | 4 +- src/scrape/services/get-task-results.ts | 6 +- src/scrape/services/run-async-scrape.ts | 4 +- src/scrape/services/settle-task.ts | 11 ++- tests/cli/services/run-data-action.test.ts | 28 ++++++ tests/docs/readme-commands.test.ts | 8 +- .../services/handle-cli-error.test.ts | 4 +- ...k.test.ts => codegen-job-commands.test.ts} | 61 +++++++++++- tests/scrape/errors/task-failed-error.test.ts | 7 +- .../task-results-not-ready-error.test.ts | 5 +- tests/scrape/helpers/schema-with-cli-tools.ts | 31 +++++++ .../scrape/services/get-task-results.test.ts | 10 +- .../scrape/services/run-async-scrape.test.ts | 2 +- tests/scrape/services/settle-task.test.ts | 8 +- 20 files changed, 266 insertions(+), 100 deletions(-) create mode 100644 src/scrape/commands/codegen-job-commands.ts delete mode 100644 src/scrape/commands/task.ts rename tests/scrape/commands/{task.test.ts => codegen-job-commands.test.ts} (71%) create mode 100644 tests/scrape/helpers/schema-with-cli-tools.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bd86e7c..a574115 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -32,12 +32,16 @@ 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), `task` (with `task status|results`), plus one - generated command per API target from `codegen-target-commands.ts`. + `scrape`, `screenshot`, `targets` (list), plus one generated command per API target from + `codegen-target-commands.ts` and the job commands from `codegen-job-commands.ts`. +- `codegen-job-commands.ts` reads the schema's `cli` surface: every tool with a `status`, + `results` or `cancel` step of a job flow becomes `decodo ` (today + `task status|results`). A schema without that surface, such as an older bundled one, + yields no job commands. - Every generated target command takes `--async`, which creates an async task through the SDK's `task` flow instead of a real-time scrape (`scrape/services/run-async-scrape.ts`); `--wait` polls the task and prints its result. Endpoints, statuses and the poll interval - come from the schema through `webScrapingApi.flows`. Like the `task` commands, which run + come from the schema through `webScrapingApi.flows`. Like the job commands, which run through `cli/services/run-data-action.ts`, `--async` requires an API key. - 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 diff --git a/src/cli/services/run-data-action.ts b/src/cli/services/run-data-action.ts index 0707845..8297044 100644 --- a/src/cli/services/run-data-action.ts +++ b/src/cli/services/run-data-action.ts @@ -1,3 +1,4 @@ +import type { DecodoSchema } from "@decodo/sdk-ts"; import type { Command } from "commander"; import { AUTH_TYPE } from "../../auth/constants.js"; import { ApiKeyRequiredError } from "../../auth/errors/api-key-required-error.js"; @@ -9,7 +10,10 @@ import type { 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, + schema?: DecodoSchema +) { return async ( input: string, _localOptions: unknown, @@ -32,7 +36,7 @@ export function createDataAction(handler: DataActionHandler) { throw new ApiKeyRequiredError(); } - const { webScrapingApi } = createDecodoClient(auth.credential); + const { webScrapingApi } = createDecodoClient(auth.credential, schema); await handler({ api: webScrapingApi, input, options, verbose }); } catch (err) { handleCliError(err, { fallbackMessage: "Request failed." }); diff --git a/src/scrape/commands/codegen-job-commands.ts b/src/scrape/commands/codegen-job-commands.ts new file mode 100644 index 0000000..079d3d8 --- /dev/null +++ b/src/scrape/commands/codegen-job-commands.ts @@ -0,0 +1,92 @@ +import type { + DecodoSchema, + FlowSchema, + IrJobFlow, + IrSurfaceTool, +} from "@decodo/sdk-ts"; +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 { INTEGRATION_HEADER } from "../constants.js"; +import { assertTaskWaitFlags } from "../services/assert-task-wait-flags.js"; +import { getTaskResults } from "../services/get-task-results.js"; +import { snakeToKebab } from "../services/naming.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 createJobResultsCommand( + command: Command, + tool: IrSurfaceTool, + schema: DecodoSchema +): Command { + attachScrapeOutputOptions(command); + + return attachTaskWaitOptions( + command, + `Wait for the ${tool.flow} to finish before printing its result` + ).action( + createDataAction(async ({ api, input, options }) => { + assertTaskWaitFlags(options); + if (options.wait) { + await settleTask(api, tool.flow, input, options); + } + + writeScrapeResponse(await getTaskResults(api, tool.flow, input), { + options, + }); + }, schema) + ); +} + +function createJobStepCommand( + tool: IrSurfaceTool, + flow: IrJobFlow, + schema: DecodoSchema +): Command { + const command = new Command(tool.step) + .description(tool.description) + .argument("", tool.descriptions?.[flow.idField] ?? `${tool.flow} id`); + + if (tool.step === "results") { + return createJobResultsCommand(command, tool, schema); + } + + return command.option("--pretty", "Pretty-print JSON on stdout").action( + createDataAction(async ({ api, input, options }) => { + const job = + tool.step === "cancel" + ? await api.flows.cancel(tool.flow, input) + : await api.flows.status(tool.flow, input); + writeJsonOutput(job, options); + }, schema) + ); +} + +export function createCodegenJobCommands(schema: DecodoSchema): Command[] { + const flowSchema = schema as Partial; + const tools = flowSchema.getSurface?.(INTEGRATION_HEADER)?.tools ?? []; + const commands = new Map(); + + for (const tool of tools) { + const flow = flowSchema.getFlow?.(tool.flow); + if (flow?.pattern !== "job" || !tool.step || tool.step === "start") { + continue; + } + + const command = + commands.get(tool.flow) ?? + new Command(snakeToKebab(tool.flow)).description( + `Follow up on a ${tool.flow} started earlier` + ); + commands.set(tool.flow, command); + command.addCommand(createJobStepCommand(tool, flow, schema)); + } + + return [...commands.values()]; +} diff --git a/src/scrape/commands/task.ts b/src/scrape/commands/task.ts deleted file mode 100644 index 391c9bf..0000000 --- a/src/scrape/commands/task.ts +++ /dev/null @@ -1,55 +0,0 @@ -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 { TASK_FLOW } from "../constants.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.flows.status(TASK_FLOW, input), options); - }) - ); -} - -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 }); - }) - ); -} - -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/errors/task-failed-error.ts b/src/scrape/errors/task-failed-error.ts index ed05ca2..67297ab 100644 --- a/src/scrape/errors/task-failed-error.ts +++ b/src/scrape/errors/task-failed-error.ts @@ -1,10 +1,12 @@ export class TaskFailedError extends Error { + readonly flow: string; readonly status: string; readonly taskId: string; - constructor(taskId: string, status: string) { - super(`Task ${taskId} ended with status ${status}.`); + constructor(flow: string, taskId: string, status: string) { + super(`${flow} ${taskId} ended with status ${status}.`); this.name = "TaskFailedError"; + this.flow = flow; 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 index 1ab93e5..1635a44 100644 --- a/src/scrape/errors/task-results-not-ready-error.ts +++ b/src/scrape/errors/task-results-not-ready-error.ts @@ -1,11 +1,13 @@ export class TaskResultsNotReadyError extends Error { + readonly flow: string; readonly taskId: string; - constructor(taskId: string) { + constructor(flow: string, taskId: string) { super( - `Task ${taskId} has no results yet. Run \`decodo task results ${taskId} --wait\` to wait for them.` + `${flow} ${taskId} has no results yet. Run \`decodo ${flow} results ${taskId} --wait\` to wait for them.` ); this.name = "TaskResultsNotReadyError"; + this.flow = flow; this.taskId = taskId; } } diff --git a/src/scrape/register.ts b/src/scrape/register.ts index d39d675..68c7d2a 100644 --- a/src/scrape/register.ts +++ b/src/scrape/register.ts @@ -1,9 +1,9 @@ import type { Command } from "commander"; +import { createCodegenJobCommands } from "./commands/codegen-job-commands.js"; import { createCodegenTargetCommands } from "./commands/codegen-target-commands.js"; 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 { @@ -12,7 +12,7 @@ export async function createScrapeCommands(): Promise { return [ createScrapeCommand(schema), createScreenshotCommand(schema), - createTaskCommand(), + ...createCodegenJobCommands(schema), createListTargetsCommand(schema), ...createCodegenTargetCommands(schema), ]; diff --git a/src/scrape/services/get-task-results.ts b/src/scrape/services/get-task-results.ts index 8afe71d..ec62ab5 100644 --- a/src/scrape/services/get-task-results.ts +++ b/src/scrape/services/get-task-results.ts @@ -1,14 +1,14 @@ import type { SyncResponse, WebScrapingApi } from "@decodo/sdk-ts"; -import { TASK_FLOW } from "../constants.js"; import { TaskResultsNotReadyError } from "../errors/task-results-not-ready-error.js"; export async function getTaskResults( api: WebScrapingApi, + flow: string, taskId: string ): Promise { - const results = await api.flows.results(TASK_FLOW, taskId); + const results = await api.flows.results(flow, taskId); if (results === undefined || results === null) { - throw new TaskResultsNotReadyError(taskId); + throw new TaskResultsNotReadyError(flow, taskId); } return results as SyncResponse; } diff --git a/src/scrape/services/run-async-scrape.ts b/src/scrape/services/run-async-scrape.ts index 26da41b..d02a432 100644 --- a/src/scrape/services/run-async-scrape.ts +++ b/src/scrape/services/run-async-scrape.ts @@ -28,9 +28,9 @@ export async function runAsyncScrape( const taskId = String(task[api.flows.describe(TASK_FLOW, "job").idField]); process.stderr.write(`task ${taskId} started\n`); - await settleTask(api, taskId, options); + await settleTask(api, TASK_FLOW, taskId, options); - writeScrapeResponse(await getTaskResults(api, taskId), { + writeScrapeResponse(await getTaskResults(api, TASK_FLOW, taskId), { options, input, ...outputContext, diff --git a/src/scrape/services/settle-task.ts b/src/scrape/services/settle-task.ts index ba56765..d10bb80 100644 --- a/src/scrape/services/settle-task.ts +++ b/src/scrape/services/settle-task.ts @@ -1,14 +1,15 @@ import type { WebScrapingApi } from "@decodo/sdk-ts"; -import { DEFAULT_TASK_TIMEOUT_SECONDS, TASK_FLOW } from "../constants.js"; +import { DEFAULT_TASK_TIMEOUT_SECONDS } from "../constants.js"; import { TaskFailedError } from "../errors/task-failed-error.js"; import type { TaskWaitOptions } from "../types/async-options.js"; export async function settleTask( { flows }: WebScrapingApi, + flow: string, taskId: string, options: TaskWaitOptions ): Promise { - const task = await flows.wait(TASK_FLOW, taskId, { + const task = await flows.wait(flow, taskId, { pollInterval: options.pollInterval === undefined ? undefined @@ -16,8 +17,8 @@ export async function settleTask( timeout: (options.timeout ?? DEFAULT_TASK_TIMEOUT_SECONDS) * 1000, }); - if (flows.hasFailed(TASK_FLOW, task)) { - const { statusField } = flows.describe(TASK_FLOW, "job"); - throw new TaskFailedError(taskId, String(task[statusField])); + if (flows.hasFailed(flow, task)) { + const { statusField } = flows.describe(flow, "job"); + throw new TaskFailedError(flow, taskId, String(task[statusField])); } } diff --git a/tests/cli/services/run-data-action.test.ts b/tests/cli/services/run-data-action.test.ts index 1683bb0..d7e891c 100644 --- a/tests/cli/services/run-data-action.test.ts +++ b/tests/cli/services/run-data-action.test.ts @@ -1,3 +1,4 @@ +import { BundledSchema } from "@decodo/sdk-ts"; import { Command } from "commander"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AUTH_TYPE } from "../../../src/auth/constants.js"; @@ -93,6 +94,33 @@ describe("createDataAction", () => { expect(stderr[0]).toContain("needs a Web Data API key"); }); + it("creates the client with the schema it was given", async () => { + const credential = { type: AUTH_TYPE.API_KEY, value: "key" } as const; + vi.mocked(resolveAuthToken).mockResolvedValue({ + credential, + source: "flag", + }); + const program = new Command() + .option("--token ") + .addCommand( + new Command("probe") + .argument("") + .action( + createDataAction( + vi.fn().mockResolvedValue(undefined), + BundledSchema.shared + ) + ) + ); + + await program.parseAsync(["probe", "value"], { from: "user" }); + + expect(createDecodoClient).toHaveBeenCalledWith( + credential, + BundledSchema.shared + ); + }); + 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 8462d95..190ddb0 100644 --- a/tests/docs/readme-commands.test.ts +++ b/tests/docs/readme-commands.test.ts @@ -1,6 +1,5 @@ import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; -import { BundledSchema } from "@decodo/sdk-ts"; import { Command } from "commander"; import { describe, expect, it } from "vitest"; import { createResetCommand } from "../../src/auth/commands/reset.js"; @@ -8,12 +7,13 @@ import { createSetupCommand } from "../../src/auth/commands/setup.js"; import { createWhoamiCommand } from "../../src/auth/commands/whoami.js"; import { createCrawlCommand } from "../../src/crawl/commands/crawl.js"; import { createMapCommand } from "../../src/map/commands/map.js"; +import { createCodegenJobCommands } from "../../src/scrape/commands/codegen-job-commands.js"; import { createCodegenTargetCommands } from "../../src/scrape/commands/codegen-target-commands.js"; 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"; +import { schemaWithCliTools } from "../scrape/helpers/schema-with-cli-tools.js"; const README_PATH = fileURLToPath(new URL("../../README.md", import.meta.url)); @@ -30,7 +30,7 @@ const GLOBAL_FLAGS = new Set([ const SHELL_BREAK = new Set(["|", "&&", "||", ";", "&", ">", ">>", "<"]); function buildProgram(): Command { - const schema = BundledSchema.shared; + const schema = schemaWithCliTools(); const program = new Command("decodo") .version("0.0.0", "-V, --version") .option("-v, --verbose") @@ -45,7 +45,7 @@ function buildProgram(): Command { createMapCommand(), createCrawlCommand(), createScreenshotCommand(schema), - createTaskCommand(), + ...createCodegenJobCommands(schema), 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 709431a..be17add 100644 --- a/tests/platform/services/handle-cli-error.test.ts +++ b/tests/platform/services/handle-cli-error.test.ts @@ -132,10 +132,10 @@ describe("handleCliError", () => { }); it("maps task failures to exit code 7", () => { - const err = new TaskFailedError("123", "faulted"); + const err = new TaskFailedError("task", "123", "faulted"); expect(() => handleCliError(err)).toThrow("process.exit:7"); - expect(stderr.join("\n")).toContain("Task 123 ended with status faulted."); + 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", () => { diff --git a/tests/scrape/commands/task.test.ts b/tests/scrape/commands/codegen-job-commands.test.ts similarity index 71% rename from tests/scrape/commands/task.test.ts rename to tests/scrape/commands/codegen-job-commands.test.ts index 1b09c35..ba27300 100644 --- a/tests/scrape/commands/task.test.ts +++ b/tests/scrape/commands/codegen-job-commands.test.ts @@ -1,9 +1,12 @@ +import { BundledSchema } from "@decodo/sdk-ts"; +import type { Command } from "commander"; 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 { createCodegenJobCommands } from "../../../src/scrape/commands/codegen-job-commands.js"; import { createDecodoClient } from "../../../src/scrape/services/client.js"; import { runDataCommand } from "../../cli/helpers/run-data-command.js"; +import { schemaWithCliTools } from "../helpers/schema-with-cli-tools.js"; vi.mock("../../../src/auth/services/resolve-token.js", () => ({ resolveAuthToken: vi.fn(), @@ -15,7 +18,11 @@ vi.mock("../../../src/scrape/services/client.js", () => ({ const RESULTS = { results: [{ content: { ok: true } }] }; -describe("createTaskCommand", () => { +function createTaskCommand(): Command { + return createCodegenJobCommands(schemaWithCliTools())[0]; +} + +describe("createCodegenJobCommands", () => { let exitCode: number | undefined; let stdout: string[]; let stderr: string[]; @@ -71,6 +78,54 @@ describe("createTaskCommand", () => { vi.restoreAllMocks(); }); + it("builds no commands when the schema has no cli surface", () => { + expect(createCodegenJobCommands(BundledSchema.shared)).toEqual([]); + }); + + it("builds one command per flow with a subcommand per step", () => { + const commands = createCodegenJobCommands(schemaWithCliTools()); + + expect(commands.map((command) => command.name())).toEqual(["task"]); + expect(commands[0].commands.map((command) => command.name())).toEqual([ + "status", + "results", + ]); + expect(commands[0].commands[0].description()).toBe( + "Show the status of an async task as JSON" + ); + }); + + it("skips tools that start a job or belong to a call flow", () => { + const commands = createCodegenJobCommands( + schemaWithCliTools([ + { + name: "task_start", + description: "Start", + flow: "task", + step: "start", + }, + { name: "search", description: "Search", flow: "search" }, + ]) + ); + + expect(commands).toEqual([]); + }); + + it("creates the client with the schema the commands were built from", async () => { + const schema = schemaWithCliTools(); + + await runDataCommand(createCodegenJobCommands(schema)[0], [ + "task", + "status", + "123", + ]); + + expect(createDecodoClient).toHaveBeenCalledWith( + { type: AUTH_TYPE.API_KEY, value: "key" }, + schema + ); + }); + it("prints the task status as JSON", async () => { await runDataCommand(createTaskCommand(), ["task", "status", "123"]); @@ -111,7 +166,7 @@ describe("createTaskCommand", () => { ).rejects.toThrow("process.exit:1"); expect(exitCode).toBe(1); - expect(stderr.join("\n")).toContain("Task 123 has no results yet."); + expect(stderr.join("\n")).toContain("task 123 has no results yet."); }); it("exits 7 when the waited task is faulted", async () => { diff --git a/tests/scrape/errors/task-failed-error.test.ts b/tests/scrape/errors/task-failed-error.test.ts index ed6b403..942b63f 100644 --- a/tests/scrape/errors/task-failed-error.test.ts +++ b/tests/scrape/errors/task-failed-error.test.ts @@ -2,11 +2,12 @@ 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"); + it("names the flow, the task and its status", () => { + const err = new TaskFailedError("task", "123", "faulted"); - expect(err.message).toBe("Task 123 ended with status faulted."); + expect(err.message).toBe("task 123 ended with status faulted."); expect(err.name).toBe("TaskFailedError"); + expect(err.flow).toBe("task"); 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 index 123a217..bda0d44 100644 --- a/tests/scrape/errors/task-results-not-ready-error.test.ts +++ b/tests/scrape/errors/task-results-not-ready-error.test.ts @@ -3,12 +3,13 @@ import { TaskResultsNotReadyError } from "../../../src/scrape/errors/task-result describe("TaskResultsNotReadyError", () => { it("names the task and the command that waits for it", () => { - const err = new TaskResultsNotReadyError("123"); + const err = new TaskResultsNotReadyError("task", "123"); expect(err.message).toBe( - "Task 123 has no results yet. Run `decodo task results 123 --wait` to wait for them." + "task 123 has no results yet. Run `decodo task results 123 --wait` to wait for them." ); expect(err.name).toBe("TaskResultsNotReadyError"); + expect(err.flow).toBe("task"); expect(err.taskId).toBe("123"); }); }); diff --git a/tests/scrape/helpers/schema-with-cli-tools.ts b/tests/scrape/helpers/schema-with-cli-tools.ts new file mode 100644 index 0000000..a299a6e --- /dev/null +++ b/tests/scrape/helpers/schema-with-cli-tools.ts @@ -0,0 +1,31 @@ +import { + BundledSchema, + type DecodoSchema, + type FlowSchema, + type IrSurfaceTool, +} from "@decodo/sdk-ts"; + +export const TASK_TOOLS: IrSurfaceTool[] = [ + { + name: "task_status", + description: "Show the status of an async task as JSON", + flow: "task", + step: "status", + descriptions: { id: "Task id" }, + }, + { + name: "task_results", + description: "Print the result of an async task", + flow: "task", + step: "results", + descriptions: { id: "Task id" }, + }, +]; + +export function schemaWithCliTools( + tools: IrSurfaceTool[] = TASK_TOOLS +): DecodoSchema { + const schema = Object.create(BundledSchema.shared) as FlowSchema; + schema.getSurface = (client) => (client === "cli" ? { tools } : undefined); + return schema; +} diff --git a/tests/scrape/services/get-task-results.test.ts b/tests/scrape/services/get-task-results.test.ts index 3be14ae..dfb1e2a 100644 --- a/tests/scrape/services/get-task-results.test.ts +++ b/tests/scrape/services/get-task-results.test.ts @@ -13,14 +13,14 @@ 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 - ); + await expect( + getTaskResults(apiReturning(results), "task", "123") + ).resolves.toBe(results); }); it("throws a TaskResultsNotReadyError when there are no results yet", async () => { await expect( - getTaskResults(apiReturning(undefined), "123") - ).rejects.toThrow(new TaskResultsNotReadyError("123")); + getTaskResults(apiReturning(undefined), "task", "123") + ).rejects.toThrow(new TaskResultsNotReadyError("task", "123")); }); }); diff --git a/tests/scrape/services/run-async-scrape.test.ts b/tests/scrape/services/run-async-scrape.test.ts index 1f3d919..e074570 100644 --- a/tests/scrape/services/run-async-scrape.test.ts +++ b/tests/scrape/services/run-async-scrape.test.ts @@ -75,7 +75,7 @@ describe("runAsyncScrape", () => { await expect( runAsyncScrape(api, { body: BODY, options: { async: true, wait: true } }) - ).rejects.toThrow(new TaskFailedError("123", "faulted")); + ).rejects.toThrow(new TaskFailedError("task", "123", "faulted")); expect(flows.results).not.toHaveBeenCalled(); }); }); diff --git a/tests/scrape/services/settle-task.test.ts b/tests/scrape/services/settle-task.test.ts index 7bd5b1e..3b79e10 100644 --- a/tests/scrape/services/settle-task.test.ts +++ b/tests/scrape/services/settle-task.test.ts @@ -16,7 +16,7 @@ describe("settleTask", () => { it("waits on the task flow with the default timeout", async () => { const { api, flows } = apiWith("done"); - await expect(settleTask(api, "123", {})).resolves.toBe(undefined); + await expect(settleTask(api, "task", "123", {})).resolves.toBe(undefined); expect(flows.wait).toHaveBeenCalledWith("task", "123", { pollInterval: undefined, timeout: 600_000, @@ -26,7 +26,7 @@ describe("settleTask", () => { it("passes the poll interval and timeout in milliseconds", async () => { const { api, flows } = apiWith("done"); - await settleTask(api, "123", { pollInterval: 2, timeout: 30 }); + await settleTask(api, "task", "123", { pollInterval: 2, timeout: 30 }); expect(flows.wait).toHaveBeenCalledWith("task", "123", { pollInterval: 2000, @@ -37,8 +37,8 @@ describe("settleTask", () => { it("throws a TaskFailedError when the flow reports a failed task", async () => { const { api } = apiWith("faulted"); - await expect(settleTask(api, "123", {})).rejects.toThrow( - new TaskFailedError("123", "faulted") + await expect(settleTask(api, "task", "123", {})).rejects.toThrow( + new TaskFailedError("task", "123", "faulted") ); }); });