143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471 | class VerseDBOnlineSource(OnlineSource):
"""Wraps the `versedb` SDK adapter for VerseDB's API."""
name: ClassVar[str] = "versedb"
metadata_source: ClassVar[MetadataSources] = MetadataSources.VERSEDB_API
metadata_format: ClassVar[MetadataFormats] = MetadataFormats.VERSEDB_API
#: Test seam: an `httpx.MockTransport` every new client sends through.
http_transport: ClassVar[Any] = None
# How many series one search asks for, all of which can go into the one
# issue-list call.
_MAX_SERIES_PER_SEARCH: ClassVar[int] = 20
# Exact matches rank first in VerseDB's issue list (seen 2026-11-21), so
# a next page is fetched only while a page still ends in one, and never
# past this many.
_MAX_ISSUE_PAGES: ClassVar[int] = 3
# A series that began more than this many years after the comic can't
# hold it; it would be a reprint run carrying the original's date. The
# slop matches the matcher's one-year tolerance.
_SERIES_START_YEAR_SLOP: ClassVar[int] = 1
@override
def is_configured(self) -> bool:
"""VerseDB requires a personal access token."""
return bool(self._credentials.key)
@override
@staticmethod
def classify_retry_exception(exc: BaseException) -> RetryCategory | None:
"""
Classify the adapter's exceptions, and httpx's transport failures.
Every `VerseDBError` subclass is claimed here: an unclaimed vendor
exception would be silently retried on the generic schedule.
"""
import httpx
categories: tuple[tuple[type[BaseException], RetryCategory], ...] = (
(VerseDBQuotaError, RetryCategory.QUOTA),
(VerseDBRateLimitError, RetryCategory.RATE_LIMIT),
(VerseDBAuthError, RetryCategory.AUTH),
(VerseDBNotFoundError, RetryCategory.NOT_FOUND),
(VerseDBServerError, RetryCategory.TRANSIENT),
# An unexpected status or an unparsable response: the same
# request can only fail the same way.
(VerseDBResponseError, RetryCategory.INVALID),
# A typo in auth.versedb.url: no retry can fix it. Both before
# TransportError, which UnsupportedProtocol subclasses.
(httpx.UnsupportedProtocol, RetryCategory.INVALID),
(httpx.InvalidURL, RetryCategory.INVALID),
(httpx.TimeoutException, RetryCategory.TRANSIENT),
(httpx.TransportError, RetryCategory.TRANSIENT),
)
for exc_class, category in categories:
if isinstance(exc, exc_class):
return category
return None
# -- the shared client --------------------------------------------------
def _get_client(self) -> VerseDBClient:
if self._client is None or self._client.closed:
self._client = self._get_or_build_shared_client()
return self._client
def _client_signature(self) -> tuple:
cache = self._settings.cache
return (cache.mode, cache.dir, cache.ttl)
def _get_or_build_shared_client(self) -> VerseDBClient:
key = (self._credentials.key or "", self._credentials.url or "")
signature = self._client_signature()
with _client_cache_lock:
entry = _client_cache.get(key)
if entry is None or entry[0].closed:
client = self._build_client()
_client_cache[key] = (client, signature)
return client
client, built_signature = entry
if built_signature != signature:
warn_once(
f"{self.name}:session-config-mismatch",
f"online {self.name}: reusing the existing shared client; this "
f"instance's differing cache settings {signature} are ignored "
f"in favor of the client's {built_signature}",
)
return client
def _build_client(self, *, cached: bool = True) -> VerseDBClient:
cache = None
if cached and (resolved := self._resolve_response_cache()) is not None:
path, ttl = resolved
cache = open_response_cache(path, ttl)
return VerseDBClient(
self._credentials.key or "",
user_agent=user_agent(),
base_url=self._credentials.url,
cache=cache,
transport=self.http_transport,
)
@override
def probe(self) -> Mapping[str, Mapping[str, Any]] | None:
"""Verify the token with one uncached one-row series request."""
client = self._build_client(cached=False)
try:
self._record_api_call("probe")
return client.probe()
finally:
client.close()
# -- fetch and search ---------------------------------------------------
@override
@with_retry()
def get(self, issue_id: int) -> dict[str, Any]:
"""
Fetch one issue's full detail.
One request: the detail already nests the series, publisher, credits
and the rest, so nothing needs a second call.
"""
self._record_api_call("get_issue")
payload = self._get_client().issue(issue_id)
data = payload.get("data")
if not isinstance(data, dict):
reason = f"VerseDB issue {issue_id}: the response carries no data"
raise VerseDBResponseError(reason)
return data
@override
def search(self, profile: ComicProfile) -> list[Candidate]:
"""
Search VerseDB for candidate issues matching the profile.
1. ``--series-id versedb:<id>`` skips discovery.
2. One series search by name.
3. Drop a series that began after the comic, or whose name (and
other names) is too far from the comic's series.
4. One issue list across all the kept series, filtered client-side
to the comic's exact number.
While VerseDB refuses requests for longer than any retry waits (its
daily cap), nothing is sent: the comic is reported skipped, so it is
tried again on a later run, and the run's other sources carry on.
"""
self.reset_search_skip_reason()
try:
return self._search(profile)
except VerseDBQuotaError:
self._note_search_skipped(SKIP_QUOTA_RESERVED)
return []
def _search(self, profile: ComicProfile) -> list[Candidate]:
number = strip_issue_leading_zeros(profile.issue)
explicit_sid = self._settings.lookup.series_ids.get(self.name)
if explicit_sid is not None:
return self._issues_in_series({int(explicit_sid): ()}, number)
if not profile.series:
logger.debug(
f"online {self.name}: no series in profile; cannot search "
"(use --id versedb:<id>, or --series-id versedb:<id>)"
)
return []
rows = self._search_series_with_retry(profile.series)
self._log_discovery_sample(
rows,
lambda row: (
f"{row.get('display_name') or row.get('name')} ({row.get('id')})"
),
noun="series",
query=f"series={profile.series!r}",
)
kept = self._kept_series(rows, profile)
if not kept:
logger.info(
f"online {self.name}: no series match series {profile.series!r}"
)
return []
return self._issues_in_series(kept, number)
@override
def _lookup_issue_in_volume(
self, volume_id: int, issue_number: str | None
) -> Candidate | None:
"""
Take the series-cache fast path: one issue list in one series.
Returns None without a request when there is no issue number: the
whole series would come back and its first row would win.
"""
number = strip_issue_leading_zeros(issue_number)
if not number:
return None
try:
candidates = self._issues_in_series({int(volume_id): ()}, number)
except VerseDBQuotaError:
# Quietly: the search this falls back to reports the skip.
return None
# First-result-wins on variant collisions, as for the other sources.
return candidates[0] if candidates else None
def _series_postdates_comic(self, start_year: Any, year: int | None) -> bool:
if start_year is None or year is None:
return False
return int(start_year) > year + self._SERIES_START_YEAR_SLOP
def _kept_series(
self, rows: Sequence[Mapping[str, Any]], profile: ComicProfile
) -> dict[int, tuple[str, ...]]:
"""Each surviving series id, with the other names its row carried."""
kept: dict[int, tuple[str, ...]] = {}
for row in rows:
if (series_id := row.get("id")) is None:
continue
name = row.get("name")
if self._series_postdates_comic(row.get("start_year"), profile.year):
logger.debug(
f"online {self.name}: skipping series {series_id} ({name!r}, "
f"start_year={row.get('start_year')}); comic year="
f"{profile.year} predates it."
)
continue
alt_names = _alt_names(row)
if not should_keep_volume_name(
profile.series, name, _NAME_THRESHOLD, alt_names=alt_names
):
logger.debug(
f"online {self.name}: skipping series {series_id} ({name!r}); "
f"name dissimilar to profile.series={profile.series!r}."
)
continue
kept[int(series_id)] = alt_names
return kept
def _issues_in_series(
self, alt_names_by_id: Mapping[int, tuple[str, ...]], number: str | None
) -> list[Candidate]:
"""Candidates for ``number`` across these series, in as few calls as can be."""
series_ids = tuple(alt_names_by_id)
candidates: list[Candidate] = []
for page in range(1, self._MAX_ISSUE_PAGES + 1):
payload = self._list_issues_with_retry(series_ids, number, page)
rows = payload.get("data") or []
candidates.extend(
self._to_candidate(row, alt_names_by_id.get(row.get("series_id"), ()))
for row in rows
if row.get("id") is not None and _number_matches(row, number)
)
if not self._next_page_may_match(payload, rows, number, page):
break
return candidates
@staticmethod
def _next_page_may_match(
payload: Mapping[str, Any],
rows: Sequence[Mapping[str, Any]],
number: str | None,
page: int,
) -> bool:
"""
Whether another page could still hold exact matches.
Exact matches rank first, so a page that ends in a non-match means
the rest are non-matches too. Without a number every row matches,
and one page is all a numberless comic gets.
"""
last_page = (payload.get("meta") or {}).get("last_page") or 1
return bool(
number is not None
and rows
and page < last_page
and _number_matches(rows[-1], number)
)
@with_retry()
def _search_series_with_retry(self, name: str) -> list[dict[str, Any]]:
self._record_api_call("search_series")
payload = self._get_client().search_series(name, self._MAX_SERIES_PER_SEARCH)
return payload.get("data") or []
@with_retry()
def _list_issues_with_retry(
self, series_ids: Sequence[int], number: str | None, page: int
) -> dict[str, Any]:
self._record_api_call("list_issues")
return self._get_client().list_issues(series_ids, number, page=page)
def _to_candidate(
self, row: Mapping[str, Any], alt_series: tuple[str, ...]
) -> Candidate:
"""
Map an issue-list row, with its included series, to a Candidate.
``publisher`` stays None as for the other sources: `s_publisher`
scores it, and filling it would move scores no calibration has
measured. The series' publisher is shown as display detail instead.
"""
series = row.get("series") or {}
images = row.get("images") or {}
publisher = _display_text(series.get("publisher_name"))
summary = CandidateSummary(
series=series.get("name") or "",
issue=str(row.get("issue_number") or ""),
year=parse_year(row.get("cover_date") or row.get("release_date")),
publisher=None,
page_count=None,
cover_url=images.get("thumb")
or images.get("cover_sm")
or row.get("cover_url"),
variant_label=None,
alt_series=alt_series,
volume=series.get("volume_number"),
cover_url_full=images.get("cover_lg"),
series_start_year=series.get("start_year"),
series_publisher=publisher,
series_issue_count=series.get("cached_issues_count") or None,
series_type=original_format(series),
issue_title=_display_text(row.get("name")),
)
return Candidate(
source=self.name,
issue_id=int(row["id"]),
summary=summary,
url=issue_url(row.get("id"), row.get("slug")) or "",
precomputed_cover_hash=None,
volume_id=row.get("series_id"),
)
|