aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/models/received.py
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--webmentions_ssg/models/received.py131
1 files changed, 131 insertions, 0 deletions
diff --git a/webmentions_ssg/models/received.py b/webmentions_ssg/models/received.py
new file mode 100644
index 0000000..a9047ad
--- /dev/null
+++ b/webmentions_ssg/models/received.py
@@ -0,0 +1,131 @@
+# 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
+
+from sqlalchemy import (
+ DateTime,
+ Enum,
+ Index,
+ Integer,
+ String,
+ Text,
+ UniqueConstraint,
+ Uuid,
+)
+from sqlalchemy.orm import Mapped, mapped_column, validates
+
+from ..extensions import Base
+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
+ )
+
+ __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)