diff --git a/AGENTS.md b/AGENTS.md index 8477718..61483fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,13 +98,13 @@ CLI (src/index.ts) ─── commander routes to 4 commands: │ validate (schema check), auth (Google sign-in) │ ├── src/commands/scrape.ts ── wraps scrapeLocation + retry + output -├── src/commands/batch.ts ── reads URL file, rate limiting, resume state, per-location timeout +├── src/commands/batch.ts ── reads URL file, rate limiting, resume state; runBatchLocations() (injected scrape) runs each place under runWithTimeout() ├── src/commands/validate.ts ── Zod schema validation of JSON files └── src/commands/auth.ts ── login (headed), status (headless), logout (delete profile) src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (used by both commands); delegates final payload construction to exported pure helper `assembleScrapeResult()` which reconciles `business.totalReviews` with `reviews.length` │ -├── browser.ts ── persistent Chromium context (~/.revcli/chrome-profile/), anti-detection, SIGINT cleanup +├── browser.ts ── persistent Chromium context (~/.revcli/chrome-profile/), anti-detection, browserLaunchOptions(), tracking + closeAllBrowsers(), closeOnAbort()/withBrowserSession(), installBrowserShutdown() ├── auth.ts ── getSessionState()/decideSessionState() (single source of truth for the Google session), hasLimitedView(), authRequiredError()/authRequiredMessage(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() ├── navigator.ts ── orchestrates state eviction → short-link redirect wait → consent → locale → tab (limited-view check before and after the review cards load) → sort; verifies loaded placeId against parsed.placeId ├── consent.ts ── Google consent handling, hl=en enforcement, g_ep/entry stripping @@ -120,10 +120,13 @@ src/core/ ├── retry.ts ── withRetry() – exponential backoff, isUnrecoverable() detection (instanceof UnrecoverableError + substring fallback) ├── errors.ts ── UnrecoverableError typed class with a `kind: UnrecoverableKind` union, hasUnrecoverableKind() – prefer over magic-substring Error for anything we throw ├── fatal.ts ── reportFatalError() – the top-level handler index.ts installs; describeFatalError() decides what it prints (message without Playwright call log; stack at debug only); re-exports safeErrorMessage() -└── rate-limiter.ts ── minimum delay between operations +├── rate-limiter.ts ── minimum delay between operations +├── timeout.ts ── runWithTimeout() – a time limit that aborts the task, waits for it to settle, then rejects LOCATION_TIMEOUT (BROWSER_NOT_CLOSED past the grace) +└── shutdown.ts ── installShutdownHandlers() (SIGHUP/SIGINT/SIGTERM → abort shutdownSignal, close browsers, exit 129/130/143) src/output/ ├── write.ts ── writeOutput() – centralized format dispatch +├── atomic.ts ── writeFileAtomic() – random temp name (`wx`) + rename, used by both writers ├── json.ts ── pretty JSON to file or stdout └── csv.ts ── CSV with formula injection protection (includes author_url column) @@ -151,7 +154,8 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **Batch resume**: `.revcli-state.json` in the output directory tracks completed URLs (Zod-validated, atomic writes). `--resume` flag skips them on re-run. - **Type-safe options**: `SortOrder` and `OutputFormat` union types in `schema.ts` provide compile-time safety. Constants `SORT_ORDERS` and `OUTPUT_FORMATS` are the single source of truth. - **Rating=0 sentinel (per-review only)**: When the stars selector is stale, individual reviews get `rating: 0` instead of being silently discarded; parser and extractor both warn. This applies to review-level ratings only. The business-level `business.rating` returned by `parseRatingText()` in business-extractor.ts uses `null` on parse failure – zero is treated as a valid user rating, not a sentinel. -- **Batch safety**: Filename deduplication prevents overwrites. Per-location timeout (`--location-timeout`, default 5 min) prevents indefinite hangs. Invalid URLs logged with warnings. +- **Batch safety**: Filename deduplication prevents overwrites. Invalid URLs logged with warnings. Per-location timeout (`--location-timeout`, default 5 min) goes through `runWithTimeout()` in `src/core/timeout.ts`, never `Promise.race`: the timer aborts a signal that `withRetry` (no further attempt, back-off cut short) and `scrapeLocation(parsed, options, signal)` honour – `withBrowserSession()` closes the browser on abort, so every pending Playwright call rejects – and the batch waits for the stopped scrape to settle before the next place, because Chromium allows one browser per profile directory (issue #33). A result that arrives after the timeout is discarded (`LOCATION_TIMEOUT`); a scrape that does not settle within `SETTLE_GRACE_MS` (15 s) yields `BROWSER_NOT_CLOSED`, which stops the batch (remaining places reported "not started", exit 1). The batch loop is `runBatchLocations()` with a **required** injected `scrape` so tests can never fall back to the real profile; `batchCommand` is the only caller passing `scrapeLocation`. Interactive sign-in in headed mode counts against the timeout. Output files are written atomically (`writeFileAtomic`). +- **Signal handling**: revcli launches with Playwright's `handleSIGINT/handleSIGTERM/handleSIGHUP: false` (`browserLaunchOptions()`), because Playwright's own SIGTERM/SIGHUP handlers close browsers *without exiting* and suppress Node's default exit – that is why `kill ` used to leave revcli running. `src/index.ts` calls `installBrowserShutdown()` once: the first signal aborts `shutdownSignal` (an `UnrecoverableError` kind `"SHUTDOWN"`; batch, `withRetry` and `launchBrowser` stop on it), closes every tracked browser and exits 128 + signal number (129/130/143), forced after `FORCE_EXIT_MS` (5 s); a later signal exits at once. `launchBrowser()` tracks the context right after launch and closes it if the rest of the launch fails. Do not install handlers as an import side effect – test workers import `browser.ts`. - **Sort order verification**: After selecting a sort order via the dropdown, `setSortOrder()` verifies the ARIA live region (`div[aria-live="polite"][aria-atomic="true"]`) contains the expected keyword (e.g., "newest"). Google Maps announces sort changes via this accessibility element. If verification fails, the scraper exits with an unrecoverable error. The `hl=en` locale enforcement guarantees English announcement text. - **Volatile state eviction between scrapes**: Before every navigation, `clearVolatileBrowserState()` in `browser.ts` uses CDP `Storage.clearDataForOrigin` to clear `service_workers,cache_storage,local_storage,indexeddb` for `https://www.google.com`. Cookies are intentionally preserved so Google auth stays intact. This prevents Google Maps' SPA shell from replaying a previously-loaded place via cached state during sequential scrapes. - **Navigation target verification**: After navigating, `navigateToReviews()` compares the loaded page's placeId (extracted from `page.url()`) against `parsed.placeId` using `placeIdsMatch()`. On mismatch, it throws an `UnrecoverableError` with kind `"NAV_VERIFY"` – `isUnrecoverable()` detects this structurally via `instanceof`, so `withRetry` will not mask a cross-contamination bug. Verification only runs when `canVerifyPlaceIdFormat(parsed.placeId)` is true (i.e., the `0x...:0x...` format). Short URLs, CID URLs, and ChIJ Place ID strings skip verification because their format does not align with `extractPlaceIdFromUrl()` output; the resolved placeId is logged at debug level for post-hoc audit. @@ -165,7 +169,7 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **Playwright locator scoping for comma-lists**: Never flat-concatenate selector constants like `` `${SELECTORS.reviewCard} ${SELECTORS.expandButton}` `` – CSS parses the comma as a selector-list union, leaving the second alternative unscoped and matching page-wide. Use chained locators (`page.locator(SELECTORS.reviewCard).locator(SELECTORS.expandButton)`) or, in-page, `card.querySelectorAll(SELECTORS.expandButton)` – both scope every alternative to the parent's subtree. `expandAllReviews()` in `extractor.ts` now scopes in-page this way. `tests/extractor-selectors.test.ts` pins the regression shape. - **Visible-filtered waits and counts**: every "first of several markers" wait uses `a.or(b).filter({ visible: true }).first().waitFor({ state: "visible", timeout })`, and every presence check uses `loc.filter({ visible: true }).count() > 0` – never `isVisible()` on a multi-match locator, and never an unfiltered `.first()`, because a hidden earlier match (a template, a duplicate link) stalls the wait or answers wrongly. Used by `setSortOrder()` and the session-marker read. - **In-page closures**: code passed to `page.evaluate`, `waitForFunction` or `locator.evaluate` runs in the browser. It may reference only its parameters and browser globals (pass Node constants as arguments – `SCROLL_STEP` read from Node scope crashed every scrape on the second scroll, issue #31), and must not declare named inner functions or `const f = () => …`: tsx/esbuild keepNames wraps those in `__name(...)`, which does not exist in the page. Anonymous inline callbacks (`.map((x) => …)`) are fine. Init scripts are passed as strings (`addInitScript({ content })`) so no transform can touch them. The vitest transform does **not** enable keepNames, so the browser tests catch Node-reference bugs but **not** `__name` bugs – that guard is a live `npm run dev` run that scrolls (e.g. `-m 30`). -- **Expand step**: Google removes a review's "More" button once clicked, so `expandAllReviews(page, skipIds)` uses mark-and-confirm, never positional `nth(i)`: one in-page scan (`scanExpandButtons`) stamps each *pending* button (rendered, not `aria-expanded="true"`) in cards not in `skipIds` with a Node-generated `data-revcli-expand` token (alphabet `[a-z0-9-]`, old stamps cleared first); each token is clicked and confirmed by `waitForFunction` (gone, disconnected, hidden, or `aria-expanded="true"` – this also covers owner-response buttons whichever way they react); up to 2 passes. The scroller passes its collected ids as `skipIds`, so a stuck button costs at most 2 clicks once. `ExpandResult` is for debug logs only: the truncation warning (`formatTruncationWarning()`) comes from the per-card `expandPending` flag that `extractReviews()` reads at extraction time, counted by `collectOnce()` for newly collected reviews and logged once at the end of `scrollAndCollectReviews()`. Every collect path (including the spinner retry) goes through `expandAndCollect()`. Still-truncated reviews are collected anyway (deferring risks losing the whole card from the virtualized list). See docs/selector-maintenance.md §5. +- **Expand step**: Google removes a review's "More" button once clicked, so `expandAllReviews(page, skipIds)` uses mark-and-confirm, never positional `nth(i)`: one in-page scan (`scanExpandButtons`) stamps each *pending* button (rendered, not `aria-expanded="true"`) in cards not in `skipIds` with a Node-generated `data-revcli-expand` token (alphabet `[a-z0-9-]`, old stamps cleared first); each token is clicked and confirmed by `waitForFunction` (gone, disconnected, hidden, or `aria-expanded="true"` – this also covers owner-response buttons whichever way they react); up to 2 passes. Collected cards carry `data-revcli-collected=""` (`COLLECTED_MARK_ATTR`, set by `markCollected()` after each collect) and are skipped by both `scanExpandButtons` and `extractReviews()` while the mark equals the card's current review id – so a cycle reads only new cards and its cost stays flat as the list grows (issue #33: re-reading every card made 4,000+ review places crawl), and a card element Google reuses for another review is read again. The scroller therefore passes no `skipIds`; a stuck button costs at most 2 clicks per cycle until its card is collected. `ScrollOptions.onCycle` reports `CycleTiming` (duration, new, total, `readCount`) per cycle; `--verbose` logs the same line. `ExpandResult` is for debug logs only: the truncation warning (`formatTruncationWarning()`) comes from the per-card `expandPending` flag that `extractReviews()` reads at extraction time, counted by `collectOnce()` for newly collected reviews and logged once at the end of `scrollAndCollectReviews()`. Every collect path (including the spinner retry) goes through `expandAndCollect()`. Still-truncated reviews are collected anyway (deferring risks losing the whole card from the virtualized list). See docs/selector-maintenance.md §5. - **Short links redirect in page script**: `maps.app.goo.gl` links no longer redirect with an HTTP 3xx, so `page.goto(..., domcontentloaded)` can resolve while the page is still on the short-link host. `waitForShortLinkRedirect()` in `navigator.ts` waits for the destination before `handleConsent()`/`ensureEnglishLocale()` run. Without it `hl=en` is added to the short link and lost in the redirect, and a signed-out or non-English profile gets a localized page that no English selector or banner text matches (the host constant `SHORT_LINK_HOST` and the pure helper `isShortLinkUrl()` live in `src/utils/url.ts`, which also derives the short-URL input regex from the same constant; pinned by `tests/browser/navigation.test.ts`, which also asserts the final URL has `hl=en` and no `entry`/`g_ep`). - **Non-place detection**: a link that lands on a search results page fails once with `UnrecoverableError` kind `"NOT_A_PLACE"` and `NOT_A_PLACE_MESSAGE` (which does not echo the URL – batch prints it). Detection is by path (`isSearchResultsUrl()`: `/maps/search…`), never by text (Google may serve that page in another language), and only after the `h1` wait (or the tab wait) times out, because CID and some redirect links pass through `/maps/search/` on their way to `/maps/place/`. Any other timeout is rethrown unchanged so real network flakiness is still retried. - **Fatal error reporting**: `index.ts` runs `program.parseAsync().catch(reportFatalError)`; `reportFatalError()` in `fatal.ts` prints `describeFatalError(err).message` once via `logger.error`, sets exit code 1, adds "Run again with --verbose for details." only for unexpected errors (not `isUnrecoverable` ones or `ENOENT`), and logs the stack at debug level only. Playwright's "Call log:" section is cut from the message and the stack (it can print the account link's label). `withRetry()` logs its "unrecoverable error" line at debug, so the message appears exactly once; command handlers do not catch `UnrecoverableError` themselves. Any error message from browser code that reaches output or logs goes through `safeErrorMessage()` (call log cut) – batch's per-location failure line, the `withRetry` debug line and the sign-in poll debug line. It is defined in `errors.ts` (no imports, so `retry.ts` can use it without a cycle) and re-exported from `fatal.ts`. @@ -179,7 +183,7 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - ESM-only (`"type": "module"`, `.js` extensions in imports) - Node 22+ required - Strict TypeScript, zero `any` types -- Tests use vitest (419 tests across 25 files) – pure-function tests for parser, schema, URL, CSV, JSON, retry, rate-limiter, consent, unrecoverable, fatal, batch-utils, validate, scroller, storage-types, scrape-location, selectors, extractor-selectors, extractor, auth, auth-command; `browser-import-guard` fails if any test file imports `launchBrowser` or `PROFILE_DIR`; plus 4 browser files in `tests/browser/` (scroll, expand, session, navigation) that run the in-page code in headless Chromium against local fixtures (see "Browser tests"). Other browser-coupled code is not unit tested, except where a narrow structural type or injected function makes it fakes-only (`ClosableBrowser` for `waitForBrowserClose`, `probe` for `waitForSignIn`, `navigateWithAuthFallback`) +- Tests use vitest (470 tests across 33 files) – pure-function tests for parser, schema, URL, CSV, JSON, atomic, retry, timeout, shutdown, rate-limiter, consent, unrecoverable, fatal, batch-utils, batch-run, validate, scroller, storage-types, scrape-location, selectors, extractor-selectors, extractor, auth, auth-command, browser-session; `browser-import-guard` fails if any test file imports `launchBrowser` or `PROFILE_DIR`; plus 7 browser files in `tests/browser/` (scroll, expand, session, navigation, collected-mark, abort, shutdown) that run the in-page code in headless Chromium against local fixtures (see "Browser tests"). `abort` and `shutdown` launch a real persistent browser on a **temporary** profile (`mkdtemp`, never `~/.revcli`); `shutdown` spawns `tests/browser/fixtures/signal-child.ts` with `HOME` pointed at a temp dir, sends SIGTERM/SIGINT and checks the exit code and, via `pgrep -f user-data-dir=` (no shell), that no Chromium is left. Other browser-coupled code is not unit tested, except where a narrow structural type or injected function makes it fakes-only (`ClosableBrowser` for `waitForBrowserClose`, `probe` for `waitForSignIn`, `navigateWithAuthFallback`) - `parseInputFile()`, `slugify()`, and `deduplicateFilename()` in batch.ts are exported for testability - `parseReview()`, `parseReviewCount()`, and `detectLanguage()` in parser.ts are exported for testability - `parseRatingText()` in business-extractor.ts is exported for testability (called Node-side after `page.evaluate()` returns the raw aria-label string) @@ -190,4 +194,5 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - `calculateStaleDelay()` and `shouldContinueScrolling()` in scroller.ts are exported for testability - `waitForBrowserClose()` in auth.ts takes the narrow structural `ClosableBrowser` (not `BrowserContext`) so its poll/close-event behaviour is testable against a fake, and `waitForSignIn()` returns the `SignInOutcome` union instead of `void` so each caller's closed-window policy is explicit and pinned by tests; its injectable `probe` keeps those tests browser-free - `decideSessionState()` and `authRequiredMessage()` in auth.ts, `formatTruncationWarning()` in extractor.ts, `isSearchResultsUrl()` in url.ts, `NOT_A_PLACE_MESSAGE` in navigator.ts, `navigateWithAuthFallback()` in scrape-location.ts (takes `navigate`/`waitForAuth`/`sessionProbe` functions, so it is tested with fakes), `hasUnrecoverableKind()` in errors.ts, `describeFatalError()`, `reportFatalError()` and `safeErrorMessage()` in fatal.ts, `englishLocaleTarget()` in consent.ts, `isShortLinkUrl()`/`SHORT_LINK_HOST` in url.ts, and `statusOutcome()`/`loginPlan()` in commands/auth.ts (the pure state → output/exit-code/next-step mapping of `auth status` and `auth`) are exported for testability +- `runWithTimeout()` (timeout.ts), `installShutdownHandlers()` (shutdown.ts, takes a `SignalSource`/`exit` and an optional `AbortController` so tests use fakes), `runBatchLocations()` (batch.ts, required `scrape`), `withBrowserSession()`/`closeOnAbort()`/`browserLaunchOptions()` (browser.ts), `markCollected()`/`COLLECTED_MARK_ATTR` (extractor.ts) and `writeFileAtomic()` (output/atomic.ts) are exported for testability (issue #33) - `extractOriginalLanguageFromButtonText()` in extractor.ts is exported for testability – pure helper that parses the human-readable language name out of the translated-review toggle button text ("See original (Polish)" → "Polish", handles nested parens like "Chinese (Simplified)") diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bee85a..76338c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` (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 ` 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. diff --git a/README.md b/README.md index cc2a5aa..e8e816b 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ Scrape reviews from a single Google Maps location. | `-f, --format ` | `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 ` | `3000` | Delay in milliseconds between scroll actions. Increase if getting rate-limited | +| `--time-limit ` | 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:** @@ -139,7 +140,7 @@ Scrape reviews from multiple locations listed in a file. Produces one output fil | `--headless` | `false` | Hide the browser window | | `--delay ` | `3000` | Delay in milliseconds between scroll actions within a location | | `--location-delay ` | `10000` | Delay in milliseconds between locations. Increase to reduce rate-limiting risk | -| `--location-timeout ` | `300000` | Timeout per location in milliseconds (default: 5 minutes). Prevents indefinite hangs | +| `--location-timeout ` | `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 | diff --git a/src/commands/batch.ts b/src/commands/batch.ts index 7e214ab..bdf575a 100644 --- a/src/commands/batch.ts +++ b/src/commands/batch.ts @@ -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; @@ -28,7 +36,7 @@ export interface BatchOptions { const BatchStateSchema = z.object({ completed: z.array(z.string()), }); -type BatchState = z.infer; +export type BatchState = z.infer; export async function batchCommand( file: string, @@ -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((resolve) => process.stdout.write("", () => resolve())); + await new Promise((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; +} + +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 { + 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((_, 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); @@ -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[] { diff --git a/src/commands/scrape.ts b/src/commands/scrape.ts index 143fe5b..8999ee3 100644 --- a/src/commands/scrape.ts +++ b/src/commands/scrape.ts @@ -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"; @@ -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( @@ -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( () => @@ -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); diff --git a/src/core/errors.ts b/src/core/errors.ts index df83ded..3f4e583 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -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. diff --git a/src/core/retry.ts b/src/core/retry.ts index dd01c8e..78d5ff6 100644 --- a/src/core/retry.ts +++ b/src/core/retry.ts @@ -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 = { maxRetries: 3, baseDelayMs: 2000, maxDelayMs: 30000, @@ -23,14 +25,20 @@ export async function withRetry( options: Partial = {}, ): Promise { 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 @@ -48,13 +56,28 @@ export async function withRetry( 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 { + 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 diff --git a/src/core/shutdown.ts b/src/core/shutdown.ts new file mode 100644 index 0000000..5d54664 --- /dev/null +++ b/src/core/shutdown.ts @@ -0,0 +1,95 @@ +/** + * SIGHUP/SIGINT/SIGTERM handling (issue #33). + * + * Playwright installs its own signal handlers while a browser runs; its + * SIGTERM handler closes the browsers but never exits, and its presence turns + * off Node's default "exit on SIGTERM" – so `kill ` left revcli running. + * revcli therefore launches with Playwright's handlers off (see + * `browserLaunchOptions`) and owns shutdown here: abort `shutdownSignal` so + * running work stops, close the browsers, and exit with 128 + signal number. + */ + +import { UnrecoverableError } from "./errors.js"; + +/** + * Exit code per signal: 128 + the signal number, the shell convention. + * SIGHUP (terminal closed) is included because Playwright's own SIGHUP handler + * would otherwise keep revcli alive the same way its SIGTERM handler did. + */ +export const SIGNAL_EXIT_CODES = { SIGHUP: 129, SIGINT: 130, SIGTERM: 143 } as const; +export type ShutdownSignalName = keyof typeof SIGNAL_EXIT_CODES; + +/** Exit at the latest this long after a signal, even if cleanup hangs. */ +export const FORCE_EXIT_MS = 5_000; + +/** The part of `process` the handlers need (a fake in tests). */ +export interface SignalSource { + on(event: ShutdownSignalName, listener: () => void): unknown; +} + +export interface ShutdownDeps { + source: SignalSource; + /** Close every open browser. Errors are ignored. */ + cleanup: () => Promise; + exit: (code: number) => void; + forceExitMs?: number; + /** Signals to handle. Default: all of SIGNAL_EXIT_CODES. */ + signals?: readonly ShutdownSignalName[]; +} + +const defaultController = new AbortController(); + +/** + * Aborted once revcli receives SIGHUP, SIGINT or SIGTERM. Long-running work (the batch + * loop, retries, browser launch) checks it so nothing new starts while the + * browsers are being closed. + */ +export const shutdownSignal: AbortSignal = defaultController.signal; + +/** + * Register the SIGHUP, SIGINT and SIGTERM handlers. Call once per process. + * The first signal aborts the shutdown signal, runs `cleanup`, and exits with + * that signal's code when cleanup settles or after `forceExitMs`. Any later + * signal exits at once (through `exit`, so Playwright's exit hook still kills + * Chromium). `exit` is called at most once. + */ +export function installShutdownHandlers( + deps: ShutdownDeps, + controller: AbortController = defaultController, +): void { + const forceExitMs = deps.forceExitMs ?? FORCE_EXIT_MS; + let exitCode: number | undefined; + let exited = false; + + const exitOnce = (code: number): void => { + if (exited) return; + exited = true; + deps.exit(code); + }; + + const onSignal = (name: ShutdownSignalName): void => { + if (exitCode !== undefined) { + // Already closing: a second signal means "stop now". + exitOnce(exitCode); + return; + } + exitCode = SIGNAL_EXIT_CODES[name]; + const code = exitCode; + controller.abort(new UnrecoverableError("SHUTDOWN", `Received ${name} – stopping`)); + + setTimeout(() => exitOnce(code), forceExitMs); + deps + .cleanup() + .catch(() => { + // Browser may already be closed; never print browser error text here. + }) + .finally(() => exitOnce(code)); + }; + + const names = deps.signals ?? (Object.keys(SIGNAL_EXIT_CODES) as ShutdownSignalName[]); + for (const name of names) { + // `on`, not `once`: a repeated signal must reach exitOnce instead of + // Node's default kill, which would skip Playwright's exit hook. + deps.source.on(name, () => onSignal(name)); + } +} diff --git a/src/core/timeout.ts b/src/core/timeout.ts new file mode 100644 index 0000000..d81332a --- /dev/null +++ b/src/core/timeout.ts @@ -0,0 +1,81 @@ +import { UnrecoverableError } from "./errors.js"; + +/** + * How long a stopped task may take to finish (close its browser) after its + * timeout. Past this, the browser may still hold the shared profile. + */ +export const SETTLE_GRACE_MS = 15_000; + +export interface TimeoutOptions { + timeoutMs: number; + /** Also stop the task when this aborts (e.g. a shutdown). */ + signal?: AbortSignal; + settleGraceMs?: number; +} + +/** Wait `ms`; the timer is cleared when `cancel` is called. */ +function delay(ms: number): { done: Promise; cancel: () => void } { + let timer: ReturnType | undefined; + const done = new Promise((resolve) => { + timer = setTimeout(resolve, ms); + }); + return { done, cancel: () => clearTimeout(timer) }; +} + +/** + * Run `task` with a time limit that really stops it (issue #33). + * + * The task gets a signal that aborts when the limit is reached (or when + * `options.signal` aborts); it must then stop and release what it holds. + * On timeout this waits for the task to settle, so the caller never starts + * the next task while the old one still runs, and then rejects with + * `LOCATION_TIMEOUT` – even if the task resolved late, so a late result is + * never used. If the task does not settle within `settleGraceMs`, it rejects + * with `BROWSER_NOT_CLOSED` instead: the caller must not start another + * browser on the same profile. + */ +export async function runWithTimeout( + task: (signal: AbortSignal) => Promise, + options: TimeoutOptions, +): Promise { + const controller = new AbortController(); + const signal = options.signal + ? AbortSignal.any([controller.signal, options.signal]) + : controller.signal; + + const running = task(signal); + const outcome = running.then( + (value) => ({ ok: true as const, value }), + (error: unknown) => ({ ok: false as const, error }), + ); + + const limit = delay(options.timeoutMs); + const first = await Promise.race([outcome, limit.done.then(() => "timeout" as const)]); + limit.cancel(); + + if (first !== "timeout") { + if (first.ok) return first.value; + throw first.error; + } + + const timeoutError = new UnrecoverableError( + "LOCATION_TIMEOUT", + `Location timeout after ${options.timeoutMs / 1000}s`, + ); + controller.abort(timeoutError); + + const grace = delay(options.settleGraceMs ?? SETTLE_GRACE_MS); + const settled = await Promise.race([ + outcome.then(() => true), + grace.done.then(() => false), + ]); + grace.cancel(); + + if (!settled) { + throw new UnrecoverableError( + "BROWSER_NOT_CLOSED", + "The timed-out place did not close its browser in time", + ); + } + throw timeoutError; +} diff --git a/src/index.ts b/src/index.ts index c28da91..9b47eb1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ import { } from "./commands/auth.js"; import { setVerbose } from "./utils/logger.js"; import { reportFatalError } from "./core/fatal.js"; +import { installBrowserShutdown } from "./scraper/browser.js"; import { SORT_ORDERS, OUTPUT_FORMATS } from "./core/schema.js"; import type { SortOrder, OutputFormat } from "./core/schema.js"; @@ -51,6 +52,11 @@ program parsePositiveInt, 3000, ) + .option( + "--time-limit ", + "stop collecting after this many minutes and save the reviews collected so far", + parsePositiveInt, + ) .option("-v, --verbose", "verbose logging", false) .action(async (url: string, opts) => { if (!(SORT_ORDERS as readonly string[]).includes(opts.sort)) { @@ -67,6 +73,7 @@ program format: opts.format as OutputFormat, headless: opts.headless, delay: opts.delay, + timeLimit: opts.timeLimit, }); }); @@ -165,6 +172,9 @@ auth await authLogoutCommand(); }); +// SIGHUP/SIGINT/SIGTERM close every browser and exit 129/130/143 (issue #33). +installBrowserShutdown(); + // parseAsync so errors from async actions reach one handler: print the message // once, no stack trace (debug level only), exit code 1. program.parseAsync().catch(reportFatalError); diff --git a/src/output/atomic.ts b/src/output/atomic.ts new file mode 100644 index 0000000..ec66eb9 --- /dev/null +++ b/src/output/atomic.ts @@ -0,0 +1,22 @@ +import { randomBytes } from "node:crypto"; +import { rename, unlink, writeFile } from "node:fs/promises"; + +/** + * Write a file so that it is either complete or not there: write a temporary + * file next to it, then rename (atomic on the same file system). A stop + * signal or crash mid-write leaves no half-written output (issue #33). + * + * The temporary name is random and opened with `wx` (fail if it exists), so + * a link planted at a guessable name in a shared folder is never written + * through. + */ +export async function writeFileAtomic(path: string, data: string): Promise { + const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`; + try { + await writeFile(tmp, data, { encoding: "utf-8", flag: "wx" }); + await rename(tmp, path); + } catch (err) { + await unlink(tmp).catch(() => {}); + throw err; + } +} diff --git a/src/output/csv.ts b/src/output/csv.ts index 6fb3165..0f5b052 100644 --- a/src/output/csv.ts +++ b/src/output/csv.ts @@ -1,4 +1,4 @@ -import { writeFile } from "node:fs/promises"; +import { writeFileAtomic } from "./atomic.js"; import type { ScrapeResult } from "../core/schema.js"; const CSV_HEADERS = [ @@ -57,7 +57,7 @@ export async function writeCsv( const csv = rows.join("\n") + "\n"; if (outputPath) { - await writeFile(outputPath, csv, "utf-8"); + await writeFileAtomic(outputPath, csv); } else { process.stdout.write(csv); } diff --git a/src/output/json.ts b/src/output/json.ts index 81fc76a..70a5fa4 100644 --- a/src/output/json.ts +++ b/src/output/json.ts @@ -1,4 +1,4 @@ -import { writeFile } from "node:fs/promises"; +import { writeFileAtomic } from "./atomic.js"; import type { ScrapeResult } from "../core/schema.js"; export async function writeJson( @@ -8,7 +8,7 @@ export async function writeJson( const json = JSON.stringify(result, null, 2); if (outputPath) { - await writeFile(outputPath, json, "utf-8"); + await writeFileAtomic(outputPath, json); } else { process.stdout.write(json + "\n"); } diff --git a/src/scraper/browser.ts b/src/scraper/browser.ts index 8ff0790..75ba0f1 100644 --- a/src/scraper/browser.ts +++ b/src/scraper/browser.ts @@ -5,6 +5,7 @@ import { chromium, type BrowserContext, type Page } from "playwright"; import { logger } from "../utils/logger.js"; import { safeErrorMessage } from "../core/errors.js"; import { VOLATILE_STORAGE_TYPES } from "./storage-types.js"; +import { installShutdownHandlers, shutdownSignal } from "../core/shutdown.js"; export interface BrowserOptions { headless: boolean; @@ -29,9 +30,47 @@ function ensureProfileDir(): void { chmodSync(PROFILE_DIR, 0o700); } +type PersistentLaunchOptions = NonNullable< + Parameters[1] +>; + +/** + * The options every revcli browser is launched with. Exported so the signal + * test can start a browser exactly like revcli does, on a temporary profile. + */ +export function browserLaunchOptions(options: BrowserOptions): PersistentLaunchOptions { + return { + headless: options.headless, + // revcli owns SIGHUP/SIGINT/SIGTERM (src/core/shutdown.ts). Playwright's + // own SIGTERM/SIGHUP handlers close browsers without exiting, which kept + // revcli alive after `kill ` (issue #33); its SIGINT handler raced ours. + handleSIGHUP: false, + handleSIGINT: false, + handleSIGTERM: false, + args: [ + "--disable-blink-features=AutomationControlled", + "--disable-dev-shm-usage", + "--lang=en-US", + ], + viewport: { width: 1366, height: 768 }, + locale: "en-US", + extraHTTPHeaders: { "Accept-Language": "en-US,en;q=0.9" }, + userAgent: + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36", + }; +} + +/** + * Launch the persistent revcli browser. Refuses (throws the shutdown reason) + * once `shutdownSignal` has aborted, and tracks the browser at once so the + * signal handler closes it. + */ export async function launchBrowser( options: BrowserOptions, ): Promise { + // Never start a browser once revcli is shutting down: it would not be + // closed by the handler that is already running. + shutdownSignal.throwIfAborted(); logger.debug("Launching browser with persistent profile..."); ensureProfileDir(); @@ -42,59 +81,125 @@ export async function launchBrowser( // survive between runs. Google's Terms of Service restrict automated access // to Maps; this tool is for data you have the right to collect. Use // responsibly and only on your own data. See README. - const context = await chromium.launchPersistentContext(PROFILE_DIR, { - headless: options.headless, - args: [ - "--disable-blink-features=AutomationControlled", - "--disable-dev-shm-usage", - "--lang=en-US", - ], - viewport: { width: 1366, height: 768 }, - locale: "en-US", - extraHTTPHeaders: { "Accept-Language": "en-US,en;q=0.9" }, - userAgent: - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36", - }); - // Remove navigator.webdriver flag. Passed as a string, not a function, so no - // transform (tsx/esbuild keepNames injecting `__name`) can ever touch the code - // that runs in the page – a broken init script would fail silently. - await context.addInitScript({ - content: - "Object.defineProperty(navigator, 'webdriver', { get: () => undefined });", - }); + const context = await chromium.launchPersistentContext( + PROFILE_DIR, + browserLaunchOptions(options), + ); + // Tracked at once, so a signal during the rest of the launch still closes it. + trackBrowser(context); - const page = context.pages()[0] ?? (await context.newPage()); - logger.debug("Browser launched"); + try { + // Remove navigator.webdriver flag. Passed as a string, not a function, so no + // transform (tsx/esbuild keepNames injecting `__name`) can ever touch the code + // that runs in the page – a broken init script would fail silently. + await context.addInitScript({ + content: + "Object.defineProperty(navigator, 'webdriver', { get: () => undefined });", + }); + + const page = context.pages()[0] ?? (await context.newPage()); + logger.debug("Browser launched"); - return { context, page }; + return { context, page }; + } catch (err) { + // A half-launched browser would keep holding the profile. + await closeBrowser(context); + throw err; + } } const activeContexts = new Set(); -// Clean up browsers on unexpected termination -process.once("SIGINT", () => { - const cleanups = [...activeContexts].map((c) => c.close().catch(() => {})); - Promise.all(cleanups).finally(() => { - process.exit(130); - }); -}); - export function trackBrowser(context: BrowserContext): void { activeContexts.add(context); } -export async function closeBrowser(context: BrowserContext): Promise { +/** Close every tracked browser; never throws. */ +export async function closeAllBrowsers(): Promise { + await Promise.all([...activeContexts].map((c) => closeBrowser(c))); +} + +/** + * Close `context` as soon as `signal` aborts (a location timeout or a + * shutdown). Closing the browser makes every pending Playwright call reject, + * so the scrape unwinds through its own `finally` and frees the profile. + * Returns a function that removes the listener. + */ +export function closeOnAbort(context: BrowserContext, signal: AbortSignal): () => void { + const onAbort = (): void => { + void closeBrowser(context); + }; + if (signal.aborted) { + onAbort(); + return () => {}; + } + signal.addEventListener("abort", onAbort, { once: true }); + return () => signal.removeEventListener("abort", onAbort); +} + +/** + * Open a browser session, run `body`, and always close the browser – at once + * when `signal` aborts (a timeout or a shutdown), otherwise when `body` + * settles. Generic over the session so it is testable with a fake. + */ +export async function withBrowserSession( + launch: () => Promise, + signal: AbortSignal | undefined, + body: (session: S) => Promise, +): Promise { + const session = await launch(); + const stopClosing = signal ? closeOnAbort(session.context, signal) : () => {}; try { - await context.close(); - logger.debug("Browser closed"); - } catch { - // Browser may already be closed + // Aborted during launch: the browser is already closing, report why. + signal?.throwIfAborted(); + return await body(session); } finally { - activeContexts.delete(context); + stopClosing(); + await closeBrowser(session.context); } } +/** Install the SIGHUP/SIGINT/SIGTERM handlers that close every browser and exit. */ +export function installBrowserShutdown(): void { + installShutdownHandlers({ + source: process, + cleanup: closeAllBrowsers, + exit: (code) => process.exit(code), + // SIGHUP only when attached to a terminal: a handler would override the + // "ignore SIGHUP" that `nohup` sets up for long unattended batches. + signals: process.stdout.isTTY || process.stderr.isTTY + ? ["SIGHUP", "SIGINT", "SIGTERM"] + : ["SIGINT", "SIGTERM"], + }); +} + +/** The close in progress per browser, so every caller waits for the same one. */ +const closing = new WeakMap>(); + +/** + * Close a browser; never throws. Every call – the abort listener, the + * session's `finally`, the signal handler – awaits the same close, because a + * second `context.close()` returns at once while the first is still running + * (issue #33: the next place must not start before Chromium has exited). + */ +export function closeBrowser(context: BrowserContext): Promise { + const inFlight = closing.get(context); + if (inFlight) return inFlight; + const done = (async () => { + try { + await context.close(); + logger.debug("Browser closed"); + } catch { + // Browser may already be closed + } finally { + activeContexts.delete(context); + } + })(); + closing.set(context, done); + return done; +} + /** * Clear volatile per-origin browser state (service workers, cache storage, * localStorage, IndexedDB) via CDP. Used between sequential scrapes to prevent diff --git a/src/scraper/extractor.ts b/src/scraper/extractor.ts index 990ced8..8ede255 100644 --- a/src/scraper/extractor.ts +++ b/src/scraper/extractor.ts @@ -1,6 +1,7 @@ import type { Page } from "playwright"; import { logger } from "../utils/logger.js"; import { SELECTORS } from "./selectors.js"; +import { safeErrorMessage } from "../core/errors.js"; // Named timeouts for the original-language toggle pass. Reduced from the old // 3000ms literals so a slow card does not stall the scroll-collect loop; the @@ -17,6 +18,13 @@ const EXPAND_CONFIRM_TIMEOUT_MS = 1500; const EXPAND_MAX_PASSES = 2; /** Attribute that marks each pending "More" button with a per-pass token. */ export const EXPAND_MARK_ATTR = "data-revcli-expand"; +/** + * Set on a review card once its review is collected, holding that review's id. + * Later cycles skip a card only while the mark equals the card's current id, + * so a card element Google reuses for another review is read again (issue #33: + * re-reading every card each cycle made collection slow down as it grew). + */ +export const COLLECTED_MARK_ATTR = "data-revcli-collected"; /** Tokens are generated Node-side and interpolated into a selector, so pin their alphabet. */ const EXPAND_TOKEN_RE = /^[a-z0-9-]+$/; @@ -155,7 +163,7 @@ async function scanExpandButtons( opts: { skipIds: string[]; stamp: boolean; prefix: string }, ): Promise { return page.evaluate( - ({ cardSel, reviewIdSel, btnSel, attr, prefix, stamp, skipIds }) => { + ({ cardSel, reviewIdSel, btnSel, attr, collectedAttr, prefix, stamp, skipIds }) => { if (stamp) { for (const el of Array.from(document.querySelectorAll(`[${attr}]`))) { el.removeAttribute(attr); @@ -170,6 +178,8 @@ async function scanExpandButtons( const reviewId = card.querySelector(reviewIdSel)?.getAttribute("data-review-id") || null; if (reviewId !== null && skip.has(reviewId)) continue; + // Already collected (and still showing the same review): skip. + if (reviewId !== null && card.getAttribute(collectedAttr) === reviewId) continue; for (const btn of Array.from(card.querySelectorAll(btnSel))) { const pending = btn.getClientRects().length > 0 && @@ -191,6 +201,7 @@ async function scanExpandButtons( reviewIdSel: SELECTORS.reviewId, btnSel: SELECTORS.expandButton, attr: EXPAND_MARK_ATTR, + collectedAttr: COLLECTED_MARK_ATTR, prefix: opts.prefix, stamp: opts.stamp, skipIds: opts.skipIds, @@ -264,8 +275,11 @@ async function safeScan( * 3. Up to EXPAND_MAX_PASSES passes; later passes re-mark whatever is still * pending (re-rendered cards, late buttons, failed clicks). * - * `skipIds` should hold already-collected reviews so a stuck button costs at - * most EXPAND_MAX_PASSES clicks in the cycle it appears in. The result is for + * Cards marked with COLLECTED_MARK_ATTR (already collected, same review) are + * always skipped, so the scroller passes no `skipIds`; a stuck button costs at + * most EXPAND_MAX_PASSES clicks per cycle until its card is collected and + * marked (again, for a card Google re-rendered). `skipIds` stays for callers + * that want to exclude reviews by id. The result is for * logging only – the truncation warning comes from `expandPending` at * extraction time. */ @@ -327,6 +341,7 @@ export async function extractReviews(page: Page): Promise { responseContainer: SELECTORS.ownerResponseContainer, responseText: SELECTORS.ownerResponseText, responseTime: SELECTORS.ownerResponseTime, + collectedAttr: COLLECTED_MARK_ATTR, }; const results = await page.evaluate((s) => { @@ -351,6 +366,8 @@ export async function extractReviews(page: Page): Promise { try { const reviewIdEl = card.querySelector(s.reviewId); const reviewId = reviewIdEl?.getAttribute("data-review-id") ?? ""; + // Collected in an earlier cycle and still the same review: skip it. + if (reviewId && card.getAttribute(s.collectedAttr) === reviewId) continue; const authorEl = card.querySelector(s.authorName); const author = authorEl?.textContent?.trim() ?? "Anonymous"; @@ -473,10 +490,41 @@ export async function extractReviews(page: Page): Promise { ); } - logger.debug(`Extracted ${reviews.length} reviews from DOM`); + logger.debug(`Extracted ${reviews.length} not-yet-collected reviews from DOM`); return reviews; } +/** + * Mark the cards of the given (collected) reviews with COLLECTED_MARK_ATTR so + * later cycles skip them. One in-page pass; ids are compared in the page, never + * built into a selector. Best-effort: a failed mark only means the card is + * read (and deduplicated) once more. + */ +export async function markCollected(page: Page, reviewIds: string[]): Promise { + if (reviewIds.length === 0) return; + try { + await page.evaluate( + ({ cardSel, reviewIdSel, attr, ids }) => { + const wanted = new Set(ids); + for (const card of Array.from(document.querySelectorAll(cardSel))) { + const id = card.querySelector(reviewIdSel)?.getAttribute("data-review-id"); + if (id && wanted.has(id) && card.getAttribute(attr) !== id) { + card.setAttribute(attr, id); + } + } + }, + { + cardSel: SELECTORS.reviewCard, + reviewIdSel: SELECTORS.reviewId, + attr: COLLECTED_MARK_ATTR, + ids: reviewIds, + }, + ); + } catch (err) { + logger.debug(`Marking collected cards failed: ${safeErrorMessage(err)}`); + } +} + /** * Wait for the translated-review toggle's `aria-checked` to reach the expected * state. aria-checked="true" means the English translation is displayed; diff --git a/src/scraper/scrape-location.ts b/src/scraper/scrape-location.ts index 6172da0..2896079 100644 --- a/src/scraper/scrape-location.ts +++ b/src/scraper/scrape-location.ts @@ -1,6 +1,6 @@ import type { ParsedUrl } from "../utils/url.js"; import { logger } from "../utils/logger.js"; -import { launchBrowser, closeBrowser, trackBrowser } from "./browser.js"; +import { launchBrowser, withBrowserSession } from "./browser.js"; import { navigateToReviews } from "./navigator.js"; import { scrollAndCollectReviews } from "./scroller.js"; import { @@ -23,6 +23,8 @@ export interface ScrapeLocationOptions { maxReviews?: number; headless: boolean; delay: number; + /** Epoch ms after which review collection stops with a partial result. */ + deadline?: number; } /** @@ -113,38 +115,38 @@ export async function navigateWithAuthFallback( export async function scrapeLocation( parsed: ParsedUrl, options: ScrapeLocationOptions, + signal?: AbortSignal, ): Promise { const startTime = Date.now(); - const { context, page } = await launchBrowser({ - headless: options.headless, - }); - trackBrowser(context); + // A timeout or shutdown closes the browser at once; every pending + // Playwright call then rejects and the session closes (issue #33). + return withBrowserSession( + () => launchBrowser({ headless: options.headless }), + signal, + async ({ page }) => { + const businessInfo: Omit = + await navigateWithAuthFallback({ + headless: options.headless, + navigate: () => navigateToReviews(page, parsed, options.sort), + waitForAuth: () => waitForUserAuth(page), + sessionProbe: () => getSessionState(page, POLL_PROBE), + }); - try { - const businessInfo: Omit = - await navigateWithAuthFallback({ - headless: options.headless, - navigate: () => navigateToReviews(page, parsed, options.sort), - waitForAuth: () => waitForUserAuth(page), - sessionProbe: () => - getSessionState(page, POLL_PROBE), - }); + logger.info( + `Found: ${businessInfo.name} (header reports ${businessInfo.totalReviews ?? "?"} reviews)`, + ); - logger.info( - `Found: ${businessInfo.name} (header reports ${businessInfo.totalReviews ?? "?"} reviews)`, - ); - - const reviews: Review[] = await scrollAndCollectReviews(page, { - maxReviews: options.maxReviews, - delayMs: options.delay, - }); + const reviews: Review[] = await scrollAndCollectReviews(page, { + maxReviews: options.maxReviews, + delayMs: options.delay, + deadline: options.deadline, + }); - return assembleScrapeResult(businessInfo, reviews, { - scrapeDate: new Date().toISOString(), - scrapeDurationMs: Date.now() - startTime, - sortOrder: options.sort, - }); - } finally { - await closeBrowser(context); - } + return assembleScrapeResult(businessInfo, reviews, { + scrapeDate: new Date().toISOString(), + scrapeDurationMs: Date.now() - startTime, + sortOrder: options.sort, + }); + }, + ); } diff --git a/src/scraper/scroller.ts b/src/scraper/scroller.ts index dbd5271..28974f8 100644 --- a/src/scraper/scroller.ts +++ b/src/scraper/scroller.ts @@ -6,6 +6,7 @@ import { expandAllReviews, extractReviews, formatTruncationWarning, + markCollected, restoreTranslations, type RawReview, } from "./extractor.js"; @@ -33,6 +34,28 @@ interface CycleState { export interface ScrollOptions { maxReviews?: number; delayMs: number; + /** + * Epoch ms after which scrolling stops and the reviews collected so far are + * returned (a partial result, with a warning). Undefined = no time limit. + */ + deadline?: number; + /** + * Called after every collect cycle (the work between two scrolls, waits + * excluded). For timing diagnostics and tests; never changes collection. + */ + onCycle?: (cycle: CycleTiming) => void; +} + +/** Timing of one collect cycle, reported through `ScrollOptions.onCycle`. */ +export interface CycleTiming { + /** Time spent restoring, expanding, extracting and collecting, in ms. */ + durationMs: number; + /** Reviews newly collected in this cycle. */ + newCount: number; + /** Reviews collected so far. */ + total: number; + /** Review cards read from the page in this cycle (collected cards are skipped). */ + readCount: number; } /** Collection state shared by every collect call within one scrape. */ @@ -44,6 +67,8 @@ interface CollectContext { restoreFailedIds: Set; /** Collected reviews whose card still had a pending "More" button when read. */ truncatedIds: Set; + /** Cards read from the page so far in the current cycle (for CycleTiming). */ + readCount: number; } /** @@ -116,6 +141,7 @@ export async function scrollAndCollectReviews( maxReviews: options.maxReviews, restoreFailedIds: new Set(), truncatedIds: new Set(), + readCount: 0, }; const scrollContainer = await findScrollContainer(page); @@ -178,7 +204,8 @@ async function collectOnce(page: Page, ctx: CollectContext): Promise { for (const id of capture.restoreFailedIds) ctx.restoreFailedIds.add(id); const enriched = enrichReviews(rawReviews, capture.results); - const before = new Set(ctx.collectedIds); + // Ids among the cards just read that were collected before this call. + const before = new Set(collectedIdsIn(rawReviews, ctx)); const newCount = collectNewReviews( enriched, ctx.collectedIds, @@ -194,15 +221,27 @@ async function collectOnce(page: Page, ctx: CollectContext): Promise { ctx.truncatedIds.add(r.reviewId); } } + ctx.readCount += rawReviews.length; + // Mark every card read here whose review is now collected (new ones, and + // re-rendered cards of reviews collected earlier), so later cycles skip them + // and a cycle's cost stays flat as the list grows (issue #33). + await markCollected(page, collectedIdsIn(rawReviews, ctx)); return newCount; } +/** Ids of the given cards whose review is in the collected set. */ +function collectedIdsIn(rawReviews: RawReview[], ctx: CollectContext): string[] { + return rawReviews.filter((r) => ctx.collectedIds.has(r.reviewId)).map((r) => r.reviewId); +} + /** * Expand truncated texts in not-yet-collected cards, then collect. Every * collect path goes through here so no card is collected unexpanded. */ async function expandAndCollect(page: Page, ctx: CollectContext): Promise { - await expandAllReviews(page, ctx.collectedIds); + // Collected cards carry COLLECTED_MARK_ATTR and are skipped in the page, so + // the collected-id list is not sent on every call (it grew with the list). + await expandAllReviews(page); return collectOnce(page, ctx); } @@ -274,50 +313,81 @@ async function collectFromCurrentSort( options: ScrollOptions, ): Promise { let state: CycleState = { staleScrollCount: 0, spinnerWithoutProgressCount: 0 }; + let cycle = 0; while (true) { - // Re-toggle any card left showing its original language so extractReviews - // never reads a stale original text as `text`. - if (ctx.restoreFailedIds.size > 0) { - await restoreTranslations(page, ctx.restoreFailedIds); - } + cycle += 1; + const cycleStart = Date.now(); + const totalBefore = ctx.reviews.length; + ctx.readCount = 0; + const reportCycle = (): void => { + const timing: CycleTiming = { + durationMs: Date.now() - cycleStart, + newCount: ctx.reviews.length - totalBefore, + total: ctx.reviews.length, + readCount: ctx.readCount, + }; + logger.debug( + `Collect cycle ${cycle}: +${timing.newCount} (total ${timing.total}, ${timing.readCount} cards read) in ${timing.durationMs}ms`, + ); + options.onCycle?.(timing); + }; - const newCount = await expandAndCollect(page, ctx); + // Timed from here to the scroll; the finally reports every exit path. + try { + // Re-toggle any card left showing its original language so extractReviews + // never reads a stale original text as `text`. + if (ctx.restoreFailedIds.size > 0) { + await restoreTranslations(page, ctx.restoreFailedIds); + } - if (newCount === -1) { - logger.info(`Reached max reviews limit (${options.maxReviews})`); - return; - } + const newCount = await expandAndCollect(page, ctx); - let decision: { state: CycleState; stop: boolean }; - if (newCount > 0) { - logger.debug(`+${newCount} new reviews (total: ${ctx.reviews.length})`); - decision = decideCycle(newCount, false, state); - } else { - const loading = await isLoadingVisible(page); - if (loading) { - const retryNewCount = await retryAfterLoading(page, ctx); - if (retryNewCount === -1) { - logger.info(`Reached max reviews limit (${options.maxReviews})`); - return; - } - if (retryNewCount > 0) { - logger.debug( - `+${retryNewCount} new reviews after loading (total: ${ctx.reviews.length})`, - ); - } - decision = decideCycle(retryNewCount, true, state); + if (newCount === -1) { + logger.info(`Reached max reviews limit (${options.maxReviews})`); + return; + } + + // Checked after a collect, so the reviews already on screen are kept. + if (options.deadline != null && Date.now() >= options.deadline) { + logger.warn( + `Time limit reached – stopping with ${ctx.reviews.length} reviews collected (partial result)`, + ); + return; + } + + let decision: { state: CycleState; stop: boolean }; + if (newCount > 0) { + logger.debug(`+${newCount} new reviews (total: ${ctx.reviews.length})`); + decision = decideCycle(newCount, false, state); } else { - decision = decideCycle(0, false, state); + const loading = await isLoadingVisible(page); + if (loading) { + const retryNewCount = await retryAfterLoading(page, ctx); + if (retryNewCount === -1) { + logger.info(`Reached max reviews limit (${options.maxReviews})`); + return; + } + if (retryNewCount > 0) { + logger.debug( + `+${retryNewCount} new reviews after loading (total: ${ctx.reviews.length})`, + ); + } + decision = decideCycle(retryNewCount, true, state); + } else { + decision = decideCycle(0, false, state); + } } - } - state = decision.state; + state = decision.state; - if (decision.stop) { - logger.info( - `No new reviews after scrolling – no more reviews available (${ctx.reviews.length} total)`, - ); - return; + if (decision.stop) { + logger.info( + `No new reviews after scrolling – no more reviews available (${ctx.reviews.length} total)`, + ); + return; + } + } finally { + reportCycle(); } await scrollDown(page, scrollContainer); diff --git a/tests/atomic.test.ts b/tests/atomic.test.ts new file mode 100644 index 0000000..f109515 --- /dev/null +++ b/tests/atomic.test.ts @@ -0,0 +1,39 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { writeFileAtomic } from "../src/output/atomic.js"; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "revcli-atomic-")); +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +describe("writeFileAtomic (issue #33)", () => { + it("writes the full content and leaves no temporary file", async () => { + await writeFileAtomic(join(dir, "out.json"), '{"a":1}'); + expect(readFileSync(join(dir, "out.json"), "utf-8")).toBe('{"a":1}'); + expect(readdirSync(dir)).toEqual(["out.json"]); + }); + + it("replaces an existing file", async () => { + await writeFileAtomic(join(dir, "out.json"), "old"); + await writeFileAtomic(join(dir, "out.json"), "new"); + expect(readFileSync(join(dir, "out.json"), "utf-8")).toBe("new"); + }); + + it("leaves nothing behind when the write fails", async () => { + await expect(writeFileAtomic(join(dir, "missing", "out.json"), "x")).rejects.toThrow(); + expect(readdirSync(dir)).toEqual([]); + }); + + it("removes its temporary file when the final rename fails", async () => { + // A directory at the target path makes rename fail after the temp file exists. + mkdirSync(join(dir, "out.json")); + await expect(writeFileAtomic(join(dir, "out.json"), "x")).rejects.toThrow(); + expect(readdirSync(dir)).toEqual(["out.json"]); + }); +}); diff --git a/tests/batch-run.test.ts b/tests/batch-run.test.ts new file mode 100644 index 0000000..ce5e808 --- /dev/null +++ b/tests/batch-run.test.ts @@ -0,0 +1,206 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runBatchLocations, type BatchOptions, type BatchRunDeps } from "../src/commands/batch.js"; +import type { ScrapeResult } from "../src/core/schema.js"; +import { UnrecoverableError } from "../src/core/errors.js"; +import type { ParsedUrl } from "../src/utils/url.js"; + +/** + * Issue #33: a place that runs past --location-timeout must be stopped and + * release its browser before the next place starts. The scrape is a fake, so + * no browser and no ~/.revcli profile is involved. + */ + +const SLOW = "https://www.google.com/maps?ftid=0x1111111111111111:0x2222222222222222"; +const FAST = "https://www.google.com/maps?ftid=0x3333333333333333:0x4444444444444444"; +const FAST_2 = "https://www.google.com/maps?ftid=0x5555555555555555:0x6666666666666666"; + +/** Time the fake "browser" takes to close after an abort. */ +const CLOSE_MS = 150; + +function result(name: string): ScrapeResult { + return { + business: { + name, + placeId: null, + url: "https://www.google.com/maps", + address: null, + rating: null, + totalReviews: 0, + headerTotalReviews: null, + scrapeDate: new Date(0).toISOString(), + }, + reviews: [], + metadata: { provider: "playwright", scrapeDurationMs: 1, reviewsCollected: 0, sortOrder: "newest" }, + }; +} + +let dir: string; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "revcli-batch-")); +}); + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +function options(locationTimeout: number): BatchOptions { + return { + outputDir: dir, + sort: "newest", + format: "json", + headless: true, + delay: 1, + resume: false, + locationDelay: 1, + locationTimeout, + }; +} + +/** + * A fake scrape: SLOW hangs until aborted, then "closes its browser" after + * CLOSE_MS and rejects; every other URL resolves at once. + */ +function fakeScrape(events: string[], slowName = "Slow"): BatchRunDeps["scrape"] { + return (parsed: ParsedUrl, signal: AbortSignal) => { + const name = parsed.url.includes("0x1111") ? slowName : parsed.url.includes("0x3333") ? "Fast" : "Fast 2"; + events.push(`${name} started`); + if (name !== slowName) return Promise.resolve(result(name)); + return new Promise((_, reject) => { + signal.addEventListener( + "abort", + () => + setTimeout(() => { + events.push(`${name} browser closed`); + reject(new Error("Target page, context or browser has been closed")); + }, CLOSE_MS), + { once: true }, + ); + }); + }; +} + +describe("runBatchLocations – location timeout (issue #33)", () => { + it("stops the timed-out place and closes its browser before the next place starts", async () => { + const events: string[] = []; + const state = { completed: [] as string[] }; + + const { progress } = await runBatchLocations( + [SLOW, FAST], + options(200), + { state, stateFile: join(dir, ".revcli-state.json") }, + { scrape: fakeScrape(events) }, + ); + + expect(events).toEqual(["Slow started", "Slow browser closed", "Fast started"]); + expect(progress.failedCount).toBe(1); + }); + + it("saves the place after a timed-out one, and writes no file for the timed-out place", async () => { + const state = { completed: [] as string[] }; + + await runBatchLocations( + [SLOW, FAST, FAST_2], + options(200), + { state, stateFile: join(dir, ".revcli-state.json") }, + { scrape: fakeScrape([]) }, + ); + + const files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.startsWith(".")); + expect(files.sort()).toEqual(["fast-2.json", "fast.json"]); + expect(existsSync(join(dir, "slow.json"))).toBe(false); + expect(state.completed).toEqual([FAST, FAST_2]); + }); + + it("does not write a late result that arrives after the timeout", async () => { + const state = { completed: [] as string[] }; + const late: BatchRunDeps["scrape"] = () => + new Promise((resolve) => setTimeout(() => resolve(result("Late")), 400)); + + const { progress } = await runBatchLocations( + [SLOW], + options(100), + { state, stateFile: join(dir, ".revcli-state.json") }, + { scrape: late }, + ); + // Give a late resolve every chance to (wrongly) write. + await new Promise((r) => setTimeout(r, 500)); + + expect(progress.failedCount).toBe(1); + expect(readdirSync(dir).filter((f) => f.endsWith(".json"))).toEqual([]); + expect(state.completed).toEqual([]); + }); + + it("stops the batch when the timed-out place does not release its browser", async () => { + const started: string[] = []; + const stuck: BatchRunDeps["scrape"] = (parsed) => { + started.push(parsed.url); + return new Promise(() => {}); // ignores the abort: browser never closes + }; + const state = { completed: [] as string[] }; + + const { progress, stoppedOnStuckBrowser } = await runBatchLocations( + [SLOW, FAST, FAST_2], + options(50), + { state, stateFile: join(dir, ".revcli-state.json"), settleGraceMs: 100 }, + { scrape: stuck }, + ); + + expect(started).toEqual([SLOW]); + expect(stoppedOnStuckBrowser).toBe(true); + // The stuck place plus the two never started. + expect(progress.failedCount).toBe(3); + expect(state.completed).toEqual([]); + }); + + it("starts no further place once the stop signal is aborted", async () => { + const controller = new AbortController(); + const started: string[] = []; + const scrape: BatchRunDeps["scrape"] = async (parsed) => { + started.push(parsed.url); + controller.abort(new Error("Received SIGTERM – stopping")); + return result("Fast"); + }; + + await runBatchLocations( + [FAST, FAST_2], + options(1_000), + { state: { completed: [] }, stateFile: join(dir, ".revcli-state.json"), signal: controller.signal }, + { scrape }, + ); + + expect(started).toEqual([FAST]); + }); + + it("a stop signal during a place aborts that scrape at once, without waiting for the timeout", async () => { + const controller = new AbortController(); + let scrapeAborted = false; + const scrape: BatchRunDeps["scrape"] = (_parsed, signal) => + new Promise((_, reject) => { + signal.addEventListener("abort", () => { + scrapeAborted = true; + reject(signal.reason); + }); + }); + setTimeout( + () => controller.abort(new UnrecoverableError("SHUTDOWN", "Received SIGTERM – stopping")), + 50, + ); + + const start = Date.now(); + const { progress } = await runBatchLocations( + [SLOW, FAST], + options(30_000), + { state: { completed: [] }, stateFile: join(dir, ".revcli-state.json"), signal: controller.signal }, + { scrape }, + ); + + expect(scrapeAborted).toBe(true); + expect(Date.now() - start).toBeLessThan(2_000); + expect(progress.failedCount).toBe(1); + expect(readdirSync(dir).filter((f) => f.endsWith(".json"))).toEqual([]); + }); +}); diff --git a/tests/browser-session.test.ts b/tests/browser-session.test.ts new file mode 100644 index 0000000..54c521b --- /dev/null +++ b/tests/browser-session.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from "vitest"; +import type { BrowserContext } from "playwright"; +import { browserLaunchOptions, closeBrowser, withBrowserSession } from "../src/scraper/browser.js"; + +/** + * Issue #33: the scrape's browser must close as soon as its signal aborts + * (timeout or shutdown), and always when the work ends. Tested with a fake + * context – no browser, no profile. + */ + +function fakeSession() { + const close = vi.fn().mockResolvedValue(undefined); + const context = { close } as unknown as BrowserContext; + return { session: { context }, close }; +} + +describe("withBrowserSession (issue #33)", () => { + it("closes the browser as soon as the signal aborts, while the work still runs", async () => { + const { session, close } = fakeSession(); + const controller = new AbortController(); + let closedDuringWork = false; + + await withBrowserSession(async () => session, controller.signal, async () => { + controller.abort(); + closedDuringWork = close.mock.calls.length > 0; + }); + + expect(closedDuringWork).toBe(true); + }); + + it("closes the browser when the work fails", async () => { + const { session, close } = fakeSession(); + await expect( + withBrowserSession(async () => session, undefined, async () => { + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + expect(close).toHaveBeenCalled(); + }); + + it("closes at once and does not start the work when the signal is already aborted", async () => { + const { session, close } = fakeSession(); + const controller = new AbortController(); + controller.abort(new Error("Location timeout")); + const body = vi.fn(); + + await expect(withBrowserSession(async () => session, controller.signal, body)).rejects.toThrow( + "Location timeout", + ); + expect(close).toHaveBeenCalled(); + expect(body).not.toHaveBeenCalled(); + }); + + it("stops listening once the work is done", async () => { + const { session, close } = fakeSession(); + const controller = new AbortController(); + await withBrowserSession(async () => session, controller.signal, async () => "ok"); + const callsAfterWork = close.mock.calls.length; + controller.abort(); + expect(close.mock.calls.length).toBe(callsAfterWork); + }); +}); + +describe("closeBrowser (issue #33)", () => { + it("makes every caller wait for the one close in progress", async () => { + let finish: () => void = () => {}; + const close = vi.fn(() => new Promise((resolve) => (finish = resolve))); + const context = { close } as unknown as BrowserContext; + + let firstDone = false; + let secondDone = false; + void closeBrowser(context).then(() => (firstDone = true)); + void closeBrowser(context).then(() => (secondDone = true)); + await new Promise((r) => setTimeout(r, 20)); + + expect(close).toHaveBeenCalledTimes(1); + expect(secondDone).toBe(false); + finish(); + await vi.waitFor(() => expect(firstDone && secondDone).toBe(true)); + }); + + it("the session settles only after the browser has finished closing", async () => { + let finish: () => void = () => {}; + const close = vi.fn(() => new Promise((resolve) => (finish = resolve))); + const context = { close } as unknown as BrowserContext; + const controller = new AbortController(); + + let settled = false; + const run = withBrowserSession(async () => ({ context }), controller.signal, async () => { + controller.abort(); + throw new Error("Target page, context or browser has been closed"); + }) + .catch(() => {}) + .then(() => (settled = true)); + await new Promise((r) => setTimeout(r, 20)); + expect(settled).toBe(false); + + finish(); + await run; + expect(settled).toBe(true); + }); +}); + +describe("browserLaunchOptions (issue #33)", () => { + it("turns off Playwright's own signal handlers, which kept revcli alive after kill", () => { + const opts = browserLaunchOptions({ headless: true }); + expect(opts.handleSIGTERM).toBe(false); + expect(opts.handleSIGINT).toBe(false); + expect(opts.handleSIGHUP).toBe(false); + }); +}); diff --git a/tests/browser/abort.test.ts b/tests/browser/abort.test.ts new file mode 100644 index 0000000..c9c3fa6 --- /dev/null +++ b/tests/browser/abort.test.ts @@ -0,0 +1,79 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { chromium, type BrowserContext } from "playwright"; +import { browserLaunchOptions, closeOnAbort } from "../../src/scraper/browser.js"; +import { scrollAndCollectReviews } from "../../src/scraper/scroller.js"; +import { buildMapsPage } from "./fixtures/maps-page.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** + * Issue #33: a location timeout must stop the running scrape and free the + * persistent profile. Uses a real persistent browser on a TEMPORARY profile + * (never ~/.revcli), with every network request aborted. + */ + +let dir: string | undefined; +const contexts: BrowserContext[] = []; + +afterEach(async () => { + await Promise.all(contexts.splice(0).map((c) => c.close().catch(() => {}))); + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; +}); + +async function launchOn(profile: string): Promise { + const context = await chromium.launchPersistentContext( + profile, + browserLaunchOptions({ headless: true }), + ); + contexts.push(context); + await context.route("**/*", (route) => route.abort()); + return context; +} + +describe("closeOnAbort with a persistent profile (issue #33)", () => { + it("stops a running scroll at once and frees the profile for the next browser", async () => { + dir = mkdtempSync(join(tmpdir(), "revcli-abort-")); + const profile = join(dir, "profile"); + const context = await launchOn(profile); + const page = context.pages()[0] ?? (await context.newPage()); + await page.setContent(buildMapsPage({ totalReviews: 5_000, batchSize: 10 })); + + const controller = new AbortController(); + closeOnAbort(context, controller.signal); + const scrolling = scrollAndCollectReviews(page, { delayMs: 200 }); + const outcome = scrolling.then( + () => "resolved" as const, + () => "rejected" as const, + ); + + await new Promise((r) => setTimeout(r, 1_500)); + const abortedAt = Date.now(); + controller.abort(new Error("Location timeout")); + + expect(await outcome).toBe("rejected"); + expect(Date.now() - abortedAt).toBeLessThan(5_000); + + // Chromium allows one browser per profile directory: a second launch only + // works when the first browser is really gone. + const next = await launchOn(profile); + const nextPage = next.pages()[0] ?? (await next.newPage()); + await nextPage.setContent("

second browser

"); + expect(await nextPage.textContent("p")).toBe("second browser"); + }); + + it("closes at once when the signal is already aborted", async () => { + dir = mkdtempSync(join(tmpdir(), "revcli-abort-")); + const context = await launchOn(join(dir, "profile")); + const controller = new AbortController(); + controller.abort(); + const closed = new Promise((resolve) => context.once("close", () => resolve())); + + closeOnAbort(context, controller.signal); + + await expect(closed).resolves.toBeUndefined(); + }); +}); diff --git a/tests/browser/collected-mark.test.ts b/tests/browser/collected-mark.test.ts new file mode 100644 index 0000000..c258a94 --- /dev/null +++ b/tests/browser/collected-mark.test.ts @@ -0,0 +1,109 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext, Page } from "playwright"; +import { + COLLECTED_MARK_ATTR, + expandAllReviews, + extractReviews, + markCollected, +} from "../../src/scraper/extractor.js"; +import { buildMapsPage, FULL_TEXT } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** + * Issue #33: collected cards are marked and skipped so a cycle does not re-read + * the whole list. A card element that Google reuses for a DIFFERENT review must + * be read again – otherwise that review would be lost without notice. + */ + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); +afterAll(async () => { + await browser?.close(); +}); +beforeEach(async () => { + context = await newFixtureContext(browser); +}); +afterEach(async () => { + await context?.close(); +}); + +/** Make card `fromId` show review `toId` (new id, long text, fresh "More" button). */ +async function reuseCard(page: Page, fromId: string, toId: string, text: string): Promise { + await page.evaluate( + ({ from, to, body }) => { + const card = document.querySelector(`div.jftiEf[data-review-id="${from}"]`); + if (!card) throw new Error("card not found"); + card.setAttribute("data-review-id", to); + card.querySelector(".inner")?.setAttribute("data-review-id", to); + const host = card.querySelector("div.MyEned"); + const span = host?.querySelector("span.wiI7pd"); + if (span) span.textContent = body; + const btn = document.createElement("button"); + btn.className = "w8nwRe kyuRq"; + btn.setAttribute("jsaction", "pane.review.expandReview"); + btn.setAttribute("aria-expanded", "false"); + btn.textContent = "More"; + host?.appendChild(btn); + }, + { from: fromId, to: toId, body: text }, + ); +} + +describe("collected mark (issue #33)", () => { + it("skips collected cards on the next read", async () => { + const page = await newFixturePage(context, buildMapsPage({ totalReviews: 10, batchSize: 10 })); + + const first = await extractReviews(page); + expect(first).toHaveLength(10); + await markCollected(page, first.map((r) => r.reviewId)); + + expect(await extractReviews(page)).toEqual([]); + const marks = await page.$$eval(`[${COLLECTED_MARK_ATTR}]`, (els, attr) => + els.map((e) => e.getAttribute(attr) === e.getAttribute("data-review-id")), COLLECTED_MARK_ATTR); + expect(marks).toEqual(Array(10).fill(true)); + }); + + it("marks only the ids it is given", async () => { + const page = await newFixturePage(context, buildMapsPage({ totalReviews: 5, batchSize: 5 })); + await markCollected(page, ["r0", "r1"]); + expect((await extractReviews(page)).map((r) => r.reviewId).sort()).toEqual(["r2", "r3", "r4"]); + }); + + it("reads a card again when Google reuses it for a different review", async () => { + const page = await newFixturePage(context, buildMapsPage({ totalReviews: 3, batchSize: 3 })); + const first = await extractReviews(page); + await markCollected(page, first.map((r) => r.reviewId)); + + await reuseCard(page, "r1", "r99", "Reused card, truncated…"); + + const again = await extractReviews(page); + expect(again.map((r) => r.reviewId)).toEqual(["r99"]); + expect(again[0].expandPending).toBe(true); + }); + + it("the expand step skips collected cards but not a reused one", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 4, batchSize: 4, longTextEvery: 1 }), + ); + await markCollected(page, ["r0", "r1", "r2", "r3"]); + const skipped = await expandAllReviews(page); + expect(skipped.attempted).toBe(0); + + await reuseCard(page, "r2", "r42", FULL_TEXT("r42").slice(0, 60) + "…"); + const result = await expandAllReviews(page); + // The fixture's click handler expands only its own reviews; what matters + // here is that the reused card's button was found and clicked. + expect(result.attempted).toBeGreaterThanOrEqual(1); + const clicks = await page.evaluate( + () => (window as unknown as { __revcliTest: { clicks: Record } }).__revcliTest.clicks, + ); + expect(Object.keys(clicks)).toEqual(["r42"]); + }); +}); diff --git a/tests/browser/fixtures/signal-child.ts b/tests/browser/fixtures/signal-child.ts new file mode 100644 index 0000000..73ced92 --- /dev/null +++ b/tests/browser/fixtures/signal-child.ts @@ -0,0 +1,57 @@ +/** + * Child process for tests/browser/shutdown.test.ts (issue #33). + * + * Starts one browser the way revcli does (same launch options, same signal + * wiring as src/index.ts, same withBrowserSession as a scrape), on a TEMPORARY + * profile passed as argv[2], prints "ready", and then stays busy like a + * running scrape until a signal arrives. + * + * It never touches ~/.revcli: the profile must be inside the OS temp + * directory, and the test also points HOME at a temp directory. + */ +import { realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, sep } from "node:path"; +import { chromium } from "playwright"; +import { + browserLaunchOptions, + installBrowserShutdown, + trackBrowser, + withBrowserSession, +} from "../../../src/scraper/browser.js"; +import { shutdownSignal } from "../../../src/core/shutdown.js"; + +const profile = process.argv[2]; +const tmpRoot = realpathSync(tmpdir()); +if ( + !profile || + profile.includes(".revcli") || + !(realpathSync(dirname(profile)) + sep).startsWith(tmpRoot + sep) +) { + process.stderr.write("signal-child: refusing a profile outside the temp directory\n"); + process.exit(2); +} + +installBrowserShutdown(); + +// Same path as a real scrape: a tracked browser inside withBrowserSession, +// which closes it when the shutdown signal aborts. +await withBrowserSession( + async () => { + const context = await chromium.launchPersistentContext( + profile, + browserLaunchOptions({ headless: true }), + ); + trackBrowser(context); + await context.route("**/*", (route) => route.abort()); + const page = context.pages()[0] ?? (await context.newPage()); + return { context, page }; + }, + shutdownSignal, + async ({ page }) => { + await page.setContent("

signal test

"); + process.stdout.write("ready\n"); + // Stay busy like a running scrape until the browser is closed under us. + await page.waitForTimeout(10 * 60_000); + }, +); diff --git a/tests/browser/scroll.test.ts b/tests/browser/scroll.test.ts index 0b84a83..303fc83 100644 --- a/tests/browser/scroll.test.ts +++ b/tests/browser/scroll.test.ts @@ -1,6 +1,6 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { Browser, BrowserContext } from "playwright"; -import { scrollAndCollectReviews } from "../../src/scraper/scroller.js"; +import { scrollAndCollectReviews, type CycleTiming } from "../../src/scraper/scroller.js"; import { buildMapsPage } from "./fixtures/maps-page.js"; import { launchTestBrowser, newFixtureContext, newFixturePage } from "./harness.js"; @@ -50,4 +50,51 @@ describe("scrollAndCollectReviews (in-page scroll code, issue #31 finding 1)", ( Array.from({ length: 12 }, (_, i) => `r${i}`).sort(), ); }); + + it("keeps a flat collect-cycle time as the list grows to 2,000 reviews (issue #33)", async () => { + const total = 2000; + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: total, batchSize: 50 }), + ); + + const cycles: CycleTiming[] = []; + const reviews = await scrollAndCollectReviews(page, { + delayMs: 1, + onCycle: (c) => cycles.push(c), + }); + + expect(reviews).toHaveLength(total); + // Only cycles that collected something: the trailing stale cycles at the + // end of the list are not "collect cycles" of a growing list. + const productive = cycles.filter((c) => c.newCount > 0); + expect(productive.length).toBeGreaterThanOrEqual(20); + const sum = (cs: CycleTiming[]) => cs.reduce((n, c) => n + c.durationMs, 0); + const first = sum(productive.slice(0, 10)); + const last = sum(productive.slice(-10)); + console.log(`collect cycles: first 10 = ${first}ms, last 10 = ${last}ms`); + // Timing-free check: a cycle reads only the cards not collected yet (about + // one scroll's worth), never the whole list. + const maxRead = Math.max(...cycles.map((c) => c.readCount)); + expect(maxRead).toBeLessThanOrEqual(2 * 50); + expect(last).toBeLessThanOrEqual(2 * Math.max(first, 1)); + // One retry: the ~10 ms timings can be disturbed by a busy machine. The + // readCount check above is timing-free and fails on the old code anyway. + }, { timeout: 180_000, retry: 1 }); + + it("stops at the time limit and keeps the reviews collected so far", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 35, batchSize: 10 }), + ); + + // A deadline already in the past: one collect, then stop. + const reviews = await scrollAndCollectReviews(page, { + delayMs: 1, + deadline: Date.now() - 1, + }); + + expect(reviews.length).toBeGreaterThan(0); + expect(reviews.length).toBeLessThan(35); + }); }); diff --git a/tests/browser/shutdown.test.ts b/tests/browser/shutdown.test.ts new file mode 100644 index 0000000..f92b68a --- /dev/null +++ b/tests/browser/shutdown.test.ts @@ -0,0 +1,120 @@ +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** + * Issue #33: `kill ` (SIGTERM) must close every browser and end revcli + * with a non-zero code within 10 seconds. Runs a real child process with a + * real Chromium on a temporary profile (never ~/.revcli). + */ + +const CHILD = fileURLToPath(new URL("./fixtures/signal-child.ts", import.meta.url)); +const EXIT_WITHIN_MS = 10_000; + +/** + * The child gets a temporary HOME, so tell Playwright where the installed + * browsers are (its default location is derived from the real HOME). + */ +const BROWSERS_PATH = + process.env.PLAYWRIGHT_BROWSERS_PATH ?? + (process.platform === "darwin" + ? join(homedir(), "Library", "Caches", "ms-playwright") + : join(homedir(), ".cache", "ms-playwright")); + +/** + * Whether a Chromium for `profileDir` is running: matched on its + * `--user-data-dir=` flag, so the child node process (which has the bare path + * in its argv) does not count. No shell involved. + */ +function processRunning(profileDir: string): boolean { + const res = spawnSync("pgrep", ["-f", `user-data-dir=${profileDir}`], { encoding: "utf8" }); + if (res.status === 0) return true; + if (res.status === 1) return false; + throw new Error(`pgrep failed (status ${res.status}): ${res.error?.message ?? res.stderr}`); +} + +async function waitUntil(check: () => boolean, timeoutMs: number): Promise { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + if (check()) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return check(); +} + +let child: ChildProcess | undefined; +let tmp: string | undefined; +let profile: string | undefined; + +afterEach(() => { + if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + if (profile) spawnSync("pkill", ["-9", "-f", profile]); + if (tmp) rmSync(tmp, { recursive: true, force: true }); + child = tmp = profile = undefined; +}); + +/** Start the child and resolve once it printed "ready". */ +async function startChild(): Promise { + tmp = mkdtempSync(join(tmpdir(), "revcli-signal-")); + const home = join(tmp, "home"); + mkdirSync(home); + profile = join(tmp, "profile"); + const proc = spawn(process.execPath, ["--import", "tsx", CHILD, profile], { + env: { ...process.env, HOME: home, PLAYWRIGHT_BROWSERS_PATH: BROWSERS_PATH }, + stdio: ["ignore", "pipe", "pipe"], + shell: false, + }); + child = proc; + let stderr = ""; + proc.stderr?.on("data", (d) => (stderr += String(d))); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`child not ready: ${stderr}`)), 45_000); + proc.stdout?.on("data", (d) => { + if (String(d).includes("ready")) { + clearTimeout(timer); + resolve(); + } + }); + proc.once("exit", (code) => { + clearTimeout(timer); + reject(new Error(`child exited early (${code}): ${stderr}`)); + }); + }); + return proc; +} + +/** Resolve with the exit code (null when killed by a signal) or "timeout". */ +function waitForExit(proc: ChildProcess, timeoutMs: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve("timeout"), timeoutMs); + proc.once("exit", (code) => { + clearTimeout(timer); + resolve(code); + }); + }); +} + +describe.skipIf(process.platform === "win32")("signal shutdown with a real browser (issue #33)", () => { + it.each([ + ["SIGTERM", 143], + ["SIGINT", 130], + ] as const)("%s closes the browser and exits %i within 10 s", async (signal, code) => { + const proc = await startChild(); + expect(processRunning(profile!)).toBe(true); + + const start = Date.now(); + proc.kill(signal); + const exitCode = await waitForExit(proc, EXIT_WITHIN_MS + 2_000); + const elapsed = Date.now() - start; + + expect(exitCode).toBe(code); + expect(elapsed).toBeLessThan(EXIT_WITHIN_MS); + // Chromium's helper processes may need a moment to go after the exit. + expect(await waitUntil(() => !processRunning(profile!), 3_000)).toBe(true); + }); +}); diff --git a/tests/retry.test.ts b/tests/retry.test.ts index d949e9b..d531d72 100644 --- a/tests/retry.test.ts +++ b/tests/retry.test.ts @@ -88,4 +88,55 @@ describe("withRetry", () => { withRetry(fn, "test", { maxRetries: 0, baseDelayMs: 10 }), ).rejects.toThrow("string error"); }); + + describe("with an abort signal (issue #33)", () => { + it("starts no further attempt once the signal is aborted", async () => { + const controller = new AbortController(); + const fn = vi.fn().mockImplementation(async () => { + controller.abort(new Error("stopped")); + throw new Error("Target page, context or browser has been closed"); + }); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("ends the back-off sleep early when aborted", async () => { + const controller = new AbortController(); + const fn = vi.fn().mockRejectedValue(new Error("flaky")); + setTimeout(() => controller.abort(new Error("stopped")), 50); + const start = Date.now(); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 5_000, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(Date.now() - start).toBeLessThan(2_000); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("does not log the retry warning for an aborted attempt", async () => { + const warnSpy = vi.spyOn(logger, "warn"); + try { + const controller = new AbortController(); + const fn = vi.fn().mockImplementation(async () => { + controller.abort(new Error("stopped")); + throw new Error("closed"); + }); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(warnSpy).not.toHaveBeenCalled(); + } finally { + warnSpy.mockRestore(); + } + }); + + it("does not start at all when the signal is already aborted", async () => { + const controller = new AbortController(); + controller.abort(new Error("stopped")); + const fn = vi.fn().mockResolvedValue("ok"); + await expect(withRetry(fn, "test", { signal: controller.signal })).rejects.toThrow("stopped"); + expect(fn).not.toHaveBeenCalled(); + }); + }); }); diff --git a/tests/shutdown.test.ts b/tests/shutdown.test.ts new file mode 100644 index 0000000..bae1366 --- /dev/null +++ b/tests/shutdown.test.ts @@ -0,0 +1,161 @@ +import { EventEmitter } from "node:events"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { installShutdownHandlers, SIGNAL_EXIT_CODES } from "../src/core/shutdown.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; + +/** A fake `process` that only emits signals. */ +function fakeSource() { + const emitter = new EventEmitter(); + return { + source: { on: (event: string, fn: () => void) => emitter.on(event, fn) }, + send: (event: "SIGHUP" | "SIGINT" | "SIGTERM") => emitter.emit(event), + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("installShutdownHandlers (issue #33)", () => { + it("closes the browsers and exits 143 on SIGTERM", async () => { + const { source, send } = fakeSource(); + const cleanup = vi.fn().mockResolvedValue(undefined); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, new AbortController()); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(cleanup).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(SIGNAL_EXIT_CODES.SIGTERM); + expect(SIGNAL_EXIT_CODES.SIGTERM).toBe(143); + }); + + it("closes the browsers and exits 130 on SIGINT", async () => { + const { source, send } = fakeSource(); + const cleanup = vi.fn().mockResolvedValue(undefined); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, new AbortController()); + + send("SIGINT"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(cleanup).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(130); + }); + + it("aborts the shutdown signal before cleanup runs, so running work stops", async () => { + const { source, send } = fakeSource(); + const controller = new AbortController(); + let abortedAtCleanup: boolean | undefined; + const cleanup = vi.fn(async () => { + abortedAtCleanup = controller.signal.aborted; + }); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, controller); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(abortedAtCleanup).toBe(true); + }); + + it("still exits when cleanup fails", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => Promise.reject(new Error("boom")), exit }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(143)); + }); + + it("forces the exit when cleanup hangs", async () => { + vi.useFakeTimers(); + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => new Promise(() => {}), exit, forceExitMs: 5_000 }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.advanceTimersByTimeAsync(4_999); + expect(exit).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(exit).toHaveBeenCalledWith(143); + }); + + it("exits only once when both signals arrive", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit }, + new AbortController(), + ); + + send("SIGTERM"); + send("SIGINT"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 20)); + + expect(exit).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(143); + }); + + it("exits 129 on SIGHUP (terminal closed)", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit }, + new AbortController(), + ); + send("SIGHUP"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(129)); + }); + + it("a second signal exits at once while cleanup still hangs", async () => { + vi.useFakeTimers(); + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => new Promise(() => {}), exit, forceExitMs: 5_000 }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.advanceTimersByTimeAsync(100); + expect(exit).not.toHaveBeenCalled(); + send("SIGTERM"); + expect(exit).toHaveBeenCalledWith(143); + await vi.advanceTimersByTimeAsync(10_000); + expect(exit).toHaveBeenCalledTimes(1); + }); + + it("aborts with a typed SHUTDOWN error, so nothing retries it", async () => { + const { source, send } = fakeSource(); + const controller = new AbortController(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit: vi.fn() }, + controller, + ); + send("SIGINT"); + expect(hasUnrecoverableKind(controller.signal.reason, "SHUTDOWN")).toBe(true); + }); + + it("handles only the signals it is given (no SIGHUP under nohup)", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit, signals: ["SIGINT", "SIGTERM"] }, + new AbortController(), + ); + send("SIGHUP"); + await new Promise((r) => setTimeout(r, 20)); + expect(exit).not.toHaveBeenCalled(); + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(143)); + }); +}); diff --git a/tests/timeout.test.ts b/tests/timeout.test.ts new file mode 100644 index 0000000..08f6699 --- /dev/null +++ b/tests/timeout.test.ts @@ -0,0 +1,119 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { runWithTimeout } from "../src/core/timeout.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** A task that runs until aborted, then takes `closeMs` to finish. */ +function untilAborted(events: string[], closeMs: number) { + return (signal: AbortSignal) => + new Promise((_, reject) => { + signal.addEventListener( + "abort", + () => + setTimeout(() => { + events.push("closed"); + reject(new Error("closed")); + }, closeMs), + { once: true }, + ); + }); +} + +describe("runWithTimeout (issue #33)", () => { + it("returns the task's value when it finishes in time", async () => { + await expect(runWithTimeout(async () => "ok", { timeoutMs: 1_000 })).resolves.toBe("ok"); + }); + + it("rethrows the task's own error when it fails in time", async () => { + await expect( + runWithTimeout(async () => Promise.reject(new Error("boom")), { timeoutMs: 1_000 }), + ).rejects.toThrow("boom"); + }); + + it("on timeout aborts the task and waits for it to finish before rejecting", async () => { + const events: string[] = []; + const err = await runWithTimeout(untilAborted(events, 100), { timeoutMs: 50 }).catch( + (e: unknown) => e, + ); + expect(events).toEqual(["closed"]); + expect(hasUnrecoverableKind(err, "LOCATION_TIMEOUT")).toBe(true); + expect((err as Error).message).toBe("Location timeout after 0.05s"); + }); + + it("passes the timeout as the abort reason", async () => { + let reason: unknown; + await runWithTimeout( + (signal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => { + reason = signal.reason; + reject(signal.reason); + }), + ), + { timeoutMs: 20 }, + ).catch(() => {}); + expect(hasUnrecoverableKind(reason, "LOCATION_TIMEOUT")).toBe(true); + }); + + it("rejects with the timeout even when the task resolves after it", async () => { + const err = await runWithTimeout( + async () => { + await wait(100); + return "late"; + }, + { timeoutMs: 20 }, + ).catch((e: unknown) => e); + expect(hasUnrecoverableKind(err, "LOCATION_TIMEOUT")).toBe(true); + }); + + it("reports BROWSER_NOT_CLOSED when the task does not finish within the grace period", async () => { + const start = Date.now(); + const err = await runWithTimeout(() => new Promise(() => {}), { + timeoutMs: 20, + settleGraceMs: 100, + }).catch((e: unknown) => e); + expect(hasUnrecoverableKind(err, "BROWSER_NOT_CLOSED")).toBe(true); + expect(Date.now() - start).toBeLessThan(1_000); + }); + + it("stops the task when the outer signal aborts", async () => { + const outer = new AbortController(); + setTimeout(() => outer.abort(new Error("shutdown")), 20); + const err = await runWithTimeout( + (signal) => + new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))), + { timeoutMs: 5_000, signal: outer.signal }, + ).catch((e: unknown) => e); + expect((err as Error).message).toBe("shutdown"); + }); + + describe("leaves no timer running (a stray timer kept revcli alive after the last place)", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("after success", async () => { + vi.useFakeTimers(); + await runWithTimeout(async () => "ok", { timeoutMs: 60_000 }); + expect(vi.getTimerCount()).toBe(0); + }); + + it("after the task fails", async () => { + vi.useFakeTimers(); + await runWithTimeout(async () => Promise.reject(new Error("x")), { timeoutMs: 60_000 }).catch(() => {}); + expect(vi.getTimerCount()).toBe(0); + }); + + it("after a timeout", async () => { + vi.useFakeTimers(); + const done = runWithTimeout( + (signal) => new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))), + { timeoutMs: 1_000 }, + ).catch(() => {}); + await vi.advanceTimersByTimeAsync(1_000); + await done; + expect(vi.getTimerCount()).toBe(0); + }); + }); +});