diff --git a/README.md b/README.md index 8840995..0d28d38 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 | @@ -177,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. @@ -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. `--async` and the `task` commands need an API key; a basic auth token cannot use them. + ## 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..a574115 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -32,8 +32,17 @@ 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), 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 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 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..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/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/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..9affcb2 --- /dev/null +++ b/src/scrape/commands/attach-task-wait-options.ts @@ -0,0 +1,22 @@ +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_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)", + parsePollInterval + ) + .option( + "--timeout ", + `Give up waiting after this many seconds (with --wait, default: ${DEFAULT_TASK_TIMEOUT_SECONDS})`, + parsePositiveInt + ); +} 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/constants.ts b/src/scrape/constants.ts index 5e424a1..dc449f1 100644 --- a/src/scrape/constants.ts +++ b/src/scrape/constants.ts @@ -2,6 +2,15 @@ export const INTEGRATION_HEADER = "cli"; export const SCHEMA_TTL_MS = 3_600_000; +export const TASK_FLOW = "task"; + +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..67297ab --- /dev/null +++ b/src/scrape/errors/task-failed-error.ts @@ -0,0 +1,13 @@ +export class TaskFailedError extends Error { + readonly flow: string; + readonly status: string; + readonly taskId: string; + + 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 new file mode 100644 index 0000000..1635a44 --- /dev/null +++ b/src/scrape/errors/task-results-not-ready-error.ts @@ -0,0 +1,13 @@ +export class TaskResultsNotReadyError extends Error { + readonly flow: string; + readonly taskId: string; + + constructor(flow: string, taskId: string) { + super( + `${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 7219eec..68c7d2a 100644 --- a/src/scrape/register.ts +++ b/src/scrape/register.ts @@ -1,4 +1,5 @@ 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"; @@ -11,6 +12,7 @@ export async function createScrapeCommands(): Promise { return [ createScrapeCommand(schema), createScreenshotCommand(schema), + ...createCodegenJobCommands(schema), 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..ec62ab5 --- /dev/null +++ b/src/scrape/services/get-task-results.ts @@ -0,0 +1,14 @@ +import type { SyncResponse, WebScrapingApi } from "@decodo/sdk-ts"; +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(flow, taskId); + if (results === undefined || results === null) { + 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 new file mode 100644 index 0000000..d02a432 --- /dev/null +++ b/src/scrape/services/run-async-scrape.ts @@ -0,0 +1,38 @@ +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"; + +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.flows.start(TASK_FLOW, body); + + if (!options.wait) { + writeJsonOutput(task, options); + return; + } + + const taskId = String(task[api.flows.describe(TASK_FLOW, "job").idField]); + process.stderr.write(`task ${taskId} started\n`); + await settleTask(api, TASK_FLOW, taskId, options); + + writeScrapeResponse(await getTaskResults(api, TASK_FLOW, taskId), { + options, + input, + ...outputContext, + }); +} diff --git a/src/scrape/services/run-target-scrape.ts b/src/scrape/services/run-target-scrape.ts index 177564e..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"; @@ -8,14 +10,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 +32,20 @@ async function executeScrape({ verbose = false, }: ExecuteScrapeOptions): Promise { 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, + options: options as AsyncOptions & OutputOptions, + outputContext, + }); + return; + } + const startedAt = Date.now(); const response = await client.webScrapingApi.scrape( body as unknown as ScrapeRequest @@ -88,6 +107,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..d10bb80 --- /dev/null +++ b/src/scrape/services/settle-task.ts @@ -0,0 +1,24 @@ +import type { WebScrapingApi } from "@decodo/sdk-ts"; +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(flow, taskId, { + pollInterval: + options.pollInterval === undefined + ? undefined + : options.pollInterval * 1000, + timeout: (options.timeout ?? DEFAULT_TASK_TIMEOUT_SECONDS) * 1000, + }); + + if (flows.hasFailed(flow, task)) { + const { statusField } = flows.describe(flow, "job"); + throw new TaskFailedError(flow, taskId, String(task[statusField])); + } +} 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..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 379191a..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,11 +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 { 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)); @@ -29,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") @@ -44,6 +45,7 @@ function buildProgram(): Command { createMapCommand(), createCrawlCommand(), createScreenshotCommand(schema), + ...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 04c5c22..be17add 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("task", "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/codegen-job-commands.test.ts b/tests/scrape/commands/codegen-job-commands.test.ts new file mode 100644 index 0000000..ba27300 --- /dev/null +++ b/tests/scrape/commands/codegen-job-commands.test.ts @@ -0,0 +1,211 @@ +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 { 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(), +})); + +vi.mock("../../../src/scrape/services/client.js", () => ({ + createDecodoClient: vi.fn(), +})); + +const RESULTS = { results: [{ content: { ok: true } }] }; + +function createTaskCommand(): Command { + return createCodegenJobCommands(schemaWithCliTools())[0]; +} + +describe("createCodegenJobCommands", () => { + let exitCode: number | undefined; + let stdout: string[]; + let stderr: string[]; + 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(flows)) { + fn.mockReset(); + } + 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.API_KEY, value: "key" }, + source: "flag", + }); + vi.mocked(createDecodoClient).mockReturnValue({ + webScrapingApi: { flows }, + } 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("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"]); + + 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(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 () => { + await runDataCommand(createTaskCommand(), [ + "task", + "results", + "123", + "--wait", + "--poll-interval", + "1", + ]); + + 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 () => { + flows.results.mockResolvedValue(undefined); + + 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 () => { + 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(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 () => { + 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..942b63f --- /dev/null +++ b/tests/scrape/errors/task-failed-error.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { TaskFailedError } from "../../../src/scrape/errors/task-failed-error.js"; + +describe("TaskFailedError", () => { + 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.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 new file mode 100644 index 0000000..bda0d44 --- /dev/null +++ b/tests/scrape/errors/task-results-not-ready-error.test.ts @@ -0,0 +1,15 @@ +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("task", "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.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/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..dfb1e2a --- /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 { + flows: { results: 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), "task", "123") + ).resolves.toBe(results); + }); + + it("throws a TaskResultsNotReadyError when there are no results yet", async () => { + await expect( + 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 new file mode 100644 index 0000000..e074570 --- /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(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 } }] }), + }; + return { api: { flows } as unknown as WebScrapingApi, flows }; +} + +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, flows } = apiWith(); + + await runAsyncScrape(api, { body: BODY, options: { async: true } }); + + 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, flows } = apiWith(); + + await runAsyncScrape(api, { + body: BODY, + options: { async: true, wait: true }, + }); + + 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, flows } = apiWith("faulted"); + + await expect( + runAsyncScrape(api, { body: BODY, options: { async: true, wait: true } }) + ).rejects.toThrow(new TaskFailedError("task", "123", "faulted")); + 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 ad79477..4de5a52 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,94 @@ 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 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, 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 program.parseAsync( + ["google-search", "coffee", "--async", "--token", "test-token"], + { from: "user" } + ); + + expect(scrape).not.toHaveBeenCalled(); + expect(start).toHaveBeenCalledWith("task", { + target: "google_search", + query: "coffee", + parse: true, + markdown: false, + }); + 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({ + 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..3b79e10 --- /dev/null +++ b/tests/scrape/services/settle-task.test.ts @@ -0,0 +1,44 @@ +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) { + 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("waits on the task flow with the default timeout", async () => { + const { api, flows } = apiWith("done"); + + await expect(settleTask(api, "task", "123", {})).resolves.toBe(undefined); + expect(flows.wait).toHaveBeenCalledWith("task", "123", { + pollInterval: undefined, + timeout: 600_000, + }); + }); + + it("passes the poll interval and timeout in milliseconds", async () => { + const { api, flows } = apiWith("done"); + + await settleTask(api, "task", "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, "task", "123", {})).rejects.toThrow( + new TaskFailedError("task", "123", "faulted") + ); + }); +});