dojinvoice_db.crawler

Crawl orchestration: discover works, then fill them in as cheaply as possible.

A run has three stages, each of which can be skipped or resumed independently:

  1. Discover — walk the search listing newest-first. Because the listing is ordered by release date, an incremental run only needs to read until it has seen stop_after_known_pages consecutive pages containing nothing new; everything older is already stored. --full disables that early stop.
  2. Summarize — one batched ajax request per 100 new IDs writes the work row and its price/sales/rating figures.
  3. Detail — one request per work whose detail_fetched_at is NULL (or stale). Interrupting a run leaves the remaining works marked pending, so the next run picks up exactly where this one stopped instead of refetching.

The stage functions all take a CrawlSession, which carries the database, the client, the options and the counters they update.

  1"""Crawl orchestration: discover works, then fill them in as cheaply as possible.
  2
  3A run has three stages, each of which can be skipped or resumed independently:
  4
  51. **Discover** — walk the search listing newest-first. Because the listing is
  6   ordered by release date, an incremental run only needs to read until it has
  7   seen ``stop_after_known_pages`` consecutive pages containing nothing new;
  8   everything older is already stored. ``--full`` disables that early stop.
  92. **Summarize** — one batched ajax request per 100 new IDs writes the work
 10   row and its price/sales/rating figures.
 113. **Detail** — one request per work whose ``detail_fetched_at`` is NULL (or
 12   stale). Interrupting a run leaves the remaining works marked pending, so
 13   the next run picks up exactly where this one stopped instead of refetching.
 14
 15The stage functions all take a :class:`CrawlSession`, which carries the
 16database, the client, the options and the counters they update.
 17"""
 18
 19from __future__ import annotations
 20
 21import asyncio
 22import logging
 23from collections.abc import Callable
 24from dataclasses import dataclass, field
 25from datetime import datetime, timedelta
 26from typing import TYPE_CHECKING
 27
 28from .dlsite import WorkNotFoundError, batched, work_from_info
 29from .models import CrawlOptions, CrawlResult, WorkStats
 30
 31if TYPE_CHECKING:
 32    from collections.abc import Sequence
 33
 34    from .db import WorkDatabase
 35    from .dlsite import DlsiteClient
 36
 37LOGGER = logging.getLogger(__name__)
 38
 39ProgressFn = Callable[[str], None]
 40
 41
 42def _noop(_: str) -> None:
 43    pass
 44
 45
 46def _now() -> datetime:
 47    return datetime.now().astimezone()
 48
 49
 50@dataclass
 51class CrawlSession:
 52    """Everything a crawl stage needs: where to read from, write to and report."""
 53
 54    db: WorkDatabase
 55    client: DlsiteClient
 56    options: CrawlOptions = field(default_factory=CrawlOptions)
 57    result: CrawlResult = field(default_factory=CrawlResult)
 58    progress: ProgressFn = _noop
 59
 60
 61async def discover_ids(session: CrawlSession) -> list[str]:
 62    """Walk the search listing and return product IDs not yet in the database."""
 63    options = session.options
 64    known = session.db.known_product_ids()
 65    new_ids: list[str] = []
 66    picked: set[str] = set()
 67    consecutive_known = 0
 68    page = 1
 69    while options.max_pages is None or page <= options.max_pages:
 70        ids = await session.client.fetch_listing_ids(options.query, page)
 71        session.result.pages_fetched += 1
 72        if not ids:
 73            session.progress(f"page {page}: empty, listing exhausted")
 74            break
 75        session.result.ids_seen += len(ids)
 76        fresh = [pid for pid in ids if pid not in known and pid not in picked]
 77        picked.update(fresh)
 78        new_ids.extend(fresh)
 79        session.progress(f"page {page}: {len(ids)} works, {len(fresh)} new (total new: {len(new_ids)})")
 80        consecutive_known = 0 if fresh else consecutive_known + 1
 81        if not options.full and consecutive_known >= options.stop_after_known_pages:
 82            session.progress(f"stopping: {consecutive_known} consecutive pages with nothing new")
 83            break
 84        if options.limit is not None and len(new_ids) >= options.limit:
 85            break
 86        page += 1
 87    if options.limit is not None:
 88        del new_ids[options.limit :]
 89    return new_ids
 90
 91
 92async def store_summaries(session: CrawlSession, product_ids: Sequence[str]) -> None:
 93    """Fetch and store ajax info for ``product_ids``, 100 works per request."""
 94    done = 0
 95    for chunk in batched(product_ids, session.options.info_batch):
 96        info = await session.client.fetch_product_info(chunk)
 97        now = _now()
 98        for product_id in chunk:
 99            entry = info.get(product_id)
100            if entry is None:
101                session.db.record_error(product_id, "not returned by product info ajax", now=now)
102                session.result.errors += 1
103                continue
104            session.db.upsert_work(work_from_info(product_id, entry), detail=False, now=now)
105            session.db.upsert_stats(WorkStats.from_info(product_id, entry), now=now)
106            session.result.summaries_written += 1
107        done += len(chunk)
108        session.progress(f"summaries: {done}/{len(product_ids)}")
109
110
111async def fetch_details(session: CrawlSession, product_ids: Sequence[str]) -> None:
112    """Fetch the work page of each ID and store the detail-only fields.
113
114    Runs ``options.concurrency`` fetches at a time; database writes happen on
115    the event loop thread, so each work is committed as soon as it arrives and
116    an interrupted run keeps everything fetched so far.
117    """
118    if not product_ids:
119        return
120    queue: asyncio.Queue[str] = asyncio.Queue()
121    for product_id in product_ids:
122        queue.put_nowait(product_id)
123    total = len(product_ids)
124    handled = 0
125
126    async def worker() -> None:
127        nonlocal handled
128        while True:
129            try:
130                product_id = queue.get_nowait()
131            except asyncio.QueueEmpty:
132                return
133            work = session.db.load_work(product_id)
134            if work is None:  # pragma: no cover - only if the row vanished mid-run
135                continue
136            try:
137                detailed = await session.client.fetch_detail(work)
138            except WorkNotFoundError as e:
139                session.db.record_error(product_id, str(e))
140                session.result.errors += 1
141            except Exception as e:  # noqa: BLE001 - one bad work must not abort the run
142                LOGGER.warning("failed to fetch %s: %s", product_id, e)
143                session.db.record_error(product_id, f"{type(e).__name__}: {e}")
144                session.result.errors += 1
145            else:
146                session.db.upsert_work(detailed, detail=True, now=_now())
147                session.db.clear_error(product_id)
148                session.result.details_fetched += 1
149            handled += 1
150            session.progress(f"details: {handled}/{total} ({product_id})")
151
152    await asyncio.gather(*(worker() for _ in range(max(session.options.concurrency, 1))))
153
154
155def pending_detail_ids(session: CrawlSession) -> list[str]:
156    """Return the works whose detail page this session should fetch."""
157    options = session.options
158    stale_before = None
159    if options.detail_stale_days is not None:
160        stale_before = _now() - timedelta(days=options.detail_stale_days)
161    return session.db.pending_detail_ids(
162        limit=options.limit,
163        stale_before=stale_before,
164        retry_errors=options.retry_errors,
165    )
166
167
168async def crawl(session: CrawlSession) -> CrawlResult:
169    """Run a full discover -> summarize -> detail pass."""
170    new_ids = await discover_ids(session)
171    session.result.new_ids = len(new_ids)
172    if new_ids:
173        await store_summaries(session, new_ids)
174    if not session.options.skip_details:
175        pending = pending_detail_ids(session)
176        session.progress(f"details pending: {len(pending)}")
177        await fetch_details(session, pending)
178    session.db.set_state("last_crawl_at", _now().isoformat(sep=" ", timespec="seconds"))
179    session.db.set_state("last_query", session.options.query.describe())
180    return session.result
181
182
183async def refresh_stats(session: CrawlSession, product_ids: Sequence[str]) -> tuple[int, int]:
184    """Re-fetch price/sales/rating figures for ``product_ids``.
185
186    The batched ajax endpoint also returns the cheap metadata columns, so the
187    work rows are refreshed at no extra cost -- useful for announced works
188    whose title or release date changes before release.
189
190    Returns:
191        ``(updated, missing)`` counts.
192    """
193    updated = 0
194    missing = 0
195    for chunk in batched(product_ids, session.options.info_batch):
196        info = await session.client.fetch_product_info(chunk)
197        now = _now()
198        for product_id in chunk:
199            entry = info.get(product_id)
200            if entry is None:
201                missing += 1
202                continue
203            session.db.upsert_work(work_from_info(product_id, entry), detail=False, now=now)
204            session.db.upsert_stats(WorkStats.from_info(product_id, entry), now=now)
205            updated += 1
206        session.progress(f"stats: {updated + missing}/{len(product_ids)}")
207    return updated, missing
LOGGER = <Logger dojinvoice_db.crawler (WARNING)>
ProgressFn = collections.abc.Callable[[str], None]
@dataclass
class CrawlSession:
51@dataclass
52class CrawlSession:
53    """Everything a crawl stage needs: where to read from, write to and report."""
54
55    db: WorkDatabase
56    client: DlsiteClient
57    options: CrawlOptions = field(default_factory=CrawlOptions)
58    result: CrawlResult = field(default_factory=CrawlResult)
59    progress: ProgressFn = _noop

Everything a crawl stage needs: where to read from, write to and report.

CrawlSession( db: dojinvoice_db.db.WorkDatabase, client: dojinvoice_db.dlsite.DlsiteClient, options: dojinvoice_db.models.CrawlOptions = <factory>, result: dojinvoice_db.models.CrawlResult = <factory>, progress: Callable[[str], None] = <function _noop>)
def progress(_: str) -> None:
43def _noop(_: str) -> None:
44    pass

The type of the None singleton.

async def discover_ids(session: CrawlSession) -> list[str]:
62async def discover_ids(session: CrawlSession) -> list[str]:
63    """Walk the search listing and return product IDs not yet in the database."""
64    options = session.options
65    known = session.db.known_product_ids()
66    new_ids: list[str] = []
67    picked: set[str] = set()
68    consecutive_known = 0
69    page = 1
70    while options.max_pages is None or page <= options.max_pages:
71        ids = await session.client.fetch_listing_ids(options.query, page)
72        session.result.pages_fetched += 1
73        if not ids:
74            session.progress(f"page {page}: empty, listing exhausted")
75            break
76        session.result.ids_seen += len(ids)
77        fresh = [pid for pid in ids if pid not in known and pid not in picked]
78        picked.update(fresh)
79        new_ids.extend(fresh)
80        session.progress(f"page {page}: {len(ids)} works, {len(fresh)} new (total new: {len(new_ids)})")
81        consecutive_known = 0 if fresh else consecutive_known + 1
82        if not options.full and consecutive_known >= options.stop_after_known_pages:
83            session.progress(f"stopping: {consecutive_known} consecutive pages with nothing new")
84            break
85        if options.limit is not None and len(new_ids) >= options.limit:
86            break
87        page += 1
88    if options.limit is not None:
89        del new_ids[options.limit :]
90    return new_ids

Walk the search listing and return product IDs not yet in the database.

async def store_summaries( session: CrawlSession, product_ids: Sequence[str]) -> None:
 93async def store_summaries(session: CrawlSession, product_ids: Sequence[str]) -> None:
 94    """Fetch and store ajax info for ``product_ids``, 100 works per request."""
 95    done = 0
 96    for chunk in batched(product_ids, session.options.info_batch):
 97        info = await session.client.fetch_product_info(chunk)
 98        now = _now()
 99        for product_id in chunk:
100            entry = info.get(product_id)
101            if entry is None:
102                session.db.record_error(product_id, "not returned by product info ajax", now=now)
103                session.result.errors += 1
104                continue
105            session.db.upsert_work(work_from_info(product_id, entry), detail=False, now=now)
106            session.db.upsert_stats(WorkStats.from_info(product_id, entry), now=now)
107            session.result.summaries_written += 1
108        done += len(chunk)
109        session.progress(f"summaries: {done}/{len(product_ids)}")

Fetch and store ajax info for product_ids, 100 works per request.

async def fetch_details( session: CrawlSession, product_ids: Sequence[str]) -> None:
112async def fetch_details(session: CrawlSession, product_ids: Sequence[str]) -> None:
113    """Fetch the work page of each ID and store the detail-only fields.
114
115    Runs ``options.concurrency`` fetches at a time; database writes happen on
116    the event loop thread, so each work is committed as soon as it arrives and
117    an interrupted run keeps everything fetched so far.
118    """
119    if not product_ids:
120        return
121    queue: asyncio.Queue[str] = asyncio.Queue()
122    for product_id in product_ids:
123        queue.put_nowait(product_id)
124    total = len(product_ids)
125    handled = 0
126
127    async def worker() -> None:
128        nonlocal handled
129        while True:
130            try:
131                product_id = queue.get_nowait()
132            except asyncio.QueueEmpty:
133                return
134            work = session.db.load_work(product_id)
135            if work is None:  # pragma: no cover - only if the row vanished mid-run
136                continue
137            try:
138                detailed = await session.client.fetch_detail(work)
139            except WorkNotFoundError as e:
140                session.db.record_error(product_id, str(e))
141                session.result.errors += 1
142            except Exception as e:  # noqa: BLE001 - one bad work must not abort the run
143                LOGGER.warning("failed to fetch %s: %s", product_id, e)
144                session.db.record_error(product_id, f"{type(e).__name__}: {e}")
145                session.result.errors += 1
146            else:
147                session.db.upsert_work(detailed, detail=True, now=_now())
148                session.db.clear_error(product_id)
149                session.result.details_fetched += 1
150            handled += 1
151            session.progress(f"details: {handled}/{total} ({product_id})")
152
153    await asyncio.gather(*(worker() for _ in range(max(session.options.concurrency, 1))))

Fetch the work page of each ID and store the detail-only fields.

Runs options.concurrency fetches at a time; database writes happen on the event loop thread, so each work is committed as soon as it arrives and an interrupted run keeps everything fetched so far.

def pending_detail_ids(session: CrawlSession) -> list[str]:
156def pending_detail_ids(session: CrawlSession) -> list[str]:
157    """Return the works whose detail page this session should fetch."""
158    options = session.options
159    stale_before = None
160    if options.detail_stale_days is not None:
161        stale_before = _now() - timedelta(days=options.detail_stale_days)
162    return session.db.pending_detail_ids(
163        limit=options.limit,
164        stale_before=stale_before,
165        retry_errors=options.retry_errors,
166    )

Return the works whose detail page this session should fetch.

async def crawl( session: CrawlSession) -> dojinvoice_db.models.CrawlResult:
169async def crawl(session: CrawlSession) -> CrawlResult:
170    """Run a full discover -> summarize -> detail pass."""
171    new_ids = await discover_ids(session)
172    session.result.new_ids = len(new_ids)
173    if new_ids:
174        await store_summaries(session, new_ids)
175    if not session.options.skip_details:
176        pending = pending_detail_ids(session)
177        session.progress(f"details pending: {len(pending)}")
178        await fetch_details(session, pending)
179    session.db.set_state("last_crawl_at", _now().isoformat(sep=" ", timespec="seconds"))
180    session.db.set_state("last_query", session.options.query.describe())
181    return session.result

Run a full discover -> summarize -> detail pass.

async def refresh_stats( session: CrawlSession, product_ids: Sequence[str]) -> tuple[int, int]:
184async def refresh_stats(session: CrawlSession, product_ids: Sequence[str]) -> tuple[int, int]:
185    """Re-fetch price/sales/rating figures for ``product_ids``.
186
187    The batched ajax endpoint also returns the cheap metadata columns, so the
188    work rows are refreshed at no extra cost -- useful for announced works
189    whose title or release date changes before release.
190
191    Returns:
192        ``(updated, missing)`` counts.
193    """
194    updated = 0
195    missing = 0
196    for chunk in batched(product_ids, session.options.info_batch):
197        info = await session.client.fetch_product_info(chunk)
198        now = _now()
199        for product_id in chunk:
200            entry = info.get(product_id)
201            if entry is None:
202                missing += 1
203                continue
204            session.db.upsert_work(work_from_info(product_id, entry), detail=False, now=now)
205            session.db.upsert_stats(WorkStats.from_info(product_id, entry), now=now)
206            updated += 1
207        session.progress(f"stats: {updated + missing}/{len(product_ids)}")
208    return updated, missing

Re-fetch price/sales/rating figures for product_ids.

The batched ajax endpoint also returns the cheap metadata columns, so the work rows are refreshed at no extra cost -- useful for announced works whose title or release date changes before release.

Returns:

(updated, missing) counts.