diff --git a/.github/workflows/magpie.yml b/.github/workflows/magpie.yml new file mode 100644 index 0000000..c60eb90 --- /dev/null +++ b/.github/workflows/magpie.yml @@ -0,0 +1,63 @@ +name: magpie + +on: + workflow_dispatch: + inputs: + steps: + description: What to run (all = crawl, then promote) + type: choice + options: [crawl, promote, all, reextract] + default: crawl + dry-run: + description: Log every write without making it + type: boolean + default: true + # Off until supabase migration 20261119000000_ingest_schema is applied, a + # dry run has been checked, and the time and limits are decided. Scheduled + # runs write. + # To turn it on: + # schedule: + # - cron: '0 4 * * *' + +concurrency: + group: magpie + cancel-in-progress: false + +env: + SUPABASE_URL: ${{ secrets.SUPABASE_URL }} + SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }} + DRY_RUN: ${{ github.event_name != 'schedule' && inputs.dry-run && '--dry-run' || '' }} + +jobs: + magpie: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7 + + - uses: astral-sh/setup-uv@v10.3.3 + with: + enable-cache: true + + - name: Install dependencies + run: uv sync --locked --no-dev + + # One crawl run: list both boards, fetch due threads, extract + # candidates. A listing that fails writes nothing and fails the job; + # failed thread fetches are routine and only listed. + - name: Crawl Geekhack + if: github.event_name == 'schedule' || inputs.steps == 'crawl' || inputs.steps == 'all' + run: uv run magpie crawl $DRY_RUN + + # Extract every stored first post again (after EXTRACTOR_VERSION is + # bumped), without requests to Geekhack. Manual only. + - name: Extract stored threads again + if: github.event_name == 'workflow_dispatch' && inputs.steps == 'reextract' + run: uv run magpie reextract $DRY_RUN + + # Manual only, never on schedule: an IC and its GB are two candidates + # (duplicate keysets), and covers and kits are not reliable enough for + # the review queue until Keebdex has a Discovered tab. + - name: Propose complete keysets to Keebdex + if: github.event_name == 'workflow_dispatch' && (inputs.steps == 'promote' || inputs.steps == 'all') + run: uv run magpie promote $DRY_RUN diff --git a/AGENTS.md b/AGENTS.md index d9877da..e50bcb1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,8 +25,9 @@ separate repository). - `config.py`: `require_env(name)` for settings. - `db.py`: `create_supabase(source=None)`, the only way to create a Supabase client, and `revision_source(job, origin)` for its source (see "Revision - sources"); `fetch_all(client, table, columns, where)` - for every paged read; `PUBLISHED_FILTER` (Keebdex's published rule); `Row`. + sources"); `fetch_all(client, table, columns, where, order)` for every paged + read (also on `client.schema("ingest")`); `PUBLISHED_FILTER` (Keebdex's + published rule); `Row`. - `pool.py`: `run_each(items, work)`, network work a few at a time (`CONCURRENCY`), counting failures. - `http.py`: `create_http_client()` for reading websites. @@ -46,7 +47,7 @@ separate repository). - `src/aviary/lorikeet/`: reference color palettes. `ral.py` crawls ralcolorchart.com, `sync.py` plans and writes the `colors` rows, `__main__.py` is the `lorikeet` command. -- `src/aviary/bowerbird/`: the artisan sync, ported from `../catalog-sync`. +- `src/aviary/bowerbird/`: the artisan sync, ported from catalog-sync (archived). `gdoc/` holds the Google Docs side (`parser.py`, `dates.py`, `jsregex.py`, `google.py` for the read-only API calls, `importer.py`); `jsregex.py` also holds JavaScript's whitespace (`JS_WHITESPACE`, `js_trim`), and per-maker name @@ -59,8 +60,16 @@ separate repository). catalog-sync's image jobs. `references.py` (`IMAGE_COLUMNS`, which images the database references), `sync.py`, `maintenance.py` (restore, prune, backup), `__main__.py` the `pelican` command. See "Images and backups". -- Planned, not yet here: `magpie` (forum crawler writing to the `ingest` schema - for staff review). Create a module only when its first real code lands. +- `src/aviary/magpie/`: the Geekhack crawler, ported from huginn without its + web UI. `geekhack.py` (boards, topic URLs, `normalize_image_url`), `fetch.py` + (the polite `Fetcher`), `parsers.py` (board list and first post), `kits.py`, + `classify.py` (title to kind and profile code), `proposal.py` (thread to + keyset candidate, `EXTRACTOR_VERSION`), `plan.py` (listings, fetch schedule, + promotions, pure), `ingest.py` (reads and writes of the `ingest` tables), + `keebdex.py` (keyset and profile reads, the promotion writes), one module + per command (`crawl.py`, `promote.py`, `reextract.py`) with `summary.py` + for what their job summaries share, and `__main__.py` the `magpie` command + line (arguments, `topic`). See "Forum crawl". ## Commands @@ -74,6 +83,10 @@ separate repository). - `uv run --env-file .env bowerbird gdoc|scrape [--maker ID] [--dry-run]`. - `uv run --env-file .env pelican sync|restore|prune|backup [--dry-run]` (`restore --force`, `backup --limit N --force-trash`). +- `uv run --env-file .env magpie crawl [--board B] [--max-pages N] + [--fetch-limit N] [--dry-run]`, `magpie promote [--limit N] + [--max-age-days N] [--dry-run]`, `magpie reextract [--limit N] + [--dry-run]`; `uv run magpie topic ` (no database). ## Rules for jobs @@ -93,6 +106,7 @@ separate repository). (lorikeet's schedule is paused). bowerbird and pelican run at catalog-sync's old times: bowerbird at 23:00 UTC, pelican sync and restore at 01:00, backup and the database dump at 02:00, prune at 00:00 on the 1st and the 15th. + magpie has no schedule until its schema is applied. ## Revision sources @@ -111,9 +125,11 @@ per process). `create_supabase(source)` sends them when `source` is given. - `lorikeet` writes only `colors`, which has no revisions, and sends no source. - `bowerbird gdoc` sends `bowerbird.gdoc`; `bowerbird scrape` gives each maker a client of its own sending `bowerbird.`; `pelican sync` sends - `pelican.cloudflare-images`; `magpie` will send `magpie.` - (`magpie.geekhack`, `magpie.novelkeys`). These are not the `source` column of - the artisan rows (`gdoc`, `scraper`), which says which sync owns a row. + `pelican.cloudflare-images`. These are not the `source` column of the artisan + rows (`gdoc`, `scraper`), which says which sync owns a row. +- `magpie promote` sends `magpie.geekhack`, the forum its candidates come from + (a vendor store would be `magpie.novelkeys`); `magpie crawl` writes only + `ingest` and sends none. ## Artisan sync @@ -229,6 +245,93 @@ source: it is JavaScript's `undefined` versus `null`. all incoming colorways, not per sculpt. Gaps are harmless: only the relative order matters. +## Forum crawl + +`magpie` is huginn (a crawler with a web UI for reviewing Geekhack topics by +hand) as a batch job. Its parsers were checked against huginn's on saved and +live pages; the choices huginn's UI left to a person are now made from the +topic, and staff review the result in Keebdex instead. + +- Its data lives in the `ingest` schema of supabase migration + `20261119000000_ingest_schema.sql` (read its header before changing what + magpie writes): `threads` (listing, first post, fetch queue), `candidates` + (extractions waiting for triage), `crawl_runs`. Staff read and triage them + from the app under RLS; magpie uses the service role. The schema must be + exposed through the Data API. +- `crawl` is one `crawl_runs` row (one running at a time; a run running for + over an hour is marked failed). Each board is listed down to the watermark + of the last succeeded run (the newest last post it saw), its last page, or + `--max-pages`; a board the cap stopped is in `incomplete_boards` and keeps + its old watermark, or, when it never had one, gets the newest last post it + saw (what lies below is backlog, for one run with a higher `--max-pages`). + Every board is read before anything is written, and only a succeeded run + moves watermarks. Stickies are skipped. Geekhack times have + no zone and are stored as UTC. +- A listed thread is due (`next_fetch_at`) when new or when its last post + moved, gone ones included; otherwise the listing only refreshes it. A fetch + stores the `div.post` HTML (`raw_body`, `parsers.parse_post` reads it again) + and its hash (`changed_at` when it changes), then schedules the next fetch: + weekly while the thread is under 90 days old (edits don't bump a thread), + else on new activity only. A failure backs off from an hour, doubling, and + stops after 5 in a row until new activity starts the count over; a 404 sets + `gone_at`. Failures are routine and the run still succeeds. robots.txt is + retried like a page: a 4xx means no rules, unreachable fails the run. +- Each fetched keyset thread (by title, `classify.py`) gets a candidate: + `payload` shaped like the keyset submission (`keyset` columns, `kits`), + `confidence` per field, `match_key` when Keebdex has the keyset. The + `candidates_supersede` trigger drops an extraction already made (same + `EXTRACTOR_VERSION` and content) and supersedes the waiting one; when the + first post goes back to an earlier version it puts that superseded + extraction back to `new` (the summary counts these apart, from the state + read before the insert). Bump the version when `extract()` changes, then + run `reextract`. Keyboards are not extracted yet. +- `reextract` extracts every stored first post (`raw_body`) of threads + neither ignored nor gone again with the current `EXTRACTOR_VERSION` and + saves candidates as `crawl` does, without requests to Geekhack and without + a `crawl_runs` row (watermarks untouched). It refuses while a crawl runs; + running it twice adds nothing. +- Extraction: the title starts with `[GB]`, `[IC]` or `[Pre-order]` (status + by board, so a pre-order on the GB board is Confirmed), and its keycap code + must name exactly one published profile + (`profile_id`, then name: KKB is `keykobo`); a second code ("GMK MTNU + Dasher") picks that profile. The name drops the codes and the profile's name + ("GMK CYL Selene" is `gmk/selene`) and what follows ` | `, ` - `, ` : ` or + two spaces (where the listing dropped a dash), and notes in parentheses + (progress, new kits, "Previously ..."); the slug is `url_slugify`. Name and + slug confidence is 0.6: staff should read them. Status is + Interest Check on the IC board, Cancelled when the title says so, else + Confirmed; `ic_date` the IC's posting day; Cherry profiles get sculpt + `1-1-2-3-4-4`. Kits: one per labelled kit image (`kits.py`), else a Base kit + with the cover (the first image when no Base label), with `name` null (it + holds a kit's own name, never its category's). An image file on + `imgur.com` (a redirect page) is stored as its `i.imgur.com` file; a link + in the post that is not a URL is skipped, never failing the fetch. The + crawl summary lists keycap codes that name no Keebdex profile, with up to + 3 titles each, and keyset titles with no code: profiles staff may add. +- `promote` runs only by hand (the workflow's `promote` or `all`, never on + schedule) until Keebdex has a Discovered tab: an IC and its GB are two + candidates, so it can insert a keyset twice, and covers and kits are not + reliable enough for the review queue yet. It inserts, newest topic first + and at most `--limit`, the waiting candidates with no `match_key` whose + payload is complete (`missing_for_promotion`) and whose thread was posted + within `--max-age-days` and is neither ignored nor gone: the keyset and its + kits `Pending` with a null `submitted_by`, like catalog-sync's vendor keysets, + then the candidate `promoted` (`promoted_kind` keyset). Keebdex's keyset + queue lists kits, so when the kits fail, or staff triaged the candidate + meanwhile (the claim finds it no longer `new`; listed apart in the + summary, not a failure), the keyset just inserted and its kits are deleted + again. A claim that raises is read back first: the keyset stays when the + candidate is promoted to it or cannot be read, so no candidate points at a + deleted keyset. A failed delete is logged with the id for removal by hand + and the run goes on. A candidate whose keyset Keebdex has now (its topic's + URL in any `topic=` form, or its key, of any source or review status, or a + keyset this run inserts) gets that `match_key` and waits for staff as an + edit; keysets are never updated, a different status is only reported. + Everything else waits for staff. +- An empty read of keysets or profiles writes nothing; a failed promotion + makes `promote` exit 1. Images stay external: `pelican sync` uploads them + once staff approve. + ## Images and backups Image columns: `artisan_colorways.img`, `keysets.img` / `order_graph` / diff --git a/README.md b/README.md index 28da8d0..68535f1 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@ bird: | `lorikeet` | Adds reference color palettes (RAL) to Keebdex | Ready | | `bowerbird` | Syncs artisan catalogs from makers and Docs | Ready | | `pelican` | Keeps Keebdex's images on Cloudflare and in R2 | Ready | -| `magpie` | Crawls forum interest checks and group buys | Planned | +| `magpie` | Crawls forum interest checks and group buys | Porting | `bowerbird` and `pelican` took over the artisan sync and the image jobs from -[catalog-sync](https://github.com/keebdex/catalog-sync), which keeps only its -vendor keyset scraper, run by hand, until `magpie` replaces it. +[catalog-sync](https://github.com/keebdex/catalog-sync), now archived; `magpie` +replaces its vendor keyset scraper. ## Setup @@ -71,7 +71,7 @@ Design code up on ralcolorchart.com as it is typed. ## bowerbird Syncs artisan sculpts and colorways into Keebdex from makers' Google Docs and -maker websites. It is a port of catalog-sync's artisan sync, and replaces it in +maker websites. It is a port of catalog-sync's artisan sync, which it replaced in production. ```bash @@ -106,7 +106,7 @@ uv run --env-file .env bowerbird scrape --dry-run ## pelican Keeps Keebdex's images on Cloudflare Images and backed up in Cloudflare R2: a -port of catalog-sync's image jobs, which it replaces in production. +port of catalog-sync's image jobs, which it replaced in production. ```bash uv run --env-file .env pelican sync --dry-run @@ -127,6 +127,56 @@ uv run --env-file .env pelican sync --dry-run - `docs/backups.md` is the operator guide for the R2 bucket: its locks, the trash, and restoring by hand. +## magpie + +Crawls Geekhack's [Interest Checks](https://geekhack.org/index.php?board=132.0) +and [Group Buys](https://geekhack.org/index.php?board=70.0) boards into the +`ingest` schema of Keebdex's database, reads a keyset candidate out of each +keyset thread, and proposes the complete ones as Pending keysets for staff to +review in Keebdex's keyset Submissions. A port of huginn (a local crawler with +a web UI) without the UI: the choices huginn left to a person (profile, cover, +kits) are made from the topic, and what magpie can't settle waits in +`ingest.candidates` for staff. + +```bash +uv run --env-file .env magpie crawl --dry-run +``` + +```bash +uv run --env-file .env magpie promote --dry-run +``` + +```bash +uv run magpie topic 127176 +``` + +- `crawl` is one run (`ingest.crawl_runs`; one at a time). It lists both + boards (`--board` for one) down to the newest last post the previous + succeeded run saw, up to 5 pages each (`--max-pages`; run once with a large + value to backfill). Every page is read, about one a second, before anything + is written: a page that fails or shows no topics fails the run and writes + nothing. Then it fetches the first post of due threads (new, with new + replies, or a week since the last fetch while under 90 days old; 100 at most, + `--fetch-limit`), keeps the post as it is, and adds a keyset candidate: + profile, name, cover, kits, status, and a confidence per field. A topic that + fails is retried with backoff; one that answers 404 is marked gone. +- `promote` inserts, newest first and at most 25 per run (`--limit`), the + candidates magpie read completely (profile, name, cover, kits), posted in the + last 90 days (`--max-age-days`), that Keebdex doesn't have: a Pending keyset + with no submitter and its Pending kits (one per labelled kit image, or a Base + kit with the cover, so the keyset shows up in the review queue). A candidate + of a keyset Keebdex has (its URL, or the same profile and slug) gets that + keyset as its `match_key` and waits for staff, as do incomplete and older + ones; a different status is reported, never written. +- `topic` prints one topic as JSON and needs no database. +- Needs the `ingest` schema (migration `20261119000000_ingest_schema.sql` in + Keebdex's supabase repository), with `ingest` added to the Data API's exposed + schemas. Promoted keysets show in Keebdex's history under the + `magpie.geekhack` revision source. +- `.github/workflows/magpie.yml` runs the crawl, the promotion, or both from + the Actions tab, as a dry run unless the box is unticked. Its schedule is off + until the schema is applied and a dry run has been checked. + ## License [MIT](LICENSE) diff --git a/pyproject.toml b/pyproject.toml index f3944db..20940ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,7 @@ dependencies = [ [project.scripts] bowerbird = "aviary.bowerbird.__main__:main" lorikeet = "aviary.lorikeet.__main__:main" +magpie = "aviary.magpie.__main__:main" pelican = "aviary.pelican.__main__:main" [build-system] diff --git a/src/aviary/common/db.py b/src/aviary/common/db.py index a586da8..b9fef5c 100644 --- a/src/aviary/common/db.py +++ b/src/aviary/common/db.py @@ -6,6 +6,7 @@ from collections.abc import Callable from typing import Any +from postgrest import SyncPostgrestClient from supabase import Client, ClientOptions, create_client from aviary.common.config import require_env @@ -62,16 +63,19 @@ def create_supabase(source: str | None = None) -> Client: def fetch_all( - client: Client, + client: Client | SyncPostgrestClient, table: str, columns: str = "*", where: Callable = lambda query: query, + order: str = "id", ) -> list[Row]: - """Every row matching `where`, in pages ordered by id. Raises on any error - (supabase-py does): a partial read must never look like "nothing there".""" + """Every row matching `where`, in pages ordered by `order` (a column whose + values are unique among those rows). `client` may also be a schema's + client (`client.schema("ingest")`). Raises on any error (supabase-py + does): a partial read must never look like "nothing there".""" rows: list[Row] = [] while True: - query = where(client.table(table).select(columns)).order("id") + query = where(client.table(table).select(columns)).order(order) data = query.range(len(rows), len(rows) + PAGE_SIZE - 1).execute().data rows += data if len(data) < PAGE_SIZE: diff --git a/src/aviary/magpie/__init__.py b/src/aviary/magpie/__init__.py new file mode 100644 index 0000000..9c29f96 --- /dev/null +++ b/src/aviary/magpie/__init__.py @@ -0,0 +1,2 @@ +"""magpie: crawls Geekhack's Interest Check and Group Buy boards into the +`ingest` schema and proposes the keysets it finds to Keebdex for review.""" diff --git a/src/aviary/magpie/__main__.py b/src/aviary/magpie/__main__.py new file mode 100644 index 0000000..1176145 --- /dev/null +++ b/src/aviary/magpie/__main__.py @@ -0,0 +1,152 @@ +"""magpie command line. + + magpie crawl [--board ic|gb ...] [--max-pages N] [--fetch-limit N] [--dry-run] + magpie promote [--limit N] [--max-age-days N] [--dry-run] + magpie reextract [--limit N] [--dry-run] + magpie topic + +`crawl` is one `ingest.crawl_runs` run: it lists the boards down to the last +run's watermark into `ingest.threads`, fetches the first post of due threads, +and adds what it reads as keyset candidates to `ingest.candidates`. `promote` +inserts the complete new keyset candidates into Keebdex as Pending keysets +with their kits (revision source `magpie.geekhack`); the rest wait for staff. `topic` +prints one topic as JSON, without a database. +""" + +import argparse +import json +import logging +import sys +from collections.abc import Sequence +from dataclasses import asdict + +from aviary.common.config import MissingSettingError +from aviary.common.report import configure_logging +from aviary.magpie.classify import suggest +from aviary.magpie.crawl import run_crawl +from aviary.magpie.fetch import Fetcher, FetchError +from aviary.magpie.geekhack import BOARDS, extract_topic_id, topic_url +from aviary.magpie.parsers import parse_topic +from aviary.magpie.promote import run_promote +from aviary.magpie.reextract import run_reextract + +log = logging.getLogger("magpie") + +DEFAULT_MAX_PAGES = 5 +DEFAULT_FETCH_LIMIT = 100 +DEFAULT_PROMOTE_LIMIT = 25 +DEFAULT_MAX_AGE_DAYS = 90 + + +def parse_args(argv: Sequence[str] | None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="magpie", + description="Crawl Geekhack interest checks and group buys for Keebdex.", + ) + commands = parser.add_subparsers(dest="command", required=True) + + crawl = commands.add_parser("crawl", help="list boards, fetch threads, extract") + crawl.add_argument( + "--board", + action="append", + choices=sorted(BOARDS), + help="list only this board (repeatable; default: every board)", + ) + crawl.add_argument( + "--max-pages", + type=int, + default=DEFAULT_MAX_PAGES, + metavar="N", + help="list at most N pages per board; raise it once to backfill " + f"(default {DEFAULT_MAX_PAGES})", + ) + crawl.add_argument( + "--fetch-limit", + type=int, + default=DEFAULT_FETCH_LIMIT, + metavar="N", + help=f"fetch at most N due threads (default {DEFAULT_FETCH_LIMIT})", + ) + + promote = commands.add_parser("promote", help="insert complete keyset candidates") + promote.add_argument( + "--limit", + type=int, + default=DEFAULT_PROMOTE_LIMIT, + metavar="N", + help=f"insert at most N keysets (default {DEFAULT_PROMOTE_LIMIT})", + ) + promote.add_argument( + "--max-age-days", + type=int, + default=DEFAULT_MAX_AGE_DAYS, + metavar="N", + help=f"only topics posted in the last N days (default {DEFAULT_MAX_AGE_DAYS})", + ) + + reextract = commands.add_parser( + "reextract", help="extract stored first posts again (no requests to Geekhack)" + ) + reextract.add_argument( + "--limit", + type=int, + metavar="N", + help="extract at most N threads, oldest first (default: all)", + ) + + for command in (crawl, promote, reextract): + command.add_argument( + "--dry-run", + action="store_true", + help="read Keebdex and log every write instead of making it", + ) + + topic = commands.add_parser("topic", help="print one topic as JSON (no database)") + topic.add_argument("topic", help="topic id or URL") + args = parser.parse_args(argv) + if args.command == "crawl" and not 1 <= args.fetch_limit <= 1000: + parser.error("--fetch-limit must be between 1 and 1000") + if args.command == "reextract" and args.limit is not None and args.limit < 1: + parser.error("--limit must be at least 1") + if args.command == "crawl" and args.max_pages < 1: + parser.error("--max-pages must be at least 1") + return args + + +def run_topic(args: argparse.Namespace) -> int: + topic_id = extract_topic_id(args.topic) + fetcher = Fetcher() + try: + detail = parse_topic(fetcher.get(topic_url(topic_id))) + except (FetchError, ValueError) as error: + log.error("Topic %d: %s", topic_id, error) + return 1 + finally: + fetcher.close() + output = {"topic_id": topic_id, "url": topic_url(topic_id), **asdict(detail)} + del output["body"] + output["suggestion"] = asdict(suggest(detail.title)) + sys.stdout.write(json.dumps(output, ensure_ascii=False, indent=2) + "\n") + return 0 + + +COMMANDS = { + "crawl": run_crawl, + "promote": run_promote, + "reextract": run_reextract, + "topic": run_topic, +} + + +def main(argv: Sequence[str] | None = None) -> int: + configure_logging() + args = parse_args(argv) + try: + return COMMANDS[args.command](args) + except MissingSettingError as error: + log.error("%s; see .env.example", error) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/aviary/magpie/classify.py b/src/aviary/magpie/classify.py new file mode 100644 index 0000000..33ecdeb --- /dev/null +++ b/src/aviary/magpie/classify.py @@ -0,0 +1,85 @@ +"""Guess from its title whether a topic sells a keyset or a keyboard. + +The rules are deliberately cautious: when the title points both ways, or +nowhere, the answer is "unknown" rather than a coin flip, and only "keyset" +topics are proposed to Keebdex. +""" + +import re +from dataclasses import dataclass +from typing import Literal + +from aviary.magpie.geekhack import extract_prefix, strip_prefix + +SuggestedKind = Literal["keyset", "keyboard", "other", "unknown"] + +# Keycap profiles and manufacturers keycap topics start with ("GMK Dasher", +# "MW Jirai"). +KEYCAP_CODES = frozenset( + { + "GMK", + "DCS", + "DSS", + "DSA", + "SA", + "MT3", + "MTNU", + "KAT", + "KAM", + "XDA", + "MDA", + "CHERRY", + "MW", + "SWG", + "KKB", + "EPBT", + "PBTFANS", + "JTK", + "DMK", + } +) + +_KEYBOARD_RE = re.compile( + r"\bkeyboards?\b|(? Suggestion: + if extract_prefix(title).upper() not in SET_PREFIXES: + return Suggestion("other", "no [GB], [IC] or [Pre-order] prefix") + name = strip_prefix(title) + first = _FIRST_WORD_RE.match(name) + if first and first.group().upper() in KEYCAP_CODES: + code = first.group().upper() + # Checked before keywords: "DSS Drank - 40% Monokit" is keycaps for a + # 40% board. + return Suggestion("keyset", f"starts with keycap code {code}", code) + keyboard = _KEYBOARD_RE.search(name) + keycap = _KEYCAP_RE.search(name) + if keyboard and keycap: + return Suggestion( + "unknown", f'mentions both "{keycap.group()}" and "{keyboard.group()}"' + ) + if keyboard: + return Suggestion("keyboard", f'mentions "{keyboard.group()}"') + if keycap: + return Suggestion("keyset", f'mentions "{keycap.group()}"') + return Suggestion("unknown", "no keycap or keyboard hint in the title") diff --git a/src/aviary/magpie/crawl.py b/src/aviary/magpie/crawl.py new file mode 100644 index 0000000..8f1b2ba --- /dev/null +++ b/src/aviary/magpie/crawl.py @@ -0,0 +1,365 @@ +"""`magpie crawl`: one `ingest.crawl_runs` run. It lists the boards down to +the last run's watermark into `ingest.threads`, fetches the first post of due +threads, and adds what it reads as keyset candidates to `ingest.candidates`.""" + +import argparse +import hashlib +import logging +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime + +from supabase import Client + +from aviary.common.db import Row, create_supabase +from aviary.common.report import write_summary +from aviary.magpie import ingest, keebdex +from aviary.magpie.fetch import Fetcher, FetchError +from aviary.magpie.geekhack import BOARDS, board_url, parse_time, topic_url +from aviary.magpie.parsers import parse_board, parse_topic +from aviary.magpie.plan import ( + BoardListing, + KeysetIndex, + plan_listing, + refetch_at, + retry_at, +) +from aviary.magpie.proposal import EXTRACTOR_VERSION, MODULE, Extraction, Topic, extract +from aviary.magpie.summary import MAX_LISTED, topic_link + +log = logging.getLogger(__name__) + +# ingest.threads limits +MAX_BODY_CHARS = 500_000 +MAX_IMAGES = 100 +MAX_ERROR_CHARS = 2000 + + +class CrawlError(Exception): + """A board listing that can't be trusted; nothing is written.""" + + +def list_board( + fetcher: Fetcher, board: str, watermark: datetime | None, max_pages: int +) -> BoardListing: + """Read a board page by page until the listing is done or the cap.""" + listing = BoardListing(board, watermark) + offset: int | None = 0 + while offset is not None and listing.pages < max_pages: + page = parse_board(fetcher.get(board_url(board, offset)), offset) + if not page.topics: + raise CrawlError( + f"board {board}: no topics on page {listing.pages + 1}, " + "has the layout changed?" + ) + listing.add_page(page) + log.info( + "Board %s page %d: %d threads", board, listing.pages, len(listing.seen) + ) + if listing.done: + break + offset = page.next_offset + return listing + + +@dataclass +class Counters: + pages_listed: int = 0 + threads_listed: int = 0 + threads_new: int = 0 + threads_fetched: int = 0 + threads_changed: int = 0 + threads_failed: int = 0 + candidates: int = 0 + candidates_restored: int = 0 + failures: list[tuple[str, str]] = field(default_factory=list) + # keyset titles whose keycap code names no Keebdex profile, by code, and + # how many keyset titles had no code at all: profiles staff may add + unknown_profiles: dict[str, list[str]] = field(default_factory=dict) + no_profile_code: int = 0 + + def columns(self) -> Row: + """The `crawl_runs` counters.""" + values = asdict(self) + for only_reported in ( + "candidates", + "candidates_restored", + "failures", + "unknown_profiles", + "no_profile_code", + ): + del values[only_reported] + return values + + def count_profile(self, extraction: Extraction, title: str) -> None: + if extraction.profile_id is not None: + return + if extraction.profile_code is None: + self.no_profile_code += 1 + else: + self.unknown_profiles.setdefault(extraction.profile_code, []).append(title) + + +def candidate_row( + thread: Row, content_hash: str, extraction: Extraction, index: KeysetIndex +) -> Row: + """The `ingest.candidates` row of a thread's extraction, with the + match_key of the keyset Keebdex has for it.""" + match = index.match(int(thread["external_id"]), extraction.key) + return { + "thread_id": thread["id"], + "module": MODULE, + "extractor_version": EXTRACTOR_VERSION, + "content_hash": content_hash, + "payload": extraction.payload, + "confidence": extraction.confidence, + "match_key": match["profile_keyset_id"] if match else None, + } + + +@dataclass +class Crawl: + client: Client + fetcher: Fetcher + profiles: list[Row] + index: KeysetIndex + dry_run: bool + counters: Counters = field(default_factory=Counters) + + def fetch(self, thread: Row) -> None: + """Fetch a thread's first post, store it, and add its candidate.""" + now = datetime.now(UTC) + topic_id = int(thread["external_id"]) + try: + detail = parse_topic(self.fetcher.get(topic_url(topic_id))) + except (FetchError, ValueError) as error: + self.fail(thread, error, now) + return + if detail.dropped_image_urls: + log.warning( + "Topic %d: dropped %d invalid image URLs", + topic_id, + detail.dropped_image_urls, + ) + + body = detail.body + if len(body) > MAX_BODY_CHARS: + log.warning( + "Topic %d: first post cut to %d characters", topic_id, MAX_BODY_CHARS + ) + body = body[:MAX_BODY_CHARS] + content_hash = hashlib.sha256(body.encode()).hexdigest() + posted_at = parse_time(detail.posted_at) + topic = Topic( + topic_id=topic_id, + board=thread["board"], + title=thread["title"] or detail.title, + author=detail.author or thread.get("author") or "", + posted_at=posted_at, + kit_images=detail.kit_images, + ) + extraction = extract(topic, self.profiles) + next_fetch = refetch_at(posted_at, now) + values = { + "raw_body": body, + "content_hash": content_hash, + "fetched_at": now.isoformat(), + "fetch_attempts": 0, + "fetch_error": None, + "author": topic.author or None, + "posted_at": posted_at.isoformat() if posted_at else None, + "images": detail.image_urls[:MAX_IMAGES], + "name": extraction.name if extraction else None, + "profile_id": extraction.profile_id if extraction else None, + "next_fetch_at": next_fetch.isoformat() if next_fetch else None, + } + if content_hash != thread.get("content_hash"): + values["changed_at"] = now.isoformat() + if thread.get("content_hash") is not None: + self.counters.threads_changed += 1 + ingest.update_thread(self.client, thread, values, self.dry_run) + self.counters.threads_fetched += 1 + + if extraction is None: + return + self.counters.count_profile(extraction, topic.title) + candidate = candidate_row(thread, content_hash, extraction, self.index) + saved = ingest.save_candidate(self.client, candidate, self.dry_run) + if saved == ingest.ADDED: + self.counters.candidates += 1 + elif saved == ingest.RESTORED: + self.counters.candidates_restored += 1 + + def fail(self, thread: Row, error: Exception, now: datetime) -> None: + """A failed fetch is routine (a deleted topic, a hiccup): back off, + and stop after a few in a row until a listing shows new activity. A + 404 marks the thread gone.""" + topic_id = thread["external_id"] + message = str(error)[:MAX_ERROR_CHARS] + log.warning("Topic %s: %s", topic_id, message) + self.counters.threads_failed += 1 + self.counters.failures.append((topic_id, message)) + if isinstance(error, FetchError) and error.status == 404: + values = {"gone_at": now.isoformat(), "next_fetch_at": None} + else: + attempts = (thread.get("fetch_attempts") or 0) + 1 + retry = retry_at(attempts, now) + values = { + "fetch_attempts": attempts, + "next_fetch_at": retry.isoformat() if retry else None, + } + values["fetch_error"] = message + ingest.update_thread(self.client, thread, values, self.dry_run) + + +def crawl_summary( + dry_run: bool, counters: Counters, incomplete: list[str], error: str | None +) -> str: + lines = [ + "## magpie crawl", + "", + f"- Pages listed: {counters.pages_listed}", + f"- Threads listed: {counters.threads_listed} ({counters.threads_new} new)", + f"- Threads fetched: {counters.threads_fetched}" + f" ({counters.threads_changed} with an edited first post)", + f"- {'Would add' if dry_run else 'Added'} keyset candidates: " + f"{counters.candidates}", + "- Keyset candidates waiting again (first post reverted to an earlier" + f" version): {counters.candidates_restored}", + f"- Failed fetches: {counters.threads_failed}", + ] + lines += [f" - {topic_link(t)}: {e}" for t, e in counters.failures[:MAX_LISTED]] + if incomplete: + lines.append( + "- Stopped by --max-pages before reaching the last run's threads: " + f"{', '.join(incomplete)} (run once with more pages to fill the gap)" + ) + if error: + lines.append(f"- **Failed**: {error}") + lines += _unknown_profiles(counters) + return "\n".join(lines) + + +# Titles shown per unknown profile code. +MAX_TITLES_PER_CODE = 3 + + +def _unknown_profiles(counters: Counters) -> list[str]: + """Keycap codes keyset titles start with that name no Keebdex profile, + most threads first: candidates for a new profile.""" + if not counters.unknown_profiles and not counters.no_profile_code: + return [] + lines = ["", "### Unknown profiles", ""] + by_count = sorted( + counters.unknown_profiles.items(), key=lambda item: (-len(item[1]), item[0]) + ) + for code, titles in by_count[:MAX_LISTED]: + shown = "; ".join(titles[:MAX_TITLES_PER_CODE]) + more = ( + f" (+{len(titles) - MAX_TITLES_PER_CODE} more)" + if len(titles) > MAX_TITLES_PER_CODE + else "" + ) + lines.append(f"- `{code}`: {_threads(len(titles))}: {shown}{more}") + if counters.no_profile_code: + lines.append( + f"- No profile code in the title: {_threads(counters.no_profile_code)}" + ) + return lines + + +def _threads(count: int) -> str: + return f"{count} thread" if count == 1 else f"{count} threads" + + +def run_crawl(args: argparse.Namespace) -> int: + client = create_supabase() + profiles = keebdex.fetch_profiles(client) + keysets = keebdex.fetch_keysets(client) + # Keebdex holds hundreds of both: an empty read is a bad read, and every + # candidate would miss its profile and match + if not profiles or not keysets: + log.error( + "Read %d profiles and %d keysets, nothing written", + len(profiles), + len(keysets), + ) + return 1 + boards = args.board or sorted(BOARDS) + previous = ingest.last_watermarks(client) + now = datetime.now(UTC) + run_id = None + if not args.dry_run: + try: + run_id = ingest.start_run(client, args.max_pages, now) + except ingest.RunningError as error: + log.error("%s; not starting another", error) + return 1 + + fetcher = Fetcher() + crawl = Crawl(client, fetcher, profiles, KeysetIndex(keysets), args.dry_run) + counters = crawl.counters + listings: list[BoardListing] = [] + error: str | None = None + try: + # every board is read before anything is written: a listing that + # fails part-way writes nothing + listings = [ + list_board(fetcher, board, previous.get(board), args.max_pages) + for board in boards + ] + stored = ingest.fetch_threads(client) + for listing in listings: + plan = plan_listing(listing, stored, now) + ingest.save_listing(client, listing.board, plan, args.dry_run) + counters.pages_listed += listing.pages + counters.threads_listed += len(listing.seen) + counters.threads_new += plan.new + due = ingest.due_threads(client, args.fetch_limit, datetime.now(UTC)) + log.info("Fetching %d due threads", len(due)) + for thread in due: + crawl.fetch(thread) + except (FetchError, CrawlError) as failure: + error = str(failure) + log.error("Crawl failed: %s", error) + except Exception as failure: + error = f"unexpected error: {failure}" + raise + finally: + fetcher.close() + incomplete = [listing.board for listing in listings if not listing.done] + if run_id is not None: + finish(client, run_id, previous, listings, counters, incomplete, error) + summary = crawl_summary(args.dry_run, counters, incomplete, error) + log.info("\n%s", summary) + write_summary(summary) + return 1 if error else 0 + + +def finish( + client: Client, + run_id: int, + previous: dict[str, datetime], + listings: list[BoardListing], + counters: Counters, + incomplete: list[str], + error: str | None, +) -> None: + """Close the run. Only a succeeded run moves watermarks; boards it did not + list keep theirs.""" + watermarks = dict(previous) + if error is None: + for listing in listings: + if (mark := listing.next_watermark()) is not None: + watermarks[listing.board] = mark + ingest.finish_run( + client, + run_id, + { + **counters.columns(), + "status": "failed" if error else "succeeded", + "finished_at": datetime.now(UTC).isoformat(), + "watermarks": {b: w.isoformat() for b, w in watermarks.items()}, + "incomplete_boards": incomplete, + "error": error[:MAX_ERROR_CHARS] if error else None, + }, + ) diff --git a/src/aviary/magpie/fetch.py b/src/aviary/magpie/fetch.py new file mode 100644 index 0000000..d24973d --- /dev/null +++ b/src/aviary/magpie/fetch.py @@ -0,0 +1,119 @@ +"""Reading Geekhack politely: robots.txt, one request at a time with a delay +between them, and retries with backoff on 429 and server errors.""" + +import logging +import time +from collections.abc import Callable +from urllib.robotparser import RobotFileParser + +import httpx + +from aviary.common.http import create_http_client +from aviary.magpie.geekhack import BASE_URL + +log = logging.getLogger(__name__) + +# A generic identifier: no personal contact details are sent to the site. +USER_AGENT = "aviary-magpie/0.1 (+https://keebdex.org)" +REQUEST_DELAY_SECONDS = 1.0 +MAX_ATTEMPTS = 4 +MAX_BACKOFF_SECONDS = 30.0 +# The forum declares ISO-8859-1 only in a tag; browsers read that as +# cp1252. +ENCODING = "cp1252" + + +class FetchError(Exception): + """A page could not be fetched; the caller may skip it. `status` is the + HTTP status when the site answered.""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +class _Retryable(FetchError): + pass + + +class Fetcher: + def __init__( + self, + client: httpx.Client | None = None, + delay: float = REQUEST_DELAY_SECONDS, + backoff: float = 1.0, + sleep: Callable[[float], None] = time.sleep, + ): + if client is None: + client = create_http_client() + client.headers["User-Agent"] = USER_AGENT + self._client = client + self._delay = delay + self._backoff = backoff + self._sleep = sleep + self._last_request: float | None = None + self._robots: RobotFileParser | None = None + + def close(self) -> None: + self._client.close() + + def get(self, url: str) -> str: + if not self._allowed(url): + raise FetchError(f"blocked by robots.txt: {url}") + return self._with_retries(url) + + def _with_retries(self, url: str) -> str: + for attempt in range(1, MAX_ATTEMPTS + 1): + try: + return self._request(url) + except _Retryable: + if attempt == MAX_ATTEMPTS: + raise + self._sleep( + min(self._backoff * 2 ** (attempt - 1), MAX_BACKOFF_SECONDS) + ) + raise AssertionError("unreachable") + + def _allowed(self, url: str) -> bool: + """RFC 9309: a robots.txt the site answers 4xx for means no rules; + one unreachable after retries (5xx, 429, network) means full + disallow, so it raises and the run reads nothing. Not cached then: + the next request asks again.""" + if self._robots is None: + robots = RobotFileParser() + try: + text = self._with_retries(f"{BASE_URL}/robots.txt") + except _Retryable as error: + raise FetchError( + f"robots.txt unreachable, not crawling: {error}", error.status + ) from error + except FetchError as error: + log.warning("robots.txt unavailable (%s); no restrictions", error) + text = "" + robots.parse(text.splitlines()) + self._robots = robots + return self._robots.can_fetch(USER_AGENT, url) + + def _request(self, url: str) -> str: + # monotonic() counts from boot, so the first request must not compare + # against 0: on a machine up for less than the delay it would wait. + if self._last_request is not None: + wait = self._delay - (time.monotonic() - self._last_request) + if wait > 0: + self._sleep(wait) + self._last_request = time.monotonic() + try: + response = self._client.get(url) + except httpx.TransportError as error: + raise _Retryable(f"{url}: {error}") from error + if response.status_code == 429 or response.status_code >= 500: + raise _Retryable( + f"{url}: HTTP {response.status_code}", response.status_code + ) + if response.status_code != 200: + raise FetchError( + f"{url}: HTTP {response.status_code}", response.status_code + ) + if response.charset_encoding is None: + response.encoding = ENCODING + return response.text diff --git a/src/aviary/magpie/geekhack.py b/src/aviary/magpie/geekhack.py new file mode 100644 index 0000000..f42c38e --- /dev/null +++ b/src/aviary/magpie/geekhack.py @@ -0,0 +1,157 @@ +"""Geekhack addresses: boards, topics, and the URLs found in posts.""" + +import ipaddress +import re +from datetime import UTC, datetime +from typing import Literal +from urllib.parse import urljoin, urlsplit, urlunsplit + +FORUM = "geekhack" +BASE_URL = "https://geekhack.org" + +Board = Literal["ic", "gb"] +# The boards magpie reads, by the short name used on the command line and in +# `ingest.threads.board`. +BOARDS: dict[str, int] = {"ic": 132, "gb": 70} + +_SESSION_RE = re.compile(r"PHPSESSID=[^&;#]*[&;]?") +_TOPIC_ID_RE = re.compile(r"topic=(\d+)") +_BBCODE_CLOSING_TAG_RE = re.compile(r"\[/[A-Za-z]+\]") +# An image file on imgur's page host ("imgur.com/PFaO1KL.jpg"): that host +# redirects to the file, which Cloudflare's upload-by-URL and may not +# follow; i.imgur.com serves it directly. +_IMGUR_PAGE_HOSTS = ("imgur.com", "www.imgur.com") +_IMGUR_FILE_RE = re.compile(r"/[A-Za-z0-9]+\.(?:jpe?g|png|gif|webp)", re.IGNORECASE) +_HOST_LABEL_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?") +_PREFIX_RE = re.compile(r"^\s*\[([^\]]+)\]") + + +def parse_time(text: str) -> datetime | None: + """A Geekhack timestamp ("Thu, 05 November 2026, 19:34:26"), or None. + + Guests see the forum's own clock with no zone; magpie reads it as UTC. It + only has to be consistent: listings are compared with earlier listings, + and posting days are a day off at worst. + """ + try: + parsed = datetime.strptime(text.strip(), "%a, %d %B %Y, %H:%M:%S") + except ValueError: + return None + return parsed.replace(tzinfo=UTC) + + +def board_url(board: Board, offset: int = 0) -> str: + return f"{BASE_URL}/index.php?board={BOARDS[board]}.{offset}" + + +def topic_url(topic_id: int) -> str: + """The address Keebdex stores in `keysets.url` for a topic.""" + return f"{BASE_URL}/index.php?topic={topic_id}.0" + + +def extract_topic_id(value: str) -> int: + """A bare id, or the id in any URL containing `topic=`.""" + value = value.strip() + if value.isdigit(): + return int(value) + match = _TOPIC_ID_RE.search(value) + if not match: + raise ValueError(f"cannot find a topic id in {value!r}") + return int(match.group(1)) + + +def topic_id_of(url: str | None) -> int | None: + """The topic a Geekhack URL points at (`topic=123`, `topic=123.0`, with or + without `www.`), or None for any other URL.""" + if not url or not is_internal(url): + return None + match = _TOPIC_ID_RE.search(url) + return int(match.group(1)) if match else None + + +def canonical_url(url: str) -> str | None: + """Make `url` absolute and drop the per-visit PHPSESSID so links stay + stable; None when it can't be parsed as a URL (`http://[broken`).""" + try: + absolute = urljoin(BASE_URL + "/", url) + except ValueError: + return None + cleaned = _SESSION_RE.sub("", absolute) + return cleaned.rstrip("?&;") + + +def is_internal(url: str) -> bool: + try: + host = urlsplit(url).hostname or "" + except ValueError: + return False + return host == "geekhack.org" or host.endswith(".geekhack.org") + + +def extract_prefix(title: str) -> str: + """The `[GB]` / `[IC]` tag a title starts with, without brackets.""" + match = _PREFIX_RE.match(title) + return match.group(1).strip() if match else "" + + +def strip_prefix(title: str) -> str: + return _PREFIX_RE.sub("", title, count=1).strip() + + +def normalize_image_url(raw: str) -> str | None: + """A clean image URL, or None if `raw` is not shaped like a URL (e.g. a + sentence that got `http://` glued in front of it). + + Only the format is checked, nothing is fetched. A URL is kept untouched + when it has an http(s) scheme, a real host, and no whitespace; a file + extension is not required (CDN and forum attachment URLs often have none). + The one rewrite: an image file on `imgur.com` moves to `i.imgur.com` + (albums stay, `is_album` drops them). + Stray BBCode left in the post (`.png[/center]`) is cut off first so the + image behind it is not lost. + """ + url = _strip_bbcode_tail(raw.strip()) + if not url or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in url): + return None + try: + parts = urlsplit(url) + except ValueError: + return None + if parts.scheme not in ("http", "https") or not _is_valid_host(parts.hostname): + return None + if parts.hostname in _IMGUR_PAGE_HOSTS and _IMGUR_FILE_RE.fullmatch(parts.path): + return urlunsplit(("https", "i.imgur.com", parts.path, parts.query, "")) + return url + + +def _strip_bbcode_tail(text: str) -> str: + """Cut `[/center]`-style closing tags and a lone `]` and what follows. + + Brackets that are part of the URL are kept: `?a[]=1`, `?filter[x]=y`, + `http://[::1]/`. + """ + closing = _BBCODE_CLOSING_TAG_RE.search(text) + if closing: + text = text[: closing.start()] + stray = text.find("]") + if stray != -1 and "[" not in text[:stray]: + text = text[:stray] + return text.strip() + + +def _is_valid_host(host: str | None) -> bool: + if not host: + return False + try: + ipaddress.ip_address(host) + except ValueError: + pass + else: + return True + try: + ascii_host = host.rstrip(".").encode("idna").decode("ascii") + except UnicodeError: + return False + labels = ascii_host.split(".") + # "We" or "Thanks" (a sentence's first word) has no dot: not a domain. + return len(labels) > 1 and all(_HOST_LABEL_RE.fullmatch(label) for label in labels) diff --git a/src/aviary/magpie/ingest.py b/src/aviary/magpie/ingest.py new file mode 100644 index 0000000..7850be8 --- /dev/null +++ b/src/aviary/magpie/ingest.py @@ -0,0 +1,265 @@ +"""magpie's reads and writes of the `ingest` schema: threads, candidates, +crawl_runs (supabase migration 20261119000000_ingest_schema.sql). + +Every read and write raises on a Supabase error (supabase-py raises APIError). +In a dry run the reads still happen and every write is logged instead. +""" + +import json +import logging +from datetime import datetime, timedelta +from itertools import batched + +from postgrest import APIError, SyncPostgrestClient +from supabase import Client + +from aviary.common.db import Row, fetch_all +from aviary.magpie.geekhack import FORUM +from aviary.magpie.plan import ListingPlan, stored_time +from aviary.magpie.proposal import MODULE + +log = logging.getLogger(__name__) + +SCHEMA = "ingest" +THREADS = "threads" +CANDIDATES = "candidates" +RUNS = "crawl_runs" + +THREAD_KEY = "source,external_id" +UPSERT_CHUNK_SIZE = 500 +# A run still `running` after this long crashed; the next run marks it failed +# so the one-running-run index lets it start. +STALE_RUN = timedelta(hours=1) +UNIQUE_VIOLATION = "23505" + + +class RunningError(RuntimeError): + """Another crawl run is in progress.""" + + +def schema(client: Client) -> SyncPostgrestClient: + return client.schema(SCHEMA) + + +def _source(query): + return query.eq("source", FORUM) + + +def dump(value: object) -> str: + return json.dumps(value, ensure_ascii=False, default=str) + + +# Crawl runs + + +def last_watermarks(client: Client) -> dict[str, datetime]: + """The newest last post per board of the last succeeded run.""" + rows = ( + _source(schema(client).table(RUNS).select("watermarks")) + .eq("status", "succeeded") + .order("started_at", desc=True) + .limit(1) + .execute() + .data + ) + marks = rows[0]["watermarks"] if rows else {} + return { + board: when for board, value in marks.items() if (when := stored_time(value)) + } + + +def start_run(client: Client, max_pages: int, now: datetime) -> int: + """Record a running run; a run left running past STALE_RUN is marked + failed first. Raises RunningError while another run is in progress.""" + stale = ( + _source( + schema(client) + .table(RUNS) + .update( + { + "status": "failed", + "finished_at": now.isoformat(), + "error": "interrupted: still running an hour after it started", + } + ) + ) + .eq("status", "running") + .lt("started_at", (now - STALE_RUN).isoformat()) + .execute() + .data + ) + if stale: + log.warning("Marked %d interrupted runs failed", len(stale)) + running = ( + _source(schema(client).table(RUNS).select("id")) + .eq("status", "running") + .execute() + .data + ) + if running: + raise RunningError(f"crawl run {running[0]['id']} is still running") + row = {"source": FORUM, "status": "running", "max_pages": max_pages} + try: + return schema(client).table(RUNS).insert(row).execute().data[0]["id"] + except APIError as error: + # another run (a local one, outside the Actions concurrency group) + # started between the check and the insert: crawl_runs_one_running_idx + if error.code == UNIQUE_VIOLATION: + raise RunningError("another crawl run just started") from error + raise + + +def finish_run(client: Client, run_id: int, values: Row) -> None: + schema(client).table(RUNS).update(values).eq("id", run_id).execute() + + +# Listing + + +def fetch_threads(client: Client) -> dict[str, Row]: + """Every stored thread by external id, with what a listing compares.""" + rows = fetch_all( + schema(client), THREADS, "id,external_id,last_post_at,gone_at", _source + ) + return {row["external_id"]: row for row in rows} + + +def save_listing(client: Client, board: str, plan: ListingPlan, dry_run: bool) -> None: + if dry_run: + log.info( + "[DRY RUN] Board %s: would upsert %d threads to fetch (%d new): %s", + board, + len(plan.due), + plan.new, + dump([(r["external_id"], r["title"]) for r in plan.due]), + ) + log.info("[DRY RUN] Board %s: would refresh %d threads", board, len(plan.seen)) + return + # two kinds of rows, each with the same columns, as a bulk upsert needs: + # only due ones move next_fetch_at + for rows in (plan.due, plan.seen): + for batch in batched(rows, UPSERT_CHUNK_SIZE, strict=False): + schema(client).table(THREADS).upsert( + list(batch), on_conflict=THREAD_KEY, default_to_null=False + ).execute() + + +# Fetching + + +def due_threads(client: Client, limit: int, now: datetime) -> list[Row]: + """Threads to fetch now, most overdue first (threads_due_idx).""" + return ( + _source( + schema(client) + .table(THREADS) + .select("id,external_id,board,title,author,content_hash,fetch_attempts") + ) + .lte("next_fetch_at", now.isoformat()) + .is_("ignored_at", "null") + .is_("gone_at", "null") + .order("next_fetch_at") + .limit(limit) + .execute() + .data + ) + + +def update_thread(client: Client, thread: Row, values: Row, dry_run: bool) -> None: + if dry_run: + shown = {k: v for k, v in values.items() if k != "raw_body"} + log.info( + "[DRY RUN] Would update thread %s: %s", thread["external_id"], dump(shown) + ) + return + schema(client).table(THREADS).update(values).eq("id", thread["id"]).execute() + + +ADDED = "added" +RESTORED = "restored" + + +def save_candidate(client: Client, candidate: Row, dry_run: bool) -> str | None: + """Insert an extraction: ADDED, RESTORED when the same extractor already + read the same content and the supersede trigger put that superseded + candidate back to waiting (the first post went back to an earlier + version), None when it was already waiting, dismissed, or promoted. The + trigger returns no row in both of the last cases, so the existing + extraction's state is read first; a dry run reads it too, to tell what + the insert would do.""" + existing = ( + schema(client) + .table(CANDIDATES) + .select("state") + .eq("thread_id", candidate["thread_id"]) + .eq("module", candidate["module"]) + .eq("extractor_version", candidate["extractor_version"]) + .eq("content_hash", candidate["content_hash"]) + .execute() + .data + ) + state = existing[0]["state"] if existing else None + if dry_run: + if state is None: + log.info("[DRY RUN] Would add candidate: %s", dump(candidate)) + return ADDED + return RESTORED if state == "superseded" else None + if schema(client).table(CANDIDATES).insert(candidate).execute().data: + return ADDED + return RESTORED if state == "superseded" else None + + +# Extracting stored posts again + +# Stored first posts read per request: each can be up to 500,000 characters. +BODY_BATCH_SIZE = 50 + + +def running_run(client: Client, now: datetime) -> int | None: + """The crawl run in progress (started within STALE_RUN), if any.""" + rows = ( + _source(schema(client).table(RUNS).select("id")) + .eq("status", "running") + .gte("started_at", (now - STALE_RUN).isoformat()) + .limit(1) + .execute() + .data + ) + return rows[0]["id"] if rows else None + + +def fetch_stored_threads(client: Client) -> list[Row]: + """Threads with a stored first post, neither ignored nor gone, without + the post itself (`stored_bodies` reads it in batches).""" + return fetch_all( + schema(client), + THREADS, + "id,external_id,board,title,author,posted_at,content_hash", + lambda query: ( + _source(query) + .not_.is_("raw_body", "null") + .is_("ignored_at", "null") + .is_("gone_at", "null") + ), + ) + + +def stored_bodies(client: Client, ids: list[int]) -> dict[int, str]: + """The `raw_body` of each thread in `ids`, by id.""" + rows = ( + schema(client).table(THREADS).select("id,raw_body").in_("id", ids).execute() + ).data + return {row["id"]: row["raw_body"] for row in rows} + + +# Candidates waiting for promotion + + +def fetch_waiting(client: Client) -> list[Row]: + """Keyset candidates waiting for triage, with their thread.""" + return fetch_all( + schema(client), + CANDIDATES, + "id,payload,match_key,thread:threads(external_id,posted_at,ignored_at,gone_at)", + lambda query: query.eq("state", "new").eq("module", MODULE), + ) diff --git a/src/aviary/magpie/keebdex.py b/src/aviary/magpie/keebdex.py new file mode 100644 index 0000000..c9285a4 --- /dev/null +++ b/src/aviary/magpie/keebdex.py @@ -0,0 +1,211 @@ +"""magpie's reads of Keebdex (keysets, profiles) and the Pending keysets and +kits it promotes into it, claiming their `ingest.candidates`. + +Every read raises on a Supabase error; a promotion that fails is logged and +reported. In a dry run the reads still happen and every write is logged +instead. +""" + +import logging +from dataclasses import dataclass, field + +from supabase import Client + +from aviary.common.db import PUBLISHED_FILTER, Row, fetch_all +from aviary.magpie.ingest import CANDIDATES, dump, schema +from aviary.magpie.plan import Promotion, PromotionPlan +from aviary.magpie.proposal import keyset_row, kit_rows + +log = logging.getLogger(__name__) + +KEYSETS = "keysets" +KITS = "keyset_kits" +PROFILES = "keyset_profiles" + + +def fetch_keysets(client: Client) -> list[Row]: + """Every keyset, of every review status: a Pending one is a proposal + already.""" + return fetch_all(client, KEYSETS, "id,profile_id,slug,profile_keyset_id,url,status") + + +def fetch_profiles(client: Client) -> list[Row]: + """Published profiles: a keyset is never proposed under one in review.""" + return fetch_all( + client, + PROFILES, + "id,profile_id,name,profile", + lambda query: query.or_(PUBLISHED_FILTER), + ) + + +@dataclass +class PromotionResult: + """Topics whose promotion failed (`promote` exits 1), and topics whose + candidate staff triaged meanwhile, so their keyset was removed again.""" + + failed: list[int] = field(default_factory=list) + triaged: list[int] = field(default_factory=list) + + +def apply_promotions( + client: Client, plan: PromotionPlan, dry_run: bool +) -> PromotionResult: + """Insert each promotion (keyset, then its kits), then claim its + candidate (mark it promoted while it still waits), then set the + match_key of rematched candidates. + + A keyset is removed again (nothing points at it yet) when its kits fail, + since the review queue would never show it, and when the claim finds the + candidate no longer waiting: staff triaged it after `fetch_waiting` read + it, and the keyset would be an orphan or a duplicate of what staff made + of it. A claim that raises may still have committed (a lost response), + so the candidate is read back first: the keyset is removed only when the + candidate is not promoted to it, and kept when that cannot be read. A + removal that fails is logged and the run goes on.""" + result = PromotionResult() + failed_keys: set[str] = set() + for promotion in plan.promotions: + payload = promotion.payload + topic = promotion.topic_id + if dry_run: + log.info( + "[DRY RUN] Would insert keyset %s from topic %d: %s with kits %s", + promotion.key, + topic, + dump(keyset_row(payload)), + dump([(k["kit_id"], k["img"]) for k in payload["kits"]]), + ) + continue + try: + inserted = client.table(KEYSETS).insert(keyset_row(payload)).execute() + keyset_id = inserted.data[0]["id"] + except Exception: + log.exception("Topic %d: inserting keyset %s failed", topic, promotion.key) + result.failed.append(topic) + failed_keys.add(promotion.key) + continue + try: + client.table(KITS).insert(kit_rows(payload)).execute() + except Exception: + log.exception( + "Topic %d: inserting the kits of %s failed, removing the keyset", + topic, + promotion.key, + ) + _remove_keyset(client, promotion, keyset_id) + result.failed.append(topic) + failed_keys.add(promotion.key) + continue + try: + claimed = _claim(client, promotion, keyset_id) + except Exception: + log.exception( + "Topic %d: claiming candidate %d failed, reading it back", + topic, + promotion.candidate_id, + ) + current = _read_candidate(client, promotion.candidate_id) + if current is None: + log.error( + "Topic %d: candidate %d could not be read back; keyset %s" + " (id %d) is kept, check it by hand", + topic, + promotion.candidate_id, + promotion.key, + keyset_id, + ) + result.failed.append(topic) + continue + if current["state"] == "promoted" and current["promoted_id"] == keyset_id: + log.info("Topic %d: the claim went through after all", topic) + continue + if current["state"] == "new": + # the claim did not apply: still waiting, try again next run + _remove_keyset(client, promotion, keyset_id) + result.failed.append(topic) + failed_keys.add(promotion.key) + continue + claimed = False + if not claimed: + log.warning( + "Topic %d: candidate %d was triaged meanwhile, removing keyset %s", + topic, + promotion.candidate_id, + promotion.key, + ) + failed_keys.add(promotion.key) + # listed once: triaged only when its keyset is really gone again + if _remove_keyset(client, promotion, keyset_id): + result.triaged.append(topic) + else: + result.failed.append(topic) + + for rematch in plan.rematches: + if rematch.key in failed_keys: + # its keyset was not inserted (or was removed again): the + # candidate waits for the next run + continue + if dry_run: + log.info( + "[DRY RUN] Would match candidate of topic %d to %s", + rematch.topic_id, + rematch.key, + ) + continue + schema(client).table(CANDIDATES).update({"match_key": rematch.key}).eq( + "id", rematch.candidate_id + ).eq("state", "new").execute() + return result + + +def _claim(client: Client, promotion: Promotion, keyset_id: int) -> bool: + """Mark the candidate promoted to `keyset_id`, only while it still + waits; False when staff triaged it meanwhile.""" + return bool( + schema(client) + .table(CANDIDATES) + .update( + {"state": "promoted", "promoted_kind": "keyset", "promoted_id": keyset_id} + ) + .eq("id", promotion.candidate_id) + .eq("state", "new") + .execute() + .data + ) + + +def _read_candidate(client: Client, candidate_id: int) -> Row | None: + """A candidate's state and promoted_id; None (logged) when it cannot be + read.""" + try: + rows = ( + schema(client) + .table(CANDIDATES) + .select("state,promoted_id") + .eq("id", candidate_id) + .execute() + .data + ) + except Exception: + log.exception("Reading candidate %d failed", candidate_id) + return None + return rows[0] if rows else None + + +def _remove_keyset(client: Client, promotion: Promotion, keyset_id: int) -> bool: + """Delete a keyset this run just inserted, kits first; False (logged) + when that fails, so the caller lists the topic as failed and the run + goes on. The kits are found by key: the keyset did not exist before.""" + try: + client.table(KITS).delete().eq("profile_keyset_id", promotion.key).execute() + client.table(KEYSETS).delete().eq("id", keyset_id).execute() + except Exception: + log.exception( + "Topic %d: removing keyset %s (id %d) failed; delete it by hand", + promotion.topic_id, + promotion.key, + keyset_id, + ) + return False + return True diff --git a/src/aviary/magpie/kits.py b/src/aviary/magpie/kits.py new file mode 100644 index 0000000..ab1c368 --- /dev/null +++ b/src/aviary/magpie/kits.py @@ -0,0 +1,26 @@ +"""Keebdex `kit_categories` a Geekhack post can label an image with.""" + +import re + +# Slugs of `kit_categories` detected from post text. +DETECTED_KITS = ("base", "novelties", "spacebars") + +# The whole line has to be the label ("Base Kit", "Novelties:", "Space bars - +# $30"): a sentence that merely mentions a kit ("Convex DSA Space Bars") must +# not switch the kit. +_LABEL_RE = re.compile( + r"""^\W* + (?:(?:the|extra|additional)\s+)? + (?:(?Pbase)|(?Pnovelt(?:y|ies))|(?Pspace\s?-?bars?)) + (?:\s+(?:kit|kits|set|sets|pack))? + [\s:\-\u2013\u2014]*(?:\$?\d[\d.,]*)?\W*$""", + re.IGNORECASE | re.VERBOSE, +) + + +def classify_kit_label(text: str) -> str | None: + """The kit slug a line of post text announces, or None.""" + match = _LABEL_RE.match(text.strip()) + if match is None: + return None + return next(slug for slug in DETECTED_KITS if match.group(slug)) diff --git a/src/aviary/magpie/parsers.py b/src/aviary/magpie/parsers.py new file mode 100644 index 0000000..0221f3f --- /dev/null +++ b/src/aviary/magpie/parsers.py @@ -0,0 +1,239 @@ +"""Geekhack pages to data: a board's topic list and a topic's first post. +Pure functions, no I/O.""" + +import re +from dataclasses import dataclass, field +from urllib.parse import urlsplit + +from bs4 import BeautifulSoup, NavigableString, Tag + +from aviary.magpie.geekhack import canonical_url, is_internal, normalize_image_url +from aviary.magpie.kits import classify_kit_label + +_TOPIC_ID_RE = re.compile(r"topic=(\d+)") +_REPLIES_RE = re.compile(r"(\d[\d,]*)\s+Repl") +_VIEWS_RE = re.compile(r"(\d[\d,]*)\s+View") +_DATE_RE = re.compile(r"\w{3}, \d{1,2} \w+ \d{4}, \d{2}:\d{2}:\d{2}") +# Pagination links only ever point at the board being read. +_BOARD_OFFSET_RE = re.compile(r"board=\d+\.(\d+)") +_IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".gif", ".webp", ".avif", ".bmp") + + +@dataclass(frozen=True) +class TopicSummary: + """One row of a board's topic list. `last_post_at` is as Geekhack prints + it ("Thu, 05 November 2026, 19:34:26").""" + + topic_id: int + title: str + author: str + replies: int + views: int + last_post_at: str + is_sticky: bool = False + is_locked: bool = False + + +@dataclass(frozen=True) +class BoardPage: + topics: list[TopicSummary] + next_offset: int | None + + +@dataclass(frozen=True) +class KitImage: + """An image of the first post and the kit (a `kit_categories` slug) whose + label precedes it: None before any label. `label` is the matched text.""" + + url: str + kit: str | None = None + label: str = "" + + +@dataclass(frozen=True) +class PostContent: + """What magpie reads from the body of a first post.""" + + kit_images: list[KitImage] = field(default_factory=list) + vendor_links: list[str] = field(default_factory=list) + # image URLs rejected as "not a URL" + dropped_image_urls: int = 0 + + @property + def image_urls(self) -> list[str]: + return [image.url for image in self.kit_images] + + +@dataclass(frozen=True) +class TopicDetail(PostContent): + """A topic's first post: the page's title, author, and posting time, and + the post itself (`body`, its `div.post` HTML, kept so a newer extractor + can read it again without crawling).""" + + title: str = "" + author: str = "" + posted_at: str = "" + body: str = "" + + +def _soup(html: str) -> BeautifulSoup: + return BeautifulSoup(html, "lxml") + + +def _text(node: Tag | None, separator: str = "") -> str: + return node.get_text(separator) if node is not None else "" + + +def _attr(node: Tag | None, name: str) -> str: + if node is None: + return "" + value = node.get(name) + if isinstance(value, list): + return " ".join(value) + return value or "" + + +def parse_board(html: str, offset: int = 0) -> BoardPage: + soup = _soup(html) + topics = [t for row in soup.select("tr") if (t := _parse_row(row)) is not None] + return BoardPage(topics=topics, next_offset=_next_offset(soup, offset)) + + +def _parse_row(row: Tag) -> TopicSummary | None: + subject = row.select_one("td.subject") + if subject is None: + return None + link = subject.select_one('span[id^="msg_"] a') + if link is None: + return None + match = _TOPIC_ID_RE.search(_attr(link, "href")) + if match is None: + return None + + icon = row.select_one("td.icon1") + icon_src = _attr(icon.select_one("img") if icon else None, "src") + stats_text = _text(row.select_one("td.stats"), " ") + date_match = _DATE_RE.search(_text(row.select_one("td.lastpost"), " ")) + + return TopicSummary( + topic_id=int(match.group(1)), + title=link.get_text().strip(), + author=_text(subject.select_one("p a")).strip(), + replies=_number(_REPLIES_RE, stats_text), + views=_number(_VIEWS_RE, stats_text), + last_post_at=date_match.group(0) if date_match else "", + is_sticky="stickybg" in _attr(icon, "class"), + is_locked="locked" in icon_src, + ) + + +def _number(pattern: re.Pattern[str], text: str) -> int: + match = pattern.search(text) + return int(match.group(1).replace(",", "")) if match else 0 + + +def _next_offset(soup: BeautifulSoup, offset: int) -> int | None: + offsets = { + int(m.group(1)) + for a in soup.select("div.pagelinks a.navPages") + if (m := _BOARD_OFFSET_RE.search(_attr(a, "href"))) + } + later = [o for o in offsets if o > offset] + return min(later) if later else None + + +def parse_topic(html: str) -> TopicDetail: + """The first post (the announcement) only; replies are ignored.""" + soup = _soup(html) + post = soup.select_one("div.post") + if post is None: + raise ValueError("no post found in topic page") + + date_match = _DATE_RE.search(_text(soup.select_one("div.keyinfo div.smalltext"))) + body = str(post) + # read from the stored body, so a later run over it reads the same + content = parse_post(body) + return TopicDetail( + title=_text(soup.select_one("title")).strip(), + author=_text(soup.select_one("div.poster h4 a")).strip(), + posted_at=date_match.group(0) if date_match else "", + body=body, + kit_images=content.kit_images, + vendor_links=content.vendor_links, + dropped_image_urls=content.dropped_image_urls, + ) + + +def parse_post(body: str) -> PostContent: + """Images (with their kit) and vendor links of a first post's HTML.""" + post = _soup(body).select_one("div.post") + if post is None: + raise ValueError("no post in the stored body") + kit_images, image_links, dropped = _images(post) + return PostContent( + kit_images=kit_images, + vendor_links=_vendor_links(post, image_links), + dropped_image_urls=dropped, + ) + + +def _is_image_link(href: str) -> bool: + """A link to a full-size image; False for one that isn't a URL at all + (`http://[broken`): one bad link must not fail the whole post.""" + try: + path = urlsplit(href).path + except ValueError: + return False + return "action=dlattach" in href or path.lower().endswith(_IMAGE_EXTENSIONS) + + +def _images(post: Tag) -> tuple[list[KitImage], set[str], int]: + """Images in document order, each with the kit whose label last appeared + before it; the links used as full-size images; how many were dropped.""" + images: list[KitImage] = [] + seen: set[str] = set() + used_links: set[str] = set() + dropped = 0 + kit: str | None = None + label = "" + for node in post.descendants: + # only plain text: comments, CDATA and the like are NavigableString + # subclasses + if type(node) is NavigableString: + if (found := classify_kit_label(str(node))) is not None: + kit, label = found, str(node).strip() + continue + if not isinstance(node, Tag) or node.name != "img": + continue + src = _attr(node, "src") + if not src or "smiley" in _attr(node, "class") or "/Smileys/" in src: + continue + # The wrapping link points at the full-size image; the may be a + # thumbnail. + parent = node.parent + href = _attr(parent, "href") + link = canonical_url(href) if _is_image_link(href) else None + if parent is not None and parent.name == "a" and link is not None: + used_links.add(link) + src = href + absolute = canonical_url(src) + url = normalize_image_url(absolute) if absolute is not None else None + if url is None: + dropped += 1 + elif url not in seen: + seen.add(url) + images.append(KitImage(url=url, kit=kit, label=label)) + return images, used_links, dropped + + +def _vendor_links(post: Tag, image_links: set[str]) -> list[str]: + links: list[str] = [] + for anchor in post.select("a"): + href = _attr(anchor, "href") + if not href.startswith(("http://", "https://")): + continue + url = canonical_url(href) + if url is None or is_internal(url) or url in image_links or url in links: + continue + links.append(url) + return links diff --git a/src/aviary/magpie/plan.py b/src/aviary/magpie/plan.py new file mode 100644 index 0000000..b83481e --- /dev/null +++ b/src/aviary/magpie/plan.py @@ -0,0 +1,280 @@ +"""What magpie writes, decided without a database: how far to list a board, +which threads to fetch again and when, and which candidates it promotes +itself. Pure functions, tested in tests/test_magpie_plan.py.""" + +from collections.abc import Sequence +from dataclasses import dataclass, field +from datetime import date, datetime, timedelta + +from aviary.common.db import Row +from aviary.magpie.geekhack import FORUM, parse_time, topic_id_of, topic_url +from aviary.magpie.parsers import BoardPage, TopicSummary +from aviary.magpie.proposal import missing_for_promotion + +# A thread posted this recently is fetched again every REFETCH_EVERY, since +# editing the first post does not bump it on the board. +ACTIVE_FOR = timedelta(days=90) +REFETCH_EVERY = timedelta(days=7) +# Failed fetches back off from an hour, doubling, up to a week; after +# MAX_FETCH_ATTEMPTS in a row the thread waits for new activity in a listing. +RETRY_FIRST = timedelta(hours=1) +RETRY_MAX = timedelta(days=7) +MAX_FETCH_ATTEMPTS = 5 + + +def stored_time(value: str | None) -> datetime | None: + return datetime.fromisoformat(value) if value else None + + +@dataclass +class BoardListing: + """The pages of a board read by one run, newest last post first. + + A listing stops at the first page that reaches `watermark` (the newest + last post the previous succeeded run saw), at the board's last page, or + at the run's page cap. Stopped by the cap, it is incomplete: threads below + may have been missed, so the board keeps its old watermark. A board that + never had one gets the newest last post anyway: what lies below the cap + is backlog, read by one run with a higher `--max-pages` on purpose, and + without a watermark every run would list the whole cap. + """ + + board: str + watermark: datetime | None + seen: dict[int, TopicSummary] = field(default_factory=dict) + pages: int = 0 + reached_end: bool = False + reached_watermark: bool = False + newest: datetime | None = None + + def add_page(self, page: BoardPage) -> None: + """Record a page. Stickies (rules, FAQs) are skipped, and a thread + seen twice (bumped while the run went on) counts once, as first + seen.""" + self.pages += 1 + self.reached_end = page.next_offset is None + for topic in page.topics: + if topic.is_sticky or topic.topic_id in self.seen: + continue + self.seen[topic.topic_id] = topic + when = parse_time(topic.last_post_at) + if when is None: + continue + if self.newest is None or when > self.newest: + self.newest = when + if self.watermark is not None and when <= self.watermark: + self.reached_watermark = True + + @property + def done(self) -> bool: + return self.reached_end or self.reached_watermark + + def next_watermark(self) -> datetime | None: + if self.newest is None: + return self.watermark + if self.watermark is None: + return self.newest + if not self.done: + return self.watermark + return max(self.newest, self.watermark) + + +@dataclass +class ListingPlan: + """`ingest.threads` upserts for a listing: `due` rows (new threads, and + threads with new activity, gone ones included) are fetched next, `seen` + rows only refresh what the listing shows.""" + + due: list[Row] = field(default_factory=list) + seen: list[Row] = field(default_factory=list) + new: int = 0 + + +def plan_listing( + listing: BoardListing, stored: dict[str, Row], now: datetime +) -> ListingPlan: + plan = ListingPlan() + for topic in listing.seen.values(): + external_id = str(topic.topic_id) + when = parse_time(topic.last_post_at) + row = { + "source": FORUM, + "external_id": external_id, + "url": topic_url(topic.topic_id), + "board": listing.board, + "title": topic.title, + "author": topic.author or None, + "reply_count": topic.replies, + "last_post_at": when.isoformat() if when else None, + "listed_at": now.isoformat(), + } + old = stored.get(external_id) + if old is None: + plan.new += 1 + elif stored_time(old.get("last_post_at")) == when: + # nothing new: a gone thread stays gone (the forum can list a + # topic it then refuses to show) + plan.seen.append(row) + continue + # new activity starts the retries over: a thread that ran out of + # attempts gets the full backoff again, not a single try + plan.due.append( + { + **row, + "next_fetch_at": now.isoformat(), + "gone_at": None, + "fetch_attempts": 0, + "fetch_error": None, + } + ) + return plan + + +def refetch_at(posted_at: datetime | None, now: datetime) -> datetime | None: + """When a fetched thread is read again without new activity: weekly while + recent, else only when a listing shows new activity.""" + if posted_at is not None and now - posted_at <= ACTIVE_FOR: + return now + REFETCH_EVERY + return None + + +def retry_at(attempts: int, now: datetime) -> datetime | None: + """When a thread whose fetch failed `attempts` times in a row is tried + again.""" + if attempts >= MAX_FETCH_ATTEMPTS: + return None + return now + min(RETRY_FIRST * 2 ** (attempts - 1), RETRY_MAX) + + +class KeysetIndex: + """Keebdex keysets by the Geekhack topic their `url` points at and by + key (`profile_keyset_id`, or profile and slug), of every source and + review status.""" + + def __init__(self, keysets: Sequence[Row]): + self.by_topic: dict[int, Row] = {} + self.by_key: dict[str, Row] = {} + for keyset in keysets: + if (topic_id := topic_id_of(keyset.get("url"))) is not None: + self.by_topic.setdefault(topic_id, keyset) + self.by_key[keyset["profile_keyset_id"]] = keyset + self.by_key.setdefault(f"{keyset['profile_id']}/{keyset['slug']}", keyset) + + def match(self, topic_id: int, key: str | None) -> Row | None: + found = self.by_topic.get(topic_id) + if found is None and key is not None: + found = self.by_key.get(key) + return found + + +def payload_key(payload: Row) -> str | None: + keyset = payload.get("keyset") or {} + if keyset.get("profile_id") and keyset.get("slug"): + return f"{keyset['profile_id']}/{keyset['slug']}" + return None + + +@dataclass(frozen=True) +class Promotion: + candidate_id: int + topic_id: int + payload: Row + + @property + def key(self) -> str: + return payload_key(self.payload) or "" + + +@dataclass(frozen=True) +class Rematch: + """A candidate whose keyset Keebdex has now: its match_key is set, so it + waits for staff as an edit of that page.""" + + candidate_id: int + topic_id: int + key: str + # what the candidate says that differs from the stored keyset + difference: str | None = None + + +@dataclass +class PromotionPlan: + promotions: list[Promotion] = field(default_factory=list) + rematches: list[Rematch] = field(default_factory=list) + # (topic id, what is missing): left for staff + incomplete: list[tuple[int, str]] = field(default_factory=list) + # left for the next run by the limit + deferred: int = 0 + # posted before the cut-off (or undated): left for staff + old: int = 0 + + +def plan_promotions( + candidates: Sequence[Row], + keysets: Sequence[Row], + *, + limit: int, + posted_since: date, +) -> PromotionPlan: + """Which waiting keyset candidates magpie promotes itself, newest topic + first: complete ones (missing_for_promotion), with no match_key and no + keyset in Keebdex now, posted on or after `posted_since`, at most `limit`. + + A candidate whose keyset Keebdex has (its topic's URL or its key, another + source's, an earlier topic's, or one this run inserts) gets that match_key + instead; a different status is only reported, the keyset is never + updated. Candidates of ignored or gone threads are left alone. + """ + index = KeysetIndex(keysets) + plan = PromotionPlan() + planned: set[str] = set() + deferred: set[str] = set() + + def topic_of(candidate: Row) -> int: + return int(candidate["thread"]["external_id"]) + + for candidate in sorted(candidates, key=topic_of, reverse=True): + thread = candidate["thread"] + if thread.get("ignored_at") or thread.get("gone_at"): + continue + topic_id = topic_of(candidate) + payload = candidate["payload"] + key = payload_key(payload) + stored = index.match(topic_id, key) + if stored is not None: + if candidate.get("match_key") != stored["profile_keyset_id"]: + plan.rematches.append( + Rematch( + candidate["id"], + topic_id, + stored["profile_keyset_id"], + _status_difference(stored, payload), + ) + ) + continue + if candidate.get("match_key"): + continue + if missing := missing_for_promotion(payload): + plan.incomplete.append((topic_id, ", ".join(missing))) + continue + posted = stored_time(thread.get("posted_at")) + if posted is None or posted.date() < posted_since: + plan.old += 1 + continue + if key in planned: + # an older topic of a keyset this run inserts + plan.rematches.append(Rematch(candidate["id"], topic_id, key)) + elif key in deferred or len(plan.promotions) >= limit: + deferred.add(key) + plan.deferred += 1 + else: + planned.add(key) + plan.promotions.append(Promotion(candidate["id"], topic_id, payload)) + return plan + + +def _status_difference(stored: Row, payload: Row) -> str | None: + suggested = (payload.get("keyset") or {}).get("status") + if suggested is None or stored.get("status") == suggested: + return None + return f"status: Keebdex {stored.get('status')}, topic {suggested}" diff --git a/src/aviary/magpie/promote.py b/src/aviary/magpie/promote.py new file mode 100644 index 0000000..b8eed71 --- /dev/null +++ b/src/aviary/magpie/promote.py @@ -0,0 +1,80 @@ +"""`magpie promote`: inserts the complete new keyset candidates into Keebdex +as Pending keysets with their kits; the rest wait for staff.""" + +import argparse +import logging +from datetime import UTC, datetime, timedelta + +from aviary.common.db import create_supabase, revision_source +from aviary.common.report import write_summary +from aviary.magpie import ingest, keebdex +from aviary.magpie.plan import PromotionPlan, plan_promotions +from aviary.magpie.summary import MAX_LISTED, topic_link + +log = logging.getLogger(__name__) + +# The revision source Keebdex shows magpie's keysets under: the job, then the +# site its candidates come from. +SOURCE = revision_source("magpie", "geekhack") + + +def promote_summary( + plan: PromotionPlan, result: keebdex.PromotionResult, dry_run: bool +) -> str: + verb = "Would insert" if dry_run else "Inserted" + failed, triaged = result.failed, result.triaged + inserted = [p for p in plan.promotions if p.topic_id not in failed + triaged] + differences = [r for r in plan.rematches if r.difference] + lines = [ + "## magpie promote", + "", + f"- {verb} (Pending): {len(inserted)}", + f"- Matched to a keyset Keebdex has (left for staff): {len(plan.rematches)}", + f"- Incomplete (left for staff): {len(plan.incomplete)}", + f"- Older than the cut-off (left for staff): {plan.old}", + f"- Left for the next run (limit): {plan.deferred}", + f"- Triaged by staff meanwhile (keyset removed again): {len(triaged)}", + f"- Failed: {len(failed)}", + ] + if inserted: + lines += ["", f"### {verb}", ""] + lines += [ + f"- `{p.key}` ({len(p.payload['kits'])} kits) from {topic_link(p.topic_id)}" + for p in inserted[:MAX_LISTED] + ] + if differences: + lines += ["", "### Different from Keebdex (left as stored)", ""] + lines += [ + f"- `{r.key}` ({topic_link(r.topic_id)}): {r.difference}" + for r in differences[:MAX_LISTED] + ] + if plan.incomplete: + lines += ["", "### Incomplete", ""] + lines += [f"- {topic_link(t)}: {m}" for t, m in plan.incomplete[:MAX_LISTED]] + if triaged: + lines += ["", "### Triaged by staff meanwhile", ""] + lines += [f"- {topic_link(t)}" for t in triaged[:MAX_LISTED]] + if failed: + lines += ["", "### Failed", ""] + lines += [f"- {topic_link(t)}" for t in failed[:MAX_LISTED]] + return "\n".join(lines) + + +def run_promote(args: argparse.Namespace) -> int: + client = create_supabase(SOURCE) + keysets = keebdex.fetch_keysets(client) + if not keysets: + log.error("Read no keysets from Keebdex, nothing written") + return 1 + since = datetime.now(UTC).date() - timedelta(days=args.max_age_days) + plan = plan_promotions( + ingest.fetch_waiting(client), + keysets, + limit=args.limit, + posted_since=since, + ) + result = keebdex.apply_promotions(client, plan, args.dry_run) + summary = promote_summary(plan, result, args.dry_run) + log.info("\n%s", summary) + write_summary(summary) + return 1 if result.failed else 0 diff --git a/src/aviary/magpie/proposal.py b/src/aviary/magpie/proposal.py new file mode 100644 index 0000000..fd08c06 --- /dev/null +++ b/src/aviary/magpie/proposal.py @@ -0,0 +1,276 @@ +"""Read a keyset candidate out of a crawled topic. Pure functions, no I/O. + +A candidate's payload is shaped like Keebdex's keyset submission: the +`keysets` columns under `keyset` and its `keyset_kits` under `kits`, without +moderation fields. Promoting it inserts both `Pending` with no submitter, the +way catalog-sync's vendor scraper proposes keysets. Keebdex's keyset review +queue lists keysets by their kits, so a payload always carries at least one +kit when it has an image. +""" + +import re +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime + +from aviary.common.db import Row +from aviary.common.slug import url_slugify +from aviary.magpie.classify import suggest +from aviary.magpie.geekhack import strip_prefix, topic_url +from aviary.magpie.kits import DETECTED_KITS +from aviary.magpie.parsers import KitImage + +# Bump when what extract() reads changes: the next crawl extracts every +# fetched thread again (ingest.candidates keeps one row per version and +# content). +EXTRACTOR_VERSION = "magpie-2" +MODULE = "Keyset" +PENDING = "Pending" + +# Everything after " | ", " - " or " : " is GB progress or a tagline ("| +# Shipping!", "- GB live", "Medusa : A Gaze Forged in Grief"), and so is +# everything after two spaces, which is where the listing drops a dash ("KBS +# Flat Out A Motorsport Inspired Keycap Set"). A colon needs spaces on both +# sides, so "Re:Zero" stays whole. +_TAIL_RE = re.compile(r"\s*\|.*$|\s+[-–—:]\s.*$|\s{2,}.*$") # noqa: RUF001 +# Notes in parentheses: progress ("(Cancelled)", "(R2 Update)"), new kits, +# and former names ("(Previously Brown on Beige)"). +_STATUS_PARENS_RE = re.compile( + r"\s*\((?=[^)]*\b(?:cancel\w*|update\w*|extras?|live|shipp\w*|production" + r"|complete\w*|ended|moq|sold out|in stock|new kits?|previously|formerly)\b)" + r"[^)]*\)", + re.IGNORECASE, +) +_ALBUM_MARKERS = ("/a/", "/gallery/") +# The row sculpt of nearly every Cherry-profile keyset in Keebdex; other +# profiles get none. +CHERRY_SCULPT = "1-1-2-3-4-4" + +# How sure extract() is of each field (0..1), for staff to see what to check: +# a title follows conventions, the thread starter is often a vendor rather +# than the designer, and the first image is often a render of a board. Names +# still carry taglines and notes often enough that staff should read them. +CONFIDENCE = { + "profile_id": 1.0, + "name": 0.6, + "slug": 0.6, + "url": 1.0, + "status": 0.8, + "ic_date": 0.9, + "designer": 0.5, + "sculpt": 0.6, + "img_labelled": 0.7, + "img_first": 0.4, + "kits_labelled": 0.7, + "kits_cover": 0.4, +} + + +@dataclass(frozen=True) +class Topic: + """A crawled topic: what a candidate is read from.""" + + topic_id: int + board: str + title: str + author: str + posted_at: datetime | None + kit_images: Sequence[KitImage] + + +@dataclass(frozen=True) +class Extraction: + """A keyset candidate. `missing` lists what magpie lacks to promote it + itself; staff can still complete it from the app.""" + + name: str | None + profile_id: str | None + payload: Row + confidence: dict[str, float] + missing: list[str] + # the keycap code the title starts with ("GMK"), found in Keebdex or not + profile_code: str | None = None + + @property + def key(self) -> str | None: + """The `profile_keyset_id` the keyset would get.""" + slug = self.payload["keyset"].get("slug") + return f"{self.profile_id}/{slug}" if self.profile_id and slug else None + + +def clean_keyset_name(title: str, prefixes: Sequence[str] = ()) -> str: + """The keyset name in a title: no `[GB]` tag, no progress tail, and none + of `prefixes` (the profile code, then the profile's own name, so "GMK CYL + Selene" under GMK's "CYL" profile is "Selene"). Never strips the name down + to nothing.""" + name = strip_prefix(title) + name = _TAIL_RE.sub("", name) + name = _STATUS_PARENS_RE.sub("", name) + name = name.strip(" .!-") + for prefix in prefixes: + rest = re.sub(rf"^{re.escape(prefix)}\s+", "", name, flags=re.IGNORECASE) + name = rest or name + return name + + +def guess_status(title: str, board: str) -> str: + """A `keyset_status`: Cancelled when the title says so, Interest Check on + the IC board, else Confirmed.""" + if re.search(r"cancel", title, re.IGNORECASE): + return "Cancelled" + return "Interest Check" if board == "ic" else "Confirmed" + + +def is_album(url: str) -> bool: + """An imgur album page: a link to several images, not an image.""" + return "imgur" in url and any(m in url for m in _ALBUM_MARKERS) + + +def usable_images(images: Sequence[KitImage]) -> list[KitImage]: + return [ + i + for i in images + if i.url.startswith(("http://", "https://")) and not is_album(i.url) + ] + + +def find_profile(code: str, profiles: Sequence[Row]) -> Row | None: + """The published profile a title's keycap code names, by `profile_id` + first ("gmk"), then by name ("KKB" is `keykobo`); None when nothing or + more than one profile matches.""" + code = code.lower() + for column in ("profile_id", "name"): + found = [p for p in profiles if (p.get(column) or "").lower() == code] + if len(found) == 1: + return found[0] + if found: + return None + return None + + +def extract(topic: Topic, profiles: Sequence[Row]) -> Extraction | None: + """The keyset candidate of a topic, or None when its title doesn't look + like a keyset (keyboards are not extracted yet).""" + suggestion = suggest(topic.title) + if suggestion.kind != "keyset": + return None + missing: list[str] = [] + confidence: dict[str, float] = {} + + codes = [suggestion.profile_code] if suggestion.profile_code else [] + profile = None + if codes: + # A second code names the profile within the maker's: "GMK MTNU + # Dasher" is MTNU's (`mtnu/dasher`), "GMK CYL Selene" GMK's own line. + words = strip_prefix(topic.title).split(maxsplit=2) + if len(words) > 2 and find_profile(words[1], profiles) is not None: + codes.append(words[1]) + profile = find_profile(codes[-1], profiles) + if profile is None: + missing.append(f"profile (no Keebdex profile for {codes[0]})") + else: + missing.append("profile (no profile code in the title)") + profile_id = profile["profile_id"] if profile else None + if profile_id: + confidence["profile_id"] = CONFIDENCE["profile_id"] + + prefixes = [*codes, profile["name"]] if profile else codes + name = clean_keyset_name(topic.title, prefixes) + if name.lower() in {p.lower() for p in prefixes}: + missing.append("name (only the profile in the title)") + name = "" + slug = url_slugify(name) if name else "" + if name and not slug: + missing.append(f"slug (none for {name!r})") + if slug: + confidence["name"] = CONFIDENCE["name"] + confidence["slug"] = CONFIDENCE["slug"] + + images = usable_images(topic.kit_images) + kit_images: dict[str, str] = {} + for image in images: + if image.kit is not None: + kit_images.setdefault(image.kit, image.url) + cover = kit_images.get("base") or (images[0].url if images else None) + if cover is None: + missing.append("cover image (no image in the first post)") + else: + labelled = "base" in kit_images + confidence["img"] = CONFIDENCE["img_labelled" if labelled else "img_first"] + confidence["kits"] = CONFIDENCE["kits_labelled" if kit_images else "kits_cover"] + + status = guess_status(topic.title, topic.board) + ic_date = ( + topic.posted_at.date() if topic.board == "ic" and topic.posted_at else None + ) + sculpt = CHERRY_SCULPT if profile and profile.get("profile") == "Cherry" else None + keyset = { + "profile_id": profile_id, + "name": name or None, + "slug": slug or None, + "designer": topic.author or None, + "sculpt": sculpt, + "img": cover, + "url": topic_url(topic.topic_id), + "status": status, + "ic_date": ic_date.isoformat() if ic_date else None, + } + for field in ("url", "status", "ic_date", "designer", "sculpt"): + if keyset[field]: + confidence[field] = CONFIDENCE[field] + + # No kit label in the post: one Base kit with the cover, so the keyset + # shows up in the review queue. `name` is only for a kit's own name ("TKL + # Base"); Keebdex shows the category's name when it is null. + chosen = kit_images or ({"base": cover} if cover else {}) + kits = [ + {"kit_id": kit, "name": None, "img": chosen[kit]} + for kit in DETECTED_KITS + if kit in chosen + ] + return Extraction( + name=name or None, + profile_id=profile_id, + profile_code=codes[0] if codes else None, + payload={"keyset": keyset, "kits": kits}, + confidence=confidence, + missing=missing, + ) + + +def missing_for_promotion(payload: Row) -> list[str]: + """What a stored payload lacks for magpie to insert it: the keyset's + required columns, a cover, and a kit.""" + keyset = payload.get("keyset") or {} + missing = [f for f in ("profile_id", "name", "slug", "img") if not keyset.get(f)] + if not payload.get("kits"): + missing.append("kits") + return missing + + +def keyset_row(payload: Row) -> Row: + """The `keysets` row a promoted payload inserts. The database sets + `profile_keyset_id` from profile and slug too; it is sent to the same + value.""" + keyset = payload["keyset"] + return { + **keyset, + "profile_keyset_id": f"{keyset['profile_id']}/{keyset['slug']}", + "review_status": PENDING, + "submitted_by": None, + } + + +def kit_rows(payload: Row) -> list[Row]: + """The `keyset_kits` rows a promoted payload inserts.""" + keyset = payload["keyset"] + key = f"{keyset['profile_id']}/{keyset['slug']}" + return [ + { + **kit, + "profile_keyset_id": key, + "review_status": PENDING, + "submitted_by": None, + } + for kit in payload["kits"] + ] diff --git a/src/aviary/magpie/reextract.py b/src/aviary/magpie/reextract.py new file mode 100644 index 0000000..65d1e38 --- /dev/null +++ b/src/aviary/magpie/reextract.py @@ -0,0 +1,131 @@ +"""`magpie reextract`: extracts every stored first post again with the +current extractor and saves candidates as `crawl` does, without requests to +Geekhack and without a crawl run.""" + +import argparse +import hashlib +import logging +from dataclasses import dataclass, field +from datetime import UTC, datetime +from itertools import batched + +from supabase import Client + +from aviary.common.db import Row, create_supabase +from aviary.common.report import write_summary +from aviary.magpie import ingest, keebdex +from aviary.magpie.crawl import candidate_row +from aviary.magpie.parsers import parse_post +from aviary.magpie.plan import KeysetIndex, stored_time +from aviary.magpie.proposal import EXTRACTOR_VERSION, Topic, extract +from aviary.magpie.summary import MAX_LISTED, topic_link + +log = logging.getLogger(__name__) + + +@dataclass +class ReextractCounters: + threads: int = 0 + not_keysets: int = 0 + added: int = 0 + restored: int = 0 + unchanged: int = 0 + # (topic id, error) of stored posts the parser can't read + parse_errors: list[tuple[str, str]] = field(default_factory=list) + + +def reextract_thread( + client: Client, + thread: Row, + raw_body: str, + profiles: list[Row], + index: KeysetIndex, + counters: ReextractCounters, + dry_run: bool, +) -> None: + """Extract one stored first post with the current extractor and save + its candidate as a crawl would.""" + counters.threads += 1 + topic_id = int(thread["external_id"]) + try: + content = parse_post(raw_body) + except ValueError as error: + log.warning("Topic %d: %s", topic_id, error) + counters.parse_errors.append((thread["external_id"], str(error))) + return + topic = Topic( + topic_id=topic_id, + board=thread["board"], + title=thread["title"] or "", + author=thread.get("author") or "", + posted_at=stored_time(thread.get("posted_at")), + kit_images=content.kit_images, + ) + extraction = extract(topic, profiles) + if extraction is None: + counters.not_keysets += 1 + return + content_hash = ( + thread.get("content_hash") or hashlib.sha256(raw_body.encode()).hexdigest() + ) + candidate = candidate_row(thread, content_hash, extraction, index) + saved = ingest.save_candidate(client, candidate, dry_run) + if saved == ingest.ADDED: + counters.added += 1 + elif saved == ingest.RESTORED: + counters.restored += 1 + else: + counters.unchanged += 1 + + +def reextract_summary(dry_run: bool, counters: ReextractCounters) -> str: + added = "Would add" if dry_run else "Added" + lines = [ + "## magpie reextract", + "", + f"- Extractor: {EXTRACTOR_VERSION}", + f"- Stored threads read: {counters.threads}", + f"- Not keysets: {counters.not_keysets}", + f"- {added} keyset candidates: {counters.added}", + f"- Waiting again (superseded before): {counters.restored}", + f"- Already extracted (skipped): {counters.unchanged}", + f"- Posts that could not be parsed: {len(counters.parse_errors)}", + ] + lines += [ + f" - {topic_link(t)}: {e}" for t, e in counters.parse_errors[:MAX_LISTED] + ] + return "\n".join(lines) + + +def run_reextract(args: argparse.Namespace) -> int: + """Read every stored first post again with the current extractor. No + requests to Geekhack and no crawl run (watermarks untouched), but never + while a crawl runs, so the two don't add the same candidates.""" + client = create_supabase() + profiles = keebdex.fetch_profiles(client) + keysets = keebdex.fetch_keysets(client) + if not profiles or not keysets: + log.error( + "Read %d profiles and %d keysets, nothing written", + len(profiles), + len(keysets), + ) + return 1 + if (run_id := ingest.running_run(client, datetime.now(UTC))) is not None: + log.error("Crawl run %d is running; not extracting meanwhile", run_id) + return 1 + threads = ingest.fetch_stored_threads(client)[: args.limit] + log.info("Extracting %d stored threads with %s", len(threads), EXTRACTOR_VERSION) + index = KeysetIndex(keysets) + counters = ReextractCounters() + for batch in batched(threads, ingest.BODY_BATCH_SIZE, strict=False): + bodies = ingest.stored_bodies(client, [thread["id"] for thread in batch]) + for thread in batch: + if (raw_body := bodies.get(thread["id"])) is not None: + reextract_thread( + client, thread, raw_body, profiles, index, counters, args.dry_run + ) + summary = reextract_summary(args.dry_run, counters) + log.info("\n%s", summary) + write_summary(summary) + return 0 diff --git a/src/aviary/magpie/summary.py b/src/aviary/magpie/summary.py new file mode 100644 index 0000000..22fb683 --- /dev/null +++ b/src/aviary/magpie/summary.py @@ -0,0 +1,10 @@ +"""What the job summaries of every magpie command share.""" + +from aviary.magpie.geekhack import topic_url + +# Rows listed in the log and job summary; the rest are only counted. +MAX_LISTED = 50 + + +def topic_link(topic_id: int | str) -> str: + return f"[{topic_id}]({topic_url(int(topic_id))})" diff --git a/tests/fixtures/magpie/board_132_0.html b/tests/fixtures/magpie/board_132_0.html new file mode 100644 index 0000000..8c3fac0 --- /dev/null +++ b/tests/fixtures/magpie/board_132_0.html @@ -0,0 +1,1681 @@ + + + + + + + + + + + + + + + Interest Checks + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ + +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Subject / Started byReplies / ViewsLast post
0 Members and 335 Guests are viewing this board. +
+ + + + + + + 2 Replies +
+ 257633 Views +
+ Last post + Thu, 18 March 2021, 10:40:10
+ by HoffmanMyster +
+ + + + + + + 3 Replies +
+ 70214 Views +
+ Last post + Mon, 16 November 2026, 05:06:29
+ by merca +
+ + + + + + + 0 Replies +
+ 2127 Views +
+ Last post + Sun, 15 November 2026, 18:08:41
+ by The Switch Journal +
+ + + + +
+ [IC] DCS Nights Alps/MX - GB Nov 18! +

Started by Kaptain Mike + «  1 2  All » +

+
+
+ 52 Replies +
+ 186785 Views +
+ Last post + Sun, 15 November 2026, 11:08:58
+ by Kaptain Mike +
+ + + + +
+ [IC] GMK Knight +

Started by Ephem_eral + +

+
+
+ 37 Replies +
+ 200384 Views +
+ Last post + Sat, 14 November 2026, 23:03:52
+ by KevinD2000 +
+ + + + + + + 10 Replies +
+ 27515 Views +
+ Last post + Sat, 14 November 2026, 19:28:44
+ by dvorcol +
+ + + + +
+ [IC]Doo&Do.25 | WYSE inspired +

Started by iSeS + +

+
+
+ 20 Replies +
+ 48407 Views +
+ Last post + Sat, 14 November 2026, 12:10:41
+ by SwearWolf +
+ + + + +
+ [IC] MW Zoltraak +

Started by mugen_ + +

+
+
+ 7 Replies +
+ 45335 Views +
+ Last post + Fri, 13 November 2026, 23:32:57
+ by SKYP.Lab +
+ + + + +
+ [IC] GMK CYL Mayan blue +

Started by nadhole69 + +

+
+
+ 5 Replies +
+ 9789 Views +
+ Last post + Fri, 13 November 2026, 23:27:27
+ by SKYP.Lab +
+ + + + + + + 18 Replies +
+ 20952 Views +
+ Last post + Fri, 13 November 2026, 21:37:20
+ by SKYP.Lab +
+ + + + +
+ [IC] GMK CYL Video 2048 +

Started by biip + +

+
+
+ 10 Replies +
+ 47627 Views +
+ Last post + Fri, 13 November 2026, 21:25:25
+ by SKYP.Lab +
+ + + + + + + 3 Replies +
+ 7164 Views +
+ Last post + Fri, 13 November 2026, 20:31:57
+ by Ortho Studio +
+ + + + + + + 5 Replies +
+ 53507 Views +
+ Last post + Fri, 13 November 2026, 15:18:37
+ by schizobovine +
+ + + + + + + 18 Replies +
+ 91804 Views +
+ Last post + Thu, 12 November 2026, 04:08:50
+ by tacahiroy +
+ + + + +
+ [IC] GMK CYL Hephaestus +

Started by Zetina + +

+
+
+ 17 Replies +
+ 99235 Views +
+ Last post + Thu, 05 November 2026, 12:02:22
+ by GMK_Andy +
+ + + + +
+ [IC] Constance 60 +

Started by aiglatsonstudio + +

+
+
+ 14 Replies +
+ 61882 Views +
+ Last post + Thu, 05 November 2026, 01:08:44
+ by aiglatsonstudio +
+ + + + +
+ [IC] KKB 1001 Nights +

Started by yowzers2026 + +

+
+
+ 6 Replies +
+ 48804 Views +
+ Last post + Wed, 04 November 2026, 21:09:27
+ by Narcolepsy +
+ + + + + + + 21 Replies +
+ 168626 Views +
+ Last post + Wed, 04 November 2026, 07:21:48
+ by minusxero +
+ + + + + + + 15 Replies +
+ 28875 Views +
+ Last post + Wed, 04 November 2026, 00:23:57
+ by lampmk +
+ + + + + + + 60 Replies +
+ 175146 Views +
+ Last post + Tue, 03 November 2026, 23:54:48
+ by BrianEF +
+ + + + + + + 26 Replies +
+ 105127 Views +
+ Last post + Tue, 03 November 2026, 23:44:44
+ by BrianEF +
+ + + + + + + 10 Replies +
+ 144923 Views +
+ Last post + Tue, 03 November 2026, 21:43:36
+ by BrianEF +
+ + + + + + + 11 Replies +
+ 82594 Views +
+ Last post + Sun, 01 November 2026, 20:39:17
+ by HungerMechanic +
+ + + + + + + 78 Replies +
+ 104930 Views +
+ Last post + Sun, 01 November 2026, 00:27:13
+ by hwalker84 +
+ + + + + + + 8 Replies +
+ 32824 Views +
+ Last post + Thu, 29 October 2026, 06:03:12
+ by meowoofun +
+ + + + + + + 0 Replies +
+ 28965 Views +
+ Last post + Thu, 29 October 2026, 03:44:53
+ by kkai +
+ + + + +
+ [IC] MTNU Dasher +

Started by nilslorand + +

+
+
+ 13 Replies +
+ 46244 Views +
+ Last post + Wed, 28 October 2026, 13:54:44
+ by konstantin +
+ + + + + + + 19 Replies +
+ 128601 Views +
+ Last post + Tue, 27 October 2026, 13:59:13
+ by Randomlosername +
+ + + + +
+ [IC] GSD Crib Artisan Tray +

Started by godsson + +

+
+
+ 1 Replies +
+ 33948 Views +
+ Last post + Mon, 26 October 2026, 11:56:32
+ by godsson +
+ + + + + + + 5 Replies +
+ 40819 Views +
+ Last post + Mon, 26 October 2026, 02:38:10
+ by swag +
+ + + + + + + 10 Replies +
+ 148055 Views +
+ Last post + Sat, 24 October 2026, 13:23:48
+ by Minisofu +
+ + + + + + + 19 Replies +
+ 68349 Views +
+ Last post + Fri, 23 October 2026, 12:44:23
+ by the flying penguin +
+ + + + + + + 0 Replies +
+ 32527 Views +
+ Last post + Fri, 23 October 2026, 09:46:46
+ by Klack! +
+ + + + +
+ [IC] KeyMaze Eden Sin +

Started by KeyMaze + +

+
+
+ 1 Replies +
+ 87582 Views +
+ Last post + Fri, 23 October 2026, 00:41:19
+ by dvorcol +
+ + + + +
+ [IC] GMK CYL Icon Beige +

Started by SumJoy + +

+
+
+ 48 Replies +
+ 157485 Views +
+ Last post + Tue, 20 October 2026, 12:29:29
+ by IBMweMissU +
+ + + + + + + 34 Replies +
+ 213437 Views +
+ Last post + Tue, 20 October 2026, 05:27:21
+ by mcmcmc +
+ + + + + + + 3 Replies +
+ 43675 Views +
+ Last post + Mon, 19 October 2026, 18:43:41
+ by danielsun23 +
+ + + + +
+ [IC] DCS Allsorts +

Started by basilkeys + +

+
+
+ 15 Replies +
+ 56900 Views +
+ Last post + Mon, 19 October 2026, 09:29:20
+ by Cheezο +
+ + + + +
+ [IC] GMK CYL Salamander +

Started by shiva1796 + +

+
+
+ 33 Replies +
+ 134186 Views +
+ Last post + Fri, 16 October 2026, 21:38:02
+ by dvorcol +
+ + + + +
+ [IC] GMK CYL Rareabic +

Started by godsson + +

+
+
+ 9 Replies +
+ 79509 Views +
+ Last post + Fri, 16 October 2026, 11:34:09
+ by Puddsy +
+ + + + + + + 28 Replies +
+ 170769 Views +
+ Last post + Tue, 13 October 2026, 22:16:51
+ by York Chan +
+ + + + +
+ [IC] PBTfans Genius #81 +

Started by sososoya + +

+
+
+ 3 Replies +
+ 53372 Views +
+ Last post + Tue, 13 October 2026, 20:03:47
+ by MartinThePolarBear +
+ + + + + + + 0 Replies +
+ 19585 Views +
+ Last post + Tue, 13 October 2026, 18:36:00
+ by iwilleatyrsnacks +
+ + + + +
+ [IC] SWG Retroguardia +

Started by raz + +

+
+
+ 36 Replies +
+ 91070 Views +
+ Last post + Mon, 12 October 2026, 10:09:27
+ by SKYP.Lab +
+ + + + + + + 36 Replies +
+ 204852 Views +
+ Last post + Mon, 12 October 2026, 10:07:01
+ by SKYP.Lab +
+ + + + + + + 113 Replies +
+ 193674 Views +
+ Last post + Sun, 11 October 2026, 21:59:22
+ by it99 +
+ + + + + + + 37 Replies +
+ 245262 Views +
+ Last post + Sun, 11 October 2026, 13:39:50
+ by MoltenKhor +
+ + + + + + + 50 Replies +
+ 238647 Views +
+ Last post + Sun, 11 October 2026, 03:09:17
+ by SKYP.Lab +
+ + + + +
+ [IC] DCS Cardio +

Started by tanghus + +

+
+
+ 22 Replies +
+ 134327 Views +
+ Last post + Fri, 09 October 2026, 15:28:30
+ by Frezzles +
+ + + + +
+ [IC] GMK Rainy Day | Round 3 +

Started by Owl + +

+
+
+ 19 Replies +
+ 190555 Views +
+ Last post + Wed, 07 October 2026, 21:15:14
+ by dvorcol +
+
+ +
+ + +
+ +
+
+

 

+

+ Normal Topic
+ Hot Topic (More than 40 replies)
+ Very Hot Topic (More than 70 replies) +

+

+ Locked Topic
+ Sticky Topic
+ Poll +

+ +
+
+
+ + +
+
+ +
+ + + + + \ No newline at end of file diff --git a/tests/fixtures/magpie/board_70_0.html b/tests/fixtures/magpie/board_70_0.html new file mode 100644 index 0000000..3ded088 --- /dev/null +++ b/tests/fixtures/magpie/board_70_0.html @@ -0,0 +1,1681 @@ + + + + + + + + + + + + + + + Group Buys and Preorders + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ + +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Subject / Started byReplies / ViewsLast post
0 Members and 126 Guests are viewing this board. +
+ + + + + + + 53 Replies +
+ 197126 Views +
+ Last post + Mon, 01 June 2026, 17:13:33
+ by Kokaloo +
+ + + + + + + 122 Replies +
+ 1258886 Views +
+ Last post + Mon, 02 February 2026, 16:26:20
+ by dragonfax +
+ + + + + + + 50 Replies +
+ 278455 Views +
+ Last post + Fri, 07 March 2025, 13:01:39
+ by HoffmanMyster +
+ + + + + + + 3 Replies +
+ 117147 Views +
+ Last post + Wed, 08 January 2025, 04:07:06
+ by smithcohn12 +
+ + + + + + + 27 Replies +
+ 146139 Views +
+ Last post + Mon, 06 May 2024, 20:06:47
+ by zebus +
+ + + + + + + 0 Replies +
+ 47043 Views +
+ Last post + Wed, 14 February 2024, 10:25:57
+ by HoffmanMyster +
+ + + + + + + 107 Replies +
+ 366843 Views +
+ Last post + Sat, 09 December 2023, 17:23:00
+ by DaaDaa +
+ + + + + + + 31 Replies +
+ 375114 Views +
+ Last post + Mon, 26 September 2022, 01:41:33
+ by MMJ1999 +
+ + + + + + + 19 Replies +
+ 39818 Views +
+ Last post + Thu, 05 November 2026, 19:34:26
+ by dvorcol +
+ + + + +
+ [GB] GMK MTNU Dasher +

Started by nilslorand + +

+
+
+ 3 Replies +
+ 4036 Views +
+ Last post + Thu, 05 November 2026, 09:49:52
+ by tavapataor +
+ + + + + + + 3 Replies +
+ 19401 Views +
+ Last post + Thu, 05 November 2026, 02:57:12
+ by Minisofu +
+ + + + + + + 4 Replies +
+ 20250 Views +
+ Last post + Wed, 04 November 2026, 15:46:10
+ by DashanYYY +
+ + + + + + + 3 Replies +
+ 9886 Views +
+ Last post + Wed, 04 November 2026, 08:31:57
+ by Shark +
+ + + + + + + 15 Replies +
+ 201886 Views +
+ Last post + Wed, 04 November 2026, 01:41:10
+ by BrianEF +
+ + + + + + + 20 Replies +
+ 198382 Views +
+ Last post + Wed, 04 November 2026, 00:35:35
+ by BrianEF +
+ + + + +
+ [GB] GMK Masterpiece +

Started by Energieschleuder + «  1 2 3 4 5 » +

+
+
+ 207 Replies +
+ 487832 Views +
+ Last post + Wed, 04 November 2026, 00:24:17
+ by BrianEF +
+ + + + + + + 7 Replies +
+ 114394 Views +
+ Last post + Tue, 03 November 2026, 21:22:11
+ by BrianEF +
+ + + + + + + 3588 Replies +
+ 3492599 Views +
+ Last post + Tue, 03 November 2026, 15:45:52
+ by Ellipse +
+ + + + + + + 7 Replies +
+ 52289 Views +
+ Last post + Mon, 02 November 2026, 09:30:14
+ by MoltenKhor +
+ + + + +
+ [GB] GMK CYL Blanks +

Started by mcmcmc + +

+
+
+ 9 Replies +
+ 29884 Views +
+ Last post + Fri, 30 October 2026, 23:25:36
+ by dvorcol +
+ + + + + + + 237 Replies +
+ 682781 Views +
+ Last post + Thu, 29 October 2026, 21:02:26
+ by Ellipse +
+ + + + + + + 11 Replies +
+ 102202 Views +
+ Last post + Thu, 29 October 2026, 16:25:11
+ by dvorcol +
+ + + + +
+ [GB] GMK Salamander +

Started by shiva1796 + +

+
+
+ 5 Replies +
+ 27683 Views +
+ Last post + Wed, 28 October 2026, 19:32:45
+ by dvorcol +
+ + + + + + + 18 Replies +
+ 154791 Views +
+ Last post + Wed, 28 October 2026, 14:41:33
+ by ARSLOCK +
+ + + + + + + 5 Replies +
+ 37262 Views +
+ Last post + Sun, 25 October 2026, 11:47:55
+ by dvorcol +
+ + + + + + + 23 Replies +
+ 68742 Views +
+ Last post + Sat, 24 October 2026, 11:21:23
+ by Piperaceae +
+ + + + + + + 13 Replies +
+ 41768 Views +
+ Last post + Tue, 20 October 2026, 21:37:19
+ by NoWrinkles +
+ + + + +
+ [GB] GMK CYL Dinokidz +

Started by mcmcmc + +

+
+
+ 4 Replies +
+ 64442 Views +
+ Last post + Tue, 20 October 2026, 05:26:05
+ by mcmcmc +
+ + + + + + + 14 Replies +
+ 89623 Views +
+ Last post + Tue, 20 October 2026, 04:36:02
+ by yoonelec +
+ + + + +
+ [GB] Code:002 TKL +

Started by Sinner + +

+
+
+ 0 Replies +
+ 31785 Views +
+ Last post + Sat, 17 October 2026, 06:46:12
+ by Sinner +
+ + + + +
+ [GB]Space66% Spaceforge +

Started by AIRPOTTER + +

+
+
+ 2 Replies +
+ 36789 Views +
+ Last post + Fri, 16 October 2026, 23:56:20
+ by AIRPOTTER +
+ + + + +
+ [GB] MW Meteor Dreams +

Started by Bobatype + +

+
+
+ 1 Replies +
+ 34086 Views +
+ Last post + Tue, 13 October 2026, 18:10:06
+ by dvorcol +
+ + + + + + + 26 Replies +
+ 166667 Views +
+ Last post + Tue, 13 October 2026, 18:05:36
+ by Shark +
+ + + + + + + 1 Replies +
+ 35176 Views +
+ Last post + Tue, 13 October 2026, 11:25:23
+ by HoffmanMyster +
+ + + + + + + 9 Replies +
+ 165825 Views +
+ Last post + Thu, 08 October 2026, 14:22:42
+ by nathanchere +
+ + + + + + + 5 Replies +
+ 163183 Views +
+ Last post + Thu, 08 October 2026, 06:14:05
+ by Karmeck +
+ + + + + + + 17 Replies +
+ 182681 Views +
+ Last post + Wed, 07 October 2026, 03:33:48
+ by Bagri +
+ + + + +
+ [GB] Sagittarius optimized ergo +

Started by Gondolindrim + «  1 2 3  All » +

+
+
+ 147 Replies +
+ 165477 Views +
+ Last post + Sat, 03 October 2026, 08:00:01
+ by disarmyouwitha +
+ + + + + + + 12 Replies +
+ 134768 Views +
+ Last post + Fri, 02 October 2026, 20:19:59
+ by baucts +
+ + + + + + + 7 Replies +
+ 147530 Views +
+ Last post + Fri, 02 October 2026, 09:49:00
+ by jigumina +
+ + + + + + + 14 Replies +
+ 154198 Views +
+ Last post + Wed, 30 September 2026, 07:45:16
+ by Thebloodyez +
+ + + + +
+ [GB] SWG Art (cancelled) +

Started by Afresh + +

+
+
+ 3 Replies +
+ 58219 Views +
+ Last post + Tue, 29 September 2026, 22:22:54
+ by dvorcol +
+ + + + + + + 4 Replies +
+ 108281 Views +
+ Last post + Thu, 24 September 2026, 18:14:35
+ by dvorcol +
+ + + + + + + 12 Replies +
+ 147303 Views +
+ Last post + Wed, 23 September 2026, 00:29:51
+ by dvorcol +
+ + + + + + + 37 Replies +
+ 104915 Views +
+ Last post + Sun, 20 September 2026, 10:52:43
+ by Piperaceae +
+ + + + + + + 47 Replies +
+ 335168 Views +
+ Last post + Fri, 18 September 2026, 22:15:47
+ by DiscountSprout +
+ + + + + + + 3 Replies +
+ 98892 Views +
+ Last post + Fri, 18 September 2026, 03:22:25
+ by Gtour +
+ + + + + + + 44 Replies +
+ 132609 Views +
+ Last post + Tue, 08 September 2026, 14:11:11
+ by dvorcol +
+ + + + +
+ [GB] GMK Ishtar R2 +

Started by Bachoo + +

+
+
+ 12 Replies +
+ 113476 Views +
+ Last post + Tue, 01 September 2026, 17:07:08
+ by dvorcol +
+ + + + + + + 8 Replies +
+ 182788 Views +
+ Last post + Sun, 30 August 2026, 09:04:33
+ by victoriarose101 +
+
+ +
+ + +
+ +
+
+

 

+

+ Normal Topic
+ Hot Topic (More than 40 replies)
+ Very Hot Topic (More than 70 replies) +

+

+ Locked Topic
+ Sticky Topic
+ Poll +

+ +
+
+
+ + +
+
+ +
+ + + + + \ No newline at end of file diff --git a/tests/fixtures/magpie/topic_127176.html b/tests/fixtures/magpie/topic_127176.html new file mode 100644 index 0000000..3227a2a --- /dev/null +++ b/tests/fixtures/magpie/topic_127176.html @@ -0,0 +1,1497 @@ + + + + + + + + + + + + + + + [GB] DSS Drank Round 2 - 40% Monokit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ + + +
+ +
+ +
+ +
+
+
+

+ + Author + Topic: [GB] DSS Drank Round 2 - 40% Monokit  (Read 39819 times) +

+
+

0 Members and 1 Guest are viewing this topic. +

+
+
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ [GB] DSS Drank Round 2 - 40% Monokit +
+
« on: Sun, 04 October 2026, 13:18:44 »
+
+
+
+
+
Introducing DSS Drank R2! After over 5 long years, this classic color way is back! It features updated kitting to cover most modern 40% keyboard layouts. Convex DSA spacebars, QAZ legends, multiple novelties and LAE/ISO keys are now included. Drank R2 brings that purple fix you’ve been waiting for!


Details:

Monokit: $130 (MoQ 50)
Color codes: Light Purple (RCJ), Dark Purple (RDA), White (WA)
Doubleshot ABS in DSS profile (1-2-3-4-3 sculpt)
Convex DSA Space Bars
Manufactured by Signature Plastics
Trashcon Icons by Trashman
Group buy period: October 9, 2026 - November 6, 2026
Manufacturing time: 12 weeks
Fulfillment: February 2027

Vendor: https://keyboardarcade.xyz


318293-0


A colemak/colemak-dh child kit is being ran by MostCallMeAndy in the 40s Keyboard discord. Please fill out the IC form, if you are interested!!

Colemak IC Form: https://forms.gle/RGDf7bF9Y5dRcfwx9


318301-1
+
+ +
+
+
+ « Last Edit: Sun, 04 October 2026, 22:04:42 by MikeTheTiger » +
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #1 on: Sun, 04 October 2026, 13:27:37 »
+
+
+
+
+
318295-0318297-1318299-2
+
+ +
+
+
+ « Last Edit: Sun, 04 October 2026, 13:33:46 by MikeTheTiger » +
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #2 on: Sun, 04 October 2026, 13:32:30 »
+
+
+
+
+
10/23/2026 Update: We are currently halfway through the group buy and halfway to MoQ. Thank you so much for everyone who has joined so far!! We are in the final 2 weeks of the GB now. Get in before November 6th, as extras may be limited.
+
+
+
+
+ « Last Edit: Fri, 23 October 2026, 17:21:46 by MikeTheTiger » +
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #3 on: Fri, 09 October 2026, 22:14:55 »
+
+
+
+
+
It’s been a great first day!! 11 sold to far.
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + HoffmanMyster +

+
    +
  • HOFF, smol MAN OF MYSTERY
  • +
  • * Senior Moderator
  • +
  • + + + +
  • +
  • Posts: 11676
  • Location: WI
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #4 on: Tue, 13 October 2026, 11:21:12 »
+
+
+
+
+
Approved! :thumb:
+
+
+
+
+
+ + +
+
+ +
+
+ +
+ +
+
+

+ Offline + bombay.duck +

+
    +
  • +
  • + + + +
  • +
  • Posts: 37
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #5 on: Tue, 13 October 2026, 13:02:08 »
+
+
+
+
+
First
+
+
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #6 on: Tue, 13 October 2026, 13:10:25 »
+
+
+
+
+ +
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #7 on: Tue, 13 October 2026, 16:19:14 »
+
+
+
+
+
+
+
+
+
+ « Last Edit: Tue, 13 October 2026, 16:27:45 by dvorcol » +
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #8 on: Sat, 17 October 2026, 00:36:15 »
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #9 on: Sat, 17 October 2026, 10:26:19 »
+
+
+
+
+
We are doing great after the first week!! Almost halfway to MoQ.
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #10 on: Fri, 23 October 2026, 17:21:58 »
+
+
+
+
+
10/23/2026 Update: We are currently halfway through the group buy and halfway to MoQ. Thank you so much for everyone who has joined so far!! We are in the final 2 weeks of the GB now. Get in before November 6th, as extras may be limited.
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #11 on: Fri, 23 October 2026, 22:24:23 »
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #12 on: Mon, 26 October 2026, 01:07:28 »
+
+
+
+
+
318593-0

318595-1

318597-2" alt="" class="bbc_img" />
+
+ +
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #13 on: Wed, 28 October 2026, 20:30:53 »
+
+
+
+
+
Current order count: 27

We have less than 2 weeks to go. Let's finish strong!!
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #14 on: Thu, 29 October 2026, 18:46:10 »
+
+
+
+
+
+
+
+
+
+ « Last Edit: Thu, 29 October 2026, 19:57:18 by dvorcol » +
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #15 on: Sun, 01 November 2026, 10:17:07 »
+
+
+
+
+
Current order count: 33

The Group Buy ends Friday November 6, 2026. Get in before time runs out!!

https://keyboardarcade.xyz
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #16 on: Sun, 01 November 2026, 15:55:54 »
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #17 on: Thu, 05 November 2026, 12:32:08 »
+
+
+
+
+
We are currently at 37 sets sold. I’m going to extend the end date for this group buy until this Sunday to allow a bit more time for us to get closer to MoQ. We are just a handful of sets away from making this happen.

After SA Paperwork launches and concludes, I will be switching things up a bit on kitting. I want to target a lower MoQ (25) moving forward. This means that some “obscure” coverage will be dropped, with preference given to the more popular modern layouts out there. It has been quite difficult for a 40% set to hit 50 MoQ recently on its own without a buyout. I always strive to offer wider coverage to make as many people happy as possible, but these larger kits are proving to be unsustainable.

I hope we finish strong over the next few days and we can get round 2 into the production queue. Thank you to everyone for joining and their continued support. ❤️
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + MikeTheTiger +

+
    +
  • +
  • + Thread Starter +
  • +
  • + + + +
  • +
  • Posts: 887
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #18 on: Thu, 05 November 2026, 15:52:30 »
+
+
+
+
+
Great news!! We have secured enough orders to be able to enter production!! I’ll still leave the store up until Sunday, but Drank Round 2 is getting made!!
+
+
+
+
+
+ +
"all the numbers or none of them cmon man" -Kokaloo
+
+
+ +
+
+ +
+ +
+
+

+ Offline + dvorcol +

+
    +
  • +
  • + + + +
  • +
  • Posts: 3919
  • Location: MI-US
  • +
  • Discord: dvorcol_5071
  • +
  • +
      +
    +
  • +
+
+
+
+
+
+ +
+
+ Re: [GB] DSS Drank Round 2 - 40% Monokit +
+
« Reply #19 on: Thu, 05 November 2026, 19:34:26 »
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+ +
+ +
+ + +
+ +
+
 
+
+ + + +
+
+ +
+ + + + + \ No newline at end of file diff --git a/tests/magpie_fakes.py b/tests/magpie_fakes.py new file mode 100644 index 0000000..db31466 --- /dev/null +++ b/tests/magpie_fakes.py @@ -0,0 +1,99 @@ +"""Stand-ins for Keebdex and the `ingest` schema shared by magpie's tests.""" + +PROFILES = [{"profile_id": "gmk", "name": "CYL", "profile": "Cherry"}] + + +def keyset(): + return { + "id": 1, + "profile_id": "gmk", + "slug": "old", + "profile_keyset_id": "gmk/old", + "url": None, + "status": "Confirmed", + } + + +class Table: + def __init__(self, db, name): + self.db, self.name, self.op, self.filters = db, name, None, [] + + def insert(self, rows): + self.op, self.rows = "insert", rows if isinstance(rows, list) else [rows] + return self + + def update(self, values): + self.op, self.values = "update", values + return self + + def delete(self): + self.op = "delete" + return self + + def select(self, columns): + self.op = "select" + return self + + def eq(self, column, value): + self.filters.append((column, value)) + return self + + def execute(self): + if {self.name, (self.name, self.op)} & self.db.failing: + raise RuntimeError(f"{self.name} {self.op} refused") + table = self.db.rows[self.name] + hit = [r for r in table if all(r.get(c) == v for c, v in self.filters)] + if self.op == "delete": + self.db.rows[self.name] = [r for r in table if r not in hit] + elif self.op == "update": + for row in hit: + row.update(self.values) + elif self.op == "insert": + if self.name in self.db.dropped: + # a before-insert trigger returned null + hit = [] + elif self.name == "candidates": + hit = [self._supersede(table, row) for row in self.rows] + hit = [row for row in hit if row is not None] + else: + hit = [{"id": len(table) + 1, **r} for r in self.rows] + table += hit + if (self.name, self.op) in self.db.lost: + raise RuntimeError(f"{self.name} {self.op}: response lost") + return type("Response", (), {"data": hit}) + + @staticmethod + def _supersede(table, row): + """candidates_supersede: an extraction already made is not inserted + again (a superseded one waits again); a new one supersedes the + thread's waiting candidate.""" + key = ("thread_id", "module", "extractor_version", "content_hash") + same = [r for r in table if all(r.get(k) == row.get(k) for k in key)] + if same: + if same[0].get("state") == "superseded": + same[0]["state"] = "new" + return None + for other in table: + if ( + other.get("thread_id") == row["thread_id"] + and other.get("state") == "new" + ): + other["state"] = "superseded" + inserted = {"id": len(table) + 1, "state": "new", **row} + table.append(inserted) + return inserted + + +class FakeClient: + def __init__(self, candidates, failing=(), lost=(), dropped=()): + # failing: refused before applying; lost: applied, then the response + # never came back; dropped: inserts a trigger turned away + self.failing, self.lost, self.dropped = set(failing), set(lost), set(dropped) + self.rows = {"keysets": [], "keyset_kits": [], "candidates": candidates} + + def table(self, name): + return Table(self, name) + + def schema(self, name): + assert name == "ingest" + return self diff --git a/tests/test_magpie_crawl.py b/tests/test_magpie_crawl.py new file mode 100644 index 0000000..8509c1b --- /dev/null +++ b/tests/test_magpie_crawl.py @@ -0,0 +1,284 @@ +"""`magpie crawl` with the network and the database stubbed out.""" + +from datetime import UTC, datetime + +import pytest +from magpie_fakes import PROFILES, keyset + +from aviary.magpie import __main__ as magpie +from aviary.magpie import crawl as crawler +from aviary.magpie import ingest, keebdex +from aviary.magpie.fetch import FetchError +from aviary.magpie.parsers import BoardPage, KitImage, TopicDetail, TopicSummary +from aviary.magpie.plan import KeysetIndex + +LAST_POST = "Thu, 05 November 2026, 10:00:00" + + +def summary(topic_id, last_post_at=LAST_POST): + return TopicSummary(topic_id, f"[GB] GMK T{topic_id}", "a", 0, 0, last_post_at) + + +class Site: + """A board of pages; a page that is an exception raises.""" + + def __init__(self, pages): + self.pages, self.read = pages, [] + + def get(self, url): + offset = int(url.rsplit(".", 1)[1]) + self.read.append(offset) + page = self.pages[offset // 50] + if isinstance(page, Exception): + raise page + return page + + def parse(self, topics, offset): + has_next = offset // 50 + 1 < len(self.pages) + return BoardPage(topics, offset + 50 if has_next else None) + + def close(self): + pass + + +@pytest.fixture +def site(monkeypatch): + def setup(pages): + board = Site(pages) + monkeypatch.setattr(crawler, "parse_board", board.parse) + return board + + return setup + + +def test_list_board_stops_at_the_cap(site): + board = site([[summary(1)], [summary(2)], [summary(3)]]) + listing = crawler.list_board(board, "gb", None, max_pages=2) + assert board.read == [0, 50] + assert not listing.done + + +def test_list_board_stops_at_the_watermark(site): + board = site([[summary(1)], [summary(2)]]) + mark = datetime(2026, 11, 5, 10, tzinfo=UTC) + assert crawler.list_board(board, "gb", mark, max_pages=5).done + assert board.read == [0] + + +def test_an_empty_page_fails_the_listing(site): + with pytest.raises(crawler.CrawlError): + crawler.list_board(site([[summary(1)], []]), "gb", None, max_pages=5) + + +@pytest.fixture +def crawl_env(monkeypatch, site): + """A crawl against a stubbed database; `written` holds what it wrote.""" + written = {"listing": [], "finish": []} + + def setup(pages, due=()): + board = site(pages) + monkeypatch.setattr(crawler, "create_supabase", lambda: None) + monkeypatch.setattr(crawler, "Fetcher", lambda: board) + monkeypatch.setattr(keebdex, "fetch_profiles", lambda c: PROFILES) + monkeypatch.setattr(keebdex, "fetch_keysets", lambda c: [keyset()]) + monkeypatch.setattr(ingest, "last_watermarks", lambda c: {}) + monkeypatch.setattr(ingest, "start_run", lambda c, pages, now: 9) + monkeypatch.setattr(ingest, "fetch_threads", lambda c: {}) + monkeypatch.setattr( + ingest, + "save_listing", + lambda c, b, plan, dry: written["listing"].append((b, plan)), + ) + monkeypatch.setattr(ingest, "due_threads", lambda c, limit, now: list(due)) + monkeypatch.setattr( + ingest, + "finish_run", + lambda c, run, values: written["finish"].append(values), + ) + return board + + return setup, written + + +def test_a_failed_board_writes_no_listing_and_fails_the_run(crawl_env): + setup, written = crawl_env + setup([[summary(1)], FetchError("HTTP 500", 500)]) + assert magpie.main(["crawl", "--board", "gb"]) == 1 + assert written["listing"] == [] + (finish,) = written["finish"] + assert finish["status"] == "failed" + # a failed run never moves the watermark + assert finish["watermarks"] == {} + + +def test_a_complete_listing_moves_the_watermark(crawl_env): + setup, written = crawl_env + setup([[summary(1), summary(2, "Thu, 05 November 2026, 09:00:00")]]) + assert magpie.main(["crawl", "--board", "gb"]) == 0 + (finish,) = written["finish"] + assert finish["status"] == "succeeded" + assert finish["watermarks"] == {"gb": "2026-11-05T10:00:00+00:00"} + assert (finish["threads_listed"], finish["threads_new"]) == (2, 2) + assert finish["incomplete_boards"] == [] + + +def test_another_running_run_stops_the_crawl(crawl_env, monkeypatch): + setup, written = crawl_env + setup([[summary(1)]]) + + def running(c, pages, now): + raise ingest.RunningError("crawl run 3 is still running") + + monkeypatch.setattr(ingest, "start_run", running) + assert magpie.main(["crawl"]) == 1 + assert written["listing"] == [] + + +class Fetches: + def __init__(self, result): + self.result = result + + def get(self, url): + if isinstance(self.result, Exception): + raise self.result + return self.result + + +def crawl(monkeypatch, result, writes): + monkeypatch.setattr(crawler, "parse_topic", lambda html: html) + monkeypatch.setattr( + ingest, + "update_thread", + lambda c, t, values, dry: writes.append(("thread", values)), + ) + monkeypatch.setattr( + ingest, + "save_candidate", + lambda c, row, dry: writes.append(("candidate", row)) or ingest.ADDED, + ) + return crawler.Crawl( + None, Fetches(result), PROFILES, KeysetIndex([keyset()]), False + ) + + +THREAD = { + "id": 3, + "external_id": "100", + "board": "gb", + "title": "[GB] GMK CYL Selene", + "content_hash": None, + "fetch_attempts": 0, +} + + +def test_a_fetched_thread_stores_its_post_and_adds_a_candidate(monkeypatch): + writes = [] + detail = TopicDetail( + title="x", + author="someone", + posted_at="Sat, 14 November 2026, 23:03:52", + body='
hi
', + kit_images=[KitImage("https://i.example/a.png")], + ) + run = crawl(monkeypatch, detail, writes) + run.fetch(THREAD) + (_, thread), (_, candidate) = writes + assert thread["raw_body"] == '
hi
' + assert thread["changed_at"] == thread["fetched_at"] + assert (thread["name"], thread["profile_id"]) == ("Selene", "gmk") + assert thread["images"] == ["https://i.example/a.png"] + assert thread["posted_at"] == "2026-11-14T23:03:52+00:00" + assert candidate["thread_id"] == 3 + assert candidate["content_hash"] == thread["content_hash"] + assert candidate["match_key"] is None + assert candidate["payload"]["keyset"]["slug"] == "selene" + # the first fetch is not an edit + assert run.counters.threads_changed == 0 + + +def test_a_candidate_of_a_keyset_keebdex_has_gets_its_match_key(monkeypatch): + writes = [] + detail = TopicDetail( + posted_at="Sat, 14 November 2026, 23:03:52", + body="b", + kit_images=[KitImage("https://i.example/a.png")], + ) + run = crawl(monkeypatch, detail, writes) + run.fetch({**THREAD, "title": "[GB] GMK Old R2", "content_hash": "x"}) + run.fetch({**THREAD, "title": "[GB] GMK Old"}) + candidates = [row for kind, row in writes if kind == "candidate"] + assert [c["match_key"] for c in candidates] == [None, "gmk/old"] + assert run.counters.threads_changed == 1 + + +def test_a_restored_candidate_is_counted_apart_from_added_ones(monkeypatch): + detail = TopicDetail( + posted_at="Sat, 14 November 2026, 23:03:52", + body="b", + kit_images=[KitImage("https://i.example/a.png")], + ) + run = crawl(monkeypatch, detail, []) + monkeypatch.setattr(ingest, "save_candidate", lambda c, row, dry: ingest.RESTORED) + run.fetch(THREAD) + assert (run.counters.candidates, run.counters.candidates_restored) == (0, 1) + summary = crawler.crawl_summary(False, run.counters, [], None) + assert "Added keyset candidates: 0" in summary + assert "earlier version): 1" in summary + # not a crawl_runs column + assert "candidates_restored" not in run.counters.columns() + + +def test_the_summary_lists_profiles_keebdex_does_not_have(monkeypatch): + detail = TopicDetail( + posted_at="Sat, 14 November 2026, 23:03:52", + body="b", + kit_images=[KitImage("https://i.example/a.png")], + ) + run = crawl(monkeypatch, detail, []) + # Keebdex has only GMK here (PROFILES) + for title in ( + "[GB] SWG Art", + "[GB] SWG Bloom", + "[IC] DSS Drank", + "[GB] KBS Flat Out keycaps", + "[GB] GMK Selene", + ): + run.fetch({**THREAD, "title": title}) + assert run.counters.unknown_profiles == { + "SWG": ["[GB] SWG Art", "[GB] SWG Bloom"], + "DSS": ["[IC] DSS Drank"], + } + assert run.counters.no_profile_code == 1 + summary = crawler.crawl_summary(False, run.counters, [], None) + section = summary.split("### Unknown profiles")[1] + assert section.splitlines()[2:] == [ + "- `SWG`: 2 threads: [GB] SWG Art; [GB] SWG Bloom", + "- `DSS`: 1 thread: [IC] DSS Drank", + "- No profile code in the title: 1 thread", + ] + # only reported, not crawl_runs columns + assert "unknown_profiles" not in run.counters.columns() + + +def test_a_summary_without_unknown_profiles_has_no_such_section(): + summary = crawler.crawl_summary(False, crawler.Counters(), [], None) + assert "Unknown profiles" not in summary + + +def test_a_404_marks_the_thread_gone(monkeypatch): + writes = [] + crawl(monkeypatch, FetchError("HTTP 404", 404), writes).fetch(THREAD) + ((_, values),) = writes + assert values["gone_at"] is not None + assert values["next_fetch_at"] is None + + +def test_other_failures_back_off(monkeypatch): + writes = [] + run = crawl(monkeypatch, ValueError("no post found"), writes) + run.fetch(THREAD) + ((_, values),) = writes + assert values["fetch_attempts"] == 1 + assert values["next_fetch_at"] is not None + assert values["fetch_error"] == "no post found" + assert run.counters.threads_failed == 1 diff --git a/tests/test_magpie_fetch.py b/tests/test_magpie_fetch.py new file mode 100644 index 0000000..fd21800 --- /dev/null +++ b/tests/test_magpie_fetch.py @@ -0,0 +1,129 @@ +"""The polite Geekhack fetcher against a fake site.""" + +import httpx +import pytest + +from aviary.magpie.fetch import MAX_ATTEMPTS, Fetcher, FetchError + +ROBOTS = "User-agent: *\nDisallow:\n" +TOPIC = "https://geekhack.org/index.php?topic=1.0" + + +def fetcher(handler, sleeps=None): + client = httpx.Client(transport=httpx.MockTransport(handler)) + sleep = sleeps.append if sleeps is not None else lambda _: None + return Fetcher(client=client, delay=0, backoff=1, sleep=sleep) + + +def site(responses): + """Robots allow everything; topic requests get `responses` in turn.""" + calls = [] + + def handler(request): + if request.url.path == "/robots.txt": + return httpx.Response(200, text=ROBOTS) + calls.append(request) + return responses[len(calls) - 1] + + return handler, calls + + +def test_pages_without_a_charset_are_read_as_cp1252(): + handler, _ = site([httpx.Response(200, content=b"caf\xe9 \x93")]) + assert fetcher(handler).get(TOPIC) == "caf\xe9 \u201c" + + +def test_server_errors_are_retried_with_backoff(): + sleeps = [] + handler, calls = site( + [httpx.Response(503), httpx.Response(429), httpx.Response(200)] + ) + assert fetcher(handler, sleeps).get(TOPIC) == "" + assert len(calls) == 3 + assert sleeps == [1, 2] + + +def test_retries_give_up_after_max_attempts(): + handler, calls = site([httpx.Response(500)] * MAX_ATTEMPTS) + with pytest.raises(FetchError, match="500"): + fetcher(handler).get(TOPIC) + assert len(calls) == MAX_ATTEMPTS + + +def test_client_errors_are_not_retried(): + handler, calls = site([httpx.Response(404)]) + with pytest.raises(FetchError, match="404"): + fetcher(handler).get(TOPIC) + assert len(calls) == 1 + + +def test_robots_txt_is_respected(): + def handler(request): + if request.url.path == "/robots.txt": + return httpx.Response(200, text="User-agent: *\nDisallow: /index.php\n") + raise AssertionError("fetched a disallowed page") + + with pytest.raises(FetchError, match="robots"): + fetcher(handler).get(TOPIC) + + +def robots_site(robots_responses): + """robots.txt answers `robots_responses` in turn; pages answer 200.""" + robots_calls = [] + + def handler(request): + if request.url.path == "/robots.txt": + robots_calls.append(request) + return robots_responses[len(robots_calls) - 1] + return httpx.Response(200, text="page") + + return handler, robots_calls + + +def test_a_missing_robots_txt_means_no_rules(): + handler, _ = robots_site([httpx.Response(404)]) + assert fetcher(handler).get(TOPIC) == "page" + + +def test_a_robots_txt_server_error_is_retried(): + handler, robots_calls = robots_site( + [httpx.Response(503), httpx.Response(200, text=ROBOTS)] + ) + assert fetcher(handler).get(TOPIC) == "page" + assert len(robots_calls) == 2 + + +def test_an_unreachable_robots_txt_fetches_nothing(): + handler, robots_calls = robots_site([httpx.Response(503)] * MAX_ATTEMPTS) + with pytest.raises(FetchError, match=r"robots\.txt unreachable"): + fetcher(handler).get(TOPIC) + assert len(robots_calls) == MAX_ATTEMPTS + + +def test_requests_wait_for_the_delay(): + sleeps = [] + handler, _ = site([httpx.Response(200), httpx.Response(200)]) + polite = Fetcher( + client=httpx.Client(transport=httpx.MockTransport(handler)), + delay=60, + sleep=sleeps.append, + ) + polite.get(TOPIC) + polite.get(TOPIC) + # robots.txt went first; both pages waited for the one before + assert len(sleeps) == 2 + assert all(s > 59 for s in sleeps) + + +def test_first_request_does_not_wait_on_a_fresh_machine(monkeypatch): + """monotonic() counts from boot: a CI runner may be up for under a minute.""" + monkeypatch.setattr("aviary.magpie.fetch.time.monotonic", lambda: 5.0) + sleeps = [] + handler, _ = site([httpx.Response(200)]) + Fetcher( + client=httpx.Client(transport=httpx.MockTransport(handler)), + delay=60, + sleep=sleeps.append, + ).get(TOPIC) + # robots.txt went first without waiting; only the page waited for it + assert sleeps == [60.0] diff --git a/tests/test_magpie_ingest.py b/tests/test_magpie_ingest.py new file mode 100644 index 0000000..21141f1 --- /dev/null +++ b/tests/test_magpie_ingest.py @@ -0,0 +1,75 @@ +"""magpie's `ingest` writes against stand-ins for Supabase.""" + +from datetime import UTC, datetime + +import pytest +from magpie_fakes import FakeClient +from postgrest import APIError + +from aviary.magpie import ingest + + +class RacedRuns: + """crawl_runs where nothing is running at the check, but another run + inserts before this one does.""" + + def table(self, name): + return self + + def schema(self, name): + return self + + def update(self, values): + return self + + def select(self, columns): + return self + + def eq(self, column, value): + return self + + def lt(self, column, value): + return self + + def insert(self, row): + self.inserting = True + return self + + def execute(self): + if getattr(self, "inserting", False): + raise APIError({"code": "23505", "message": "one_running_idx"}) + return type("Response", (), {"data": []}) + + +def test_a_run_started_between_check_and_insert_is_a_running_error(): + with pytest.raises(ingest.RunningError): + ingest.start_run(RacedRuns(), 5, datetime(2026, 11, 21, tzinfo=UTC)) + + +# candidates and the supersede trigger + + +def candidate_row(**values): + return { + "thread_id": 3, + "module": "Keyset", + "extractor_version": "magpie-1", + "content_hash": "h", + **values, + } + + +def test_a_new_extraction_is_added(): + client = FakeClient([]) + assert ingest.save_candidate(client, candidate_row(), False) == ingest.ADDED + + +def test_a_superseded_extraction_brought_back_by_a_revert_is_restored(): + client = FakeClient([candidate_row(state="superseded")], dropped={"candidates"}) + assert ingest.save_candidate(client, candidate_row(), False) == ingest.RESTORED + + +@pytest.mark.parametrize("state", ["new", "dismissed", "promoted"]) +def test_an_extraction_already_made_is_not_counted(state): + client = FakeClient([candidate_row(state=state)], dropped={"candidates"}) + assert ingest.save_candidate(client, candidate_row(), False) is None diff --git a/tests/test_magpie_parsers.py b/tests/test_magpie_parsers.py new file mode 100644 index 0000000..e8dff32 --- /dev/null +++ b/tests/test_magpie_parsers.py @@ -0,0 +1,308 @@ +"""Geekhack pages, URLs, and kit labels, on pages saved from the forum.""" + +from pathlib import Path + +import pytest + +from aviary.magpie.geekhack import ( + canonical_url, + extract_topic_id, + is_internal, + normalize_image_url, + topic_id_of, +) +from aviary.magpie.kits import classify_kit_label +from aviary.magpie.parsers import parse_board, parse_topic + +FIXTURES = Path(__file__).parent / "fixtures" / "magpie" + + +def read_fixture(name: str) -> str: + # the decoding the Fetcher applies to live pages + return (FIXTURES / name).read_bytes().decode("cp1252") + + +@pytest.fixture +def gb_board() -> str: + return read_fixture("board_70_0.html") + + +@pytest.fixture +def topic_html() -> str: + return read_fixture("topic_127176.html") + + +def test_board_page_has_50_topics_with_8_stickies(gb_board): + page = parse_board(gb_board, 0) + assert len(page.topics) == 50 + assert sum(t.is_sticky for t in page.topics) == 8 + assert page.next_offset == 50 + + +def test_board_topic_fields(gb_board): + topic = next(t for t in parse_board(gb_board).topics if t.topic_id == 127176) + assert topic.title == "[GB] DSS Drank Round 2 - 40% Monokit" + assert topic.author == "MikeTheTiger" + assert (topic.replies, topic.views) == (19, 39818) + assert topic.last_post_at == "Thu, 05 November 2026, 19:34:26" + assert not topic.is_sticky + + +def test_board_sticky_is_flagged(gb_board): + sticky = next(t for t in parse_board(gb_board).topics if t.topic_id == 57761) + assert sticky.is_sticky + + +def test_last_board_page_has_no_next_offset(gb_board): + assert parse_board(gb_board, 10_000).next_offset is None + + +def test_ic_board_parses_like_the_gb_board(): + page = parse_board(read_fixture("board_132_0.html")) + assert len(page.topics) == 50 + assert [t.topic_id for t in page.topics if t.is_sticky] == [36672] + assert page.next_offset == 50 + topic = next(t for t in page.topics if t.topic_id == 126906) + assert topic.title == "[IC] GMK Knight" + assert topic.author == "Ephem_eral" + assert topic.last_post_at == "Sat, 14 November 2026, 23:03:52" + + +def test_topic_fields(topic_html): + detail = parse_topic(topic_html) + assert detail.title == "[GB] DSS Drank Round 2 - 40% Monokit" + assert detail.author == "MikeTheTiger" + assert detail.posted_at == "Sun, 04 October 2026, 13:18:44" + + +def test_topic_images_are_only_from_the_first_post(topic_html): + assert parse_topic(topic_html).image_urls == [ + "https://geekhack.org/index.php?action=dlattach;topic=127176.0;attach=318293;image", + "https://geekhack.org/index.php?action=dlattach;topic=127176.0;attach=318301;image", + ] + + +def test_vendor_links_leave_out_images_and_the_forum(topic_html): + detail = parse_topic(topic_html) + assert detail.vendor_links[0] == "https://keyboardarcade.xyz" + assert all("geekhack.org" not in link for link in detail.vendor_links) + assert not any("PHPSESSID" in u for u in detail.image_urls + detail.vendor_links) + + +def test_topic_without_a_post_raises(): + with pytest.raises(ValueError): + parse_topic("nothing") + + +def test_topic_drops_non_url_images_and_cleans_bbcode_tails(): + html = """ + [GB] Demo + +
+ on: Sun, 04 October 2026, 13:18:44 +
+
+ + + + + +
+ """ + detail = parse_topic(html) + assert detail.image_urls == [ + "https://i.imgur.com/ok.png", + "https://i.imgur.com/tail.png", + "https://imagedelivery.net/abc/def/public", + ] + assert detail.dropped_image_urls == 1 + + +def test_a_broken_link_does_not_fail_the_post(): + # "Invalid IPv6 URL": urlsplit raises on an unclosed "[" + html = """ + [GB] NP-R +
+ """ + detail = parse_topic(html) + assert detail.image_urls == [ + "https://i.example/thumb.png", + "https://i.example/a.png", + ] + assert detail.vendor_links == ["https://vendor.example/np-r"] + assert detail.dropped_image_urls == 1 + + +def test_unparseable_urls_are_not_urls(): + assert canonical_url("http://[broken") is None + assert not is_internal("http://[broken") + + +def test_images_follow_the_kit_label_before_them(): + html = """ + [GB] Demo +
+ + Base Kit
+ +
Novelties
+ + Convex DSA Space Bars
+ Spacebars
+ +
+ """ + detail = parse_topic(html) + assert [(i.url, i.kit, i.label) for i in detail.kit_images] == [ + ("https://i.imgur.com/hero.png", None, ""), + ("https://i.imgur.com/base.png", "base", "Base Kit"), + ("https://i.imgur.com/nov-full.png", "novelties", "Novelties"), + ("https://i.imgur.com/still-nov.png", "novelties", "Novelties"), + ("https://i.imgur.com/space.png", "spacebars", "Spacebars"), + ] + + +def test_topic_without_kit_labels_leaves_images_unassigned(topic_html): + assert {i.kit for i in parse_topic(topic_html).kit_images} == {None} + + +@pytest.mark.parametrize( + ("text", "kit"), + [ + ("Base", "base"), + ("Base Kit", "base"), + (" NOVELTIES: ", "novelties"), + ("Novelty Kit", "novelties"), + ("Extra Novelties", "novelties"), + ("Spacebars", "spacebars"), + ("Space bars - $30", "spacebars"), + ("Space bars – $30", "spacebars"), # noqa: RUF001 + ("Spacebar kit 35", "spacebars"), + ], +) +def test_kit_labels(text, kit): + assert classify_kit_label(text) == kit + + +@pytest.mark.parametrize( + "text", + [ + "", + "database", + "Convex DSA Space Bars", + "Base kit includes alphas", + "Monokit: $130", + ], +) +def test_not_kit_labels(text): + assert classify_kit_label(text) is None + + +def test_canonical_url_drops_the_session_and_makes_urls_absolute(): + assert ( + canonical_url("https://geekhack.org/index.php?PHPSESSID=abc123&topic=5.0") + == "https://geekhack.org/index.php?topic=5.0" + ) + assert ( + canonical_url("index.php?topic=5.0;PHPSESSID=abc") + == "https://geekhack.org/index.php?topic=5.0" + ) + + +def test_extract_topic_id(): + assert extract_topic_id("127176") == 127176 + assert extract_topic_id("https://geekhack.org/index.php?topic=127176.0") == 127176 + with pytest.raises(ValueError): + extract_topic_id("https://example.com") + + +@pytest.mark.parametrize( + ("url", "topic_id"), + [ + ("https://geekhack.org/index.php?topic=110062.0", 110062), + ("https://geekhack.org/index.php?topic=91883", 91883), + ("http://www.geekhack.org/index.php?topic=5.msg1#msg1", 5), + ("https://novelkeys.xyz/products/topic=5", None), + ("https://geekhack.org/index.php?board=70.0", None), + (None, None), + ("", None), + ], +) +def test_topic_id_of(url, topic_id): + assert topic_id_of(url) == topic_id + + +@pytest.mark.parametrize( + "url", + [ + "https://i.imgur.com/a.png", + "https://geekhack.org/index.php?action=dlattach;topic=1.0;attach=2;image", + "https://imagedelivery.net/x/y/public", + "https://cdn.example.com:8443/a.png", + "http://192.168.0.10/a.png", + "https://cdn.example.com/img.php?a[]=1&b[]=2", + "https://cdn.example.com/img.php?filter[size]=big", + "http://[::1]/a.png", + "https://example.com./a.png", + "https://δΎ‹γˆ.jp/a.png", + ], +) +def test_real_image_urls_are_kept_untouched(url): + assert normalize_image_url(url) == url + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("https://i.imgur.com/a.png[/center]", "https://i.imgur.com/a.png"), + ("https://i.postimg.cc/x/r3.jpg]", "https://i.postimg.cc/x/r3.jpg"), + (" https://i.imgur.com/a.png ", "https://i.imgur.com/a.png"), + ], +) +def test_bbcode_tails_and_whitespace_are_cut(raw, expected): + assert normalize_image_url(raw) == expected + + +@pytest.mark.parametrize( + "raw", + [ + "https://We are introducing the new set", + "https://We", + "http://localhost/a.png", + "ftp://x.com/a.png", + "javascript:alert(1)", + "data:image/png;base64,AAAA", + "//cdn.example.com/a.png", + "", + "https://", + "https://-bad.example/a.png", + "https://exa mple.com/a.png", + "https://example.com/a\x00.png", + "https://[/center]x.png", + ], +) +def test_things_that_are_not_urls_are_dropped(raw): + assert normalize_image_url(raw) is None + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("https://imgur.com/PFaO1KL.jpg", "https://i.imgur.com/PFaO1KL.jpg"), + ("http://www.imgur.com/PFaO1KL.png", "https://i.imgur.com/PFaO1KL.png"), + ("https://imgur.com/PFaO1KL.jpg?1", "https://i.imgur.com/PFaO1KL.jpg?1"), + # albums and pages without a file stay as they are + ("https://imgur.com/a/xyz", "https://imgur.com/a/xyz"), + ("https://imgur.com/gallery/xyz.jpg", "https://imgur.com/gallery/xyz.jpg"), + ("https://imgur.com/PFaO1KL", "https://imgur.com/PFaO1KL"), + ("https://i.imgur.com/PFaO1KL.jpg", "https://i.imgur.com/PFaO1KL.jpg"), + ], +) +def test_imgur_page_links_to_a_file_point_at_the_file(raw, expected): + assert normalize_image_url(raw) == expected diff --git a/tests/test_magpie_plan.py b/tests/test_magpie_plan.py new file mode 100644 index 0000000..97645ba --- /dev/null +++ b/tests/test_magpie_plan.py @@ -0,0 +1,241 @@ +"""Listings, fetch schedules, and promotions, decided without a database.""" + +from datetime import UTC, date, datetime, timedelta + +from aviary.magpie.parsers import BoardPage, TopicSummary +from aviary.magpie.plan import ( + MAX_FETCH_ATTEMPTS, + BoardListing, + Rematch, + plan_listing, + plan_promotions, + refetch_at, + retry_at, +) + +NOW = datetime(2026, 11, 20, 12, 0, tzinfo=UTC) + + +def at(day, hour=0): + return f"Thu, {day:02d} November 2026, {hour:02d}:00:00" + + +def summary(topic_id, last_post_at="Thu, 10 November 2026, 00:00:00", replies=3, **kw): + values = {"title": f"[GB] GMK T{topic_id}", "author": "a", "views": 0} + return TopicSummary( + topic_id, replies=replies, last_post_at=last_post_at, **(values | kw) + ) + + +def page(*topics, last=False): + return BoardPage(list(topics), None if last else 50) + + +def watermark(day): + return datetime(2026, 11, day, tzinfo=UTC) + + +# listing + + +def test_a_first_listing_stopped_by_the_cap_still_sets_a_watermark(): + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(12)), summary(2, at(11)))) + # stopped by the page cap: incomplete, but the next run stops at its + # newest thread instead of listing the whole cap again + assert not listing.done + assert listing.next_watermark() == watermark(12) + + +def test_a_listing_without_dated_threads_keeps_no_watermark(): + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, ""))) + assert listing.next_watermark() is None + + +def test_a_listing_that_reaches_the_end_sets_the_watermark(): + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(12)), summary(2, at(11)), last=True)) + assert listing.done + assert listing.next_watermark() == watermark(12) + + +def test_a_listing_stops_at_the_previous_watermark(): + listing = BoardListing("gb", watermark(11)) + listing.add_page(page(summary(1, at(13)), summary(2, at(12)))) + assert not listing.done + listing.add_page(page(summary(3, at(11)), summary(4, at(9)))) + assert listing.done + assert listing.next_watermark() == watermark(13) + + +def test_an_incomplete_listing_keeps_the_old_watermark(): + listing = BoardListing("gb", watermark(5)) + listing.add_page(page(summary(1, at(13)))) + assert listing.next_watermark() == watermark(5) + + +def test_stickies_and_bumped_threads_count_once(): + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(1), is_sticky=True), summary(2, at(12)))) + listing.add_page(page(summary(2, at(13)), summary(3, at(11)))) + assert list(listing.seen) == [2, 3] + assert listing.seen[2].last_post_at == at(12) + # a sticky's old last post never stops a listing + assert not listing.reached_watermark + + +def stored(last_post_at, gone_at=None): + return {"last_post_at": last_post_at, "gone_at": gone_at} + + +def test_new_threads_and_new_activity_are_due(): + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(12)), summary(2, at(12)), summary(3, at(12)))) + rows = { + "2": stored("2026-11-12T00:00:00+00:00"), + "3": stored("2026-11-11T00:00:00+00:00"), + } + plan = plan_listing(listing, rows, NOW) + assert plan.new == 1 + assert [r["external_id"] for r in plan.due] == ["1", "3"] + assert [r["external_id"] for r in plan.seen] == ["2"] + due = plan.due[0] + assert due["next_fetch_at"] == NOW.isoformat() + assert due["url"] == "https://geekhack.org/index.php?topic=1.0" + assert due["last_post_at"] == "2026-11-12T00:00:00+00:00" + # a row that only refreshes the listing never moves the fetch queue + assert "next_fetch_at" not in plan.seen[0] + + +def test_a_gone_thread_is_fetched_again_only_after_new_activity(): + gone = stored("2026-11-12T00:00:00+00:00", gone_at="2026-11-13T00:00:00+00:00") + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(12)))) + assert plan_listing(listing, {"1": gone}, NOW).due == [] + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(14)))) + assert plan_listing(listing, {"1": gone}, NOW).due[0]["gone_at"] is None + + +def test_new_activity_restarts_the_retries_of_a_thread_that_gave_up(): + # whatever its stored fetch_attempts, the due row resets them + listing = BoardListing("gb", None) + listing.add_page(page(summary(1, at(14)))) + (due,) = plan_listing(listing, {"1": stored("2026-11-12T00:00:00+00:00")}, NOW).due + assert (due["fetch_attempts"], due["fetch_error"]) == (0, None) + + +# fetch schedule + + +def test_recent_threads_are_fetched_again_weekly(): + assert refetch_at(NOW - timedelta(days=10), NOW) == NOW + timedelta(days=7) + assert refetch_at(NOW - timedelta(days=200), NOW) is None + assert refetch_at(None, NOW) is None + + +def test_failed_fetches_back_off_then_stop(): + assert retry_at(1, NOW) == NOW + timedelta(hours=1) + assert retry_at(3, NOW) == NOW + timedelta(hours=4) + assert retry_at(MAX_FETCH_ATTEMPTS - 1, NOW) <= NOW + timedelta(days=7) + assert retry_at(MAX_FETCH_ATTEMPTS, NOW) is None + + +# promotion + +SINCE = date(2026, 1, 1) + + +def candidate(candidate_id, topic_id, slug="selene", match_key=None, **thread): + payload = { + "keyset": { + "profile_id": "gmk", + "name": slug.title(), + "slug": slug, + "img": "https://i.example/a.png", + "status": "Confirmed", + }, + "kits": [{"kit_id": "base", "name": "Base", "img": "https://i.example/a.png"}], + } + return { + "id": candidate_id, + "payload": payload, + "match_key": match_key, + "thread": { + "external_id": str(topic_id), + "posted_at": "2026-11-14T00:00:00+00:00", + } + | thread, + } + + +def keyset(keyset_id, key, url=None, status="Confirmed"): + profile_id, slug = key.split("/") + return { + "id": keyset_id, + "profile_id": profile_id, + "slug": slug, + "profile_keyset_id": key, + "url": url, + "status": status, + } + + +def promote(candidates, keysets=(), limit=10): + return plan_promotions(candidates, list(keysets), limit=limit, posted_since=SINCE) + + +def test_a_complete_new_candidate_is_promoted(): + plan = promote([candidate(1, 100)]) + assert [(p.candidate_id, p.key) for p in plan.promotions] == [(1, "gmk/selene")] + + +def test_a_candidate_keebdex_has_now_is_matched_not_promoted(): + by_url = keyset(7, "gmk/other", "https://geekhack.org/index.php?topic=100") + by_key = keyset(8, "gmk/b", status="Interest Check") + plan = promote([candidate(1, 100), candidate(2, 200, "b")], [by_url, by_key]) + assert plan.promotions == [] + assert plan.rematches == [ + Rematch(2, 200, "gmk/b", "status: Keebdex Interest Check, topic Confirmed"), + Rematch(1, 100, "gmk/other"), + ] + + +def test_matched_candidates_wait_for_staff(): + already = keyset(7, "gmk/selene") + plan = promote([candidate(1, 100, match_key="gmk/selene")], [already]) + assert (plan.promotions, plan.rematches) == ([], []) + # a match_key whose keyset is gone (renamed, deleted) is staff's too + assert promote([candidate(1, 100, match_key="gmk/x")]).promotions == [] + + +def test_the_newest_topic_is_promoted_and_older_ones_matched_to_it(): + plan = promote([candidate(1, 100), candidate(2, 200)]) + assert [p.topic_id for p in plan.promotions] == [200] + assert plan.rematches == [Rematch(1, 100, "gmk/selene")] + + +def test_incomplete_old_ignored_and_gone_candidates_are_left_alone(): + incomplete = candidate(1, 100) + incomplete["payload"]["keyset"]["profile_id"] = None + old = candidate(2, 200, "b", posted_at="2019-03-04T00:00:00+00:00") + undated = candidate(3, 300, "c", posted_at=None) + ignored = candidate(4, 400, "d", ignored_at="2026-11-15T00:00:00+00:00") + gone = candidate(5, 500, "e", gone_at="2026-11-15T00:00:00+00:00") + plan = promote([incomplete, old, undated, ignored, gone]) + assert (plan.promotions, plan.rematches) == ([], []) + assert plan.incomplete == [(100, "profile_id")] + assert plan.old == 2 + + +def test_the_limit_defers_the_rest_with_their_older_topics(): + candidates = [ + candidate(1, 300, "a"), + candidate(2, 200, "b"), + candidate(3, 100, "b"), + ] + plan = promote(candidates, limit=1) + assert [p.key for p in plan.promotions] == ["gmk/a"] + assert plan.rematches == [] + assert plan.deferred == 2 diff --git a/tests/test_magpie_promote.py b/tests/test_magpie_promote.py new file mode 100644 index 0000000..f826edb --- /dev/null +++ b/tests/test_magpie_promote.py @@ -0,0 +1,145 @@ +"""`magpie promote` against an in-memory Supabase.""" + +from magpie_fakes import FakeClient + +from aviary.magpie import keebdex, promote +from aviary.magpie.keebdex import PromotionResult +from aviary.magpie.plan import Promotion, PromotionPlan, Rematch +from aviary.magpie.proposal import kit_rows + + +def payload(slug): + return { + "keyset": {"profile_id": "gmk", "name": slug, "slug": slug, "img": "i"}, + "kits": [{"kit_id": "base", "name": "Base", "img": "i"}], + } + + +def waiting(*ids): + return [{"id": i, "state": "new", "match_key": None} for i in ids] + + +def test_promotion_inserts_and_marks_the_candidate(): + client = FakeClient(waiting(1, 2)) + plan = PromotionPlan( + promotions=[Promotion(1, 200, payload("a"))], + rematches=[Rematch(2, 100, "gmk/a")], + ) + assert keebdex.apply_promotions(client, plan, dry_run=False) == PromotionResult() + (keyset,) = client.rows["keysets"] + assert (keyset["profile_keyset_id"], keyset["review_status"]) == ( + "gmk/a", + "Pending", + ) + assert client.rows["keyset_kits"][0]["profile_keyset_id"] == "gmk/a" + first, second = client.rows["candidates"] + assert (first["state"], first["promoted_kind"], first["promoted_id"]) == ( + "promoted", + "keyset", + 1, + ) + assert (second["state"], second["match_key"]) == ("new", "gmk/a") + + +def test_a_keyset_whose_kits_fail_is_removed_and_its_candidates_wait(): + client = FakeClient(waiting(1, 2), failing={("keyset_kits", "insert")}) + plan = PromotionPlan( + promotions=[Promotion(1, 200, payload("a"))], + rematches=[Rematch(2, 100, "gmk/a")], + ) + result = keebdex.apply_promotions(client, plan, dry_run=False) + assert result == PromotionResult(failed=[200]) + assert client.rows["keysets"] == [] + assert client.rows["candidates"] == waiting(1, 2) + + +def test_a_candidate_triaged_meanwhile_rolls_its_keyset_back(): + # staff dismissed candidate 1 after fetch_waiting read it + client = FakeClient([{"id": 1, "state": "dismissed"}, *waiting(2)]) + plan = PromotionPlan( + promotions=[Promotion(1, 200, payload("a"))], + rematches=[Rematch(2, 100, "gmk/a")], + ) + result = keebdex.apply_promotions(client, plan, dry_run=False) + assert result == PromotionResult(triaged=[200]) + assert client.rows["keysets"] == [] + assert client.rows["keyset_kits"] == [] + assert client.rows["candidates"] == [{"id": 1, "state": "dismissed"}, *waiting(2)] + + +def test_a_triaged_candidate_whose_keyset_stays_is_only_failed(): + client = FakeClient( + [{"id": 1, "state": "dismissed"}], failing={("keysets", "delete")} + ) + plan = PromotionPlan(promotions=[Promotion(1, 200, payload("a"))]) + result = keebdex.apply_promotions(client, plan, dry_run=False) + # the keyset is still in Keebdex: not "removed again" + assert result == PromotionResult(failed=[200]) + assert [k["slug"] for k in client.rows["keysets"]] == ["a"] + + +def test_a_failed_rollback_is_reported_and_the_run_goes_on(): + client = FakeClient( + waiting(1, 2), failing={("keyset_kits", "insert"), ("keysets", "delete")} + ) + plan = PromotionPlan( + promotions=[Promotion(1, 200, payload("a")), Promotion(2, 300, payload("b"))] + ) + result = keebdex.apply_promotions(client, plan, dry_run=False) + assert result == PromotionResult(failed=[200, 300]) + # both promotions were tried; their keysets are left for staff to remove + assert [k["slug"] for k in client.rows["keysets"]] == ["a", "b"] + assert client.rows["candidates"] == waiting(1, 2) + + +def test_a_claim_whose_response_was_lost_keeps_itskeyset(): + # the database promoted the candidate, but the response never came back + client = FakeClient(waiting(1), lost={("candidates", "update")}) + plan = PromotionPlan(promotions=[Promotion(1, 200, payload("a"))]) + assert keebdex.apply_promotions(client, plan, dry_run=False) == PromotionResult() + (keyset,) = client.rows["keysets"] + (candidate,) = client.rows["candidates"] + assert (candidate["state"], candidate["promoted_id"]) == ("promoted", keyset["id"]) + assert len(client.rows["keyset_kits"]) == 1 + + +def test_a_claim_that_did_not_apply_rolls_back_and_the_candidate_waits(): + client = FakeClient(waiting(1), failing={("candidates", "update")}) + plan = PromotionPlan(promotions=[Promotion(1, 200, payload("a"))]) + result = keebdex.apply_promotions(client, plan, dry_run=False) + assert result == PromotionResult(failed=[200]) + assert client.rows["keysets"] == [] + assert client.rows["keyset_kits"] == [] + assert client.rows["candidates"] == waiting(1) + + +def test_a_claim_that_cannot_be_read_back_keeps_itskeyset(): + client = FakeClient( + waiting(1), failing={("candidates", "update"), ("candidates", "select")} + ) + plan = PromotionPlan(promotions=[Promotion(1, 200, payload("a"))]) + result = keebdex.apply_promotions(client, plan, dry_run=False) + assert result == PromotionResult(failed=[200]) + # never delete what a candidate may point at + assert [k["slug"] for k in client.rows["keysets"]] == ["a"] + + +def test_the_promote_summary_lists_triaged_topics_apart_from_inserted(): + plan = PromotionPlan( + promotions=[Promotion(1, 200, payload("a")), Promotion(2, 300, payload("b"))] + ) + summary = promote.promote_summary(plan, PromotionResult(triaged=[300]), False) + assert "- Inserted (Pending): 1" in summary + assert "- Triaged by staff meanwhile (keyset removed again): 1" in summary + assert "topic=300" in summary.split("### Triaged by staff meanwhile")[1] + assert "`gmk/b`" not in summary + + +def test_a_dry_run_writes_nothing(): + client = FakeClient(waiting(1), failing={"keysets", "keyset_kits", "candidates"}) + plan = PromotionPlan(promotions=[Promotion(1, 200, payload("a"))]) + assert keebdex.apply_promotions(client, plan, dry_run=True) == PromotionResult() + + +def test_kit_rows_follow_the_keyset_key(): + assert [k["profile_keyset_id"] for k in kit_rows(payload("a"))] == ["gmk/a"] diff --git a/tests/test_magpie_proposal.py b/tests/test_magpie_proposal.py new file mode 100644 index 0000000..f3dd921 --- /dev/null +++ b/tests/test_magpie_proposal.py @@ -0,0 +1,293 @@ +"""Topic titles to keyset candidates.""" + +from datetime import UTC, datetime +from pathlib import Path + +import pytest + +from aviary.magpie.classify import suggest +from aviary.magpie.geekhack import parse_time +from aviary.magpie.parsers import KitImage, parse_board +from aviary.magpie.proposal import ( + Topic, + clean_keyset_name, + extract, + find_profile, + guess_status, + keyset_row, + kit_rows, + missing_for_promotion, +) + +FIXTURES = Path(__file__).parent / "fixtures" / "magpie" + +# shaped like Keebdex's: GMK's profile is named after its CYL line, and KKB is +# found by name +PROFILES = [ + {"profile_id": "gmk", "name": "CYL", "profile": "Cherry"}, + {"profile_id": "keykobo", "name": "KKB", "profile": "Cherry"}, + {"profile_id": "dcs", "name": "DCS", "profile": "DCS"}, + {"profile_id": "mtnu", "name": "MTNU", "profile": "MTNU"}, +] +POSTED = datetime(2026, 11, 14, 23, 3, 52, tzinfo=UTC) + + +def topic(title="[GB] GMK CYL Selene | Production Underway", board="gb", **fields): + values = { + "topic_id": 5, + "board": board, + "title": title, + "author": "someone", + "posted_at": POSTED, + "kit_images": [KitImage("https://i.example/hero.png")], + } + return Topic(**(values | fields)) + + +@pytest.mark.parametrize( + ("title", "kind", "code"), + [ + ("[GB] GMK MTNU Dasher", "keyset", "GMK"), + ("[GB] MW Datenshi | 26 Oct - 16 Nov", "keyset", "MW"), + ("[GB] DSS Drank Round 2 - 40% Monokit", "keyset", "DSS"), + ("[GB]PBS-Kids Typewriter keycap set", "keyset", None), + ("[GB] Code:002 TKL ", "keyboard", None), + ("[GB]Space66% Spaceforge", "keyboard", None), + ("[GB] Sagittarius optimized ergo", "keyboard", None), + ("[GB] Enso-E by Clever | Dec 8 - 22", "unknown", None), + ("[GB] 60% keycap set", "unknown", None), + ("Group Buy Rules and Guidelines (Updated 2025-03-07)", "other", None), + ("", "other", None), + ("[GB] gmk lowercase", "keyset", "GMK"), + ("[GB] Sagittarius", "unknown", None), + ("[IC] GMK CYL Mayan blue", "keyset", "GMK"), + ("[IC] Radius 68: A Mac-Friendly Keyboard with Nacre", "keyboard", None), + ("[Pre-order] GMK CYL Neon Vice | Nov 18 - Dec 15", "keyset", "GMK"), + ("[Preorder] SA Bliss", "keyset", "SA"), + ("[pre order] MW Jirai", "keyset", "MW"), + ("[Sold] GMK Olivia", "other", None), + ], +) +def test_suggest(title, kind, code): + suggestion = suggest(title) + assert (suggestion.kind, suggestion.profile_code) == (kind, code) + assert suggestion.reason + + +def test_fixture_board_mix(): + page = parse_board((FIXTURES / "board_70_0.html").read_bytes().decode("cp1252")) + kinds = [suggest(t.title).kind for t in page.topics] + assert kinds.count("other") == 9 + assert kinds.count("unknown") == 3 + assert kinds.count("keyboard") == 8 + assert kinds.count("keyset") == len(kinds) - 20 + + +@pytest.mark.parametrize( + ("title", "prefixes", "name"), + [ + ("[GB] GMK CYL Selene | Production Underway", [], "GMK CYL Selene"), + ("[GB] GMK CYL Selene | Production Underway", ["GMK", "CYL"], "Selene"), + ( + "[GB] GMK Orange Alert - 8/14/26 to 9/14/26 | GB Successful", + ["GMK"], + "Orange Alert", + ), + ("[GB] GMK CYL Purple. | Group Buy is live!", ["GMK", "CYL"], "Purple"), + ("[GB] SWG Art (cancelled)", ["SWG"], "Art"), + ( + "[GB] MW Jirai (Doubleshot ABS) | (Cancelled)", + ["MW"], + "Jirai (Doubleshot ABS)", + ), + ( + "[GB] DCS Cream Cheese R3 (Update: Oct. 27th, 2026)", + ["DCS"], + "Cream Cheese R3", + ), + ("[GB] DCS Cream – GB live", ["DCS"], "Cream"), # noqa: RUF001 + # titles from crawl run #1 + ("[GB] Medusa : A Gaze Forged in Grief (NEW KITS)", [], "Medusa"), + ("[GB] KBS Flat Out A Motorsport Inspired Keycap Set", [], "KBS Flat Out"), + ( + "[GB] SA 64 / SA 64C / SA 16 SA keycaps for vintage boards", + ["SA"], + "64 / SA 64C / SA 16", + ), + ("[GB] GMK 3077 (Previously Brown on Beige)", ["GMK"], "3077"), + ("[GB] GMK Olivia (Formerly Rose)", ["GMK"], "Olivia"), + ("[GB] DCS Cream Cheese R3 (R2 Update)", ["DCS"], "Cream Cheese R3"), + # a colon without spaces is part of the name + ("[GB] GMK Re:Zero", ["GMK"], "Re:Zero"), + ("[GB] GMK", ["GMK"], "GMK"), + ("[GB] GMK !!!", ["GMK"], "GMK"), + ("[GB] GMK CYL", ["GMK", "CYL"], "CYL"), + ], +) +def test_clean_keyset_name(title, prefixes, name): + assert clean_keyset_name(title, prefixes) == name + + +def test_guess_status(): + assert guess_status("[GB] KKB Korean Delights - Cancelled", "gb") == "Cancelled" + assert guess_status("[IC] GMK Boho (cancelled)", "ic") == "Cancelled" + assert guess_status("[GB] GMK Boho | Shipping", "gb") == "Confirmed" + assert guess_status("[IC] GMK Boho", "ic") == "Interest Check" + + +def test_parse_time(): + assert parse_time("Sat, 14 November 2026, 23:03:52") == POSTED + assert parse_time("Today at 10:00:00") is None + assert parse_time("") is None + + +def test_find_profile_by_id_then_name(): + assert find_profile("GMK", PROFILES)["profile_id"] == "gmk" + assert find_profile("KKB", PROFILES)["profile_id"] == "keykobo" + assert find_profile("SA", PROFILES) is None + twins = [{"profile_id": "a", "name": "X"}, {"profile_id": "b", "name": "X"}] + assert find_profile("X", twins) is None + + +def test_candidate_from_a_group_buy(): + extraction = extract(topic(), PROFILES) + assert (extraction.name, extraction.profile_id, extraction.key) == ( + "Selene", + "gmk", + "gmk/selene", + ) + assert extraction.missing == [] + assert extraction.payload == { + "keyset": { + "profile_id": "gmk", + "name": "Selene", + "slug": "selene", + "designer": "someone", + "sculpt": "1-1-2-3-4-4", + "img": "https://i.example/hero.png", + "url": "https://geekhack.org/index.php?topic=5.0", + "status": "Confirmed", + "ic_date": None, + }, + # without kit labels, one Base kit with the cover keeps it in the queue + "kits": [{"kit_id": "base", "name": None, "img": "https://i.example/hero.png"}], + } + # the cover is only the first image: staff should look at it + assert extraction.confidence["img"] < extraction.confidence["profile_id"] + assert "ic_date" not in extraction.confidence + + +def test_promotion_rows_are_pending_without_submitter(): + payload = extract(topic(), PROFILES).payload + keyset = keyset_row(payload) + assert keyset["profile_keyset_id"] == "gmk/selene" + assert (keyset["review_status"], keyset["submitted_by"]) == ("Pending", None) + assert kit_rows(payload) == [ + { + "kit_id": "base", + "name": None, + "img": "https://i.example/hero.png", + "profile_keyset_id": "gmk/selene", + "review_status": "Pending", + "submitted_by": None, + } + ] + + +@pytest.mark.parametrize( + ("title", "key"), + [ + ("[GB] GMK MTNU Dasher", "mtnu/dasher"), + ("[GB] GMK CYL Selene", "gmk/selene"), + ("[GB] GMK Rainy Day", "gmk/rainy-day"), + ("[GB] GMK MTNU", "gmk/mtnu"), + ("[GB] KKB Cobalt - MOQ REACHED!", "keykobo/cobalt"), + ], +) +def test_the_profile_is_the_one_named_after_the_makers_code(title, key): + assert extract(topic(title), PROFILES).key == key + + +def test_interest_check_gets_its_status_and_posting_day(): + extraction = extract(topic("[IC] DCS Boho", board="ic"), PROFILES) + assert extraction.payload["keyset"]["status"] == "Interest Check" + assert extraction.payload["keyset"]["ic_date"] == "2026-11-14" + # only Cherry profiles get the usual row sculpt + assert extraction.payload["keyset"]["sculpt"] is None + + +def test_labelled_images_become_kits_and_the_base_one_the_cover(): + images = [ + KitImage("https://i.imgur.com/a/album"), + KitImage("https://i.example/hero.png"), + KitImage("https://i.example/nov.png", "novelties", "Novelties"), + KitImage("https://i.example/nov2.png", "novelties", "Novelties"), + KitImage("https://i.example/base.png", "base", "Base"), + ] + extraction = extract(topic(kit_images=images), PROFILES) + assert extraction.payload["keyset"]["img"] == "https://i.example/base.png" + assert extraction.payload["kits"] == [ + {"kit_id": "base", "name": None, "img": "https://i.example/base.png"}, + {"kit_id": "novelties", "name": None, "img": "https://i.example/nov.png"}, + ] + assert extraction.confidence["img"] == 0.7 + + +def test_kits_leave_the_name_to_their_category(): + # keyset_kits.name holds a kit's own name ("TKL Base"); never the + # category's, which Keebdex shows when it is null + images = [ + KitImage("https://i.example/base.png", "base", "Base Kit"), + KitImage("https://i.example/space.png", "spacebars", "Spacebars"), + ] + kits = extract(topic(kit_images=images), PROFILES).payload["kits"] + assert [(k["kit_id"], k["name"]) for k in kits] == [ + ("base", None), + ("spacebars", None), + ] + + +def test_keyboards_and_other_topics_are_not_extracted(): + assert extract(topic("[GB] Seed Plan Linedge 65 Keyboard"), PROFILES) is None + assert extract(topic("Group Buy Rules"), PROFILES) is None + + +@pytest.mark.parametrize( + ("fields", "missing"), + [ + ({"title": "[GB] PBS-Kids Typewriter keycap set"}, "no profile code"), + ({"title": "[GB] SA Bliss"}, "no Keebdex profile for SA"), + ({"kit_images": []}, "no image"), + ({"kit_images": [KitImage("https://imgur.com/gallery/x")]}, "no image"), + ({"title": "[GB] GMK CYL"}, "only the profile"), + ({"title": "[GB] GMK !!!"}, "only the profile"), + ({"title": "[GB] GMK \u2605"}, "slug"), + ], +) +def test_incomplete_candidates_say_what_is_missing(fields, missing): + extraction = extract(topic(**fields), PROFILES) + assert any(missing in m for m in extraction.missing) + # still stored for staff, and never promoted by magpie + assert missing_for_promotion(extraction.payload) + + +def test_an_unknown_profile_still_names_the_keyset(): + extraction = extract(topic("[GB] SA Bliss"), PROFILES) + assert (extraction.name, extraction.profile_id, extraction.key) == ( + "Bliss", + None, + None, + ) + assert missing_for_promotion(extraction.payload) == ["profile_id"] + + +def test_a_pre_order_on_the_gb_board_is_a_confirmed_keyset(): + title = "[Pre-order] GMK CYL Neon Vice | Nov 18 - Dec 15" + keyset = extract(topic(title, board="gb"), PROFILES).payload["keyset"] + assert (keyset["name"], keyset["status"]) == ("Neon Vice", "Confirmed") + + +def test_names_are_left_for_staff_to_read(): + confidence = extract(topic(), PROFILES).confidence + assert confidence["name"] == confidence["slug"] == 0.6 + assert confidence["name"] < confidence["status"] diff --git a/tests/test_magpie_reextract.py b/tests/test_magpie_reextract.py new file mode 100644 index 0000000..de2aab6 --- /dev/null +++ b/tests/test_magpie_reextract.py @@ -0,0 +1,107 @@ +"""`magpie reextract` against an in-memory candidates table.""" + +import pytest +from magpie_fakes import PROFILES, FakeClient, keyset + +from aviary.magpie import __main__ as magpie +from aviary.magpie import ingest, keebdex, reextract +from aviary.magpie.plan import KeysetIndex +from aviary.magpie.proposal import EXTRACTOR_VERSION + +STORED_POST = ( + '
' + '
' +) + + +def stored_thread(thread_id, title="[GB] GMK CYL Selene", **values): + return { + "id": thread_id, + "external_id": str(100 + thread_id), + "board": "gb", + "title": title, + "author": "someone", + "posted_at": "2026-11-14T23:03:52+00:00", + "content_hash": f"hash{thread_id}", + **values, + } + + +@pytest.fixture +def reextract_env(monkeypatch): + """`magpie reextract` against an in-memory candidates table; `bodies` + are the stored first posts by thread id.""" + + def setup(threads, bodies, running=None): + client = FakeClient([]) + monkeypatch.setattr(reextract, "create_supabase", lambda: client) + monkeypatch.setattr(keebdex, "fetch_profiles", lambda c: PROFILES) + monkeypatch.setattr(keebdex, "fetch_keysets", lambda c: [keyset()]) + monkeypatch.setattr(ingest, "running_run", lambda c, now: running) + monkeypatch.setattr(ingest, "fetch_stored_threads", lambda c: threads) + monkeypatch.setattr( + ingest, "stored_bodies", lambda c, ids: {i: bodies[i] for i in ids} + ) + return client + + return setup + + +def test_reextract_adds_a_candidate_with_the_current_extractor(reextract_env): + client = reextract_env( + [stored_thread(1), stored_thread(2, "[GB] Rules of the board")], + {1: STORED_POST, 2: STORED_POST}, + ) + assert magpie.main(["reextract"]) == 0 + (candidate,) = client.rows["candidates"] + assert candidate["thread_id"] == 1 + assert candidate["extractor_version"] == EXTRACTOR_VERSION + assert candidate["content_hash"] == "hash1" + assert candidate["payload"]["keyset"]["name"] == "Selene" + + +def test_reextract_run_again_adds_nothing(reextract_env): + client = reextract_env([stored_thread(1)], {1: STORED_POST}) + assert magpie.main(["reextract"]) == 0 + assert magpie.main(["reextract"]) == 0 + assert len(client.rows["candidates"]) == 1 + + +def test_reextract_counts_posts_it_cannot_parse(): + counters = reextract.ReextractCounters() + reextract.reextract_thread( + FakeClient([]), + stored_thread(1), + "

no post here

", + PROFILES, + KeysetIndex([]), + counters, + dry_run=False, + ) + assert counters.parse_errors == [("101", "no post in the stored body")] + summary = reextract.reextract_summary(False, counters) + assert "Posts that could not be parsed: 1" in summary + + +def test_reextract_waits_for_a_running_crawl(reextract_env): + client = reextract_env([stored_thread(1)], {1: STORED_POST}, running=7) + assert magpie.main(["reextract"]) == 1 + assert client.rows["candidates"] == [] + + +def test_a_reextract_dry_run_writes_nothing_and_tells_what_it_would_add( + reextract_env, +): + client = reextract_env([stored_thread(1)], {1: STORED_POST}) + counters = reextract.ReextractCounters() + reextract.reextract_thread( + client, + stored_thread(1), + STORED_POST, + PROFILES, + KeysetIndex([]), + counters, + dry_run=True, + ) + assert client.rows["candidates"] == [] + assert counters.added == 1