From 1ee8a405611ac1e44b497e5a695fb4a371e0dbe8 Mon Sep 17 00:00:00 2001 From: Marcin Obel <7283716+marcinobel@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:09:36 +0100 Subject: [PATCH 1/3] fix(scraper): repair scraping broken in 0.1.5 (#32) Scrapes crashed after the first ~10 reviews, long reviews stayed cut off, and a dead Google session was reported as signed in. - scroll: pass the scroll step into the page instead of reading a Node-side constant inside page.evaluate (ReferenceError on the second scroll) - expand: click each "More" button by a mark on the element and confirm the result; Google now removes the button on click, which made the positional loop skip every second review. Warn with the number of reviews that stay cut off - session: one check for "Google accepts this session" (getSessionState) used by auth, auth status and the sign-in wait; an expired session is no longer reported as signed in - limited view: typed AUTH_REQUIRED error, never retried, one message that says to run `revcli auth`, for every sort order; headed mode asks for sign-in and continues - non-place links fail once with NOT_A_PLACE - short links: wait for the in-page redirect before forcing hl=en, so signed-out and non-English profiles get an English page - errors: one top-level handler, no stack trace without --verbose, Playwright call logs removed from messages - tests: browser tests run the scroll, expand, session and navigation code in headless Chromium against local fixtures; CI installs Chromium - docs: README, AGENTS.md, selector maintenance guide, CHANGELOG Refs #31 Claude-Session: https://claude.ai/code/session_01PuLVjZfdZVDn9e5QnCEtCH --- .github/workflows/ci.yml | 7 + AGENTS.md | 32 ++- CHANGELOG.md | 13 ++ README.md | 26 ++- docs/selector-maintenance.md | 33 ++- package.json | 1 + src/commands/auth.ts | 138 +++++++++--- src/commands/batch.ts | 6 +- src/core/errors.ts | 52 ++++- src/core/fatal.ts | 48 +++++ src/core/retry.ts | 8 +- src/index.ts | 5 +- src/scraper/auth.ts | 271 ++++++++++++++++++------ src/scraper/browser.ts | 14 +- src/scraper/consent.ts | 52 ++++- src/scraper/extractor.ts | 229 ++++++++++++++++++-- src/scraper/navigator.ts | 128 +++++++++-- src/scraper/scrape-location.ts | 77 +++++-- src/scraper/scroller.ts | 142 +++++++------ src/scraper/selectors.ts | 30 ++- src/utils/url.ts | 39 +++- tests/auth-command.test.ts | 56 +++++ tests/auth.test.ts | 94 +++++++-- tests/browser-import-guard.test.ts | 96 +++++++++ tests/browser/expand.test.ts | 221 +++++++++++++++++++ tests/browser/fixtures/maps-page.ts | 316 ++++++++++++++++++++++++++++ tests/browser/harness.ts | 62 ++++++ tests/browser/navigation.test.ts | 208 ++++++++++++++++++ tests/browser/scroll.test.ts | 53 +++++ tests/browser/session.test.ts | 210 ++++++++++++++++++ tests/consent.test.ts | 55 ++++- tests/extractor.test.ts | 15 ++ tests/fatal.test.ts | 123 +++++++++++ tests/retry.test.ts | 25 +++ tests/scrape-location.test.ts | 77 ++++++- tests/selectors.test.ts | 28 +++ tests/unrecoverable.test.ts | 27 ++- tests/url.test.ts | 51 +++++ 38 files changed, 2793 insertions(+), 275 deletions(-) create mode 100644 src/core/fatal.ts create mode 100644 tests/auth-command.test.ts create mode 100644 tests/browser-import-guard.test.ts create mode 100644 tests/browser/expand.test.ts create mode 100644 tests/browser/fixtures/maps-page.ts create mode 100644 tests/browser/harness.ts create mode 100644 tests/browser/navigation.test.ts create mode 100644 tests/browser/scroll.test.ts create mode 100644 tests/browser/session.test.ts create mode 100644 tests/fatal.test.ts create mode 100644 tests/selectors.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95c621e..f929a35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,13 @@ jobs: - name: Install dependencies run: npm ci + # Browser tests (tests/browser) run the in-page scroll/expand/session/navigation code + # against local fixtures in headless Chromium. Only the headless shell is needed. + # `npm exec --no` uses the locally installed Playwright and never fetches from the registry. + # Do not copy this step into release.yml's publish job (it holds id-token: write). + - name: Install Chromium (headless shell) for browser tests + run: npm exec --no -- playwright install --with-deps --only-shell chromium + - name: Type check run: npm run typecheck diff --git a/AGENTS.md b/AGENTS.md index 5128c34..8477718 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,13 +15,14 @@ npm run dev -- scrape '' [options] # Run CLI directly (single-quote URLs!) npm run dev -- auth # Authenticate with Google (opens browser) npm run dev -- auth status # Check if signed in npm run build # Build to dist/ via tsup (ESM, shebang) -npm test # Run all tests (vitest) +npm test # Run all tests (vitest) – needs Chromium (browser tests) +npm run test:browser # Only the headless-browser tests (tests/browser) npm run test:watch # Watch mode npx vitest run tests/parser.test.ts # Run a single test file npm run typecheck # Type check without emitting npm run check:pack # Assert the tarball contract (dist present, no src/tests) npm run test:package # Pack + install into a temp consumer, assert --version -npx playwright install chromium # Required once before first scrape +npx playwright install chromium # Required once before first scrape and before `npm test` # Release (see "Release and publishing" below) node scripts/release.mjs patch|minor|major # Prepare: stamp package.json + lock (the workflow opens the bump PR) @@ -104,8 +105,8 @@ CLI (src/index.ts) ─── commander routes to 4 commands: 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 -├── auth.ts ── isSignedIn(), hasLimitedView(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() – Google auth detection; decideSignedIn()/GOOGLE_AUTH_COOKIES make the cookie check authoritative -├── navigator.ts ── orchestrates state eviction → consent → locale → limited-view check → tab → sort; verifies loaded placeId against parsed.placeId +├── 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 ├── business-extractor.ts ── business name/rating/totalReviews/address extraction; page.evaluate() returns raw DOM strings only, parsing happens Node-side via parseReviewCount + parseRatingText; PII-scrubbed debug logging of candidate strings ├── scroller.ts ── mouse wheel scrolling, deduplication by review ID, exponential backoff stale-scroll detection, loading spinner awareness @@ -117,7 +118,8 @@ src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (u src/core/ ├── schema.ts ── Zod schemas + SortOrder/OutputFormat union types + SORT_ORDERS/OUTPUT_FORMATS constants ├── retry.ts ── withRetry() – exponential backoff, isUnrecoverable() detection (instanceof UnrecoverableError + substring fallback) -├── errors.ts ── UnrecoverableError typed class with `kind` discriminator – prefer over magic-substring Error for anything we throw +├── 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 src/output/ @@ -138,10 +140,10 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la ### Patterns to know - **Persistent browser profile**: `launchBrowser()` uses `chromium.launchPersistentContext()` with `~/.revcli/chrome-profile/`. Google auth cookies survive between CLI runs. The `PROFILE_DIR` constant is exported from `browser.ts`. `ensureProfileDir()` in `browser.ts` creates the directory with owner-only `0700` permissions – it is a **credential store** holding your Google session cookies, so it must never be shared, backed up, or committed. The profile's spoofed user-agent and `navigator.webdriver` masking are ToS-sensitive (see the anti-automation note in README's Legal notice); removing them would break unauthenticated scraping. -- **Authentication flow**: Google Maps shows a "limited view" (no Reviews tab) to unauthenticated EEA users. `revcli auth` opens a browser for manual sign-in and never short-circuits on an existing session – the window stays open (until the user closes it) so the profile can be switched to a different account. The scrape command also detects limited view inline and can prompt for auth in headed mode. -- **Cookie-authoritative sign-in detection**: `auth.ts` defines `GOOGLE_AUTH_COOKIES` (the definitive set of Google session cookies: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`). `decideSignedIn(cookieCheckSucceeded, hasAuthCookies, signInButtonVisible)` treats a successful cookie check as authoritative – when `cookieCheckSucceeded` is true, `hasAuthCookies` decides, and the DOM "Sign in" button is only a fallback when the cookie check failed. `hasGoogleAuthSession()` checks the cookie set directly; `waitForSignIn()` polls and throws a typed `UnrecoverableError` with kind `"AUTH_POLL"` on timeout, returning `SignInOutcome` (`"signed-in"` | `"browser-closed"`) otherwise – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. +- **Authentication flow**: Google Maps shows a "limited view" to signed-out EEA users and to profiles whose saved session has expired: the Reviews tab is still there but only ~5 reviews load, a "You're seeing a limited view of Google Maps" banner appears, and Sort opens a "Sign-in to get the best of Google Maps" dialog. **The scrape decides from these limited-view signals (banner + Sort sign-in dialog), not from session state**, because non-EEA signed-out users get the full view – do not "simplify" this to a session check. `openReviewsTab()` checks the banner twice (after the tabs, and again after the review cards, since it can render late and `relevant` has no Sort click); `setSortOrder()` waits for the first *visible* of the sort menu or `SELECTORS.signInDialog`. Both throw `authRequiredError()` (`UnrecoverableError` kind `"AUTH_REQUIRED"`, never retried). `scrapeLocation()` delegates to the exported, fake-tested `navigateWithAuthFallback()`: headless rethrows at once; headed runs `waitForUserAuth()` and navigates again, **using the second navigation's business info**. A terminal `AUTH_REQUIRED` is reworded by a 5 s session probe: `authRequiredMessage()` gives the "run `revcli auth`" text for `expired`/`signed-out`/unknown and a "appears to be signed in" text for `signed-in`/`unconfirmed`, so `auth status` and the scrape cannot contradict each other silently. Session state is only used to word that error and to detect sign-in completion. `revcli auth` opens a browser for manual sign-in and never short-circuits on a real session – for `signed-in`/`unconfirmed` the window stays open until the user closes it (#24, account switching); for `expired` it says so and waits for a fresh sign-in, closing on detection. +- **Session state (single source of truth)**: `getSessionState(page, { timeoutMs, stableMs })` in `auth.ts` returns `SessionState` (`"signed-in" | "expired" | "signed-out" | "unconfirmed"`) and is used by `auth`, `auth status` and `waitForSignIn()`; there is no second "is signed in" check. It reads the `.google.com` cookies (`GOOGLE_AUTH_COOKIES`: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`/`__Secure-*PAPISID`) – no auth cookies is a fast `signed-out` – then waits (default 15 s) for an account marker: `SELECTORS.accountButton` (`a[href^="https://accounts.google.com/SignOutOptions"]`) vs `SELECTORS.signInLink` (`…/ServiceLogin`). Markers are matched by **href, never aria-label**: hrefs are language-independent, while labels are localized and the account label holds the user's name and email. Cookies prove a session *exists*, not that Google *accepts* it – a dead session keeps its cookies and shows "Sign in", which `decideSessionState()` (pure, exported) maps to `expired`. With auth cookies a "Sign in" link must stay the only marker for `stableMs` because Google can render it briefly on a valid session – `SESSION_SIGN_IN_STABLE_MS` (3 s, the default, for `auth` and `auth status`, which report once) and `POLL_SIGN_IN_STABLE_MS` (1.5 s, in `POLL_PROBE`, for the sign-in poll loop and the scrape's error wording, which simply ask again); the account link always wins; no stable marker in time → `unconfirmed` (trusted with a warning by `auth`/`auth status`; `waitForSignIn()` keeps polling). The marker read swallows every Playwright error and never logs error text, element HTML or labels (Playwright call logs print markup). `waitForSignIn()` takes an injectable `probe` (defaults to `getSessionState` with `POLL_PROBE`: 5 s marker wait, 1.5 s stability; `tests/browser/session.test.ts` also runs it with the real probe), returns `"signed-in"` only when the probe says so, throws `UnrecoverableError` kind `"AUTH_POLL"` on timeout, and returns `SignInOutcome` (`"signed-in"` | `"browser-closed"`) – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. - **Default headed mode**: The browser shows by default so users can observe scraping. Use `--headless` to hide it. This is the opposite of most scrapers – it's intentional because auth requires a visible browser. -- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. +- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. After the page has landed (redirects, consent), `ensureEnglishLocale()` navigates again when the *parsed* query has `hl` other than exactly `en` (pure helper `englishLocaleTarget()`). Only for short-link input (`stripLimitedViewParams: parsed.isShortUrl`) it also navigates to strip `entry`/`g_ep`, because that is the one case where they could not be stripped before the load; on other links Google's own page script may add them back, and re-checking would cost a second page load on every scrape. - **Centralized selectors**: All Google Maps CSS class selectors live in `src/scraper/selectors.ts`. Google obfuscates these names and changes them periodically. When scraping breaks, check selectors first. See [docs/selector-maintenance.md](docs/selector-maintenance.md) for the full update procedure. - **Mouse wheel scrolling**: Google Maps' virtualized review list only lazy-loads from real scroll events. `page.mouse.wheel()` triggers it; `scrollTop` alone does not. - **Zod as source of truth**: Types are derived from Zod schemas via `z.infer<>`. The `parseReview()` function validates every review at the boundary before it enters the output. @@ -160,7 +162,14 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **totalReviews reconciliation**: `assembleScrapeResult()` in `src/scraper/scrape-location.ts` is an exported pure helper called from `scrapeLocation()` to enforce the invariant `business.totalReviews === reviews.length` at the single seam where `businessInfo` (header-derived) and `reviews` (scraped) first coexist. The original Google-header value is preserved as `business.headerTotalReviews`. See issue #5. When `--max-reviews N` caps collection, `totalReviews === N` (not the header) and `headerTotalReviews` holds Google's larger number. - **Header parsing extracted for testability**: `src/scraper/parser.ts` exports `parseReviewCount(text)` and `src/scraper/business-extractor.ts` exports `parseRatingText(text)`. Both are pure functions called from the Node side after `page.evaluate()` returns raw DOM strings. This matches the repo's "extract pure logic out of Playwright-coupled code" convention (see `parseInputFile`, `extractPlaceIdFromUrl`, `calculateStaleDelay`). `parseReviewCount` assumes the `hl=en` locale – comma thousand separator, period is a decimal and not a thousands separator. Suffix forms (`1.6K reviews`) return null; reconciliation backfills via `reviews.length`. - **Business header debug logging**: `business-extractor.ts` emits PII-scrubbed debug-level logs of raw DOM candidate strings (tab text, aria-label badge, scoped `[role="main"]` body snippet) so selector staleness can be diagnosed from `--verbose` output without leaking reviewer names or review content. The scrub preserves digits, separators, K/M/B suffixes, and the letters of "reviews"; all other characters become `·`. -- **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)`. Chaining scopes both alternatives to the parent's subtree. `expandAllReviews()` in `extractor.ts` is the reference implementation. `tests/extractor-selectors.test.ts` pins the regression shape. +- **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. +- **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`. +- **Browser tests**: `tests/browser/*.test.ts` run the real in-page code (scroll, expand, session markers, navigation) in a fresh non-persistent headless Chromium (`chromium.launch`) against local HTML from `tests/browser/fixtures/maps-page.ts`. They must **never** import `launchBrowser` or `PROFILE_DIR` (the `~/.revcli` credential store); `tests/browser-import-guard.test.ts` scans every test file for such imports. Timing-sensitive fixture behaviour is event-driven where possible (e.g. `bannerOnReviewsTabClick` shows the banner only after revcli's first check). The harness registers `context.route("**/*", abort)` first and fixture routes after it, so nothing reaches the network even with fake cookies. Fixture behaviour is a plain ` +`; +} diff --git a/tests/browser/harness.ts b/tests/browser/harness.ts new file mode 100644 index 0000000..d800c5a --- /dev/null +++ b/tests/browser/harness.ts @@ -0,0 +1,62 @@ +/** + * Browser-test harness: a throwaway headless Chromium that only ever sees + * local fixture HTML. + * + * Rules (see AGENTS.md "Browser tests"): + * - Never import `launchBrowser` or `PROFILE_DIR` from src/scraper/browser.ts + * here or in any browser test. They open the persistent profile in + * ~/.revcli, which is a credential store holding a real Google session. + * - Every context blocks all network traffic first; fixture routes are added + * afterwards (Playwright runs the most recently registered matching route + * first), so nothing can reach Google even with fake cookies in the context. + */ +import { + chromium, + type Browser, + type BrowserContext, + type Page, +} from "playwright"; + +export async function launchTestBrowser(): Promise { + return chromium.launch({ headless: true }); +} + +/** A fresh, non-persistent context with every network request aborted. */ +export async function newFixtureContext(browser: Browser): Promise { + const context = await browser.newContext({ + viewport: { width: 1280, height: 800 }, + locale: "en-US", + }); + await context.route("**/*", (route) => route.abort()); + return context; +} + +/** A page whose content is the given fixture HTML (no URL, no network). */ +export async function newFixturePage( + context: BrowserContext, + html: string, +): Promise { + const page = await context.newPage(); + await page.setContent(html); + return page; +} + +export type RouteMatcher = string | RegExp | ((url: URL) => boolean); + +/** + * Serve fixture HTML for requests matching `url`. Registered after the + * abort-all route, so it takes precedence for its own URLs only. + * + * There is deliberately no redirect variant: Playwright does not route the + * follow-up request of a fulfilled 3xx, so such a navigation hangs. Fixtures + * that need a different final URL use `rewriteUrlTo` (history.replaceState). + */ +export async function routeFixture( + context: BrowserContext, + url: RouteMatcher, + html: string, +): Promise { + await context.route(url, (route) => + route.fulfill({ status: 200, contentType: "text/html", body: html }), + ); +} diff --git a/tests/browser/navigation.test.ts b/tests/browser/navigation.test.ts new file mode 100644 index 0000000..b56677e --- /dev/null +++ b/tests/browser/navigation.test.ts @@ -0,0 +1,208 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { navigateToReviews, NOT_A_PLACE_MESSAGE, setSortOrder } from "../../src/scraper/navigator.js"; +import { parseGoogleMapsInput } from "../../src/utils/url.js"; +import { hasUnrecoverableKind, UnrecoverableError } from "../../src/core/errors.js"; +import { SORT_ORDERS } from "../../src/core/schema.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +const PLACE_URL = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en"; +const isPlacePath = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps/place/Test/data=!1s0x1:0x2"; +const CID_URL = "https://www.google.com/maps?cid=1234567890"; +const isCidLink = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps" && u.searchParams.has("cid"); +const SEARCH_PATH = "/maps/search/foo/@1,2,3z?hl=en"; + +const PLACE: MapsFixtureOptions = { totalReviews: 10, batchSize: 10, withSortMenu: true }; + +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(); +}); + +async function rejection(p: Promise): Promise { + return p.then( + () => new Error("expected a rejection"), + (e: unknown) => e, + ); +} + +describe("navigateToReviews on a limited view (issue #31 finding 5)", () => { + it.each([...SORT_ORDERS])("fails with AUTH_REQUIRED for sort %s", async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, limitedViewBanner: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it("catches a banner that appears only after the Reviews tab is clicked", async () => { + // The banner is inserted by the tab click, i.e. after the first check: + // only the second check (after the review cards) can see it. + await routeFixture( + context, + isPlacePath, + buildMapsPage({ ...PLACE, limitedViewBanner: true, bannerOnReviewsTabClick: true }), + ); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it.each(["newest", "highest", "lowest"] as const)( + "fails with AUTH_REQUIRED when Sort opens the sign-in dialog, with no banner (sort %s)", + async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }, + ); + + it("does not see the Sort sign-in dialog for sort relevant (no Sort click), so it resolves", async () => { + // Pins current behaviour: with no banner, "relevant" never clicks Sort, so + // the dialog signal cannot fire. The banner is the only signal for it. + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); + + it("is not fooled by a review quoting the banner text", async () => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, reviewQuotingBanner: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); +}); + +describe("navigateToReviews on a short link (issue #31)", () => { + it("waits for the script redirect before forcing hl=en", async () => { + // Google redirects maps.app.goo.gl links in page script. If hl=en is added + // to the short link itself it is lost, and a signed-out or non-English + // profile gets a localized page that no English selector matches. + // hl=en is already there, so only the short-link rule can cause the + // extra navigation that strips entry/g_ep. + const target = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en&entry=tts&g_ep=Egoy"; + await routeFixture( + context, + (u) => u.hostname === "maps.app.goo.gl", + ``, + ); + await routeFixture(context, isPlacePath, buildMapsPage(PLACE)); + const page = await context.newPage(); + + await navigateToReviews(page, parseGoogleMapsInput("https://maps.app.goo.gl/abcDEF123"), "relevant"); + + const finalUrl = new URL(page.url()); + expect(finalUrl.hostname).toBe("www.google.com"); + expect(finalUrl.searchParams.get("hl")).toBe("en"); + expect(finalUrl.searchParams.has("entry")).toBe(false); + expect(finalUrl.searchParams.has("g_ep")).toBe(false); + }); +}); + +describe("setSortOrder", () => { + it("fails fast with AUTH_REQUIRED when Sort opens the sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("is not stalled by a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ ...PLACE, sortOpensSignInDialog: true, hiddenMenuTemplate: true }), + ); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("carries on when the sort menu is visible alongside a sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, signInDialogAtLoad: true })); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort through the real menu", async () => { + const page = await newFixturePage(context, buildMapsPage(PLACE)); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort with a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, hiddenMenuTemplate: true })); + + await expect(setSortOrder(page, "lowest")).resolves.toBeUndefined(); + }); +}); + +// The link loads, then the page rewrites its URL to a search results path – as +// Google Maps does for a link that does not resolve to one place. +describe("navigateToReviews on a non-place link (issue #31 finding 6)", () => { + const searchPage = (h1: string | null) => + buildMapsPage({ totalReviews: 0, batchSize: 1, h1, tabs: [], rewriteUrlTo: SEARCH_PATH }); + + it("fails once with NOT_A_PLACE when the link lands on a search page without h1", async () => { + await routeFixture(context, isCidLink, searchPage(null)); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(UnrecoverableError); + expect((err as UnrecoverableError).kind).toBe("NOT_A_PLACE"); + expect((err as UnrecoverableError).message).toBe(NOT_A_PLACE_MESSAGE); + }); + + it("fails with NOT_A_PLACE when the search page has an h1 but no tabs", async () => { + await routeFixture(context, isCidLink, searchPage("Results")); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "NOT_A_PLACE")).toBe(true); + }); + + it("rethrows a plain timeout when a place panel never loads on a non-search URL", async () => { + await routeFixture(context, isCidLink, buildMapsPage({ totalReviews: 0, batchSize: 1, h1: null })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(Error); + expect(err).not.toBeInstanceOf(UnrecoverableError); + }); +}); diff --git a/tests/browser/scroll.test.ts b/tests/browser/scroll.test.ts new file mode 100644 index 0000000..0b84a83 --- /dev/null +++ b/tests/browser/scroll.test.ts @@ -0,0 +1,53 @@ +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 { buildMapsPage } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +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(); +}); + +describe("scrollAndCollectReviews (in-page scroll code, issue #31 finding 1)", () => { + it("collects exactly maxReviews across several scrolls", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 35, batchSize: 10 }), + ); + + const reviews = await scrollAndCollectReviews(page, { maxReviews: 30, delayMs: 1 }); + + expect(reviews).toHaveLength(30); + expect(new Set(reviews.map((r) => r.id)).size).toBe(30); + }); + + it("collects every review and stops when the list stops growing", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 12, batchSize: 5 }), + ); + + const reviews = await scrollAndCollectReviews(page, { delayMs: 1 }); + + expect(reviews.map((r) => r.id).sort()).toEqual( + Array.from({ length: 12 }, (_, i) => `r${i}`).sort(), + ); + }); +}); diff --git a/tests/browser/session.test.ts b/tests/browser/session.test.ts new file mode 100644 index 0000000..9877311 --- /dev/null +++ b/tests/browser/session.test.ts @@ -0,0 +1,210 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { + getSessionState, + POLL_PROBE, + SESSION_SIGN_IN_STABLE_MS, + waitForSignIn, +} from "../../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../../src/core/errors.js"; +import { logger } from "../../src/utils/logger.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** Made-up values: the context blocks all network, so these never reach Google. */ +const FAKE_AUTH_COOKIES = ["SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-1PSID", "__Secure-3PSID"]; +const PII = ["test.user@example.com", "Konto Google"]; + +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(); +}); + +async function addFakeAuthCookies(): Promise { + await context.addCookies( + FAKE_AUTH_COOKIES.map((name) => ({ + name, + value: `revcli-fake-${name}`, + domain: ".google.com", + path: "/", + secure: true, + })), + ); +} + +function page(opts: Partial) { + return newFixturePage(context, buildMapsPage({ totalReviews: 0, batchSize: 1, ...opts })); +} + +async function timed(fn: () => Promise): Promise<{ value: T; ms: number }> { + const start = Date.now(); + const value = await fn(); + return { value, ms: Date.now() - start }; +} + +describe("getSessionState (issue #31 findings 3–4)", () => { + it("reports a dead session (cookies + steady Sign in link) as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("expired"); + expect(ms).toBeGreaterThanOrEqual(SESSION_SIGN_IN_STABLE_MS); + }); + + it("uses a longer stability window for the commands than for the poll loop", async () => { + // "Sign in" for 2 s, then the account link: longer than the poll loop's + // 1.5 s window, shorter than the commands' 3 s window. + await addFakeAuthCookies(); + const timeline = [ + { atMs: 0, marker: "sign-in" as const }, + { atMs: 2000, marker: "account" as const }, + ]; + + const forCommands = await page({ markerTimeline: timeline }); + expect(await getSessionState(forCommands)).toBe("signed-in"); + + const forPolling = await page({ markerTimeline: timeline }); + expect(await getSessionState(forPolling, POLL_PROBE)).toBe("expired"); + }); + + it("reports cookies + account link as signed-in", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "en" }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("reads the markers independently of the page language", async () => { + await addFakeAuthCookies(); + const account = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "pl" }); + expect(await getSessionState(account)).toBe("signed-in"); + + const signIn = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }], markerLang: "pl" }); + expect(await getSessionState(signIn)).toBe("expired"); + }); + + it("reports signed-out quickly when there are no auth cookies", async () => { + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-out"); + expect(ms).toBeLessThan(1000); + }); + + it("waits for a slow account marker, and is unconfirmed when none appears", async () => { + await addFakeAuthCookies(); + const slow = await page({ markerTimeline: [{ atMs: 1500, marker: "account" }] }); + expect(await getSessionState(slow)).toBe("signed-in"); + + const none = await page({}); + expect(await getSessionState(none, { timeoutMs: 500 })).toBe("unconfirmed"); + }); + + it("never reports a transient Sign in link on a valid session as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ + markerTimeline: [ + { atMs: 0, marker: "sign-in" }, + { atMs: 800, marker: "account" }, + ], + }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("ignores a hidden duplicate Sign in link earlier in the DOM", async () => { + await addFakeAuthCookies(); + const p = await page({ + hiddenDuplicateMarker: "sign-in", + markerTimeline: [{ atMs: 0, marker: "account" }], + }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-in"); + expect(ms).toBeLessThan(2000); + }); + + it("never logs the account label (name, email)", async () => { + const spies = (["debug", "info", "warn", "error"] as const).map((level) => + vi.spyOn(logger, level), + ); + try { + await addFakeAuthCookies(); + for (const markerLang of ["en", "pl"] as const) { + for (const marker of ["account", "sign-in"] as const) { + const p = await page({ markerTimeline: [{ atMs: 0, marker }], markerLang }); + await getSessionState(p, POLL_PROBE); + } + } + const unconfirmed = await page({ hiddenDuplicateMarker: "account" }); + await getSessionState(unconfirmed, { timeoutMs: 300 }); + + const logged = spies.flatMap((s) => s.mock.calls).map((args) => args.map(String).join(" ")); + expect(logged.length).toBeGreaterThan(0); + for (const line of logged) { + for (const secret of PII) expect(line).not.toContain(secret); + } + } finally { + for (const spy of spies) spy.mockRestore(); + } + }); +}); + +// The real session probe inside the sign-in poll loop (no injected `probe`). +// A cookie-only check would report "signed-in" for the dead session below. +describe("waitForSignIn with the real session probe", () => { + const MAPS_HOME = "https://www.google.com/maps?hl=en"; + const isMapsHome = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps"; + + it("keeps waiting on a dead session (cookies + steady Sign in link) and times out", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "sign-in" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + const err = await waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 }).catch( + (e: unknown) => e, + ); + + expect(hasUnrecoverableKind(err, "AUTH_POLL")).toBe(true); + }); + + it("returns signed-in once Google shows the account link", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "account" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + await expect(waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 })).resolves.toBe( + "signed-in", + ); + }); +}); diff --git a/tests/consent.test.ts b/tests/consent.test.ts index e92b189..a3121c0 100644 --- a/tests/consent.test.ts +++ b/tests/consent.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { appendHlParam } from "../src/scraper/consent.js"; +import { appendHlParam, englishLocaleTarget } from "../src/scraper/consent.js"; import { extractPlaceIdFromUrl } from "../src/utils/url.js"; describe("appendHlParam", () => { @@ -68,3 +68,56 @@ describe("appendHlParam", () => { expect(placeId).toBe("0x3e2ee3641f7016d7:0x8e3a8bcf52dad296"); }); }); + +describe("appendHlParam short-link detection", () => { + it("rewrites a normal Maps link that only mentions the short-link host in its query", () => { + const out = appendHlParam("https://www.google.com/maps/place/Test/@0,0,15z?ref=maps.app.goo.gl"); + expect(new URL(out).searchParams.get("hl")).toBe("en"); + }); +}); + +describe("englishLocaleTarget", () => { + const params = (url: string | null) => new URL(url ?? "about:blank").searchParams; + + it("returns null for an English URL without limited-view params", () => { + expect(englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en")).toBeNull(); + }); + + it("forces hl=en when hl is missing or another language", () => { + for (const url of [ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=pl", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en-GB", + ]) { + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + } + }); + + it("does not mistake hl=en inside another parameter's value for the locale", () => { + const url = "https://www.google.com/maps/place/Test/@0,0,15z?q=hl%3Den&hl=de"; + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + }); + + it("leaves an English URL alone when Google's script re-added entry/g_ep", () => { + // Without the option, tracking params must not cost a second page load. + expect( + englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=ttu&g_ep=Egoy"), + ).toBeNull(); + }); + + it("strips entry and g_ep after a short-link redirect even when hl is already en", () => { + const target = englishLocaleTarget( + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=tts&g_ep=Egoy", + { stripLimitedViewParams: true }, + ); + const p = params(target); + expect(p.get("hl")).toBe("en"); + expect(p.has("entry")).toBe(false); + expect(p.has("g_ep")).toBe(false); + }); + + it("returns null for a short link and for unparseable input", () => { + expect(englishLocaleTarget("https://maps.app.goo.gl/abc123")).toBeNull(); + expect(englishLocaleTarget("not a url")).toBeNull(); + }); +}); diff --git a/tests/extractor.test.ts b/tests/extractor.test.ts index 769c23e..c7f75cf 100644 --- a/tests/extractor.test.ts +++ b/tests/extractor.test.ts @@ -5,8 +5,23 @@ import { buildCardSelector, shouldFallbackLang, resolveOriginalLanguage, + formatTruncationWarning, } from "../src/scraper/extractor.js"; +describe("formatTruncationWarning", () => { + it("uses the singular noun for a single collected review", () => { + expect(formatTruncationWarning(1, 1)).toBe( + 'Could not expand the full text of 1 of 1 collected review – their text may be cut off (ends with "…").', + ); + }); + + it("uses the plural noun for several collected reviews", () => { + expect(formatTruncationWarning(3, 300)).toBe( + 'Could not expand the full text of 3 of 300 collected reviews – their text may be cut off (ends with "…").', + ); + }); +}); + describe("isShowingTranslation", () => { it("is true when aria-checked is 'true'", () => { expect(isShowingTranslation("true")).toBe(true); diff --git a/tests/fatal.test.ts b/tests/fatal.test.ts new file mode 100644 index 0000000..c19271c --- /dev/null +++ b/tests/fatal.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { describeFatalError, reportFatalError, safeErrorMessage } from "../src/core/fatal.js"; +import { logger } from "../src/utils/logger.js"; +import { UnrecoverableError } from "../src/core/errors.js"; + +describe("describeFatalError", () => { + it("treats a typed UnrecoverableError as expected", () => { + const f = describeFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + expect(f).toMatchObject({ message: "Run `revcli auth`.", expected: true }); + }); + + it("treats an invalid-input error as expected", () => { + const f = describeFatalError(new Error('Invalid input: "foo". Provide a Google Maps URL or Place ID.')); + expect(f.expected).toBe(true); + expect(f.message).toBe('Invalid input: "foo". Provide a Google Maps URL or Place ID.'); + }); + + it("treats a missing file (ENOENT) as expected", () => { + const err = Object.assign(new Error("ENOENT: no such file or directory, open 'urls.txt'"), { + code: "ENOENT", + }); + expect(describeFatalError(err).expected).toBe(true); + }); + + it("treats a plain error as unexpected and keeps its stack for debug output", () => { + const f = describeFatalError(new Error("Something went wrong")); + expect(f.expected).toBe(false); + expect(f.message).toBe("Something went wrong"); + expect(f.stack).toContain("Something went wrong"); + }); + + it("stringifies a non-Error throwable", () => { + expect(describeFatalError("plain string")).toEqual({ + message: "plain string", + stack: null, + expected: false, + }); + }); + + it("cuts Playwright's call log, which can contain the account name and email", () => { + const err = new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + const f = describeFatalError(err); + expect(f.message).toBe("locator.click: Timeout 1000ms exceeded."); + expect(f.message).not.toContain("Call log"); + expect(f.message).not.toContain("example.com"); + expect(f.stack).not.toContain("example.com"); + }); +}); + +const CALL_LOG_ERROR = () => + new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + +describe("safeErrorMessage", () => { + it("cuts Playwright's call log", () => { + expect(safeErrorMessage(CALL_LOG_ERROR())).toBe("locator.click: Timeout 1000ms exceeded."); + }); + + it("keeps a message without a call log unchanged", () => { + expect(safeErrorMessage(new Error("boom\nsecond line"))).toBe("boom\nsecond line"); + }); + + it("stringifies a non-Error throwable", () => { + expect(safeErrorMessage("plain")).toBe("plain"); + expect(safeErrorMessage(42)).toBe("42"); + }); +}); + +describe("reportFatalError", () => { + const originalExitCode = process.exitCode; + + afterEach(() => { + process.exitCode = originalExitCode; + vi.restoreAllMocks(); + }); + + function spies() { + return { + error: vi.spyOn(logger, "error").mockImplementation(() => {}), + info: vi.spyOn(logger, "info").mockImplementation(() => {}), + debug: vi.spyOn(logger, "debug").mockImplementation(() => {}), + }; + } + + it("prints an expected error once, with no --verbose hint, stack at debug only", () => { + const s = spies(); + + reportFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("Run `revcli auth`."); + expect(s.info).not.toHaveBeenCalled(); + expect(s.debug).toHaveBeenCalledTimes(1); + expect(String(s.debug.mock.calls[0][0])).toContain("UnrecoverableError"); + expect(process.exitCode).toBe(1); + }); + + it("adds the --verbose hint for an unexpected error and never prints the stack at error level", () => { + const s = spies(); + + reportFatalError(CALL_LOG_ERROR()); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("locator.click: Timeout 1000ms exceeded."); + expect(s.info).toHaveBeenCalledWith("Run again with --verbose for details."); + expect(String(s.error.mock.calls[0][0])).not.toContain(" at "); + expect(String(s.debug.mock.calls[0][0])).not.toContain("example.com"); + expect(process.exitCode).toBe(1); + }); + + it("reports a non-Error throwable without a stack", () => { + const s = spies(); + + reportFatalError("plain string"); + + expect(s.error).toHaveBeenCalledWith("plain string"); + expect(s.debug).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/tests/retry.test.ts b/tests/retry.test.ts index c989f6f..d949e9b 100644 --- a/tests/retry.test.ts +++ b/tests/retry.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect, vi } from "vitest"; import { withRetry } from "../src/core/retry.js"; +import { UnrecoverableError } from "../src/core/errors.js"; +import { logger } from "../src/utils/logger.js"; describe("withRetry", () => { it("returns result on first success", async () => { @@ -57,6 +59,29 @@ describe("withRetry", () => { expect(fn).toHaveBeenCalledTimes(1); }); + it("does not retry a typed AUTH_REQUIRED error", async () => { + const fn = vi + .fn() + .mockRejectedValue(new UnrecoverableError("AUTH_REQUIRED", "limited view")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("limited view"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("does not log an UnrecoverableError at error level (the caller prints it once)", async () => { + const errorSpy = vi.spyOn(logger, "error"); + try { + const fn = vi.fn().mockRejectedValue(new UnrecoverableError("NOT_A_PLACE", "search page")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("search page"); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } + }); + it("wraps non-Error throwables", async () => { const fn = vi.fn().mockRejectedValue("string error"); await expect( diff --git a/tests/scrape-location.test.ts b/tests/scrape-location.test.ts index db3a1ae..888fb44 100644 --- a/tests/scrape-location.test.ts +++ b/tests/scrape-location.test.ts @@ -1,5 +1,11 @@ -import { describe, it, expect } from "vitest"; -import { assembleScrapeResult } from "../src/scraper/scrape-location.js"; +import { describe, it, expect, vi } from "vitest"; +import { + assembleScrapeResult, + navigateWithAuthFallback, + type AuthFallbackDeps, +} from "../src/scraper/scrape-location.js"; +import { authRequiredError, type SessionState } from "../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; import type { Business, Review } from "../src/core/schema.js"; function makeReview(id: string): Review { @@ -155,3 +161,70 @@ describe("assembleScrapeResult", () => { expect(reviews[0].id).toBe(originalFirstId); }); }); + +describe("navigateWithAuthFallback", () => { + const M1_START = "Google Maps is showing a limited view: this browser profile is not signed in"; + const M1B_START = "Google Maps is showing a limited view even though this browser profile appears to be signed in"; + + function deps(overrides: Partial> = {}) { + const navigate = vi.fn<() => Promise<{ name: string }>>(); + const waitForAuth = vi.fn<() => Promise>().mockResolvedValue(undefined); + const sessionProbe = vi.fn<() => Promise>().mockResolvedValue("expired"); + return { headless: true, navigate, waitForAuth, sessionProbe, ...overrides }; + } + + it("fails headless at once with the sign-in wording", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1_START)).toBe(true); + expect(d.waitForAuth).not.toHaveBeenCalled(); + expect(d.navigate).toHaveBeenCalledTimes(1); + }); + + it("headed: waits for sign-in and returns the second navigation's result", async () => { + const d = deps({ headless: false }); + d.navigate + .mockRejectedValueOnce(authRequiredError()) + .mockResolvedValueOnce({ name: "B" }); + + await expect(navigateWithAuthFallback(d)).resolves.toEqual({ name: "B" }); + expect(d.waitForAuth).toHaveBeenCalledTimes(1); + expect(d.sessionProbe).not.toHaveBeenCalled(); + }); + + it("headed: a limited view after sign-in on a signed-in profile gets the M1b wording", async () => { + const d = deps({ headless: false }); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockResolvedValue("signed-in"); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1B_START)).toBe(true); + expect(d.navigate).toHaveBeenCalledTimes(2); + }); + + it("falls back to the sign-in wording when the session probe fails", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockRejectedValue(new Error("page closed")); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect((err as Error).message.startsWith(M1_START)).toBe(true); + }); + + it("rethrows any other error unchanged without probing or prompting", async () => { + const d = deps({ headless: false }); + const boom = new Error("boom"); + d.navigate.mockRejectedValue(boom); + + await expect(navigateWithAuthFallback(d)).rejects.toBe(boom); + expect(d.sessionProbe).not.toHaveBeenCalled(); + expect(d.waitForAuth).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/selectors.test.ts b/tests/selectors.test.ts new file mode 100644 index 0000000..d6431e3 --- /dev/null +++ b/tests/selectors.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from "vitest"; +import { SELECTORS, TEXT_MARKERS } from "../src/scraper/selectors.js"; + +describe("SELECTORS", () => { + it("never uses Playwright's :has-text substring match", () => { + for (const value of Object.values(SELECTORS)) { + const all = Array.isArray(value) ? value : [value]; + for (const sel of all) expect(sel).not.toContain("has-text"); + } + }); + + it.each([ + ["accountButton", SELECTORS.accountButton, "SignOutOptions"], + ["signInLink", SELECTORS.signInLink, "ServiceLogin"], + ])("matches %s by its accounts.google.com href only", (_name, sel, path) => { + expect(sel).toBe(`a[href^="https://accounts.google.com/${path}"]`); + expect(sel).not.toContain("aria-label"); + }); +}); + +describe("TEXT_MARKERS", () => { + it("holds a lower-case limited-view phrase longer than 'limited view'", () => { + const marker = TEXT_MARKERS.limitedViewBanner; + expect(marker).toBe(marker.toLowerCase()); + expect(marker.length).toBeGreaterThan("limited view".length); + expect(marker).toContain("limited view"); + }); +}); diff --git a/tests/unrecoverable.test.ts b/tests/unrecoverable.test.ts index e468601..a63b8bd 100644 --- a/tests/unrecoverable.test.ts +++ b/tests/unrecoverable.test.ts @@ -1,6 +1,26 @@ import { describe, it, expect } from "vitest"; import { isUnrecoverable } from "../src/core/retry.js"; -import { UnrecoverableError } from "../src/core/errors.js"; +import { UnrecoverableError, hasUnrecoverableKind } from "../src/core/errors.js"; + +describe("hasUnrecoverableKind", () => { + it("is true for an UnrecoverableError of the given kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("AUTH_REQUIRED", "x"), "AUTH_REQUIRED"), + ).toBe(true); + }); + + it("is false for an UnrecoverableError of another kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("NOT_A_PLACE", "x"), "AUTH_REQUIRED"), + ).toBe(false); + }); + + it("is false for plain errors and non-errors", () => { + expect(hasUnrecoverableKind(new Error("AUTH_REQUIRED"), "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind("AUTH_REQUIRED", "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind(undefined, "AUTH_REQUIRED")).toBe(false); + }); +}); describe("isUnrecoverable", () => { it("detects 'invalid input'", () => { @@ -52,6 +72,11 @@ describe("isUnrecoverable", () => { expect(isUnrecoverable(new UnrecoverableError("SORT_VERIFY", ""))).toBe(true); }); + it("detects the AUTH_REQUIRED and NOT_A_PLACE kinds", () => { + expect(isUnrecoverable(new UnrecoverableError("AUTH_REQUIRED", "limited view"))).toBe(true); + expect(isUnrecoverable(new UnrecoverableError("NOT_A_PLACE", "search page"))).toBe(true); + }); + it("matches the exact navigation verification error template thrown by navigator.ts", () => { // Pin the exact message shape so retry.ts classifier and navigator.ts // thrower cannot silently drift apart. Mirrors navigator.ts:58-62 template. diff --git a/tests/url.test.ts b/tests/url.test.ts index 4b264fa..daf369c 100644 --- a/tests/url.test.ts +++ b/tests/url.test.ts @@ -5,8 +5,59 @@ import { extractPlaceIdFromUrl, placeIdsMatch, canVerifyPlaceIdFormat, + isSearchResultsUrl, + isShortLinkUrl, + SHORT_LINK_HOST, } from "../src/utils/url.js"; +describe("isShortLinkUrl", () => { + it("is true for a maps.app.goo.gl share link", () => { + expect(SHORT_LINK_HOST).toBe("maps.app.goo.gl"); + expect(isShortLinkUrl("https://maps.app.goo.gl/MTVGWdpd8vVqTouv9")).toBe(true); + expect(isShortLinkUrl("http://maps.app.goo.gl/abc?g_st=ic")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps?continue=https://maps.app.goo.gl/abc", + "https://maps.app.goo.gl.example.com/abc", + "https://evilmaps.app.goo.gl/abc", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isShortLinkUrl(url)).toBe(false); + }); + + it("is the same host that parseGoogleMapsInput treats as a short URL", () => { + expect(parseGoogleMapsInput(`https://${SHORT_LINK_HOST}/abc123`).isShortUrl).toBe(true); + expect(() => parseGoogleMapsInput("https://mapsXappXgooXgl/abc123")).toThrow(/Invalid input/); + }); +}); + +describe("isSearchResultsUrl", () => { + it("is true for a /maps/search/ page, tracking params included", () => { + expect( + isSearchResultsUrl( + "https://www.google.com/maps/search/coffee+near+me/@52.23,21.01,14z?entry=ttu&g_ep=EgoyMDI2", + ), + ).toBe(true); + expect(isSearchResultsUrl("https://www.google.pl/maps/search/foo/@1,2,3z?hl=en")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Optimo+Nakheel/@24.74,46.64,867m/data=!1s0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps?cid=1234567890", + "https://www.google.com/maps?ftid=0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps/place/?q=place_id:ChIJN1t_tDeuEmsRUsoyG83frY4", + "https://www.google.com/maps/place/Caf%C3%A9+S%C5%82odki/@52.2,21.0,17z", + "https://www.google.com/maps/searchable-place/", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isSearchResultsUrl(url)).toBe(false); + }); +}); + describe("parseGoogleMapsInput", () => { it("parses a long Google Maps URL", () => { const url = From 5bc686524093bb39f7f6b4a807adfb457c9a92eb Mon Sep 17 00:00:00 2001 From: Marcin Obel Date: Wed, 18 Nov 2026 15:48:32 +0100 Subject: [PATCH 2/3] chore: ignore macOS .DS_Store files Claude-Session: https://claude.ai/code/session_01PuLVjZfdZVDn9e5QnCEtCH --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index c778c87..3b5ccec 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ dist/ /output/ *.log coverage/ +.DS_Store # Local scratch. Never committed. .local/ From c7eb9c592ae2c0c3b139925b643da08e7b81c2cc Mon Sep 17 00:00:00 2001 From: Marcin Obel <7283716+marcinobel@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:07:51 +0100 Subject: [PATCH 3/3] fix(batch): stop timed-out places, handle SIGTERM, keep collection fast (#34) Issue #33: `revcli batch` could not finish long lists unattended. - A location timeout now really stops the scrape: runWithTimeout() aborts a signal that withRetry and scrapeLocation honour, closes the browser, and waits until it is closed before the next place starts. A late result is never saved. If a stopped browser does not close within 15 s, the batch stops with exit 1 (resume with --resume). - revcli owns SIGHUP/SIGINT/SIGTERM: Playwright's own handlers (whose SIGTERM handler closed browsers without exiting) are turned off; a signal aborts running work, closes every browser and exits 129/130/143. - Collected review cards are marked with their review id and skipped, so a collect cycle reads only new cards (last/first 10 cycles at 2,000 reviews: 970/177 ms before, ~140/85 ms after). A reused card is read again. - Output and state files are written atomically (temp file + rename). Also includes `revcli scrape --time-limit `: stop collecting after the given time and save the reviews collected so far, with a warning. Closes #33 --- AGENTS.md | 17 +- CHANGELOG.md | 7 + README.md | 3 +- src/commands/batch.ts | 140 +++++++++++++---- src/commands/scrape.ts | 11 +- src/core/errors.ts | 9 +- src/core/retry.ts | 27 +++- src/core/shutdown.ts | 95 ++++++++++++ src/core/timeout.ts | 81 ++++++++++ src/index.ts | 10 ++ src/output/atomic.ts | 22 +++ src/output/csv.ts | 4 +- src/output/json.ts | 4 +- src/scraper/browser.ts | 179 ++++++++++++++++----- src/scraper/extractor.ts | 56 ++++++- src/scraper/scrape-location.ts | 62 ++++---- src/scraper/scroller.ts | 146 +++++++++++++----- tests/atomic.test.ts | 39 +++++ tests/batch-run.test.ts | 206 +++++++++++++++++++++++++ tests/browser-session.test.ts | 111 +++++++++++++ tests/browser/abort.test.ts | 79 ++++++++++ tests/browser/collected-mark.test.ts | 109 +++++++++++++ tests/browser/fixtures/signal-child.ts | 57 +++++++ tests/browser/scroll.test.ts | 49 +++++- tests/browser/shutdown.test.ts | 120 ++++++++++++++ tests/retry.test.ts | 51 ++++++ tests/shutdown.test.ts | 161 +++++++++++++++++++ tests/timeout.test.ts | 119 ++++++++++++++ 28 files changed, 1817 insertions(+), 157 deletions(-) create mode 100644 src/core/shutdown.ts create mode 100644 src/core/timeout.ts create mode 100644 src/output/atomic.ts create mode 100644 tests/atomic.test.ts create mode 100644 tests/batch-run.test.ts create mode 100644 tests/browser-session.test.ts create mode 100644 tests/browser/abort.test.ts create mode 100644 tests/browser/collected-mark.test.ts create mode 100644 tests/browser/fixtures/signal-child.ts create mode 100644 tests/browser/shutdown.test.ts create mode 100644 tests/shutdown.test.ts create mode 100644 tests/timeout.test.ts 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); + }); + }); +});