aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/sender.py
blob: 3f64bed2dee024d8933a8a3805b1446f33311a1f (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Claim, send, and persist outgoing Webmention attempts."""

import uuid
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta

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

from ..db_helpers import rows_affected
from ..extensions import db, huey
from ..models import SentWebmention, SentWebmentionStatus
from ..net import (
    AddressResolutionError,
    UnsafeAddressError,
    build_public_http_client,
    is_http_url,
    is_retryable_status,
)
from ..version import APP_NAME, VERSION
from .endpoint_discovery import (
    PermanentDeliveryError,
    RetryableDeliveryError,
    discover_webmention_endpoint,
    post_webmention,
)


def revision_still_pending(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.
    :returns: Whether the attempt is still current and requires processing.
    """
    db.session.refresh(webmention)

    return webmention.desired_revision == revision and webmention.awaiting_processing


def backoff_delay(attempt: int) -> timedelta:
    """Calculate the capped exponential delay after a numbered send attempt.

    :param attempt: One-based send attempt number.
    :returns: Delay until the next attempt, capped by the configured maximum.
    """
    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.

    Run the delivery workflow under a lock associated with the outgoing Webmention.

    :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}"):
            _process_send_locked(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


@dataclass(frozen=True)
class ClaimedSendAttempt:
    """Claimed source revision and retry budget for one send."""

    webmention_uuid: uuid.UUID
    revision: int
    attempt_number: int
    max_attempts: int
    source: str
    target: str


@dataclass(frozen=True)
class DeliveryResult:
    """HTTP outcome, with whether the failure is eligible for another attempt.

    ``retryable`` describes the failure type; it does not account for the
    remaining retry budget, which may already have been exhausted.
    """

    status: SentWebmentionStatus
    reason: str | None = None
    endpoint: str | None = None
    response_status: int | None = None
    status_url: str | None = None
    retryable: bool = False


def is_ready_to_send(webmention: SentWebmention, now: datetime) -> bool:
    """Return whether an unprocessed Webmention has reached its retry deadline.

    :param webmention: Outgoing Webmention whose retry eligibility is checked.
    :param now: Current timestamp against which the retry deadline is compared.
    :returns: ``True`` if the Webmention is pending and its retry deadline has elapsed.
    """
    if not webmention.awaiting_processing:
        return False

    deadline = webmention.next_retry_at
    if deadline is None:
        return True

    aware_deadline = deadline if deadline.tzinfo else deadline.replace(tzinfo=UTC)
    return aware_deadline <= now


def reserve_send_attempt(
    webmention: SentWebmention, now: datetime
) -> ClaimedSendAttempt | None:
    """Atomically reserve one send attempt, or finish an exhausted revision.

    An attempt's next retry deadline is persisted *before* the HTTP request so
    a lost worker cannot cause an immediate duplicate send.

    :param webmention: Outgoing Webmention to reserve for sending.
    :param now: Timestamp at which the attempt is claimed.
    :returns: Reserved attempt details, or ``None`` if no attempt can be started.
    """
    revision = webmention.desired_revision
    max_attempts = max(1, int(current_app.config["SEND_MAX_ATTEMPTS"]))

    if webmention.attempt_count >= max_attempts:
        # A dead worker may have already consumed the final attempt. Never
        # finish a newer revision or a retry whose deadline is still in future.
        db.session.execute(
            sa.update(SentWebmention)
            .where(
                SentWebmention.uuid == webmention.uuid,
                SentWebmention.desired_revision == revision,
                SentWebmention.attempt_count >= max_attempts,
                SentWebmention.awaiting_processing,
                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 None

    attempt = ClaimedSendAttempt(
        webmention_uuid=webmention.uuid,
        revision=revision,
        attempt_number=webmention.attempt_count + 1,
        max_attempts=max_attempts,
        source=webmention.source.url,
        target=webmention.target,
    )
    changed = db.session.execute(
        sa.update(SentWebmention)
        .where(
            SentWebmention.uuid == attempt.webmention_uuid,
            SentWebmention.desired_revision == revision,
            SentWebmention.attempt_count == attempt.attempt_number - 1,
            SentWebmention.awaiting_processing,
            sa.or_(
                SentWebmention.next_retry_at.is_(None),
                SentWebmention.next_retry_at <= now,
            ),
        )
        .values(
            attempt_count=attempt.attempt_number,
            last_attempted_at=now,
            next_retry_at=now + backoff_delay(attempt.attempt_number),
            webmention_endpoint=None,
            endpoint_response_status=None,
            status_url=None,
        )
        .execution_options(synchronize_session=False)
    )
    db.session.commit()

    if rows_affected(changed) != 1:
        return None

    db.session.refresh(webmention)
    return attempt


def attempt_delivery(
    source: str, target: str, *, webmention_uuid: uuid.UUID
) -> DeliveryResult:
    """Discover and POST a Webmention, returning an outcome without DB writes.

    :param source: Public source URL advertising the target link.
    :param target: Target URL to notify.
    :param webmention_uuid: Identifier used for delivery logging.
    :returns: Delivery status, endpoint, response details, and any failure reason.
    """
    endpoint: str | None = None
    response_status: int | None = None
    status_url: str | None = None

    try:
        if not is_http_url(target):
            raise PermanentDeliveryError(f"Invalid target URL: {target!r}")

        with build_public_http_client(f"{APP_NAME}/{VERSION} SentWebmention") as client:
            endpoint = discover_webmention_endpoint(client, target)

            if endpoint is None:
                return DeliveryResult(
                    status=SentWebmentionStatus.NO_ENDPOINT,
                    reason="No Webmention endpoint discovered",
                )

            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 is_retryable_status(response_status):
                    raise RetryableDeliveryError(message)
                raise PermanentDeliveryError(message)

            return DeliveryResult(
                status=SentWebmentionStatus.SENT,
                endpoint=endpoint,
                response_status=response_status,
                status_url=status_url,
            )
    except (
        PermanentDeliveryError,
        UnsafeAddressError,
        httpx.InvalidURL,
        httpx.UnsupportedProtocol,
        httpx.LocalProtocolError,
    ) as exc:
        # Known permanent failures cannot improve with retries.
        return DeliveryResult(
            status=SentWebmentionStatus.FAILED,
            reason=str(exc) or type(exc).__name__,
            endpoint=endpoint,
            response_status=response_status,
        )
    except (RetryableDeliveryError, AddressResolutionError, httpx.RequestError) as exc:
        return DeliveryResult(
            status=SentWebmentionStatus.FAILED,
            reason=str(exc) or "Webmention request failed",
            endpoint=endpoint,
            response_status=response_status,
            retryable=True,
        )
    except Exception as exc:
        # Unexpected errors should not be retried; keep their traceback.
        current_app.logger.exception(
            "Unexpected error sending SentWebmention %s", webmention_uuid
        )
        return DeliveryResult(
            status=SentWebmentionStatus.FAILED,
            reason=str(exc) or type(exc).__name__,
            endpoint=endpoint,
            response_status=response_status,
        )


def record_delivery_outcome(
    webmention: SentWebmention,
    attempt: ClaimedSendAttempt,
    result: DeliveryResult,
    *,
    terminal: bool,
) -> bool:
    """Record an outcome only while the claimed source revision is current.

    :param webmention: Outgoing Webmention being updated.
    :param attempt: Claimed revision and attempt details.
    :param result: Result of the delivery attempt.
    :param terminal: Whether this outcome ends attempts for the current revision.
    :returns: ``True`` if the outcome was recorded for the current revision.
    """
    # A scanner may have reopened or superseded the revision during I/O.
    if not revision_still_pending(webmention, attempt.revision):
        return False

    webmention.status = result.status
    webmention.failure_reason = result.reason
    webmention.webmention_endpoint = result.endpoint
    webmention.endpoint_response_status = result.response_status

    if terminal:
        webmention.processed_revision = attempt.revision
        webmention.next_retry_at = None

    if result.status == SentWebmentionStatus.SENT:
        webmention.sent_revision = attempt.revision
        webmention.status_url = (
            result.status_url
            if result.status_url is not None and is_http_url(result.status_url)
            else None
        )
        webmention.last_sent_at = datetime.now(UTC)

    db.session.commit()
    return True


def _process_send_locked(webmention_uuid: uuid.UUID) -> bool:
    """Process a due Webmention while holding its per-UUID task lock.

    :param webmention_uuid: Identifier of the outgoing Webmention being processed.
    :returns: Whether this worker recorded a delivery outcome.
    """
    webmention = db.session.get(SentWebmention, webmention_uuid)
    if webmention is None:
        current_app.logger.warning(
            "Cannot send unknown SentWebmention %s", webmention_uuid
        )
        return False

    now = datetime.now(UTC)
    if not is_ready_to_send(webmention, now):
        return False

    if (attempt := reserve_send_attempt(webmention, now)) is None:
        return False

    result = attempt_delivery(
        attempt.source, attempt.target, webmention_uuid=webmention_uuid
    )
    terminal = not result.retryable or attempt.attempt_number >= attempt.max_attempts

    if not record_delivery_outcome(webmention, attempt, result, terminal=terminal):
        return False

    if result.retryable and not terminal:
        # Huey does not retry: the scanner requeues after next_retry_at.
        current_app.logger.info(
            "Webmention %s send attempt %d failed; will retry",
            webmention_uuid,
            attempt.attempt_number,
        )
    elif result.retryable:
        current_app.logger.warning(
            "Webmention %s exhausted %d send attempts: %s",
            webmention_uuid,
            attempt.attempt_number,
            result.reason,
        )

    return True