Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ You should see Markdown or parsed JSON within seconds. If you see an auth error,
| `decodo map <url>` | List a site's URLs, one per line (`--limit`, `--sitemap`, `--full`) |
| `decodo crawl <url>` | Start a crawl and print its id; `--wait` prints pages as NDJSON |
| `decodo screenshot <url>` | Capture a PNG screenshot (`-o` file or directory) |
| `decodo task status\|results <id>` | 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 |
Expand Down Expand Up @@ -193,6 +194,25 @@ decodo universal --help

Use `decodo <target> --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 <id>
decodo task results <id>
decodo task results <id> --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`).
Expand Down
8 changes: 6 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions src/cli/services/run-data-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Options>(handler: DataActionHandler<Options>) {
export function createDataAction<Options>(
handler: DataActionHandler<Options>,
{ apiKeyOnly = true }: DataActionConfig = {}
) {
return async (
input: string,
_localOptions: unknown,
Expand All @@ -28,7 +34,7 @@ export function createDataAction<Options>(handler: DataActionHandler<Options>) {
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();
}

Expand Down
1 change: 1 addition & 0 deletions src/cli/services/sort-commands-by-order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const ROOT_COMMAND_ORDER = [
"map",
"crawl",
"screenshot",
"task",
"setup",
"reset",
"whoami",
Expand Down
4 changes: 4 additions & 0 deletions src/cli/types/data-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ export interface DataActionContext<Options> {
verbose: boolean;
}

export interface DataActionConfig {
apiKeyOnly?: boolean;
}

export type DataActionHandler<Options> = (
context: DataActionContext<Options>
) => Promise<void>;
7 changes: 6 additions & 1 deletion src/platform/services/handle-cli-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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;
}

Expand Down
14 changes: 14 additions & 0 deletions src/scrape/commands/attach-async-options.ts
Original file line number Diff line number Diff line change
@@ -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)"
);
}
25 changes: 25 additions & 0 deletions src/scrape/commands/attach-task-wait-options.ts
Original file line number Diff line number Diff line change
@@ -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>",
`Seconds between status checks (with --wait, default: ${DEFAULT_TASK_POLL_INTERVAL_SECONDS})`,
parsePollInterval
)
.option(
"--timeout <seconds>",
`Give up waiting after this many seconds (with --wait, default: ${DEFAULT_TASK_TIMEOUT_SECONDS})`,
parsePositiveInt
);
}
60 changes: 60 additions & 0 deletions src/scrape/commands/task.ts
Original file line number Diff line number Diff line change
@@ -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("<id>", "Task id")
.option("--pretty", "Pretty-print JSON on stdout")
.action(
createDataAction<TaskStatusOptions>(
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("<id>", "Task id");

attachScrapeOutputOptions(command);

return attachTaskWaitOptions(
command,
"Wait for the task to finish before printing its result"
).action(
createDataAction<TaskResultsOptions>(
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());
}
13 changes: 13 additions & 0 deletions src/scrape/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
11 changes: 11 additions & 0 deletions src/scrape/errors/task-failed-error.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
11 changes: 11 additions & 0 deletions src/scrape/errors/task-results-not-ready-error.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
2 changes: 2 additions & 0 deletions src/scrape/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Command[]> {
Expand All @@ -11,6 +12,7 @@ export async function createScrapeCommands(): Promise<Command[]> {
return [
createScrapeCommand(schema),
createScreenshotCommand(schema),
createTaskCommand(),
createListTargetsCommand(schema),
...createCodegenTargetCommands(schema),
];
Expand Down
11 changes: 11 additions & 0 deletions src/scrape/services/assert-async-flags.ts
Original file line number Diff line number Diff line change
@@ -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);
}
15 changes: 15 additions & 0 deletions src/scrape/services/assert-task-wait-flags.ts
Original file line number Diff line number Diff line change
@@ -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.`);
}
}
}
2 changes: 2 additions & 0 deletions src/scrape/services/command-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -120,6 +121,7 @@ export function configureTargetCommand(
}

attachScrapeOutputOptions(command);
attachAsyncOptions(command);

return { target, primaryField, optionFields };
}
Expand Down
13 changes: 13 additions & 0 deletions src/scrape/services/get-task-results.ts
Original file line number Diff line number Diff line change
@@ -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<TaskResultsResponse> {
const results = await api.getResults(taskId);
if (results === null) {
throw new TaskResultsNotReadyError(taskId);
}
return results;
}
36 changes: 36 additions & 0 deletions src/scrape/services/run-async-scrape.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
input?: string;
options: AsyncOptions & OutputOptions;
outputContext?: Partial<WriteScrapeResponseContext>;
}

export async function runAsyncScrape(
api: WebScrapingApi,
{ body, input, options, outputContext }: RunAsyncScrapeOptions
): Promise<void> {
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,
});
}
Loading
Loading