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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Incoming Webmention state and persistence."""
from datetime import UTC, datetime
from enum import StrEnum
from uuid import UUID
import sqlalchemy as sa
from sqlalchemy import (
DateTime,
Enum,
ForeignKey,
Index,
Integer,
String,
Text,
UniqueConstraint,
Uuid,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship, validates
from ..extensions import Base, db
from .utils import source_target_digest, uuid7_to_datetime
class ReceivedWebmentionStatus(StrEnum):
"""Persisted lifecycle state of an incoming Webmention."""
RECEIVED = "received"
VERIFYING = "verifying"
VERIFIED = "verified"
FAILED = "failed"
SOURCE_REMOVED = "source_removed"
class ReceivedWebmention(Base):
"""Represent a Webmention received for verification."""
__tablename__ = "received_webmentions"
uuid: Mapped[UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True)
source: Mapped[str] = mapped_column(Text(), nullable=False)
target: Mapped[str] = mapped_column(Text(), nullable=False)
source_target_digest: Mapped[str] = mapped_column(String(64), nullable=False)
@validates("source", "target")
def _refresh_url_digest(self, key: str, value: str) -> str:
source = value if key == "source" else self.__dict__.get("source")
target = value if key == "target" else self.__dict__.get("target")
if source is not None and target is not None:
self.source_target_digest = source_target_digest(source, target)
return value
status: Mapped[ReceivedWebmentionStatus] = mapped_column(
Enum(
ReceivedWebmentionStatus,
name="received_webmention_status",
values_callable=lambda enum_type: [member.value for member in enum_type],
native_enum=False,
),
nullable=False,
default=ReceivedWebmentionStatus.RECEIVED,
)
# Counts stale-row requeues, not Huey's bounded in-task retries. A fresh
# explicit submission resets this counter.
recovery_attempts: Mapped[int] = mapped_column(
Integer, nullable=False, default=0, server_default="0"
)
failure_reason: Mapped[str | None] = mapped_column(
Text(), nullable=True, default=None
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(UTC),
onupdate=lambda: datetime.now(UTC),
nullable=False,
)
notification_sent_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True, default=None
)
status_events: Mapped[list[ReceivedWebmentionStatusEvent]] = relationship(
back_populates="webmention", cascade="all, delete-orphan"
)
__table_args__ = (
UniqueConstraint(
"source_target_digest", name="uq_webmention_source_target_digest"
),
Index("ix_received_webmentions_status_updated_at", "status", "updated_at"),
)
def __repr__(self) -> str:
"""Represent the received Webmention by source and target."""
return f"<ReceivedWebmention {self.source!r} -> {self.target!r}>"
@staticmethod
def reopen_verification_values(
*, at: datetime, recovery_attempts: int = 0
) -> dict[str, object]:
"""Return the columns to reset when verification is explicitly reopened.
:param at: Timestamp to record for the newly opened verification.
:param recovery_attempts: Number of stale-lease recovery attempts to retain.
:returns: Column values for resetting the verification state.
"""
return {
"status": ReceivedWebmentionStatus.RECEIVED,
"failure_reason": None,
"recovery_attempts": recovery_attempts,
"updated_at": at,
}
def reopen_verification(self) -> None:
"""Reopen an existing row for manual verification.
Clear the previous outcome and restore the received state with a fresh
timestamp.
"""
for key, value in self.reopen_verification_values(at=datetime.now(UTC)).items():
setattr(self, key, value)
@property
def verified(self) -> bool:
"""Return whether the Webmention has been successfully verified."""
return self.status == ReceivedWebmentionStatus.VERIFIED
@property
def created_at(self) -> datetime:
"""Return the creation time encoded in the Webmention UUID."""
return uuid7_to_datetime(self.uuid)
class ReceivedWebmentionStatusEvent(Base):
"""A persisted lifecycle transition for a received Webmention.
Events record observed transitions rather than reconstructing missing history
from the current status. They are private to the authenticated admin view.
"""
__tablename__ = "received_webmention_status_events"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
webmention_uuid: Mapped[UUID] = mapped_column(
Uuid(as_uuid=True),
ForeignKey("received_webmentions.uuid", ondelete="CASCADE"),
nullable=False,
)
status: Mapped[ReceivedWebmentionStatus] = mapped_column(
Enum(
ReceivedWebmentionStatus,
name="received_webmention_status",
values_callable=lambda enum_type: [member.value for member in enum_type],
native_enum=False,
),
nullable=False,
)
action: Mapped[str] = mapped_column(String(80), nullable=False)
failure_reason: Mapped[str | None] = mapped_column(Text(), nullable=True)
recovery_attempts: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
occurred_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False
)
webmention: Mapped[ReceivedWebmention] = relationship(
back_populates="status_events"
)
__table_args__ = (
Index(
"ix_received_webmention_status_events_webmention_id",
"webmention_uuid",
"id",
),
)
def purge_orphaned_received_events() -> None:
"""Remove status events whose parent Webmention no longer exists.
Provides a fallback when database-level ON DELETE CASCADE is not
enforced (e.g. SQLite with foreign-key enforcement disabled).
Run after deleting parent rows in the same transaction so that
events belonging to surviving rows are preserved.
"""
db.session.execute(
sa.delete(ReceivedWebmentionStatusEvent).where(
~sa.exists(
sa.select(ReceivedWebmention.uuid).where(
ReceivedWebmention.uuid
== ReceivedWebmentionStatusEvent.webmention_uuid
)
)
)
)
|