mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 21:29:59 -05:00
Zim estimates and searches run in a libzim worker process so a cold Zim cannot stall the API worker (#928)
* Zim search estimates run in a separate process so a cold estimate cannot stall the API worker The global search estimates every auto-search Zim on each keystroke. On a large library that estimate took tens of seconds when the Zims' pages were not cached, and every other request routed to the same Sanic worker, such as the channel suggestions, waited behind it. Two things held the worker: opening a large Zim cold takes seconds (ten for a 75 GB Zim) and `Zims.get_all` did that on the event loop; and python-libzim never releases the GIL, so the estimate offloaded with asyncio.to_thread still froze the worker. Everything libzim does for an estimate now runs in a standalone script started as a subprocess (Sanic workers are daemonic, so a multiprocessing pool cannot be forked from them). It reads the Zim paths and search string on stdin and writes the counts on stdout. A Zim it cannot read is reported and left out, as `Zims.get_all` would leave it out. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Zim searches run in the libzim worker process too The /api/zim/search endpoints had the same stall as the estimate: they opened every Zim through Zims.get_all and searched them with libzim, which holds the GIL, so a thread offload still froze the Sanic worker. The estimate script is now a general libzim worker with estimate, search and entries jobs. A search of all Zims sends every Zim's job to one worker process; the API worker only headlines the returned HTML and looks up tags. The worker also returns each Zim's metadata so Zim.__json__ does not open the Zim again on the event loop. Zim.entries_with_tags is split so the tagged paths come from the database without opening the Zim. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Tagged Zim estimates count from the database, and a cancelled request kills the libzim worker Review of the earlier commits found two gaps. Estimates with tags selected still went through Zims.entries_with_tags, which opened every Zim in the API process, and after the thread offload was removed it did so on the event loop; they now count the tagged paths in SQL and ask the worker only for metadata. And Sanic cancels a handler at its response timeout or on disconnect, which left the worker process running until its stdout pipe filled; the runner now kills and reaps it on cancellation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
9c258b41ee
commit
bfe7b8afbd
6 changed files with 376 additions and 154 deletions
|
|
@ -5,7 +5,7 @@ from collections import OrderedDict
|
|||
from datetime import datetime
|
||||
from typing import List, Tuple, OrderedDict as OrderedDictType, Dict, Optional
|
||||
|
||||
from libzim import Archive, Searcher, Query, Entry, SuggestionSearcher
|
||||
from libzim import Archive, Entry
|
||||
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, Text, tuple_, Boolean, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, relationship, Session, joinedload
|
||||
from sqlalchemy.orm.exc import NoResultFound # noqa
|
||||
|
|
@ -165,39 +165,6 @@ class Zim(Base, ModelHelper):
|
|||
)
|
||||
return metadata
|
||||
|
||||
def get_searcher(self) -> Searcher:
|
||||
searcher = Searcher(self.get_zim())
|
||||
return searcher
|
||||
|
||||
def get_search(self, search_str: str):
|
||||
query = Query().set_query(search_str)
|
||||
searcher = self.get_searcher()
|
||||
search = searcher.search(query)
|
||||
return search
|
||||
|
||||
def get_suggestion_searcher(self) -> SuggestionSearcher:
|
||||
searcher = SuggestionSearcher(self.get_zim())
|
||||
return searcher
|
||||
|
||||
def estimate(self, search_str: str) -> int:
|
||||
"""Count the number of Entry(s) that contain the `search_str`."""
|
||||
search = self.get_search(search_str)
|
||||
count = search.getEstimatedMatches()
|
||||
return count
|
||||
|
||||
def search(self, search_str: str, offset: int = 0, limit: int = 10) -> List[str]:
|
||||
"""Return the paths of the Entry(s) that contain the `search_str`."""
|
||||
search = self.get_search(search_str)
|
||||
results = list(search.getResults(offset, limit))
|
||||
return results
|
||||
|
||||
def suggest(self, search_str: str, offset: int = 0, limit: int = 10) -> List[str]:
|
||||
"""Return the paths of the Entry(s) that contain the `search_str`. Also searches the titles."""
|
||||
searcher = self.get_suggestion_searcher()
|
||||
suggestions = searcher.suggest(search_str)
|
||||
results = list(suggestions.getResults(offset, limit))
|
||||
return results
|
||||
|
||||
def get_entry(self, path: str) -> Optional[Entry]:
|
||||
"""Search this Zim file for the provided Entry at the `path`."""
|
||||
zim = self.get_zim()
|
||||
|
|
@ -256,22 +223,21 @@ class Zim(Base, ModelHelper):
|
|||
.order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) \
|
||||
.offset(offset).limit(limit)
|
||||
|
||||
entries = list()
|
||||
for tag_zim_entry, zim in tag_zim_entries:
|
||||
entry = zim.find_entry(tag_zim_entry.zim_entry)
|
||||
entries.append(entry)
|
||||
return [(zim, tag_zim_entry.zim_entry) for tag_zim_entry, zim in tag_zim_entries]
|
||||
|
||||
return entries
|
||||
|
||||
def entries_with_tags(self, session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) -> List[
|
||||
Entry]:
|
||||
"""Return Zim Entries tagged with the provided names."""
|
||||
def entry_paths_with_tags(self, session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) \
|
||||
-> List[str]:
|
||||
"""Return the paths of the Zim Entries tagged with the provided names. Does not open the Zim."""
|
||||
if limit < 1:
|
||||
raise RuntimeError('Limit must be greater than zero')
|
||||
|
||||
tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=self.id)
|
||||
entries = Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select)
|
||||
return entries
|
||||
return [path for _, path in Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select)]
|
||||
|
||||
def entries_with_tags(self, session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) -> List[
|
||||
Entry]:
|
||||
"""Return Zim Entries tagged with the provided names."""
|
||||
return [self.find_entry(i) for i in self.entry_paths_with_tags(session, tag_names, limit, offset)]
|
||||
|
||||
|
||||
class Zims:
|
||||
|
|
@ -290,23 +256,6 @@ class Zims:
|
|||
logger.error(f'Failed to read Zim: {zim}', exc_info=e)
|
||||
return zims
|
||||
|
||||
@classmethod
|
||||
def estimate(cls, session: Session, search_str: str) -> OrderedDictType[Zim, int]:
|
||||
zims = cls.get_all(session)
|
||||
results = OrderedDict()
|
||||
for zim in zims:
|
||||
if zim.auto_search:
|
||||
results[zim] = zim.estimate(search_str)
|
||||
return results
|
||||
|
||||
@classmethod
|
||||
def entries_with_tags(cls, session: Session, tag_names: List[str]) -> OrderedDictType[Zim, int]:
|
||||
zims = cls.get_all(session)
|
||||
results = OrderedDict()
|
||||
for zim in zims:
|
||||
results[zim] = len(zim.entries_with_tags(session, tag_names))
|
||||
return results
|
||||
|
||||
|
||||
class TagZimEntry(Base):
|
||||
__tablename__ = 'tag_zim'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue