aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/sender.py
blob: a4a83671e21cf99431c4c25301ec457b55b30d62 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Discover endpoints and deliver outgoing Webmentions."""

import re
import uuid
from datetime import UTC, datetime, timedelta
from urllib.parse import urljoin

import httpx
import sqlalchemy as sa
from bs4 import BeautifulSoup
from flask import current_app
from huey.exceptions import TaskLockedException

from .. import APP_NAME, VERSION
from .. import DATABASE as db
from .. import HUEY as huey
from ..models import SentWebmention, SentWebmentionStatus
from ..url_security import AddressResolutionError, is_http_url, is_public_url

LINK_SPLIT = re.compile(r",\s*(?=<)")

DISCOVERY_HEADERS = {"Accept": "text/html, application/xhtml+xml;q=0.9"}


class SenderError(Exception):
    """A Webmention cannot be sent."""


class TemporarySenderError(SenderError):
    """A Webmention send failed for a potentially temporary reason."""


class PermanentSenderError(SenderError):
    """A Webmention send failed permanently for this source revision."""


def temporary_http_status(status: int) -> bool:
    """
    Return whether an HTTP status indicates a temporary failure.

    :param status: HTTP response status code.
    :return: Whether the request should be retried.
    """
    return status in {408, 425, 429} or 500 <= status <= 599


def ensure_public_request(request: httpx.Request) -> None:
    """
    Ensure that an HTTP request targets a public network address.

    :param request: HTTP request to validate.
    :raises PermanentSenderError: If the request resolves to a non-public address.
    :raises TemporarySenderError: If the request hostname cannot be resolved.
    """
    try:
        if not is_public_url(str(request.url)):
            raise PermanentSenderError("Request resolves to a non-public address")
    except AddressResolutionError as exc:
        raise TemporarySenderError("Request hostname could not be resolved") from exc


def resolve_endpoint(response: httpx.Response, href: str) -> str:
    """
    Resolve and validate a discovered Webmention endpoint.

    :param response: Response from which the endpoint was discovered.
    :param href: Endpoint reference to resolve.
    :return: Absolute Webmention endpoint URL.
    :raises PermanentSenderError: If the resolved endpoint is not an HTTP or
        HTTPS URL.
    """
    endpoint = urljoin(str(response.url), href.strip())

    if not is_http_url(endpoint):
        raise PermanentSenderError(f"Invalid Webmention endpoint: {endpoint!r}")

    return endpoint


def parse_link_value(value: str) -> tuple[str, set[str]] | None:
    """
    Parse a Link header value into its target and relations.

    :param value: Link header value to parse.
    :return: Link target and relation names, or ``None`` if the value is invalid.
    """
    value = value.strip()

    if not value.startswith("<"):
        return None

    href, separator, parameters = value[1:].partition(">")

    if not separator:
        return None

    relations: set[str] = set()

    for parameter in parameters.split(";"):
        name, separator, value = parameter.partition("=")

        if separator and name.strip().lower() == "rel":
            relations.update(
                relation.lower() for relation in value.strip().strip("\"'").split()
            )

    return href, relations


def endpoint_from_headers(response: httpx.Response) -> str | None:
    """
    Find a Webmention endpoint in the response Link headers.

    :param response: HTTP response whose headers should be inspected.
    :return: First advertised Webmention endpoint, or ``None`` if none is found.
    :raises PermanentSenderError: If a discovered endpoint is invalid.
    """
    for header in response.headers.get_list("Link"):
        for value in LINK_SPLIT.split(header):
            if (link := parse_link_value(value)) is None:
                continue

            href, relations = link

            if "webmention" in relations:
                return resolve_endpoint(response, href)

    return None


def endpoint_from_html(response: httpx.Response, body: bytes) -> str | None:
    """
    Find a Webmention endpoint in an HTML document.

    ``link`` and ``a`` elements are inspected in document order.

    :param response: HTTP response from which the document was retrieved.
    :param body: HTML document body.
    :return: First advertised Webmention endpoint, or ``None`` if none is found.
    :raises PermanentSenderError: If a discovered endpoint is invalid.
    """
    document = BeautifulSoup(body, "html5lib")

    for element in document.find_all(["link", "a"], href=True):
        relations = element.get("rel")

        if isinstance(relations, str):
            relations = relations.split()

        if not relations:
            continue

        if not any(
            isinstance(relation, str) and relation.lower() == "webmention"
            for relation in relations
        ):
            continue

        href = element.get("href")

        if not isinstance(href, str):
            continue

        return resolve_endpoint(response, href)

    return None


def read_target_body(response: httpx.Response) -> bytes:
    """
    Read a target document up to the configured size limit.

    :param response: Streaming HTTP response to read.
    :return: Response body.
    :raises PermanentSenderError: If the document exceeds the configured maximum
        size.
    """
    max_bytes = current_app.config.get("MAX_TARGET_BYTES", 1_000_000)

    if (content_length := response.headers.get("Content-Length")) is not None:
        try:
            if int(content_length) > max_bytes:
                raise PermanentSenderError("Target document is too large")
        except ValueError:
            pass

    body = bytearray()

    for chunk in response.iter_bytes(chunk_size=64 * 1024):
        body.extend(chunk)

        if len(body) > max_bytes:
            raise PermanentSenderError("Target document is too large")

    return bytes(body)


def discover_webmention_endpoint(client: httpx.Client, target: str) -> str | None:
    """
    Discover the Webmention endpoint advertised by a target URL.

    Endpoint discovery first checks the response to a HEAD request and then falls
    back to a GET request, inspecting both HTTP Link headers and supported HTML
    documents.

    :param client: HTTP client to use for discovery requests.
    :param target: Target URL whose Webmention endpoint should be discovered.
    :return: Discovered Webmention endpoint, or ``None`` if none is advertised.
    :raises TemporarySenderError: If the target returns a temporary HTTP failure.
    :raises PermanentSenderError: If the target returns a permanent HTTP failure
        or advertises an invalid endpoint.
    """
    head_response = client.head(target, headers=DISCOVERY_HEADERS)

    if endpoint := endpoint_from_headers(head_response):
        return endpoint

    with client.stream("GET", target, headers=DISCOVERY_HEADERS) as response:
        if endpoint := endpoint_from_headers(response):
            return endpoint

        if temporary_http_status(response.status_code):
            raise TemporarySenderError(f"Target returned HTTP {response.status_code}")

        if not response.is_success:
            raise PermanentSenderError(f"Target returned HTTP {response.status_code}")

        media_type = (
            response.headers.get("Content-Type", "").partition(";")[0].strip().lower()
        )

        if media_type not in {"text/html", "application/xhtml+xml"}:
            return None

        return endpoint_from_html(response, read_target_body(response))


def post_webmention(
    client: httpx.Client, *, endpoint: str, source: str, target: str
) -> tuple[int, str | None]:
    """
    Send a Webmention to a discovered endpoint.

    :param client: HTTP client to use for the request.
    :param endpoint: Webmention endpoint URL.
    :param source: Source URL of the Webmention.
    :param target: Target URL of the Webmention.
    :return: HTTP response status code and optional status URL.
    """
    with client.stream(
        "POST", endpoint, data={"source": source, "target": target}
    ) as response:
        status_url = None

        if response.status_code == 201 and (
            location := response.headers.get("Location")
        ):
            try:
                candidate = urljoin(str(response.url), location)
            except ValueError:
                # A malformed Location must not fail an otherwise successful send.
                pass
            else:
                if is_http_url(candidate):
                    status_url = candidate

        return (response.status_code, status_url)


def attempt_is_current(webmention: SentWebmention, revision: int) -> bool:
    """
    Check whether a send attempt still represents the desired revision.

    The Webmention is refreshed from the database before comparing its desired
    and processed revisions.

    :param webmention: Sent Webmention being processed.
    :param revision: Source revision represented by the current attempt.
    :return: Whether the attempt is still current and requires processing.
    """
    db.session.refresh(webmention)

    return webmention.desired_revision == revision and (
        webmention.processed_revision is None
        or webmention.processed_revision < revision
    )


def retry_delay(attempt: int) -> timedelta:
    """Calculate the capped exponential delay after a numbered send attempt."""
    base = max(1, int(current_app.config["SEND_RETRY_BASE_SECONDS"]))
    maximum = max(base, int(current_app.config["SEND_RETRY_MAX_SECONDS"]))
    return timedelta(seconds=min(base * 2 ** (attempt - 1), maximum))


@huey.task()
def send_webmention(webmention_uuid: uuid.UUID) -> None:
    """
    Discover a receiver endpoint and send a Webmention.

    The result of the attempt is stored on the corresponding sent Webmention.
    Temporary failures are recorded with an exponential retry deadline. The
    scanner requeues them when due; Huey does not retry them independently.
    The retry budget is per desired source revision.

    :param webmention_uuid: Identifier of the sent Webmention to process.
    """
    # Huey locks have static names when used as decorators. Acquire one keyed by
    # UUID inside the task so different Webmentions can still send in parallel.
    # The pending/retry checks must happen *under* this lock.
    try:
        with huey.lock_task(f"send-webmention-{webmention_uuid}"):
            send_webmention_task(webmention_uuid)
    except TaskLockedException:
        # Another worker is already sending this Webmention. The active worker
        # owns its result; a later scan will requeue it if it remains pending.
        return


def send_webmention_task(webmention_uuid: uuid.UUID) -> None:
    """Process a Webmention while holding its per-UUID task lock."""
    webmention = db.session.get(SentWebmention, webmention_uuid)

    if webmention is None:
        current_app.logger.warning(
            "Cannot send unknown SentWebmention %s", webmention_uuid
        )
        return

    if (
        webmention.processed_revision is not None
        and webmention.processed_revision >= webmention.desired_revision
    ):
        return

    revision = webmention.desired_revision
    source = webmention.source.url
    target = webmention.target
    now = datetime.now(UTC)
    deadline = webmention.next_retry_at

    # SQLite returns timezone-naive datetimes even for timezone-aware columns.
    if deadline is not None:
        aware_deadline = deadline if deadline.tzinfo else deadline.replace(tzinfo=UTC)
        if aware_deadline > now:
            return

    max_attempts = max(1, int(current_app.config["SEND_MAX_ATTEMPTS"]))
    if webmention.attempt_count >= max_attempts:
        # Recover records whose worker died during the final attempt, without
        # touching a newer revision that may have been queued in the meantime.
        db.session.execute(
            sa.update(SentWebmention)
            .where(
                SentWebmention.uuid == webmention_uuid,
                SentWebmention.desired_revision == revision,
                SentWebmention.attempt_count >= max_attempts,
                sa.or_(
                    SentWebmention.processed_revision.is_(None),
                    SentWebmention.processed_revision < revision,
                ),
                sa.or_(
                    SentWebmention.next_retry_at.is_(None),
                    SentWebmention.next_retry_at <= now,
                ),
            )
            .values(
                processed_revision=revision,
                next_retry_at=None,
                status=SentWebmentionStatus.FAILED,
                failure_reason=(
                    webmention.failure_reason
                    or f"Retry limit reached ({max_attempts} attempts)"
                ),
            )
            .execution_options(synchronize_session=False)
        )
        db.session.commit()
        return

    attempt = webmention.attempt_count + 1
    next_retry_at = now + retry_delay(attempt)

    # Claim the attempt atomically: duplicate queued tasks must not send the
    # same revision concurrently or bypass its retry deadline.
    claim = db.session.execute(
        sa.update(SentWebmention)
        .where(
            SentWebmention.uuid == webmention_uuid,
            SentWebmention.desired_revision == revision,
            SentWebmention.attempt_count == attempt - 1,
            sa.or_(
                SentWebmention.processed_revision.is_(None),
                SentWebmention.processed_revision < revision,
            ),
            sa.or_(
                SentWebmention.next_retry_at.is_(None),
                SentWebmention.next_retry_at <= now,
            ),
        )
        .values(
            attempt_count=attempt,
            last_attempted_at=now,
            next_retry_at=next_retry_at,
            endpoint=None,
            response_status=None,
            status_url=None,
        )
        .execution_options(synchronize_session=False)
    )
    db.session.commit()

    if claim.rowcount != 1:
        return

    db.session.refresh(webmention)

    endpoint: str | None = None
    response_status: int | None = None

    try:
        with httpx.Client(
            headers={"User-Agent": (f"{APP_NAME}/{VERSION} SentWebmention")},
            timeout=httpx.Timeout(current_app.config.get("REQUEST_TIMEOUT", 5.0)),
            follow_redirects=True,
            max_redirects=current_app.config.get("MAX_REDIRECTS", 20),
            trust_env=False,
            event_hooks={"request": [ensure_public_request]},
        ) as client:
            endpoint = discover_webmention_endpoint(client, target)

            if endpoint is None:
                if not attempt_is_current(webmention, revision):
                    return

                webmention.processed_revision = revision
                webmention.next_retry_at = None
                webmention.status = SentWebmentionStatus.UNSUPPORTED
                webmention.failure_reason = "No Webmention endpoint discovered"
                webmention.endpoint = None
                webmention.response_status = None

                db.session.commit()
                return

            (response_status, status_url) = post_webmention(
                client, endpoint=endpoint, source=source, target=target
            )

            if not (200 <= response_status <= 299):
                message = f"Webmention endpoint returned HTTP {response_status}"

                if temporary_http_status(response_status):
                    raise TemporarySenderError(message)

                raise PermanentSenderError(message)

    except (TemporarySenderError, httpx.RequestError) as exc:
        if not attempt_is_current(webmention, revision):
            return

        webmention.status = SentWebmentionStatus.FAILED
        webmention.failure_reason = str(exc) or "Webmention request failed"
        if attempt >= max_attempts:
            webmention.processed_revision = revision
            webmention.next_retry_at = None
            current_app.logger.warning(
                "Webmention %s exhausted %d send attempts: %s",
                webmention_uuid,
                attempt,
                webmention.failure_reason,
            )
        webmention.endpoint = endpoint
        webmention.response_status = response_status

        db.session.commit()

        # No Huey retries: only the scanner may requeue after next_retry_at.
        return

    except PermanentSenderError as exc:
        if not attempt_is_current(webmention, revision):
            return

        webmention.processed_revision = revision
        webmention.next_retry_at = None
        webmention.status = SentWebmentionStatus.FAILED
        webmention.failure_reason = str(exc)
        webmention.endpoint = endpoint
        webmention.response_status = response_status

        db.session.commit()
        return

    if not attempt_is_current(webmention, revision):
        return

    webmention.processed_revision = revision
    webmention.next_retry_at = None
    webmention.sent_revision = revision

    webmention.status = SentWebmentionStatus.SENT
    webmention.failure_reason = None

    webmention.endpoint = endpoint
    webmention.response_status = response_status
    webmention.status_url = (
        status_url if status_url is not None and is_http_url(status_url) else None
    )

    webmention.last_sent_at = datetime.now(UTC)

    db.session.commit()