diff --git a/.github/workflows/data-sync.yml b/.github/workflows/data-sync.yml index d7b7db8..465c97c 100644 --- a/.github/workflows/data-sync.yml +++ b/.github/workflows/data-sync.yml @@ -37,7 +37,7 @@ jobs: - name: Mask the connection details run: > uv run python -c "import os; - from hackproof.db_utils.connection import Connection; + from trawl.schema.connection import Connection; print('\n'.join(Connection.from_url(os.environ['DATABASE_URL']).mask_lines()))" - name: Restore the scan data the database does not hold run: uv run hackproof import --remote diff --git a/apps/api/pyproject.toml b/apps/api/pyproject.toml index fbed6d1..b2fa651 100644 --- a/apps/api/pyproject.toml +++ b/apps/api/pyproject.toml @@ -15,14 +15,12 @@ dependencies = [ "pydantic-settings>=2.16.1", "pyyaml>=6.0.3", "stellar-sdk>=16.1.1", + "trawl @ https://github.com/devodii/trawl/releases/download/v0.1.0/trawl-0.1.0-py3-none-any.whl", ] [project.scripts] hackproof = "hackproof.cli:main" -[project.entry-points."sqlfluff"] -hackproof = "hackproof.db_utils.sqlfluff.plugin" - [build-system] requires = ["uv_build>=0.12.5,<0.13.0"] build-backend = "uv_build" diff --git a/apps/api/src/hackproof/cli.py b/apps/api/src/hackproof/cli.py index 7cbded2..9714f9e 100644 --- a/apps/api/src/hackproof/cli.py +++ b/apps/api/src/hackproof/cli.py @@ -4,9 +4,10 @@ import os from pathlib import Path +from trawl.schema.connection import Connection + from hackproof.config import get_settings from hackproof.db_utils import pgschema -from hackproof.db_utils.connection import Connection from hackproof.export.jobs import run_check, run_export, run_import from hackproof.github.jobs import run_discover, run_scan from hackproof.indexer.sync import run_sync diff --git a/apps/api/src/hackproof/config.py b/apps/api/src/hackproof/config.py index f27942c..8b6e24b 100644 --- a/apps/api/src/hackproof/config.py +++ b/apps/api/src/hackproof/config.py @@ -4,6 +4,7 @@ from pydantic import AliasChoices, Field, field_validator from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict +from trawl.github.client import parse_tokens ROOT = Path(__file__).resolve().parents[4] ROOT_ENV = ROOT / ".env" @@ -42,9 +43,7 @@ class Settings(BaseSettings): @field_validator("github_tokens", mode="before") @classmethod def split_tokens(cls, value: object) -> object: - if isinstance(value, str): - return [token.strip() for token in value.split(",") if token.strip()] - return value + return parse_tokens(value) if isinstance(value, str) else value @lru_cache diff --git a/apps/api/src/hackproof/db.py b/apps/api/src/hackproof/db.py index 310e0d2..142c146 100644 --- a/apps/api/src/hackproof/db.py +++ b/apps/api/src/hackproof/db.py @@ -1,23 +1,14 @@ -import json - import asyncpg +from trawl.db.pool import open_pool as connect from hackproof.config import get_settings _pool: asyncpg.Pool | None = None -async def _init_connection(connection: asyncpg.Connection) -> None: - await connection.set_type_codec( - "jsonb", encoder=json.dumps, decoder=json.loads, schema="pg_catalog" - ) - - async def open_pool() -> asyncpg.Pool: global _pool - _pool = await asyncpg.create_pool( - get_settings().database_url, min_size=1, max_size=10, init=_init_connection - ) + _pool = await connect(get_settings().database_url) return _pool diff --git a/apps/api/src/hackproof/db_utils/connection.py b/apps/api/src/hackproof/db_utils/connection.py deleted file mode 100644 index 6f38ac7..0000000 --- a/apps/api/src/hackproof/db_utils/connection.py +++ /dev/null @@ -1,55 +0,0 @@ -import sys -from typing import Self -from urllib.parse import parse_qs, quote, unquote, urlparse - -from pydantic import BaseModel - -LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1", "host.docker.internal"} - - -class Connection(BaseModel): - """One database, as pgschema's container needs to reach it.""" - - host: str - port: int = 5432 - user: str - password: str - database: str - sslmode: str = "prefer" - - @classmethod - def from_url(cls, url: str) -> Self: - parsed = urlparse(url) - query = parse_qs(parsed.query) - return cls( - host=parsed.hostname or "localhost", - port=parsed.port or 5432, - user=unquote(parsed.username or ""), - password=unquote(parsed.password or ""), - database=parsed.path.lstrip("/"), - sslmode=query.get("sslmode", ["prefer"])[0], - ) - - @property - def is_local(self) -> bool: - return self.host in LOCAL_HOSTS - - @property - def label(self) -> str: - return f"{self.user}@{self.host}:{self.port}/{self.database}" - - def mask_lines(self) -> list[str]: - """Workflow commands that keep this database out of public CI logs.""" - secrets = {self.host, self.user, self.password, quote(self.password, safe="")} - return [f"::add-mask::{value}" for value in sorted(secrets) if value] - - def container_route(self) -> tuple[list[str], str]: - """Docker network flags and the host name the container should dial.""" - if not self.is_local: - return [], self.host - if sys.platform == "linux": - return ["--network", "host"], "localhost" - return [ - "--add-host", - "host.docker.internal:host-gateway", - ], "host.docker.internal" diff --git a/apps/api/src/hackproof/db_utils/guard.py b/apps/api/src/hackproof/db_utils/guard.py deleted file mode 100644 index f386f49..0000000 --- a/apps/api/src/hackproof/db_utils/guard.py +++ /dev/null @@ -1,43 +0,0 @@ -import re - -from pydantic import BaseModel - -RULES = [ - (r"\bDROP\s+TABLE\b", "drops a table and every row in it"), - (r"\bDROP\s+COLUMN\b", "drops a column and its data"), - (r"\bDROP\s+TYPE\b", "drops a type"), - (r"\bDROP\s+SCHEMA\b", "drops a schema"), - (r"\bDROP\s+SEQUENCE\b", "drops a sequence"), - (r"\bDROP\s+MATERIALIZED\s+VIEW\b", "drops stored view data"), - ( - r"\bALTER\s+COLUMN\b[^;]*\bTYPE\b", - "changes a column type and can rewrite or lose data", - ), - (r"\bTRUNCATE\b", "empties a table"), - (r"\bDELETE\s+FROM\b", "deletes rows"), - (r"\bUPDATE\s+\S+\s+SET\b", "rewrites rows"), -] - - -class Finding(BaseModel): - reason: str - statement: str - - -def strip_comments(sql: str) -> str: - return re.sub(r"--[^\n]*", "", sql) - - -def destructive_statements(sql: str) -> list[Finding]: - """ - Every statement in a plan that could lose data. Dropping an index, view, - trigger, function or constraint loses none, so those pass. - """ - findings = [] - for statement in strip_comments(sql).split(";"): - for pattern, reason in RULES: - if re.search(pattern, statement, re.IGNORECASE): - findings.append( - Finding(reason=reason, statement=" ".join(statement.split())[:200]) - ) - return findings diff --git a/apps/api/src/hackproof/db_utils/manifest.py b/apps/api/src/hackproof/db_utils/manifest.py deleted file mode 100644 index 7bd684d..0000000 --- a/apps/api/src/hackproof/db_utils/manifest.py +++ /dev/null @@ -1,90 +0,0 @@ -import re -from collections.abc import Callable -from pathlib import Path - -LAYERS = [ - "types", - "functions", - "tables", - "constraints", - "indexes", - "views", - "triggers", -] - -OBJECT_RE = { - "tables": re.compile(r'CREATE TABLE( IF NOT EXISTS)? "?([A-Za-z_][A-Za-z0-9_]*)"?'), - "views": re.compile( - r'CREATE (?:OR REPLACE )?VIEW "?([A-Za-z_][A-Za-z0-9_]*)"?', re.IGNORECASE - ), -} -REFERENCE_RE = { - "tables": re.compile(r'REFERENCES "?([A-Za-z_][A-Za-z0-9_]*)"?'), - "views": re.compile(r'(?:FROM|JOIN)\s+"?([A-Za-z_][A-Za-z0-9_]*)"?', re.IGNORECASE), -} - - -def object_name(layer: str, path: Path) -> str | None: - match = OBJECT_RE[layer].search(path.read_text()) - return match.group(match.lastindex or 1) if match else None - - -def order_by_dependency(layer: str, directory: Path) -> list[Path]: - """ - Objects another object points at must load first, and file names alone do not - guarantee that. Tables point at each other through REFERENCES, views through - FROM and JOIN. - """ - files = sorted(directory.glob("*.sql")) - by_name = {name: f for f in files if (name := object_name(layer, f))} - ordered: list[Path] = [] - visited: set[str] = set() - - def visit(name: str) -> None: - if name in visited: - return - visited.add(name) - path = by_name[name] - for dependency in REFERENCE_RE[layer].findall(path.read_text()): - if dependency != name and dependency in by_name: - visit(dependency) - ordered.append(path) - - for name in by_name: - visit(name) - return ordered - - -def layer_files(schema_dir: Path, layer: str) -> list[Path]: - directory = schema_dir / layer - if not directory.is_dir(): - return [] - ordering: Callable[[], list[Path]] = ( - (lambda: order_by_dependency(layer, directory)) - if layer in OBJECT_RE - else (lambda: sorted(directory.glob("*.sql"))) - ) - return ordering() - - -def manifest_text(schema_dir: Path) -> str: - lines = [ - f"\\i {layer}/{path.name}" - for layer in LAYERS - for path in layer_files(schema_dir, layer) - ] - return "\n".join(lines) + "\n" if lines else "" - - -def generate_manifest(schema_dir: Path) -> None: - (schema_dir / "manifest.sql").write_text(manifest_text(schema_dir)) - - -def schema_sql(schema_dir: Path) -> str: - paths = [ - schema_dir / line.removeprefix("\\i ").strip() - for line in (schema_dir / "manifest.sql").read_text().splitlines() - if line.startswith("\\i ") - ] - body = "\n".join(path.read_text() for path in paths) - return f"SET check_function_bodies = off;\n{body}" diff --git a/apps/api/src/hackproof/db_utils/pgschema.py b/apps/api/src/hackproof/db_utils/pgschema.py index be17d74..ffc8a71 100644 --- a/apps/api/src/hackproof/db_utils/pgschema.py +++ b/apps/api/src/hackproof/db_utils/pgschema.py @@ -1,136 +1,21 @@ -import os -import subprocess -import sys from pathlib import Path -from tempfile import TemporaryDirectory + +from trawl.schema import pgschema as schema +from trawl.schema.connection import Connection from hackproof.config import ROOT, get_settings -from hackproof.db_utils.connection import Connection -from hackproof.db_utils.guard import destructive_statements -from hackproof.db_utils.manifest import generate_manifest, manifest_text API_DIR = ROOT / "apps" / "api" DB_DIR = API_DIR / "db" SCHEMA_DIR = DB_DIR / "schema" MIGRATIONS_DIR = DB_DIR / "migrations" -MANIFEST = "/db/schema/manifest.sql" -LOCK_TIMEOUT = "30s" - - -def docker_command( - command: str, - *args: str, - connection: Connection, - mounts: dict[Path, str], - image: str, -) -> list[str]: - network, host = connection.container_route() - mount_flags = [ - flag - for source, target in mounts.items() - for flag in ("-v", f"{source}:{target}") - ] - return [ - "docker", - "run", - "--rm", - "-i", - *network, - "-e", - "PGPASSWORD", - *mount_flags, - image, - command, - "--host", - host, - "--port", - str(connection.port), - "--db", - connection.database, - "--user", - connection.user, - "--schema", - "public", - "--sslmode", - connection.sslmode, - *args, - ] - - -def run_pgschema( - command: str, - *args: str, - connection: Connection, - mounts: dict[Path, str] | None = None, -) -> int: - cmd = docker_command( - command, - *args, - connection=connection, - mounts={DB_DIR: "/db", **(mounts or {})}, - image=get_settings().pgschema_image, - ) - env = {**os.environ, "PGPASSWORD": connection.password} - return subprocess.run(cmd, env=env, check=False).returncode - - -def format_schema() -> None: - """Fix what sqlfluff can, then lint so what is left shows its file and rule.""" - for action in ("fix", "lint"): - subprocess.run( - [sys.executable, "-m", "sqlfluff", action, str(SCHEMA_DIR)], - cwd=API_DIR, - check=False, - ) - - -def next_migration_path() -> Path: - MIGRATIONS_DIR.mkdir(parents=True, exist_ok=True) - numbers = [ - int(f.stem) for f in MIGRATIONS_DIR.glob("[0-9][0-9][0-9][0-9][0-9][0-9].sql") - ] - return MIGRATIONS_DIR / f"{max(numbers, default=0) + 1:06d}.sql" - - -def plan_sql(connection: Connection, out_dir: Path) -> tuple[int, str]: - out_dir.mkdir(parents=True, exist_ok=True) - out_dir.chmod(0o777) - returncode = run_pgschema( - "plan", - "--file", - MANIFEST, - "--output-json", - "/out/plan.json", - "--output-sql", - "/out/plan.sql", - connection=connection, - mounts={out_dir: "/out"}, - ) - sql_file = out_dir / "plan.sql" - return returncode, sql_file.read_text() if sql_file.is_file() else "" +TARGET = schema.Target( + name="hackproof", db_dir=DB_DIR, image=get_settings().pgschema_image +) def plan(connection: Connection, *, format: bool = True) -> int: - if format: - format_schema() - generate_manifest(SCHEMA_DIR) - path = next_migration_path() - returncode = run_pgschema( - "plan", - "--file", - MANIFEST, - "--output-sql", - f"/db/migrations/{path.name}", - connection=connection, - ) - if returncode != 0: - return returncode - if not path.is_file() or path.stat().st_size == 0: - path.unlink(missing_ok=True) - print("No changes detected.") - return 0 - print(f"Wrote the migration plan to {path.relative_to(ROOT)}") - return 0 + return schema.plan(connection, format=format, target=TARGET) def apply( @@ -139,51 +24,13 @@ def apply( allow_destructive: bool = False, out_dir: Path | None = None, ) -> int: - generate_manifest(SCHEMA_DIR) - with TemporaryDirectory() as scratch: - target = out_dir or Path(scratch) - target.mkdir(parents=True, exist_ok=True) - returncode, sql = plan_sql(connection, target) - if returncode != 0: - return returncode - if not sql.strip(): - print(f"No changes: {connection.label} already matches the schema files.") - return 0 - print(f"Pending changes for {connection.label}:\n\n{sql}") - findings = destructive_statements(sql) - if findings and not allow_destructive: - print("Refusing to apply: the plan could lose data.", file=sys.stderr) - for finding in findings: - print(f" {finding.reason}: {finding.statement}", file=sys.stderr) - return 2 - return run_pgschema( - "apply", - "--plan", - "/out/plan.json", - "--auto-approve", - "--lock-timeout", - LOCK_TIMEOUT, - connection=connection, - mounts={target: "/out"}, - ) + return schema.apply( + connection, + allow_destructive=allow_destructive, + out_dir=out_dir, + target=TARGET, + ) def verify(connection: Connection) -> int: - manifest = SCHEMA_DIR / "manifest.sql" - if not manifest.is_file() or manifest.read_text() != manifest_text(SCHEMA_DIR): - print( - "manifest.sql is out of date: run `hackproof schema plan`.", file=sys.stderr - ) - return 1 - with TemporaryDirectory() as scratch: - returncode, sql = plan_sql(connection, Path(scratch)) - if returncode != 0: - return returncode - if sql.strip(): - print( - f"{connection.label} differs from the schema files:\n\n{sql}", - file=sys.stderr, - ) - return 1 - print(f"In sync: {connection.label} matches the schema files.") - return 0 + return schema.verify(connection, TARGET) diff --git a/apps/api/src/hackproof/db_utils/sqlfluff/__init__.py b/apps/api/src/hackproof/db_utils/sqlfluff/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/api/src/hackproof/db_utils/sqlfluff/plugin.py b/apps/api/src/hackproof/db_utils/sqlfluff/plugin.py deleted file mode 100644 index 8d7d26c..0000000 --- a/apps/api/src/hackproof/db_utils/sqlfluff/plugin.py +++ /dev/null @@ -1,9 +0,0 @@ -from sqlfluff.core.plugin import hookimpl -from sqlfluff.core.rules import BaseRule - - -@hookimpl -def get_rules() -> list[type[BaseRule]]: - from hackproof.db_utils.sqlfluff.rules import Rule_Hackproof_CT01 - - return [Rule_Hackproof_CT01] diff --git a/apps/api/src/hackproof/db_utils/sqlfluff/rules.py b/apps/api/src/hackproof/db_utils/sqlfluff/rules.py deleted file mode 100644 index 3a3b513..0000000 --- a/apps/api/src/hackproof/db_utils/sqlfluff/rules.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlfluff.core.rules import BaseRule, LintFix, LintResult, RuleContext -from sqlfluff.core.rules.crawlers import SegmentSeekerCrawler - - -class Rule_Hackproof_CT01(BaseRule): - """Enforce upper-case CREATE TYPE names.""" - - name = "custom.create_type_upper" - groups = ("all",) - crawl_behaviour = SegmentSeekerCrawler({"create_type_statement"}) - is_fix_compatible = True - - def _eval(self, context: RuleContext) -> LintResult | None: - identifier = next(context.segment.recursive_crawl("data_type_identifier"), None) - if identifier is None: - return None - - raw = identifier.raw - if raw == raw.upper(): - return None - - return LintResult( - anchor=identifier, - fixes=[LintFix.replace(identifier, [identifier.edit(raw.upper())])], - description=f"CREATE TYPE names must be upper case: '{raw}' -> '{raw.upper()}'.", - ) diff --git a/apps/api/src/hackproof/github/client.py b/apps/api/src/hackproof/github/client.py deleted file mode 100644 index b0339c1..0000000 --- a/apps/api/src/hackproof/github/client.py +++ /dev/null @@ -1,168 +0,0 @@ -import asyncio -import time -from typing import Any, Literal - -import httpx -from pydantic import BaseModel, Field - -API = "https://api.github.com" -RAW = "https://raw.githubusercontent.com" -SEARCH_INTERVAL = {"code": 6.5, "repositories": 2.2} -RETRYABLE = {403, 429, 500, 502, 503, 504} -ABSENT = {404, 409, 451} -ATTEMPTS = 6 - -Search = Literal["code", "repositories"] -Resource = Literal["core", "graphql"] - - -class GithubUnavailable(Exception): - pass - - -class Token(BaseModel): - value: str | None - budget: dict[str, int] = Field( - default_factory=lambda: {"core": 5000, "graphql": 5000} - ) - blocked_until: float = 0.0 - next_search_at: dict[str, float] = Field( - default_factory=lambda: {"code": 0.0, "repositories": 0.0} - ) - - -class GithubClient: - def __init__(self, http: httpx.AsyncClient, tokens: list[str]) -> None: - self._http = http - self._tokens = [Token(value=value) for value in tokens] or [Token(value=None)] - self._lock = asyncio.Lock() - self._raw_resume_at = 0.0 - - async def _acquire(self, search: Search | None, resource: Resource) -> Token: - while True: - async with self._lock: - now = time.monotonic() - usable = [ - t - for t in self._tokens - if t.blocked_until <= now and t.budget[resource] > 20 - ] - if usable and search is None: - return max(usable, key=lambda t: t.budget[resource]) - if usable: - token = min(usable, key=lambda t: t.next_search_at[search]) - start = max(token.next_search_at[search], now) - token.next_search_at[search] = start + SEARCH_INTERVAL[search] - wait = start - now - else: - token = None - wait = max(min(t.blocked_until for t in self._tokens) - now, 1) - await asyncio.sleep(wait) - if token is not None: - return token - - @staticmethod - def _record(token: Token, response: httpx.Response) -> None: - remaining = response.headers.get("x-ratelimit-remaining") - resource = response.headers.get("x-ratelimit-resource") - if remaining is not None and resource in token.budget: - token.budget[resource] = int(remaining) - if response.status_code in (403, 429) and remaining == "0": - reset = int(response.headers.get("x-ratelimit-reset", time.time() + 60)) - token.blocked_until = time.monotonic() + max(reset - time.time(), 1) - elif response.status_code in (403, 429) and "retry-after" in response.headers: - token.blocked_until = time.monotonic() + int( - response.headers["retry-after"] - ) - - async def _send( - self, - method: str, - url: str, - *, - search: Search | None = None, - resource: Resource = "core", - **options: Any, - ) -> httpx.Response: - for attempt in range(ATTEMPTS): - token = await self._acquire(search, resource) - headers = {"Accept": "application/vnd.github+json"} - if token.value: - headers["Authorization"] = f"Bearer {token.value}" - try: - response = await self._http.request( - method, url, headers=headers, **options - ) - except httpx.TransportError: - await asyncio.sleep(2**attempt / 2) - continue - self._record(token, response) - if response.status_code in RETRYABLE: - await asyncio.sleep(2**attempt / 4) - continue - return response - raise GithubUnavailable(url) - - async def get( - self, - path: str, - params: dict[str, Any] | None = None, - *, - search: Search | None = None, - ) -> httpx.Response | None: - response = await self._send("GET", f"{API}{path}", search=search, params=params) - if response.status_code in ABSENT: - return None - response.raise_for_status() - return response - - async def json( - self, - path: str, - params: dict[str, Any] | None = None, - *, - search: Search | None = None, - ) -> Any | None: - response = await self.get(path, params, search=search) - if response is None or response.status_code == 204: - return None - return response.json() - - async def graphql(self, query: str) -> dict[str, Any]: - for attempt in range(ATTEMPTS): - response = await self._send( - "POST", f"{API}/graphql", resource="graphql", json={"query": query} - ) - try: - payload = response.json() - except ValueError: - await asyncio.sleep(2**attempt / 2) - continue - errors = [ - e for e in payload.get("errors", []) if e.get("type") != "NOT_FOUND" - ] - if errors or "data" not in payload: - await asyncio.sleep(2**attempt / 2) - continue - return payload["data"] - raise GithubUnavailable("graphql") - - async def raw( - self, full_name: str, ref: str, path: str, limit: int = 512_000 - ) -> bytes | None: - url = f"{RAW}/{full_name}/{ref}/{path}" - for attempt in range(ATTEMPTS): - await asyncio.sleep(max(self._raw_resume_at - time.monotonic(), 0)) - try: - response = await self._http.get(url) - except httpx.TransportError: - await asyncio.sleep(2**attempt / 2) - continue - if response.status_code in RETRYABLE: - pause = float(response.headers.get("retry-after", 2 ** (attempt + 1))) - self._raw_resume_at = max(self._raw_resume_at, time.monotonic() + pause) - continue - if response.status_code != 200 or len(response.content) > limit: - return None - return response.content - raise GithubUnavailable(url) diff --git a/apps/api/src/hackproof/github/discovery.py b/apps/api/src/hackproof/github/discovery.py index 123e08a..6c85ed5 100644 --- a/apps/api/src/hackproof/github/discovery.py +++ b/apps/api/src/hackproof/github/discovery.py @@ -1,29 +1,22 @@ import asyncio import logging -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator from datetime import UTC, datetime, timedelta -from typing import Any import asyncpg +from trawl.github.client import GithubClient +from trawl.github.refs import normalize_repo +from trawl.github.search import code_slices, hits, patient, repository_slices -from hackproof.github.client import GithubClient, GithubUnavailable, Search from hackproof.github.models import Candidate from hackproof.github.repositories import fetch_repositories from hackproof.hackathon import Discovery, Window from hackproof.linking.country import resolve_country -from hackproof.linking.repo_ref import normalize_repo from hackproof.sql_loader import load_sql log = logging.getLogger("hackproof.discovery") -PAGE_SIZE = 100 -RESULT_CAP = 1000 -SIZE_CEILING = 400_000 PINNED_VIA = "wasm_meta" -OUTAGE_ROUNDS = 5 -OUTAGE_PAUSE = 60 - -Count = Callable[[int, int], Awaitable[int]] def is_pinned(candidate: Candidate) -> bool: @@ -47,79 +40,6 @@ def should_keep(candidate: Candidate, window: Window, discovery: Discovery) -> b ) -async def split_range( - lo: int, hi: int, count: Count, cap: int = RESULT_CAP -) -> list[tuple[int, int]]: - if lo >= hi or await count(lo, hi) <= cap: - return [(lo, hi)] - middle = (lo + hi) // 2 - left, right = await asyncio.gather( - split_range(lo, middle, count, cap), split_range(middle + 1, hi, count, cap) - ) - return left + right - - -def _stamp(seconds: int) -> str: - return datetime.fromtimestamp(seconds, UTC).strftime("%Y-%m-%dT%H:%M:%SZ") - - -async def _total(github: GithubClient, path: str, query: str, kind: Search) -> int: - data = await github.json(path, {"q": query, "per_page": 1}, search=kind) - return data["total_count"] if data else 0 - - -async def repository_slices( - github: GithubClient, query: str, since: datetime, until: datetime -) -> list[str]: - async def count(lo: int, hi: int) -> int: - pushed = f"pushed:{_stamp(lo)}..{_stamp(hi)}" - return await _total( - github, "/search/repositories", f"{query} {pushed}", "repositories" - ) - - ranges = await split_range(int(since.timestamp()), int(until.timestamp()), count) - return [f"{query} pushed:{_stamp(lo)}..{_stamp(hi)}" for lo, hi in ranges] - - -async def code_slices(github: GithubClient, query: str) -> list[str]: - if await _total(github, "/search/code", query, "code") <= RESULT_CAP: - return [query] - - async def count(lo: int, hi: int) -> int: - return await _total(github, "/search/code", f"{query} size:{lo}..{hi}", "code") - - return [ - f"{query} size:{lo}..{hi}" - for lo, hi in await split_range(0, SIZE_CEILING, count) - ] - - -async def _hits( - github: GithubClient, path: str, query: str, kind: Search -) -> list[dict[str, Any]]: - items: list[dict[str, Any]] = [] - for page in range(1, RESULT_CAP // PAGE_SIZE + 1): - data = await github.json( - path, {"q": query, "per_page": PAGE_SIZE, "page": page}, search=kind - ) - batch = data["items"] if data else [] - items.extend(batch) - if len(batch) < PAGE_SIZE: - break - return items - - -async def patient(query: str, run: Callable[[str], Awaitable[None]]) -> None: - for _ in range(OUTAGE_ROUNDS): - try: - await run(query) - return - except GithubUnavailable: - log.warning("github unreachable, retrying in %ss: %s", OUTAGE_PAUSE, query) - await asyncio.sleep(OUTAGE_PAUSE) - log.error("gave up after %s rounds: %s", OUTAGE_ROUNDS, query) - - async def _collect( github: GithubClient, found: dict[str, set[str]], @@ -134,7 +54,7 @@ def note(name: str, via: str) -> None: async def repository_query(query: str) -> None: slices = await repository_slices(github, query, since, until) for sliced in slices: - for item in await _hits( + for item in await hits( github, "/search/repositories", sliced, "repositories" ): note(item["full_name"], f"search:{query}") @@ -143,7 +63,7 @@ async def repository_query(query: str) -> None: async def code_query(query: str) -> None: slices = await code_slices(github, query) for sliced in slices: - for item in await _hits(github, "/search/code", sliced, "code"): + for item in await hits(github, "/search/code", sliced, "code"): note(item["repository"]["full_name"], f"code:{query}") log.info("code search done: %s slices, %s", len(slices), query) diff --git a/apps/api/src/hackproof/github/files.py b/apps/api/src/hackproof/github/files.py index c98cd46..cb16915 100644 --- a/apps/api/src/hackproof/github/files.py +++ b/apps/api/src/hackproof/github/files.py @@ -1,7 +1,7 @@ import asyncio import json -from hackproof.github.client import GithubClient, GithubUnavailable +from trawl.github.client import GithubClient, GithubUnavailable BATCH = 25 CONCURRENCY = 6 diff --git a/apps/api/src/hackproof/github/history.py b/apps/api/src/hackproof/github/history.py index 60132e7..9fc202a 100644 --- a/apps/api/src/hackproof/github/history.py +++ b/apps/api/src/hackproof/github/history.py @@ -2,7 +2,8 @@ from datetime import datetime from pathlib import PurePosixPath -from hackproof.github.client import GithubClient +from trawl.github.client import GithubClient + from hackproof.github.dependencies import MANIFESTS, SKIP_DIRECTORIES, fingerprint MAX_MANIFESTS = 60 diff --git a/apps/api/src/hackproof/github/jobs.py b/apps/api/src/hackproof/github/jobs.py index cc3e390..a418790 100644 --- a/apps/api/src/hackproof/github/jobs.py +++ b/apps/api/src/hackproof/github/jobs.py @@ -2,10 +2,10 @@ import logging import httpx +from trawl.github.client import GithubClient, GithubUnavailable from hackproof.config import get_settings from hackproof.db import open_pool, pool -from hackproof.github.client import GithubClient, GithubUnavailable from hackproof.github.discovery import discover, store_candidates, wasm_meta_repos from hackproof.github.models import Candidate from hackproof.github.profiles import resolve_profiles diff --git a/apps/api/src/hackproof/github/profiles.py b/apps/api/src/hackproof/github/profiles.py index 612b4bb..34cb8be 100644 --- a/apps/api/src/hackproof/github/profiles.py +++ b/apps/api/src/hackproof/github/profiles.py @@ -1,8 +1,8 @@ import json import asyncpg +from trawl.github.client import GithubClient -from hackproof.github.client import GithubClient from hackproof.linking.country import resolve_country from hackproof.sql_loader import load_sql diff --git a/apps/api/src/hackproof/github/repositories.py b/apps/api/src/hackproof/github/repositories.py index 915934a..a503566 100644 --- a/apps/api/src/hackproof/github/repositories.py +++ b/apps/api/src/hackproof/github/repositories.py @@ -4,7 +4,8 @@ from collections.abc import Iterable from typing import Any -from hackproof.github.client import GithubClient, GithubUnavailable +from trawl.github.client import GithubClient, GithubUnavailable + from hackproof.github.models import Candidate from hackproof.hackathon import Window diff --git a/apps/api/src/hackproof/github/scan.py b/apps/api/src/hackproof/github/scan.py index 675adf3..0d86c1d 100644 --- a/apps/api/src/hackproof/github/scan.py +++ b/apps/api/src/hackproof/github/scan.py @@ -6,8 +6,8 @@ import asyncpg import httpx +from trawl.github.client import GithubClient -from hackproof.github.client import GithubClient from hackproof.github.demo import scan_demo from hackproof.github.dependencies import MANIFESTS, SKIP_DIRECTORIES, fingerprint from hackproof.github.files import fetch_texts diff --git a/apps/api/src/hackproof/linking/reconcile.py b/apps/api/src/hackproof/linking/reconcile.py index 1a20ee2..2a02fc6 100644 --- a/apps/api/src/hackproof/linking/reconcile.py +++ b/apps/api/src/hackproof/linking/reconcile.py @@ -2,12 +2,12 @@ import asyncpg from pydantic import BaseModel +from trawl.github.refs import normalize_repo from hackproof.config import get_settings from hackproof.db import open_pool, pool from hackproof.hackathon import get_hackathon from hackproof.linking.methods import LinkMethod -from hackproof.linking.repo_ref import normalize_repo from hackproof.sql_loader import load_sql log = logging.getLogger("hackproof.reconcile") diff --git a/apps/api/src/hackproof/linking/repo_ref.py b/apps/api/src/hackproof/linking/repo_ref.py deleted file mode 100644 index 32cabcf..0000000 --- a/apps/api/src/hackproof/linking/repo_ref.py +++ /dev/null @@ -1,14 +0,0 @@ -import re - -REPO_PATTERN = re.compile( - r"^(?:(?:https?://)?(?:www\.)?github\.com/|github:)?" - r"(?P[A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))/" - r"(?P[A-Za-z0-9._-]+?)(?:\.git)?/?(?:[/#?].*)?$" -) - - -def normalize_repo(value: str) -> str | None: - match = REPO_PATTERN.match(value.strip()) - if match is None: - return None - return f"{match['owner']}/{match['repo']}" diff --git a/apps/api/src/hackproof/sql_loader.py b/apps/api/src/hackproof/sql_loader.py index 88cb0d8..f880882 100644 --- a/apps/api/src/hackproof/sql_loader.py +++ b/apps/api/src/hackproof/sql_loader.py @@ -1,9 +1,6 @@ -from functools import cache from pathlib import Path -SQL_DIR = Path(__file__).with_name("sql") - +from trawl.db.sql import sql_loader -@cache -def load_sql(name: str) -> str: - return (SQL_DIR / f"{name}.sql").read_text() +SQL_DIR = Path(__file__).with_name("sql") +load_sql = sql_loader(SQL_DIR) diff --git a/apps/api/tests/conftest.py b/apps/api/tests/conftest.py index fdbf25a..30686a4 100644 --- a/apps/api/tests/conftest.py +++ b/apps/api/tests/conftest.py @@ -5,9 +5,9 @@ import asyncpg import pytest +from trawl.schema.manifest import schema_sql from hackproof.config import get_settings -from hackproof.db_utils.manifest import schema_sql from hackproof.db_utils.pgschema import SCHEMA_DIR diff --git a/apps/api/tests/test_discovery.py b/apps/api/tests/test_discovery.py index 7d26e3b..0ba6e4a 100644 --- a/apps/api/tests/test_discovery.py +++ b/apps/api/tests/test_discovery.py @@ -1,8 +1,6 @@ from datetime import UTC, datetime -from hackproof.github import discovery -from hackproof.github.client import GithubUnavailable -from hackproof.github.discovery import is_pinned, patient, should_keep, split_range +from hackproof.github.discovery import is_pinned, should_keep from hackproof.github.models import Candidate from hackproof.hackathon import Discovery, Window @@ -61,61 +59,3 @@ def test_excluded_repos_stay_out_even_when_wasm_metadata_names_them(): WINDOW, DISCOVERY, ) - - -async def test_split_range_slices_until_every_range_fits_the_cap(): - matches = [value for value in range(0, 10_000, 7)] - - async def count(lo: int, hi: int) -> int: - return sum(1 for value in matches if lo <= value <= hi) - - ranges = await split_range(0, 10_000, count, cap=100) - counts = [await count(lo, hi) for lo, hi in ranges] - - assert max(counts) <= 100 - assert sum(counts) == len(matches) - assert ranges[0][0] == 0 and ranges[-1][1] == 10_000 - assert all(a[1] + 1 == b[0] for a, b in zip(ranges, ranges[1:], strict=False)) - - -async def test_split_range_stops_at_a_single_value_even_when_over_the_cap(): - async def count(lo: int, hi: int) -> int: - return 5_000 - - assert await split_range(7, 7, count, cap=10) == [(7, 7)] - - -async def test_split_range_leaves_small_queries_whole(): - async def count(lo: int, hi: int) -> int: - return 3 - - assert await split_range(0, 400_000, count) == [(0, 400_000)] - - -async def test_a_query_survives_a_connection_outage(monkeypatch): - async def instant(_seconds): - return None - - monkeypatch.setattr(discovery.asyncio, "sleep", instant) - runs: list[str] = [] - - async def flaky(query: str) -> None: - runs.append(query) - if len(runs) < 3: - raise GithubUnavailable(query) - - await patient("q", flaky) - - assert runs == ["q", "q", "q"] - - -async def test_a_query_that_never_recovers_is_skipped_not_fatal(monkeypatch): - async def instant(_seconds): - return None - - monkeypatch.setattr(discovery.asyncio, "sleep", instant) - - async def down(query: str) -> None: - raise GithubUnavailable(query) - - await patient("q", down) diff --git a/apps/api/tests/test_files.py b/apps/api/tests/test_files.py index 9eb774a..f8e0a25 100644 --- a/apps/api/tests/test_files.py +++ b/apps/api/tests/test_files.py @@ -1,6 +1,6 @@ import pytest +from trawl.github.client import GithubUnavailable -from hackproof.github.client import GithubUnavailable from hackproof.github.files import BATCH, _query, fetch_texts diff --git a/apps/api/tests/test_pgschema.py b/apps/api/tests/test_pgschema.py index 2657665..fe85438 100644 --- a/apps/api/tests/test_pgschema.py +++ b/apps/api/tests/test_pgschema.py @@ -1,141 +1,8 @@ -import sys -from pathlib import Path - -import pytest +from trawl.schema.manifest import manifest_text from hackproof.db_utils import pgschema -from hackproof.db_utils.connection import Connection -from hackproof.db_utils.guard import destructive_statements -from hackproof.db_utils.manifest import manifest_text, order_by_dependency from hackproof.linking.methods import LinkMethod -NEON = "postgresql://owner:p%40ss@ep-cool-1234.us-east-2.aws.neon.tech/hackproof?sslmode=require&channel_binding=require" - - -def write(root: Path, files: dict[str, str]) -> Path: - for name, text in files.items(): - path = root / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text) - return root - - -def test_a_connection_is_read_from_a_url(): - connection = Connection.from_url(NEON) - - assert connection.host == "ep-cool-1234.us-east-2.aws.neon.tech" - assert connection.port == 5432 - assert connection.user == "owner" - assert connection.password == "p@ss" - assert connection.database == "hackproof" - assert connection.sslmode == "require" - assert not connection.is_local - - -def test_every_part_of_a_remote_url_is_masked_in_ci_logs(): - lines = Connection.from_url(NEON).mask_lines() - - assert "::add-mask::ep-cool-1234.us-east-2.aws.neon.tech" in lines - assert "::add-mask::owner" in lines - assert "::add-mask::p@ss" in lines - assert "::add-mask::p%40ss" in lines - - -def test_a_local_database_is_reached_through_the_host_the_container_can_see( - monkeypatch, -): - local = Connection.from_url("postgresql://u:p@localhost:5440/hackproof") - - monkeypatch.setattr(sys, "platform", "darwin") - assert local.container_route() == ( - ["--add-host", "host.docker.internal:host-gateway"], - "host.docker.internal", - ) - monkeypatch.setattr(sys, "platform", "linux") - assert local.container_route() == (["--network", "host"], "localhost") - assert Connection.from_url(NEON).container_route() == ( - [], - "ep-cool-1234.us-east-2.aws.neon.tech", - ) - - -def test_the_password_never_appears_in_the_docker_command(tmp_path): - connection = Connection.from_url(NEON) - - command = pgschema.docker_command( - "plan", - "--file", - "/db/schema/manifest.sql", - connection=connection, - mounts={tmp_path: "/db"}, - image="pgplex/pgschema:1.14.1", - ) - - assert not any("p@ss" in part or "p%40ss" in part for part in command) - assert command[command.index("-e") + 1] == "PGPASSWORD" - assert command[command.index("--sslmode") + 1] == "require" - assert f"{tmp_path}:/db" in command - - -@pytest.mark.parametrize( - "sql", - [ - "DROP TABLE IF EXISTS wasm_repos CASCADE;", - "ALTER TABLE repos DROP COLUMN stars;", - "ALTER TABLE repos ALTER COLUMN stars TYPE bigint;", - "alter table repos drop column stars;", - "TRUNCATE contracts;", - "DELETE FROM projects;", - ], -) -def test_the_guard_flags_statements_that_can_lose_data(sql): - assert destructive_statements(sql) - - -def test_the_guard_lets_additive_and_data_safe_changes_through(): - sql = """ - CREATE TABLE notes (id text PRIMARY KEY); - ALTER TABLE repos ADD COLUMN notes text; - CREATE INDEX notes_id ON notes (id); - DROP INDEX IF EXISTS contracts_wasm; - DROP VIEW IF EXISTS attribution; - DROP FUNCTION IF EXISTS method_rank(text); - ALTER TABLE repos DROP CONSTRAINT repos_pkey; - -- DROP TABLE contracts; - """ - - assert destructive_statements(sql) == [] - - -def test_tables_load_after_the_tables_they_reference(tmp_path): - root = write( - tmp_path, - { - "a_child.sql": "CREATE TABLE a_child (p text REFERENCES z_parent (id));", - "z_parent.sql": "CREATE TABLE z_parent (id text PRIMARY KEY);", - }, - ) - - assert [f.name for f in order_by_dependency("tables", root)] == [ - "z_parent.sql", - "a_child.sql", - ] - - -def test_views_load_after_the_views_they_select_from(tmp_path): - root = write( - tmp_path, - { - "account_projects.sql": "CREATE OR REPLACE VIEW account_projects AS SELECT 1 FROM attribution;", - "attribution.sql": "CREATE OR REPLACE VIEW attribution AS SELECT 1 FROM links;", - }, - ) - - assert [f.name for f in order_by_dependency("views", root)] == [ - "attribution.sql", - "account_projects.sql", - ] - def test_the_committed_manifest_matches_the_schema_files(): committed = (pgschema.SCHEMA_DIR / "manifest.sql").read_text() @@ -143,54 +10,12 @@ def test_the_committed_manifest_matches_the_schema_files(): assert committed == manifest_text(pgschema.SCHEMA_DIR) -def test_migrations_are_numbered_one_after_another(tmp_path, monkeypatch): - monkeypatch.setattr(pgschema, "MIGRATIONS_DIR", tmp_path) - assert pgschema.next_migration_path().name == "000001.sql" - - write(tmp_path, {"000001.sql": "x", "000002.sql": "y", "notes.md": "z"}) - assert pgschema.next_migration_path().name == "000003.sql" +def test_the_target_points_at_this_projects_database_files(): + assert pgschema.TARGET.schema_dir == pgschema.SCHEMA_DIR + assert pgschema.TARGET.migrations_dir == pgschema.MIGRATIONS_DIR async def test_the_sql_method_rank_follows_the_python_order(scratch_db): for position, method in enumerate(LinkMethod, start=1): assert await scratch_db.fetchval("SELECT method_rank($1)", method) == position assert await scratch_db.fetchval("SELECT method_rank('unknown')") is None - - -def test_apply_runs_the_reviewed_plan_with_a_lock_timeout(monkeypatch, tmp_path): - seen = [] - monkeypatch.setattr( - pgschema, - "run_pgschema", - lambda command, *args, **kwargs: seen.append((command, args)) or 0, - ) - monkeypatch.setattr( - pgschema, "plan_sql", lambda *_: (0, "CREATE TABLE x (id text);") - ) - monkeypatch.setattr(pgschema, "generate_manifest", lambda *_: None) - - code = pgschema.apply(Connection.from_url(NEON), out_dir=tmp_path) - - assert code == 0 - command, args = seen[0] - assert command == "apply" - assert args[:2] == ("--plan", "/out/plan.json") - assert args[args.index("--lock-timeout") + 1] == "30s" - - -def test_apply_refuses_a_plan_that_drops_data_and_never_runs_it(monkeypatch, tmp_path): - ran = [] - monkeypatch.setattr(pgschema, "run_pgschema", lambda *a, **k: ran.append(a) or 0) - monkeypatch.setattr(pgschema, "plan_sql", lambda *_: (0, "DROP TABLE contracts;")) - monkeypatch.setattr(pgschema, "generate_manifest", lambda *_: None) - - code = pgschema.apply(Connection.from_url(NEON), out_dir=tmp_path) - - assert code == 2 - assert ran == [] - assert ( - pgschema.apply( - Connection.from_url(NEON), allow_destructive=True, out_dir=tmp_path - ) - == 0 - ) diff --git a/apps/api/tests/test_repo_ref.py b/apps/api/tests/test_repo_ref.py deleted file mode 100644 index d4b80eb..0000000 --- a/apps/api/tests/test_repo_ref.py +++ /dev/null @@ -1,19 +0,0 @@ -import pytest - -from hackproof.linking.repo_ref import normalize_repo - - -@pytest.mark.parametrize( - ("raw", "expected"), - [ - ("github:acme/vault", "acme/vault"), - ("https://github.com/acme/vault", "acme/vault"), - ("https://github.com/acme/vault.git", "acme/vault"), - ("https://github.com/acme/vault/tree/main/contracts", "acme/vault"), - ("acme/vault", "acme/vault"), - ("https://gitlab.com/acme/vault", None), - ("not a repo", None), - ], -) -def test_normalize_repo(raw, expected): - assert normalize_repo(raw) == expected diff --git a/apps/api/uv.lock b/apps/api/uv.lock index 7d32e7c..6ee9a3e 100644 --- a/apps/api/uv.lock +++ b/apps/api/uv.lock @@ -628,6 +628,7 @@ dependencies = [ { name = "pydantic-settings" }, { name = "pyyaml" }, { name = "stellar-sdk" }, + { name = "trawl" }, ] [package.dev-dependencies] @@ -649,6 +650,7 @@ requires-dist = [ { name = "pydantic-settings", specifier = ">=2.16.1" }, { name = "pyyaml", specifier = ">=6.0.3" }, { name = "stellar-sdk", specifier = ">=16.1.1" }, + { name = "trawl", url = "https://github.com/devodii/trawl/releases/download/v0.1.0/trawl-0.1.0-py3-none-any.whl" }, ] [package.metadata.requires-dev] @@ -1956,6 +1958,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, ] +[[package]] +name = "trawl" +version = "0.1.0" +source = { url = "https://github.com/devodii/trawl/releases/download/v0.1.0/trawl-0.1.0-py3-none-any.whl" } +dependencies = [ + { name = "asyncpg" }, + { name = "httpx" }, + { name = "pydantic" }, + { name = "pyyaml" }, +] +wheels = [ + { url = "https://github.com/devodii/trawl/releases/download/v0.1.0/trawl-0.1.0-py3-none-any.whl", hash = "sha256:bb57971034beafdca321ce3092ebe21664aadfca1694cc5788a3fc11257f6cab" }, +] + +[package.metadata] +requires-dist = [ + { name = "asyncpg", specifier = ">=0.32.0" }, + { name = "duckdb", marker = "extra == 'stellar'", specifier = ">=1.2.0" }, + { name = "httpx", specifier = ">=0.28.1" }, + { name = "pydantic", specifier = ">=2.11.0" }, + { name = "pyyaml", specifier = ">=6.0.3" }, + { name = "sqlfluff", marker = "extra == 'sql'", specifier = ">=4.5.0" }, + { name = "stellar-sdk", marker = "extra == 'stellar'", specifier = ">=17.0.1" }, + { name = "tree-sitter", marker = "extra == 'parse'", specifier = ">=0.25.0" }, + { name = "tree-sitter-rust", marker = "extra == 'parse'", specifier = ">=0.24.0" }, + { name = "tree-sitter-toml", marker = "extra == 'parse'", specifier = ">=0.7.0" }, +] +provides-extras = ["parse", "sql", "stellar"] + [[package]] name = "truststore" version = "0.10.5"