Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Track crawled URLs using a bloom filter

Daoud Clarke5782e26763c3
diff --git a/devdata/index-v2.tinysearch b/devdata/index-v2.tinysearch
index 77813c8..7f03d99 100644
Binary files a/devdata/index-v2.tinysearch and b/devdata/index-v2.tinysearch differ
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index d19c46d..c80c7a9 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -37,7 +37,6 @@ class MwmblConfig(AppConfig):
with Database() as db:
url_db = URLDatabase(db.connection)
- url_db.create_tables()
index_db = IndexDatabase(db.connection)
index_db.create_tables()
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 723dd18..c7d2b3b 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -23,7 +23,6 @@ def run(data_path: str):
with Database() as db:
url_db = URLDatabase(db.connection)
- url_db.create_tables()
historical.run()
index_path = Path(data_path) / INDEX_NAME
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 26ccf8a..2edd4d8 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -115,10 +115,7 @@ def create_router(batch_cache: BatchCache, queued_batches: Queue, version: str)
except Empty:
return []
- found_urls = [FoundURL(url, user_id_hash, 0.0, URLStatus.ASSIGNED, datetime.utcnow()) for url in urls]
- with Database() as db:
- url_db = URLDatabase(db.connection)
- url_db.update_found_urls(found_urls)
+ # TODO: track which URLs are currently being crawled
return urls
diff --git a/mwmbl/crawler/urls.py b/mwmbl/crawler/urls.py
index 7c83edf..b50b660 100644
--- a/mwmbl/crawler/urls.py
+++ b/mwmbl/crawler/urls.py
@@ -5,8 +5,11 @@ from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from logging import getLogger
+from pathlib import Path
+from django.conf import settings
from psycopg2.extras import execute_values
+from pybloomfilter import BloomFilter
# Client has one hour to crawl a URL that has been assigned to them, or it will be reassigned
from mwmbl.utils import batch
@@ -35,6 +38,9 @@ class URLStatus(Enum):
CRAWLED = 100 # At least one user has crawled the URL
+CRAWLED_STATUSES = {URLStatus.CRAWLED, URLStatus.ERROR_TIMEOUT, URLStatus.ERROR_404, URLStatus.ERROR_OTHER, URLStatus.ERROR_ROBOTS_DENIED}
+
+
@dataclass
class FoundURL:
url: str
@@ -46,111 +52,25 @@ class FoundURL:
class URLDatabase:
def __init__(self, connection):
- self.connection = connection
-
- def create_tables(self):
- logger.info("Creating URL tables")
-
- sql = """
- CREATE TABLE IF NOT EXISTS urls (
- url VARCHAR PRIMARY KEY,
- status INT NOT NULL DEFAULT 0,
- user_id_hash VARCHAR NOT NULL,
- score FLOAT NOT NULL DEFAULT 1,
- updated TIMESTAMP NOT NULL DEFAULT NOW()
- )
- """
-
- with self.connection.cursor() as cursor:
- cursor.execute(sql)
- # cursor.execute(index_sql)
- # cursor.execute(view_sql)
-
- def update_found_urls(self, found_urls: list[FoundURL]) -> list[FoundURL]:
- if len(found_urls) == 0:
- return []
-
- get_urls_sql = """
- SELECT url FROM urls
- WHERE url in %(urls)s
- """
-
- lock_urls_sql = """
- SELECT url FROM urls
- WHERE url in %(urls)s
- FOR UPDATE SKIP LOCKED
- """
-
- insert_sql = f"""
- INSERT INTO urls (url, status, user_id_hash, score, updated) values %s
- ON CONFLICT (url) DO UPDATE SET
- status = GREATEST(urls.status, excluded.status),
- user_id_hash = CASE
- WHEN urls.status > excluded.status THEN urls.user_id_hash ELSE excluded.user_id_hash
- END,
- score = urls.score + excluded.score,
- updated = CASE
- WHEN urls.status > excluded.status THEN urls.updated ELSE excluded.updated
- END
- RETURNING url, user_id_hash, score, status, updated
- """
+ try:
+ self.urls = BloomFilter.open(settings.URLS_BLOOM_FILTER_PATH)
+ except FileNotFoundError:
+ logger.info("No existing bloom filter found, creating a new one")
+ self.urls = BloomFilter(settings.NUM_URLS_IN_BLOOM_FILTER, 0.01, settings.URLS_BLOOM_FILTER_PATH, perm=0o666)
- input_urls = [x.url for x in found_urls]
- assert len(input_urls) == len(set(input_urls))
-
- with self.connection as connection:
- with connection.cursor() as cursor:
- logger.info(f"Input URLs: {len(input_urls)}")
- cursor.execute(get_urls_sql, {'urls': tuple(input_urls)})
- existing_urls = {x[0] for x in cursor.fetchall()}
- new_urls = set(input_urls) - existing_urls
-
- cursor.execute(lock_urls_sql, {'urls': tuple(input_urls)})
- locked_urls = {x[0] for x in cursor.fetchall()}
-
- urls_to_insert = new_urls | locked_urls
- logger.info(f"URLs to insert: {len(urls_to_insert)}")
-
- if len(urls_to_insert) != len(input_urls):
- print(f"Only got {len(urls_to_insert)} instead of {len(input_urls)} - {len(new_urls)} new")
-
- sorted_urls = sorted(found_urls, key=lambda x: x.url)
- data = [
- (found_url.url, found_url.status.value, found_url.user_id_hash, found_url.score, found_url.timestamp)
- for found_url in sorted_urls if found_url.url in urls_to_insert]
-
- logger.info(f"Data: {len(data)}")
- results = execute_values(cursor, insert_sql, data, fetch=True)
- logger.info(f"Results: {len(results)}")
- updated = [FoundURL(*result) for result in results]
- return updated
-
- def get_urls(self, status: URLStatus, num_urls: int) -> list[FoundURL]:
- sql = f"""
- SELECT url, status, user_id_hash, score, updated FROM urls
- WHERE status = %(status)s
- LIMIT %(num_urls)s
+ def update_found_urls(self, found_urls: list[FoundURL]):
"""
-
- # TODO: reinstate this line once performance issue is resolved:
- # ORDER BY score DESC
-
- with self.connection.cursor() as cursor:
- cursor.execute(sql, {'status': status.value, 'num_urls': num_urls})
- results = cursor.fetchall()
-
- return [FoundURL(url, user_id_hash, score, status, updated) for url, status, user_id_hash, score, updated in results]
-
- def get_url_scores(self, urls: list[str]) -> dict[str, float]:
- sql = f"""
- SELECT url, score FROM urls WHERE url IN %(urls)s
+ Update URL that have been crawled, and return any that have not yet been crawled
"""
-
- url_scores = {}
- for url_batch in batch(urls, 10000):
- with self.connection.cursor() as cursor:
- cursor.execute(sql, {'urls': tuple(url_batch)})
- results = cursor.fetchall()
- url_scores.update({result[0]: result[1] for result in results})
-
- return url_scores
+ new_urls = []
+ num_crawled_urls = 0
+ for url in found_urls:
+ if url.url not in self.urls:
+ if url.status in CRAWLED_STATUSES:
+ self.urls.add(url.url)
+ num_crawled_urls += 1
+ else:
+ new_urls.append(url)
+
+ logger.info(f"Found {num_crawled_urls} crawled URLs and {len(new_urls)} new URLs")
+ return new_urls
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 55397b9..10971df 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -31,20 +31,16 @@ def get_documents_from_batches(batches: Collection[HashedBatch]) -> Iterable[tup
def run(batch_cache: BatchCache, index_path: str):
def process(batches: Collection[HashedBatch]):
- with Database() as db:
- url_db = URLDatabase(db.connection)
- index_batches(batches, index_path, url_db)
- logger.info("Indexed pages")
+ index_batches(batches, index_path)
+ logger.info("Indexed pages")
process_batch.run(batch_cache, BatchStatus.URLS_UPDATED, BatchStatus.INDEXED, process, 10000)
-def index_batches(batch_data: Collection[HashedBatch], index_path: str, url_db: URLDatabase):
+def index_batches(batch_data: Collection[HashedBatch], index_path: str):
document_tuples = list(get_documents_from_batches(batch_data))
- urls = [url for title, url, extract in document_tuples]
- url_scores = url_db.get_url_scores(urls)
- logger.info(f"Indexing {len(urls)} document tuples and {len(url_scores)} URL scores")
- documents = [Document(title, url, extract, url_scores.get(url, 1.0)) for title, url, extract in document_tuples]
+ # TODO: compute a proper score for each document
+ documents = [Document(title, url, extract, 1/len(url)) for title, url, extract in document_tuples]
page_documents = preprocess_documents(documents, index_path)
index_pages(index_path, page_documents)
diff --git a/mwmbl/settings_dev.py b/mwmbl/settings_dev.py
index 344e1bd..c8dc860 100644
--- a/mwmbl/settings_dev.py
+++ b/mwmbl/settings_dev.py
@@ -26,6 +26,8 @@ ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATA_PATH = "./devdata"
-RUN_BACKGROUND_PROCESSES = False
+RUN_BACKGROUND_PROCESSES = True
NUM_PAGES = 2560
+URLS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "urls.bloom")
+NUM_URLS_IN_BLOOM_FILTER = 100_000
diff --git a/mwmbl/settings_prod.py b/mwmbl/settings_prod.py
index 3ba4533..bfbbbf8 100644
--- a/mwmbl/settings_prod.py
+++ b/mwmbl/settings_prod.py
@@ -32,3 +32,6 @@ EMAIL_USE_TLS = True
DATA_PATH = "/app/storage"
RUN_BACKGROUND_PROCESSES = False
NUM_PAGES = 10240000
+
+URLS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "urls.bloom")
+NUM_URLS_IN_BLOOM_FILTER = 200_000_000
diff --git a/mwmbl/url_queue.py b/mwmbl/url_queue.py
index 3facf86..d520b87 100644
--- a/mwmbl/url_queue.py
+++ b/mwmbl/url_queue.py
@@ -9,7 +9,7 @@ from typing import KeysView, Union
from mwmbl.crawler.urls import BATCH_SIZE, URLDatabase, URLStatus, FoundURL, REASSIGN_MIN_HOURS
from mwmbl.database import Database
-from mwmbl.hn_top_domains_filtered import DOMAINS as TOP_DOMAINS
+from mwmbl.hn_top_domains_filtered import DOMAINS as TOP_DOMAINS, DOMAINS
from mwmbl.indexer.blacklist import is_domain_blacklisted, get_blacklist_domains
from mwmbl.settings import CORE_DOMAINS
from mwmbl.utils import batch, get_domain
@@ -44,15 +44,6 @@ class URLQueue:
self._min_top_domains = min_top_domains
assert min_top_domains > 0, "Need a minimum greater than 0 to prevent a never-ending loop"
- def initialize(self):
- logger.info(f"Initializing URL queue")
- blacklist_domains = get_blacklist_domains()
- with Database() as db:
- url_db = URLDatabase(db.connection)
- found_urls = url_db.get_urls(URLStatus.NEW, INITIALIZE_URLS)
- self._process_found_urls(found_urls, blacklist_domains)
- logger.info(f"Initialized URL queue with {len(found_urls)} urls, current queue size: {self.num_queued_batches}")
-
def update(self):
blacklist_domains = get_blacklist_domains()
num_processed = 0
@@ -94,7 +85,7 @@ class URLQueue:
if is_domain_blacklisted(domain, blacklist_domains):
continue
url_store = self._top_urls if domain in TOP_DOMAINS else self._other_urls
- url_store[domain][found_url.url] = found_url.score
+ url_store[domain][found_url.url] = 1/len(found_url.url)
logger.info(f"URL store updated: {len(self._top_urls)} top domains, {len(self._other_urls)} other domains")
@@ -146,7 +137,6 @@ def _add_urls(domains: Union[set[str], KeysView], domain_urls: dict[str, dict[st
def update_queue_continuously(new_item_queue: Queue, queued_batches: Queue):
queue = URLQueue(new_item_queue, queued_batches)
- queue.initialize()
while True:
num_processed = queue.update()
logger.info(f"Queue update, num processed: {num_processed}, queue size: {queue.num_queued_batches}, num top "
diff --git a/poetry.lock b/poetry.lock
index 800e178..c82c1cb 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1500,6 +1500,16 @@ files = [
[package.dependencies]
numpy = ">=1.16.6"
+[[package]]
+name = "pybloomfiltermmap3"
+version = "0.5.7"
+description = "A fast implementation of Bloom filter for Python 3 built on mmap"
+optional = false
+python-versions = ">=3.5, <4"
+files = [
+ {file = "pybloomfiltermmap3-0.5.7.tar.gz", hash = "sha256:fe2cf925a1623b886ff12b8ab3f31c33392cd5c192ecd60d55af66d162bb9e71"},
+]
+
[[package]]
name = "pycparser"
version = "2.21"
@@ -2561,4 +2571,4 @@ indexer = ["Levenshtein", "beautifulsoup4", "idna", "langdetect", "lxml", "pyarr
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.11"
-content-hash = "4e4233221e9f3bd317c0693584612898b7b736f45983b7f3f5bad4d43e567353"
+content-hash = "f884b27d04703e4a611c6d37cc1b3153b9de0522637c3216672138ee6c22ffd6"
diff --git a/pyproject.toml b/pyproject.toml
index ba9c755..cb8cba4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,6 +41,7 @@ django-allauth = "^0.57.0"
dj-database-url = "^2.1.0"
django-htmx = "^1.17.0"
django-vite = "^2.1.3"
+pybloomfiltermmap3 = "^0.5.7"
[tool.poetry.extras]
indexer = [