Files
StarPunk/docs/design/v1.6.0/background-worker.md
T
PhilandClaude Opus 5.5 0716984958 docs: Bring all documentation up to date for v2.10.1
- architecture/: overview, technology stack, auth (OIDC + built-in
  IndieAuth), syndication (POSSE) rewritten; new database.md,
  deployment.md and indieweb-protocols.md; legacy stack marked historical
- decisions/: reconstructed ADR-060 and ADR-063; 31 status corrections
  (superseded auth ADRs, proposed -> accepted); INDEX rebuilt
- design/: reconstructed the v1.6.0 documents the webmention code cites;
  reports for 18 v2 releases without a design folder; INDEX rebuilt
- projectplan/: BACKLOG rewritten (shipped items removed, open issues from
  the reviews added); RELEASE.md for v2.0.0-v2.10.1; INDEX
- standards/: development setup (uv, tests, DEV_MODE), testing (CI test
  stage), git and release flow, versioning, coding standards, cookies
- README, CLAUDE.md, .env.example (every setting the code reads, with
  defaults) brought up to date
- 137 broken links repaired (old absolute paths, moved files); stale ADR
  references in code comments corrected (comments only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:40:19 -07:00

9.7 KiB
Raw Blame History

v1.6.0 Design: Webmention Background Worker

Reconstructed on 2026-11-03 from the implementation; the original v1.6.0 document was lost. Later changes: v2.6.8–v2.7.2 (see CHANGELOG). Also affected by v2.8.0 (source details, authorship, own-crosspost filter) and v2.10.1 (hard time limit on fetches). This describes the code as of v2.10.1.

Related: ADR-063 (Webmention implementation), api-contract.md, database-schema.md, rate-limiting.md, display-moderation.md.

Purpose

Webmention work that involves fetching remote URLs never happens inside a request. POST /webmention only stores a row; a background thread validates incoming webmentions and sends outgoing ones.

Modules

Module Role
starpunk/webmention_worker.py WebmentionWorker thread: queue loop, validation bookkeeping, endpoint discovery, sending, retries
starpunk/webmention_processor.py Fetch source, verify link, parse mf2, extract type/author/content
starpunk/webmention_sender.py Extract links from a note and queue outgoing webmentions
starpunk/webmention_ssrf.py safe_get / safe_post: SSRF-checked, address-pinned HTTP
starpunk/reply_context.py Fetch context for reply/like/repost targets (synchronous, see below)

Thread lifecycle

  • Started in create_app() (starpunk/__init__.py) when WEBMENTION_WORKER_ENABLED is true and TESTING is false. Stored as app.webmention_worker. Daemon thread named webmention-worker, following the MemoryMonitor pattern (a threading.Event for stop).
  • There is no teardown hook: until v2.6.8 a teardown_appcontext handler stopped the worker after the first request.
  • Each poll runs inside app.app_context() (v2.6.8), because the SSRF checks read current_app.config (DEV_MODE).
  • stop() sets the event; the loop exits after the current pass.

One worker across processes (v2.6.9)

Every gunicorn process starts a worker. Only the one holding an exclusive, non-blocking fcntl.flock on <db dir>/webmention-worker.lock processes the queues; the others poll the lock every poll_interval. The OS releases the lock when the holder dies, so another process takes over.

Orphan cleanup

When a worker first acquires the lock it resets webmention_queue rows stuck in sending for more than 5 minutes back to pending (a previous holder crashed mid-send).

Main loop

while not stopped:
    if not lock acquired: wait poll_interval; continue
    with app.app_context():
        n  = process pending validations (incoming, oldest received first, batch_size)
        n += process pending sends (outgoing, due rows, oldest first, batch_size)
    if n == 0: wait poll_interval
    on unexpected error: log, wait error_backoff
Setting Default Meaning
WEBMENTION_WORKER_ENABLED true Start the thread
WEBMENTION_POLL_INTERVAL 10 s Sleep when idle / lock not held
WEBMENTION_ERROR_BACKOFF 60 s Sleep after a loop error
WEBMENTION_BATCH_SIZE 5 Rows per queue per pass
WEBMENTION_AUTO_APPROVE true New valid mentions start approved (else pending)

get_stats() (running, last_processed, pending_validations, pending_sends) is included in the basic (unauthenticated) /health response. Note it reports the worker of whichever process answers, which may not hold the lock.

Incoming: validation

For each webmentions row with validation_status = 'pending':

  1. process_webmention(source, target, SITE_URL):
    • fetch_source: safe_get with an Accept header preferring HTML, following redirects (each hop checked). 4xx, SSRF block or >1 MB is a ValidationError; network error, timeout, 3xx without location or 5xx is a TransientError.
    • verify_link_presence (spec 3.2.2): exact target match, fragments ignored. HTML: any link-bearing attribute after resolving relative URLs against the final URL; JSON: any string value; other text/*: substring. Fails with "Source does not link to target".
    • HTML only: mf2py.parse, then mf2_utils.responding_entry picks the h-entry that responds to the target; response_type gives reply, like, repost, bookmark or mention; entry_author applies the authorship algorithm without extra fetches; extract_content takes e-content (else p-summary) as a sanitized snippet of at most ~500 characters; extract_source_details gives the entry's u-url, u-uid and dt-published (v2.8.0).
    • Author URL and photo are kept only if they are http(s) URLs (v2.6.9); the author URL falls back to the source, the name to its host.
  2. If the source is one of the target note's own u-syndication copies (syndications.remote_url, compared normalised), it is rejected (v2.8.0).
  3. Success: the row becomes valid with the extracted fields. Moderation: a first-time valid mention gets approved/pending per WEBMENTION_AUTO_APPROVE; a mention that was valid before keeps its moderation status, and hidden/deleted are never overwritten (v2.7.0).
  4. Failure (_mark_validation_failed):
    • Transient error and the mention was valid before (validated_at set, no validation_error): restored to valid with its old data; nothing disappears because the source was briefly down (v2.7.0).
    • "does not link", "returned 4xx" or own syndicated copy: invalid.
    • Anything else: error. Either way the error text is stored and the mention is no longer displayed (spec 3.2.4 for 410/no link).

Displayed responses are an update (v2.7.2, spec 3.1.4)

_validate_webmention compares _display_state() (what the note shows for this mention: type, author, photo, snippet; None if hidden) before and after validation. If it changed, webmention_sender.note_responses_changed re-queues the target note's previously sent webmentions. A re-validation that changes nothing sends nothing, so two sites doing the same don't ping-pong.

Outgoing: queueing

webmention_sender.queue_webmentions_for_note() is called by notes.py after the note is committed, best-effort (failures are logged, never fail the note):

  • Create (published only): the response target first (in_reply_to, else like_of, repost_of, bookmark_of), then <a href> links from the rendered HTML in document order; links inside <pre>/<code> are skipped (including a top-level <pre>, v2.7.0); only absolute http(s) URLs; de-duplicated; at most 10 ("architect's answer to Q1").
  • Update ("Phase 6" answers): queued when a note is published or unpublished, or a published note's content or reply target changes. The current targets (capped at 10) plus every target this note was queued for before and every link the edit removed (not capped), so receivers can update or remove the mention (v2.7.0).
  • Delete / undelete (spec 3.1.5): requeue_previous_webmentions resets all of the note's queue rows to pending; on hard delete with detach=True the source_note_id is cleared so the rows survive the cascade.
  • Rows are UPSERTed on (source_url, target_url); re-queueing resets status, retry count, error and endpoint_url.

Outgoing: sending

For each due webmention_queue row (pending, next_retry_at null or past):

  1. Mark sending with started_at.
  2. Discover the endpoint (spec 3.1.2), every time (the v1.6.0 1–24 h discovery cache was removed in v2.7.0): safe_get the target; 5xx raises (retry); 4xx, blocked or too large means no endpoint. The first Link header with rel containing the token webmention (case-insensitive, several headers and multi-value rels handled) wins, then the first <link>/<a> with that rel and an href, in document order. Relative URLs resolve against the final URL; an empty href is the target itself. No endpoint: status no_endpoint (permanent).
  3. POST source/target form-encoded with safe_post (no redirects). 2xx: sent. 429 or 5xx: retry. Other (3xx, 4xx): failed. Network error: retry. SSRF block: failed.

Retries ("architect's answer to Q5")

retry_count is incremented after the failed attempt; at 4 the row is failed. Delays after attempt 1, 2, 3: 1 h, 6 h, 24 h.

Outbound safety (webmention_ssrf.py)

Used for every fetch and send (and since v2.9.0/v2.10.0 by Micropub photo fetches and the WebSub hub):

  • http(s) only; every address the host resolves to must be public (blocks private, loopback, link-local, multicast, reserved, unspecified, CGNAT, 0.0.0.0/8, IPv4-mapped forms). DEV_MODE allows localhost.
  • The connection goes to the checked address; the hostname is sent in Host and TLS SNI so certificates are still verified (v2.7.2). IPv4 preferred.
  • Redirects followed by hand, each hop checked, at most 10; 1 MB body limit; 10 s total time limit enforced by a watchdog that closes the client (v2.10.1).
  • User-Agent StarPunk/<version> Webmention (+SITE_URL).

Reply context

reply_context.fetch_reply_context() is not run by the worker: notes.py calls it synchronously after creating a reply/like/repost/bookmark (or when an update sets in_reply_to). See database-schema.md.

Known limits

  • A DNS failure while fetching a source (ResolutionError, a ValueError) is treated as a blocked request, i.e. a permanent error, not a transient one; the WebSub worker retries DNS failures, the webmention worker does not.
  • Between receipt of a re-sent webmention and its re-validation the row is pending and not shown on the note (get_webmentions_for_note requires valid), although _display_state counts it as shown.
  • The worker opens its own sqlite3 connections (not the request pool).