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

"""Delete old received Webmentions in terminal unsuccessful states."""

from datetime import UTC, datetime, timedelta

import sqlalchemy as sa
from flask import current_app

from ..db_helpers import rows_affected
from ..extensions import db
from ..models.received import (
    ReceivedWebmention,
    ReceivedWebmentionStatus,
    purge_orphaned_received_events,
)


def purge_old_received_webmentions() -> int:
    """Delete old failed/deleted received rows, retaining verified and in-flight ones.

    The status/time predicate is checked by the database in one DELETE, so a
    row recently requeued for verification is not purged based on a stale read.
    Outgoing sources and Webmentions are intentionally unaffected.

    Use the configured retention period and leave verified or in-progress rows
    untouched.

    :returns: Number of expired terminal Webmentions removed.
    """
    cutoff = datetime.now(UTC) - timedelta(
        days=current_app.config["RECEIVED_RETENTION_DAYS"]
    )

    result = db.session.execute(
        sa.delete(ReceivedWebmention).where(
            ReceivedWebmention.status.in_(
                (
                    ReceivedWebmentionStatus.FAILED,
                    ReceivedWebmentionStatus.SOURCE_REMOVED,
                )
            ),
            ReceivedWebmention.updated_at < cutoff,
        )
    )
    purge_orphaned_received_events()
    db.session.commit()

    count = rows_affected(result)
    if count:
        current_app.logger.info("Purged %d old failed/deleted Webmentions", count)

    return count