- 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>
9.7 KiB
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) whenWEBMENTION_WORKER_ENABLEDis true andTESTINGis false. Stored asapp.webmention_worker. Daemon thread namedwebmention-worker, following theMemoryMonitorpattern (athreading.Eventfor stop). - There is no teardown hook: until v2.6.8 a
teardown_appcontexthandler stopped the worker after the first request. - Each poll runs inside
app.app_context()(v2.6.8), because the SSRF checks readcurrent_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':
process_webmention(source, target, SITE_URL):fetch_source:safe_getwith anAcceptheader preferring HTML, following redirects (each hop checked). 4xx, SSRF block or >1 MB is aValidationError; network error, timeout, 3xx without location or 5xx is aTransientError.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; othertext/*: substring. Fails with "Source does not link to target".- HTML only:
mf2py.parse, thenmf2_utils.responding_entrypicks the h-entry that responds to the target;response_typegivesreply,like,repost,bookmarkormention;entry_authorapplies the authorship algorithm without extra fetches;extract_contenttakese-content(elsep-summary) as a sanitized snippet of at most ~500 characters;extract_source_detailsgives the entry'su-url,u-uidanddt-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.
- If the source is one of the target note's own
u-syndicationcopies (syndications.remote_url, compared normalised), it is rejected (v2.8.0). - Success: the row becomes
validwith the extracted fields. Moderation: a first-time valid mention getsapproved/pendingperWEBMENTION_AUTO_APPROVE; a mention that was valid before keeps its moderation status, andhidden/deletedare never overwritten (v2.7.0). - Failure (
_mark_validation_failed):- Transient error and the mention was valid before (
validated_atset, novalidation_error): restored tovalidwith 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).
- Transient error and the mention was valid before (
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, elselike_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_webmentionsresets all of the note's queue rows topending; on hard delete withdetach=Truethesource_note_idis cleared so the rows survive the cascade. - Rows are UPSERTed on
(source_url, target_url); re-queueing resets status, retry count, error andendpoint_url.
Outgoing: sending
For each due webmention_queue row (pending, next_retry_at null or
past):
- Mark
sendingwithstarted_at. - 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_getthe target; 5xx raises (retry); 4xx, blocked or too large means no endpoint. The firstLinkheader withrelcontaining the tokenwebmention(case-insensitive, several headers and multi-value rels handled) wins, then the first<link>/<a>with that rel and anhref, in document order. Relative URLs resolve against the final URL; an emptyhrefis the target itself. No endpoint: statusno_endpoint(permanent). - POST
source/targetform-encoded withsafe_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_MODEallowslocalhost. - The connection goes to the checked address; the hostname is sent in
Hostand 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, aValueError) is treated as a blocked request, i.e. a permanenterror, 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
pendingand not shown on the note (get_webmentions_for_noterequiresvalid), although_display_statecounts it as shown. - The worker opens its own
sqlite3connections (not the request pool).