Files
javis_bot/src/voice_worker/collect.py
javis-bot 55d19364a0 fix(app): the proxy refuses IPv6 outside global unicast and its stop closes open tunnels
- IPv6 counts as public only in 2000::/3 (without 2001::/23, documentation and 6to4), so site
  local fec0::/10 and IPv4-compatible addresses are refused; the collector uses the same rule
- every proxy connection is a task of one set: a stop ends the open CONNECT tunnels and waits
  until their sockets are gone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:07:50 +09:00

389 lines
15 KiB
Python

"""Background collection of sites, search words and RSS feeds (voice_worker.spec.md, "Background
collection"). Results go only to day files in the data folder; logs carry target names and counts."""
from __future__ import annotations
import hashlib
import ipaddress
import json
import re
import socket
import threading
import time
import urllib.parse
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Callable, Optional
from .log import debug_log, notice
MAX_BYTES = 1024 * 1024
TOTAL_S = 15.0
CONNECT_S = 10.0
READ_S = 5.0
MAX_REDIRECTS = 5
SITE_CHARS = 20_000
SUMMARY_CHARS = 2_000
SEEN_KEEP = 1000
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36")
_DAY_FILE = re.compile(r"^(\d{4}-\d{2}-\d{2})\.jsonl$")
@dataclass
class Target:
name: str
kind: str
value: str
every_s: float
@dataclass
class Config:
dir: Path
keep_days: int
targets: list
def load_config(path) -> Config:
raw = json.loads(Path(path).read_text(encoding="utf-8"))
return Config(Path(raw["dir"]), int(raw.get("keepDays", 30)),
[Target(t["name"], t["kind"], t["value"], float(t["everyMinutes"]) * 60) for t in raw.get("targets", [])])
def _is_public_ip(ip) -> bool:
if ip.version == 6:
if ip.ipv4_mapped:
return _is_public_ip(ip.ipv4_mapped)
# Only global unicast 2000::/3 is routed on the internet (leaves out site local fec0::/10,
# IPv4-compatible ::a.b.c.d and the rest); 6to4 can embed any IPv4 address.
if ip not in _GLOBAL_UNICAST or ip in _SIX_TO_FOUR:
return False
return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
or ip.is_multicast or ip.is_unspecified)
_GLOBAL_UNICAST = ipaddress.ip_network("2000::/3")
_SIX_TO_FOUR = ipaddress.ip_network("2002::/16")
def _resolve(host: str, port: int, deadline: float) -> list:
"""getaddrinfo on a daemon thread, waited for only until `deadline` (a late answer is dropped)."""
out: dict = {}
done = threading.Event()
def run():
try:
out["v"] = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except OSError as e:
out["e"] = e
done.set()
threading.Thread(target=run, name="collect-dns", daemon=True).start()
if not done.wait(max(0.0, deadline - time.monotonic())):
raise TimeoutError("took too long")
if "e" in out:
raise ValueError("name not found")
return out["v"]
def _public_ips(host: str, port: int, deadline: float) -> list:
"""The addresses to connect to: every address the name resolves to must be public. The caller
connects only to these, so a second lookup cannot point elsewhere. Nothing about the address
is logged (it is the user's collection target)."""
try:
addrs = [str(ipaddress.ip_address(host))]
except ValueError:
addrs = list(dict.fromkeys(i[4][0] for i in _resolve(host, port, deadline)))
if not addrs or not all(_is_public_ip(ipaddress.ip_address(a.split("%")[0])) for a in addrs):
raise ValueError("not a public address")
return addrs
class _Watchdog:
"""Shuts the current socket down at the deadline, so a wait anywhere in the request (TLS,
status line, headers, body) ends then even if every byte comes within the per-read limit."""
def __init__(self, deadline: float):
self.fired = False
self._sock: Optional[socket.socket] = None
self._lock = threading.Lock()
self._timer = threading.Timer(max(0.0, deadline - time.monotonic()), self._fire)
self._timer.daemon = True
self._timer.start()
def _fire(self) -> None:
with self._lock:
self.fired = True
if self._sock is not None:
try:
self._sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def watch(self, sock: socket.socket) -> None:
with self._lock:
self._sock = sock
if self.fired:
raise TimeoutError("took too long")
def cancel(self) -> None:
self._timer.cancel()
def _connect(ips: list, port: int, deadline: float) -> socket.socket:
"""A socket to the first checked address that connects before `deadline`."""
for i, ip in enumerate(ips):
left = deadline - time.monotonic()
if left <= 0:
raise TimeoutError("took too long")
try:
return socket.create_connection((ip, port), timeout=min(CONNECT_S, left))
except OSError:
if i == len(ips) - 1:
raise
def _ascii(part: str) -> str:
return urllib.parse.quote(part, safe="/%:@!$&'()*+,;=?[]~")
def _get(url: str, deadline: float, dog: _Watchdog):
"""One hop: ("redirect", next url) or ("body", bytes)."""
import http.client
import ssl
import certifi
p = urllib.parse.urlsplit(url)
if p.scheme not in ("http", "https") or not p.hostname:
raise ValueError("not an http(s) address")
port = p.port or (443 if p.scheme == "https" else 80)
sock = _connect(_public_ips(p.hostname, port, deadline), port, deadline)
try:
dog.watch(sock)
sock.settimeout(READ_S)
if p.scheme == "https":
# TLS checks the certificate against the name, not the address connected to. The TLS
# socket takes over the connection, so the watchdog watches it from here.
ctx = ssl.create_default_context(cafile=certifi.where())
conn = http.client.HTTPSConnection(p.hostname, port, context=ctx)
sock = ctx.wrap_socket(sock, server_hostname=p.hostname, do_handshake_on_connect=False)
dog.watch(sock)
sock.do_handshake()
else:
conn = http.client.HTTPConnection(p.hostname, port)
conn.sock = sock
# The request line is ASCII: other characters (and spaces) go as UTF-8 %HH; existing %HH
# and the reserved separators stay as they are.
path = _ascii(p.path or "/") + (f"?{_ascii(p.query)}" if p.query else "")
conn.request("GET", path, headers={"User-Agent": USER_AGENT, "Accept-Encoding": "identity"})
r = conn.getresponse()
if r.status in (301, 302, 303, 307, 308):
return "redirect", urllib.parse.urljoin(url, r.getheader("Location", ""))
if r.status != 200: # e.g. DuckDuckGo's 202 challenge
raise ValueError(f"status {r.status}")
body = b""
while chunk := r.read1(64 * 1024):
body += chunk
if len(body) > MAX_BYTES:
raise ValueError("response too large")
# read1 ends quietly when the watchdog cuts the connection or the server stops early.
if dog.fired:
raise TimeoutError("took too long")
if r.length:
raise ValueError("incomplete response")
return "body", body
finally:
sock.close()
def safe_get(url: str) -> bytes:
"""GET a public http(s) address: every hop's address checked and connected to as checked, at
most ``MAX_BYTES`` and ``TOTAL_S`` seconds in all (lookup, connect, TLS, headers and body of
every redirect)."""
deadline = time.monotonic() + TOTAL_S
dog = _Watchdog(deadline)
try:
for _ in range(MAX_REDIRECTS + 1):
kind, value = _get(url, deadline, dog)
if kind == "body":
return value
url = value
raise ValueError("too many redirects")
except Exception:
if dog.fired: # the watchdog cut the connection: whatever broke, it took too long
raise TimeoutError("took too long") from None
raise
finally:
dog.cancel()
def _text(html) -> str:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
for tag in soup(["script", "style", "noscript"]):
tag.decompose()
return " ".join(soup.get_text(" ").split())
def _site(body: bytes) -> list:
from bs4 import BeautifulSoup
soup = BeautifulSoup(body, "html.parser")
title = soup.title.get_text().strip() if soup.title else ""
for tag in soup(["script", "style", "noscript", "title"]):
tag.decompose()
text = "\n".join(line for line in (" ".join(l.split()) for l in soup.get_text("\n").splitlines()) if line)
return [{"title": title, "text": text[:SITE_CHARS]}]
def _local(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def _feed(body: bytes) -> list:
"""RSS 2.0 items or Atom entries, each with an ``id`` to tell new ones."""
out = []
for el in ET.fromstring(body).iter():
if _local(el.tag) not in ("item", "entry"):
continue
f = {_local(c.tag): c for c in el}
link = (f["link"].get("href") or (f["link"].text or "")).strip() if "link" in f else ""
get = lambda *keys: next(((f[k].text or "").strip() for k in keys if k in f), "")
item = {"title": get("title"), "url": link, "published": get("pubDate", "published", "updated"),
"text": _text(get("description", "summary", "content"))[:SUMMARY_CHARS]}
item["id"] = get("guid", "id") or link or item["title"]
out.append(item)
return out
def search_url(words: str) -> str:
return "https://lite.duckduckgo.com/lite/?q=" + urllib.parse.quote_plus(words)
class SearchBlocked(Exception):
"""DuckDuckGo served its bot challenge instead of results (web_search.spec.md)."""
def _search(body: bytes) -> list:
from bs4 import BeautifulSoup
if b"anomaly-modal" in body or b"anomaly.js" in body:
raise SearchBlocked()
out = []
for a in BeautifulSoup(body, "html.parser").find_all("a", href=True):
href, title = a["href"], " ".join(a.get_text().split())
if href.startswith("//duckduckgo.com/l/"):
href = urllib.parse.parse_qs(urllib.parse.urlparse(href).query).get("uddg", [""])[0]
host = urllib.parse.urlparse(href).hostname or ""
if href.startswith("http") and len(title) > 10 and not host.endswith("duckduckgo.com"):
out.append({"title": title, "url": href, "id": href})
return out[:10]
class Collector:
def __init__(self, cfg: Config, fetch: Callable[[str], bytes] = safe_get, check_every: float = 30.0):
self.cfg = cfg
self.fetch = fetch
self.check_every = check_every
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
# -- state ----------------------------------------------------------------------------------
def _folder(self, t: Target) -> Path:
return self.cfg.dir / t.name
def _state(self, t: Target) -> dict:
try:
return json.loads((self._folder(t) / "state.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
def _save_state(self, t: Target, state: dict) -> None:
f = self._folder(t) / "state.json"
f.parent.mkdir(parents=True, exist_ok=True)
tmp = f.with_suffix(".tmp")
tmp.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
tmp.replace(f)
def _keep(self, t: Target, new: list) -> None:
if not new:
return
f = self._folder(t) / f"{date.today()}.jsonl"
f.parent.mkdir(parents=True, exist_ok=True)
at = datetime.now().astimezone().isoformat(timespec="seconds")
with f.open("a", encoding="utf-8") as out:
for item in new:
out.write(json.dumps({"at": at, **item}, ensure_ascii=False) + "\n")
# -- one round ------------------------------------------------------------------------------
def _prune(self) -> None:
oldest = date.today() - timedelta(days=self.cfg.keep_days)
if not self.cfg.dir.is_dir():
return
for folder in self.cfg.dir.iterdir():
if not folder.is_dir():
continue
for f in folder.iterdir():
m = _DAY_FILE.match(f.name)
if m and date.fromisoformat(m.group(1)) < oldest:
f.unlink(missing_ok=True)
def _run(self, t: Target, state: dict) -> int:
if t.kind == "site":
[page] = _site(self.fetch(t.value))
digest = hashlib.sha256(json.dumps([page["title"], page["text"]]).encode()).hexdigest()
if digest == state.get("hash"):
return 0
state["hash"] = digest
self._keep(t, [{**page, "url": t.value}])
return 1
found = _feed(self.fetch(t.value)) if t.kind == "rss" else _search(self.fetch(search_url(t.value)))
seen = state.get("seen", [])
new = [i for i in found if i["id"] not in seen]
state["seen"] = (seen + [i["id"] for i in new])[-SEEN_KEEP:]
self._keep(t, [{k: v for k, v in i.items() if k != "id"} for i in new])
return len(new)
def run_due(self, now: Optional[float] = None) -> None:
now = time.time() if now is None else now
self._prune()
for t in self.cfg.targets:
if self._stop.is_set():
return
state = self._state(t)
if now - state.get("last", float("-inf")) < t.every_s:
continue
state["last"] = now
t0 = time.perf_counter()
try:
n = self._run(t, state)
notice(f"collect {t.name}: {n} new", "voice_worker")
except Exception as e: # noqa: BLE001 - a broken target waits for its next interval
notice(f"Warning: collect {t.name} failed: {type(e).__name__}", "voice_worker")
self._save_state(t, state)
debug_log(f"collect {t.name} kind={t.kind} ms={(time.perf_counter() - t0) * 1000:.0f}", "voice_worker")
# -- thread ---------------------------------------------------------------------------------
def start(self) -> None:
def loop():
while not self._stop.is_set():
try:
self.run_due()
except Exception as e: # noqa: BLE001 - e.g. the folder became unwritable
notice(f"Warning: collect round failed: {type(e).__name__}", "voice_worker")
self._stop.wait(self.check_every)
self._thread = threading.Thread(target=loop, name="collect", daemon=True)
self._thread.start()
debug_log(f"collect started: {len(self.cfg.targets)} target(s)", "voice_worker")
def stop(self, timeout: float = 5.0) -> None:
self._stop.set()
if self._thread:
self._thread.join(timeout)
def running(self) -> bool:
return bool(self._thread and self._thread.is_alive())