Skip to content
Merged
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
17 changes: 11 additions & 6 deletions AGENTS.md

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A link that opens a Google Maps search results page instead of a place fails once with a clear message. The broken batch example link in the README was replaced.
- Short links (`maps.app.goo.gl/...`) are now always loaded in English. Google redirects them inside the page, so the English setting was lost and a signed-out profile got a localized page the scraper could not read. The tracking parameters that trigger Google's limited view (`entry`, `g_ep`) are also removed from the page the link lands on.
- Errors from any command are printed as a single message without a stack trace (use `--verbose` for details). Batch failure lines no longer include Playwright's internal call log.
- `revcli batch` finishes long lists again. A place that runs past `--location-timeout` is now really stopped and its browser closed before the next place starts, so the places after it no longer fail on the shared profile. A late result from a stopped place is never saved. If a stopped browser does not close within 15 seconds, the batch stops with exit code 1 and tells you to run again with `--resume`. In headed mode, time spent signing in counts against the timeout.
- `kill <pid>` (SIGTERM) and closing the terminal (SIGHUP) now close the browser and end revcli within a few seconds, with exit code 143 / 129 (Ctrl+C: 130). Before, revcli kept running and only `kill -9` stopped it.
- Places with thousands of reviews no longer slow down as the list grows. Each cycle used to read every review card on the page again; now it reads only the cards not collected yet. Nothing that was collected before is skipped.
- Output files are written to a temporary file and renamed, so a stopped run never leaves a half-written file.

### Added
- `revcli scrape --time-limit <minutes>` stops collecting after the given time and saves the reviews collected so far, with a warning that the result is partial.

### Changed
- The test suite now runs the in-page scroll, expand, session and navigation code in headless Chromium against local fixtures. CI installs Chromium for it; locally `npm test` needs `npx playwright install chromium` once.
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Scrape reviews from a single Google Maps location.
| `-f, --format <type>` | `json` | Output format. Choices: `json`, `csv` |
| `--headless` | `false` | Hide the browser window. Browser shows by default so you can observe scraping and handle auth prompts |
| `--delay <ms>` | `3000` | Delay in milliseconds between scroll actions. Increase if getting rate-limited |
| `--time-limit <minutes>` | none | Stop collecting after this many minutes and save the reviews collected so far (a partial result, with a warning). Useful for places with thousands of reviews, where collection slows down as the list grows |
| `-v, --verbose` | `false` | Enable debug-level logging |

**Examples:**
Expand Down Expand Up @@ -139,7 +140,7 @@ Scrape reviews from multiple locations listed in a file. Produces one output fil
| `--headless` | `false` | Hide the browser window |
| `--delay <ms>` | `3000` | Delay in milliseconds between scroll actions within a location |
| `--location-delay <ms>` | `10000` | Delay in milliseconds between locations. Increase to reduce rate-limiting risk |
| `--location-timeout <ms>` | `300000` | Timeout per location in milliseconds (default: 5 minutes). Prevents indefinite hangs |
| `--location-timeout <ms>` | `300000` | Timeout per location in milliseconds (default: 5 minutes). A place that runs longer is stopped and its browser closed, then the batch goes on with the next place (no file is saved for the stopped place). In headed mode, time spent signing in counts too |
| `--resume` | `false` | Skip locations already scraped in a previous run. State tracked via `.revcli-state.json` in the output directory |
| `-v, --verbose` | `false` | Enable debug-level logging |

Expand Down
140 changes: 109 additions & 31 deletions src/commands/batch.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import { readFile, mkdir, writeFile, rename } from "node:fs/promises";
import { readFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { existsSync } from "node:fs";
import { z } from "zod";
import { createHash } from "node:crypto";
import { isGoogleMapsUrl, parseGoogleMapsInput } from "../utils/url.js";
import { isGoogleMapsUrl, parseGoogleMapsInput, type ParsedUrl } from "../utils/url.js";
import { logger } from "../utils/logger.js";
import { writeOutput } from "../output/write.js";
import { scrapeLocation } from "../scraper/scrape-location.js";
import { writeFileAtomic } from "../output/atomic.js";
import {
scrapeLocation,
type ScrapeLocationOptions,
} from "../scraper/scrape-location.js";
import { closeAllBrowsers } from "../scraper/browser.js";
import { withRetry } from "../core/retry.js";
import { runWithTimeout } from "../core/timeout.js";
import { shutdownSignal } from "../core/shutdown.js";
import { hasUnrecoverableKind } from "../core/errors.js";
import { safeErrorMessage } from "../core/fatal.js";
import { RateLimiter } from "../core/rate-limiter.js";
import { BatchProgress } from "../utils/progress.js";
import type { SortOrder, OutputFormat } from "../core/schema.js";
import type { SortOrder, OutputFormat, ScrapeResult } from "../core/schema.js";

export interface BatchOptions {
outputDir: string;
Expand All @@ -28,7 +36,7 @@ export interface BatchOptions {
const BatchStateSchema = z.object({
completed: z.array(z.string()),
});
type BatchState = z.infer<typeof BatchStateSchema>;
export type BatchState = z.infer<typeof BatchStateSchema>;

export async function batchCommand(
file: string,
Expand Down Expand Up @@ -70,32 +78,100 @@ export async function batchCommand(
return;
}

const { progress, stoppedOnStuckBrowser } = await runBatchLocations(
remaining,
options,
{ state, stateFile, signal: shutdownSignal },
{ scrape: (parsed, signal) => scrapeLocation(parsed, scrapeOptions(options), signal) },
);

progress.summary();

if (progress.failedCount > 0) {
process.exitCode = 1;
}

if (stoppedOnStuckBrowser) {
// The stuck browser keeps the process alive; close what we can, then end.
await Promise.race([
closeAllBrowsers(),
new Promise((resolve) => setTimeout(resolve, STUCK_CLOSE_MS)),
]);
// Let the summary reach a pipe (`| tee log`) before exiting.
await new Promise<void>((resolve) => process.stdout.write("", () => resolve()));
await new Promise<void>((resolve) => process.stderr.write("", () => resolve()));
process.exit(1);
}
}

/** How long to try closing a stuck browser before exiting anyway. */
const STUCK_CLOSE_MS = 5_000;

function scrapeOptions(options: BatchOptions): ScrapeLocationOptions {
return {
sort: options.sort,
maxReviews: options.maxReviews,
headless: options.headless,
delay: options.delay,
};
}

/** What `runBatchLocations` needs from the outside world. */
export interface BatchRunDeps {
/**
* Scrape one place. Required, with no default, so a test can never fall
* back to the real scrape (which opens the ~/.revcli credential store).
* Must stop and release its browser when `signal` aborts.
*/
scrape: (parsed: ParsedUrl, signal: AbortSignal) => Promise<ScrapeResult>;
}

export interface BatchRunResult {
progress: BatchProgress;
/** True when the batch stopped because a timed-out browser did not close. */
stoppedOnStuckBrowser: boolean;
}

/**
* Scrape each URL in turn, writing one output file per place and recording it
* in the resume state. Exported (with an injected `scrape`) for testing.
*/
export async function runBatchLocations(
remaining: string[],
options: BatchOptions,
run: {
state: BatchState;
stateFile: string;
/** Stops the batch (and the running scrape) when aborted – the shutdown signal. */
signal?: AbortSignal;
/** Override of SETTLE_GRACE_MS (tests). */
settleGraceMs?: number;
},
deps: BatchRunDeps,
): Promise<BatchRunResult> {
const { state, stateFile } = run;
const progress = new BatchProgress(remaining.length);
const rateLimiter = new RateLimiter(options.locationDelay);

for (const url of remaining) {
for (const [index, url] of remaining.entries()) {
if (run.signal?.aborted) break;
await rateLimiter.wait();
if (run.signal?.aborted) break;

try {
const parsed = parseGoogleMapsInput(url);
const scrapePromise = withRetry(
() =>
scrapeLocation(parsed, {
sort: options.sort,
maxReviews: options.maxReviews,
headless: options.headless,
delay: options.delay,
}),
url,
{ maxRetries: 2 },
);
const timeoutPromise = new Promise<never>((_, reject) =>
setTimeout(
() => reject(new Error(`Location timeout after ${options.locationTimeout / 1000}s`)),
options.locationTimeout,
),
// The timeout really stops the scrape and waits until its browser is
// closed, so the next place never meets a browser still holding the
// shared profile (issue #33).
const result = await runWithTimeout(
(signal) =>
withRetry(() => deps.scrape(parsed, signal), url, { maxRetries: 2, signal }),
{
timeoutMs: options.locationTimeout,
signal: run.signal,
settleGraceMs: run.settleGraceMs,
},
);
const result = await Promise.race([scrapePromise, timeoutPromise]);

const ext = options.format === "csv" ? ".csv" : ".json";
const baseSlug = slugify(result.business.name);
Expand All @@ -106,20 +182,22 @@ export async function batchCommand(

progress.success(result.business.name, result.reviews.length);
state.completed.push(url);
const tmpFile = stateFile + ".tmp";
await writeFile(tmpFile, JSON.stringify(state, null, 2));
await rename(tmpFile, stateFile);
await writeFileAtomic(stateFile, JSON.stringify(state, null, 2));
} catch (error) {
// Call log removed: Playwright errors can print element markup.
progress.failure(url, safeErrorMessage(error));
if (hasUnrecoverableKind(error, "BROWSER_NOT_CLOSED")) {
const notStarted = remaining.slice(index + 1);
logger.error(
`Stopping the batch: a browser may still be using the profile. ${notStarted.length} location(s) not started – run again with --resume.`,
);
for (const skipped of notStarted) progress.failure(skipped, "not started");
return { progress, stoppedOnStuckBrowser: true };
}
}
}

progress.summary();

if (progress.failedCount > 0) {
process.exitCode = 1;
}
return { progress, stoppedOnStuckBrowser: false };
}

export function parseInputFile(content: string): string[] {
Expand Down
11 changes: 9 additions & 2 deletions src/commands/scrape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { logger } from "../utils/logger.js";
import { writeOutput } from "../output/write.js";
import { scrapeLocation } from "../scraper/scrape-location.js";
import { withRetry } from "../core/retry.js";
import { shutdownSignal } from "../core/shutdown.js";

import type { SortOrder, OutputFormat } from "../core/schema.js";

Expand All @@ -13,6 +14,8 @@ export interface ScrapeOptions {
format: OutputFormat;
headless: boolean;
delay: number;
/** Minutes after which collection stops and the reviews so far are saved. */
timeLimit?: number;
}

export async function scrapeCommand(
Expand All @@ -23,6 +26,8 @@ export async function scrapeCommand(
logger.info(`Scraping reviews from: ${parsed.url}`);

const startTime = Date.now();
const deadline =
options.timeLimit != null ? startTime + options.timeLimit * 60_000 : undefined;

const result = await withRetry(
() =>
Expand All @@ -31,9 +36,11 @@ export async function scrapeCommand(
maxReviews: options.maxReviews,
headless: options.headless,
delay: options.delay,
}),
deadline,
}, shutdownSignal),
"scrape",
{ maxRetries: 2 },
// A signal stops the scrape without retries (issue #33).
{ maxRetries: 2, signal: shutdownSignal },
);

await writeOutput(result, options.output ?? null, options.format);
Expand Down
9 changes: 8 additions & 1 deletion src/core/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@
* - AUTH_POLL: interactive sign-in timed out or the window was closed
* - AUTH_REQUIRED: Google Maps shows a limited view; `revcli auth` is needed
* - NOT_A_PLACE: the link opened a search results page, not a single place
* - LOCATION_TIMEOUT: one place ran past `--location-timeout` and was stopped
* - BROWSER_NOT_CLOSED: a stopped place did not release its browser in time,
* so no further browser may be started on the shared profile
* - SHUTDOWN: revcli received SIGHUP/SIGINT/SIGTERM and is closing
*/
export type UnrecoverableKind =
| "NAV_VERIFY"
| "SORT_VERIFY"
| "AUTH_POLL"
| "AUTH_REQUIRED"
| "NOT_A_PLACE";
| "NOT_A_PLACE"
| "LOCATION_TIMEOUT"
| "BROWSER_NOT_CLOSED"
| "SHUTDOWN";

/**
* Typed error for failures that must NOT be retried by withRetry.
Expand Down
27 changes: 25 additions & 2 deletions src/core/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ export interface RetryOptions {
maxRetries: number;
baseDelayMs: number;
maxDelayMs: number;
/** Once aborted: no further attempt starts and the back-off sleep ends early. */
signal?: AbortSignal;
}

const DEFAULT_OPTIONS: RetryOptions = {
const DEFAULT_OPTIONS: Omit<RetryOptions, "signal"> = {
maxRetries: 3,
baseDelayMs: 2000,
maxDelayMs: 30000,
Expand All @@ -23,14 +25,20 @@ export async function withRetry<T>(
options: Partial<RetryOptions> = {},
): Promise<T> {
const opts = { ...DEFAULT_OPTIONS, ...options };
const { signal } = opts;
let lastError: Error | undefined;

for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
signal?.throwIfAborted();
try {
return await fn();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));

// Stopped from outside (timeout, shutdown): the attempt's own error is
// a consequence, so report the reason and do not retry or warn.
signal?.throwIfAborted();

if (attempt === opts.maxRetries) break;

// Don't retry on known unrecoverable errors. Debug level only: the caller
Expand All @@ -48,13 +56,28 @@ export async function withRetry<T>(
logger.warn(
`${label}: attempt ${attempt + 1}/${opts.maxRetries + 1} failed – retrying in ${Math.round(delay / 1000)}s`,
);
await new Promise((resolve) => setTimeout(resolve, delay));
await sleep(delay, signal);
}
}

throw lastError!;
}

/** Sleep for `ms`, ending early (rejecting with the reason) when `signal` aborts. */
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
const onAbort = (): void => {
clearTimeout(timer);
reject(signal?.reason);
};
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
signal?.addEventListener("abort", onAbort, { once: true });
});
}

export function isUnrecoverable(error: Error): boolean {
// Typed unrecoverable errors we throw ourselves are detected structurally
// (no string matching required). Retained below: substring fallback for
Expand Down
Loading