SPB Git

Repository Public

ARCHITECTURE.md 5.8 KB 101 lines markdown

1# SPIDER architecture23Version 0.1 — matches the code in this repository. Decisions are in `docs/DECISIONS/`.45```mermaid6flowchart TD7  C[CLI / SDK / Dashboard] -->|/v1, API key or session| G[Gateway  src/spider/api]8  G --> O[Orchestrator  orchestrator.py + scheduler.py]9  O <--> PG[(PostgreSQL: jobs, frontier, tasks, leases, evidence, search)]10  G <--> ST[(Object store: content-addressed blobs)]11  W1[HTTP worker] -->|/internal/v1 leases, uploads, acks| G12  W2[Browser worker + egress proxy] --> G13  W3[macOS worker: Apple Vision OCR] --> G14  W4[Apple Silicon worker: MLX vision] --> G15  W1 -->|SSRF guard| WEB((Web))16  W2 -->|egress proxy = SSRF guard| WEB17```1819## Planes2021| Plane | Process | Holds | Talks to |22|---|---|---|---|23| Control | `spider serve` (gateway + orchestrator + maintenance loop) | DB credentials, signing secret, blob store | PostgreSQL, clients, workers |24| Data | `spider worker --capabilities …` | a worker key only | gateway `/internal/v1`, the Web through the guard |2526Workers never see the database. The gateway never fetches a source page (the only outbound calls of27the control plane are signed webhooks, through the same SSRF guard).2829## Modules (`src/spider`)3031| Module | Role |32|---|---|33| `contracts.py` | v1 request models and worker payloads (pydantic, unknown fields rejected) |34| `netguard.py` | SSRF rules, pinned-address resolver, loopback egress proxy for browsers |35| `canonical.py` | URL canonicalisation, scope allowlist, trap heuristics, SimHash |36| `robots.py` | RFC 9309 parser and matcher |37| `engine/http.py` | guarded HTTP engine: per-hop validation, bounded streaming, conditional requests, MIME sniffing, sitemaps |38| `refusal.py`, `browser/refusal.py` | access-denial recognition (never circumvention) |39| `browser/` | browser pool, stability, snapshot, capture (viewport, full page, tiles, mosaic, elements), state exploration, replay |40| `extract/` | HTML, Markdown, structured data, tables, PDF, media, label/value pairs, schema candidates |41| `ocr/` + `services/ocr-worker` | Apple Vision worker (Swift) and its client, tile geometry, CER/WER |42| `vision/` | local MLX model registry, warm runner, OCR-attestation guard |43| `fusion.py` | evidence reconciliation by dependency group, conflicts, calibration measures |44| `pipeline.py` | worker-side page processing: artifacts, links, text, record |45| `orchestrator.py` | jobs, frontier admission, leases with fencing tokens, ingestion, finalisation |46| `scheduler.py` | lease reaper, deadlines, monitors, change events, webhooks, garbage collection |47| `diffing.py` | text / layout / field / pixel comparison |48| `store/objects.py` | content-addressed blob store |49| `api/` | gateway: public `/v1`, admin, internal worker API |50| `worker.py`, `cli.py` | worker runtime and the `spider` command |5152## Life of a crawl53541. `POST /v1/crawl` → request validated (mandatory policies cannot be disabled, budgets bounded),55   seeds canonicalised and checked by the SSRF guard, source kill switches and suspensions checked,56   job stored (idempotency key unique per tenant). Seeds are admitted to the frontier; a `sitemap`57   task is queued for `robots.txt` → sitemaps.582. A worker heartbeats and asks for leases. In one transaction the orchestrator picks runnable59   tasks (`SKIP LOCKED`), keeps at most one per host, checks the host is free (delay elapsed, nothing60   in flight, not suspended), marks it busy and issues a lease with a new fencing token.613. The worker fetches through the guard: scheme, port and address rules, robots.txt, scope62   re-checked on every redirect hop, body capped after decompression. For a browser task it then63   renders the page in a fresh context whose only route out is the egress proxy, captures, explores64   read-only states, and runs extraction, OCR, optional vision and fusion locally.654. Artifacts are uploaded by hash (the gateway verifies the hash), then the task is completed. The66   completion transaction checks the fencing token, stores snapshot / artifacts / states / record /67   evidence / search document, updates the URL, admits the links found (scope, depth, trap and68   pattern budgets, page budget), applies host feedback (delay, 429 back-off, denial counters,69   suspension) and finalises the job when nothing is left.705. Clients read progress (`GET /v1/jobs/{id}`, SSE events), partial results at any time, the graph71   and the coverage report.7273## Delivery guarantees7475At-least-once. A lost worker's lease expires; the task is re-queued with a higher fencing token, so76a late result from the first worker is refused (409) and cannot overwrite the second. Ingestion is77idempotent (`unique (job_id, url_id, engine, profile)` on snapshots). Attempts are bounded; exhausted78tasks are dead-lettered and the job ends `partial` with the reason. No exactly-once claim is made.7980## Data model8182Tables: tenants, api_keys, sessions, sites, policies, host_state, jobs, urls, crawl_edges, tasks,83job_attempts, workers, snapshots, page_states, blobs, artifacts, extracted_records, field_evidence,84schemas, connectors, schedules, change_events, audit_events, usage_counters, job_events,85webhook_deliveries, search_documents (`migrations/0001_init.sql`). Every tenant-owned table carries86`tenant_id`.8788## Modes8990- **Single node**: `spider serve` + `spider worker --capabilities http,browser,ocr,vision` on one91  machine, PostgreSQL local (`infra/compose` provides PostgreSQL for development).92- **Distributed**: one gateway; workers on any node that reaches it over the private network. Routing93  is by capability: OCR only where the Swift binary exists (macOS), vision only where the model is94  cached and memory suffices; a worker that cannot provide a capability drops it at start-up and95  says so in its log.9697## What is deliberately absent9899Stealth, fingerprint evasion, identity rotation, CAPTCHA solving, form submission, logged-in100sessions, private endpoints. See `THREAT_MODEL.md` and ADR-0005.101
Files main
Menu

Theme