#!/usr/bin/env python3 """Keep a knowledge base fresh with the Ujeebu Crawl API: the webhook receiver (Flask). When a crawl job ends, Ujeebu sends one signed POST to /hooks/crawl. This receiver checks the signature, answers at once, then downloads the job's archive, checks its checksum and compares each page's sha256 with the previous run, so only new and changed pages are processed again. pip install flask requests UJEEBU_API_KEY=your-key python3 receiver.py """ import hashlib import hmac import io import json import os import tarfile import threading import time import requests from flask import Flask, abort, request API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY") # webhooks are signed with your API key HASHES_FILE = "page-hashes.json" # url -> sha256 of the content last processed MAX_AGE = 300 # refuse a call signed more than 5 minutes ago app = Flask(__name__) seen_ids = set() # X-Ujeebu-Webhook-Id of the calls already accepted lock = threading.Lock() # one refresh at a time def signature_ok(raw_body, timestamp, signature): """HMAC-SHA256 of "." keyed with your API key, compared in constant time.""" if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > MAX_AGE: return False digest = hmac.new(API_KEY.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest("sha256=" + digest, signature) def download_archive(archive): """The job's tar.gz archive as {file name: bytes}, once its sha256 matches.""" raw = requests.get(archive["url"], timeout=300).content if hashlib.sha256(raw).hexdigest() != archive["checksum_sha256"]: raise ValueError("archive checksum mismatch") with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar: return {m.name: tar.extractfile(m).read() for m in tar.getmembers() if m.isfile()} def reprocess(url, markdown): """Your pipeline: chunk, embed and upsert this page (see the previous tutorial).""" print(f" process {url} ({len(markdown)} chars)") def remove(url): """Your pipeline: delete this page's chunks from the knowledge base.""" print(f" remove {url}") def refresh(event): files = download_archive(event["archive"]) manifest = json.loads(files["manifest.json"]) with lock: hashes = {} if os.path.exists(HASHES_FILE): with open(HASHES_FILE) as f: hashes = json.load(f) changed = unchanged = removed = 0 for page in manifest["pages"]: url = page["url"] if page["state"] == "done": if hashes.get(url) == page["sha256"]: unchanged += 1 continue reprocess(url, files[page["file"]].decode("utf-8")) hashes[url] = page["sha256"] changed += 1 elif page.get("error_class") == "not_found" and url in hashes: remove(url) # the page is gone (404 or 410) del hashes[url] removed += 1 with open(HASHES_FILE, "w") as f: json.dump(hashes, f, indent=1) print(f"{event['job_id']}: {changed} new or changed, {unchanged} unchanged, " f"{removed} removed ({event['credits_used']} credits)") @app.post("/hooks/crawl") def crawl_webhook(): raw = request.get_data() # the raw bytes: the signature covers them exactly if not signature_ok(raw, request.headers.get("X-Ujeebu-Timestamp", ""), request.headers.get("X-Ujeebu-Signature", "")): abort(401) webhook_id = request.headers.get("X-Ujeebu-Webhook-Id", "") if webhook_id in seen_ids: return "", 200 # a retry of a call already accepted seen_ids.add(webhook_id) event = json.loads(raw) if event["event"] != "crawl.job.completed": # crawl.job.failed or crawl.job.cancelled print(f"{event['job_id']}: {event['event']} ({event['stop_reason']}), nothing to refresh") return "", 200 threading.Thread(target=refresh, args=(event,), daemon=True).start() return "", 202 # answer at once; the refresh runs in the background if __name__ == "__main__": app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))