# SPDX-FileCopyrightText: 2026 Dennis Fink # # 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" {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 ) ) ) )