Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

13.0 KB
Raw Blame
"""Shared constants for the news subsystem."""

from ..database.models.news import SubscriptionFolder

# Subscription scheduling bounds. Shared by the create route and both
# update routes (``web/routers/news_flask_api.py`` imports these back) so
# their limits cannot drift apart.
NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES = 1
# Cap on a value being written now: create, and both update routes.
NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES = 10_080
# Ceiling on a value that is already saved. v1.10.7 stored whatever interval
# it was sent -- its form set only min="1" and its docs allowed up to 30 days
# -- so rows above the write cap exist and must keep running after an
# upgrade. One year is far past that documented range and keeps every
# ``timedelta``/``datetime``/APScheduler date computed from the value
# comfortably in range; anything beyond it is not a usable schedule.
NEWS_SUBSCRIPTION_MAX_SAVED_REFRESH_MINUTES = 525_600

# Shown when a saved row cannot be run until the user fixes its interval.
# Shared by the manual run, the overdue sweep and the research-start guard.
SUBSCRIPTION_INTERVAL_REPAIR_MESSAGE = (
    "Edit this subscription's refresh interval before running it"
)


def _is_whole_minutes_up_to(value, maximum: int) -> bool:
    # ``type(...) is int`` rather than ``isinstance`` so bool, float (NaN and
    # infinity included), str and None are all rejected.
    return (
        type(value) is int
        and NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES <= value <= maximum
    )


def is_valid_refresh_interval(value) -> bool:
    """Whether ``value`` may be written as a refresh interval now.

    Applies to a new subscription and to an interval sent with an edit. A
    row saved before the cap existed is judged by
    :func:`is_runnable_refresh_interval` instead.
    """
    return _is_whole_minutes_up_to(value, NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES)


def is_runnable_refresh_interval(value) -> bool:
    """Whether an already-saved interval is safe to schedule and run.

    Accepts every whole number of minutes the released form could store, up
    to :data:`NEWS_SUBSCRIPTION_MAX_SAVED_REFRESH_MINUTES`. Rejects what
    cannot be scheduled: non-integers (NaN, fractions, text, null), zero and
    negatives (APScheduler turns a zero interval into a one-second trigger)
    and anything beyond the ceiling.
    """
    return _is_whole_minutes_up_to(
        value, NEWS_SUBSCRIPTION_MAX_SAVED_REFRESH_MINUTES
    )


def validate_refresh_interval(value) -> None:
    """Reject an interval that may not be written (create or edit)."""
    if not is_valid_refresh_interval(value):
        from .exceptions import NewsAPIException

        raise NewsAPIException(
            "Refresh interval must be an integer between "
            f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "
            f"{NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES} minutes",
            status_code=400,
            error_code="INVALID_REFRESH_INTERVAL",
        )


def validate_runnable_refresh_interval(value) -> None:
    """Reject a saved interval before a run's schedule is advanced from it."""
    if not is_runnable_refresh_interval(value):
        from .exceptions import NewsAPIException

        raise NewsAPIException(
            "Saved refresh interval must be an integer between "
            f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "
            f"{NEWS_SUBSCRIPTION_MAX_SAVED_REFRESH_MINUTES} minutes",
            status_code=400,
            error_code="INVALID_REFRESH_INTERVAL",
        )


# ``NewsSubscription.name`` is ``Column(String(255))`` (database/models/
# news.py:63) -- this mirrors that column's length, it is not an
# independently chosen limit.
COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH = 255

COMPACT_SUBSCRIPTION_DIRECT_FIELDS = (
    "folder",
    "folder_id",
    "name",
    "notes",
    "refresh_interval_minutes",
)
COMPACT_SUBSCRIPTION_INPUT_FIELDS = frozenset(
    (*COMPACT_SUBSCRIPTION_DIRECT_FIELDS, "is_active", "status")
)
COMPACT_SUBSCRIPTION_STATUSES = frozenset({"active", "paused"})

# The exact key set of the response body
# ``news_flask_api._update_subscription_folder_sync`` returns from a
# successful PUT /news/api/subscription/subscriptions/{id}. NewsSubscription
# has no ``to_dict()`` (unlike SubscriptionFolder below), so this is hand-kept
# in sync with that dict literal rather than introspected off the model --
# deliberately NOT "every NewsSubscription column minus the allowlist", which
# would also swallow genuinely sensitive, non-response columns such as
# ``custom_endpoint`` (the very field #5603/this PR's docstring call out as
# needing to stay rejected, not silently dropped).
COMPACT_SUBSCRIPTION_RESPONSE_FIELDS = frozenset(
    (
        "id",
        "name",
        "status",
        "is_active",
        "folder_id",
        "refresh_interval_minutes",
        "next_refresh",
        "last_refresh",
    )
)
# Fields the endpoint's own response echoes back that are not writable.
# A client that PUTs its own prior PUT response back (change one field,
# resend the rest) always resends these; rejecting them broke that pattern.
# They are still never written -- see the allowlist-only comprehension at
# the end of normalize_compact_subscription_update -- only no longer
# rejected for merely being present.
COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS = (
    COMPACT_SUBSCRIPTION_RESPONSE_FIELDS - COMPACT_SUBSCRIPTION_INPUT_FIELDS
)


def _unsupported_update_fields_message(unsupported_fields):
    """Reflect at most eight sorted names, each at most 32 characters.

    Including separators and the omitted-count suffix, this stays below
    320 characters. This bounds reflected content, not parsing or sorting.
    """
    fields = sorted(unsupported_fields)
    message = ", ".join(
        field if len(field) <= 32 else field[:29] + "..."
        for field in fields[:8]
    )
    if len(fields) > 8:
        message += f", ... (+{len(fields) - 8} more)"
    return message


def compact_subscription_update_error(data):
    """Return the validation message for a compact subscription update, or None.

    Routes return this string to the client directly rather than echoing
    ``str()`` of a caught exception. Unsupported names are reflected with
    bounded content; other validation messages are fixed.
    """
    unsupported_fields = (
        set(data)
        - COMPACT_SUBSCRIPTION_INPUT_FIELDS
        - COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS
    )
    if unsupported_fields:
        fields = _unsupported_update_fields_message(unsupported_fields)
        return f"Unsupported subscription update fields: {fields}"

    if "is_active" in data and type(data["is_active"]) is not bool:
        return "is_active must be a boolean"

    if "status" in data and (
        type(data["status"]) is not str
        or data["status"] not in COMPACT_SUBSCRIPTION_STATUSES
    ):
        return "status must be 'active' or 'paused'"

    if "refresh_interval_minutes" in data and not is_valid_refresh_interval(
        data["refresh_interval_minutes"]
    ):
        return (
            "refresh_interval_minutes must be an integer between "
            f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "
            f"{NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES}"
        )

    for field in ("folder", "folder_id", "name", "notes"):
        if (
            field in data
            and data[field] is not None
            and type(data[field]) is not str
        ):
            return f"{field} must be a string or null"

    # ``name`` is user-editable through the full ``PUT /subscriptions/{id}``
    # route's ``field_mapping`` (web/routers/news_flask_api.py) and shares
    # that column's length bound here.
    if (
        "name" in data
        and isinstance(data["name"], str)
        and len(data["name"]) > COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH
    ):
        return (
            "name exceeds maximum length of "
            f"{COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH} characters"
        )

    return None


def normalize_compact_subscription_update(data):
    error = compact_subscription_update_error(data)
    if error is not None:
        raise ValueError(error)

    update_data = {
        field: data[field]
        for field in COMPACT_SUBSCRIPTION_DIRECT_FIELDS
        if field in data
    }
    if "is_active" in data:
        update_data["status"] = "active" if data["is_active"] else "paused"
    if "status" in data:
        update_data["status"] = data["status"]
    return update_data


# The SubscriptionFolder model's user-editable columns (see
# database/models/news.py). id/created_at/updated_at are deliberately
# excluded -- they are server-managed, so setattr must never reach them --
# but see FOLDER_READONLY_ECHO_FIELDS below: excluded from *writes* is not
# the same as rejecting a request that merely *mentions* them.
FOLDER_UPDATABLE_FIELDS = frozenset(
    ("name", "description", "color", "icon", "is_default", "sort_order")
)

# SubscriptionFolder.to_dict() emits every column on the model, including
# id/created_at/updated_at, which are not in FOLDER_UPDATABLE_FIELDS above.
# A read-modify-write client (GET the folder, change ``name``, PUT the whole
# to_dict() body back) always resends those three. Derived from the live
# model's columns -- not hardcoded -- so it can't drift from what to_dict()
# actually returns; anything that's a real column here is inherently safe to
# ignore rather than reject, since FOLDER_UPDATABLE_FIELDS below still
# decides what actually gets written regardless of what this set allows
# through the door.
FOLDER_READONLY_ECHO_FIELDS = (
    frozenset(column.name for column in SubscriptionFolder.__table__.columns)
    - FOLDER_UPDATABLE_FIELDS
)


def folder_update_error(data):
    """Return the validation message for a folder update, or None.

    See :func:`normalize_folder_update` for the rules. Like
    :func:`compact_subscription_update_error`, this lets routes return a
    fixed message without echoing ``str()`` of a caught exception.
    """
    unsupported_fields = (
        set(data) - FOLDER_UPDATABLE_FIELDS - FOLDER_READONLY_ECHO_FIELDS
    )
    if unsupported_fields:
        fields = _unsupported_update_fields_message(unsupported_fields)
        return f"Unsupported folder update fields: {fields}"

    # ``name`` is NOT NULL on the SubscriptionFolder model (database/models/
    # news.py), so unlike description/color/icon it cannot accept a null.
    if "name" in data and type(data["name"]) is not str:
        return "name must be a string"

    for field in ("description", "color", "icon"):
        if (
            field in data
            and data[field] is not None
            and type(data[field]) is not str
        ):
            return f"{field} must be a string or null"

    if "is_default" in data and type(data["is_default"]) is not bool:
        return "is_default must be a boolean"

    # ``type(x) is not int`` (rather than ``isinstance``) also rejects a
    # bool masquerading as an int -- ``type(True) is bool``, not ``int`` --
    # matching the convention already used above for ``is_default`` and by
    # ``normalize_compact_subscription_update`` for ``is_active``/
    # ``refresh_interval_minutes``.
    if "sort_order" in data and type(data["sort_order"]) is not int:
        return "sort_order must be an integer"

    return None


def normalize_folder_update(data):
    """Validate a folder update payload against the allowlisted fields.

    ``FolderManager.update_folder`` used to accept any key for which
    ``hasattr(folder, key)`` was true on the live SQLAlchemy instance --
    which holds not just for real columns but also for ORM internals like
    ``_sa_instance_state``, ``metadata``/``registry``, and the bound
    ``to_dict`` method. A request body could therefore corrupt ORM
    identity state or shadow ``to_dict`` on the instance (breaking the
    route's own ``folder.to_dict()`` call on the same request). Restrict
    updates to the model's real, user-editable columns instead.

    Field-name allowlisting alone isn't enough: ``FolderManager.update_folder``
    does a blind ``setattr(folder, key, value)`` loop over whatever survives
    here, straight into the SQLAlchemy session. A wrong-typed value (e.g.
    ``{"sort_order": "abc"}``) either dies as an opaque 500 at
    ``session.commit()`` or, thanks to SQLite's dynamic column typing,
    silently coerces/stores the wrong type instead of erroring at all. So
    type-check each field here too, mirroring
    :func:`normalize_compact_subscription_update`'s style -- an invalid body
    must never reach the session.

    Keys in :data:`FOLDER_READONLY_ECHO_FIELDS` (``id``, ``created_at``,
    ``updated_at``) are accepted but ignored rather than rejected: they are
    exactly what ``folder.to_dict()`` echoes back, so a client doing a
    normal read-modify-write round trip always resends them. The final
    dict comprehension below still only pulls from
    ``FOLDER_UPDATABLE_FIELDS``, so none of them ever reaches ``setattr`` --
    this only changes whether *mentioning* them 400s the whole request.
    """
    error = folder_update_error(data)
    if error is not None:
        raise ValueError(error)

    return {
        field: data[field] for field in FOLDER_UPDATABLE_FIELDS if field in data
    }