An open source, non-profit web search engine
Run URL update as a separate app
Daoud Clarke77a9a03faafb
diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex d3f0983..fe29c69 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -14,12 +14,8 @@ class MwmblConfig(AppConfig):def ready(self):# Imports here to avoid AppRegistryNotReady exception- from mwmbl.search_setup import queued_batches- from mwmbl import backgroundfrom mwmbl.indexer.paths import INDEX_NAME- from mwmbl.indexer.update_urls import update_urls_continuouslyfrom mwmbl.tinysearchengine.indexer import TinyIndex, Document, PAGE_SIZE- from mwmbl.url_queue import update_queue_continuouslyindex_path = Path(settings.DATA_PATH) / INDEX_NAMEtry:@@ -35,9 +31,3 @@ class MwmblConfig(AppConfig):with Database() as db:index_db = IndexDatabase(db.connection)index_db.create_tables()-- if settings.RUN_BACKGROUND_PROCESSES:- new_item_queue = Queue()- Process(target=background.run, args=(settings.DATA_PATH,)).start()- Process(target=update_queue_continuously, args=(new_item_queue, queued_batches,)).start()- Process(target=update_urls_continuously, args=(settings.DATA_PATH, new_item_queue)).start()diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 6ef5e61..07c5ac0 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -18,6 +18,7 @@ from mwmbl.crawler.stats import MwmblStats, StatsManagerfrom mwmbl.database import Databasefrom mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.indexdb import IndexDatabase, BatchInfo, BatchStatus+from mwmbl.redis_url_queue import RedisURLQueuefrom mwmbl.settings import (ENDPOINT_URL,KEY_ID,@@ -31,7 +32,7 @@ from mwmbl.settings import (FILE_NAME_SUFFIX,DATE_REGEX)-stats_manager = StatsManager(Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379")))+stats_manager = StatsManager(Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True))def get_bucket(name):@@ -49,7 +50,7 @@ def upload(data: bytes, name: str):last_batch = None-def create_router(batch_cache: BatchCache, queued_batches: Queue, version: str) -> NinjaAPI:+def create_router(batch_cache: BatchCache, queued_batches: RedisURLQueue, version: str) -> NinjaAPI:router = NinjaAPI(urls_namespace=f"crawler-{version}")@router.post('/batches/')@@ -110,10 +111,9 @@ def create_router(batch_cache: BatchCache, queued_batches: Queue, version: str)def request_new_batch(request, batch_request: NewBatchRequest) -> list[str]:user_id_hash = _get_user_id_hash(batch_request)try:- urls = queued_batches.get(block=False)+ urls = queued_batches.get_batch()except Empty:return []-# TODO: track which URLs are currently being crawledreturn urlsdiff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.pyindex cecdd77..d3e8771 100644--- a/mwmbl/indexer/update_urls.py+++ b/mwmbl/indexer/update_urls.py@@ -18,6 +18,7 @@ from mwmbl.indexer.blacklist import get_blacklist_domains, is_domain_blacklistedfrom mwmbl.indexer.index_batches import get_url_error_statusfrom mwmbl.indexer.indexdb import BatchStatusfrom mwmbl.indexer.paths import BATCH_DIR_NAME+from mwmbl.redis_url_queue import RedisURLQueuefrom mwmbl.settings import UNKNOWN_DOMAIN_MULTIPLIER, SCORE_FOR_SAME_DOMAIN, \SCORE_FOR_DIFFERENT_DOMAIN, SCORE_FOR_ROOT_PATH, EXTRA_LINK_MULTIPLIERfrom mwmbl.utils import get_domain@@ -25,7 +26,7 @@ from mwmbl.utils import get_domainlogger = getLogger(__name__)-def update_urls_continuously(data_path: str, new_item_queue: Queue):+def update_urls_continuously(data_path: str, new_item_queue: RedisURLQueue):batch_cache = BatchCache(Path(data_path) / BATCH_DIR_NAME)while True:try:@@ -35,11 +36,12 @@ def update_urls_continuously(data_path: str, new_item_queue: Queue):sleep(10)-def run(batch_cache: BatchCache, new_item_queue: Queue):- process_batch.run(batch_cache, BatchStatus.LOCAL, BatchStatus.URLS_UPDATED, record_urls_in_database, 100, new_item_queue)+def run(batch_cache: BatchCache, new_item_queue: RedisURLQueue):+ process_batch.run(batch_cache, BatchStatus.LOCAL, BatchStatus.URLS_UPDATED, record_urls_in_database, 100,+ new_item_queue)-def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Queue):+def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: RedisURLQueue):start = datetime.now()blacklist_domains = get_blacklist_domains()blacklist_retrieval_time = datetime.now() - start@@ -80,7 +82,7 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Quwith URLDatabase() as url_db:new_urls = url_db.update_found_urls(found_urls)- new_item_queue.put(new_urls)+ new_item_queue.queue_urls(new_urls)logger.info(f"Put {len(new_urls)} new items in the URL queue")with DomainLinkDatabase() as domain_link_db:diff --git a/mwmbl/main.py b/mwmbl/main.pyindex da6f212..5b93ad7 100644--- a/mwmbl/main.py+++ b/mwmbl/main.py@@ -1,13 +1,41 @@+import logging+import os+import sys+import djangoimport uvicornfrom django.core.management import call_command+from redis import Redis++from mwmbl.indexer.update_urls import update_urls_continuously+from mwmbl.redis_url_queue import RedisURLQueuedef run():+ # FORMAT = '%(levelname)s %(name)s %(asctime)s %(message)s'+ # logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=FORMAT)+django.setup()- call_command("collectstatic", "--clear", "--noinput")++ from django.conf import settings+ from mwmbl import background++ if settings.STATIC_ROOT:+ call_command("collectstatic", "--clear", "--noinput")+call_command("migrate")- uvicorn.run("mwmbl.asgi:application", host="0.0.0.0", port=5000)++ mwmbl_app = os.environ["MWMBL_APP"]+ if mwmbl_app == "update_urls":+ redis: Redis = Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)+ url_queue = RedisURLQueue(redis)+ update_urls_continuously(settings.DATA_PATH, url_queue)+ elif mwmbl_app == "background":+ background.run(settings.DATA_PATH)+ elif mwmbl_app == "server":+ uvicorn.run("mwmbl.asgi:application", host="0.0.0.0", port=5000)+ else:+ raise ValueError(f"Unknown MWMBL_APP: {mwmbl_app}")if __name__ == "__main__":diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.pyindex 24925bb..7fb0686 100644--- a/mwmbl/redis_url_queue.py+++ b/mwmbl/redis_url_queue.py@@ -1,3 +1,4 @@+from logging import getLoggerfrom random import Randomfrom urllib.parse import urlparse@@ -9,6 +10,7 @@ from mwmbl.hn_top_domains_filtered import DOMAINSfrom mwmbl.settings import CORE_DOMAINSrandom = Random(1)+logger = getLogger(__name__)DOMAIN_URLS_KEY = "domain-urls-{domain}"@@ -56,6 +58,8 @@ class RedisURLQueue:lowest_scoring_domain = self.redis.zpopmin(DOMAIN_SCORE_KEY)self.redis.delete(DOMAIN_URLS_KEY.format(domain=lowest_scoring_domain))+ logger.info(f"Queued {len(found_urls)} URLs, number of domains: {self.redis.zcard(DOMAIN_SCORE_KEY)}")+def get_batch(self) -> list[str]:top_scoring_domains = set(self.redis.zrange(DOMAIN_SCORE_KEY, 0, 2000, desc=True))top_other_domains = top_scoring_domains - DOMAINS.keys()@@ -64,11 +68,18 @@ class RedisURLQueue:+ random.sample(DOMAINS.keys(), 50)+ random.sample(top_other_domains, 100))+ logger.info(f"Getting batch from domains {domains}")+# Pop the highest scoring URL from each domainurls = []for domain in domains:- urls.append(self.redis.zpopmax(DOMAIN_URLS_KEY.format(domain=domain)))- if len(urls) > BATCH_SIZE:+ domain_urls_scores = self.redis.zpopmax(DOMAIN_URLS_KEY.format(domain=domain))++ for url, score in domain_urls_scores:+ urls.append(url)++ if len(urls) >= BATCH_SIZE:break+ logger.info(f"Returning URLs: {urls}")return urlsdiff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.pyindex f44867a..c1a37ad 100644--- a/mwmbl/search_setup.py+++ b/mwmbl/search_setup.py@@ -1,15 +1,18 @@-from multiprocessing import Queue+import osfrom pathlib import Pathfrom django.conf import settings+from redis import Redisfrom mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.paths import INDEX_NAME, BATCH_DIR_NAME+from mwmbl.redis_url_queue import RedisURLQueuefrom mwmbl.tinysearchengine.completer import Completerfrom mwmbl.tinysearchengine.indexer import TinyIndex, Documentfrom mwmbl.tinysearchengine.rank import HeuristicRanker-queued_batches = Queue()+redis = Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)+queued_batches = RedisURLQueue(redis)completer = Completer()index_path = Path(settings.DATA_PATH) / INDEX_NAMEtiny_index = TinyIndex(item_factory=Document, index_path=index_path)